code
stringlengths
22
1.05M
apis
listlengths
1
3.31k
extract_api
stringlengths
75
3.25M
#!/usr/bin/env python3 """ SQLite Clinet written in python3 """ # Always prefer setuptools over distutils import re import sys # To use a consistent encoding from codecs import open from os import path from setuptools import find_packages, setup here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='sqlite', # Versions should comply with PEP440. For a discussion on single-sourcing # the version across setup.py and the project code, see # https://packaging.python.org/en/latest/single_source_version.html version='0.2.0', description='SQLite Clinet written in python3', long_description=long_description, # The project's main homepage. url='https://github.com/nl253/SQLiteREPL', # Author details author='<NAME>', author_email='<EMAIL>', # Choose your license license='MIT', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Topic :: Database :: Front-Ends', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], keywords='database sqllite3 sqlite clinet SQLite prompt-toolkit prompt_toolkit', packages=find_packages(), # List run-time dependencies here. These will be installed by pip when # your project is installed. For an analysis of "install_requires" vs pip's # requirements files see: # https://packaging.python.org/en/latest/requirements.html install_requires=['prompt_toolkit', 'tabulate', 'pygments'], entry_points={ 'console_scripts': ['sqlite = sqlite.main:main'] })
[ "os.path.dirname", "setuptools.find_packages", "os.path.join" ]
[((270, 292), 'os.path.dirname', 'path.dirname', (['__file__'], {}), '(__file__)\n', (282, 292), False, 'from os import path\n'), ((353, 382), 'os.path.join', 'path.join', (['here', '"""README.rst"""'], {}), "(here, 'README.rst')\n", (362, 382), False, 'from os import path\n'), ((1398, 1413), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (1411, 1413), False, 'from setuptools import find_packages, setup\n')]
import cv2 import numpy as np # Capture the input frame def get_frame(cap, scaling_factor=0.5): ret, frame = cap.read() # Resize the frame frame = cv2.resize(frame, None, fx=scaling_factor, fy=scaling_factor, interpolation=cv2.INTER_AREA) return frame if __name__=='__main__': # Initialize the video capture object cap = cv2.VideoCapture(1) # Create the background subtractor object bgSubtractor = cv2.createBackgroundSubtractorMOG2() # This factor controls the learning rate of the algorithm. # The learning rate refers to the rate at which your model # will learn about the background. Higher value for # 'history' indicates a slower learning rate. You # can play with this parameter to see how it affects # the output. history = 100 # Iterate until the user presses the ESC key while True: frame = get_frame(cap, 0.5) # Apply the background subtraction model to the input frame mask = bgSubtractor.apply(frame, learningRate=1.0/history) # Convert from grayscale to 3-channel RGB mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR) cv2.imshow('Input frame', frame) cv2.imshow('Moving Objects MOG', mask & frame) # Check if the user pressed the ESC key c = cv2.waitKey(delay=30) if c == 27: break cap.release() cv2.destroyAllWindows()
[ "cv2.createBackgroundSubtractorMOG2", "cv2.imshow", "cv2.destroyAllWindows", "cv2.VideoCapture", "cv2.cvtColor", "cv2.resize", "cv2.waitKey" ]
[((169, 265), 'cv2.resize', 'cv2.resize', (['frame', 'None'], {'fx': 'scaling_factor', 'fy': 'scaling_factor', 'interpolation': 'cv2.INTER_AREA'}), '(frame, None, fx=scaling_factor, fy=scaling_factor, interpolation\n =cv2.INTER_AREA)\n', (179, 265), False, 'import cv2\n'), ((376, 395), 'cv2.VideoCapture', 'cv2.VideoCapture', (['(1)'], {}), '(1)\n', (392, 395), False, 'import cv2\n'), ((465, 501), 'cv2.createBackgroundSubtractorMOG2', 'cv2.createBackgroundSubtractorMOG2', ([], {}), '()\n', (499, 501), False, 'import cv2\n'), ((1447, 1470), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (1468, 1470), False, 'import cv2\n'), ((1159, 1197), 'cv2.cvtColor', 'cv2.cvtColor', (['mask', 'cv2.COLOR_GRAY2BGR'], {}), '(mask, cv2.COLOR_GRAY2BGR)\n', (1171, 1197), False, 'import cv2\n'), ((1208, 1240), 'cv2.imshow', 'cv2.imshow', (['"""Input frame"""', 'frame'], {}), "('Input frame', frame)\n", (1218, 1240), False, 'import cv2\n'), ((1249, 1295), 'cv2.imshow', 'cv2.imshow', (['"""Moving Objects MOG"""', '(mask & frame)'], {}), "('Moving Objects MOG', mask & frame)\n", (1259, 1295), False, 'import cv2\n'), ((1359, 1380), 'cv2.waitKey', 'cv2.waitKey', ([], {'delay': '(30)'}), '(delay=30)\n', (1370, 1380), False, 'import cv2\n')]
# # Copyright 2021 Splunk Inc. # # 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. # import re import urllib.error import urllib.parse import urllib.request import splunktalib.state_store as ss import splunktaucclib.common.log as stulog from . import ta_consts as c class TACheckPointMgr: SEPARATOR = "___" def __init__(self, meta_config, task_config): self._task_config = task_config self._store = ss.get_state_store( meta_config, task_config[c.appname], use_kv_store=self._use_kv_store() ) if isinstance(self._store, ss.CachedFileStateStore): stulog.logger.info("State store type is CachedFileStateStore") def _use_kv_store(self): use_kv_store = self._task_config.get(c.use_kv_store, False) if use_kv_store: stulog.logger.info( "Stanza={} Using KV store for checkpoint".format( self._task_config[c.stanza_name] ) ) return use_kv_store def get_ckpt_key(self): return self.key_formatter() def get_ckpt(self): key = self.get_ckpt_key() return self._store.get_state(key) def update_ckpt(self, ckpt): key = self.get_ckpt_key() self._store.update_state(key, ckpt) def remove_ckpt(self): key = self.get_ckpt_key() self._store.delete_state(key) def key_formatter(self): divide_value = [self._task_config[c.stanza_name]] for key in self._task_config[c.divide_key]: divide_value.append(self._task_config[key]) key_str = TACheckPointMgr.SEPARATOR.join(divide_value) qualified_key_str = "" for i in range(len(key_str)): if re.match(r"[^\w]", key_str[i]): qualified_key_str += urllib.parse.quote(key_str[i]) else: qualified_key_str += key_str[i] return qualified_key_str
[ "re.match", "splunktaucclib.common.log.logger.info" ]
[((1106, 1168), 'splunktaucclib.common.log.logger.info', 'stulog.logger.info', (['"""State store type is CachedFileStateStore"""'], {}), "('State store type is CachedFileStateStore')\n", (1124, 1168), True, 'import splunktaucclib.common.log as stulog\n'), ((2224, 2254), 're.match', 're.match', (['"""[^\\\\w]"""', 'key_str[i]'], {}), "('[^\\\\w]', key_str[i])\n", (2232, 2254), False, 'import re\n')]
# # Copyright (C) 2020 IBM. All Rights Reserved. # # See LICENSE.txt file in the root directory # of this source tree for licensing information. # import selectors import socket import types from typing import Callable from clai.datasource.server_status_datasource import ServerStatusDatasource from clai.server.command_message import Action from clai.server.server_connector import ServerConnector from clai.server.logger import current_logger as logger class SocketServerConnector(ServerConnector): BUFFER_SIZE = 4024 def __init__(self, server_status_datasource: ServerStatusDatasource): self.server_status_datasource = server_status_datasource self.sel = selectors.DefaultSelector() self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def create_socket(self, host: str, port: int): self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.server_socket.bind((host, port)) self.server_socket.listen() logger.info(f"Listening {host} {port}") self.server_socket.setblocking(False) def loop(self, process_message: Callable[[bytes], Action]): self.sel.register(self.server_socket, selectors.EVENT_READ, data=None) try: while self.server_status_datasource.running: events = self.sel.select(timeout=None) for key, mask in events: if key.data is None: self.__accept_wrapper(key.fileobj) else: self.__service_connection(key, mask, process_message) self.sel.unregister(self.server_socket) self.server_socket.close() except KeyboardInterrupt: logger.info("caught keyboard interrupt, exiting") finally: logger.info("server closed") self.sel.close() def __accept_wrapper(self, server_socket): connection, address = server_socket.accept() connection.setblocking(False) data = types.SimpleNamespace(addr=address, inb=b"", outb=b"") events = selectors.EVENT_READ | selectors.EVENT_WRITE self.sel.register(connection, events, data=data) def __service_connection(self, key, mask, process_message): logger.info(f"service connection") fileobj = key.fileobj data = key.data if mask & selectors.EVENT_READ: data = self.__read(data, fileobj, process_message) if mask & selectors.EVENT_WRITE: self.__write(data, fileobj) @staticmethod def __write(data, server_socket): if data.outb: logger.info(f"sending from client ${data.outb}") server_socket.send(data.outb) data.outb = b'' def __read(self, data, server_socket, process_message): recv_data = b'' chewing = True logger.info(f"receiving from client") while chewing: part = server_socket.recv(self.BUFFER_SIZE) recv_data += part if len(part) < self.BUFFER_SIZE: chewing = False if recv_data: logger.info(f"receiving from client ${recv_data}") action = process_message(recv_data) data.outb = str(action.json()).encode('utf8') else: self.sel.unregister(server_socket) server_socket.close() return data
[ "socket.socket", "clai.server.logger.current_logger.info", "selectors.DefaultSelector", "types.SimpleNamespace" ]
[((687, 714), 'selectors.DefaultSelector', 'selectors.DefaultSelector', ([], {}), '()\n', (712, 714), False, 'import selectors\n'), ((744, 793), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (757, 793), False, 'import socket\n'), ((1017, 1056), 'clai.server.logger.current_logger.info', 'logger.info', (['f"""Listening {host} {port}"""'], {}), "(f'Listening {host} {port}')\n", (1028, 1056), True, 'from clai.server.logger import current_logger as logger\n'), ((2045, 2099), 'types.SimpleNamespace', 'types.SimpleNamespace', ([], {'addr': 'address', 'inb': "b''", 'outb': "b''"}), "(addr=address, inb=b'', outb=b'')\n", (2066, 2099), False, 'import types\n'), ((2292, 2326), 'clai.server.logger.current_logger.info', 'logger.info', (['f"""service connection"""'], {}), "(f'service connection')\n", (2303, 2326), True, 'from clai.server.logger import current_logger as logger\n'), ((2891, 2928), 'clai.server.logger.current_logger.info', 'logger.info', (['f"""receiving from client"""'], {}), "(f'receiving from client')\n", (2902, 2928), True, 'from clai.server.logger import current_logger as logger\n'), ((1833, 1861), 'clai.server.logger.current_logger.info', 'logger.info', (['"""server closed"""'], {}), "('server closed')\n", (1844, 1861), True, 'from clai.server.logger import current_logger as logger\n'), ((2656, 2704), 'clai.server.logger.current_logger.info', 'logger.info', (['f"""sending from client ${data.outb}"""'], {}), "(f'sending from client ${data.outb}')\n", (2667, 2704), True, 'from clai.server.logger import current_logger as logger\n'), ((3150, 3200), 'clai.server.logger.current_logger.info', 'logger.info', (['f"""receiving from client ${recv_data}"""'], {}), "(f'receiving from client ${recv_data}')\n", (3161, 3200), True, 'from clai.server.logger import current_logger as logger\n'), ((1754, 1803), 'clai.server.logger.current_logger.info', 'logger.info', (['"""caught keyboard interrupt, exiting"""'], {}), "('caught keyboard interrupt, exiting')\n", (1765, 1803), True, 'from clai.server.logger import current_logger as logger\n')]
# -*- coding: utf-8 -*- import numpy from simmate.toolkit import Structure from pymatgen.analysis.diffusion.neb.pathfinder import ( DistinctPathFinder, MigrationHop as PymatgenMigrationHop, IDPPSolver, ) from typing import List class MigrationImages(list): """ This class is just a list of structures for a diffusion pathway. It has utility methods to help create these structures but otherwise behaves exactly like a python list. Note, this class is primarily used to generate inputs for calculations. If you'd like more advanced features, you should represent your diffusion pathway as a MigrationHop instead.As a rule of thumb: Only use this class if you are manually creating your pathway from endpoint supercells or from a set of supercell images. All MigrationHop's can be converted to MigrationImages (using the `from_migration_hop` method); but not all MigrationImages can be converted to MigrationHops. """ def __init__(self, structures: List[Structure]): # This init function does nothing except apply typing -- specifically, # it says that it expects a list of structures. super().__init__(structures) def get_sum_structure(self, tolerance: float = 1e-3): """ Takes all structures and combines them into one. Atoms that are within the given tolerance are joined into a single site. This is primarily used to view a diffusing pathway within a single structure -- as well as how the host lattice changes during diffusion. If you are able to convert your pathway to a MigrationHop, the MigrationHop.write_path() method is much faster and cleaner than this method, so it should be preffered. Also, because there are many atoms that are overlapping here, the output structure may cause programs like VESTA to crash. #### Parameters - `tolerance`: the angle and distance tolerance to consider fractional coordinates as matching. Matching sites will be merged as 1 site in the final sum structure. """ # OPTIMIZE: this is very inefficient. It's much faster to visualize # structures with MigrationHop class because you know which atom is # moving. Here, we need to treat all atoms as moving. We can also # speed this up by only looking at diffusing species too. final_coords = [] final_species = [] for structure in self: # recall self is a list of structures for site in structure: is_new = True for coords in final_coords: if all( numpy.isclose( site.frac_coords, coords, rtol=tolerance, atol=tolerance, ) ): is_new = False break if is_new: final_coords.append(site.frac_coords) final_species.append(site.specie) structure = Structure( lattice=structure.lattice, species=final_species, coords=final_coords, ) return structure @staticmethod def get_nimages( pathway_length: float, min_image_step: float = 0.7, require_midpoint: bool = True, ): """ Gives the desirable number of images (not including start/end structures). This method helps generate a MigrationImages object, and typically is not called directly. The other classmethods of MigrationImages call this for you. #### Parameters - `pathway_length`: The length of the pathway. - `min_image_step`: The minimum step distance for the diffusing atom between images. The default is 0.7 Angstroms. For example, a path 2.8A long would require at least 4 images for this default. - `require_midpoint`: Whether there should be an image at the midpoint. In other words, whether the number of images should be odd. This is often important if you expect the transition state to be at the midpoint and you are not running CI-NEB. The default is True. Returns ------- - `nimages`: The number of images to use for this pathway. """ # At a minimum, we want to have images be 0.7 angstroms apart, and # with one additional image. nimages = pathway_length // min_image_step + 1 # We also want an odd number of images. This ensures we have an image # at exactly the midpoint, which is often necessary if we aren't # running CI-NEB. if require_midpoint and nimages % 2 == 0: nimages += 1 # This is a float but it makes more sense to have an integer return int(nimages) @classmethod def from_migration_hop( cls, migration_hop: PymatgenMigrationHop, vacancy_mode: bool = True, min_nsites: int = 80, max_nsites: int = 240, min_length: int = 10, **kwargs, ): """ Creates a MigrationImages object from a MigrationHop object #### Parameters - `migration_hop`: The MigrationHop object that should be converted. - `vacancy_mode`: Whether to use single-vacancy diffusion (True) or interstitial diffusion (False). The default is True. - `min_nsites`: The minimum number of sites to have in the supercell structure. The default is 80. - `max_nsites`: The maximum number of sites to have in the supercell structure. The default is 240. - `min_length`: The minimum length for each vector in the supercell structure. The default is 10 Angstroms. - `**kwargs`: Any arguments that are normally accepted by IDPPSolver """ # The third thing returned is the bulk_supercell which we don't need. start_supercell, end_supercell, _ = migration_hop.get_sc_structures( vac_mode=vacancy_mode, min_atoms=min_nsites, max_atoms=max_nsites, min_length=min_length, ) # calculate the number of images required nimages = cls.get_nimages(migration_hop.length) return cls.from_endpoints( start_supercell, end_supercell, nimages=nimages, **kwargs, ) @classmethod def from_endpoints( cls, structure_start: Structure, structure_end: Structure, nimages: int, **kwargs, ): """ Creates a MigrationImages object from start and end supercell structures. You do not need to specify the diffusing atom(s) as all sites are linearly interpolated and then relaxed by IDPP. #### Parameters - `structure_start`: The starting supercell of the diffusion pathway. - `structure_end`: The ending supercell of the diffusion pathway. - `nimages`: The number of desired images for the pathway. Note, if you know the pathway length of your path, you can use the `get_nimages` static method to get a logical number of images. - `**kwargs`: Any arguments that are normally accepted by IDPPSolver """ # Run IDPP relaxation on the images before returning them idpp_solver = IDPPSolver.from_endpoints( [structure_start, structure_end], nimages=nimages, **kwargs, ) images = idpp_solver.run() return cls(images) @classmethod def from_startend_sites( cls, structure: Structure, site_start: int, site_end: int, **kwargs, ): """ Creates a MigrationImages object from a bulk structure and start/end periodic sites of the diffusing atom. For example, this would allow a diffusion pathway that goes from a site at (0,0,0) to (1,1,1). Thus, symmetry and periodic boundry conditions are considered. Note, this method just creates a MigrationHop and then uses the `from_migration_hop` method to make a MigrationImages object. #### Parameters - `structure`: The bulk crystal structure (NOT the supercell). - `site_start`: The starting periodic site for this pathway. - `site_end`: The end periodic site for this pathway. - `**kwargs`: Any arguments that are normally accepted by `from_migration_hop`. """ # This information is all we need for a MigrationHop object pathway = PymatgenMigrationHop(site_start, site_end, structure) return cls.from_migration_hop(pathway, **kwargs) @classmethod def from_structure( cls, structure: Structure, migrating_specie: str, pathfinder_kwargs: dict = {}, **kwargs, ): """ Given a bulk crystal structure, this will find all symmetrically unique pathways and return them as list of MigrationImages objects. #### Parameters - `structure`: The bulk crystal structure (NOT the supercell). - `migrating_specie`: The identity of the diffusing ion (e.g. "Li" or "Li1+"). Note, only provide oxidation state if you are using an oxidation-state decorated structure. - `pathfinder_kwargs`: Any arguments that are normally accepted by DistinctPathFinder, but given as a dictionary. The default is {}. - `**kwargs`: Any arguments that are normally accepted by `from_migration_hop`. """ # convert to the LLL reduced primitive cell to make it as cubic as possible structure_lll = structure.get_sanitized_structure() # Use pymatgen to find all the symmetrically unique pathways. # NOTE: This only finds pathways up until the structure is percolating. # If you are interested in longer pathways, then this script needs to # be adjusted by passing additional kwargs pathfinder = DistinctPathFinder( structure_lll, migrating_specie=migrating_specie, **pathfinder_kwargs, ) pathways = pathfinder.get_paths() # Now go through each path and convert to a MigrationPath. We return # these as a list of paths. migration_paths = [] for pathway in pathways: migration_path = cls.from_migration_hop( migration_hop=pathway, **kwargs, ) migration_paths.append(migration_path) return migration_paths @classmethod def from_dynamic(cls, migration_images): """ This is an experimental feature. The code here is a repurposing of Structre.from_dynamic so consider making a general class for from_dynamic methods. """ is_from_past_calc = False # assume any list is in the MigrationHop format if there are more than # two structures (i.e. there is at least one midpoint image) if isinstance(migration_images, list) and len(migration_images) > 2: migration_images_cleaned = migration_images else: raise Exception("Unknown format provided for migration_images input.") migration_images_cleaned.is_from_past_calc = is_from_past_calc return migration_images_cleaned def as_dict(self): return [s.as_dict() for s in self]
[ "simmate.toolkit.Structure", "numpy.isclose", "pymatgen.analysis.diffusion.neb.pathfinder.MigrationHop", "pymatgen.analysis.diffusion.neb.pathfinder.IDPPSolver.from_endpoints", "pymatgen.analysis.diffusion.neb.pathfinder.DistinctPathFinder" ]
[((3195, 3280), 'simmate.toolkit.Structure', 'Structure', ([], {'lattice': 'structure.lattice', 'species': 'final_species', 'coords': 'final_coords'}), '(lattice=structure.lattice, species=final_species, coords=final_coords\n )\n', (3204, 3280), False, 'from simmate.toolkit import Structure\n'), ((7774, 7864), 'pymatgen.analysis.diffusion.neb.pathfinder.IDPPSolver.from_endpoints', 'IDPPSolver.from_endpoints', (['[structure_start, structure_end]'], {'nimages': 'nimages'}), '([structure_start, structure_end], nimages=nimages,\n **kwargs)\n', (7799, 7864), False, 'from pymatgen.analysis.diffusion.neb.pathfinder import DistinctPathFinder, MigrationHop as PymatgenMigrationHop, IDPPSolver\n'), ((9060, 9113), 'pymatgen.analysis.diffusion.neb.pathfinder.MigrationHop', 'PymatgenMigrationHop', (['site_start', 'site_end', 'structure'], {}), '(site_start, site_end, structure)\n', (9080, 9113), True, 'from pymatgen.analysis.diffusion.neb.pathfinder import DistinctPathFinder, MigrationHop as PymatgenMigrationHop, IDPPSolver\n'), ((10560, 10654), 'pymatgen.analysis.diffusion.neb.pathfinder.DistinctPathFinder', 'DistinctPathFinder', (['structure_lll'], {'migrating_specie': 'migrating_specie'}), '(structure_lll, migrating_specie=migrating_specie, **\n pathfinder_kwargs)\n', (10578, 10654), False, 'from pymatgen.analysis.diffusion.neb.pathfinder import DistinctPathFinder, MigrationHop as PymatgenMigrationHop, IDPPSolver\n'), ((2732, 2803), 'numpy.isclose', 'numpy.isclose', (['site.frac_coords', 'coords'], {'rtol': 'tolerance', 'atol': 'tolerance'}), '(site.frac_coords, coords, rtol=tolerance, atol=tolerance)\n', (2745, 2803), False, 'import numpy\n')]
# Copyright 2020 LMNT, Inc. All Rights Reserved. # # 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. # ============================================================================== import numpy as np import os import torch import torch.nn as nn from torch.nn.parallel import DistributedDataParallel from torch.utils.tensorboard import SummaryWriter from tqdm import tqdm from wavegrad.dataset import from_path as dataset_from_path from wavegrad.model import WaveGrad def _nested_map(struct, map_fn): if isinstance(struct, tuple): return tuple(_nested_map(x, map_fn) for x in struct) if isinstance(struct, list): return [_nested_map(x, map_fn) for x in struct] if isinstance(struct, dict): return { k: _nested_map(v, map_fn) for k, v in struct.items() } return map_fn(struct) class WaveGradLearner: def __init__(self, model_dir, model, dataset, optimizer, params, *args, **kwargs): os.makedirs(model_dir, exist_ok=True) self.model_dir = model_dir self.model = model self.dataset = dataset self.optimizer = optimizer self.params = params self.autocast = torch.cuda.amp.autocast(enabled=kwargs.get('fp16', False)) self.scaler = torch.cuda.amp.GradScaler(enabled=kwargs.get('fp16', False)) self.step = 0 self.is_master = True beta = np.array(self.params.noise_schedule) noise_level = np.cumprod(1 - beta)**0.5 noise_level = np.concatenate([[1.0], noise_level], axis=0) self.noise_level = torch.tensor(noise_level.astype(np.float32)) self.loss_fn = nn.L1Loss() self.summary_writer = None def state_dict(self): if hasattr(self.model, 'module') and isinstance(self.model.module, nn.Module): model_state = self.model.module.state_dict() else: model_state = self.model.state_dict() return { 'step': self.step, 'model': { k: v.cpu() if isinstance(v, torch.Tensor) else v for k, v in model_state.items() }, 'optimizer': { k: v.cpu() if isinstance(v, torch.Tensor) else v for k, v in self.optimizer.state_dict().items() }, 'params': dict(self.params), 'scaler': self.scaler.state_dict(), } def load_state_dict(self, state_dict): if hasattr(self.model, 'module') and isinstance(self.model.module, nn.Module): self.model.module.load_state_dict(state_dict['model']) else: self.model.load_state_dict(state_dict['model']) self.optimizer.load_state_dict(state_dict['optimizer']) self.scaler.load_state_dict(state_dict['scaler']) self.step = state_dict['step'] def save_to_checkpoint(self, filename='weights'): save_basename = f'{filename}-{self.step}.pt' save_name = f'{self.model_dir}/{save_basename}' link_name = f'{self.model_dir}/{filename}.pt' torch.save(self.state_dict(), save_name) if os.name == 'nt': torch.save(self.state_dict(), link_name) else: if os.path.islink(link_name): os.unlink(link_name) os.symlink(save_basename, link_name) def restore_from_checkpoint(self, filename='weights'): try: checkpoint = torch.load(f'{self.model_dir}/{filename}.pt') self.load_state_dict(checkpoint) return True except FileNotFoundError: return False def train(self, max_steps=None): device = next(self.model.parameters()).device while True: for features in tqdm(self.dataset, desc=f'Epoch {self.step // len(self.dataset)}') if self.is_master else self.dataset: if max_steps is not None and self.step >= max_steps: return features = _nested_map(features, lambda x: x.to(device) if isinstance(x, torch.Tensor) else x) loss = self.train_step(features) if torch.isnan(loss).any(): raise RuntimeError(f'Detected NaN loss at step {self.step}.') if self.is_master: if self.step % 100 == 0: self._write_summary(self.step, features, loss) if self.step % len(self.dataset) == 0: self.save_to_checkpoint() self.step += 1 def train_step(self, features): for param in self.model.parameters(): param.grad = None audio = features['audio'] spectrogram = features['spectrogram'] N, T = audio.shape S = 1000 device = audio.device self.noise_level = self.noise_level.to(device) with self.autocast: s = torch.randint(1, S + 1, [N], device=audio.device) l_a, l_b = self.noise_level[s-1], self.noise_level[s] noise_scale = l_a + torch.rand(N, device=audio.device) * (l_b - l_a) noise_scale = noise_scale.unsqueeze(1) noise = torch.randn_like(audio) noisy_audio = noise_scale * audio + (1.0 - noise_scale**2)**0.5 * noise predicted = self.model(noisy_audio, spectrogram, noise_scale.squeeze(1)) loss = self.loss_fn(noise, predicted.squeeze(1)) self.scaler.scale(loss).backward() self.scaler.unscale_(self.optimizer) self.grad_norm = nn.utils.clip_grad_norm_(self.model.parameters(), self.params.max_grad_norm) self.scaler.step(self.optimizer) self.scaler.update() return loss def _write_summary(self, step, features, loss): writer = self.summary_writer or SummaryWriter(self.model_dir, purge_step=step) writer.add_audio('audio/reference', features['audio'][0], step, sample_rate=self.params.sample_rate) writer.add_scalar('train/loss', loss, step) writer.add_scalar('train/grad_norm', self.grad_norm, step) writer.flush() self.summary_writer = writer def _train_impl(replica_id, model, dataset, args, params): torch.backends.cudnn.benchmark = True opt = torch.optim.Adam(model.parameters(), lr=params.learning_rate) learner = WaveGradLearner(args.model_dir, model, dataset, opt, params, fp16=args.fp16) learner.is_master = (replica_id == 0) learner.restore_from_checkpoint() learner.train(max_steps=args.max_steps) def train(args, params): dataset = dataset_from_path(args.data_dirs, params) model = WaveGrad(params).cuda() _train_impl(0, model, dataset, args, params) def train_distributed(replica_id, replica_count, port, args, params): os.environ['MASTER_ADDR'] = 'localhost' os.environ['MASTER_PORT'] = str(port) torch.distributed.init_process_group('nccl', rank=replica_id, world_size=replica_count) device = torch.device('cuda', replica_id) torch.cuda.set_device(device) model = WaveGrad(params).to(device) model = DistributedDataParallel(model, device_ids=[replica_id]) _train_impl(replica_id, model, dataset_from_path(args.data_dirs, params, is_distributed=True), args, params)
[ "wavegrad.model.WaveGrad", "torch.nn.L1Loss", "numpy.array", "wavegrad.dataset.from_path", "os.path.islink", "torch.isnan", "torch.utils.tensorboard.SummaryWriter", "torch.randint", "os.unlink", "numpy.concatenate", "torch.nn.parallel.DistributedDataParallel", "torch.randn_like", "torch.cuda...
[((6383, 6424), 'wavegrad.dataset.from_path', 'dataset_from_path', (['args.data_dirs', 'params'], {}), '(args.data_dirs, params)\n', (6400, 6424), True, 'from wavegrad.dataset import from_path as dataset_from_path\n'), ((6662, 6754), 'torch.distributed.init_process_group', 'torch.distributed.init_process_group', (['"""nccl"""'], {'rank': 'replica_id', 'world_size': 'replica_count'}), "('nccl', rank=replica_id, world_size=\n replica_count)\n", (6698, 6754), False, 'import torch\n'), ((6762, 6794), 'torch.device', 'torch.device', (['"""cuda"""', 'replica_id'], {}), "('cuda', replica_id)\n", (6774, 6794), False, 'import torch\n'), ((6797, 6826), 'torch.cuda.set_device', 'torch.cuda.set_device', (['device'], {}), '(device)\n', (6818, 6826), False, 'import torch\n'), ((6875, 6930), 'torch.nn.parallel.DistributedDataParallel', 'DistributedDataParallel', (['model'], {'device_ids': '[replica_id]'}), '(model, device_ids=[replica_id])\n', (6898, 6930), False, 'from torch.nn.parallel import DistributedDataParallel\n'), ((1409, 1446), 'os.makedirs', 'os.makedirs', (['model_dir'], {'exist_ok': '(True)'}), '(model_dir, exist_ok=True)\n', (1420, 1446), False, 'import os\n'), ((1798, 1834), 'numpy.array', 'np.array', (['self.params.noise_schedule'], {}), '(self.params.noise_schedule)\n', (1806, 1834), True, 'import numpy as np\n'), ((1897, 1941), 'numpy.concatenate', 'np.concatenate', (['[[1.0], noise_level]'], {'axis': '(0)'}), '([[1.0], noise_level], axis=0)\n', (1911, 1941), True, 'import numpy as np\n'), ((2029, 2040), 'torch.nn.L1Loss', 'nn.L1Loss', ([], {}), '()\n', (2038, 2040), True, 'import torch.nn as nn\n'), ((6964, 7026), 'wavegrad.dataset.from_path', 'dataset_from_path', (['args.data_dirs', 'params'], {'is_distributed': '(True)'}), '(args.data_dirs, params, is_distributed=True)\n', (6981, 7026), True, 'from wavegrad.dataset import from_path as dataset_from_path\n'), ((1853, 1873), 'numpy.cumprod', 'np.cumprod', (['(1 - beta)'], {}), '(1 - beta)\n', (1863, 1873), True, 'import numpy as np\n'), ((3376, 3401), 'os.path.islink', 'os.path.islink', (['link_name'], {}), '(link_name)\n', (3390, 3401), False, 'import os\n'), ((3438, 3474), 'os.symlink', 'os.symlink', (['save_basename', 'link_name'], {}), '(save_basename, link_name)\n', (3448, 3474), False, 'import os\n'), ((3561, 3606), 'torch.load', 'torch.load', (['f"""{self.model_dir}/{filename}.pt"""'], {}), "(f'{self.model_dir}/{filename}.pt')\n", (3571, 3606), False, 'import torch\n'), ((4825, 4874), 'torch.randint', 'torch.randint', (['(1)', '(S + 1)', '[N]'], {'device': 'audio.device'}), '(1, S + 1, [N], device=audio.device)\n', (4838, 4874), False, 'import torch\n'), ((5069, 5092), 'torch.randn_like', 'torch.randn_like', (['audio'], {}), '(audio)\n', (5085, 5092), False, 'import torch\n'), ((5650, 5696), 'torch.utils.tensorboard.SummaryWriter', 'SummaryWriter', (['self.model_dir'], {'purge_step': 'step'}), '(self.model_dir, purge_step=step)\n', (5663, 5696), False, 'from torch.utils.tensorboard import SummaryWriter\n'), ((6435, 6451), 'wavegrad.model.WaveGrad', 'WaveGrad', (['params'], {}), '(params)\n', (6443, 6451), False, 'from wavegrad.model import WaveGrad\n'), ((6837, 6853), 'wavegrad.model.WaveGrad', 'WaveGrad', (['params'], {}), '(params)\n', (6845, 6853), False, 'from wavegrad.model import WaveGrad\n'), ((3411, 3431), 'os.unlink', 'os.unlink', (['link_name'], {}), '(link_name)\n', (3420, 3431), False, 'import os\n'), ((4961, 4995), 'torch.rand', 'torch.rand', (['N'], {'device': 'audio.device'}), '(N, device=audio.device)\n', (4971, 4995), False, 'import torch\n'), ((4174, 4191), 'torch.isnan', 'torch.isnan', (['loss'], {}), '(loss)\n', (4185, 4191), False, 'import torch\n')]
# VISUALISER OF CONTAMINATION # v0.0.1, 21.8.2020 import tkinter as tk from tkinter import messagebox as msgb from tkinter import filedialog as fdialog from itertools import product import pickle from ppopt.auxil import * # ----------------------WINDOW (AS A CLASS DEFINITION)--------------------- class Vis(tk.Frame): def __init__(self): super().__init__() self.initUI() def initUI(self): self.choose_and_load() # display tutorial messagebox title='Welcome to contamination visualiser tool' message='Welcome!\nHere is how to use the contamination visulaiser tool:\n\n' message+='Left-click a well - for all the tips that served it, the parts that were present in the previously-visited wells will be displayed in bold.' message+='\n\nMiddle-click - undo left-click' message+='\n\nRight-click - display well contents in a message box' msgb.showinfo(title=title, message=message) self.master.title("Construct contamination") self.pack(fill=tk.BOTH, expand=1) self.canvas = tk.Canvas(self) self.mode = 'initial' self.coord_w = {(i, j): -1 for i, j in product(range(1, 9), range(1, 13))} self.rows = 'ABCDEFGH' self.rowcoords = {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5, 'F': 6, 'G': 7, 'H': 8} self.defx_tl = 30 self.defy_tl = 30 self.xside = 115 self.yside = 10 * len(self.w[0]) + 20 self.interval = 10 self.basicpaint() self.mode = 'general' def basicpaint(self): self.canvas.delete("all") if (self.mode != 'clicked'): self.bold = [] empty1 = [] for i in range(0, len(self.w[0])): empty1.append(False) for i in range(0, len(self.w)): self.bold.append(empty1.copy()) for i in range(1, 9): for j in range(1, 13): y_tl = self.defy_tl + (i - 1) * (self.yside + self.interval) x_tl = self.defx_tl + (j - 1) * (self.xside + self.interval) self.canvas.create_rectangle(x_tl, y_tl, x_tl + self.xside, y_tl + self.yside, outline="#000") # label self.rows and columns for i in range(1, 9): y_tl = self.defy_tl + self.yside / 2 + (i - 1) * (self.yside + self.interval) self.canvas.create_text(5, y_tl, anchor=tk.W, font="Verdana", text=self.rows[i - 1]) for j in range(1, 13): x_tl = self.defx_tl + self.xside / 3 + (j - 1) * (self.xside + self.interval) self.canvas.create_text(x_tl, 10, anchor=tk.W, font="Verdana", text=str(j)) self.canvas.pack(fill=tk.BOTH, expand=1) # display constructs for i in range(0, len(self.w)): con = self.dic['constructs'][i] if (self.assembly == 'Start-Stop'): precoord = con['con_liqloc'][0].display_name x_coord_str = '' for k in range(1, len(precoord)): if (precoord[k] != ' '): x_coord_str += precoord[k] else: break x_coord = int(x_coord_str) y_coord = self.rowcoords[precoord[0]] elif (self.assembly == 'BASIC'): precoord = con['con_liqloc'] x_coord = int(precoord[1:]) y_coord = self.rowcoords[precoord[0]] y_tl = self.defy_tl + (y_coord - 1) * (self.yside + self.interval) x_tl = self.defx_tl + (x_coord - 1) * (self.xside + self.interval) self.canvas.create_text(x_tl + 2, y_tl + 10, anchor=tk.W, font=("Verdana", 6), text=con['con_name']) for j in range(0, len(self.w[i])): part_name = self.dic['parts'][self.w[i][j]]['part_name'] if (self.bold[i][j] == True): self.canvas.create_text(x_tl + 20, y_tl + 20 + j * 10, anchor=tk.W, font=('Verdana', 6, 'bold'), text=part_name, ) else: self.canvas.create_text(x_tl + 20, y_tl + 20 + j * 10, anchor=tk.W, font=('Verdana', 6), text=part_name, ) if (self.mode == 'initial'): self.coord_w[(x_coord, y_coord)] = i elif (self.mode == 'clicked'): if (self.select == i): self.canvas.create_rectangle(x_tl, y_tl, x_tl + self.xside, y_tl + self.yside, outline="#f00") # if(self.mode == 'initial') # self.tutorial() def click(self, event): n = self.clickedwell(event.x, event.y) if (n != -1): self.mode = 'clicked' self.bold_cont(n) self.select = n self.basicpaint() def bold_cont(self, n): self.bold = [] empty1 = [] for i in range(0, len(self.w[0])): empty1.append(False) for i in range(0, len(self.w)): self.bold.append(empty1.copy()) added = np.zeros((len(self.w), len(self.w[0]))) # tells which parts were added to which well # for the first operation in fin added[self.fin[0].well][self.fin[0].part[0]] = 1 for i in range(1, len(self.fin)): one_cost = cost_func_with_w(self.fin[0:i], self.fin[i], self.w, added, self.caps) added[self.fin[i].well][self.fin[i].part[0]] = 1 if (self.fin[i].well == n and self.fin[i].changed != True): backroll = 1 while (True): previ = i - backroll for j in range(0, len(self.w[self.fin[previ].well])): if (added[self.fin[previ].well][j] == 1): self.bold[self.fin[previ].well][j] = True if (self.fin[previ].changed == 1): break else: backroll += 1 def clickedwell(self, x, y): x -= 25 y -= 25 x_coord = int(np.ceil(x / (self.xside + self.interval))) y_coord = int(np.ceil(y / (self.yside + self.interval))) return self.coord_w[(x_coord, y_coord)] def unclick(self, event): self.mode = 'general' self.basicpaint() def examine(self, event): n = self.clickedwell(event.x, event.y) title = 'Construct ' + self.dic['constructs'][n]['con_name'] # for Start-Stop Assembly, we exactly know the part types if (self.assembly == 'Start-Stop'): part_type = ['Promoter: ', 'RBS: ', 'CDS: ', 'Terminator: ', 'Backbone: '] # otherwise, create generic insert names else: part_type = ['DNA Part 1: '] for i in range(1, len(self.w[n])): part_type += ['DNA Part ' + str(i + 1) + ': '] message = '' if (self.mode != 'clicked'): for i in range(0, len(self.w[n])): message += part_type[i] + self.dic['parts'][self.w[n][i]]['part_name'] message += ' \n' else: if (n != self.select): present = 'Parts present before tip proceeded to selected well:\n' notpresent = 'Parts not present before tip proceeded to selected well:\n' for i in range(0, len(self.w[n])): if (self.bold[n][i] == True): present += part_type[i] + self.dic['parts'][self.w[n][i]]['part_name'] present += '\n' else: notpresent += part_type[i] + self.dic['parts'][self.w[n][i]]['part_name'] notpresent += '\n' message = present + '\n' + notpresent else: message = 'This is the well whose predecessors are displayed' msgb.showinfo(title=title, message=message) def tutorial(self): title = 'Welcome to contamination viewer' message = 'Left-click a well with construct to check which wells were visited befroe it\n' message += 'and which parts were present in these wells then\n\n' message += 'Middle-click anywhere to return to general view\n\n' message += 'Right-click a well to inspect it in detail' msgb.showinfo(title=title, message=message) def choose_and_load(self): # select the recording output = fdialog.askopenfile( title='Select the recording', filetypes=(("Pickle files", "*.p"), ("all files", "*.*"))) # load the recording file rec = pickle.load(open(output.name, 'rb')) self.assembly = rec['assembly'] self.w = rec['w'] self.fin = rec['fin'] self.dic = rec['dic'] self.caps = rec['caps'] # BASIC assembly does not have inherent names of parts or constructs stored, # as parts are PREPARED IN SITU on a magnetic bead well plate. # Thus we refer to these parts by their location on magbead plate only. if (rec['assembly'] == 'BASIC'): for part in self.dic['parts'].values(): part['part_name'] = 'Magbead well ' + part['part_liqloc'] for construct in self.dic['constructs'].values(): construct['con_name'] = 'Well ' + construct['con_liqloc'] # ---------------------RECORDER OF INFORMATION--------------------- def rec(assem, w, fin, dic,caps): recording={'assembly': assem, 'w': w, 'fin': fin, 'dic': dic, 'caps': caps} if (assem=='Start-Stop'): name = 'ppopt_recording_StartStop.p' elif(assem=='BASIC'): name = 'ppopt_recording_BASIC_'+ str(len(w[0])) + 'parts.p' pickle.dump(recording, open(name, 'wb')) return # ---------------------- CALL THE VISUALISER -------------------- def main(): root = tk.Tk() vis = Vis() root.geometry("1600x900") root.bind("<Button-1>", vis.click) root.bind("<Button-2>", vis.unclick) root.bind("<Button-3>", vis.examine) root.mainloop() if __name__ == "__main__": main()
[ "tkinter.Canvas", "tkinter.Tk", "tkinter.messagebox.showinfo", "tkinter.filedialog.askopenfile" ]
[((10111, 10118), 'tkinter.Tk', 'tk.Tk', ([], {}), '()\n', (10116, 10118), True, 'import tkinter as tk\n'), ((929, 972), 'tkinter.messagebox.showinfo', 'msgb.showinfo', ([], {'title': 'title', 'message': 'message'}), '(title=title, message=message)\n', (942, 972), True, 'from tkinter import messagebox as msgb\n'), ((1092, 1107), 'tkinter.Canvas', 'tk.Canvas', (['self'], {}), '(self)\n', (1101, 1107), True, 'import tkinter as tk\n'), ((8101, 8144), 'tkinter.messagebox.showinfo', 'msgb.showinfo', ([], {'title': 'title', 'message': 'message'}), '(title=title, message=message)\n', (8114, 8144), True, 'from tkinter import messagebox as msgb\n'), ((8538, 8581), 'tkinter.messagebox.showinfo', 'msgb.showinfo', ([], {'title': 'title', 'message': 'message'}), '(title=title, message=message)\n', (8551, 8581), True, 'from tkinter import messagebox as msgb\n'), ((8662, 8775), 'tkinter.filedialog.askopenfile', 'fdialog.askopenfile', ([], {'title': '"""Select the recording"""', 'filetypes': "(('Pickle files', '*.p'), ('all files', '*.*'))"}), "(title='Select the recording', filetypes=((\n 'Pickle files', '*.p'), ('all files', '*.*')))\n", (8681, 8775), True, 'from tkinter import filedialog as fdialog\n')]
import frappe def execute(): frappe.reload_doc("education", "doctype", "student_attendance") frappe.db.sql(''' update `tabStudent Attendance` set docstatus=0 where docstatus=1''')
[ "frappe.db.sql", "frappe.reload_doc" ]
[((31, 94), 'frappe.reload_doc', 'frappe.reload_doc', (['"""education"""', '"""doctype"""', '"""student_attendance"""'], {}), "('education', 'doctype', 'student_attendance')\n", (48, 94), False, 'import frappe\n'), ((96, 202), 'frappe.db.sql', 'frappe.db.sql', (['"""\n\t\tupdate `tabStudent Attendance` set\n\t\t\tdocstatus=0\n\t\twhere\n\t\t\tdocstatus=1"""'], {}), '(\n """\n\t\tupdate `tabStudent Attendance` set\n\t\t\tdocstatus=0\n\t\twhere\n\t\t\tdocstatus=1"""\n )\n', (109, 202), False, 'import frappe\n')]
"""TDNN modules definition for custom encoder.""" from typing import Tuple from typing import Union import torch class TDNN(torch.nn.Module): """TDNN module with symmetric context. Args: idim: Input dimension. odim: Output dimension. ctx_size: Size of the context window. stride: Stride of the sliding blocks. dilation: Control the stride of elements within the neighborhood. batch_norm: Whether to apply batch normalization. relu: Whether to use a final non-linearity layer (ReLU). """ def __init__( self, idim: int, odim: int, ctx_size: int = 5, dilation: int = 1, stride: int = 1, batch_norm: bool = False, relu: bool = True, dropout_rate: float = 0.0, ): """Construct a TDNN object.""" super().__init__() self.idim = idim self.odim = odim self.ctx_size = ctx_size self.stride = stride self.dilation = dilation self.batch_norm = batch_norm self.relu = relu self.tdnn = torch.nn.Conv1d( idim, odim, ctx_size, stride=stride, dilation=dilation ) if self.relu: self.relu_func = torch.nn.ReLU() if self.batch_norm: self.bn = torch.nn.BatchNorm1d(odim) self.dropout = torch.nn.Dropout(p=dropout_rate) def forward( self, sequence: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]], mask: torch.Tensor, ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]], torch.Tensor]: """Forward TDNN for custom encoder. Args: sequence: TDNN input sequences. (B, T, D_in) or ((B, T, D_in), (B, T, D_att)) or ((B, T, D_in), (B, 2 * (T - 1), D_att)) mask: Mask of TDNN input sequences. (B, 1, T) Returns: sequenceput: TDNN output sequences. (B, sub(T), D_out) or ((B, sub(T), D_out), (B, sub(T), att_dim)) or ((B, T, D_out), (B, 2 * (sub(T) - 1), D_att) mask: Mask of TDNN output sequences. (B, 1, sub(T)) """ if isinstance(sequence, tuple): sequence, pos_emb = sequence[0], sequence[1] else: sequence, pos_emb = sequence, None sequence = sequence.transpose(1, 2) # The bidirect_pos is used to distinguish legacy_rel_pos and rel_pos in # Conformer model. Note the `legacy_rel_pos` will be deprecated in the future. # Details can be found in https://github.com/espnet/espnet/pull/2816. if pos_emb is not None and pos_emb.size(1) == (2 * sequence.size(2)) - 1: bidir_pos_emb = True else: bidir_pos_emb = False sequence = self.tdnn(sequence) if self.relu: sequence = self.relu_func(sequence) sequence = self.dropout(sequence) if self.batch_norm: sequence = self.bn(sequence) sequence = sequence.transpose(1, 2) return self.create_outputs(sequence, pos_emb, mask, bidir_pos_emb) def create_outputs( self, sequence: torch.Tensor, pos_emb: torch.Tensor, mask: torch.Tensor, bidir_pos_emb: bool, ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]], torch.Tensor]: """Create outputs with subsampled version of pos_emb and masks. Args: sequence: TDNN output sequences. (B, sub(T), D_out) pos_emb: Input positional embedding. (B, T, att_dim) or (B, 2 * (T - 1), D_att) mask: Mask of TDNN input sequences. (B, 1, T) bidir_pos_emb: Whether to use bidirectional positional embedding. Returns: sequence: TDNN output sequences. (B, sub(T), D_out) pos_emb: Output positional embedding. (B, sub(T), D_att) or (B, 2 * (sub(T) - 1), D_att) mask: Mask of TDNN output sequences. (B, 1, sub(T)) """ sub = (self.ctx_size - 1) * self.dilation if mask is not None: if sub != 0: mask = mask[:, :, :-sub] mask = mask[:, :, :: self.stride] if pos_emb is not None: # If the bidirect_pos is true, the pos_emb will include both positive and # negative embeddings. Refer to https://github.com/espnet/espnet/pull/2816. if bidir_pos_emb: pos_emb_positive = pos_emb[:, : pos_emb.size(1) // 2 + 1, :] pos_emb_negative = pos_emb[:, pos_emb.size(1) // 2 :, :] if sub != 0: pos_emb_positive = pos_emb_positive[:, :-sub, :] pos_emb_negative = pos_emb_negative[:, :-sub, :] pos_emb_positive = pos_emb_positive[:, :: self.stride, :] pos_emb_negative = pos_emb_negative[:, :: self.stride, :] pos_emb = torch.cat( [pos_emb_positive, pos_emb_negative[:, 1:, :]], dim=1 ) else: if sub != 0: pos_emb = pos_emb[:, :-sub, :] pos_emb = pos_emb[:, :: self.stride, :] return (sequence, pos_emb), mask return sequence, mask
[ "torch.nn.ReLU", "torch.nn.Dropout", "torch.nn.BatchNorm1d", "torch.nn.Conv1d", "torch.cat" ]
[((1111, 1182), 'torch.nn.Conv1d', 'torch.nn.Conv1d', (['idim', 'odim', 'ctx_size'], {'stride': 'stride', 'dilation': 'dilation'}), '(idim, odim, ctx_size, stride=stride, dilation=dilation)\n', (1126, 1182), False, 'import torch\n'), ((1375, 1407), 'torch.nn.Dropout', 'torch.nn.Dropout', ([], {'p': 'dropout_rate'}), '(p=dropout_rate)\n', (1391, 1407), False, 'import torch\n'), ((1257, 1272), 'torch.nn.ReLU', 'torch.nn.ReLU', ([], {}), '()\n', (1270, 1272), False, 'import torch\n'), ((1324, 1350), 'torch.nn.BatchNorm1d', 'torch.nn.BatchNorm1d', (['odim'], {}), '(odim)\n', (1344, 1350), False, 'import torch\n'), ((5064, 5128), 'torch.cat', 'torch.cat', (['[pos_emb_positive, pos_emb_negative[:, 1:, :]]'], {'dim': '(1)'}), '([pos_emb_positive, pos_emb_negative[:, 1:, :]], dim=1)\n', (5073, 5128), False, 'import torch\n')]
# Copyright (c) 2011 <NAME> # Licensed under the MIT license # see LICENSE file for copying permission. import datetime, os, glob # build info BUILD_VERSION = '0.12' BUILD_DATETIME = datetime.datetime(2011, 9, 27, 7, 44, 0) # base db set up, the rest is in environment specific setting files DATABASE_ENGINE = 'mysql' DATABASE_OPTIONS = { "init_command" : "SET storage_engine=INNODB" } # locale set up TIME_ZONE = 'America/New_York' LANGUAGE_CODE = 'en-us' USE_I18N = False # template set up TEMPLATE_LOADERS = ( 'django.template.loaders.app_directories.load_template_source', ) TEMPLATE_DIRS = ( ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.request', ) # middleware and app set up ROOT_URLCONF = 'frano.urls' MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', ) INSTALLED_APPS = ( 'django.contrib.sessions', 'frano', 'frano.main', 'frano.quotes', 'frano.transactions', 'frano.account', 'frano.positions', ) # session settings SESSION_ENGINE = 'django.contrib.sessions.backends.db' SESSION_EXPIRE_AT_BROWSER_CLOSE = True # load external settings settings_dir = os.path.realpath(os.path.dirname(__file__)) settings_files = glob.glob(os.path.join(settings_dir, 'settings/*.py')) settings_files.sort() for f in settings_files: execfile(os.path.abspath(f))
[ "datetime.datetime", "os.path.dirname", "os.path.join", "os.path.abspath" ]
[((185, 225), 'datetime.datetime', 'datetime.datetime', (['(2011)', '(9)', '(27)', '(7)', '(44)', '(0)'], {}), '(2011, 9, 27, 7, 44, 0)\n', (202, 225), False, 'import datetime, os, glob\n'), ((1234, 1259), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (1249, 1259), False, 'import datetime, os, glob\n'), ((1288, 1331), 'os.path.join', 'os.path.join', (['settings_dir', '"""settings/*.py"""'], {}), "(settings_dir, 'settings/*.py')\n", (1300, 1331), False, 'import datetime, os, glob\n'), ((1391, 1409), 'os.path.abspath', 'os.path.abspath', (['f'], {}), '(f)\n', (1406, 1409), False, 'import datetime, os, glob\n')]
''' Builder for the snapshot from smaller snapshots. ''' from amuse.datamodel.particles import Particles from amuse.lab import units from amuse.units.quantities import VectorQuantity from omtool.core.datamodel import Snapshot class SnapshotBuilder: ''' Builder for the snapshot from smaller snapshots. ''' def __init__(self): self.snapshot = Snapshot(Particles(), 0 | units.Myr) def add_snapshot(self, snapshot: Snapshot, offset: VectorQuantity = [0, 0, 0] | units.kpc, velocity: VectorQuantity = [0, 0, 0] | units.kms ): ''' Appends snapshot of any number of particles to the result. ''' snapshot.particles.position += offset snapshot.particles.velocity += velocity self.snapshot = self.snapshot + snapshot def add_particles(self, particles: Particles): ''' Appends particles to the result and takes timestamp from it. ''' self.snapshot.particles.add_particles(particles) def get_result(self) -> Snapshot: ''' Returns resulting snapshot. ''' self.snapshot.particles.move_to_center() return self.snapshot def to_fits(self, filename: str): ''' Writes reult to FITS file. ''' self.snapshot.particles.move_to_center() self.snapshot.to_fits(filename)
[ "amuse.datamodel.particles.Particles" ]
[((377, 388), 'amuse.datamodel.particles.Particles', 'Particles', ([], {}), '()\n', (386, 388), False, 'from amuse.datamodel.particles import Particles\n')]
"""A collection of utility functions""" import json import os def parse_quantity(q): """ Parse an Onshape units definition Args: q:an Onshape units definition... for instance: { 'typeTag': '', 'unitToPower': [ { 'key': 'METER', 'value': 1 } ], 'value': 0.0868175271040671 } Returns: a string that can be converted to any other unit engine. >>> from onshape_client.utility import parse_quantity >>> d = {'value': 0.1414213562373095, 'unitToPower': [{'value': 1, 'key': 'METER'}], 'typeTag': ''} >>> parse_quantity(d) '0.1414213562373095*meter' >>> d = {'value': 0.1414213562373095, 'unitToPower': [{'value': 3, 'key': 'MILLIMETER'}], 'typeTag': ''} >>> parse_quantity(d) '0.1414213562373095*millimeter**3' """ units_s = str(q["value"]) for u in q["unitToPower"]: units_s = units_s + "*" + u["key"].lower() power = u["value"] if not power == 1: units_s = units_s + "**" + str(power) return units_s def get_field(response, field): return load_json(response)[field] def load_json(response): data = json.loads(response.data.decode("UTF-8")) return data def write_to_file(data_uri): """Write a data uri to a local file""" from base64 import b64decode import re header, encoded = data_uri.split(",", 1) data = b64decode(encoded) pattern = re.compile(r"""name=([^;]*)""") name = pattern.search(header).groups()[0] name = name.replace("+", " ") tmp_path = "tmp/" try: os.mkdir(tmp_path) except BaseException: pass file_path = os.getcwd() + "/" + tmp_path + name with open(file_path, "wb") as f: f.write(data) return file_path
[ "os.getcwd", "os.mkdir", "base64.b64decode", "re.compile" ]
[((1507, 1525), 'base64.b64decode', 'b64decode', (['encoded'], {}), '(encoded)\n', (1516, 1525), False, 'from base64 import b64decode\n'), ((1540, 1566), 're.compile', 're.compile', (['"""name=([^;]*)"""'], {}), "('name=([^;]*)')\n", (1550, 1566), False, 'import re\n'), ((1691, 1709), 'os.mkdir', 'os.mkdir', (['tmp_path'], {}), '(tmp_path)\n', (1699, 1709), False, 'import os\n'), ((1765, 1776), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1774, 1776), False, 'import os\n')]
#-*- coding=utf-8 -*- #@Time : 2020/10/9 8:40 PM #@Author : 小邋遢 #@File : dandong_policy_spider.py #@Software : PyCharm import pymysql import requests import re from lxml import etree import pandas as pd from policy.config import * headers = { "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36" } def total_page_numbers(): url = "http://ddkjj.dandong.gov.cn/webfile/zcfg/index.html" r = requests.get(url,headers=headers) try: if r.status_code == 200: r.encoding = 'utf-8' html = etree.HTML(r.text) total_page_number = html.xpath("//div[@class='foot_list']/a/text()") total_page_number = total_page_number[-3] total_page_number = ''.join(total_page_number).strip() return total_page_number else: return None except ConnectionError: print("Error of parsing the total number of pages") def page_urls(url): r = requests.get(url,headers=headers) try: if r.status_code == 200: r.encoding = 'utf-8' html = etree.HTML(r.text) urls = html.xpath("//div[@class='frame_list01']/ul/li/a/@href") return urls else: return None except ConnectionError: print("Error of parsing each page URL") def coonect_mysql(): db = pymysql.connect(**CONFIG) cursor = db.cursor() return db,cursor def id_is(title): db, cursor = coonect_mysql() # 判断数据是否存在 sql = 'select title from policy where title="{}"'.format(title) data = pd.read_sql_query(sql, db) if len(data["title"]) != 0: print("该内容已经存在数据库....") return 1 else: return 0 def save_to_mysql(results): db,cursor = coonect_mysql() title = results['title'] flag = id_is(title) if flag == 0: print("正在保存数据.....") release_data = results['release_data'] source = results['source'] details = results['details'] original_link = results['original_link'] try: sql = 'insert into policy(title,release_data,source,details,original_link) values(%s,%s,%s,%s,%s)' cursor.execute(sql, (title,release_data,source,details,original_link)) db.commit() print("保存到数据库成功.....") cursor.close() db.close() except: print('保存到数据库失败.....') def page_details(url): r = requests.get(url,headers=headers) try: if r.status_code == 200: r.encoding = 'utf-8' print("正在抓取数据......") html = etree.HTML(r.text) # 标题 title = html.xpath("//div[@id='ivs_title']//text()") title = ''.join(title).strip() data = html.xpath("//div[@class='read color02']//text()") data = ''.join(data).strip() # 发布日期:release_data release_data = re.findall("发布日期: (.*)", data) release_data = ''.join(release_data) # 来源 source = re.findall("信息来源:(.*) ", data) source = ''.join(source) source = re.split(r"\u3000\u3000", source)[0] try: # 内容 details = html.xpath("//div[@class='article_cont']//text()") details = ''.join(details) except: details = None # 链接 original_link = html.xpath("//div[@class='article_cont']/p/a/@href") if original_link: original_link = ''.join(original_link) original_link = 'http:' + original_link else: original_link = None results = { "title":title, "release_data":release_data, "source":source, "details":details, "original_link":original_link, } print(results) save_to_mysql(results) else: return None except ConnectionError: print(" Error of parsing img url ") def main(): # 获取总页数 total_page_number = total_page_numbers() for i in range(1,int(total_page_number)+1): if i == 1: url = "http://ddkjj.dandong.gov.cn/webfile/zcfg/index.html" else: url = "http://ddkjj.dandong.gov.cn/webfile/zcfg/index_{}.html".format(i) urls = page_urls(url) for url in urls: url = "http:" + url page_details(url) if __name__ == '__main__': main()
[ "pandas.read_sql_query", "re.split", "pymysql.connect", "requests.get", "lxml.etree.HTML", "re.findall" ]
[((490, 524), 'requests.get', 'requests.get', (['url'], {'headers': 'headers'}), '(url, headers=headers)\n', (502, 524), False, 'import requests\n'), ((1033, 1067), 'requests.get', 'requests.get', (['url'], {'headers': 'headers'}), '(url, headers=headers)\n', (1045, 1067), False, 'import requests\n'), ((1425, 1450), 'pymysql.connect', 'pymysql.connect', ([], {}), '(**CONFIG)\n', (1440, 1450), False, 'import pymysql\n'), ((1643, 1669), 'pandas.read_sql_query', 'pd.read_sql_query', (['sql', 'db'], {}), '(sql, db)\n', (1660, 1669), True, 'import pandas as pd\n'), ((2513, 2547), 'requests.get', 'requests.get', (['url'], {'headers': 'headers'}), '(url, headers=headers)\n', (2525, 2547), False, 'import requests\n'), ((618, 636), 'lxml.etree.HTML', 'etree.HTML', (['r.text'], {}), '(r.text)\n', (628, 636), False, 'from lxml import etree\n'), ((1161, 1179), 'lxml.etree.HTML', 'etree.HTML', (['r.text'], {}), '(r.text)\n', (1171, 1179), False, 'from lxml import etree\n'), ((2675, 2693), 'lxml.etree.HTML', 'etree.HTML', (['r.text'], {}), '(r.text)\n', (2685, 2693), False, 'from lxml import etree\n'), ((2992, 3022), 're.findall', 're.findall', (['"""发布日期: (.*)"""', 'data'], {}), "('发布日期: (.*)', data)\n", (3002, 3022), False, 'import re\n'), ((3110, 3140), 're.findall', 're.findall', (['"""信息来源:(.*) """', 'data'], {}), "('信息来源:(.*) ', data)\n", (3120, 3140), False, 'import re\n'), ((3199, 3233), 're.split', 're.split', (['"""\\\\u3000\\\\u3000"""', 'source'], {}), "('\\\\u3000\\\\u3000', source)\n", (3207, 3233), False, 'import re\n')]
from __future__ import unicode_literals import inspect import sys import pytest from _pytest_mock_version import version __version__ = version # pseudo-six; if this starts to require more than this, depend on six already if sys.version_info[0] == 2: # pragma: no cover text_type = unicode # noqa else: text_type = str def _get_mock_module(config): """ Import and return the actual "mock" module. By default this is "mock" for Python 2 and "unittest.mock" for Python 3, but the user can force to always use "mock" on Python 3 using the mock_use_standalone_module ini option. """ if not hasattr(_get_mock_module, "_module"): use_standalone_module = parse_ini_boolean( config.getini("mock_use_standalone_module") ) if sys.version_info[0] == 2 or use_standalone_module: import mock _get_mock_module._module = mock else: import unittest.mock _get_mock_module._module = unittest.mock return _get_mock_module._module class MockFixture(object): """ Fixture that provides the same interface to functions in the mock module, ensuring that they are uninstalled at the end of each test. """ def __init__(self, config): self._patches = [] # list of mock._patch objects self._mocks = [] # list of MagicMock objects self.mock_module = mock_module = _get_mock_module(config) self.patch = self._Patcher(self._patches, self._mocks, mock_module) # aliases for convenience self.Mock = mock_module.Mock self.MagicMock = mock_module.MagicMock self.NonCallableMock = mock_module.NonCallableMock self.PropertyMock = mock_module.PropertyMock self.call = mock_module.call self.ANY = mock_module.ANY self.DEFAULT = mock_module.DEFAULT self.create_autospec = mock_module.create_autospec self.sentinel = mock_module.sentinel self.mock_open = mock_module.mock_open def resetall(self): """ Call reset_mock() on all patchers started by this fixture. """ for m in self._mocks: m.reset_mock() def stopall(self): """ Stop all patchers started by this fixture. Can be safely called multiple times. """ for p in reversed(self._patches): p.stop() self._patches[:] = [] self._mocks[:] = [] def spy(self, obj, name): """ Creates a spy of method. It will run method normally, but it is now possible to use `mock` call features with it, like call count. :param object obj: An object. :param unicode name: A method in object. :rtype: mock.MagicMock :return: Spy object. """ method = getattr(obj, name) autospec = inspect.ismethod(method) or inspect.isfunction(method) # Can't use autospec classmethod or staticmethod objects # see: https://bugs.python.org/issue23078 if inspect.isclass(obj): # Bypass class descriptor: # http://stackoverflow.com/questions/14187973/python3-check-if-method-is-static try: value = obj.__getattribute__(obj, name) except AttributeError: pass else: if isinstance(value, (classmethod, staticmethod)): autospec = False result = self.patch.object(obj, name, side_effect=method, autospec=autospec) return result def stub(self, name=None): """ Creates a stub method. It accepts any arguments. Ideal to register to callbacks in tests. :param name: the constructed stub's name as used in repr :rtype: mock.MagicMock :return: Stub object. """ return self.mock_module.MagicMock(spec=lambda *args, **kwargs: None, name=name) class _Patcher(object): """ Object to provide the same interface as mock.patch, mock.patch.object, etc. We need this indirection to keep the same API of the mock package. """ def __init__(self, patches, mocks, mock_module): self._patches = patches self._mocks = mocks self.mock_module = mock_module def _start_patch(self, mock_func, *args, **kwargs): """Patches something by calling the given function from the mock module, registering the patch to stop it later and returns the mock object resulting from the mock call. """ p = mock_func(*args, **kwargs) mocked = p.start() self._patches.append(p) if hasattr(mocked, "reset_mock"): self._mocks.append(mocked) return mocked def object(self, *args, **kwargs): """API to mock.patch.object""" return self._start_patch(self.mock_module.patch.object, *args, **kwargs) def multiple(self, *args, **kwargs): """API to mock.patch.multiple""" return self._start_patch(self.mock_module.patch.multiple, *args, **kwargs) def dict(self, *args, **kwargs): """API to mock.patch.dict""" return self._start_patch(self.mock_module.patch.dict, *args, **kwargs) def __call__(self, *args, **kwargs): """API to mock.patch""" return self._start_patch(self.mock_module.patch, *args, **kwargs) @pytest.yield_fixture def mocker(pytestconfig): """ return an object that has the same interface to the `mock` module, but takes care of automatically undoing all patches after each test method. """ result = MockFixture(pytestconfig) yield result result.stopall() @pytest.fixture def mock(mocker): """ Same as "mocker", but kept only for backward compatibility. """ import warnings warnings.warn( '"mock" fixture has been deprecated, use "mocker" instead', DeprecationWarning ) return mocker _mock_module_patches = [] _mock_module_originals = {} def assert_wrapper(__wrapped_mock_method__, *args, **kwargs): __tracebackhide__ = True try: __wrapped_mock_method__(*args, **kwargs) return except AssertionError as e: if getattr(e, "_mock_introspection_applied", 0): msg = text_type(e) else: __mock_self = args[0] msg = text_type(e) if __mock_self.call_args is not None: actual_args, actual_kwargs = __mock_self.call_args msg += "\n\npytest introspection follows:\n" try: assert actual_args == args[1:] except AssertionError as e: msg += "\nArgs:\n" + text_type(e) try: assert actual_kwargs == kwargs except AssertionError as e: msg += "\nKwargs:\n" + text_type(e) e = AssertionError(msg) e._mock_introspection_applied = True raise e def wrap_assert_not_called(*args, **kwargs): __tracebackhide__ = True assert_wrapper(_mock_module_originals["assert_not_called"], *args, **kwargs) def wrap_assert_called_with(*args, **kwargs): __tracebackhide__ = True assert_wrapper(_mock_module_originals["assert_called_with"], *args, **kwargs) def wrap_assert_called_once(*args, **kwargs): __tracebackhide__ = True assert_wrapper(_mock_module_originals["assert_called_once"], *args, **kwargs) def wrap_assert_called_once_with(*args, **kwargs): __tracebackhide__ = True assert_wrapper(_mock_module_originals["assert_called_once_with"], *args, **kwargs) def wrap_assert_has_calls(*args, **kwargs): __tracebackhide__ = True assert_wrapper(_mock_module_originals["assert_has_calls"], *args, **kwargs) def wrap_assert_any_call(*args, **kwargs): __tracebackhide__ = True assert_wrapper(_mock_module_originals["assert_any_call"], *args, **kwargs) def wrap_assert_called(*args, **kwargs): __tracebackhide__ = True assert_wrapper(_mock_module_originals["assert_called"], *args, **kwargs) def wrap_assert_methods(config): """ Wrap assert methods of mock module so we can hide their traceback and add introspection information to specified argument asserts. """ # Make sure we only do this once if _mock_module_originals: return mock_module = _get_mock_module(config) wrappers = { "assert_called": wrap_assert_called, "assert_called_once": wrap_assert_called_once, "assert_called_with": wrap_assert_called_with, "assert_called_once_with": wrap_assert_called_once_with, "assert_any_call": wrap_assert_any_call, "assert_has_calls": wrap_assert_has_calls, "assert_not_called": wrap_assert_not_called, } for method, wrapper in wrappers.items(): try: original = getattr(mock_module.NonCallableMock, method) except AttributeError: # pragma: no cover continue _mock_module_originals[method] = original patcher = mock_module.patch.object(mock_module.NonCallableMock, method, wrapper) patcher.start() _mock_module_patches.append(patcher) if hasattr(config, "add_cleanup"): add_cleanup = config.add_cleanup else: # pytest 2.7 compatibility add_cleanup = config._cleanup.append add_cleanup(unwrap_assert_methods) def unwrap_assert_methods(): for patcher in _mock_module_patches: try: patcher.stop() except RuntimeError as e: # a patcher might have been stopped by user code (#137) # so we need to catch this error here and ignore it; # unfortunately there's no public API to check if a patch # has been started, so catching the error it is if text_type(e) == "stop called on unstarted patcher": pass else: raise _mock_module_patches[:] = [] _mock_module_originals.clear() def pytest_addoption(parser): parser.addini( "mock_traceback_monkeypatch", "Monkeypatch the mock library to improve reporting of the " "assert_called_... methods", default=True, ) parser.addini( "mock_use_standalone_module", 'Use standalone "mock" (from PyPI) instead of builtin "unittest.mock" ' "on Python 3", default=False, ) def parse_ini_boolean(value): if value in (True, False): return value try: return {"true": True, "false": False}[value.lower()] except KeyError: raise ValueError("unknown string for bool: %r" % value) def pytest_configure(config): tb = config.getoption("--tb") if ( parse_ini_boolean(config.getini("mock_traceback_monkeypatch")) and tb != "native" ): wrap_assert_methods(config)
[ "warnings.warn", "inspect.isclass", "inspect.isfunction", "inspect.ismethod" ]
[((5934, 6031), 'warnings.warn', 'warnings.warn', (['""""mock" fixture has been deprecated, use "mocker" instead"""', 'DeprecationWarning'], {}), '(\'"mock" fixture has been deprecated, use "mocker" instead\',\n DeprecationWarning)\n', (5947, 6031), False, 'import warnings\n'), ((3045, 3065), 'inspect.isclass', 'inspect.isclass', (['obj'], {}), '(obj)\n', (3060, 3065), False, 'import inspect\n'), ((2864, 2888), 'inspect.ismethod', 'inspect.ismethod', (['method'], {}), '(method)\n', (2880, 2888), False, 'import inspect\n'), ((2892, 2918), 'inspect.isfunction', 'inspect.isfunction', (['method'], {}), '(method)\n', (2910, 2918), False, 'import inspect\n')]
from __future__ import print_function import os import json import base64 from multiprocessing import Process import hashlib import webbrowser import warnings from .GanjaScene import GanjaScene from .color import Color CEFAVAILABLE = False try: from .cefwindow import * CEFAVAILABLE = True except: warnings.warn( 'Failed to import cef_gui, cef functions will be unavailable', stacklevel=2) JUPYTERAVAILABLE = False try: from IPython.display import display, Javascript from IPython import get_ipython JUPYTERAVAILABLE = True except: warnings.warn( 'Failed to import ipython, notebook rendering will be unavailable', stacklevel=2) def html_to_data_uri(html): html = html.encode("utf-8", "replace") b64 = base64.b64encode(html).decode("utf-8", "replace") ret = "data:text/html;base64,{data}".format(data=b64) return ret def read_ganja(): dir_name = os.path.dirname(os.path.abspath(__file__)) ganja_filename = dir_name + '/static/ganja.js/ganja.js' with open(ganja_filename, 'r', encoding='utf8') as ganja_file: output = ganja_file.read() return output def generate_notebook_js(scene, sig=None, grid=True, scale=1.0, gl=True, default_color=Color.DEFAULT, default_static=False): script_json = _to_scene_string(scene, default_color=default_color, default_static=default_static) if sig is not None: p = (sig > 0).sum().item() # convert to json-compatible scalar q = (sig < 0).sum().item() # convert to json-compatible scalar r = len(sig) - p - q else: p = 4 q = 1 r = 0 mv_length = str(2 ** (p + q + r)) # not the best way to test conformal, as it prevents non-euclidean geometry if q != 0: conformal = True else: conformal = False if (p, q, r) in [(4, 1, 0), (3, 1, 0), (3, 0, 0), (3, 0, 1)]: if p - q == 2: gl = False # 2d opts = dict( p=p, q=q, r=r, gl=gl, conformal=conformal, grid=grid, scale=scale, mv_length=mv_length ) js = read_ganja() js += """ // take a closure on element before the next cell replaces it (function(element) { (requirejs||require)(['Algebra'], function(Algebra) { var opts = """ + json.dumps(opts) + """; // injected from python var output = Algebra({p: opts.p, q: opts.q, r: opts.r, baseType: Float64Array}).inline((opts)=>{ var data = """ + script_json + """; // injected from python // When we get a file, we load and display. var canvas; var h=0, p=0; // convert arrays of floats back to CGA elements. data = data.map(x=>x.length==opts.mv_length?new Element(x):x); // add the graph to the page. canvas = this.graph(data, {gl: opts.gl, conformal: opts.conformal, grid: opts.grid, scale: opts.scale, useUnnaturalLineDisplayForPointPairs: true}); canvas.options.h = h; canvas.options.p = p; // make it big. canvas.style.width = '100%'; canvas.style.height = '50vh'; return canvas; })(opts); element.append(output); var a = document.createElement("button"); var t = document.createTextNode("\N{FLOPPY DISK} Save"); a.appendChild(t); function screenshot(){ //output.width = 1920; output.height = 1080; output.update(output.value); output.toBlob(function(blob) { var url = URL.createObjectURL(blob); window.open(url, '_blank'); }); } window.addEventListener('resize', function() { output.update(output.value); }); a.onclick = screenshot var butnelem = element.append(a); }); })(element); """ else: raise ValueError('Algebra not yet supported') return Javascript(js) def generate_full_html(scene, sig=None, grid=True, scale=1.0, gl=True, default_color=Color.DEFAULT, default_static=False): script_json = _to_scene_string(scene, default_color=default_color, default_static=default_static) if sig is not None: p = (sig > 0).sum() q = (sig < 0).sum() r = len(sig) - p - q else: p = 4 q = 1 r = 0 sig_short = '%i,%i,%i' % (p, q, r) print(sig_short) mv_length = str(2 ** (p + q + r)) # not the best way to test conformal, as it prevents non-euclidean geometry conformal = 'false' if q!=0: conformal = 'true' if sig_short in ['4,1,0', '3,0,0', '3,0,1']: if grid: gridstr = 'true' else: gridstr = 'false' scalestr = str(scale) script_string = """ Algebra("""+sig_short+""",()=>{ var canvas = this.graph((""" + script_json + """).map(x=>x.length=="""+mv_length+"""?new Element(x):x), {conformal:"""+conformal+""",gl:"""+str(gl).lower()+""",grid:"""+gridstr+""",scale:"""+scalestr+""",useUnnaturalLineDisplayForPointPairs:true}); canvas.style.width = '100vw'; canvas.style.height = '100vh'; document.body.appendChild(canvas); }); """ full_html = """<!DOCTYPE html> <html lang="en" style="height:100%;"> <HEAD> <meta charset="UTF-8"> <title>pyganja</title> <SCRIPT>""" + read_ganja() + """</SCRIPT> </HEAD> <BODY style="position:absolute; top:0; bottom:0; right:0; left:0; overflow:hidden;"> <SCRIPT> """ + script_string + """ </SCRIPT> </BODY> </html> """ return full_html else: raise ValueError('Algebra not yet supported') def render_browser_script(scene, sig=None, grid=True, scale=1.0, gl=True, filename=None, default_color=Color.DEFAULT, default_static=False): """ If we have no jupyter and no cefpython we will be forced to generate html and render that in the users browser """ html_code = generate_full_html(scene, sig=sig, grid=grid, scale=scale, gl=gl, default_color=default_color, default_static=default_static) if filename is None: hash_object = hashlib.md5(html_code.encode()) filename = hash_object.hexdigest() + '.html' with open(filename, 'w', encoding='utf8') as fo: print(html_code,file=fo) webbrowser.open(filename) def render_notebook_script(scene, sig=None, grid=True, scale=1.0, gl=True, default_color=Color.DEFAULT, default_static=False): """ In a notebook we dont need to start cefpython as we are already in the browser! """ js = generate_notebook_js(scene, sig=sig, grid=grid, scale=scale, gl=gl, default_color=default_color, default_static=default_static) display(js) def render_cef_script(scene="", sig=None, grid=True, scale=1.0, gl=True, default_color=Color.DEFAULT, default_static=False): def render_script(): final_url = html_to_data_uri(generate_full_html(scene, sig=sig, grid=grid, scale=scale, gl=gl, default_color=default_color, default_static=default_static)) run_cef_gui(final_url, "pyganja") p = Process(target=render_script) p.start() p.join() def isnotebook(): # See: # https://stackoverflow.com/questions/15411967/how-can-i-check-if-code-is-executed-in-the-ipython-notebook try: shell = get_ipython().__class__.__name__ if shell == 'ZMQInteractiveShell': return True # Jupyter notebook or qtconsole elif shell == 'TerminalInteractiveShell': return False # Terminal running IPython else: return False # Other type (?) except NameError: return False # Probably standard Python interpreter def draw(objects, color=Color.DEFAULT, sig=None, grid=True, scale=1.0, browser_window=False, new_window=False, static=False, gl=True): if JUPYTERAVAILABLE: if isnotebook(): if not new_window: render_notebook_script(objects, sig=sig, grid=grid, scale=scale, gl=gl, default_color=color, default_static=static) else: if CEFAVAILABLE: if browser_window: render_browser_script(objects, sig=sig, grid=grid, scale=scale, gl=gl, default_color=color, default_static=static) else: render_cef_script(objects, sig=sig, grid=grid, scale=scale, gl=gl, default_color=color, default_static=static) else: render_browser_script(objects, sig=sig, grid=grid, scale=scale, gl=gl, default_color=color, default_static=static) else: if CEFAVAILABLE: if browser_window: render_browser_script(objects, sig=sig, grid=grid, scale=scale, gl=gl, default_color=color, default_static=static) else: render_cef_script(objects, sig=sig, grid=grid, scale=scale, gl=gl, default_color=color, default_static=static) else: render_browser_script(objects, sig=sig, grid=grid, scale=scale, gl=gl, default_color=color, default_static=static) else: if CEFAVAILABLE: if browser_window: render_browser_script(objects, sig=sig, grid=grid, scale=scale, gl=gl, default_color=color, default_static=static) else: render_cef_script(objects, sig=sig, grid=grid, scale=scale, gl=gl, default_color=color, default_static=static) else: render_browser_script(objects, sig=sig, grid=grid, scale=scale, gl=gl, default_color=color, default_static=static) def _to_scene_string(objects, default_color=Color.DEFAULT, default_static=False): if isinstance(objects, list): sc = GanjaScene() sc.add_objects(objects, color=default_color, static=default_static) return str(sc) elif isinstance(objects, str): return objects elif isinstance(objects, GanjaScene): return str(objects) else: sc = GanjaScene() try: print('Treating as iterable') sc.add_objects([i for i in objects], color=default_color, static=default_static) return str(sc) except Exception: raise ValueError('The input cannot be interpreted, it is not a list of objects or ganja scene')
[ "IPython.get_ipython", "IPython.display.display", "IPython.display.Javascript", "multiprocessing.Process", "base64.b64encode", "json.dumps", "webbrowser.open", "warnings.warn", "os.path.abspath" ]
[((4298, 4312), 'IPython.display.Javascript', 'Javascript', (['js'], {}), '(js)\n', (4308, 4312), False, 'from IPython.display import display, Javascript\n'), ((6932, 6957), 'webbrowser.open', 'webbrowser.open', (['filename'], {}), '(filename)\n', (6947, 6957), False, 'import webbrowser\n'), ((7389, 7400), 'IPython.display.display', 'display', (['js'], {}), '(js)\n', (7396, 7400), False, 'from IPython.display import display, Javascript\n'), ((7845, 7874), 'multiprocessing.Process', 'Process', ([], {'target': 'render_script'}), '(target=render_script)\n', (7852, 7874), False, 'from multiprocessing import Process\n'), ((314, 408), 'warnings.warn', 'warnings.warn', (['"""Failed to import cef_gui, cef functions will be unavailable"""'], {'stacklevel': '(2)'}), "('Failed to import cef_gui, cef functions will be unavailable',\n stacklevel=2)\n", (327, 408), False, 'import warnings\n'), ((581, 685), 'warnings.warn', 'warnings.warn', (['"""Failed to import ipython, notebook rendering will be unavailable"""'], {'stacklevel': '(2)'}), "(\n 'Failed to import ipython, notebook rendering will be unavailable',\n stacklevel=2)\n", (594, 685), False, 'import warnings\n'), ((951, 976), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (966, 976), False, 'import os\n'), ((777, 799), 'base64.b64encode', 'base64.b64encode', (['html'], {}), '(html)\n', (793, 799), False, 'import base64\n'), ((8069, 8082), 'IPython.get_ipython', 'get_ipython', ([], {}), '()\n', (8080, 8082), False, 'from IPython import get_ipython\n'), ((2360, 2376), 'json.dumps', 'json.dumps', (['opts'], {}), '(opts)\n', (2370, 2376), False, 'import json\n')]
# ------------------------------------------------------------------------------ # Copyright IBM Corp. 2020 # # 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. # ------------------------------------------------------------------------------ # flake8: noqa F522 import os import sys import tempfile import time import types import urllib import xml.etree.ElementTree as ET from collections import namedtuple from pprint import pformat import backoff import dateutil.parser import numpy as np import pandas as pd import requests from requests.exceptions import HTTPError try: from exceptions import ( RateLimitedException, CosUrlNotFoundException, CosUrlInaccessibleException, SqlQueryCrnInvalidFormatException, SqlQueryInvalidPlanException, SqlQueryFailException, SqlQueryInvalidFormatException, InternalError502Exception, ) except Exception: from .exceptions import ( RateLimitedException, CosUrlNotFoundException, CosUrlInaccessibleException, SqlQueryCrnInvalidFormatException, SqlQueryInvalidPlanException, SqlQueryFailException, SqlQueryInvalidFormatException, InternalError502Exception, ) try: from .cos import COSClient from .utilities import rename_keys from .sql_magic import SQLMagic, format_sql, print_sql from .catalog_table import HiveMetastore except ImportError: from cos import COSClient from utilities import rename_keys from sql_magic import SQLMagic, format_sql, print_sql from catalog_table import HiveMetastore import logging from functools import wraps import json from json import JSONDecodeError import inspect import re logger = logging.getLogger(__name__) def validate_job_status(f): """check if input about job status, via `status` argument is corrected""" @wraps(f) def wrapped(*args, **kwargs): self = args[0] dictionary = inspect.getcallargs(f, *args, **kwargs) status = dictionary["status"] supported_job_status = ["running", "completed", "failed"] if status not in supported_job_status: raise ValueError( "`status` must be a value in {}".format(supported_job_status) ) else: return f(*args, **kwargs) return wrapped def check_saved_jobs_decorator(f): """a decorator that load data from ProjectLib, check for completed SQL Query job, before deciding to launch it""" @wraps(f) def wrapped(*args, **kwargs): self = args[0] dictionary = inspect.getcallargs(f, *args, **kwargs) prefix = dictionary["file_name"] # Gets you the username, default or modifed sql_stmt = dictionary["sql_stmt"] # refine query sql_stmt = format_sql(sql_stmt) status_no_job_id = "not_launched" run_as_usual = True if self.project_lib is not None: # Use Watson Studio # handle here if self.project_lib.data is None: self.read_project_lib_data(file_name=prefix) keys_mapping = {} # refine existing data for key, _ in self.project_lib.data.items(): new_key = format_sql(key) if key != new_key: keys_mapping[key] = new_key if len(keys_mapping) > 0: rename_keys(self.project_lib.data, keys_mapping) if sql_stmt in self.project_lib.data: run_as_usual = False job_id = self.project_lib.data[sql_stmt]["job_id"] if self.project_lib.data[sql_stmt]["status"] == "completed": print("Job {} completed".format(job_id)) else: if self.project_lib.data[sql_stmt]["status"] != status_no_job_id: # query the status job_result = self.get_job(job_id) self.project_lib.data[sql_stmt]["job_info"] = job_result try: self.project_lib.data[sql_stmt]["status"] = job_result[ "status" ] except KeyError as e: import pprint pprint.pprint(job_id, "\n", job_result) raise e if job_result["status"] == "failed": run_as_usual = True self.write_project_lib_data() else: run_as_usual = True else: # use local file if prefix is None: if self._tracking_filename is None: msg = "Please configure the JSON file via `set_tracking_file`" raise ValueError(msg) else: prefix = self._tracking_filename try: with open(prefix) as json_data: self._data = json.load(json_data) if sql_stmt in self._data: run_as_usual = False job_id = self._data[sql_stmt]["job_id"] if self._data[sql_stmt]["status"] == "completed": print("Job {} completed".format(job_id)) else: if self._data[sql_stmt]["status"] != status_no_job_id: # query the status job_result = self.get_job(job_id) self._data[sql_stmt]["job_info"] = job_result try: self._data[sql_stmt]["status"] = job_result["status"] except KeyError as e: import pprint pprint.pprint(job_result) raise e if job_result["status"] == "failed": run_as_usual = True with open(prefix, "w") as outfile: json.dump(self._data, outfile) else: run_as_usual = True except FileNotFoundError: self._data = {} if run_as_usual: e_ = None job_id = "" status = "queued" try: job_id = f(*args, **kwargs) result = {"job_id": job_id, "status": status} if self.project_lib is not None: self.project_lib.data[sql_stmt] = result self.write_project_lib_data() else: # use local file self._data[sql_stmt] = result with open(prefix, "w") as outfile: json.dump(self._data, outfile) except Exception as e: e_ = e status = status_no_job_id if e_ is not None: if self.project_lib is not None: self.project_lib.data[sql_stmt] = { "job_id": job_id, "status": status, } self.write_project_lib_data() else: # use local file self._data[sql_stmt] = {"job_id": job_id, "status": status} with open(prefix, "w") as outfile: json.dump(self._data, outfile) if e_ is not None: raise e_ return job_id return wrapped class SQLQuery(COSClient, SQLMagic, HiveMetastore): """The class the provides necessary APIs to interact with 1. IBM SQL Serverless service 2. IBM COS service Parameters ---------- apikey : str, optional an account-level API key [manage/Access (IAM)/IBM Cloud API keys] instance_crn :str, optional CRN from SQLQuery instance target_cos_url : str, optional the URI where retrieved data is stored max_concurrent_jobs: int, optional the max number of concurrent jobs client_info : str, optional User-defined string max_tries: int, optional The number of time :meth:`.submit_sql`, should try to request CloudSQL before giving up. iam_max_tries: int, optional The number of times to request credential from IAM. By default, token is returned from a request to `iam.cloud.ibm.com` which may not be responsive (i.e. timeout=5 seconds). This parameter controls how many times to try. thread_safe: bool, optional (=False) If thread-safe is used, a new Session object is created upon this object creation """ def __init__( self, api_key, instance_crn, target_cos_url=None, client_info="IBM Cloud SQL Query Python SDK", thread_safe=False, max_concurrent_jobs=4, max_tries=1, iam_max_tries=1, ): staging_env = instance_crn.startswith("crn:v1:staging") if staging_env: self.api_hostname = "api.sql-query.test.cloud.ibm.com" self.ui_hostname = "sql-query.test.cloud.ibm.com" else: self.api_hostname = "api.sql-query.cloud.ibm.com" self.ui_hostname = "sql-query.cloud.ibm.com" COSClient.__init__( self, cloud_apikey=api_key, cos_url=target_cos_url, client_info=client_info, iam_max_tries=iam_max_tries, thread_safe=thread_safe, staging=staging_env, ) SQLMagic.__init__(self) if target_cos_url is not None: HiveMetastore.__init__(self, target_cos_url) self.instance_crn = instance_crn self.target_cos_url = target_cos_url self.export_cos_url = target_cos_url self.user_agent = client_info self.max_tries = max_tries self.max_concurrent_jobs = ( max_concurrent_jobs # the current maximum concurrent jobs ) # track the status of jobs - save the time to SQLQuery server self.jobs_tracking = {} self._tracking_filename = None logger.debug("SQLClient created successful") def set_tracking_file(self, file_name): """provides the file name which is used for tracking multiple SQL requests Notes ----- This is the local file, which is used when you don't have access to Watson Studio """ self._tracking_filename = file_name @property def my_jobs(self): """ Return information about jobs already queried via :meth:`.get_job` issued by this SQLClient class object This is different from :py:meth:`.get_jobs` Returns ------- dict """ return self.jobs_tracking def configure(self, apikey=None, instance_crn=None, cos_out_url=None): """ update the configuration """ COSClient.configure(self, apikey) if instance_crn is None: self.instance_crn = ( input( "Enter SQL Query Instance CRN (leave empty to use previous one): " ) or self.instance_crn ) else: self.instance_crn = instance_crn if cos_out_url is None: if self.target_cos_url is None or self.target_cos_url == "": while True: self.target_cos_url = input("Enter target URI for SQL results: ") if self.is_valid_cos_url(cos_url): break else: old_cos_url = str(self.target_cos_url) while True: self.target_cos_url = ( input( "Enter target URI for SQL results (leave empty to use " + self.target_cos_url + "): " ) or old_cos_url ) if self.is_valid_cos_url(cos_url): break else: self.target_cos_url = cos_out_url HiveMetastore.configure(self, self.target_cos_url) self.logon(force=True) def _response_error_msg(self, response): try: return response.json()["errors"][0]["message"] except: # if we get the error from some intermediate proxy, it may # not match the SQLQuery error format return "Non-parseable error: {txt}".format(txt=response.text[0:200]) def _send_req(self, json_data): """send SQL data to API. return job id""" try: response = requests.post( "https://{}/v2/sql_jobs?instance_crn={}".format( self.api_hostname, self.instance_crn ), headers=self.request_headers, json=json_data, ) # Throw in case we hit the rate limit if response.status_code == 429: time.sleep(3) # seconds raise RateLimitedException( "SQL submission failed ({code}): {msg}".format( code=response.status_code, msg=self._response_error_msg(response), ) ) # Throw in case we hit 502, which sometimes is sent by Cloudflare when API is temporarily unreachable if response.status_code == 502: time.sleep(3) # seconds raise InternalError502Exception( "Internal Error ({code}): {msg}".format( code=response.status_code, msg=self._response_error_msg(response), ) ) # any other error but 429 will be raised here, like 403 etc response.raise_for_status() resp = response.json() if "job_id" in resp: return resp["job_id"] else: raise SyntaxError( "Response {resp} contains no job ID".format(resp=resp) ) except (HTTPError) as _: msg = self._response_error_msg(response) error_message = "SQL submission failed ({code}): {msg} - {query}".format( code=response.status_code, msg=msg, query=pformat(json_data) ) crn_error = "Service CRN has an invalid format" crn_invalid_plan_error = "upgrade this instance" if crn_error in error_message: error_message = "SQL submission failed ({code}): {msg}".format( code=response.status_code, msg=msg ) raise SqlQueryCrnInvalidFormatException(error_message) elif crn_invalid_plan_error in error_message: error_message = "SQL submission failed ({code}): {msg}".format( code=response.status_code, msg=msg ) raise SqlQueryInvalidPlanException(error_message) else: raise SyntaxError(error_message) def submit(self, pagesize=None): """ run the internal SQL statement that you created using the APIs provided by SQLMagic """ self.format_() return self.submit_sql(self._sql_stmt, pagesize=pagesize) def submit_sql(self, sql_stmt, pagesize=None): """ Asynchronous call - submit and quickly return the job_id. Parameters ---------- sql_stmt: str SQL Query string pagesize: int, optional an integer indicating the number of rows for each partition/page [using PARTITIONED EVERY <pagesize> ROWS syntax] Returns ------- str job_id Raises ------ RateLimitedException when the SQLQUery instance is serving the max-limit of requests SyntaxError for both KeyError or HTTPError Examples -------- .. code-block:: console curl -XPOST \ --url "https://api.sql-query.cloud.ibm.com/v2/sql_jobs?instance_crn=YOUR_SQL_QUERY_CRN" \ -H "Accept: application/json" \ -H "Authorization: Bearer YOUR_BEARER_TOKEN" \ -H "Content-Type: application/json" \ -d '{"statement":"SELECT firstname FROM cos://us-geo/sql/employees.parquet STORED AS PARQUET WHERE EMPLOYEEID=5 INTO cos://us-geo/target-bucket/q1-results" }' NOTE: 1. All the headers (-H) can be put into a dictionary and passed to the *headers* argument of requests.post() API. 2. All the data (-d option) is put into a dictionary and passed to the *json* argument of requests.post() API. * 'statement': value is full SQL statement in string * 'resultset_target' (optional): only need when there is no 'INTO statement' in the query string, and the value must be the COS URL output .. code-block:: python sqlData = {'statement': sql_stmt} request_headers = {'Content-Type': 'application/json'} request_headers.update({'Accept':'application/json'}) request_headers.update({'User-Agent': self.user_agent}) request_headers.update({'authorization': 'Bearer {}'.format(ro_credentials.token)}) response = requests.post( "https://api.sql-query.cloud.ibm.com/v2/sql_jobs?instance_crn={}".format(self.instance_crn), headers=request_headers, json=sqlData) \"\"\" { "errors": [ { "code": "bad_request", "message": "Target url specified in parameter resultset_target and as part of into clause in statement" } ] } { "job_id": "e2adca0a-9247-4cfa-ac58-db4b2bc33a01", "status": "queued" } { "status_code": 429, "errors": [ { "code": "too_many_requests", "message": "This instance is currently running its maximum number of query jobs. Try again later, after at least one of the currently running jobs has completed." } ] } \"\"\" # error code information: https://cloud.ibm.com/apidocs/sql-query """ self.logon() sql_text = sql_stmt sqlData = {"statement": sql_text} def INTO_is_present(sql_text): """ check if INTO keyword is present in the SQL query""" tmp = sql_text.replace("\n", " ") return (" INTO " in tmp.upper()) or ("\nINTO " in tmp.upper()) # If a valid pagesize is specified we need to append the proper PARTITIONED EVERY <num> ROWS clause if pagesize or pagesize == 0: if type(pagesize) == int and pagesize > 0: if self.target_cos_url and not INTO_is_present(sql_text): sqlData["statement"] += " INTO {}".format(self.target_cos_url) elif not INTO_is_present(sql_text): raise SyntaxError( 'Neither resultset_target parameter nor "INTO" clause specified.' ) elif " PARTITIONED " in sql_text.upper(): raise SyntaxError( "Must not use PARTITIONED clause when specifying pagesize parameter." ) sqlData["statement"] += " PARTITIONED EVERY {} ROWS".format(pagesize) else: raise ValueError( "pagesize parameter ({}) is not valid.".format(pagesize) ) elif self.target_cos_url and not INTO_is_present(sql_text): sqlData.update({"resultset_target": self.target_cos_url}) max_tries = self.max_tries intrumented_send = backoff.on_exception( backoff.expo, (RateLimitedException, InternalError502Exception), max_tries=max_tries, )(self._send_req) return intrumented_send(sqlData) @check_saved_jobs_decorator def submit_and_track_sql(self, sql_stmt, pagesize=None, file_name=None): """ Each SQL Query instance is limited by the number of sql queries that it can handle at a time. This can be a problem when you launch many SQL Query jobs, as such limitation may prevent you to complete all of them in one session. The `max_tries` options when creating the SQL Query client object allows you to re-send the job, which is still limited to one session. The time for one session is often limited when when using SQL Query client via Watson Studio, i.e. you will lose the session after having no interaction with the notebook for a period of time. This API provides the capability to put the information of each launched jobs in a `file_name` stored either * as an asset in the Watson Studio's Project. * as a regular file in the local machine. The SQL Query client will check the content of such file name to see if the given `sql_stmt` has been launched, and if so, whether it is completed or not. If not completed, then it relaunches the job, and update the content in this file. Otherwise, it skips the `sql_stmt`. To check if a `sql_stmt` has been issued or not, the :func:`.format_sql` transforms the query string into a style that can be used for string comparison that is tolerance to white spaces, new lines, comments, lower-case or upper-case uses in the query string. This is done by the decorator :meth:`check_saved_jobs_decorator`. This is beneficial in the scenario when you launch many many jobs, and don't want to restart from the beginning. Parameters ---------- sql_stmt: str sql string pagesize: int, optional the page size file_name: str, optional The file name should be a JSON file, i.e. $file_name.json. You need to provide the file name if * (1) you use Watson studio notebook and you haven't provided it in :meth:`.connect_project_lib`, * (2) you use local notebook, and you want to use a local file to track it You don't need to provide the file name if you're using Watson studio, and the file name has been provided via :meth:`.connect_project_lib`. Notes ----- To use this API in Watson Studio, the SQL Query client must already connected to the ProjectLib object via :meth:`.connect_project_lib` method. This APIs make use of :py:meth:`.COSClient.connect_project_lib`, :py:meth:`.COSClient.read_project_lib_data`. """ return self.submit_sql(sql_stmt, pagesize=pagesize) def wait_for_job(self, jobId, sleep_time=2): """ It's possible that the job's failed because of Spark's internal error which does not have any status. So "unknown" is added for such cases. Parameters ----------- jobId: str The job-id sleep_time: int, optional The time interval to sleep before making a new check if the job is done Returns ------- 'failed', 'completed', or 'unknown' """ def wait_for_job(jobId): while True: self.logon() response = requests.get( "https://{}/v2/sql_jobs/{}?instance_crn={}".format( self.api_hostname, jobId, self.instance_crn ), headers=self.request_headers, ) if response.status_code == 200 or response.status_code == 201: status_response = response.json() jobStatus = status_response["status"] if jobStatus == "completed": break if jobStatus == "failed": print("Job {} has failed".format(jobId)) break else: print( "Job status check failed with http code {}".format( response.status_code ) ) break time.sleep(sleep_time) return jobStatus job_id = jobId try: x = wait_for_job(job_id) except UnboundLocalError as _: x = "unknown" return x def __iter__(self): return 0 def get_result(self, jobId, pagenumber=None): """ Return the queried data from the given job-id Parameters ---------- jobId: int The value, if not stored, can be retrieved from :meth:`.get_jobs` pagenumber: int, optional If the data, from the given `job_id` is saved in pages/partitions, then this should be a value in the range from 1 to len(self.list_results(job_id)) Returns ------- dataframe The dataframe holding the queried data from a completed job Examples -------- .. code-block:: console curl -XGET \\ --url "https://api.sql-query.cloud.ibm.com/v2/sql_jobs?instance_crn=<YOUR_SQL_QUERY_CRN>" \\ -H "Accept: application/json" \\ -H "Authorization: Bearer <YOUR_BEARER_TOKEN>" \\ -H "Content-Type: application/json" \"\"\" { "jobs": [ { "job_id": "7ebed7f7-00dc-44a2-acfa-5bdb53889648", "status": "completed", "submit_time": "2018-08-14T08:45:54.012Z", "user_id": "<EMAIL>" }, { "job_id": "ffde4c5a-1cc2-448b-b377-43573818e5d8", "status": "completed", "submit_time": "2018-08-14T08:47:33.350Z", "user_id": "<EMAIL>" } ] } \"\"\" .. code-block:: python response = requests.get( "https://api.sql-query.cloud.ibm.com/v2/sql_jobs/{}?instance_crn={}".format(jobId, self.instance_crn), headers=self.request_headers, ) if response.status_code == 200 or response.status_code == 201: status_response = response.json() https://cloud.ibm.com/apidocs/sql-query#run-an-sql-job """ self.logon() job_details = self.get_job(jobId) job_status = job_details.get("status") if job_status == "running": raise ValueError( "SQL job with jobId {} still running. Come back later.".format(jobId) ) elif job_status != "completed": raise ValueError( "SQL job with jobId {} did not finish successfully. No result available.".format( jobId ) ) if "resultset_location" not in job_details: return None url_parsed = self.analyze_cos_url(job_details["resultset_location"]) result_location = "https://{}/{}?prefix={}".format( url_parsed.endpoint, url_parsed.bucket, url_parsed.prefix ) result_format = job_details["resultset_format"] if result_format not in ["csv", "parquet", "json"]: raise ValueError( "Result object format {} currently not supported by get_result().".format( result_format ) ) response = requests.get(result_location, headers=self.request_headers,) if response.status_code == 200 or response.status_code == 201: ns = {"s3": "http://s3.amazonaws.com/doc/2006-03-01/"} responseBodyXMLroot = ET.fromstring(response.text) bucket_objects = [] # Find result objects with data for contents in responseBodyXMLroot.findall("s3:Contents", ns): key = contents.find("s3:Key", ns) if int(contents.find("s3:Size", ns).text) > 0: bucket_objects.append(key.text) # print("Job result for {} stored at: {}".format(jobId, result_object)) else: raise ValueError( "Result object listing for job {} at {} failed with http code {}".format( jobId, result_location, response.status_code ) ) cos_client = self._get_cos_client(url_parsed.endpoint) # When pagenumber is specified we only retrieve that page. Otherwise we concatenate all pages to one DF: if pagenumber or pagenumber == 0: if " PARTITIONED EVERY " not in job_details["statement"].upper(): raise ValueError( "pagenumber ({}) specified, but the job was not submitted with pagination option.".format( pagenumber ) ) if type(pagenumber) == int and 0 < pagenumber <= len(bucket_objects): if result_format == "csv": body = cos_client.get_object( Bucket=url_parsed.bucket, Key=bucket_objects[pagenumber - 1] )["Body"] if not hasattr(body, "__iter__"): body.__iter__ = types.MethodType(self.__iter__, body) result_df = pd.read_csv(body) elif result_format == "parquet": tmpfile = tempfile.NamedTemporaryFile() tempfilename = tmpfile.name tmpfile.close() cos_client.download_file( Bucket=url_parsed.bucket, Key=bucket_objects[pagenumber - 1], Filename=tempfilename, ) result_df = pd.read_parquet(tempfilename) elif result_format == "json": body = cos_client.get_object( Bucket=url_parsed.bucket, Key=bucket_objects[pagenumber - 1] )["Body"] body = body.read().decode("utf-8") result_df = pd.read_json(body, lines=True) else: raise ValueError("Invalid pagenumner ({}) specified".format(pagenumber)) else: # Loop over result objects and read and concatenate them into result data frame for bucket_object in bucket_objects: if result_format == "csv": body = cos_client.get_object( Bucket=url_parsed.bucket, Key=bucket_object )["Body"] # add missing __iter__ method, so pandas accepts body as file-like object if not hasattr(body, "__iter__"): body.__iter__ = types.MethodType(self.__iter__, body) partition_df = pd.read_csv(body, on_bad_lines='skip') elif result_format == "parquet": tmpfile = tempfile.NamedTemporaryFile() tempfilename = tmpfile.name tmpfile.close() cos_client.download_file( Bucket=url_parsed.bucket, Key=bucket_object, Filename=tempfilename, ) partition_df = pd.read_parquet(tempfilename) elif result_format == "json": body = cos_client.get_object( Bucket=url_parsed.bucket, Key=bucket_object )["Body"] body = body.read().decode("utf-8") partition_df = pd.read_json(body, lines=True) # Add columns from hive style partition naming schema hive_partition_candidates = bucket_object.replace( url_parsed.prefix + "/", "" ).split("/") for hive_partition_candidate in hive_partition_candidates: if ( hive_partition_candidate.count("=") == 1 ): # Hive style folder names contain exactly one '=' column = hive_partition_candidate.split("=") column_name = column[0] column_value = column[1] if ( column_value == "__HIVE_DEFAULT_PARTITION__" ): # Null value partition column_value = np.nan if len(column_name) > 0 and len(column_value) > 0: partition_df[column_name] = column_value if "result_df" not in locals(): result_df = partition_df else: result_df = result_df.append(partition_df, sort=False) if "result_df" not in locals(): return None return result_df def list_results(self, jobId, wait=False): """ NOTE: A single SQL Query can store the queried data in the COS output in multiple objects/partitions When one of those below is used .. code-block:: console [ PARTITIONED BY, PARTITIONED EVERY x ROWS [implicitly used with pagesize=X option] ] Parameters ------------ job_id: str The Job ID wait: bool, default:False If True, wait for the requested `job_id` to complete to get the information Returns ------- None (or nothing) if the function fails DataFrame (4 fields: ObjectURL, Size, Bucket, Object) - each row correspond to the information of one partition Raises ---------- ValueError Notes ------- To know the number of partitions being used, use 'len(self.list_results(job_id))' """ def list_results(jobId): self.logon() job_details = self.get_job(jobId) if job_details["status"] == "running": raise ValueError( "SQL job with jobId {} still running. Come back later." ) elif job_details["status"] != "completed": raise ValueError( "SQL job with jobId {} did not finish successfully. No result available." ) if "resultset_location" not in job_details: return None result_location = job_details["resultset_location"] url_parsed = self.analyze_cos_url(result_location) result_bucket = url_parsed.bucket result_endpoint = url_parsed.endpoint result_objects_df = self.list_cos_objects(job_details["resultset_location"]) result_objects_df["Bucket"] = result_bucket result_objects_df["ObjectURL"] = result_objects_df.apply( lambda x: "cos://%s/%s/%s" % (result_endpoint, result_bucket, x["Object"]), axis=1, ) return result_objects_df job_id = jobId if wait is True: job_running = True while job_running: try: x = list_results(job_id) job_running = False except ValueError as e: if "running" in str(e): pass else: raise e time.sleep(2) else: x = list_results(job_id) return x def rename_exact_result(self, jobId, wait=False): """ A SQL Query can store data into partitioned/paginated multiple objects, or single object. Even with single object, indeed, multiple objects are created, two of them has size 0. (<URL>/_SUCCESS, and <URL>/) beside the ones that hold data (<URL>/<data1>, <URL>/<data2>) This API deletes the two 0-size objects, and keep only the ones that hold data. Parameters ---------- job_id : str A string representation of job_id wait: bool, optional The given `job_id` may not be completed yet, so you have the option to wait for it to completed first. Default is False Returns -------- None Raises ------ ValueError If the job_id is the job in that the result is "PARTITIONED BY" or "pagesize=" or "PARITIONED EVERY x ROWS" is used or the rename_exact_result() has been applied to this job_id. """ self.logon() job_details = self.get_job(jobId) job_status = job_details.get("status") if wait is True: job_status = self.wait_for_job(jobId) if job_status == "running": raise ValueError( "SQL job with jobId {} still running. Come back later.".format(jobId) ) elif job_status != "completed": raise ValueError( "SQL job with jobId {} did not finish successfully. No result available.".format( jobId ) ) if ( "resultset_location" not in job_details or job_details["resultset_location"] is None ): return None url_parsed = self.analyze_cos_url(job_details["resultset_location"]) cos_client = self._get_cos_client(url_parsed.endpoint) result_objects = self.list_results(jobId) if len(result_objects) > 3: raise ValueError( "Renaming partitioned results of jobId {} to single exact result object name not supported.".format( jobId ) ) if ( len(result_objects) == 3 and (int(result_objects.Size[0]) != 0 or int(result_objects.Size[1]) != 0) ) or len(result_objects) < 3: raise ValueError( "Results of job_id {} don't seem to be regular SQL query output.".format( jobId ) ) if len(result_objects) == 1: return # HANDLING [can be 2 rows or 3 rows] - only the last row can be non-zero in size max_row_index = len(result_objects) - 1 pre_row_zeros = True for row in range(0, max_row_index): if int(result_objects.Size[row]) > 0: pre_row_zeros = False break if pre_row_zeros is False: raise ValueError( "Results of job_id {} don't seem to be regular SQL query output.".format( jobId ) ) if len(result_objects) == 3: # basically copy the object[2] to object[0] # then delete object[2] and object[1] copy_source = result_objects.Bucket[2] + "/" + result_objects.Object[2] cos_client.copy_object( Bucket=result_objects.Bucket[0], CopySource=copy_source, Key=result_objects.Object[0], ) cos_client.delete_object( Bucket=result_objects.Bucket[2], Key=result_objects.Object[2] ) cos_client.delete_object( Bucket=result_objects.Bucket[1], Key=result_objects.Object[1] ) else: # len(result_objects) == 2 cos_client.delete_object( Bucket=result_objects.Bucket[0], Key=result_objects.Object[0] ) return def rename_exact_result_joblist(self, job_list, wait=False): """ The bulk mode of `rename_exact_result` method. Parameters ---------- job_list: list A list of job_id wait: bool, optional The same meaning as the one used in :meth:`.rename_exact_result` """ for job_id in job_list: self.rename_exact_result(job_id, wait=wait) def delete_result(self, jobId): """ Delete the COS objects created by a given job-id Returns ------- dataframe A dataframe, with 3 rows, and one field name "Deleted Object" Examples -------- Delete 3 entries in the output COS .. code-block:: console cos://<cos-name>/bucket_name/jobid=<JOB-ID-NUMBER>/ cos://<cos-name>/bucket_name/jobid=<JOB-ID-NUMBER>/_SUCCESS cos://<cos-name>/bucket_name/jobid=<JOB-ID-NUMBER>/[parquet|csv|json] Notes ----- * The last entry holds the real data, and the last word also indicates the data format * 'JOBPREFIX NONE' would avoid having 'jobid=JOB-ID-NAME' in the URL """ self.logon() job_details = self.get_job(jobId) if job_details["status"] == "running": raise ValueError("SQL job with jobId {} still running. Come back later.") elif job_details["status"] != "completed": raise ValueError( "SQL job with jobId {} did not finish successfully. No result available." ) if "resultset_location" not in job_details: return None result_location = job_details["resultset_location"] url_parsed = self.analyze_cos_url(result_location) bucket_name = url_parsed.bucket bucket_objects_df = self.list_cos_objects(result_location)[["Object"]] if bucket_objects_df.empty: print("There are no result objects for the jobid {}".format(jobId)) return bucket_objects_df = bucket_objects_df.rename(columns={"Object": "Key"}) bucket_objects = bucket_objects_df.to_dict("records") cos_client = self._get_cos_client(url_parsed.endpoint) response = cos_client.delete_objects( Bucket=bucket_name, Delete={"Objects": bucket_objects} ) deleted_list_df = pd.DataFrame(columns=["Deleted Object"]) for deleted_object in response["Deleted"]: deleted_list_df = deleted_list_df.append( [{"Deleted Object": deleted_object["Key"]}], ignore_index=True, sort=False, ) return deleted_list_df def get_job(self, jobId): """ Return the details of the job-id Returns ------- dict a dict of job details (see keys below) Raises ---------- ValueError when jobId is not correct HTTPError when RestAPI request fails JSONDEcodeError when RestAPI returns a non-JSON compliant result Notes ----- .. code-block:: python 'job_id', 'status', : "running", "failed", "completed" 'statement': "SELECT * ..." [the content of SQL Query], 'plan_id' , 'submit_time', 'resultset_location', 'rows_returned', 'rows_read' , 'bytes_read' , 'resultset_format': 'csv', 'end_time': '2020-03-06T21:58:26.274Z', 'user_id': '<EMAIL>' Examples -------- .. code-block:: python { "bytes_read": 43058, "end_time": "2020-03-08T03:20:39.131Z", "job_id": "ab3f7567-280b-40c9-87a9-256b846f89db", "plan_id": "ead0f7f5-0c96-40c0-9aae-63c4846d8188", "resultset_format": "parquet", "resultset_location": "cos://s3.us-south.cloud-object-storage.appdomain.cloud/tuan-sql-result/customer_orders/jobid=ab3f7567-280b-40c9-87a9-256b846f89db", "rows_read": 921, "rows_returned": 830, "statement": "SELECT OrderID, c.CustomerID CustomerID, CompanyName, ContactName, ContactTitle, Address, City, Region, PostalCode, Country, Phone, Fax EmployeeID, OrderDate, RequiredDate, ShippedDate, ShipVia, Freight, ShipName, ShipAddress, ShipCity, ShipRegion, ShipPostalCode, ShipCountry FROM cos://us-geo/sql/orders.parquet STORED AS PARQUET o, cos://us-geo/sql/customers.parquet STORED AS PARQUET c WHERE c.CustomerID = o.CustomerID INTO cos://us-south/tuan-sql-result/customer_orders STORED AS PARQUET PARTITIONED BY (ShipCountry, ShipCity)", "status": "completed", "submit_time": "2020-03-08T03:20:00.617Z", "user_id": "<EMAIL>" } """ def get_job(jobId): self.logon() try: response = requests.get( "https://{}/v2/sql_jobs/{}?instance_crn={}".format( self.api_hostname, jobId, self.instance_crn ), headers=self.request_headers, ) except HTTPError as e: if e.response.status_code == 404: raise ValueError("SQL jobId {} unknown".format(jobId)) else: raise e return response.json() if len(jobId) == 0: msg = "Invalid job_id: {}".format(jobId) raise ValueError(msg) job_id = jobId if ( job_id in self.jobs_tracking and self.jobs_tracking[job_id].get("status") != "running" and self.jobs_tracking[job_id].get("status") != "queued" ): result = self.jobs_tracking[job_id] else: try: result = get_job(job_id) except JSONDecodeError as e: print("Error at querying job {}".format(job_id)) raise e self.jobs_tracking[job_id] = result return result def get_jobs(self): """ Return the up-to-30 most recent jobs from the given Cloud API Returns ------- dataframe a pd.DataFrame with fields - total 30 rows, corresponding to the 30 most recent jobs Exceptions ---------- SqlQueryFailException: when a job list can't be queried Examples -------- .. code-block:: console job_id status: "running", "failed", "completed" user_id statement resultset_location submit_time end_time rows_read rows_returned bytes_read error error_message .. code-block:: console job_id status user_id statement resultset_location submit_time end_time ... <long-string> completed <email-here> <query-string> <cos-url-result-location> 2020-02-21T16:19:03.638Z 2020-02-21T16:19:13.691Z rows_read rows_returned bytes_read error error_message 1760 29 41499 None None Notes ----- * get_jobs() is used by `export_job_history`(cos_out_url) which is used to save such data """ self.logon() response = requests.get( "https://{}/v2/sql_jobs?instance_crn={}".format( self.api_hostname, self.instance_crn ), headers=self.request_headers, ) if response.status_code == 200 or response.status_code == 201: job_list = response.json() job_list_df = pd.DataFrame( columns=[ "job_id", "status", "user_id", "statement", "resultset_location", "submit_time", "end_time", "rows_read", "rows_returned", "bytes_read", "objects_skipped", "objects_qualified", "error", "error_message", ] ) for job in job_list["jobs"]: response = requests.get( "https://{}/v2/sql_jobs/{}?instance_crn={}".format( self.api_hostname, job["job_id"], self.instance_crn ), headers=self.request_headers, ) if response.status_code == 200 or response.status_code == 201: job_details = response.json() # None gets converted to integer type in pandas.to_parquet error = "" error_message = "" rows_read = None rows_returned = None bytes_read = None objects_skipped = None objects_qualified = None end_time = "" if "error" in job_details: error = job_details["error"] if "end_time" in job_details: end_time = job_details["end_time"] if "error_message" in job_details: error_message = job_details["error_message"] if "rows_read" in job_details: rows_read = job_details["rows_read"] if "rows_returned" in job_details: rows_returned = job_details["rows_returned"] if "bytes_read" in job_details: bytes_read = job_details["bytes_read"] if "objects_skipped" in job_details: objects_skipped = job_details["objects_skipped"] if "objects_qualified" in job_details: objects_qualified = job_details["objects_qualified"] resultset_loc = np.NaN if "resultset_location" in job_details: resultset_loc = job_details["resultset_location"] job_list_df = job_list_df.append( [ { "job_id": job["job_id"], "status": job_details["status"], "user_id": job_details["user_id"], "statement": job_details["statement"], "resultset_location": resultset_loc, "submit_time": job_details["submit_time"], "end_time": end_time, "rows_read": rows_read, "rows_returned": rows_returned, "bytes_read": bytes_read, "objects_skipped": objects_skipped, "objects_qualified": objects_qualified, "error": error, "error_message": error_message, } ], ignore_index=True, sort=False, ) else: print( "Job details retrieval for jobId {} failed with http code {}".format( job["job_id"], response.status_code ) ) break else: msg = "Job list retrieval failed with http code {}".format( response.status_code ) raise SqlQueryFailException(msg) return job_list_df @validate_job_status def get_jobs_with_status(self, job_id_list, status): """ return the list of job_id, among those provided, that have the given status Parameters ---------- job_id_list: list List of job_id to check status : str "completed", "running", or "failed" Returns -------- list: List of job ids """ results = [] for job_id in job_id_list: response = self.get_job(job_id) if response["status"] == status: results.append(job_id) return results @validate_job_status def get_jobs_count_with_status(self, status): """ return the number of jobs in the SQL Query server for the given `status` It has the limitation as described in :meth:`.get_jobs` """ jobs = self.get_jobs() num_jobs = len(jobs[jobs["status"] == status]) return num_jobs def get_number_running_jobs(self): """ return the number of running jobs in the SQL Query server""" return self.get_jobs_count_with_status("running") def execute_sql(self, sql_stmt, pagesize=None, get_result=False): """ Extend the behavior of :meth:`.run_sql`. It is a blocking call that waits for the job to finish (unlike :meth:`.submit_sql`), but it has the following features: 1. returning of data (Pandas dataframe) is optional (controlled by `get_result` parameter): to help avoiding Python runtime memory overload. This is also useful when you run SQL statements such as DDLs that don't produce results at all. 2. returns a namedtuple, in that result.data is the one returned by `run_sql`, while result.job_id is the one returned by `submit_sql` 3. raise an exception for a failed job Parameters -------------- sql_stmt: str the SQL statement to run pagesize: int, optional an integer indicating the number of rows for each partition/page [using PARTITIONED EVERY <pagesize> ROWS syntax] get_result: bool, optional (default=False) When set it will return only the job_id, but still wait for the job's completion. Later, you can get the data using :meth:`.get_result` (job_id, pagenumber) Returns ------- namedtuple [`data`, `job_id`] `get_result` = True, then behavior like :meth:`.run_sql` which materializes the returned data as type pd.DataFrame in memory. The default behavior is opposite, to avoid unintended overload of memory. Raises ------ KeyError when information about a failed job is missing (job_status, job_id, error, error_message) SqlQueryFailException when the sql query fails, e.g. time out on the server side """ Container = namedtuple("RunSql", ["data", "job_id"]) job_id = self.submit_sql(sql_stmt, pagesize=pagesize) data = None job_status = self.wait_for_job(job_id) logger.debug("Job " + job_id + " terminated with status: " + job_status) if job_status == "completed": if get_result is True: data = self.get_result(job_id) elif job_status == "unknown": job_status = self.wait_for_job(job_id) if job_status == "failed": details = self.get_job(job_id) try: error_message = "{status}: SQL job {job_id} failed while executing with error {error}. Detailed message: {msg}".format( status=job_status, job_id=job_id, error=details["error"], msg=details["error_message"], ) raise SqlQueryFailException(error_message) except KeyError as e: pprint.pprint(details) raise e mycontainer = Container(data, job_id) return mycontainer def run_sql(self, sql_text, pagesize=None): """ Submits a SQL job, waits for the job to finish (unlike :meth:`.submit_sql`) and return the result as Pandas DataFrame. Parameters -------------- sql_text: str the SQL statement to run pagesize: int, optional an integer indicating the number of rows for each partition/page [using PARTITIONED EVERY <pagesize> ROWS syntax] Returns ------- pd.DataFrame with the query results. Raises ------ CosUrlNotFoundException the COS URL is not valid CosUrlInaccessibleException the COS URL is inaccessible - no access granted to the given API key SqlQueryInvalidFormatException the format provided to COS URL is incorrect KeyError the returned error message does not have job_id, error, or error_message Exception unexpected exception """ self.logon() job_id = self.submit_sql(sql_text, pagesize) job_status = self.wait_for_job(job_id) if job_status == "failed": details = self.get_job(job_id) try: error_message = "SQL job {job_id} failed while executing \n{sql_text}\nwith error {error}. Detailed message: {msg}".format( job_id=job_id, sql_text=sql_text, error=details["error"], msg=details["error_message"], ) cos_in_url_error_msg = "Specify a valid Cloud Object Storage location" cos_out_url_error_msg = ( "Specify a valid Cloud Object Storage bucket location" ) cos_url_not_accessible_error_msg = "Accessing the specified Cloud Object Storage location is forbidden." cos_invalid_format_error_msg = "The input data doesn't have a correct" if cos_in_url_error_msg in error_message: raise CosUrlNotFoundException(error_message) elif cos_out_url_error_msg in error_message: raise CosUrlNotFoundException(error_message) elif cos_url_not_accessible_error_msg in error_message: raise CosUrlInaccessibleException(error_message) elif cos_invalid_format_error_msg in error_message: raise SqlQueryInvalidFormatException(error_message) else: raise Exception(error_message) except KeyError as e: pprint.pprint(details) raise e return self.get_result(job_id) def run(self, pagesize=None, get_result=False): """ run the internal SQL statement provided by SQLMagic using :meth:`.execute_sql` """ self.format_() return self.execute_sql( self._sql_stmt, pagesize=pagesize, get_result=get_result ) def process_failed_jobs_until_all_completed(self, job_id_list): """ re-send those that are failed - due to the time-out mechanism of SQL Query server Here, if job_time < 40 minutes, then we re-send. """ complete_all = False while complete_all is False: complete_all = True for index, job_id in enumerate(job_id_list): job_result = self.get_job(job_id) if job_result["status"] == "failed": delta = dateutil.parser.parse( job_result["end_time"] ) - dateutil.parser.parse(job_result["submit_time"]) job_time = delta.total_seconds() if job_time < 2400: # 40 minutes new_job_id = self.submit_sql(job_result["statement"]) job_id_list[index] = new_job_id complete_all = False return job_id_list def sql_ui_link(self): """ both print out and also return the string containing SQL Query URL""" self.logon() if sys.version_info >= (3, 0): result = "https://{}/sqlquery/?instance_crn={}".format( self.ui_hostname, urllib.parse.unquote(self.instance_crn) ) else: result = "https://{}/sqlquery/?instance_crn={}".format( self.ui_hostname, urllib.unquote(self.instance_crn).decode("utf8") ) print(result) return result def export_job_history( self, cos_url=None, export_file_prefix="job_export_", export_file_suffix=".parquet", ): """ Export the most recent jobs to COS URL Parameters ---------- cos_url : str A COS URL with prefix, i.e. cos://<cos-name>/<bucket>/<prefix>, where the data will be stored Raises ------ ValueError if COS URL is invalid """ if cos_url: # Default export location is target COS URL set at __init__ # But we'll overwrite that with the provided export URL if not self.is_valid_cos_url(cos_url): msg = "Not a valid COS URL" raise ValueError(msg) self.export_cos_url = cos_url elif not self.export_cos_url: raise ValueError("No configured export COS URL.") if not self.export_cos_url.endswith("/"): self.export_cos_url += "/" url_parsed = self.analyze_cos_url(self.export_cos_url) job_history_df = ( self.get_jobs() ) # Retrieve current job history (most recent 30 jobs) if sys.version_info < (3, 0): job_history_df["error"] = job_history_df["error"].astype(unicode) job_history_df["error_message"] = job_history_df["error_message"].astype( unicode ) terminated_job_history_df = job_history_df[ job_history_df["status"].isin(["completed", "failed"]) ] # Only export terminated jobs newest_job_end_time = terminated_job_history_df.loc[ pd.to_datetime(terminated_job_history_df["end_time"]).idxmax() ].end_time # List all existing objects in export location and identify latest exported job timestamp: cos_client = self._get_cos_client(url_parsed.endpoint) paginator = cos_client.get_paginator("list_objects") page_iterator = paginator.paginate( Bucket=url_parsed.bucket, Prefix=url_parsed.prefix ) newest_exported_job_end_time = "" expected_object_prefix = url_parsed.prefix + export_file_prefix for page in page_iterator: if "Contents" in page: for key in page["Contents"]: object_name = key["Key"] if not (object_name.startswith(expected_object_prefix)): continue prefix_end_index = len(expected_object_prefix) suffix_index = object_name.find(export_file_suffix) if not (prefix_end_index < suffix_index): continue job_end_time = object_name[prefix_end_index:suffix_index] if job_end_time > newest_exported_job_end_time: newest_exported_job_end_time = job_end_time # Export all new jobs if there are some: if newest_exported_job_end_time < newest_job_end_time: import pyarrow from packaging import version tmpfile = tempfile.NamedTemporaryFile() tempfilename = tmpfile.name new_jobs_df = terminated_job_history_df[ terminated_job_history_df["end_time"] > newest_exported_job_end_time ] if version.parse(pd.__version__) >= version.parse("1.0.0"): new_jobs_df.to_parquet( engine="pyarrow", path=tempfilename, compression="snappy", index=False, ) else: new_jobs_df.to_parquet( engine="pyarrow", fname=tempfilename, compression="snappy", index=False, ) export_object = ( url_parsed.prefix + export_file_prefix + newest_job_end_time + export_file_suffix ) cos_client.upload_file( Bucket=url_parsed.bucket, Filename=tempfilename, Key=export_object ) print("Exported {} new jobs".format(new_jobs_df["job_id"].count())) tmpfile.close() else: print("No new jobs to export") def get_schema_data(self, cos_url, type="json", dry_run=False): """ Return the schema of COS URL Parameters ---------- cos_url : str The COS URL where data is stored type : str, optional The format type of the data, default is 'json' Use from ['json', 'csv', 'parquet'] with case-insensitive dry_run: bool, optional This option, once selected as True, returns the internally generated SQL statement, and no job is queried. Returns ------- DataFrame 3 columns: name (object), nullable (bool), type (object) Raises ------- ValueError in either scenarios: (1) target COS URL is not set, (2) invalid type, (3) invalid COS URL """ supported_types = ["JSON", "CSV", "PARQUET"] if self.target_cos_url is None: msg = "Need to pass target COS URL when creating SQL Client object" raise ValueError(msg) if type.upper() not in supported_types: msg = "Expected 'type' value: " + str(supported_types) raise ValueError(msg) if not self.is_valid_cos_url(cos_url): msg = "Not a valid COS URL" raise ValueError(msg) sql_stmt = """ SELECT * FROM DESCRIBE({cos_in} STORED AS {type}) INTO {cos_out} STORED AS JSON """.format( cos_in=cos_url, type=type.upper(), cos_out=self.target_cos_url ) if dry_run: print(sql_stmt) return None else: df = self.run_sql(sql_stmt) if (df.name[0] == "_corrupt_record") or ( "�]�]L�" in df.name[0] and "PAR1" in df.name[0] ): msg = ( "ERROR: Revise 'type' value, underlying data format maybe different" ) raise ValueError(msg) return df def analyze(self, job_id, print_msg=True): """Provides some insights about the data layout from the current SQL statement Parameters ------------- job_id : str The job ID print_msg: bool, optional Default is True: print out the hints to the console .. todo:: 1. new sql only when max_obj_size > 300MB 2. check if STORED AS is used, if not suggested adding to sql with PARQUET or JSON 3. add PARITIONED ... not at the end, but right after STORED AS (which can be missing in original SQL) """ def INTO_is_present(sql_text): """ check if INTO keyword is present in the SQL query""" return (" INTO " in sql_text.upper()) or ("\nINTO " in sql_text.upper()) BestPracticeContainer = namedtuple("SqlBestPractice", ["size", "max_objs"]) best_practice = BestPracticeContainer("128 MB", 50) result = self.get_job(job_id) # make use of 'resultset_location' and 'resultset_format' if not INTO_is_present(result["statement"]): cos_out = result["resultset_location"] if "jobid=" in result["resultset_location"]: cos_out = cos_out[: cos_out.rfind("jobid=")] result["statement"] += ( " INTO " + cos_out + " STORED AS " + result["resultset_format"] ) if result["status"] != "completed": msg = "Job {job_id} is {status} - no more insights".format( job_id=job_id, status=result["status"] ) return msg cos_url = result["resultset_location"] if not cos_url: msg = "Job {job_id} does not return anything - no more insights".format( job_id=job_id ) return msg cos_result = self.get_cos_summary(cos_url) def get_total_objects(): # total_objects = cos_result['total_objects'] #not exact r = self.list_results(job_id) seriesObj = r.apply(lambda x: True if int(x["Size"]) > 0 else False, axis=1) return seriesObj.to_list().count(True) total_objects = get_total_objects() def get_size_in_MB(size_info): num, unit = size_info.split(" ") mapping = {"TB": 1048576, "GB": 1024, "MB": 1} if unit in mapping: size_MB = float(num) * mapping[unit] else: size_MB = 1.0 return size_MB largest_size_MB = get_size_in_MB(cos_result["largest_object_size"]) if largest_size_MB < float(best_practice.size.split(" ")[0]) * 2: msg = "Job {job_id} looks fine - no more insights".format(job_id=job_id) return msg total_volume_MB = get_size_in_MB(cos_result["total_volume"]) SqlContainer = namedtuple( "SqlStatus", ["job_id", "total_data_objects", "total_volume", "max_object_size"], ) query = SqlContainer(job_id, total_objects, total_volume_MB, largest_size_MB) mappings = { "job_id": job_id, "total_objects": total_objects, "total_volume_MB": total_volume_MB, } msg_01 = "Job {job_id} has {total_objects} object{s}, with {total_volume_MB} MB in total.".format( **mappings, s="s" if mappings["total_objects"] > 1 else "" ) if mappings["total_objects"] > 1: msg_01 = msg_01 + " Current object size is ~ {size} MB".format( size=mappings["total_volume_MB"] / mappings["total_objects"] ) mappings = {"size": best_practice.size} msg_02 = "Best practices: object sizes ~ {size}".format(**mappings) mappings = { "num_objs": min( best_practice.max_objs, int(query.total_volume / float(best_practice.size.split(" ")[0])), ) } msg_03 = "Current SQL:\n {sql}\n".format(sql=result["statement"]) def revise_storage(sql_stmt, storage="parquet"): url_storage = re.search(r"INTO (cos)://[^\s]* STORED AS", sql_stmt) if url_storage: loc = url_storage.span(0)[1] pre = sql_stmt[: loc + 1] post = sql_stmt[loc + 1 :] detected_storage = re.search(r"^[^\s]*", post).group(0) if storage.upper() != detected_storage: post = post.replace(detected_storage, storage.upper(), 1) sql_stmt = pre + post else: url = re.search(r"INTO (cos)://[^\s]*", sql_stmt) if url: loc = url.span(0)[1] sql_stmt = ( sql_stmt[:loc] + " STORED AS " + storage.upper() + sql_stmt[loc + 1 :] ) else: # no explicit INTO msg = "Error: needs INTO <cos-url> clause" raise Exception(msg) return sql_stmt def msg_partition_into(): msg_sub = [None] * 2 msg_sub[ 0 ] = "Consider using: PARTITIONED INTO {num_objs} OBJECTS/BUCKETS".format( **mappings ) new_sql = result["statement"] if "PARTITION" not in new_sql: new_sql = format_sql(revise_storage(new_sql, "parquet")) import re url = re.search( r"INTO (cos)://[^\s]*[\s]+STORED[\s]+AS[\s]+PARQUET", new_sql ) loc = url.span(0)[1] new_sql = ( new_sql[:loc] + " PARTITIONED INTO {num_objs} OBJECTS".format(**mappings) + new_sql[loc + 1 :] ) result["rows_returned"] msg_sub[1] = "Suggested SQL:\n {sql}\n".format(sql=new_sql) return msg_sub def msg_partition_every(): msg_05 = [None] * 2 num_rows = int( float(result["rows_returned"]) / (query.total_volume / float(best_practice.size.split(" ")[0])) ) msg_05[0] = "Consider using: PARTITIONED EVERY {num_rows} ROWS".format( **mappings, num_rows=num_rows ) new_sql = result["statement"] if "PARITION" not in new_sql: # new_sql = new_sql + " PARTITIONED EVERY {num_rows} ROWS".format( # **mappings, num_rows=num_rows) new_sql = format_sql(revise_storage(new_sql, "parquet")) url = re.search( r"INTO (cos)://[^\s]*[\s]+STORED[\s]+AS[\s]+PARQUET", new_sql ) loc = url.span(0)[1] new_sql = ( new_sql[:loc] + " PARTITIONED EVERY {num_rows} ROWS".format( **mappings, num_rows=num_rows ) + new_sql[loc + 1 :] ) result["rows_returned"] msg_05[1] = "Suggested SQL:\n {sql}\n".format(sql=new_sql) return msg_05 msg_04 = msg_partition_into() msg_05 = msg_partition_every() my_list = [msg_01, msg_02, msg_03] my_list.extend(msg_04) my_list.extend(msg_05) msg = os.linesep.join(my_list) if print_msg: print(msg) return msg
[ "logging.getLogger", "pandas.read_parquet", "pandas.read_csv", "exceptions.SqlQueryInvalidFormatException", "exceptions.SqlQueryFailException", "time.sleep", "backoff.on_exception", "cos.COSClient.__init__", "inspect.getcallargs", "types.MethodType", "utilities.rename_keys", "pprint.pprint", ...
[((2224, 2251), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (2241, 2251), False, 'import logging\n'), ((2366, 2374), 'functools.wraps', 'wraps', (['f'], {}), '(f)\n', (2371, 2374), False, 'from functools import wraps\n'), ((3003, 3011), 'functools.wraps', 'wraps', (['f'], {}), '(f)\n', (3008, 3011), False, 'from functools import wraps\n'), ((2453, 2492), 'inspect.getcallargs', 'inspect.getcallargs', (['f', '*args'], {}), '(f, *args, **kwargs)\n', (2472, 2492), False, 'import inspect\n'), ((3090, 3129), 'inspect.getcallargs', 'inspect.getcallargs', (['f', '*args'], {}), '(f, *args, **kwargs)\n', (3109, 3129), False, 'import inspect\n'), ((3300, 3320), 'sql_magic.format_sql', 'format_sql', (['sql_stmt'], {}), '(sql_stmt)\n', (3310, 3320), False, 'from sql_magic import SQLMagic, format_sql, print_sql\n'), ((9981, 10160), 'cos.COSClient.__init__', 'COSClient.__init__', (['self'], {'cloud_apikey': 'api_key', 'cos_url': 'target_cos_url', 'client_info': 'client_info', 'iam_max_tries': 'iam_max_tries', 'thread_safe': 'thread_safe', 'staging': 'staging_env'}), '(self, cloud_apikey=api_key, cos_url=target_cos_url,\n client_info=client_info, iam_max_tries=iam_max_tries, thread_safe=\n thread_safe, staging=staging_env)\n', (9999, 10160), False, 'from cos import COSClient\n'), ((10255, 10278), 'sql_magic.SQLMagic.__init__', 'SQLMagic.__init__', (['self'], {}), '(self)\n', (10272, 10278), False, 'from sql_magic import SQLMagic, format_sql, print_sql\n'), ((11648, 11681), 'cos.COSClient.configure', 'COSClient.configure', (['self', 'apikey'], {}), '(self, apikey)\n', (11667, 11681), False, 'from cos import COSClient\n'), ((12877, 12927), 'catalog_table.HiveMetastore.configure', 'HiveMetastore.configure', (['self', 'self.target_cos_url'], {}), '(self, self.target_cos_url)\n', (12900, 12927), False, 'from catalog_table import HiveMetastore\n'), ((28812, 28871), 'requests.get', 'requests.get', (['result_location'], {'headers': 'self.request_headers'}), '(result_location, headers=self.request_headers)\n', (28824, 28871), False, 'import requests\n'), ((43382, 43422), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['Deleted Object']"}), "(columns=['Deleted Object'])\n", (43394, 43422), True, 'import pandas as pd\n'), ((55954, 55994), 'collections.namedtuple', 'namedtuple', (['"""RunSql"""', "['data', 'job_id']"], {}), "('RunSql', ['data', 'job_id'])\n", (55964, 55994), False, 'from collections import namedtuple\n'), ((68773, 68824), 'collections.namedtuple', 'namedtuple', (['"""SqlBestPractice"""', "['size', 'max_objs']"], {}), "('SqlBestPractice', ['size', 'max_objs'])\n", (68783, 68824), False, 'from collections import namedtuple\n'), ((70816, 70912), 'collections.namedtuple', 'namedtuple', (['"""SqlStatus"""', "['job_id', 'total_data_objects', 'total_volume', 'max_object_size']"], {}), "('SqlStatus', ['job_id', 'total_data_objects', 'total_volume',\n 'max_object_size'])\n", (70826, 70912), False, 'from collections import namedtuple\n'), ((75449, 75473), 'os.linesep.join', 'os.linesep.join', (['my_list'], {}), '(my_list)\n', (75464, 75473), False, 'import os\n'), ((10330, 10374), 'catalog_table.HiveMetastore.__init__', 'HiveMetastore.__init__', (['self', 'target_cos_url'], {}), '(self, target_cos_url)\n', (10352, 10374), False, 'from catalog_table import HiveMetastore\n'), ((20870, 20980), 'backoff.on_exception', 'backoff.on_exception', (['backoff.expo', '(RateLimitedException, InternalError502Exception)'], {'max_tries': 'max_tries'}), '(backoff.expo, (RateLimitedException,\n InternalError502Exception), max_tries=max_tries)\n', (20890, 20980), False, 'import backoff\n'), ((29046, 29074), 'xml.etree.ElementTree.fromstring', 'ET.fromstring', (['response.text'], {}), '(response.text)\n', (29059, 29074), True, 'import xml.etree.ElementTree as ET\n'), ((48852, 49089), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['job_id', 'status', 'user_id', 'statement', 'resultset_location',\n 'submit_time', 'end_time', 'rows_read', 'rows_returned', 'bytes_read',\n 'objects_skipped', 'objects_qualified', 'error', 'error_message']"}), "(columns=['job_id', 'status', 'user_id', 'statement',\n 'resultset_location', 'submit_time', 'end_time', 'rows_read',\n 'rows_returned', 'bytes_read', 'objects_skipped', 'objects_qualified',\n 'error', 'error_message'])\n", (48864, 49089), True, 'import pandas as pd\n'), ((52963, 52989), 'exceptions.SqlQueryFailException', 'SqlQueryFailException', (['msg'], {}), '(msg)\n', (52984, 52989), False, 'from exceptions import RateLimitedException, CosUrlNotFoundException, CosUrlInaccessibleException, SqlQueryCrnInvalidFormatException, SqlQueryInvalidPlanException, SqlQueryFailException, SqlQueryInvalidFormatException, InternalError502Exception\n'), ((64734, 64763), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', ([], {}), '()\n', (64761, 64763), False, 'import tempfile\n'), ((72062, 72115), 're.search', 're.search', (['"""INTO (cos)://[^\\\\s]* STORED AS"""', 'sql_stmt'], {}), "('INTO (cos)://[^\\\\s]* STORED AS', sql_stmt)\n", (72071, 72115), False, 'import re\n'), ((13778, 13791), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (13788, 13791), False, 'import time\n'), ((14244, 14257), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (14254, 14257), False, 'import time\n'), ((25451, 25473), 'time.sleep', 'time.sleep', (['sleep_time'], {}), '(sleep_time)\n', (25461, 25473), False, 'import time\n'), ((36894, 36907), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (36904, 36907), False, 'import time\n'), ((56855, 56891), 'exceptions.SqlQueryFailException', 'SqlQueryFailException', (['error_message'], {}), '(error_message)\n', (56876, 56891), False, 'from exceptions import RateLimitedException, CosUrlNotFoundException, CosUrlInaccessibleException, SqlQueryCrnInvalidFormatException, SqlQueryInvalidPlanException, SqlQueryFailException, SqlQueryInvalidFormatException, InternalError502Exception\n'), ((61330, 61369), 'urllib.parse.unquote', 'urllib.parse.unquote', (['self.instance_crn'], {}), '(self.instance_crn)\n', (61350, 61369), False, 'import urllib\n'), ((64971, 65000), 'packaging.version.parse', 'version.parse', (['pd.__version__'], {}), '(pd.__version__)\n', (64984, 65000), False, 'from packaging import version\n'), ((65004, 65026), 'packaging.version.parse', 'version.parse', (['"""1.0.0"""'], {}), "('1.0.0')\n", (65017, 65026), False, 'from packaging import version\n'), ((72558, 72601), 're.search', 're.search', (['"""INTO (cos)://[^\\\\s]*"""', 'sql_stmt'], {}), "('INTO (cos)://[^\\\\s]*', sql_stmt)\n", (72567, 72601), False, 'import re\n'), ((73525, 73600), 're.search', 're.search', (['"""INTO (cos)://[^\\\\s]*[\\\\s]+STORED[\\\\s]+AS[\\\\s]+PARQUET"""', 'new_sql'], {}), "('INTO (cos)://[^\\\\s]*[\\\\s]+STORED[\\\\s]+AS[\\\\s]+PARQUET', new_sql)\n", (73534, 73600), False, 'import re\n'), ((74707, 74782), 're.search', 're.search', (['"""INTO (cos)://[^\\\\s]*[\\\\s]+STORED[\\\\s]+AS[\\\\s]+PARQUET"""', 'new_sql'], {}), "('INTO (cos)://[^\\\\s]*[\\\\s]+STORED[\\\\s]+AS[\\\\s]+PARQUET', new_sql)\n", (74716, 74782), False, 'import re\n'), ((3762, 3777), 'sql_magic.format_sql', 'format_sql', (['key'], {}), '(key)\n', (3772, 3777), False, 'from sql_magic import SQLMagic, format_sql, print_sql\n'), ((3931, 3979), 'utilities.rename_keys', 'rename_keys', (['self.project_lib.data', 'keys_mapping'], {}), '(self.project_lib.data, keys_mapping)\n', (3942, 3979), False, 'from utilities import rename_keys\n'), ((5597, 5617), 'json.load', 'json.load', (['json_data'], {}), '(json_data)\n', (5606, 5617), False, 'import json\n'), ((15502, 15550), 'exceptions.SqlQueryCrnInvalidFormatException', 'SqlQueryCrnInvalidFormatException', (['error_message'], {}), '(error_message)\n', (15535, 15550), False, 'from exceptions import RateLimitedException, CosUrlNotFoundException, CosUrlInaccessibleException, SqlQueryCrnInvalidFormatException, SqlQueryInvalidPlanException, SqlQueryFailException, SqlQueryInvalidFormatException, InternalError502Exception\n'), ((30683, 30700), 'pandas.read_csv', 'pd.read_csv', (['body'], {}), '(body)\n', (30694, 30700), True, 'import pandas as pd\n'), ((32227, 32265), 'pandas.read_csv', 'pd.read_csv', (['body'], {'on_bad_lines': '"""skip"""'}), "(body, on_bad_lines='skip')\n", (32238, 32265), True, 'import pandas as pd\n'), ((56942, 56964), 'pprint.pprint', 'pprint.pprint', (['details'], {}), '(details)\n', (56955, 56964), False, 'import pprint\n'), ((59128, 59166), 'exceptions.CosUrlNotFoundException', 'CosUrlNotFoundException', (['error_message'], {}), '(error_message)\n', (59151, 59166), False, 'from exceptions import RateLimitedException, CosUrlNotFoundException, CosUrlInaccessibleException, SqlQueryCrnInvalidFormatException, SqlQueryInvalidPlanException, SqlQueryFailException, SqlQueryInvalidFormatException, InternalError502Exception\n'), ((59697, 59719), 'pprint.pprint', 'pprint.pprint', (['details'], {}), '(details)\n', (59710, 59719), False, 'import pprint\n'), ((7463, 7493), 'json.dump', 'json.dump', (['self._data', 'outfile'], {}), '(self._data, outfile)\n', (7472, 7493), False, 'import json\n'), ((8105, 8135), 'json.dump', 'json.dump', (['self._data', 'outfile'], {}), '(self._data, outfile)\n', (8114, 8135), False, 'import json\n'), ((15130, 15148), 'pprint.pformat', 'pformat', (['json_data'], {}), '(json_data)\n', (15137, 15148), False, 'from pprint import pformat\n'), ((15784, 15827), 'exceptions.SqlQueryInvalidPlanException', 'SqlQueryInvalidPlanException', (['error_message'], {}), '(error_message)\n', (15812, 15827), False, 'from exceptions import RateLimitedException, CosUrlNotFoundException, CosUrlInaccessibleException, SqlQueryCrnInvalidFormatException, SqlQueryInvalidPlanException, SqlQueryFailException, SqlQueryInvalidFormatException, InternalError502Exception\n'), ((30613, 30650), 'types.MethodType', 'types.MethodType', (['self.__iter__', 'body'], {}), '(self.__iter__, body)\n', (30629, 30650), False, 'import types\n'), ((30780, 30809), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', ([], {}), '()\n', (30807, 30809), False, 'import tempfile\n'), ((31151, 31180), 'pandas.read_parquet', 'pd.read_parquet', (['tempfilename'], {}), '(tempfilename)\n', (31166, 31180), True, 'import pandas as pd\n'), ((32153, 32190), 'types.MethodType', 'types.MethodType', (['self.__iter__', 'body'], {}), '(self.__iter__, body)\n', (32169, 32190), False, 'import types\n'), ((32346, 32375), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', ([], {}), '()\n', (32373, 32375), False, 'import tempfile\n'), ((32704, 32733), 'pandas.read_parquet', 'pd.read_parquet', (['tempfilename'], {}), '(tempfilename)\n', (32719, 32733), True, 'import pandas as pd\n'), ((59254, 59292), 'exceptions.CosUrlNotFoundException', 'CosUrlNotFoundException', (['error_message'], {}), '(error_message)\n', (59277, 59292), False, 'from exceptions import RateLimitedException, CosUrlNotFoundException, CosUrlInaccessibleException, SqlQueryCrnInvalidFormatException, SqlQueryInvalidPlanException, SqlQueryFailException, SqlQueryInvalidFormatException, InternalError502Exception\n'), ((61500, 61533), 'urllib.unquote', 'urllib.unquote', (['self.instance_crn'], {}), '(self.instance_crn)\n', (61514, 61533), False, 'import urllib\n'), ((63274, 63327), 'pandas.to_datetime', 'pd.to_datetime', (["terminated_job_history_df['end_time']"], {}), "(terminated_job_history_df['end_time'])\n", (63288, 63327), True, 'import pandas as pd\n'), ((72309, 72336), 're.search', 're.search', (['"""^[^\\\\s]*"""', 'post'], {}), "('^[^\\\\s]*', post)\n", (72318, 72336), False, 'import re\n'), ((31479, 31509), 'pandas.read_json', 'pd.read_json', (['body'], {'lines': '(True)'}), '(body, lines=True)\n', (31491, 31509), True, 'import pandas as pd\n'), ((33020, 33050), 'pandas.read_json', 'pd.read_json', (['body'], {'lines': '(True)'}), '(body, lines=True)\n', (33032, 33050), True, 'import pandas as pd\n'), ((59391, 59433), 'exceptions.CosUrlInaccessibleException', 'CosUrlInaccessibleException', (['error_message'], {}), '(error_message)\n', (59418, 59433), False, 'from exceptions import RateLimitedException, CosUrlNotFoundException, CosUrlInaccessibleException, SqlQueryCrnInvalidFormatException, SqlQueryInvalidPlanException, SqlQueryFailException, SqlQueryInvalidFormatException, InternalError502Exception\n'), ((4864, 4903), 'pprint.pprint', 'pprint.pprint', (['job_id', '"""\n"""', 'job_result'], {}), "(job_id, '\\n', job_result)\n", (4877, 4903), False, 'import pprint\n'), ((6711, 6741), 'json.dump', 'json.dump', (['self._data', 'outfile'], {}), '(self._data, outfile)\n', (6720, 6741), False, 'import json\n'), ((59528, 59573), 'exceptions.SqlQueryInvalidFormatException', 'SqlQueryInvalidFormatException', (['error_message'], {}), '(error_message)\n', (59558, 59573), False, 'from exceptions import RateLimitedException, CosUrlNotFoundException, CosUrlInaccessibleException, SqlQueryCrnInvalidFormatException, SqlQueryInvalidPlanException, SqlQueryFailException, SqlQueryInvalidFormatException, InternalError502Exception\n'), ((6433, 6458), 'pprint.pprint', 'pprint.pprint', (['job_result'], {}), '(job_result)\n', (6446, 6458), False, 'import pprint\n')]
"""Extract the language known by the registered users in Wikipedia and some statistics about them""" import json import more_itertools import mwxml import datetime from typing import Iterable, Iterator, Mapping from backports.datetime_fromisoformat import MonkeyPatch from .. import extractors, languages, utils # Polyfiller for retrocompatibiliy with Python3.5 MonkeyPatch.patch_fromisoformat() # REVISION AND PAGE CLASSES class Revision: """Class which represent a revision of the user page""" def __init__(self, id: str, user: mwxml.Revision.User, timestamp: str, languages: Iterable[extractors.languages.LanguageLevel], num_langs_known: int): self.id = id # revision id self.user = user # revision user self.timestamp = timestamp # revision timestamp self.languages = languages # set of the languages associated with the user in that revision of his or her user page self.num_langs_known = num_langs_known # number of language known by the user def to_dict(self) -> str: """Converts the object instance into a dictionary""" obj = dict() obj['id'] = self.id obj['user_id'] = self.user.id obj['user_name'] = self.user.text obj['timestamp'] = self.timestamp obj['num_languages_declared'] = self.num_langs_known obj['languages'] = list() for lang in self.languages: obj['languages'].append(lang.to_dict()) return obj class Page: """Class which represent a page containing a list of revisions""" def __init__(self, id: str, namespace: str, title: str, revisions: Iterator[Revision], num_langs_known: int): self.id = id # page id self.namespace = namespace # page namespace self.title = title # page title self.revisions = revisions # list of revisions self.num_langs_known = num_langs_known # number of languages known def to_dict(self) -> Mapping: """Converts the object instance into a dictionary""" obj = dict() obj['id'] = self.id obj['namespace'] = self.namespace obj['title'] = self.title obj['revisions'] = list() for rev in self.revisions: obj['revisions'].append(rev.to_dict()) return obj def count_languages_occurences(language_knowledge_levels_list: Iterable[extractors.languages.LanguageLevel]) -> int: """Count the unique names of the languages stored in language_knowledge_levels_list list""" langs_set = set() counter = 0 for lang_knowledge in language_knowledge_levels_list: if not lang_knowledge.lang in langs_set: counter += 1 langs_set.add(lang_knowledge.lang) return counter def extract_revisions( mw_page: mwxml.Page, stats: Mapping, only_last_revision: bool, only_revisions_with_languages: bool) -> Iterator[Revision]: """Extracts the known languages within a user page.""" revisions = more_itertools.peekable(mw_page) # Newest revisions, useful only if the only_last_revision flag is set equal to true newest_revision = None for mw_revision in revisions: utils.dot() # check if it's last revision is_last_revision = not utils.has_next(revisions) # remove html comments text = utils.remove_comments(mw_revision.text or '') # It extracts a list of LanguageLevel instances, composed of (languages and it's level) languages = [lang for lang, _ in extractors.languages.language_knowledge(text)] # number of languages that the user said they know num_langs_known = count_languages_occurences(languages) # Update stats if not only_last_revision or (only_last_revision and is_last_revision): for l in languages: if l.lang in stats['users']['languages']: # not to exceed the indices of the list if 0 <= l.level < len(stats['users']['languages'][l.lang]['knowledge']): stats['users']['languages'][l.lang]['knowledge'][l.level] += 1 else: stats['users']['languages'][l.lang] = dict() stats['users']['languages'][l.lang]['knowledge'] = [0] * (extractors.languages.LanguageLevel.MOTHER_TONGUE_LEVEL + 1) stats['users']['languages'][l.lang]['knowledge'][l.level] = 1 # Build the revision rev = Revision( id=mw_revision.id, user=mw_revision.user, timestamp=mw_revision.timestamp.to_json(), languages=languages, num_langs_known=num_langs_known ) # Check the oldest revisions possible if not newest_revision: newest_revision = rev else: newest_date = datetime.datetime.fromisoformat(newest_revision.timestamp.replace('Z', '+00:00')) current_date = datetime.datetime.fromisoformat(mw_revision.timestamp.to_json().replace('Z', '+00:00')) # change the revision if the current one is newer if newest_date < current_date: newest_revision = rev # Return only the revisions with at least one language if the flag's active stats['performance']['revisions_analyzed'] += 1 # Yield when requested # requested only the last revision if only_last_revision: # asked for revisions with languages if only_revisions_with_languages: # has the languages list not empty if newest_revision.languages and is_last_revision: yield newest_revision elif is_last_revision: yield newest_revision elif only_revisions_with_languages: if languages: yield rev else: yield rev def extract_pages( dump: Iterable[mwxml.Page], stats: Mapping, only_last_revision: bool, only_pages_with_languages: bool, only_revisions_with_languages: bool) -> Iterator[Page]: """Extract known languages from an user page.""" # Loop on all the pages in the dump, one at a time for mw_page in dump: utils.log("Processing", mw_page.title) # Skip non-user pages, according to https://en.wikipedia.org/wiki/Wikipedia:Namespace if mw_page.namespace != 2: utils.log('Skipped (namespace != 2)') continue revisions_generator = extract_revisions( mw_page, stats=stats, only_last_revision=only_last_revision, only_revisions_with_languages=only_revisions_with_languages ) revisions_list = list(revisions_generator) page = Page( id=mw_page.id, namespace=mw_page.namespace, title=mw_page.title, revisions=revisions_list, num_langs_known=sum(rev.num_langs_known for rev in revisions_list) ) # Return only the pages with at least one language if the flag's active if only_pages_with_languages: if page.num_langs_known > 0: stats['users']['total'] += 1 yield page else: stats['users']['total'] += 1 yield page stats['performance']['pages_analyzed'] += 1 def configure_subparsers(subparsers): """Configure a new subparser for the known languages.""" parser = subparsers.add_parser( 'extract-known-languages', help='Extract the languages known by the users', ) parser.add_argument( '--only-pages-with-languages', action='store_true', help='Consider only the pages with at least a revision which contains a known language.', ) parser.add_argument( '--only-revisions-with-languages', action='store_true', help='Consider only the revisions with contain at least a known language.', ) parser.add_argument( '--only-last-revision', action='store_true', help='Consider only the last revision for each page.', ) parser.set_defaults(func=main) def main( dump: Iterable[mwxml.Page], features_output_h, stats_output_h, args) -> None: """Main function that parses the arguments and writes the output.""" stats = { 'performance': { 'start_time': None, 'end_time': None, 'revisions_analyzed': 0, 'pages_analyzed': 0, }, 'users': { 'total': 0, # total number of users who have declared to know at least one language 'languages': dict(), # dictionary of languages and the level of knowledge associated 'num_unique_languages': 0, # total number of different and unique languages known by all analyzed users }, } pages_generator = extract_pages( dump, stats=stats, only_last_revision=args.only_last_revision, only_pages_with_languages=args.only_pages_with_languages, only_revisions_with_languages=args.only_revisions_with_languages ) stats['performance']['start_time'] = datetime.datetime.utcnow() # Number of unique languages known stats['users']['flex'] = len(stats['users']['languages']) for obj in pages_generator: features_output_h.write(json.dumps(obj.to_dict())) features_output_h.write("\n") stats['performance']['end_time'] = datetime.datetime.utcnow() stats_output_h.write(json.dumps(stats, indent=4, default=str))
[ "more_itertools.peekable", "json.dumps", "datetime.datetime.utcnow", "backports.datetime_fromisoformat.MonkeyPatch.patch_fromisoformat" ]
[((365, 398), 'backports.datetime_fromisoformat.MonkeyPatch.patch_fromisoformat', 'MonkeyPatch.patch_fromisoformat', ([], {}), '()\n', (396, 398), False, 'from backports.datetime_fromisoformat import MonkeyPatch\n'), ((3138, 3170), 'more_itertools.peekable', 'more_itertools.peekable', (['mw_page'], {}), '(mw_page)\n', (3161, 3170), False, 'import more_itertools\n'), ((9461, 9487), 'datetime.datetime.utcnow', 'datetime.datetime.utcnow', ([], {}), '()\n', (9485, 9487), False, 'import datetime\n'), ((9764, 9790), 'datetime.datetime.utcnow', 'datetime.datetime.utcnow', ([], {}), '()\n', (9788, 9790), False, 'import datetime\n'), ((9816, 9856), 'json.dumps', 'json.dumps', (['stats'], {'indent': '(4)', 'default': 'str'}), '(stats, indent=4, default=str)\n', (9826, 9856), False, 'import json\n')]
from django.db import models from vendor.models import Store class Category(models.Model): BEAUTY = 'Beauty and Health' CLOTHING = 'Clothing' ELECTRONIC = 'Electronics' FOOD = 'Food and Drinks' GROCERY = 'Grocery' HOME = 'Home' CATEGORY_CHOICES = ( (BEAUTY, 'Beauty and Health'), (CLOTHING, 'Clothing'), (ELECTRONIC, 'Electronics'), (FOOD,'Food and Drinks'), (GROCERY, 'Grocery'), (HOME, 'Home'), ) image = models.ImageField(upload_to='img') name = models.CharField(max_length=30, choices=CATEGORY_CHOICES) id = models.AutoField(primary_key=True) def __str__(self): return self.name class Item (models.Model): id = models.AutoField(primary_key=True) image = models.ImageField(upload_to='img') name = models.CharField(max_length = 100, unique=True) category = models.ForeignKey(Category, on_delete=models.PROTECT) # key price = models.DecimalField(max_digits=10, decimal_places=2) store = models.ManyToManyField(Store) # key description = models.CharField(max_length = 2000, blank=True) qty = models.PositiveIntegerField() def __str__(self): return self.name + "- $" + str(self.price)
[ "django.db.models.ForeignKey", "django.db.models.ManyToManyField", "django.db.models.AutoField", "django.db.models.PositiveIntegerField", "django.db.models.ImageField", "django.db.models.DecimalField", "django.db.models.CharField" ]
[((481, 515), 'django.db.models.ImageField', 'models.ImageField', ([], {'upload_to': '"""img"""'}), "(upload_to='img')\n", (498, 515), False, 'from django.db import models\n'), ((527, 584), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)', 'choices': 'CATEGORY_CHOICES'}), '(max_length=30, choices=CATEGORY_CHOICES)\n', (543, 584), False, 'from django.db import models\n'), ((594, 628), 'django.db.models.AutoField', 'models.AutoField', ([], {'primary_key': '(True)'}), '(primary_key=True)\n', (610, 628), False, 'from django.db import models\n'), ((715, 749), 'django.db.models.AutoField', 'models.AutoField', ([], {'primary_key': '(True)'}), '(primary_key=True)\n', (731, 749), False, 'from django.db import models\n'), ((762, 796), 'django.db.models.ImageField', 'models.ImageField', ([], {'upload_to': '"""img"""'}), "(upload_to='img')\n", (779, 796), False, 'from django.db import models\n'), ((808, 853), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)', 'unique': '(True)'}), '(max_length=100, unique=True)\n', (824, 853), False, 'from django.db import models\n'), ((871, 924), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Category'], {'on_delete': 'models.PROTECT'}), '(Category, on_delete=models.PROTECT)\n', (888, 924), False, 'from django.db import models\n'), ((943, 995), 'django.db.models.DecimalField', 'models.DecimalField', ([], {'max_digits': '(10)', 'decimal_places': '(2)'}), '(max_digits=10, decimal_places=2)\n', (962, 995), False, 'from django.db import models\n'), ((1008, 1037), 'django.db.models.ManyToManyField', 'models.ManyToManyField', (['Store'], {}), '(Store)\n', (1030, 1037), False, 'from django.db import models\n'), ((1062, 1107), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(2000)', 'blank': '(True)'}), '(max_length=2000, blank=True)\n', (1078, 1107), False, 'from django.db import models\n'), ((1120, 1149), 'django.db.models.PositiveIntegerField', 'models.PositiveIntegerField', ([], {}), '()\n', (1147, 1149), False, 'from django.db import models\n')]
#!/usr/bin/env python3 import argparse import datetime from functools import lru_cache import logging import os.path import errno import stat from fuse import FUSE, FuseOSError, Operations, LoggingMixIn import requests_cache from opengrokfs.opengrok import File, OpenGrok class OpenGrokFs(LoggingMixIn, Operations): def __init__(self, opengrok): self.opengrok = opengrok self.pseudofile = '.opengrokfs' self.files = {} self.data = {} self.fd = 0 self.list = {} self.today = datetime.datetime.today() self.files['/'] = File('', date=self.today, dir=True, size=0) @lru_cache(maxsize=4096) def _get_file(self, path): self._readdir(os.path.dirname(path) + '/') try: file = self.files[path] except KeyError: raise FuseOSError(errno.ENOENT) return file def getattr(self, path, fh=None): file = self._get_file(path) info = { 'st_mode': 0o644 | (stat.S_IFDIR if file.dir else stat.S_IFREG), 'st_ctime': file.date.timestamp(), 'st_nlink': 2 if file.dir else 1, 'st_size': 0 if file.dir else file.size, } info['st_mtime'] = info['st_atime'] = info['st_ctime'] return info def _get_projects(self): return [f.name for f in self._readdir('/') if f.dir] @lru_cache(maxsize=4096) def _read(self, path): parts = path.strip('/').split('/') if self.pseudofile and parts[-1] == self.pseudofile: if len(parts) == 1: strip = '/' projects = self._get_projects() else: projects = [parts[0]] strip = '/' + '/'.join(parts[:-1]) + '/' args = ['--url', self.opengrok.url, '--strip', strip] for project in projects: args.extend(('--project', project)) data = '\n'.join(args).encode('utf-8') else: data = self.opengrok.get(path).encode('utf-8') file = self._get_file(path) if len(data) < file.size: # file.size reports larger sizes to compensate rounding in the OpenGrok UI, # fill the remaining bytes with whitespace instead of leaving it unfilled # to print junk and errors in vim and gedit due to \0 bytes adjust = file.size - len(data) data += ((adjust - 1) * ' ' + '\n').encode('utf-8') return data def read(self, path, size, offset, fh): data = self._read(path) return data[offset:offset + size] @lru_cache(maxsize=4096) def _readdir(self, path): files = self.opengrok.list(path) if self.pseudofile: files.append(File(self.pseudofile, date=self.today, size=1024)) for file in files: self.files[path + file.name] = file return files def readdir(self, path, fh): if not path.endswith('/'): path += '/' return ['.'] + [f.name for f in self._readdir(path)] def main(): parser = argparse.ArgumentParser() parser.add_argument('--debug', action='store_true') parser.add_argument('--cache', nargs='?', const='opengrokfs', help="Cache network requests persistently") parser.add_argument('url') parser.add_argument('mountpoint') args = parser.parse_args() if args.debug: logging.basicConfig(level=logging.DEBUG) if args.cache: requests_cache.install_cache(args.cache) FUSE(OpenGrokFs(OpenGrok(args.url)), args.mountpoint, foreground=True) if __name__ == '__main__': main()
[ "logging.basicConfig", "argparse.ArgumentParser", "requests_cache.install_cache", "fuse.FuseOSError", "opengrokfs.opengrok.File", "datetime.datetime.today", "functools.lru_cache", "opengrokfs.opengrok.OpenGrok" ]
[((640, 663), 'functools.lru_cache', 'lru_cache', ([], {'maxsize': '(4096)'}), '(maxsize=4096)\n', (649, 663), False, 'from functools import lru_cache\n'), ((1392, 1415), 'functools.lru_cache', 'lru_cache', ([], {'maxsize': '(4096)'}), '(maxsize=4096)\n', (1401, 1415), False, 'from functools import lru_cache\n'), ((2640, 2663), 'functools.lru_cache', 'lru_cache', ([], {'maxsize': '(4096)'}), '(maxsize=4096)\n', (2649, 2663), False, 'from functools import lru_cache\n'), ((3120, 3145), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (3143, 3145), False, 'import argparse\n'), ((538, 563), 'datetime.datetime.today', 'datetime.datetime.today', ([], {}), '()\n', (561, 563), False, 'import datetime\n'), ((590, 633), 'opengrokfs.opengrok.File', 'File', (['""""""'], {'date': 'self.today', 'dir': '(True)', 'size': '(0)'}), "('', date=self.today, dir=True, size=0)\n", (594, 633), False, 'from opengrokfs.opengrok import File, OpenGrok\n'), ((3466, 3506), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.DEBUG'}), '(level=logging.DEBUG)\n', (3485, 3506), False, 'import logging\n'), ((3535, 3575), 'requests_cache.install_cache', 'requests_cache.install_cache', (['args.cache'], {}), '(args.cache)\n', (3563, 3575), False, 'import requests_cache\n'), ((3597, 3615), 'opengrokfs.opengrok.OpenGrok', 'OpenGrok', (['args.url'], {}), '(args.url)\n', (3605, 3615), False, 'from opengrokfs.opengrok import File, OpenGrok\n'), ((838, 863), 'fuse.FuseOSError', 'FuseOSError', (['errno.ENOENT'], {}), '(errno.ENOENT)\n', (849, 863), False, 'from fuse import FUSE, FuseOSError, Operations, LoggingMixIn\n'), ((2789, 2838), 'opengrokfs.opengrok.File', 'File', (['self.pseudofile'], {'date': 'self.today', 'size': '(1024)'}), '(self.pseudofile, date=self.today, size=1024)\n', (2793, 2838), False, 'from opengrokfs.opengrok import File, OpenGrok\n')]
import matplotlib matplotlib.use('Agg') import io import matplotlib.pyplot as plt import numpy as np def save_to_mime_img(filename): buf = io.BytesIO() plt.savefig(buf, format='png') buf.seek(0) binary_img = buf.getvalue() buf.close() # if JiraInfo().instance.is_debug(): # save_image(filename, binary_img) # plt.show() return binary_img def generate_bar_chart(label, data, filename=None): ind = np.arange(len(data)) fig, ax = plt.subplots() rects = ax.bar(ind, data, width=0.5) ax.set_title('Online Bug Summary') ax.set_ylabel("Count", fontsize=8) ax.set_xticks(ind) ax.set_xticklabels(label, fontsize=8) highest = max(data) for rect, i in zip(rects, data): ax.text(rect.get_x() + rect.get_width() / 2, i + highest * 0.02, str(i), color='black', ha='center', fontweight='bold', fontsize=8) return save_to_mime_img(filename) def generate_barh_chart(label, data, filename=None): ind = np.arange(len(data)) fig, ax = plt.subplots() rects = ax.barh(ind, data, height=0.5) ax.set_title('Priority') ax.set_xlabel("Count", fontsize=8) ax.set_ylabel("Level", fontsize=8) ax.set_yticks(ind) ax.set_yticklabels(label, fontsize=8) highest = max(data) for rect, i in zip(rects, data): ax.text(i + highest * 0.03, rect.get_y() + rect.get_height() / 2, str(i), color='black', ha='center', fontweight='bold', fontsize=8) return save_to_mime_img(filename) def generate_pie_chart(label, data, filename=None, title='No-Title'): plt.clf() plt.title(title) label_with_num = [str(label[i]) + "(" + str(data[i]) + ")" for i in range(len(label))] patches, texts, autotexts = plt.pie(data, labels=label_with_num, autopct='%1.1f%%') [_.set_fontsize(8) for _ in texts] [_.set_fontsize(8) for _ in autotexts] plt.axis('equal') return save_to_mime_img(filename) def bug_data_and_label_classified_in_catalog(bug_list, bug_label, bug_catalog): bug_data_in_catalog = [] bug_classified_data_in_catalog = [] for bug in bug_list.bugs: if bug[bug_catalog] is None: continue bug_data_in_catalog.append(bug[bug_catalog]) for var in bug_label: bug_classified_data_in_catalog.append(bug_data_in_catalog.count(var)) return bug_classified_data_in_catalog, bug_label
[ "matplotlib.pyplot.savefig", "matplotlib.use", "matplotlib.pyplot.clf", "io.BytesIO", "matplotlib.pyplot.pie", "matplotlib.pyplot.axis", "matplotlib.pyplot.title", "matplotlib.pyplot.subplots" ]
[((19, 40), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (33, 40), False, 'import matplotlib\n'), ((147, 159), 'io.BytesIO', 'io.BytesIO', ([], {}), '()\n', (157, 159), False, 'import io\n'), ((164, 194), 'matplotlib.pyplot.savefig', 'plt.savefig', (['buf'], {'format': '"""png"""'}), "(buf, format='png')\n", (175, 194), True, 'import matplotlib.pyplot as plt\n'), ((481, 495), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (493, 495), True, 'import matplotlib.pyplot as plt\n'), ((1037, 1051), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1049, 1051), True, 'import matplotlib.pyplot as plt\n'), ((1601, 1610), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (1608, 1610), True, 'import matplotlib.pyplot as plt\n'), ((1615, 1631), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (1624, 1631), True, 'import matplotlib.pyplot as plt\n'), ((1756, 1811), 'matplotlib.pyplot.pie', 'plt.pie', (['data'], {'labels': 'label_with_num', 'autopct': '"""%1.1f%%"""'}), "(data, labels=label_with_num, autopct='%1.1f%%')\n", (1763, 1811), True, 'import matplotlib.pyplot as plt\n'), ((1899, 1916), 'matplotlib.pyplot.axis', 'plt.axis', (['"""equal"""'], {}), "('equal')\n", (1907, 1916), True, 'import matplotlib.pyplot as plt\n')]
# Import necessary packages here from typing import List import warnings from datetime import datetime import pandas as pd import numpy as np import matplotlib.dates as mdates from matplotlib import rc, pyplot as plt # ============================================================================ # ============================================================================ # Date: December 18, 2020 # Purpose: This file contains classes and functions necessary for # plotting. # Source Code Metadata __author__ = "<NAME>" __copyright__ = "Copyright 2020, Jon Webb Inc." __version__ = "1.0" # ============================================================================ # ============================================================================ def text_date_plot(dates: List[List[str]], y_data: List[List[float]], line_colors: List[str], line_style: List[str], line_weight: List[str], x_label: str, y_label: str, dat_labels: List[str], label_pos: str, y_scale: str = 'LIN', plot_name: str = 'NULL', save: bool = False, label_font_size: int = 18, tick_font_size: int = 18, style_name: str = 'default', title: str = 'NULL', title_font_size: int = 24) -> None: """ :param dates: A list of lists, where each inner list contains a list of dates as a text string in the format YYYY-MM-DD or YYYY/MM/DD :param y_data: A list of lists containing y-axis data corresponding to the list of lists in `dates` :param line_colors: A list of line colors ,one for each curve. Acceptable line color indicators can be found in documentation for matplotlib colors <https://matplotlib.org/3.1.0/gallery/color/named_colors.html>`_. :param line_style: A list of line styles, one for each curve. Acceptable line styles can be found in documentation for `matplotlib style <https://matplotlib.org/3.1.0/gallery/lines_bars_and_markers/linestyles.html>`_. :param line_weight: A list of line weights, one for each curve. :param x_label: The x-axis label :param y_label: The y-axis label :param dat_labels: A list of labels, one for each curve :param label_pos: The position of the label in the plot, examples might be ``upper left``, ``lower right``. :param y_scale: 'LOG' or 'LIN' for logarithmic or linear scale :param plot_name: The plot name and path-link, if the user wants to save the plot. If not, the variable is defaulted to ``NULL`` :param save: True or False, defaulted to False :param label_font_size: The font size for plot labels, defaulted to 18 :param tick_font_size: The tick font size, defaulted to 18 :param style_name: The plot style to be used. Acceptable styles can be found at `matplotlib styles <https://matplotlib.org/3.2.1/gallery/style_sheets/style_sheets_reference.html>`_. defaulted to ``default`` :param title: The title of the plot to incorporate into the header. Defaulted to NULL :param title_font_size: The font size for the tile, defaulted to 24 :return None: This function utilizes the matplotlib `subplots <https://matplotlib.org/3.3.3/api/_as_gen/matplotlib.pyplot.subplots.html>`_ functionality to produce single plots of one or multiple data sets as a function of date. This function assumes that the date string is in the format of a text string and not a Timestamp or datetime. This function also autonomusly determines the appropriate date display format. If you desire plots as a function of time you should use the ``text_time_plot`` function. The function can be used in the following manner; .. code-block:: python > # Use stock data for example > tickers = ['AAPL', 'WMT'] > data = yf.download(tickers, '2015-1-1')['Adj Close'] > # transform Timestamps to string > dates = list(data.index.strftime('%Y-%m-%d')) > date_list = [dates, dates] > y_list = [list(data[tickers[0]]), list(data[tickers[1]])] > colors = ['red', 'green'] > line_style = ['-', '-'] > weight = [1.0, 1.0] > text_date_plot(date_list, y_list, colors, line_style, weight, 'Date', '$', tickers, 'upper left') .. image:: date.eps :align: center """ # Adjust format for YYYY/MM/DD to YYYY-MM-DD outer_list = [] for i in range(len(dates)): inner_list = [] for j in range(len(dates[i])): year = dates[i][j][0:4] month = dates[i][j][5:7] day = dates[i][j][8:10] date_string = year + '-' + month + '-' + day inner_list.append(datetime.strptime(date_string, '%Y-%m-%d')) outer_list.append(inner_list) # Determine time difference between min and max point days = 0 for i in outer_list: delta = (max(i) - min(i)).days if delta > days: days = delta # Start plot fig, td_plot = plt.subplots() plt.rcParams.update({'figure.autolayout': True}) plt.style.use(style_name) rc('xtick', labelsize=tick_font_size) rc('ytick', labelsize=tick_font_size) if y_scale.upper() == 'LOG': td_plot.set_yscale('log') if days <= 15: myfmt = mdates.DateFormatter('%d') td_plot.xaxis.set_major_locator(mdates.DayLocator()) elif days <= 180: myfmt = mdates.DateFormatter('%b-%y') td_plot.xaxis.set_major_locator(mdates.MonthLocator()) else: myfmt = mdates.DateFormatter('%b-%y') td_plot.xaxis.set_major_locator(plt.MaxNLocator(4)) td_plot.set_xlabel(x_label, fontsize=label_font_size) td_plot.set_ylabel(y_label, fontsize=label_font_size) if title != 'NULL': td_plot.set_title(title, fontsize=title_font_size) td_plot.xaxis.set_major_formatter(myfmt) for i in range(len(outer_list)): td_plot.plot(outer_list[i], y_data[i], color=line_colors[i], label=dat_labels[i], linewidth=line_weight[i], linestyle=line_style[i]) plt.legend(loc=label_pos) if not save: plt.show() else: plt.savefig(plot_name) # ---------------------------------------------------------------------------- def two_d_line_matplot(x_data: List[List[float]], y_data: List[List[float]], line_colors: List[str], line_style: List[str], line_weight: List[str], x_label: str, y_label: str, dat_labels: List[str], label_pos: str, x_scale: str = 'LIN', y_scale: str = 'LIN', plot_name: str = 'NULL', save: bool = False, label_font_size: int = 18, tick_font_size: int = 18, style_name: str = 'default', title: str = 'NULL', title_font_size: int = 24) -> None: """ :param x_data: A list of lists, where the inner lists contain data points for the x-axis :param y_data: A list of lists, where the inner lists contain data points for the y-axis :param line_colors: A list of line colors ,one for each curve. Acceptable line color indicators can be found in documentation for matplotlib colors <https://matplotlib.org/3.1.0/gallery/color/named_colors.html>`_. :param line_style: A list of line styles, one for each curve. Acceptable line styles can be found in documentation for `matplotlib style <https://matplotlib.org/3.1.0/gallery/lines_bars_and_markers/linestyles.html>`_. :param line_weight: A list of line weights, one for each curve. :param x_label: The label for the x-axis :param y_label: The label for the y-axis :param dat_labels: A list of labels, one for each curve :param label_pos: The position of the label in the plot, examples might be ``upper left``, ``lower right``. :param x_scale: LOG or LIN for logarithmic or linear, defaulted to LIN :param y_scale: LOG or LIN for logarithmic or linear, defaulted to LIN :param plot_name: The plot name and path-link, if the user wants to save the plot. If not, the variable is defaulted to ``NULL`` :param save: True or False, defaulted to False :param label_font_size: The font size for plot labels, defaulted to 18 :param tick_font_size: The tick font size, defaulted to 18 :param style_name: The plot style to be used. Acceptable styles can be found at `matplotlib styles <https://matplotlib.org/3.2.1/gallery/style_sheets/style_sheets_reference.html>`_. defaulted to ``default`` :param title: The title of the plot to incorporate into the header. Defaulted to NULL :param title_font_size: The font size for the tile, defaulted to 24 :return None: This function utilizes the matplotlib `subplots <https://matplotlib.org/3.3.3/api/_as_gen/matplotlib.pyplot.subplots.html>`_ functionality to produce single plots of one or multiple data sets. This function will only produce line plots and not scatter plots or a combination of both. The function can be used in the following manner; .. code-block:: python > x_dat = np.linspace(0, 10, 15) > y1_dat = x_dat > y2_dat = x_dat ** 2.0 > y3_dat = x_dat ** 3.0 > x_list = [x_dat, x_dat, x_dat] > y_list = [y1_dat, y2_dat, y3_dat] > colors = ['red', 'blue', 'black'] > line_style = ['-', '-', '--'] > labels = ['linear', 'squared', 'cubed'] > weight = [1, 2, 3] > two_d_line_matplot(x_list, y_list, colors, line_style, weight, 'x-data', 'y-data', labels, 'upper left') .. image:: line_plot.eps :scale: 90% :align: center """ # Error checking and warnings if save and plot_name == 'NULL': warnings.warn('if save is True then plot name cannot be NULL') if len(x_data) != len(y_data): warnings.warn('length of x list of lists is not the same as y list of lists, plot not printed') return if len(line_colors) != len(x_data): warnings.warn('line colors list not the same length as data lists, plot not printed') return if len(line_style) != len(x_data): warnings.warn('line_style list not the same length as data lists, plot not printed') return if len(line_weight) != len(x_data): warnings.warn('line_weight list not the same length as data lists, plot not printed') return if y_scale != 'LOG' and y_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') if x_scale != 'LOG' and x_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') # begin plot plt.rcParams.update({'figure.autolayout': True}) plt.style.use(style_name) fig, td_plot = plt.subplots() rc('xtick', labelsize=tick_font_size) rc('ytick', labelsize=tick_font_size) td_plot.set_xlabel(x_label, fontsize=label_font_size) td_plot.set_ylabel(y_label, fontsize=label_font_size) if title != 'NULL': td_plot.set_title(title, fontsize=title_font_size) if x_scale.upper() == 'LOG': td_plot.set_xscale('log') if y_scale.upper() == 'LOG': td_plot.set_yscale('log') for i in range(len(line_colors)): td_plot.plot(x_data[i], y_data[i], color=line_colors[i], label=dat_labels[i], linewidth=line_weight[i], linestyle=line_style[i]) plt.legend(loc=label_pos) if not save: plt.show() else: plt.savefig(plot_name) # ---------------------------------------------------------------------------- def two_d_scatter_matplot(x_data: List[List[float]], y_data: List[List[float]], marker_colors: List[str], marker_style: List[str], x_label: str, y_label: str, dat_labels: List[str], label_pos: str, x_scale: str = 'LIN', y_scale: str = 'LIN', plot_name: str = 'NULL', save: bool = False, label_font_size: int = 18, tick_font_size: int = 18, style_name: str = 'default', title: str = 'NULL', title_font_size: int = 24) -> None: """ :param x_data: A list of lists, where the inner lists contain data points for the x-axis :param y_data: A list of lists, where the inner lists contain data points for the y-axis :param marker_colors: A list of line colors ,one for each curve. Acceptable line color indicators can be found in documentation for `matplotlib colors <https://matplotlib.org/3.1.0/gallery/color/named_colors.html>`_. :param marker_style: A list of line styles, one for each curve. Acceptable line styles can be found in documentation for `matplotlib style`_. :param x_label: The label for the x-axis :param y_label: The label for the y-axis :param dat_labels: A list of labels, one for each curve :param label_pos: The position of the label in the plot, examples might be ``upper left``, ``lower right`` :param x_scale: LOG or LIN for logarithmic or linear, defaulted to LIN :param y_scale: LOG or LIN for logarithmic or linear, defaulted to LIN :param plot_name: The plot name and path-link, if the user wants to save the plot. If not, the variable is defaulted to ``NULL`` :param save: True or False, defaulted to False :param label_font_size: The font size for plot labels, defaulted to 18 :param tick_font_size: The tick font size, defaulted to 18 :param style_name: The plot style to be used. Acceptable styles can be found at `matplotlib styles <https://matplotlib.org/3.2.1/gallery/style_sheets/style_sheets_reference.html>`_. defaulted to ``default`` :param title: The title of the plot to incorporate into the header. Defaulted to NULL :param title_font_size: The font size for the tile, defaulted to 24 :return None: This function utilizes the matplotlib `subplots <https://matplotlib.org/3.3.3/api/_as_gen/matplotlib.pyplot.subplots.html>`_ functionality to produce single plots of one or multiple data sets. This function will only produce line plots and not scatter plots or a combination of both. The function can be used in the following manner; .. code-block:: python > x_dat = np.linspace(0, 10, 15) > y1_dat = x_dat > y2_dat = x_dat ** 2.0 > y3_dat = x_dat ** 3.0 > x_list = [x_dat, x_dat, x_dat] > y_list = [y1_dat, y2_dat, y3_dat] > colors = ['red', 'blue', 'black'] > line_style = ['-', '-', '--'] > labels = ['linear', 'squared', 'cubed'] > weight = [1, 2, 3] > two_d_scatter_matplot(x_list, y_list, colors, line_style, weight, 'x-data', 'y-data', labels, 'upper left') .. image:: scatter_plot.eps :align: center """ # Error checking and warnings if save and plot_name == 'NULL': warnings.warn('if save is True then plot name cannot be NULL') if len(x_data) != len(y_data): warnings.warn('length of x list of lists is not the same as y list of lists, plot not printed') return if len(marker_colors) != len(x_data): warnings.warn('line colors list not the same length as data lists, plot not printed') return if len(marker_style) != len(x_data): warnings.warn('line_style list not the same length as data lists, plot not printed') return if y_scale != 'LOG' and y_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') if x_scale != 'LOG' and x_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') # begin plot plt.rcParams.update({'figure.autolayout': True}) plt.style.use(style_name) fig, td_plot = plt.subplots() rc('xtick', labelsize=tick_font_size) rc('ytick', labelsize=tick_font_size) td_plot.set_xlabel(x_label, fontsize=label_font_size) td_plot.set_ylabel(y_label, fontsize=label_font_size) if title != 'NULL': td_plot.set_title(title, fontsize=title_font_size) if x_scale.upper() == 'LOG': td_plot.set_xscale('log') if y_scale.upper() == 'LOG': td_plot.set_yscale('log') for i in range(len(marker_colors)): td_plot.plot(x_data[i], y_data[i], color=marker_colors[i], label=dat_labels[i], marker=marker_style[i], linestyle=' ') plt.legend(loc=label_pos) if not save: plt.show() else: plt.savefig(plot_name) # ---------------------------------------------------------------------------- def two_d_scatter_line_matplot(x_data: List[List[float]], y_data: List[List[float]], marker_colors: List[str], marker_style: List[str], line_style: List[str], line_weight: List[str], x_label: str, y_label: str, dat_labels: List[str], label_pos: str, x_scale: str = 'LIN', y_scale: str = 'LIN', plot_name: str = 'NULL', save: bool = False, label_font_size: int = 18, tick_font_size: int = 18, style_name: str = 'default', title: str = 'NULL', title_font_size: int = 24) -> None: """ :param x_data: A list of lists, where the inner lists contain data points for the x-axis :param y_data: A list of lists, where the inner lists contain data points for the y-axis :param marker_colors: A list of line colors ,one for each curve. Acceptable line color indicators can be found in documentation for `matplotlib colors <https://matplotlib.org/3.1.0/gallery/color/named_colors.html>`_. :param marker_style: A list of line styles, one for each curve. Acceptable line styles can be found in documentation for `matplotlib style`_. :param line_style: A list of line styles, one for each curve. Acceptable line styles can be found in documentation for `matplotlib style <https://matplotlib.org/3.1.0/gallery/lines_bars_and_markers/linestyles.html>`_. :param line_weight: A list of line weights, one for each curve. :param x_label: The label for the x-axis :param y_label: The label for the y-axis :param dat_labels: A list of labels, one for each curve :param label_pos: The position of the label in the plot, examples might be ``upper left``, ``lower right`` :param x_scale: LOG or LIN for logarithmic or linear, defaulted to LIN :param y_scale: LOG or LIN for logarithmic or linear, defaulted to LIN :param plot_name: The plot name and path-link, if the user wants to save the plot. If not, the variable is defaulted to ``NULL`` :param save: True or False, defaulted to False :param label_font_size: The font size for plot labels, defaulted to 18 :param tick_font_size: The tick font size, defaulted to 18 :param style_name: The plot style to be used. Acceptable styles can be found at `matplotlib styles <https://matplotlib.org/3.2.1/gallery/style_sheets/style_sheets_reference.html>`_. defaulted to ``default`` :param title: The title of the plot to incorporate into the header. Defaulted to NULL :param title_font_size: The font size for the tile, defaulted to 24 :return None: This function utilizes the matplotlib `subplots <https://matplotlib.org/3.3.3/api/_as_gen/matplotlib.pyplot.subplots.html>`_ functionality to produce single plots of one or multiple data sets overlaid with line plots. This function will only produce line plots and not scatter plots or a combination of both. The function can be used in the following manner; .. code-block:: python > x_dat = np.linspace(0, 10, 15) > y1_dat = x_dat > y2_dat = x_dat ** 2.0 > y3_dat = x_dat ** 3.0 > x_list = [x_dat, x_dat, x_dat] > y_list = [y1_dat, y2_dat, y3_dat] > colors = ['red', 'blue', 'black'] > line_style = ['-', '-', '--'] > labels = ['linear', 'squared', 'cubed'] > weight = [1, 2, 3] > marker_style = ['^', 'o', 'd'] > two_d_scatter_line_matplot(x_list, y_list, colors, marker_style, line_style, weight, 'x-axis', 'y-axis', labels, 'upper left', save=True, plot_name=plt_name) .. image:: line_mark.eps :align: center """ # Error checking and warnings if save and plot_name == 'NULL': warnings.warn('if save is True then plot name cannot be NULL') if len(x_data) != len(y_data): warnings.warn('length of x list of lists is not the same as y list of lists, plot not printed') return if len(marker_colors) != len(x_data): warnings.warn('line colors list not the same length as data lists, plot not printed') return if len(marker_style) != len(x_data): warnings.warn('line_style list not the same length as data lists, plot not printed') return if y_scale != 'LOG' and y_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') if x_scale != 'LOG' and x_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') # begin plot plt.rcParams.update({'figure.autolayout': True}) plt.style.use(style_name) fig, td_plot = plt.subplots() rc('xtick', labelsize=tick_font_size) rc('ytick', labelsize=tick_font_size) if title != 'NULL': td_plot.set_title(title, fontsize=title_font_size) td_plot.set_xlabel(x_label, fontsize=label_font_size) td_plot.set_ylabel(y_label, fontsize=label_font_size) if x_scale.upper() == 'LOG': td_plot.set_xscale('log') if y_scale.upper() == 'LOG': td_plot.set_yscale('log') for i in range(len(marker_colors)): td_plot.plot(x_data[i], y_data[i], color=marker_colors[i], label=dat_labels[i], marker=marker_style[i], linestyle=line_style[i], linewidth=line_weight[i]) plt.legend(loc=label_pos) if not save: plt.show() else: plt.savefig(plot_name) # ---------------------------------------------------------------------------- def one_d_histogram_plot(data: List[List[float]], labels: List[List[str]], x_label: str, y_label: str, colors: List[str], edge_colors: List[str], shading: List[float], label_pos: str, num_bins: int = 50, tick_font_size: int = 18, label_font_size: str = 18, style_name: str = 'default', save: bool = False, plot_name: str = 'NULL', hist_type: str = 'bar', dens: bool = False, title: str = 'NULL', title_font_size: int = 24) -> None: """ :param data: A list of lists containing data for one or multiple distributions :param labels: A list of labels, one for each distribution :param x_label: The label for the x-axis :param y_label: The label for the y-axis :param colors: The fill colors for each ``bar`` plot. If a ``step`` plot is selected, this input is irrelevant, but data must still be passed to the function. :param edge_colors: The colors for the edge of each bar or step plot :param shading: The level of transparency for bar plot fill. a Value of 0 is invisible, 1 is the maximum color density :param label_pos: Where in the plot, the labels for each curve are to be placed. ``upper left`` or ``lower right`` are examples. :param num_bins: The number of bins to be plotted, defaulted to 50 :param tick_font_size: The size for each tick, defaulted to 18 :param label_font_size: The size for printed font, defaulted to 18 :param style_name: The plot style to be used. Acceptable styles can be found at `matplotlib styles <https://matplotlib.org/3.2.1/gallery/style_sheets/style_sheets_reference.html>`_. defaulted to ``default`` :param save: True or False, defaulted to False :param plot_name: The plot name and path-link, if the user wants to save the plot. If not, the variable is defaulted to ``NULL`` :param hist_type: {``bar``, ``barstacked``, ``step``, ``stepfilled``} See `histogram <https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.hist.html>`_ for more information. :param dens: If True, the first element of the return tuple will be the counts normalized to form a probability density, i.e., the area (or integral) under the histogram will sum to 1 :param title: The title of the plot to incorporate into the header. Defaulted to NULL :param title_font_size: The font size for the tile, defaulted to 24 :return: This function utilizes the matplotlib `subplots <https://matplotlib.org/3.3.3/api/_as_gen/matplotlib.pyplot.subplots.html>`_ functionality to produce single phistogram plots or multiple overlaid plots. The function can be used in the following manner; .. code-block:: python > np.random.seed(19680801) > x = np.random.normal(15.0, 3.0, 1000) > y = np.random.normal(20.0, 3.0, 1000) > data = [x, y] > labels = ['one', 'two'] > colors = ['blue', 'green'] > edge_colors = ['black', 'black'] > alpha = [0.9, 0.2] > x_label = 'x-axis' > y_label = 'y-axis' > one_d_histogram_plot(data, labels, x_label, y_label, colors, edge_colors, alpha, 'upper left', num_bins=50, hist_type='step', dens=True) .. image:: hist1.eps :align: center The plot parameters can be changed to produce a normalized plot, only showing the histogram outline with the following code. .. code-block:: python > np.random.seed(19680801) > x = np.random.normal(15.0, 3.0, 1000) > y = np.random.normal(20.0, 3.0, 1000) > data = [x, y] > labels = ['one', 'two'] > colors = ['black', 'red'] > edge_colors = ['black', 'red'] > alpha = [1.0, 1.0] > x_label = 'x-axis' > y_label = 'y-axis' > one_d_histogram_plot(data, labels, x_label, y_label, colors, edge_colors, alpha, 'upper left', num_bins=50) .. image:: hist2.eps :align: center """ if len(labels) != len(data): warnings.warn("data list should be the same length as the labels list") if len(labels) != len(colors): warnings.warn("data list should be the same length as the colors list") if len(labels) != len(edge_colors): warnings.warn("labels list should be the same length as the edge_colors list") if len(labels) != len(shading): warnings.warn("labels list should be the same length as the shading list") plt.tight_layout() plt.gcf().subplots_adjust(bottom=0.15) plt.rcParams.update({'figure.autolayout': True}) plt.style.use(style_name) rc('xtick', labelsize=tick_font_size) rc('ytick', labelsize=tick_font_size) plt.xlabel(x_label, fontsize=label_font_size) plt.ylabel(y_label, fontsize=label_font_size) if title != 'NULL': plt.title(title, fontsize=title_font_size) for i in range(len(labels)): plt.hist(data[i], bins=num_bins, color=colors[i], edgecolor=edge_colors[i], alpha=shading[i], label=labels[i], histtype=hist_type, density=dens) plt.legend(loc=label_pos) if not save: plt.show() else: plt.savefig(plot_name) plt.close() # ================================================================================ # ================================================================================ class MatPlotDataFrame: """ :param df: Dataframe containing columnar data to be plotted This class will plot user specified data from a pandas dataframe """ def __init__(self, df: pd.DataFrame): self.df = df self.colors = ['lightgrey', 'deepskyblue', 'sandybrown', 'teal', 'limegreen', 'coral', 'hotpink', 'magenta', 'red', 'white', 'gold', 'darkgreen', 'turqoise', 'olive', 'orange', 'mediumvioletred', 'purple' , 'darkred'] self.styles = ['o' for i in range(len(self.colors))] # -------------------------------------------------------------------------------- def scatter_plot_parse_column(self, x_header: str, y_header: str, parsing_header: str, column_values: List[str], style_name: str='default', marker_colors: List[str]=['None'], marker_style: List[str]=['None'], fill_alpha: np.float32=0.7, edge_color: str='black', x_label: str='', y_label: str='', title: str='', label_pos: str='upper right', x_scale: str='LIN', y_scale: str='LIN', plot_name: str='NULL', save: bool=False, label_font_size: int=18, tick_font_size: int=18, title_font_size: int=24, marker_size: int=35, marker_edge_width: np.float32=0.8, grid: bool=False, grid_style='-', grid_color='grey') -> None: """ :param x_header: The title of the dataframe column containing the x-axis data sets :param y_header: The title of the dataframe column containing the y-axis data sets :param parsing_header: The title of the dataframe column containing the values which will be used to parse the dataframe into one or multiple data sets :param column_values: The values contained in the parsing_header column that will be used to parse the data set into multiple data sets :param style_name: The name of the matplotlib style that will be used to format the plot. Defaulted to 'default'. Possible styles can be found at :href `styles<https://matplotlib.org/stable/api/style_api.html>` :param marker_colors: A list of marker colors, where each marker color corresponds to each data set. This parameter has a default color lists that can accomodate 18 different data sets. The user can override the default colors with a list of their own. Potential colors can be found at :href `colors<https://matplotlib.org/stable/gallery/color/named_colors.html>` :param marker_style: A list of marker styles, where each marker style corresponds to a data set. This parameter has a default list of 18 circle marker styles that the user can override. Marker styles can be found at :href `marker style<https://matplotlib.org/stable/api/markers_api.html>` :param fill_apha: The density of the marker fill. Defaulted to 0.7 :param edge_color: The color of the line surrounding the marker :param x_label: The x axis label,defaulted to ' ' :param y_label: The y axis label, defaulted to ' ' :param title: The plot title, defaulted to ' ' :param label_pos: The position of the legend in the plot. Defaulted to 'upper right' :param x_scale: 'LOG' or 'LIN', defaulted to 'LIN' :param y_scale: 'LOG' or 'LIN', defaulted to 'LIN' :param plot_name: The name of the file containing the plot if the plot is to be saved. Defaulted to 'NULL' :param save: True if the plot is to be saved, False if the plot is to be shown and not saved. Defaulted to False :param label_font_size: The label font size, defaulted to 18 :param tick_font_size: The tick font size, defaulted to 18 :param title_font_size: The title font size, defaulted to 24 :param marker_size: The size of the marker, defaulted to 35 :param marker_edge_width: The thickness of the line outlining each marker. Defaulted to 0.8 :param grid: True if a grid overlaid on the plot is desired, False if not :param grid_color: Defaulted to 'grey' :grid_style: Defaulted to '-' This method will parse a dataframe column based on a user specified value or list of values, and plot the data in a user specified x and y axis column based on filter data. As an example, consider a dataframe with the following columnar data structure. .. code-block:: python > length = 20 > x = np.linspace(0, length, num=length) > linear = x > squared = x ** 2.0 > lin = np.repeat('linear', length) > sq = np.repeat('squared', length) > # Combine arrays into one > x = np.hstack((x, x)) > y = np.hstack((linear, squared)) > power = np.hstack((lin, sq)) > # Create dataframe > dictionary = {'x': x, 'y': y, 'power': power} > df = pd.DataFrame(dictionary) > # Plot data > obj = MatPlotDataFrame(df) > parsing_header = 'power' > column_values = ['linear', 'squared'] obj.scatter_plot_filter_column('x', 'y', parsing_header, column_values, marker_colors=['red', 'green'], marker_style=['o', '^'], label_pos='upper left') .. image:: mat_scatter_test1.eps :align: center """ df_list = [self.df[self.df[parsing_header] == col_val] for col_val in column_values] # Error checking if marker_colors[0] == 'None': marker_colors = self.colors if len(marker_colors) < len(column_values): msg1 = 'FATAL ERROR: The length of the marker color list must be as ' msg2 = 'large or larger than the size of the column values' sys.exit(msg + ms2) if marker_style[0] == 'None': marker_style = self.styles if len(marker_style) < len(column_values): msg1 = 'FATAL ERROR: The length of the marker stye list must be as ' msg2 = 'large or larger than the size of the column values' sys.exit(msg + ms2) if save and plot_name == 'NULL': warnings.warn('if save is True then plot name cannot be NULL') if y_scale != 'LOG' and y_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') if x_scale != 'LOG' and x_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') # begin plot plt.rcParams.update({'figure.autolayout': True}) plt.style.use(style_name) fig, td_plot = plt.subplots() rc('xtick', labelsize=tick_font_size) rc('ytick', labelsize=tick_font_size) td_plot.set_xlabel(x_label, fontsize=label_font_size) td_plot.set_ylabel(y_label, fontsize=label_font_size) if title != 'NULL': td_plot.set_title(title, fontsize=title_font_size) if x_scale.upper() == 'LOG': td_plot.set_xscale('log') if y_scale.upper() == 'LOG': td_plot.set_yscale('log') for i in range(len(df_list)): td_plot.scatter(df_list[i][x_header], df_list[i][y_header], label=column_values[i], marker=marker_style[i], color=marker_colors[i], alpha=fill_alpha, edgecolors=edge_color, s=marker_size, linewidth=marker_edge_width) plt.legend(loc=label_pos) if grid: plt.grid(color=grid_color, linestyle=grid_style) if not save: plt.show() else: plt.savefig(plot_name) plt.close() # -------------------------------------------------------------------------------- def scatter_plot_columns(self, x_headers: List[str], y_headers: List[str], labels: List[str], style_name: str='default', marker_colors: List[str]=['None'], marker_style: List[str]=['None'], fill_alpha: np.float32=0.7, edge_color: str='black', x_label: str='', y_label: str='', title: str='', label_pos: str='upper right', x_scale: str='LIN', y_scale: str='LIN', plot_name: str='NULL', save: bool=False, label_font_size: int=18, tick_font_size: int=18, title_font_size: int=24, marker_size: int=35, marker_edge_width: np.float32=0.8, grid: bool=False, grid_style='-', grid_color='grey'): """ :param x_headers: The title of the dataframe columns containing the x-axis data sets :param y_headers: The title of the dataframe columns containing the y-axis data sets :param labels: A list of the label names for each data set :param style_name: The name of the matplotlib style that will be used to format the plot. Defaulted to 'default'. Possible styles can be found at :href `styles<https://matplotlib.org/stable/api/style_api.html>` :param marker_colors: A list of marker colors, where each marker color corresponds to each data set. This parameter has a default color lists that can accomodate 18 different data sets. The user can override the default colors with a list of their own. Potential colors can be found at :href `colors<https://matplotlib.org/stable/gallery/color/named_colors.html>` :param marker_style: A list of marker styles, where each marker style corresponds to a data set. This parameter has a default list of 18 circle marker styles that the user can override. Marker styles can be found at :href `marker style<https://matplotlib.org/stable/api/markers_api.html>` :param fill_apha: The density of the marker fill. Defaulted to 0.7 :param edge_color: The color of the line surrounding the marker :param x_label: The x axis label,defaulted to ' ' :param y_label: The y axis label, defaulted to ' ' :param title: The plot title, defaulted to ' ' :param label_pos: The position of the legend in the plot. Defaulted to 'upper right' :param x_scale: 'LOG' or 'LIN', defaulted to 'LIN' :param y_scale: 'LOG' or 'LIN', defaulted to 'LIN' :param plot_name: The name of the file containing the plot if the plot is to be saved. Defaulted to 'NULL' :param save: True if the plot is to be saved, False if the plot is to be shown and not saved. Defaulted to False :param label_font_size: The label font size, defaulted to 18 :param tick_font_size: The tick font size, defaulted to 18 :param title_font_size: The title font size, defaulted to 24 :param marker_size: The size of the marker, defaulted to 35 :param marker_edge_width: The thickness of the line outlining each marker. Defaulted to 0.8 :param grid: True if a grid overlaid on the plot is desired, False if not :param grid_color: Defaulted to 'grey' :grid_style: Defaulted to '-' This method will plot used defined dataframe columns for the x and y axis of a 2-d plot as a scatter plot. .. code-block:: python > length = 20 > x = np.linspace(0, 20, num=20) > linear = x > squared = x ** 2.0 > # create dataframe > dictionary = {'x': x, 'linear': linear, 'squared': squared} > df = pd.DataFrame(dictionary) > # plot data > obj = MatPlotDataFrame(df) > x_headers = ['x', 'x'] > y_headers = ['linear', 'squared'] > obj.scatter_plot_columns(x_headers, y_headers, y_headers, x_label='x-axis', y_label='y-axis', title='Test', style_name='default',marker_colors=['red', 'green'], fill_alpha=0.7, marker_style=['o', '^'], label_pos='upper left', grid=False, save=True, plot_name=plt_name) .. image:: mat_scatter_test2.eps :align: center """ # Error checking if marker_colors[0] == 'None': marker_colors = self.colors if len(x_headers) != len(y_headers): sys.exit('FATAL ERROR: x and y arrays must be the same size') if marker_style[0] == 'None': marker_style = self.styles if len(marker_style) < len(x_headers): msg1 = 'FATAL ERROR: The length of the marker stye list must be as ' msg2 = 'large or larger than the size of the column values' sys.exit(msg + ms2) if save and plot_name == 'NULL': warnings.warn('if save is True then plot name cannot be NULL') if y_scale != 'LOG' and y_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') if x_scale != 'LOG' and x_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') # begin plot plt.rcParams.update({'figure.autolayout': True}) plt.style.use(style_name) fig, td_plot = plt.subplots() rc('xtick', labelsize=tick_font_size) rc('ytick', labelsize=tick_font_size) td_plot.set_xlabel(x_label, fontsize=label_font_size) td_plot.set_ylabel(y_label, fontsize=label_font_size) if title != 'NULL': td_plot.set_title(title, fontsize=title_font_size) if x_scale.upper() == 'LOG': td_plot.set_xscale('log') if y_scale.upper() == 'LOG': td_plot.set_yscale('log') for i in range(len(x_headers)): td_plot.scatter(self.df[x_headers[i]], self.df[y_headers[i]], label=labels[i], marker=marker_style[i], color=marker_colors[i], alpha=fill_alpha, edgecolors=edge_color, s=marker_size, linewidth=marker_edge_width) plt.legend(loc=label_pos) if grid: plt.grid(color=grid_color, linestyle=grid_style) if not save: plt.show() else: plt.savefig(plot_name) plt.close() # -------------------------------------------------------------------------------- def line_plot_parse_column(self, x_header: str, y_header: str, parsing_header: str, column_values: List[str], style_name: str='default', line_colors: List[str]=['None'], line_weight: np.float32=2.0, fill_alpha: np.float32=0.7, line_style: str='-', x_label: str='', y_label: str='', title: str='', label_pos: str='upper right', x_scale: str='LIN', y_scale: str='LIN', plot_name: str='NULL', save: bool=False, label_font_size: int=18, tick_font_size: int=18, title_font_size: int=24, marker_size: int=35, marker_edge_width: np.float32=0.8, grid: bool=False, grid_style='-', grid_color='grey') -> None: """ :param x_header: The title of the dataframe column containing the x-axis data sets :param y_header: The title of the dataframe column containing the y-axis data sets :param parsing_header: The title of the dataframe column containing the values which will be used to parse the dataframe into one or multiple data sets :param column_values: The values contained in the parsing_header column that will be used to parse the data set into multiple data sets :param style_name: The name of the matplotlib style that will be used to format the plot. Defaulted to 'default'. Possible styles can be found at :href `styles<https://matplotlib.org/stable/api/style_api.html>` :param line_colors: A list of line colors, where each marker color corresponds to each data set. This parameter has a default color lists that can accomodate 18 different data sets. The user can override the default colors with a list of their own. Potential colors can be found at :href `colors<https://matplotlib.org/stable/gallery/color/named_colors.html>` :param line_weight: The weight corresponding to the line thickness, defaulted to 2.0 :param fill_apha: The density of the marker fill. Defaulted to 0.7 :param x_label: The x axis label,defaulted to ' ' :param y_label: The y axis label, defaulted to ' ' :param title: The plot title, defaulted to ' ' :param label_pos: The position of the legend in the plot. Defaulted to 'upper right' :param x_scale: 'LOG' or 'LIN', defaulted to 'LIN' :param y_scale: 'LOG' or 'LIN', defaulted to 'LIN' :param plot_name: The name of the file containing the plot if the plot is to be saved. Defaulted to 'NULL' :param save: True if the plot is to be saved, False if the plot is to be shown and not saved. Defaulted to False :param label_font_size: The label font size, defaulted to 18 :param tick_font_size: The tick font size, defaulted to 18 :param title_font_size: The title font size, defaulted to 24 :param marker_size: The size of the marker, defaulted to 35 :param marker_edge_width: The thickness of the line outlining each marker. Defaulted to 0.8 :param grid: True if a grid overlaid on the plot is desired, False if not :param grid_color: Defaulted to 'grey' :grid_style: Defaulted to '-' This method will parse a dataframe column based on a user specified value or list of values, and plot the data in a user specified x and y axis column based on filter data. As an example, consider a dataframe with the following columnar data structure. .. code-block:: python > length = 20 > x = np.linspace(0, length, num=length) > linear = x > squared = x ** 2.0 > lin = np.repeat('linear', length) > sq = np.repeat('squared', length) > # Combine arrays into one > x = np.hstack((x, x)) > y = np.hstack((linear, squared)) > power = np.hstack((lin, sq)) > # Create dataframe > dictionary = {'x': x, 'y': y, 'power': power} > df = pd.DataFrame(dictionary) > # Plot data > obj = MatPlotDataFrame(df) > parsing_header = 'power' > column_values = ['linear', 'squared'] obj.line_plot_filter_column('x', 'y', parsing_header, column_values, marker_colors=['red', 'green'], marker_style=['o', '^'], label_pos='upper left') .. image:: line_scatter_test1.eps :align: center """ df_list = [self.df[self.df[parsing_header] == col_val] for col_val in column_values] # Error checking if line_colors[0] == 'None': line_colors = self.colors if len(line_colors) < len(column_values): msg1 = 'FATAL ERROR: The length of the marker color list must be as ' msg2 = 'large or larger than the size of the column values' sys.exit(msg + ms2) if save and plot_name == 'NULL': warnings.warn('if save is True then plot name cannot be NULL') if y_scale != 'LOG' and y_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') if x_scale != 'LOG' and x_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') # begin plot plt.rcParams.update({'figure.autolayout': True}) plt.style.use(style_name) fig, td_plot = plt.subplots() rc('xtick', labelsize=tick_font_size) rc('ytick', labelsize=tick_font_size) td_plot.set_xlabel(x_label, fontsize=label_font_size) td_plot.set_ylabel(y_label, fontsize=label_font_size) if title != 'NULL': td_plot.set_title(title, fontsize=title_font_size) if x_scale.upper() == 'LOG': td_plot.set_xscale('log') if y_scale.upper() == 'LOG': td_plot.set_yscale('log') for i in range(len(df_list)): td_plot.plot(df_list[i][x_header], df_list[i][y_header], label=column_values[i], linestyle=line_style, color=line_colors[i], linewidth=line_weight) plt.legend(loc=label_pos) if grid: plt.grid(color=grid_color, linestyle=grid_style) if not save: plt.show() else: plt.savefig(plot_name) plt.close() # -------------------------------------------------------------------------------- def line_plot_columns(self, x_headers: str, y_headers: str, labels: List[str], style_name: str='default', line_colors: List[str]=['None'], line_weight: np.float32=2.0, fill_alpha: np.float32=0.7, line_style: str='-', x_label: str='', y_label: str='', title: str='', label_pos: str='upper right', x_scale: str='LIN', y_scale: str='LIN', plot_name: str='NULL', save: bool=False, label_font_size: int=18, tick_font_size: int=18, title_font_size: int=24, marker_size: int=35, marker_edge_width: np.float32=0.8, grid: bool=False, grid_style='-', grid_color='grey') -> None: """ :param x_headers: The title of the dataframe columns containing the x-axis data sets :param y_headers: The title of the dataframe columns containing the y-axis data sets :param labels: A list containing the name of each label :param style_name: The name of the matplotlib style that will be used to format the plot. Defaulted to 'default'. Possible styles can be found at :href `styles<https://matplotlib.org/stable/api/style_api.html>` :param line_colors: A list of line colors, where each marker color corresponds to each data set. This parameter has a default color lists that can accomodate 18 different data sets. The user can override the default colors with a list of their own. Potential colors can be found at :href `colors<https://matplotlib.org/stable/gallery/color/named_colors.html>` :param line_weight: The weight corresponding to the line thickness, defaulted to 2.0 :param fill_apha: The density of the marker fill. Defaulted to 0.7 :param x_label: The x axis label,defaulted to ' ' :param y_label: The y axis label, defaulted to ' ' :param title: The plot title, defaulted to ' ' :param label_pos: The position of the legend in the plot. Defaulted to 'upper right' :param x_scale: 'LOG' or 'LIN', defaulted to 'LIN' :param y_scale: 'LOG' or 'LIN', defaulted to 'LIN' :param plot_name: The name of the file containing the plot if the plot is to be saved. Defaulted to 'NULL' :param save: True if the plot is to be saved, False if the plot is to be shown and not saved. Defaulted to False :param label_font_size: The label font size, defaulted to 18 :param tick_font_size: The tick font size, defaulted to 18 :param title_font_size: The title font size, defaulted to 24 :param marker_size: The size of the marker, defaulted to 35 :param marker_edge_width: The thickness of the line outlining each marker. Defaulted to 0.8 :param grid: True if a grid overlaid on the plot is desired, False if not :param grid_color: Defaulted to 'grey' :grid_style: Defaulted to '-' This method will plot used defined dataframe columns for the x and y axis of a 2-d plot as a line plot. .. code-block:: python > length = 20 > x = np.linspace(0, 20, num=20) > linear = x > squared = x ** 2.0 > # create dataframe > dictionary = {'x': x, 'linear': linear, 'squared': squared} > df = pd.DataFrame(dictionary) > # plot data > obj = MatPlotDataFrame(df) > x_headers = ['x', 'x'] > y_headers = ['linear', 'squared'] > obj.line_plot_columns(x_headers, y_headers, y_headers, x_label='x-axis', y_label='y-axis', title='Test', style_name='default',marker_colors=['red', 'green'], fill_alpha=0.7, marker_style=['o', '^'], label_pos='upper left', grid=False, save=True, plot_name=plt_name) .. image:: line_scatter_test2.eps :align: center """ # Error checking if line_colors[0] == 'None': line_colors = self.colors if len(line_colors) < len(labels): msg1 = 'FATAL ERROR: The length of the marker color list must be as ' msg2 = 'large or larger than the size of the column values' sys.exit(msg + ms2) if save and plot_name == 'NULL': warnings.warn('if save is True then plot name cannot be NULL') if y_scale != 'LOG' and y_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') if x_scale != 'LOG' and x_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') # begin plot plt.rcParams.update({'figure.autolayout': True}) plt.style.use(style_name) fig, td_plot = plt.subplots() rc('xtick', labelsize=tick_font_size) rc('ytick', labelsize=tick_font_size) td_plot.set_xlabel(x_label, fontsize=label_font_size) td_plot.set_ylabel(y_label, fontsize=label_font_size) if title != 'NULL': td_plot.set_title(title, fontsize=title_font_size) if x_scale.upper() == 'LOG': td_plot.set_xscale('log') if y_scale.upper() == 'LOG': td_plot.set_yscale('log') for i in range(len(x_headers)): td_plot.plot(self.df[x_headers[i]], self.df[y_headers[i]], label=labels[i], linestyle=line_style, color=line_colors[i], linewidth=line_weight) plt.legend(loc=label_pos) if grid: plt.grid(color=grid_color, linestyle=grid_style) if not save: plt.show() else: plt.savefig(plot_name) plt.close() # -------------------------------------------------------------------------------- def timedate_plot_parse_column(self, x_header: str, y_header: str, parsing_header: str, column_values: List[str], style_name: str='default', line_colors: List[str]=['None'], line_weight: np.float32=2.0, fill_alpha: np.float32=0.7, line_style: str='-', x_label: str='', y_label: str='', title: str='', label_pos: str='upper right', x_scale: str='LIN', y_scale: str='LIN', plot_name: str='NULL', save: bool=False, label_font_size: int=18, tick_font_size: int=18, title_font_size: int=24, marker_size: int=35, marker_edge_width: np.float32=0.8, grid: bool=False, grid_style='-', grid_color='grey'): """ :param x_header: The title of the dataframe column containing the x-axis data sets. It is assumes that the x axis is the datetime axis for this plot. :param y_header: The title of the dataframe column containing the y-axis data sets :param parsing_header: The title of the dataframe column containing the values which will be used to parse the dataframe into one or multiple data sets :param column_values: The values contained in the parsing_header column that will be used to parse the data set into multiple data sets :param style_name: The name of the matplotlib style that will be used to format the plot. Defaulted to 'default'. Possible styles can be found at :href `styles<https://matplotlib.org/stable/api/style_api.html>` :param line_colors: A list of line colors, where each marker color corresponds to each data set. This parameter has a default color lists that can accomodate 18 different data sets. The user can override the default colors with a list of their own. Potential colors can be found at :href `colors<https://matplotlib.org/stable/gallery/color/named_colors.html>` :param line_weight: The weight corresponding to the line thickness, defaulted to 2.0 :param fill_apha: The density of the marker fill. Defaulted to 0.7 :param x_label: The x axis label,defaulted to ' ' :param y_label: The y axis label, defaulted to ' ' :param title: The plot title, defaulted to ' ' :param label_pos: The position of the legend in the plot. Defaulted to 'upper right' :param x_scale: 'LOG' or 'LIN', defaulted to 'LIN' :param y_scale: 'LOG' or 'LIN', defaulted to 'LIN' :param plot_name: The name of the file containing the plot if the plot is to be saved. Defaulted to 'NULL' :param save: True if the plot is to be saved, False if the plot is to be shown and not saved. Defaulted to False :param label_font_size: The label font size, defaulted to 18 :param tick_font_size: The tick font size, defaulted to 18 :param title_font_size: The title font size, defaulted to 24 :param marker_size: The size of the marker, defaulted to 35 :param marker_edge_width: The thickness of the line outlining each marker. Defaulted to 0.8 :param grid: True if a grid overlaid on the plot is desired, False if not :param grid_color: Defaulted to 'grey' :grid_style: Defaulted to '-' This method will parse a dataframe column based on a user specified value or list of values, and plot the data in a user specified x and y axis column based on filter data. As an example, consider a dataframe with the following columnar data structure. .. code-block:: python > length = 20 > x = np.linspace(0, length, num=length) > linear = x > squared = x ** 2.0 > lin = np.repeat('linear', length) > sq = np.repeat('squared', length) > # Combine arrays into one > x = np.hstack((x, x)) > y = np.hstack((linear, squared)) > power = np.hstack((lin, sq)) > # Create dataframe > dictionary = {'x': x, 'y': y, 'power': power} > df = pd.DataFrame(dictionary) > # Plot data > obj = MatPlotDataFrame(df) > parsing_header = 'power' > column_values = ['linear', 'squared'] obj.line_plot_filter_column('x', 'y', parsing_header, column_values, marker_colors=['red', 'green'], marker_style=['o', '^'], label_pos='upper left') .. image:: line_scatter_test1.eps :align: center """ max_date = self.df[x_header].max() min_date = self.df[x_header].min() diff = (max_date - min_date) / np.timedelta64(1, 'D') df_list = [self.df[self.df[parsing_header] == col_val] for col_val in column_values] df_list = [df.set_index(x_header) for df in df_list] # Error checking if line_colors[0] == 'None': line_colors = self.colors if len(line_colors) < len(column_values): msg1 = 'FATAL ERROR: The length of the marker color list must be as ' msg2 = 'large or larger than the size of the column values' sys.exit(msg + ms2) if save and plot_name == 'NULL': warnings.warn('if save is True then plot name cannot be NULL') if y_scale != 'LOG' and y_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') if x_scale != 'LOG' and x_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') # begin plot plt.rcParams.update({'figure.autolayout': True}) plt.style.use(style_name) fig, td_plot = plt.subplots() rc('xtick', labelsize=tick_font_size) rc('ytick', labelsize=tick_font_size) td_plot.set_xlabel(x_label, fontsize=label_font_size) td_plot.set_ylabel(y_label, fontsize=label_font_size) if title != 'NULL': td_plot.set_title(title, fontsize=title_font_size) if x_scale.upper() == 'LOG': td_plot.set_xscale('log') if y_scale.upper() == 'LOG': td_plot.set_yscale('log') if diff <= 2: myfmt = mdates.DateFormatter('%H') td_plot.xaxis.set_major_locator(plt.MaxNLocator(6)) elif diff <= 15: myfmt = mdates.DateFormatter('%b-%d') td_plot.xaxis.set_major_locator(plt.MaxNLocator(6)) elif diff <= 180: myfmt = mdates.DateFormatter('%b-%Y') td_plot.xaxis.set_major_locator(plt.MaxNLocator(5)) elif diff <= 2191: myfmt = mdates.DateFormatter('%Y') td_plot.xaxis.set_major_locator(plt.MaxNLocator(5)) else: myfmt = mdates.DateFormatter('%Y') td_plot.xaxis.set_major_locator(plt.MaxNLocator(5)) td_plot.xaxis.set_major_formatter(myfmt) for i in range(len(df_list)): td_plot.plot(df_list[i].index, df_list[i][y_header], label=column_values[i], linestyle=line_style, color=line_colors[i], linewidth=line_weight) plt.legend(loc=label_pos) if grid: plt.grid(color=grid_color, linestyle=grid_style) if not save: plt.show() else: plt.savefig(plot_name) plt.close() # -------------------------------------------------------------------------------- def timedate_plot_columns(self, x_headers: str, y_headers: str, labels: List[str], style_name: str='default', line_colors: List[str]=['None'], line_weight: np.float32=2.0, fill_alpha: np.float32=0.7, line_style: str='-', x_label: str='', y_label: str='', title: str='', label_pos: str='upper right', x_scale: str='LIN', y_scale: str='LIN', plot_name: str='NULL', save: bool=False, label_font_size: int=18, tick_font_size: int=18, title_font_size: int=24, marker_size: int=35, marker_edge_width: np.float32=0.8, grid: bool=False, grid_style='-', grid_color='grey'): """ :param x_headers: The title of the dataframe column containing the x-axis data sets. It is assumes that the x axis is the datetime axis for this plot. :param y_headers: The title of the dataframe column containing the y-axis data sets :param labels: A list of the labels to use for each curve in the legend :param style_name: The name of the matplotlib style that will be used to format the plot. Defaulted to 'default'. Possible styles can be found at :href `styles<https://matplotlib.org/stable/api/style_api.html>` :param line_colors: A list of line colors, where each marker color corresponds to each data set. This parameter has a default color lists that can accomodate 18 different data sets. The user can override the default colors with a list of their own. Potential colors can be found at :href `colors<https://matplotlib.org/stable/gallery/color/named_colors.html>` :param line_weight: The weight corresponding to the line thickness, defaulted to 2.0 :param fill_apha: The density of the marker fill. Defaulted to 0.7 :param x_label: The x axis label,defaulted to ' ' :param y_label: The y axis label, defaulted to ' ' :param title: The plot title, defaulted to ' ' :param label_pos: The position of the legend in the plot. Defaulted to 'upper right' :param x_scale: 'LOG' or 'LIN', defaulted to 'LIN' :param y_scale: 'LOG' or 'LIN', defaulted to 'LIN' :param plot_name: The name of the file containing the plot if the plot is to be saved. Defaulted to 'NULL' :param save: True if the plot is to be saved, False if the plot is to be shown and not saved. Defaulted to False :param label_font_size: The label font size, defaulted to 18 :param tick_font_size: The tick font size, defaulted to 18 :param title_font_size: The title font size, defaulted to 24 :param marker_size: The size of the marker, defaulted to 35 :param marker_edge_width: The thickness of the line outlining each marker. Defaulted to 0.8 :param grid: True if a grid overlaid on the plot is desired, False if not :param grid_color: Defaulted to 'grey' :grid_style: Defaulted to '-' This method will parse a dataframe column based on a user specified value or list of values, and plot the data in a user specified x and y axis column based on filter data. As an example, consider a dataframe with the following columnar data structure. .. code-block:: python > length = 20 > x = np.linspace(0, length, num=length) > linear = x > squared = x ** 2.0 > lin = np.repeat('linear', length) > sq = np.repeat('squared', length) > # Combine arrays into one > x = np.hstack((x, x)) > y = np.hstack((linear, squared)) > power = np.hstack((lin, sq)) > # Create dataframe > dictionary = {'x': x, 'y': y, 'power': power} > df = pd.DataFrame(dictionary) > # Plot data > obj = MatPlotDataFrame(df) > parsing_header = 'power' > column_values = ['linear', 'squared'] obj.line_plot_filter_column('x', 'y', parsing_header, column_values, marker_colors=['red', 'green'], marker_style=['o', '^'], label_pos='upper left') .. image:: line_scatter_test1.eps :align: center """ diff = 0 for i in range(len(x_headers)): max_date = self.df[x_headers[i]].max() min_date = self.df[x_headers[i]].min() delta = (max_date - min_date) / np.timedelta64(1, 'D') if delta > diff: diff = delta # Error checking if line_colors[0] == 'None': line_colors = self.colors if len(line_colors) < len(x_headers): msg1 = 'FATAL ERROR: The length of the marker color list must be as ' msg2 = 'large or larger than the size of the column values' sys.exit(msg + ms2) if save and plot_name == 'NULL': warnings.warn('if save is True then plot name cannot be NULL') if y_scale != 'LOG' and y_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') if x_scale != 'LOG' and x_scale != 'LIN': warnings.warn('y_scale must be set to LOG or LIN') # begin plot plt.rcParams.update({'figure.autolayout': True}) plt.style.use(style_name) fig, td_plot = plt.subplots() rc('xtick', labelsize=tick_font_size) rc('ytick', labelsize=tick_font_size) td_plot.set_xlabel(x_label, fontsize=label_font_size) td_plot.set_ylabel(y_label, fontsize=label_font_size) if title != 'NULL': td_plot.set_title(title, fontsize=title_font_size) if x_scale.upper() == 'LOG': td_plot.set_xscale('log') if y_scale.upper() == 'LOG': td_plot.set_yscale('log') if diff <= 2: myfmt = mdates.DateFormatter('%H') td_plot.xaxis.set_major_locator(plt.MaxNLocator(6)) elif diff <= 15: myfmt = mdates.DateFormatter('%b-%d') td_plot.xaxis.set_major_locator(plt.MaxNLocator(6)) elif diff <= 180: myfmt = mdates.DateFormatter('%b-%Y') td_plot.xaxis.set_major_locator(plt.MaxNLocator(5)) elif diff <= 2191: myfmt = mdates.DateFormatter('%Y') td_plot.xaxis.set_major_locator(plt.MaxNLocator(5)) else: myfmt = mdates.DateFormatter('%Y') td_plot.xaxis.set_major_locator(plt.MaxNLocator(5)) td_plot.xaxis.set_major_formatter(myfmt) for i in range(len(x_headers)): td_plot.plot(self.df[x_headers[i]], self.df[y_headers[i]], label=labels[i], linestyle=line_style, color=line_colors[i], linewidth=line_weight) plt.legend(loc=label_pos) if grid: plt.grid(color=grid_color, linestyle=grid_style) if not save: plt.show() else: plt.savefig(plot_name) plt.close() # -------------------------------------------------------------------------------- def histogram_plot_parse_column(self, header: str, parsing_header: str, column_values: List[str], x_label: str='', y_label: str='', colors: List[str]=['None'], edge_colors: List[str]=['None'], shading: List[float]=['None'], label_pos: str='upper right', num_bins: int = 50, tick_font_size: int = 18, label_font_size: str = 18, style_name: str = 'default', save: bool = False, plot_name: str = 'NULL', hist_type: str = 'bar', dens: bool = False, title: str = 'NULL', title_font_size: int = 24) -> None: """ :param headers: A string representing the dataframe column that contains the data to be parsed and plotted :param parsing_header: A string representing the dataframe header that contains key phrases that will be used to filter the dataframe for specific data :param column_values: The key phrases in the dataframe column described by the `parsing_header` variable :param x_label: The title for the x axis. Defaulted to '' :param y_label: The title for the y axis. Defaulted to '' :param colors: A list containing the colors that will be used to represent each plot. :param edge_colors: A list of line colors, where each marker color corresponds to each data set. This parameter has a default color lists that can accomodate 18 different data sets. The user can override the default colors with a list of their own. Potential colors can be found at :href `colors<https://matplotlib.org/stable/gallery/color/named_colors.html>`_ :param shading: The density of the fill for each plot, defaulted to 0.7 :param label_pos: The position of the ledgend in the plot. Defaulted to 'upper_right' :param num_bins: The number of bins used to represent the histogram. Defaulted to 50 :param tick_font_size: The font size of the plot ticks. Defaulted to 18 :param label_font_size: The font size of plot labels. Defaulted to 18 :param style_name: The plot style, defaulted to 'default'. Acceptable styles can be found at `matplotlib styles <https://matplotlib.org/3.2.1/gallery/style_sheets/style_sheets_reference.html>`_. :param save: True if the plot is to be saved, False if the plot is only to be shown :param plot_name: The name of the plot, if it is to be saved :param hist_type: {``bar``, ``barstacked``, ``step``, ``stepfilled``} See `histogram <https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.hist.html>`_ for more information. :param dens: If True, the first element of the return tuple will be the counts normalized to form a probability density, i.e., the area (or integral) under the histogram will sum to 1 :param title: The title of the plot to incorporate into the header. Defaulted to NULL :param title_font_size: The font size for the tile, defaulted to 24 .. code-block:: python > np.random.seed(19680801) > x = np.random.normal(15.0, 3.0, 1000) > y = np.random.normal(20.0, 3.0, 1000) > data = [x, y] > labels = ['one', 'two'] > one = np.repeat('one', len(x)) > two = np.repeat('two', len(x)) > x = np.hstack((x, y)) > y = np.hstack((one, two)) > dictionary = {'data': x, 'type': y} > df = pd.DataFrame(dictionary) > obj = MatPlotDataFrame(df) > obj.histogram_plot_parse_column('data', 'type', labels, x_label='x-axis', y_label='y-axis', shading=[0.9, 0.4], save=True, .. image:: hist2.eps :align: center """ if colors[0] == "None": colors = self.colors if edge_colors[0] == 'None': edge_colors = np.repeat('black', len(column_values)) if shading[0] == "None": shading = np.repeat(0.7, len(column_values)) df_list = [self.df[self.df[parsing_header] == col_val] for col_val in column_values] plt.tight_layout() plt.gcf().subplots_adjust(bottom=0.15) plt.rcParams.update({'figure.autolayout': True}) plt.style.use(style_name) rc('xtick', labelsize=tick_font_size) rc('ytick', labelsize=tick_font_size) plt.xlabel(x_label, fontsize=label_font_size) plt.ylabel(y_label, fontsize=label_font_size) if title != 'NULL': plt.title(title, fontsize=title_font_size) if title != 'NULL': plt.title(title, fontsize=title_font_size) for i in range(len(column_values)): plt.hist(df_list[i][header], bins=num_bins, color=colors[i], edgecolor=edge_colors[i], alpha=shading[i], label=column_values[i], histtype=hist_type, density=dens) plt.legend(loc=label_pos) if not save: plt.show() else: plt.savefig(plot_name) plt.close() # -------------------------------------------------------------------------------- def histogram_plot_columns(self, x_headers: List[str], labels: List[str], x_label: str='', y_label: str='', colors: List[str]=['None'], edge_colors: List[str]=['None'], shading: List[float]=['None'], label_pos: str='upper right', num_bins: int = 50, tick_font_size: int = 18, label_font_size: str = 18, style_name: str = 'default', save: bool = False, plot_name: str = 'NULL', hist_type: str = 'bar', dens: bool = False, title: str = 'NULL', title_font_size: int = 24) -> None: """ :param x_headers: A list of strings representing the dataframe columns to be used for the x axis of a plot :param labels: A list of labels, each label corresponding to each histogram :param x_label: The title for the x axis. Defaulted to '' :param y_label: The title for the y axis. Defaulted to '' :param colors: A list containing the colors that will be used to represent each plot. :param edge_colors: A list of line colors, where each marker color corresponds to each data set. This parameter has a default color lists that can accomodate 18 different data sets. The user can override the default colors with a list of their own. Potential colors can be found at :href `colors<https://matplotlib.org/stable/gallery/color/named_colors.html>`_ :param shading: The density of the fill for each plot, defaulted to 0.7 :param label_pos: The position of the ledgend in the plot. Defaulted to 'upper_right' :param num_bins: The number of bins used to represent the histogram. Defaulted to 50 :param tick_font_size: The font size of the plot ticks. Defaulted to 18 :param label_font_size: The font size of plot labels. Defaulted to 18 :param style_name: The plot style, defaulted to 'default'. Acceptable styles can be found at `matplotlib styles <https://matplotlib.org/3.2.1/gallery/style_sheets/style_sheets_reference.html>`_. :param save: True if the plot is to be saved, False if the plot is only to be shown :param plot_name: The name of the plot, if it is to be saved :param hist_type: {``bar``, ``barstacked``, ``step``, ``stepfilled``} See `histogram <https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.hist.html>`_ for more information. :param dens: If True, the first element of the return tuple will be the counts normalized to form a probability density, i.e., the area (or integral) under the histogram will sum to 1 :param title: The title of the plot to incorporate into the header. Defaulted to NULL :param title_font_size: The font size for the tile, defaulted to 24 .. code-block:: python > np.random.seed(19680801) > x = np.random.normal(15.0, 3.0, 1000) > y = np.random.normal(20.0, 3.0, 1000) > data = [x, y] > labels = ['one', 'two'] > one = np.repeat('one', len(x)) > two = np.repeat('two', len(x)) > x = np.hstack((x, y)) > y = np.hstack((one, two)) > dictionary = {'data': x, 'type': y} > df = pd.DataFrame(dictionary) > obj = MatPlotDataFrame(df) > obj.histogram_plot_parse_column('data', 'type', labels, x_label='x-axis', y_label='y-axis', shading=[0.9, 0.4], save=True, .. image:: hist2.eps :align: center """ if colors[0] == "None": colors = self.colors if edge_colors[0] == 'None': edge_colors = np.repeat('black', len(labels)) if shading[0] == "None": shading = np.repeat(0.7, len(labels)) plt.tight_layout() plt.gcf().subplots_adjust(bottom=0.15) plt.rcParams.update({'figure.autolayout': True}) plt.style.use(style_name) rc('xtick', labelsize=tick_font_size) rc('ytick', labelsize=tick_font_size) plt.xlabel(x_label, fontsize=label_font_size) plt.ylabel(y_label, fontsize=label_font_size) if title != 'NULL': plt.title(title, fontsize=title_font_size) if title != 'NULL': plt.title(title, fontsize=title_font_size) for i in range(len(x_headers)): plt.hist(self.df[x_headers[i]], bins=num_bins, color=colors[i], edgecolor=edge_colors[i], alpha=shading[i], label=labels[i], density=dens) plt.legend(loc=label_pos) if not save: plt.show() else: plt.savefig(plot_name) plt.close() # ================================================================================ # ================================================================================ # eof # TODO Create histogram version of plots # TODO Repeat for Bokeh plots
[ "matplotlib.pyplot.grid", "matplotlib.pyplot.hist", "matplotlib.pyplot.ylabel", "matplotlib.rc", "matplotlib.dates.DayLocator", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.style.use", "matplotlib.pyplot.close", "warnings.warn", "matplotlib.pyplot.savefig", "matplotlib.pyplot.MaxNLocator", "...
[((5218, 5232), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (5230, 5232), True, 'from matplotlib import rc, pyplot as plt\n'), ((5237, 5285), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'figure.autolayout': True}"], {}), "({'figure.autolayout': True})\n", (5256, 5285), True, 'from matplotlib import rc, pyplot as plt\n'), ((5290, 5315), 'matplotlib.pyplot.style.use', 'plt.style.use', (['style_name'], {}), '(style_name)\n', (5303, 5315), True, 'from matplotlib import rc, pyplot as plt\n'), ((5320, 5357), 'matplotlib.rc', 'rc', (['"""xtick"""'], {'labelsize': 'tick_font_size'}), "('xtick', labelsize=tick_font_size)\n", (5322, 5357), False, 'from matplotlib import rc, pyplot as plt\n'), ((5362, 5399), 'matplotlib.rc', 'rc', (['"""ytick"""'], {'labelsize': 'tick_font_size'}), "('ytick', labelsize=tick_font_size)\n", (5364, 5399), False, 'from matplotlib import rc, pyplot as plt\n'), ((6306, 6331), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': 'label_pos'}), '(loc=label_pos)\n', (6316, 6331), True, 'from matplotlib import rc, pyplot as plt\n'), ((11101, 11149), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'figure.autolayout': True}"], {}), "({'figure.autolayout': True})\n", (11120, 11149), True, 'from matplotlib import rc, pyplot as plt\n'), ((11154, 11179), 'matplotlib.pyplot.style.use', 'plt.style.use', (['style_name'], {}), '(style_name)\n', (11167, 11179), True, 'from matplotlib import rc, pyplot as plt\n'), ((11199, 11213), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (11211, 11213), True, 'from matplotlib import rc, pyplot as plt\n'), ((11218, 11255), 'matplotlib.rc', 'rc', (['"""xtick"""'], {'labelsize': 'tick_font_size'}), "('xtick', labelsize=tick_font_size)\n", (11220, 11255), False, 'from matplotlib import rc, pyplot as plt\n'), ((11260, 11297), 'matplotlib.rc', 'rc', (['"""ytick"""'], {'labelsize': 'tick_font_size'}), "('ytick', labelsize=tick_font_size)\n", (11262, 11297), False, 'from matplotlib import rc, pyplot as plt\n'), ((11854, 11879), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': 'label_pos'}), '(loc=label_pos)\n', (11864, 11879), True, 'from matplotlib import rc, pyplot as plt\n'), ((16347, 16395), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'figure.autolayout': True}"], {}), "({'figure.autolayout': True})\n", (16366, 16395), True, 'from matplotlib import rc, pyplot as plt\n'), ((16400, 16425), 'matplotlib.pyplot.style.use', 'plt.style.use', (['style_name'], {}), '(style_name)\n', (16413, 16425), True, 'from matplotlib import rc, pyplot as plt\n'), ((16445, 16459), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (16457, 16459), True, 'from matplotlib import rc, pyplot as plt\n'), ((16464, 16501), 'matplotlib.rc', 'rc', (['"""xtick"""'], {'labelsize': 'tick_font_size'}), "('xtick', labelsize=tick_font_size)\n", (16466, 16501), False, 'from matplotlib import rc, pyplot as plt\n'), ((16506, 16543), 'matplotlib.rc', 'rc', (['"""ytick"""'], {'labelsize': 'tick_font_size'}), "('ytick', labelsize=tick_font_size)\n", (16508, 16543), False, 'from matplotlib import rc, pyplot as plt\n'), ((17092, 17117), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': 'label_pos'}), '(loc=label_pos)\n', (17102, 17117), True, 'from matplotlib import rc, pyplot as plt\n'), ((22170, 22218), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'figure.autolayout': True}"], {}), "({'figure.autolayout': True})\n", (22189, 22218), True, 'from matplotlib import rc, pyplot as plt\n'), ((22223, 22248), 'matplotlib.pyplot.style.use', 'plt.style.use', (['style_name'], {}), '(style_name)\n', (22236, 22248), True, 'from matplotlib import rc, pyplot as plt\n'), ((22268, 22282), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (22280, 22282), True, 'from matplotlib import rc, pyplot as plt\n'), ((22287, 22324), 'matplotlib.rc', 'rc', (['"""xtick"""'], {'labelsize': 'tick_font_size'}), "('xtick', labelsize=tick_font_size)\n", (22289, 22324), False, 'from matplotlib import rc, pyplot as plt\n'), ((22329, 22366), 'matplotlib.rc', 'rc', (['"""ytick"""'], {'labelsize': 'tick_font_size'}), "('ytick', labelsize=tick_font_size)\n", (22331, 22366), False, 'from matplotlib import rc, pyplot as plt\n'), ((22950, 22975), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': 'label_pos'}), '(loc=label_pos)\n', (22960, 22975), True, 'from matplotlib import rc, pyplot as plt\n'), ((27969, 27987), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (27985, 27987), True, 'from matplotlib import rc, pyplot as plt\n'), ((28035, 28083), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'figure.autolayout': True}"], {}), "({'figure.autolayout': True})\n", (28054, 28083), True, 'from matplotlib import rc, pyplot as plt\n'), ((28088, 28113), 'matplotlib.pyplot.style.use', 'plt.style.use', (['style_name'], {}), '(style_name)\n', (28101, 28113), True, 'from matplotlib import rc, pyplot as plt\n'), ((28118, 28155), 'matplotlib.rc', 'rc', (['"""xtick"""'], {'labelsize': 'tick_font_size'}), "('xtick', labelsize=tick_font_size)\n", (28120, 28155), False, 'from matplotlib import rc, pyplot as plt\n'), ((28160, 28197), 'matplotlib.rc', 'rc', (['"""ytick"""'], {'labelsize': 'tick_font_size'}), "('ytick', labelsize=tick_font_size)\n", (28162, 28197), False, 'from matplotlib import rc, pyplot as plt\n'), ((28202, 28247), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['x_label'], {'fontsize': 'label_font_size'}), '(x_label, fontsize=label_font_size)\n', (28212, 28247), True, 'from matplotlib import rc, pyplot as plt\n'), ((28252, 28297), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['y_label'], {'fontsize': 'label_font_size'}), '(y_label, fontsize=label_font_size)\n', (28262, 28297), True, 'from matplotlib import rc, pyplot as plt\n'), ((28580, 28605), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': 'label_pos'}), '(loc=label_pos)\n', (28590, 28605), True, 'from matplotlib import rc, pyplot as plt\n'), ((28687, 28698), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (28696, 28698), True, 'from matplotlib import rc, pyplot as plt\n'), ((5502, 5528), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%d"""'], {}), "('%d')\n", (5522, 5528), True, 'import matplotlib.dates as mdates\n'), ((6357, 6367), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6365, 6367), True, 'from matplotlib import rc, pyplot as plt\n'), ((6386, 6408), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_name'], {}), '(plot_name)\n', (6397, 6408), True, 'from matplotlib import rc, pyplot as plt\n'), ((10207, 10269), 'warnings.warn', 'warnings.warn', (['"""if save is True then plot name cannot be NULL"""'], {}), "('if save is True then plot name cannot be NULL')\n", (10220, 10269), False, 'import warnings\n'), ((10313, 10418), 'warnings.warn', 'warnings.warn', (['"""length of x list of lists is not the same as y list of lists, plot not printed"""'], {}), "(\n 'length of x list of lists is not the same as y list of lists, plot not printed'\n )\n", (10326, 10418), False, 'import warnings\n'), ((10472, 10562), 'warnings.warn', 'warnings.warn', (['"""line colors list not the same length as data lists, plot not printed"""'], {}), "(\n 'line colors list not the same length as data lists, plot not printed')\n", (10485, 10562), False, 'import warnings\n'), ((10620, 10709), 'warnings.warn', 'warnings.warn', (['"""line_style list not the same length as data lists, plot not printed"""'], {}), "(\n 'line_style list not the same length as data lists, plot not printed')\n", (10633, 10709), False, 'import warnings\n'), ((10768, 10858), 'warnings.warn', 'warnings.warn', (['"""line_weight list not the same length as data lists, plot not printed"""'], {}), "(\n 'line_weight list not the same length as data lists, plot not printed')\n", (10781, 10858), False, 'import warnings\n'), ((10923, 10973), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (10936, 10973), False, 'import warnings\n'), ((11028, 11078), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (11041, 11078), False, 'import warnings\n'), ((11905, 11915), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (11913, 11915), True, 'from matplotlib import rc, pyplot as plt\n'), ((11934, 11956), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_name'], {}), '(plot_name)\n', (11945, 11956), True, 'from matplotlib import rc, pyplot as plt\n'), ((15598, 15660), 'warnings.warn', 'warnings.warn', (['"""if save is True then plot name cannot be NULL"""'], {}), "('if save is True then plot name cannot be NULL')\n", (15611, 15660), False, 'import warnings\n'), ((15704, 15809), 'warnings.warn', 'warnings.warn', (['"""length of x list of lists is not the same as y list of lists, plot not printed"""'], {}), "(\n 'length of x list of lists is not the same as y list of lists, plot not printed'\n )\n", (15717, 15809), False, 'import warnings\n'), ((15865, 15955), 'warnings.warn', 'warnings.warn', (['"""line colors list not the same length as data lists, plot not printed"""'], {}), "(\n 'line colors list not the same length as data lists, plot not printed')\n", (15878, 15955), False, 'import warnings\n'), ((16015, 16104), 'warnings.warn', 'warnings.warn', (['"""line_style list not the same length as data lists, plot not printed"""'], {}), "(\n 'line_style list not the same length as data lists, plot not printed')\n", (16028, 16104), False, 'import warnings\n'), ((16169, 16219), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (16182, 16219), False, 'import warnings\n'), ((16274, 16324), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (16287, 16324), False, 'import warnings\n'), ((17143, 17153), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (17151, 17153), True, 'from matplotlib import rc, pyplot as plt\n'), ((17172, 17194), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_name'], {}), '(plot_name)\n', (17183, 17194), True, 'from matplotlib import rc, pyplot as plt\n'), ((21421, 21483), 'warnings.warn', 'warnings.warn', (['"""if save is True then plot name cannot be NULL"""'], {}), "('if save is True then plot name cannot be NULL')\n", (21434, 21483), False, 'import warnings\n'), ((21527, 21632), 'warnings.warn', 'warnings.warn', (['"""length of x list of lists is not the same as y list of lists, plot not printed"""'], {}), "(\n 'length of x list of lists is not the same as y list of lists, plot not printed'\n )\n", (21540, 21632), False, 'import warnings\n'), ((21688, 21778), 'warnings.warn', 'warnings.warn', (['"""line colors list not the same length as data lists, plot not printed"""'], {}), "(\n 'line colors list not the same length as data lists, plot not printed')\n", (21701, 21778), False, 'import warnings\n'), ((21838, 21927), 'warnings.warn', 'warnings.warn', (['"""line_style list not the same length as data lists, plot not printed"""'], {}), "(\n 'line_style list not the same length as data lists, plot not printed')\n", (21851, 21927), False, 'import warnings\n'), ((21992, 22042), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (22005, 22042), False, 'import warnings\n'), ((22097, 22147), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (22110, 22147), False, 'import warnings\n'), ((23001, 23011), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (23009, 23011), True, 'from matplotlib import rc, pyplot as plt\n'), ((23030, 23052), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_name'], {}), '(plot_name)\n', (23041, 23052), True, 'from matplotlib import rc, pyplot as plt\n'), ((27531, 27602), 'warnings.warn', 'warnings.warn', (['"""data list should be the same length as the labels list"""'], {}), "('data list should be the same length as the labels list')\n", (27544, 27602), False, 'import warnings\n'), ((27646, 27717), 'warnings.warn', 'warnings.warn', (['"""data list should be the same length as the colors list"""'], {}), "('data list should be the same length as the colors list')\n", (27659, 27717), False, 'import warnings\n'), ((27766, 27844), 'warnings.warn', 'warnings.warn', (['"""labels list should be the same length as the edge_colors list"""'], {}), "('labels list should be the same length as the edge_colors list')\n", (27779, 27844), False, 'import warnings\n'), ((27889, 27963), 'warnings.warn', 'warnings.warn', (['"""labels list should be the same length as the shading list"""'], {}), "('labels list should be the same length as the shading list')\n", (27902, 27963), False, 'import warnings\n'), ((28330, 28372), 'matplotlib.pyplot.title', 'plt.title', (['title'], {'fontsize': 'title_font_size'}), '(title, fontsize=title_font_size)\n', (28339, 28372), True, 'from matplotlib import rc, pyplot as plt\n'), ((28414, 28562), 'matplotlib.pyplot.hist', 'plt.hist', (['data[i]'], {'bins': 'num_bins', 'color': 'colors[i]', 'edgecolor': 'edge_colors[i]', 'alpha': 'shading[i]', 'label': 'labels[i]', 'histtype': 'hist_type', 'density': 'dens'}), '(data[i], bins=num_bins, color=colors[i], edgecolor=edge_colors[i],\n alpha=shading[i], label=labels[i], histtype=hist_type, density=dens)\n', (28422, 28562), True, 'from matplotlib import rc, pyplot as plt\n'), ((28631, 28641), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (28639, 28641), True, 'from matplotlib import rc, pyplot as plt\n'), ((28660, 28682), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_name'], {}), '(plot_name)\n', (28671, 28682), True, 'from matplotlib import rc, pyplot as plt\n'), ((36372, 36420), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'figure.autolayout': True}"], {}), "({'figure.autolayout': True})\n", (36391, 36420), True, 'from matplotlib import rc, pyplot as plt\n'), ((36429, 36454), 'matplotlib.pyplot.style.use', 'plt.style.use', (['style_name'], {}), '(style_name)\n', (36442, 36454), True, 'from matplotlib import rc, pyplot as plt\n'), ((36478, 36492), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (36490, 36492), True, 'from matplotlib import rc, pyplot as plt\n'), ((36501, 36538), 'matplotlib.rc', 'rc', (['"""xtick"""'], {'labelsize': 'tick_font_size'}), "('xtick', labelsize=tick_font_size)\n", (36503, 36538), False, 'from matplotlib import rc, pyplot as plt\n'), ((36547, 36584), 'matplotlib.rc', 'rc', (['"""ytick"""'], {'labelsize': 'tick_font_size'}), "('ytick', labelsize=tick_font_size)\n", (36549, 36584), False, 'from matplotlib import rc, pyplot as plt\n'), ((37342, 37367), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': 'label_pos'}), '(loc=label_pos)\n', (37352, 37367), True, 'from matplotlib import rc, pyplot as plt\n'), ((37547, 37558), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (37556, 37558), True, 'from matplotlib import rc, pyplot as plt\n'), ((43499, 43547), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'figure.autolayout': True}"], {}), "({'figure.autolayout': True})\n", (43518, 43547), True, 'from matplotlib import rc, pyplot as plt\n'), ((43556, 43581), 'matplotlib.pyplot.style.use', 'plt.style.use', (['style_name'], {}), '(style_name)\n', (43569, 43581), True, 'from matplotlib import rc, pyplot as plt\n'), ((43605, 43619), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (43617, 43619), True, 'from matplotlib import rc, pyplot as plt\n'), ((43628, 43665), 'matplotlib.rc', 'rc', (['"""xtick"""'], {'labelsize': 'tick_font_size'}), "('xtick', labelsize=tick_font_size)\n", (43630, 43665), False, 'from matplotlib import rc, pyplot as plt\n'), ((43674, 43711), 'matplotlib.rc', 'rc', (['"""ytick"""'], {'labelsize': 'tick_font_size'}), "('ytick', labelsize=tick_font_size)\n", (43676, 43711), False, 'from matplotlib import rc, pyplot as plt\n'), ((44469, 44494), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': 'label_pos'}), '(loc=label_pos)\n', (44479, 44494), True, 'from matplotlib import rc, pyplot as plt\n'), ((44674, 44685), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (44683, 44685), True, 'from matplotlib import rc, pyplot as plt\n'), ((50791, 50839), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'figure.autolayout': True}"], {}), "({'figure.autolayout': True})\n", (50810, 50839), True, 'from matplotlib import rc, pyplot as plt\n'), ((50848, 50873), 'matplotlib.pyplot.style.use', 'plt.style.use', (['style_name'], {}), '(style_name)\n', (50861, 50873), True, 'from matplotlib import rc, pyplot as plt\n'), ((50897, 50911), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (50909, 50911), True, 'from matplotlib import rc, pyplot as plt\n'), ((50920, 50957), 'matplotlib.rc', 'rc', (['"""xtick"""'], {'labelsize': 'tick_font_size'}), "('xtick', labelsize=tick_font_size)\n", (50922, 50957), False, 'from matplotlib import rc, pyplot as plt\n'), ((50966, 51003), 'matplotlib.rc', 'rc', (['"""ytick"""'], {'labelsize': 'tick_font_size'}), "('ytick', labelsize=tick_font_size)\n", (50968, 51003), False, 'from matplotlib import rc, pyplot as plt\n'), ((51629, 51654), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': 'label_pos'}), '(loc=label_pos)\n', (51639, 51654), True, 'from matplotlib import rc, pyplot as plt\n'), ((51834, 51845), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (51843, 51845), True, 'from matplotlib import rc, pyplot as plt\n'), ((57108, 57156), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'figure.autolayout': True}"], {}), "({'figure.autolayout': True})\n", (57127, 57156), True, 'from matplotlib import rc, pyplot as plt\n'), ((57165, 57190), 'matplotlib.pyplot.style.use', 'plt.style.use', (['style_name'], {}), '(style_name)\n', (57178, 57190), True, 'from matplotlib import rc, pyplot as plt\n'), ((57214, 57228), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (57226, 57228), True, 'from matplotlib import rc, pyplot as plt\n'), ((57237, 57274), 'matplotlib.rc', 'rc', (['"""xtick"""'], {'labelsize': 'tick_font_size'}), "('xtick', labelsize=tick_font_size)\n", (57239, 57274), False, 'from matplotlib import rc, pyplot as plt\n'), ((57283, 57320), 'matplotlib.rc', 'rc', (['"""ytick"""'], {'labelsize': 'tick_font_size'}), "('ytick', labelsize=tick_font_size)\n", (57285, 57320), False, 'from matplotlib import rc, pyplot as plt\n'), ((57944, 57969), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': 'label_pos'}), '(loc=label_pos)\n', (57954, 57969), True, 'from matplotlib import rc, pyplot as plt\n'), ((58149, 58160), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (58158, 58160), True, 'from matplotlib import rc, pyplot as plt\n'), ((64598, 64646), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'figure.autolayout': True}"], {}), "({'figure.autolayout': True})\n", (64617, 64646), True, 'from matplotlib import rc, pyplot as plt\n'), ((64655, 64680), 'matplotlib.pyplot.style.use', 'plt.style.use', (['style_name'], {}), '(style_name)\n', (64668, 64680), True, 'from matplotlib import rc, pyplot as plt\n'), ((64704, 64718), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (64716, 64718), True, 'from matplotlib import rc, pyplot as plt\n'), ((64727, 64764), 'matplotlib.rc', 'rc', (['"""xtick"""'], {'labelsize': 'tick_font_size'}), "('xtick', labelsize=tick_font_size)\n", (64729, 64764), False, 'from matplotlib import rc, pyplot as plt\n'), ((64773, 64810), 'matplotlib.rc', 'rc', (['"""ytick"""'], {'labelsize': 'tick_font_size'}), "('ytick', labelsize=tick_font_size)\n", (64775, 64810), False, 'from matplotlib import rc, pyplot as plt\n'), ((66163, 66188), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': 'label_pos'}), '(loc=label_pos)\n', (66173, 66188), True, 'from matplotlib import rc, pyplot as plt\n'), ((66368, 66379), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (66377, 66379), True, 'from matplotlib import rc, pyplot as plt\n'), ((72353, 72401), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'figure.autolayout': True}"], {}), "({'figure.autolayout': True})\n", (72372, 72401), True, 'from matplotlib import rc, pyplot as plt\n'), ((72410, 72435), 'matplotlib.pyplot.style.use', 'plt.style.use', (['style_name'], {}), '(style_name)\n', (72423, 72435), True, 'from matplotlib import rc, pyplot as plt\n'), ((72459, 72473), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (72471, 72473), True, 'from matplotlib import rc, pyplot as plt\n'), ((72482, 72519), 'matplotlib.rc', 'rc', (['"""xtick"""'], {'labelsize': 'tick_font_size'}), "('xtick', labelsize=tick_font_size)\n", (72484, 72519), False, 'from matplotlib import rc, pyplot as plt\n'), ((72528, 72565), 'matplotlib.rc', 'rc', (['"""ytick"""'], {'labelsize': 'tick_font_size'}), "('ytick', labelsize=tick_font_size)\n", (72530, 72565), False, 'from matplotlib import rc, pyplot as plt\n'), ((73921, 73946), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': 'label_pos'}), '(loc=label_pos)\n', (73931, 73946), True, 'from matplotlib import rc, pyplot as plt\n'), ((74126, 74137), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (74135, 74137), True, 'from matplotlib import rc, pyplot as plt\n'), ((79108, 79126), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (79124, 79126), True, 'from matplotlib import rc, pyplot as plt\n'), ((79182, 79230), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'figure.autolayout': True}"], {}), "({'figure.autolayout': True})\n", (79201, 79230), True, 'from matplotlib import rc, pyplot as plt\n'), ((79239, 79264), 'matplotlib.pyplot.style.use', 'plt.style.use', (['style_name'], {}), '(style_name)\n', (79252, 79264), True, 'from matplotlib import rc, pyplot as plt\n'), ((79273, 79310), 'matplotlib.rc', 'rc', (['"""xtick"""'], {'labelsize': 'tick_font_size'}), "('xtick', labelsize=tick_font_size)\n", (79275, 79310), False, 'from matplotlib import rc, pyplot as plt\n'), ((79319, 79356), 'matplotlib.rc', 'rc', (['"""ytick"""'], {'labelsize': 'tick_font_size'}), "('ytick', labelsize=tick_font_size)\n", (79321, 79356), False, 'from matplotlib import rc, pyplot as plt\n'), ((79365, 79410), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['x_label'], {'fontsize': 'label_font_size'}), '(x_label, fontsize=label_font_size)\n', (79375, 79410), True, 'from matplotlib import rc, pyplot as plt\n'), ((79419, 79464), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['y_label'], {'fontsize': 'label_font_size'}), '(y_label, fontsize=label_font_size)\n', (79429, 79464), True, 'from matplotlib import rc, pyplot as plt\n'), ((79883, 79908), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': 'label_pos'}), '(loc=label_pos)\n', (79893, 79908), True, 'from matplotlib import rc, pyplot as plt\n'), ((80010, 80021), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (80019, 80021), True, 'from matplotlib import rc, pyplot as plt\n'), ((84532, 84550), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (84548, 84550), True, 'from matplotlib import rc, pyplot as plt\n'), ((84606, 84654), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'figure.autolayout': True}"], {}), "({'figure.autolayout': True})\n", (84625, 84654), True, 'from matplotlib import rc, pyplot as plt\n'), ((84663, 84688), 'matplotlib.pyplot.style.use', 'plt.style.use', (['style_name'], {}), '(style_name)\n', (84676, 84688), True, 'from matplotlib import rc, pyplot as plt\n'), ((84697, 84734), 'matplotlib.rc', 'rc', (['"""xtick"""'], {'labelsize': 'tick_font_size'}), "('xtick', labelsize=tick_font_size)\n", (84699, 84734), False, 'from matplotlib import rc, pyplot as plt\n'), ((84743, 84780), 'matplotlib.rc', 'rc', (['"""ytick"""'], {'labelsize': 'tick_font_size'}), "('ytick', labelsize=tick_font_size)\n", (84745, 84780), False, 'from matplotlib import rc, pyplot as plt\n'), ((84789, 84834), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['x_label'], {'fontsize': 'label_font_size'}), '(x_label, fontsize=label_font_size)\n', (84799, 84834), True, 'from matplotlib import rc, pyplot as plt\n'), ((84843, 84888), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['y_label'], {'fontsize': 'label_font_size'}), '(y_label, fontsize=label_font_size)\n', (84853, 84888), True, 'from matplotlib import rc, pyplot as plt\n'), ((85303, 85328), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': 'label_pos'}), '(loc=label_pos)\n', (85313, 85328), True, 'from matplotlib import rc, pyplot as plt\n'), ((85430, 85441), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (85439, 85441), True, 'from matplotlib import rc, pyplot as plt\n'), ((5569, 5588), 'matplotlib.dates.DayLocator', 'mdates.DayLocator', ([], {}), '()\n', (5586, 5588), True, 'import matplotlib.dates as mdates\n'), ((5628, 5657), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%b-%y"""'], {}), "('%b-%y')\n", (5648, 5657), True, 'import matplotlib.dates as mdates\n'), ((5747, 5776), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%b-%y"""'], {}), "('%b-%y')\n", (5767, 5776), True, 'import matplotlib.dates as mdates\n'), ((27992, 28001), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (27999, 28001), True, 'from matplotlib import rc, pyplot as plt\n'), ((36053, 36115), 'warnings.warn', 'warnings.warn', (['"""if save is True then plot name cannot be NULL"""'], {}), "('if save is True then plot name cannot be NULL')\n", (36066, 36115), False, 'import warnings\n'), ((36178, 36228), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (36191, 36228), False, 'import warnings\n'), ((36291, 36341), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (36304, 36341), False, 'import warnings\n'), ((37397, 37445), 'matplotlib.pyplot.grid', 'plt.grid', ([], {'color': 'grid_color', 'linestyle': 'grid_style'}), '(color=grid_color, linestyle=grid_style)\n', (37405, 37445), True, 'from matplotlib import rc, pyplot as plt\n'), ((37479, 37489), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (37487, 37489), True, 'from matplotlib import rc, pyplot as plt\n'), ((37516, 37538), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_name'], {}), '(plot_name)\n', (37527, 37538), True, 'from matplotlib import rc, pyplot as plt\n'), ((43180, 43242), 'warnings.warn', 'warnings.warn', (['"""if save is True then plot name cannot be NULL"""'], {}), "('if save is True then plot name cannot be NULL')\n", (43193, 43242), False, 'import warnings\n'), ((43305, 43355), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (43318, 43355), False, 'import warnings\n'), ((43418, 43468), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (43431, 43468), False, 'import warnings\n'), ((44524, 44572), 'matplotlib.pyplot.grid', 'plt.grid', ([], {'color': 'grid_color', 'linestyle': 'grid_style'}), '(color=grid_color, linestyle=grid_style)\n', (44532, 44572), True, 'from matplotlib import rc, pyplot as plt\n'), ((44606, 44616), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (44614, 44616), True, 'from matplotlib import rc, pyplot as plt\n'), ((44643, 44665), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_name'], {}), '(plot_name)\n', (44654, 44665), True, 'from matplotlib import rc, pyplot as plt\n'), ((50472, 50534), 'warnings.warn', 'warnings.warn', (['"""if save is True then plot name cannot be NULL"""'], {}), "('if save is True then plot name cannot be NULL')\n", (50485, 50534), False, 'import warnings\n'), ((50597, 50647), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (50610, 50647), False, 'import warnings\n'), ((50710, 50760), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (50723, 50760), False, 'import warnings\n'), ((51684, 51732), 'matplotlib.pyplot.grid', 'plt.grid', ([], {'color': 'grid_color', 'linestyle': 'grid_style'}), '(color=grid_color, linestyle=grid_style)\n', (51692, 51732), True, 'from matplotlib import rc, pyplot as plt\n'), ((51766, 51776), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (51774, 51776), True, 'from matplotlib import rc, pyplot as plt\n'), ((51803, 51825), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_name'], {}), '(plot_name)\n', (51814, 51825), True, 'from matplotlib import rc, pyplot as plt\n'), ((56789, 56851), 'warnings.warn', 'warnings.warn', (['"""if save is True then plot name cannot be NULL"""'], {}), "('if save is True then plot name cannot be NULL')\n", (56802, 56851), False, 'import warnings\n'), ((56914, 56964), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (56927, 56964), False, 'import warnings\n'), ((57027, 57077), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (57040, 57077), False, 'import warnings\n'), ((57999, 58047), 'matplotlib.pyplot.grid', 'plt.grid', ([], {'color': 'grid_color', 'linestyle': 'grid_style'}), '(color=grid_color, linestyle=grid_style)\n', (58007, 58047), True, 'from matplotlib import rc, pyplot as plt\n'), ((58081, 58091), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (58089, 58091), True, 'from matplotlib import rc, pyplot as plt\n'), ((58118, 58140), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_name'], {}), '(plot_name)\n', (58129, 58140), True, 'from matplotlib import rc, pyplot as plt\n'), ((63692, 63714), 'numpy.timedelta64', 'np.timedelta64', (['(1)', '"""D"""'], {}), "(1, 'D')\n", (63706, 63714), True, 'import numpy as np\n'), ((64280, 64342), 'warnings.warn', 'warnings.warn', (['"""if save is True then plot name cannot be NULL"""'], {}), "('if save is True then plot name cannot be NULL')\n", (64293, 64342), False, 'import warnings\n'), ((64405, 64455), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (64418, 64455), False, 'import warnings\n'), ((64518, 64568), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (64531, 64568), False, 'import warnings\n'), ((65227, 65253), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%H"""'], {}), "('%H')\n", (65247, 65253), True, 'import matplotlib.dates as mdates\n'), ((66218, 66266), 'matplotlib.pyplot.grid', 'plt.grid', ([], {'color': 'grid_color', 'linestyle': 'grid_style'}), '(color=grid_color, linestyle=grid_style)\n', (66226, 66266), True, 'from matplotlib import rc, pyplot as plt\n'), ((66300, 66310), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (66308, 66310), True, 'from matplotlib import rc, pyplot as plt\n'), ((66337, 66359), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_name'], {}), '(plot_name)\n', (66348, 66359), True, 'from matplotlib import rc, pyplot as plt\n'), ((72035, 72097), 'warnings.warn', 'warnings.warn', (['"""if save is True then plot name cannot be NULL"""'], {}), "('if save is True then plot name cannot be NULL')\n", (72048, 72097), False, 'import warnings\n'), ((72160, 72210), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (72173, 72210), False, 'import warnings\n'), ((72273, 72323), 'warnings.warn', 'warnings.warn', (['"""y_scale must be set to LOG or LIN"""'], {}), "('y_scale must be set to LOG or LIN')\n", (72286, 72323), False, 'import warnings\n'), ((72982, 73008), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%H"""'], {}), "('%H')\n", (73002, 73008), True, 'import matplotlib.dates as mdates\n'), ((73976, 74024), 'matplotlib.pyplot.grid', 'plt.grid', ([], {'color': 'grid_color', 'linestyle': 'grid_style'}), '(color=grid_color, linestyle=grid_style)\n', (73984, 74024), True, 'from matplotlib import rc, pyplot as plt\n'), ((74058, 74068), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (74066, 74068), True, 'from matplotlib import rc, pyplot as plt\n'), ((74095, 74117), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_name'], {}), '(plot_name)\n', (74106, 74117), True, 'from matplotlib import rc, pyplot as plt\n'), ((79505, 79547), 'matplotlib.pyplot.title', 'plt.title', (['title'], {'fontsize': 'title_font_size'}), '(title, fontsize=title_font_size)\n', (79514, 79547), True, 'from matplotlib import rc, pyplot as plt\n'), ((79592, 79634), 'matplotlib.pyplot.title', 'plt.title', (['title'], {'fontsize': 'title_font_size'}), '(title, fontsize=title_font_size)\n', (79601, 79634), True, 'from matplotlib import rc, pyplot as plt\n'), ((79691, 79863), 'matplotlib.pyplot.hist', 'plt.hist', (['df_list[i][header]'], {'bins': 'num_bins', 'color': 'colors[i]', 'edgecolor': 'edge_colors[i]', 'alpha': 'shading[i]', 'label': 'column_values[i]', 'histtype': 'hist_type', 'density': 'dens'}), '(df_list[i][header], bins=num_bins, color=colors[i], edgecolor=\n edge_colors[i], alpha=shading[i], label=column_values[i], histtype=\n hist_type, density=dens)\n', (79699, 79863), True, 'from matplotlib import rc, pyplot as plt\n'), ((79942, 79952), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (79950, 79952), True, 'from matplotlib import rc, pyplot as plt\n'), ((79979, 80001), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_name'], {}), '(plot_name)\n', (79990, 80001), True, 'from matplotlib import rc, pyplot as plt\n'), ((84929, 84971), 'matplotlib.pyplot.title', 'plt.title', (['title'], {'fontsize': 'title_font_size'}), '(title, fontsize=title_font_size)\n', (84938, 84971), True, 'from matplotlib import rc, pyplot as plt\n'), ((85016, 85058), 'matplotlib.pyplot.title', 'plt.title', (['title'], {'fontsize': 'title_font_size'}), '(title, fontsize=title_font_size)\n', (85025, 85058), True, 'from matplotlib import rc, pyplot as plt\n'), ((85112, 85255), 'matplotlib.pyplot.hist', 'plt.hist', (['self.df[x_headers[i]]'], {'bins': 'num_bins', 'color': 'colors[i]', 'edgecolor': 'edge_colors[i]', 'alpha': 'shading[i]', 'label': 'labels[i]', 'density': 'dens'}), '(self.df[x_headers[i]], bins=num_bins, color=colors[i], edgecolor=\n edge_colors[i], alpha=shading[i], label=labels[i], density=dens)\n', (85120, 85255), True, 'from matplotlib import rc, pyplot as plt\n'), ((85362, 85372), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (85370, 85372), True, 'from matplotlib import rc, pyplot as plt\n'), ((85399, 85421), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_name'], {}), '(plot_name)\n', (85410, 85421), True, 'from matplotlib import rc, pyplot as plt\n'), ((4913, 4955), 'datetime.datetime.strptime', 'datetime.strptime', (['date_string', '"""%Y-%m-%d"""'], {}), "(date_string, '%Y-%m-%d')\n", (4930, 4955), False, 'from datetime import datetime\n'), ((5698, 5719), 'matplotlib.dates.MonthLocator', 'mdates.MonthLocator', ([], {}), '()\n', (5717, 5719), True, 'import matplotlib.dates as mdates\n'), ((5817, 5835), 'matplotlib.pyplot.MaxNLocator', 'plt.MaxNLocator', (['(4)'], {}), '(4)\n', (5832, 5835), True, 'from matplotlib import rc, pyplot as plt\n'), ((65298, 65316), 'matplotlib.pyplot.MaxNLocator', 'plt.MaxNLocator', (['(6)'], {}), '(6)\n', (65313, 65316), True, 'from matplotlib import rc, pyplot as plt\n'), ((65363, 65392), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%b-%d"""'], {}), "('%b-%d')\n", (65383, 65392), True, 'import matplotlib.dates as mdates\n'), ((71567, 71589), 'numpy.timedelta64', 'np.timedelta64', (['(1)', '"""D"""'], {}), "(1, 'D')\n", (71581, 71589), True, 'import numpy as np\n'), ((73053, 73071), 'matplotlib.pyplot.MaxNLocator', 'plt.MaxNLocator', (['(6)'], {}), '(6)\n', (73068, 73071), True, 'from matplotlib import rc, pyplot as plt\n'), ((73118, 73147), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%b-%d"""'], {}), "('%b-%d')\n", (73138, 73147), True, 'import matplotlib.dates as mdates\n'), ((79135, 79144), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (79142, 79144), True, 'from matplotlib import rc, pyplot as plt\n'), ((84559, 84568), 'matplotlib.pyplot.gcf', 'plt.gcf', ([], {}), '()\n', (84566, 84568), True, 'from matplotlib import rc, pyplot as plt\n'), ((65437, 65455), 'matplotlib.pyplot.MaxNLocator', 'plt.MaxNLocator', (['(6)'], {}), '(6)\n', (65452, 65455), True, 'from matplotlib import rc, pyplot as plt\n'), ((65503, 65532), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%b-%Y"""'], {}), "('%b-%Y')\n", (65523, 65532), True, 'import matplotlib.dates as mdates\n'), ((73192, 73210), 'matplotlib.pyplot.MaxNLocator', 'plt.MaxNLocator', (['(6)'], {}), '(6)\n', (73207, 73210), True, 'from matplotlib import rc, pyplot as plt\n'), ((73258, 73287), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%b-%Y"""'], {}), "('%b-%Y')\n", (73278, 73287), True, 'import matplotlib.dates as mdates\n'), ((65577, 65595), 'matplotlib.pyplot.MaxNLocator', 'plt.MaxNLocator', (['(5)'], {}), '(5)\n', (65592, 65595), True, 'from matplotlib import rc, pyplot as plt\n'), ((65644, 65670), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%Y"""'], {}), "('%Y')\n", (65664, 65670), True, 'import matplotlib.dates as mdates\n'), ((65769, 65795), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%Y"""'], {}), "('%Y')\n", (65789, 65795), True, 'import matplotlib.dates as mdates\n'), ((73332, 73350), 'matplotlib.pyplot.MaxNLocator', 'plt.MaxNLocator', (['(5)'], {}), '(5)\n', (73347, 73350), True, 'from matplotlib import rc, pyplot as plt\n'), ((73399, 73425), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%Y"""'], {}), "('%Y')\n", (73419, 73425), True, 'import matplotlib.dates as mdates\n'), ((73524, 73550), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%Y"""'], {}), "('%Y')\n", (73544, 73550), True, 'import matplotlib.dates as mdates\n'), ((65715, 65733), 'matplotlib.pyplot.MaxNLocator', 'plt.MaxNLocator', (['(5)'], {}), '(5)\n', (65730, 65733), True, 'from matplotlib import rc, pyplot as plt\n'), ((65840, 65858), 'matplotlib.pyplot.MaxNLocator', 'plt.MaxNLocator', (['(5)'], {}), '(5)\n', (65855, 65858), True, 'from matplotlib import rc, pyplot as plt\n'), ((73470, 73488), 'matplotlib.pyplot.MaxNLocator', 'plt.MaxNLocator', (['(5)'], {}), '(5)\n', (73485, 73488), True, 'from matplotlib import rc, pyplot as plt\n'), ((73595, 73613), 'matplotlib.pyplot.MaxNLocator', 'plt.MaxNLocator', (['(5)'], {}), '(5)\n', (73610, 73613), True, 'from matplotlib import rc, pyplot as plt\n')]
import re from django.core.exceptions import ValidationError def validate_country(value): if len(value) != 2 or not re.match('[A-Z]{2}', value): raise ValidationError('Please enter your country code. e.g. US') def validate_phone(value): if not re.match('\+\d{1,3}\.\d+', value): raise ValidationError('Please your phone number. e.g. +1.1234567890')
[ "re.match", "django.core.exceptions.ValidationError" ]
[((166, 224), 'django.core.exceptions.ValidationError', 'ValidationError', (['"""Please enter your country code. e.g. US"""'], {}), "('Please enter your country code. e.g. US')\n", (181, 224), False, 'from django.core.exceptions import ValidationError\n'), ((265, 302), 're.match', 're.match', (['"""\\\\+\\\\d{1,3}\\\\.\\\\d+"""', 'value'], {}), "('\\\\+\\\\d{1,3}\\\\.\\\\d+', value)\n", (273, 302), False, 'import re\n'), ((314, 377), 'django.core.exceptions.ValidationError', 'ValidationError', (['"""Please your phone number. e.g. +1.1234567890"""'], {}), "('Please your phone number. e.g. +1.1234567890')\n", (329, 377), False, 'from django.core.exceptions import ValidationError\n'), ((123, 150), 're.match', 're.match', (['"""[A-Z]{2}"""', 'value'], {}), "('[A-Z]{2}', value)\n", (131, 150), False, 'import re\n')]
import tempfile from concurrent.futures import ProcessPoolExecutor, as_completed import numpy as np import pytest import zarr from dask.distributed import LocalCluster from swyft import Dataset, DirectoryStore, Prior, Simulator from swyft.store.simulator import SimulationStatus PARAMS = ["z1", "z2"] PRIOR = Prior.from_uv(lambda u: u * np.array([1 for _ in PARAMS]), len(PARAMS)) OUTPUT_SHAPE = (20, 20) SIM_SHAPES = {"x": OUTPUT_SHAPE} N_SIMULATIONS = 1000 BATCH_SIZE = 100 MAX_WORKERS = 4 # number of simultaneous processes acting on the store def model(_): """ Model with dummy parameters. Return random numbers in (0; 1]. """ return dict(x=-np.random.random(OUTPUT_SHAPE) + 1) @pytest.fixture(scope="function") def store(): simulator = Simulator(model, sim_shapes=SIM_SHAPES) with tempfile.TemporaryDirectory() as tmpdir: path = f"{tmpdir}/test_store" yield DirectoryStore(path=path, params=PARAMS, simulator=simulator) @pytest.fixture(scope="module") def cluster(): return LocalCluster(n_workers=2, threads_per_worker=1) def simulate(cluster, path="./cache", wait_for_results=True): """ Open store, sample simulation parameters and run the corresponding simulations. """ simulator = Simulator(model=model, sim_shapes=SIM_SHAPES, cluster=cluster) store = DirectoryStore(path=path, params=PARAMS, simulator=simulator) dataset = Dataset(N_SIMULATIONS, PRIOR, store=store) dataset.simulate(wait_for_results=wait_for_results, batch_size=BATCH_SIZE) return dataset.indices def read_from_store(path): """ Extract data from the Zarr Directory store """ z = zarr.open(f"{path}/samples/pars") x = zarr.open_group(f"{path}/samples/sims") s = zarr.open_array(f"{path}/samples/simulation_status") return z[:], {key: val[:] for key, val in x.items()}, s[:] def test_concurrent_runs_waiting_for_results(cluster, store): """ Run several processes that access the same store to sample parameters and to submit the corresponding simulations. The outcome of the simulations is waited for within the processes, so when they return all outcome should be written to the store. """ path = store._zarr_store.path with ProcessPoolExecutor(max_workers=MAX_WORKERS) as executor: futures = [] for i in range(MAX_WORKERS): # each process grows and sample the same cache future = executor.submit( simulate, cluster=cluster.scheduler_address, path=path, ) futures.append(future) for future in as_completed(futures): # processes are waiting for results, so all simulations should be finished status = store.get_simulation_status(future.result()) assert np.all(status == SimulationStatus.FINISHED) z, x, s = read_from_store(path) # check shape of the parameter array n_simulations, n_params = z.shape # the real number of samples can differ slightly from the required value assert n_simulations > 0.80 * N_SIMULATIONS and n_simulations < 1.20 * N_SIMULATIONS assert n_params == len(PARAMS) # check shape and values of the simulation array assert x.keys() == SIM_SHAPES.keys() for key, val in SIM_SHAPES.items(): assert x[key].shape == (n_simulations, *val) assert np.all(x[key][:] > 0.0) # all simulation output has been updated # check shape and values of the status array assert s.shape == (n_simulations,) assert np.all(s == SimulationStatus.FINISHED) # all simulations are done def test_concurrent_run_without_waiting_for_results(cluster, store): """ Run several processes that access the same store to sample parameters and to submit the corresponding simulations. The processes do not wait for the simulations to be done, so when they return some simulations should still be running. """ path = store._zarr_store.path with ProcessPoolExecutor(max_workers=MAX_WORKERS) as executor: futures = [] for i in range(MAX_WORKERS): # each process grows and sample the same cache future = executor.submit( simulate, cluster=cluster.scheduler_address, path=path, wait_for_results=False, ) futures.append(future) for future in as_completed(futures): # processes are not waiting for results, so some simulations should still be running status = store.get_simulation_status(future.result()) assert np.any(status == SimulationStatus.RUNNING) z, x, s = read_from_store(path) # check shape of the parameter array n_simulations, n_params = z.shape # the real number of samples can differ slightly from the required value assert n_simulations > 0.80 * N_SIMULATIONS and n_simulations < 1.20 * N_SIMULATIONS assert n_params == len(PARAMS) # check shape of the simulation array assert x.keys() == SIM_SHAPES.keys() for key, val in SIM_SHAPES.items(): assert x[key].shape == (n_simulations, *val) # check shape of the status array assert s.shape == (n_simulations,) # now explicitly wait for simulations store.wait_for_simulations(indices=np.arange(n_simulations)) z, x, s = read_from_store(path) for key, val in SIM_SHAPES.items(): assert np.all(x[key] > 0.0) # all simulation output has been updated assert np.all(s == SimulationStatus.FINISHED) # all simulations are done
[ "tempfile.TemporaryDirectory", "dask.distributed.LocalCluster", "numpy.random.random", "swyft.Simulator", "numpy.any", "swyft.Dataset", "concurrent.futures.as_completed", "numpy.array", "zarr.open", "swyft.DirectoryStore", "zarr.open_group", "pytest.fixture", "concurrent.futures.ProcessPoolE...
[((700, 732), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (714, 732), False, 'import pytest\n'), ((969, 999), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (983, 999), False, 'import pytest\n'), ((762, 801), 'swyft.Simulator', 'Simulator', (['model'], {'sim_shapes': 'SIM_SHAPES'}), '(model, sim_shapes=SIM_SHAPES)\n', (771, 801), False, 'from swyft import Dataset, DirectoryStore, Prior, Simulator\n'), ((1026, 1073), 'dask.distributed.LocalCluster', 'LocalCluster', ([], {'n_workers': '(2)', 'threads_per_worker': '(1)'}), '(n_workers=2, threads_per_worker=1)\n', (1038, 1073), False, 'from dask.distributed import LocalCluster\n'), ((1258, 1320), 'swyft.Simulator', 'Simulator', ([], {'model': 'model', 'sim_shapes': 'SIM_SHAPES', 'cluster': 'cluster'}), '(model=model, sim_shapes=SIM_SHAPES, cluster=cluster)\n', (1267, 1320), False, 'from swyft import Dataset, DirectoryStore, Prior, Simulator\n'), ((1333, 1394), 'swyft.DirectoryStore', 'DirectoryStore', ([], {'path': 'path', 'params': 'PARAMS', 'simulator': 'simulator'}), '(path=path, params=PARAMS, simulator=simulator)\n', (1347, 1394), False, 'from swyft import Dataset, DirectoryStore, Prior, Simulator\n'), ((1409, 1451), 'swyft.Dataset', 'Dataset', (['N_SIMULATIONS', 'PRIOR'], {'store': 'store'}), '(N_SIMULATIONS, PRIOR, store=store)\n', (1416, 1451), False, 'from swyft import Dataset, DirectoryStore, Prior, Simulator\n'), ((1650, 1683), 'zarr.open', 'zarr.open', (['f"""{path}/samples/pars"""'], {}), "(f'{path}/samples/pars')\n", (1659, 1683), False, 'import zarr\n'), ((1692, 1731), 'zarr.open_group', 'zarr.open_group', (['f"""{path}/samples/sims"""'], {}), "(f'{path}/samples/sims')\n", (1707, 1731), False, 'import zarr\n'), ((1740, 1792), 'zarr.open_array', 'zarr.open_array', (['f"""{path}/samples/simulation_status"""'], {}), "(f'{path}/samples/simulation_status')\n", (1755, 1792), False, 'import zarr\n'), ((3556, 3594), 'numpy.all', 'np.all', (['(s == SimulationStatus.FINISHED)'], {}), '(s == SimulationStatus.FINISHED)\n', (3562, 3594), True, 'import numpy as np\n'), ((5530, 5568), 'numpy.all', 'np.all', (['(s == SimulationStatus.FINISHED)'], {}), '(s == SimulationStatus.FINISHED)\n', (5536, 5568), True, 'import numpy as np\n'), ((811, 840), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (838, 840), False, 'import tempfile\n'), ((2241, 2285), 'concurrent.futures.ProcessPoolExecutor', 'ProcessPoolExecutor', ([], {'max_workers': 'MAX_WORKERS'}), '(max_workers=MAX_WORKERS)\n', (2260, 2285), False, 'from concurrent.futures import ProcessPoolExecutor, as_completed\n'), ((2630, 2651), 'concurrent.futures.as_completed', 'as_completed', (['futures'], {}), '(futures)\n', (2642, 2651), False, 'from concurrent.futures import ProcessPoolExecutor, as_completed\n'), ((3390, 3413), 'numpy.all', 'np.all', (['(x[key][:] > 0.0)'], {}), '(x[key][:] > 0.0)\n', (3396, 3413), True, 'import numpy as np\n'), ((4005, 4049), 'concurrent.futures.ProcessPoolExecutor', 'ProcessPoolExecutor', ([], {'max_workers': 'MAX_WORKERS'}), '(max_workers=MAX_WORKERS)\n', (4024, 4049), False, 'from concurrent.futures import ProcessPoolExecutor, as_completed\n'), ((4434, 4455), 'concurrent.futures.as_completed', 'as_completed', (['futures'], {}), '(futures)\n', (4446, 4455), False, 'from concurrent.futures import ProcessPoolExecutor, as_completed\n'), ((5455, 5475), 'numpy.all', 'np.all', (['(x[key] > 0.0)'], {}), '(x[key] > 0.0)\n', (5461, 5475), True, 'import numpy as np\n'), ((340, 371), 'numpy.array', 'np.array', (['[(1) for _ in PARAMS]'], {}), '([(1) for _ in PARAMS])\n', (348, 371), True, 'import numpy as np\n'), ((904, 965), 'swyft.DirectoryStore', 'DirectoryStore', ([], {'path': 'path', 'params': 'PARAMS', 'simulator': 'simulator'}), '(path=path, params=PARAMS, simulator=simulator)\n', (918, 965), False, 'from swyft import Dataset, DirectoryStore, Prior, Simulator\n'), ((2825, 2868), 'numpy.all', 'np.all', (['(status == SimulationStatus.FINISHED)'], {}), '(status == SimulationStatus.FINISHED)\n', (2831, 2868), True, 'import numpy as np\n'), ((4639, 4681), 'numpy.any', 'np.any', (['(status == SimulationStatus.RUNNING)'], {}), '(status == SimulationStatus.RUNNING)\n', (4645, 4681), True, 'import numpy as np\n'), ((5337, 5361), 'numpy.arange', 'np.arange', (['n_simulations'], {}), '(n_simulations)\n', (5346, 5361), True, 'import numpy as np\n'), ((661, 691), 'numpy.random.random', 'np.random.random', (['OUTPUT_SHAPE'], {}), '(OUTPUT_SHAPE)\n', (677, 691), True, 'import numpy as np\n')]
import argparse from typing import List, Iterable, Tuple, Optional from dejima.plugin import NoteField, SourcePlugin, CardTemplate, Note __version__ = "0.1.0" class SomeSource(SourcePlugin): # These can be named anything you want, and will become fields on # your notes in Anki. Note that the templates in `get_card_templates` # below have to match the field names, though! Front = NoteField(unique=True, merge=True) Back = NoteField(unique=True, merge=True) # You could add more fields for storing other information like images # audio files or anything else you might find convenient to show # on a flash card. # # See https://github.com/coddingtonbear/dejima/blob/master/src/dejima/sources/lln.py # to get an idea of how media works in Anki. def get_card_templates(self) -> List[CardTemplate]: # Every Dejima "Source" gets its own card type in Anki; this allows # each source to define their own fields and have a little more # flexibility. Below, we're defining the templates that will # be used by Anki for generating flash cards from your notes. # # If you want your flash cards to not have a reverse side (i.e. # where your question is the *Back* of the card, and you're # expected to answer with the *Front*), just remove the second # of these options. # # You can also make certain templates optionally generate a card # by carefully crafting the `front` field such that it is empty # in certain situations. See https://github.com/coddingtonbear/dejima/blob/master/src/dejima/sources/boox.py # for an example of how to do that. return [ CardTemplate( name="Card 1", front="<p>{{Front}}</p>", back=""" {{FrontSide}} <hr id='answer' /> <p> {{Back}} </p> """, ), CardTemplate( name="Card 2", front=""" <p> {{Back}} </p> """, back=""" {{FrontSide}} <hr id='answer' /> <p> {{Front}} </p> """, ), ] @classmethod def add_arguments(self, parser: argparse.ArgumentParser) -> None: # You *probably* need to read your content from a file somewhere # if so, the following block is useful in that it'll open the # file you have specified for you and make it available under # `self.options.input`. # # If you do need to open a file -- just un-comment the following # statement: # parser.add_argument( # "-i", # "--input", # nargs="?", # type=argparse.FileType("r"), # default=sys.stdin, # help="File to read from (default: stdin)", # ) return super().add_arguments(parser) def get_entries(self) -> Iterable[Tuple[Optional[str], Note]]: # Here is where you do the actual work of importing content # from whatever source and `yield`-ing `Note` instances that # will become entries in Anki. # # The below example is pretty useless, but will give you # a simple way of understanding how this works. flash_cards_i_want_to_create = [ {"English": "hey there", "Russian": "привет"}, {"English": "bye", "Russian": "пока"}, ] for card in flash_cards_i_want_to_create: # Dejima handles making sure that any particular entry is # imported only once, no matter how many times it might # appear in an import (so you don't need to worry about # being careful not to import particular content more than # once), but to do that, you need to give it a "foreign key" # to use for identifying this partiuclar entry. Here, we're # just using the "English" text on the card. If you were # sure you didn't want Dejima to prevent double-imports, # you can set this value to `None` and no double-import # checks will take place. # # If you want to skip those double-import checks for testing # or because you've deleted the relevant cards in Anki, you # can use the `--reimport` command-line argument. foreign_key = card["English"] # Now, we create our "Note" object -- the note object has # three properties: # # - fields: This is a dictionary having values for each of # the field names you defined at the top of your class. # - tags: This is a list of strings allowing you to add # tags to your card. We're not adding any tags here, # but it's easy to do that if you wanted to. # - media: A list of media objects to upload into Anki # for use as images in flash cards or audio files. We're # not using those here either, but look at the importer # here: https://github.com/coddingtonbear/dejima/blob/master/src/dejima/sources/lln.py # to get an idea of how that works. # # You'll see that we're getting the field name via # `self.Fields.field_name` -- that's just a convenience # property -- you could just use "Front" or "Back", too, # if you wanted. Using it the way shown below just makes # it easier in cases where the name of the attribute on # this class doesn't match the name of the field you # would like to create in Anki. note = Note( fields={ self.Front.field_name: card["English"], self.Back.field_name: card["Russian"], } ) yield foreign_key, note
[ "dejima.plugin.NoteField", "dejima.plugin.Note", "dejima.plugin.CardTemplate" ]
[((404, 438), 'dejima.plugin.NoteField', 'NoteField', ([], {'unique': '(True)', 'merge': '(True)'}), '(unique=True, merge=True)\n', (413, 438), False, 'from dejima.plugin import NoteField, SourcePlugin, CardTemplate, Note\n'), ((450, 484), 'dejima.plugin.NoteField', 'NoteField', ([], {'unique': '(True)', 'merge': '(True)'}), '(unique=True, merge=True)\n', (459, 484), False, 'from dejima.plugin import NoteField, SourcePlugin, CardTemplate, Note\n'), ((1736, 1984), 'dejima.plugin.CardTemplate', 'CardTemplate', ([], {'name': '"""Card 1"""', 'front': '"""<p>{{Front}}</p>"""', 'back': '"""\n {{FrontSide}}\n <hr id=\'answer\' />\n <p>\n {{Back}}\n </p>\n """'}), '(name=\'Card 1\', front=\'<p>{{Front}}</p>\', back=\n """\n {{FrontSide}}\n <hr id=\'answer\' />\n <p>\n {{Back}}\n </p>\n """\n )\n', (1748, 1984), False, 'from dejima.plugin import NoteField, SourcePlugin, CardTemplate, Note\n'), ((2051, 2397), 'dejima.plugin.CardTemplate', 'CardTemplate', ([], {'name': '"""Card 2"""', 'front': '"""\n <p>\n {{Back}}\n </p>\n """', 'back': '"""\n {{FrontSide}}\n <hr id=\'answer\' />\n <p>\n {{Front}}\n </p>\n """'}), '(name=\'Card 2\', front=\n """\n <p>\n {{Back}}\n </p>\n """\n , back=\n """\n {{FrontSide}}\n <hr id=\'answer\' />\n <p>\n {{Front}}\n </p>\n """\n )\n', (2063, 2397), False, 'from dejima.plugin import NoteField, SourcePlugin, CardTemplate, Note\n'), ((5986, 6082), 'dejima.plugin.Note', 'Note', ([], {'fields': "{self.Front.field_name: card['English'], self.Back.field_name: card['Russian']}"}), "(fields={self.Front.field_name: card['English'], self.Back.field_name:\n card['Russian']})\n", (5990, 6082), False, 'from dejima.plugin import NoteField, SourcePlugin, CardTemplate, Note\n')]
import time from .minesweeper import * # utility / debugging code def parse_api_payload(payload): if 'board' in payload: rules, mine_p = read_board(payload['board'], payload['total_mines'], everything_mode=True) else: rules = [Rule(r['num_mines'], r['cells']) for r in payload['rules']] try: mine_p = payload['mine_prob'] except KeyError: mine_p = MineCount(payload['total_cells'], payload['total_mines']) return rules, mine_p def api_solve(payload): rules, mine_p = parse_api_payload(payload) result = {} start = time.time() try: result['solution'] = solve(rules, mine_p, '_other') except InconsistencyError: result['solution'] = None end = time.time() result['processing_time'] = end - start return result def read_board(encoded_board, total_mines, everything_mode=False): """convert an ascii-art game board into the ruleset describing it""" board = Board(encoded_board) return generate_rules(board, total_mines, everything_mode) def read_board_file(path, total_mines, everything_mode=False): """read a board from a file""" with open(path) as f: return read_board(f.read(), total_mines, everything_mode) class Board(object): """simple representation of a game board (no actual game logic!)""" def __init__(self, encoded): """create a game board from an ascii-encoded description, where . = blank; * = mine; x = unknown; N = count e.g.: ...2x .113x .2*xx 13*xx xxxxx """ lines = [ln.strip() for ln in encoded.strip().split()] self.height = len(lines) self.width = len(lines[0] if lines else []) self.cells = {} for row, ln in enumerate(lines): for col, c in enumerate(ln): pos = (row + 1, col + 1) self.cells[pos] = BoardCell(c, self.cell_name(*pos)) def adjacent(self, xxx_todo_changeme): (row, col) = xxx_todo_changeme for r in range(max(row - 1, 1), min(row + 2, self.height + 1)): for c in range(max(col - 1, 1), min(col + 2, self.width + 1)): pos = (r, c) if pos != (row, col): yield (pos, self.cells[pos]) def cell_name(self, r, c): return '%0*d-%0*d' % (len(str(self.height)), r, len(str(self.width)), c) def total_cells(self): return self.width * self.height class BoardCell(object): """representation of a board cell""" def __init__(self, c, name): """create a cell from its ascii description""" self.name = name if c == '.': c = '0' try: self.type = 'clear' self.adj = int(c) except ValueError: self.type = {'*': 'mine', 'x': 'unkn'}[c] def is_mine(self): return self.type == 'mine' def is_unknown(self): return self.type == 'unkn' def __hash__(self): return hash(self.name) def __eq__(self, o): return self.name == o.name def generate_rules(board, total_mines, everything_mode=False): """reference algorithm for generating input rules / mine_prevalence from a game state board -- game board object total_mines -- total # of mines on board everything_mode -- if False, only include 'interesting' rules, i.e., omit the parts of the board that have already been solved; if True, include rules to completely describe the state of the board (but still don't include _every_ possible rule, as this would include a huge number of degenerate / redundant rules). in general, invalid boards will only be detected by everything mode. in particular, in 'interesting mode': * create a rule for each 'number' cell that borders an uncovered cell * create a rule encompassing cells with known mines, including ONLY those cells which are referenced by the rules from the previous step in everything mode: * create a rule for each 'number' cell * create a rule encompassing all known mines * create a rule encompassing all uncovered cells * create a rule for all cells adjacent to 'blank'/'empty' cells, and not included in the previous rule. thus, this rule will only be present for invalid boards or boards whose empty areas have not been fully expanded """ def _rule(mines, cells): """rule-building helper; don't create degenerate rules we allow # mines > # cells, such as in the event of an invalid board""" if mines or cells: yield Rule(mines, [cell.name for cell in cells]) clear_cells = set() # set of cells that have been unconvered zero_cells = set() # set of cells adjacent to blank/empty/'zero' cells relevant_mines = set() # set of known mine cells that interest us num_known_mines = 0 # total number of known mines rules = [] for cell_id, cell in board.cells.items(): if cell.is_mine(): num_known_mines += 1 if everything_mode: relevant_mines.add(cell) elif not cell.is_unknown(): clear_cells.add(cell) neighbors = list(dict(board.adjacent(cell_id)).values()) if cell.adj > 0: if any(nc.is_unknown() for nc in neighbors) or everything_mode: rules.extend(_rule(cell.adj, [nc for nc in neighbors if nc.is_mine() or nc.is_unknown()])) relevant_mines.update(nc for nc in neighbors if nc.is_mine()) else: zero_cells.update(neighbors) rules.extend(_rule(len(relevant_mines), relevant_mines)) if everything_mode: rules.extend(_rule(0, clear_cells)) rules.extend(_rule(0, zero_cells - clear_cells)) num_irrelevant_mines = num_known_mines - len(relevant_mines) mine_prevalence = MineCount( board.total_cells() - (0 if everything_mode else len(clear_cells) + num_irrelevant_mines), total_mines - (0 if everything_mode else num_irrelevant_mines) ) return (rules, mine_prevalence)
[ "time.time" ]
[((544, 555), 'time.time', 'time.time', ([], {}), '()\n', (553, 555), False, 'import time\n'), ((679, 690), 'time.time', 'time.time', ([], {}), '()\n', (688, 690), False, 'import time\n')]
import requests import json import csv import time import os import scrape from datetime import datetime # A dict of numerical location codes used by the bandcamp API. LOCATION_CODES = {'novascotia': 6091530, 'ottawa': 6094817, 'pei': 6113358, 'newbrunswick': 6087430, 'saskatchewan': 6141242, 'newfoundland': 6354959, 'victoria': 6174041, 'edmonton': 5946768, 'calgary': 5913490, 'manitoba': 6065171, 'ontario': 6093943, 'quebec': 6115047, 'britishcolumbia': 5909050, 'alberta': 5883102} GENRES_TO_IGNORE = ['metal', 'podcasts', 'classical', 'latin', 'spoken word', 'comedy', 'kids', 'audiobooks'] BASE_URL = 'https://bandcamp.com/api/hub/2/dig_deeper' def get_bandcamp_releases(tag_str, page_count=10, location_id=0, region_str=None, sort_str='pop'): albums = list() # If no region input, assume it is the same as the input tag. if not(region_str): region_str = tag_str # Search by popularity not date, to remove bandcamp bloat. post_requests = [{"filters": {"format": "all", "location": location_id, "sort": sort_str, "tags": [tag_str]}, "page": i} for i in range(1, page_count + 1)] for post_request in post_requests: tmp, continue_flag = scrape_response(post_request, region_str) albums.extend(tmp) if not continue_flag: break return albums # Scrape an individual bandcamp post response. def scrape_response(post_request, region_str): # Attempt search, if fail, wait 5s to try again. x = requests.post(BASE_URL, json=post_request) if (not x.ok): print("*** Failed Search, Continuing in 5s ***") time.sleep(5) x = requests.post(BASE_URL, json=post_request) request_results = x.json() albums = list() for result in request_results['items']: # Skip albums that have genre within the ignore list. genre_str = result['genre'] if genre_str in GENRES_TO_IGNORE: continue # Skip albums that have not released, aka, are up for pre-order. if result['is_preorder']: continue artist_str = result['artist'] title_str = result['title'] url_str = result['tralbum_url'] albums.append({'artist': artist_str, 'title': title_str, 'genre': genre_str, 'region': region_str, 'url': url_str}) # Stop searching for pages if we reach the final page. if(not request_results['more_available']): return albums, False return albums, True # A utility function to effectively search each region w/o duplicates. def get_bandcamp_releases_util(albums, tag_str='canada', location_id=0, region_str=None): # Complete one large recent release search and one small popular search. if region_str is None: res1 = get_bandcamp_releases(tag_str, page_count=10, sort_str='date') res2 = get_bandcamp_releases(tag_str, page_count=1, sort_str='pop') else: res1 = get_bandcamp_releases('canada', page_count=10, location_id=location_id, region_str=region_str, sort_str='date') res2 = get_bandcamp_releases('canada', page_count=1, location_id=location_id, region_str=region_str, sort_str='pop') # Ensure the url is not yet in the current list. url_list = [r['url'] for r in albums] for result in res1: if result['url'] not in url_list: albums.append(result) url_list = [r['url'] for r in albums] for result in res2: if result['url'] not in url_list: albums.append(result) return albums # Generate recommendation scores. These are likely overwritten when the # data json files are transferred into the mongo database. def get_bandcamp_scores(albums): for r in albums: if not('sp_popularity' in r): r['sp_popularity'] = 0 date_obj = datetime.strptime(r['sp_date'], "%Y-%m-%dT00:00.000Z") time_score = max(60 - (datetime.now() - date_obj).days, 0) r['score'] = r['sp_popularity'] / 100 * 40 + time_score / 60 * 60 r['score'] = round(r['score'], 3) albums = sorted(albums, key=lambda k: k['score'], reverse=True) return albums # WHERE THE SEARCHING TAKES PLACE ###################################### # Retrieve primary locations by popularity. albums = list() for tag_str in ['toronto', 'montreal', 'vancouver']: print("Scraping Bandcamp %s" % tag_str) albums = get_bandcamp_releases_util(albums, tag_str) # Retrieve secondary locations by date. for region_str, location_id in LOCATION_CODES.items(): print("Scraping Bandcamp %s" % region_str) albums = get_bandcamp_releases_util(albums, tag_str='canada', location_id=location_id, region_str=region_str) # Write results to a csv file before the spotify search for debugging. # with open('results/canada_pre.csv', mode='w') as csv_file: # fieldnames = ['artist', 'title', 'genre', 'url', 'region'] # csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames) # csv_writer.writeheader() # csv_writer.writerows(albums) print('Fetching %d Spotify Results' % len(albums), end='', flush=True) current_time = datetime.now() bandcamp_scraper = scrape.AlbumScraper(albums) albums = bandcamp_scraper.run() albums = get_bandcamp_scores(albums) print(", Completed in %ds" % (datetime.now() - current_time).seconds) # Write results to csv and json files. script_loc = os.path.dirname(os.path.realpath(__file__)) with open(script_loc + '/results/canada.csv', mode='w+') as csv_file: fieldnames = ['artist', 'title', 'genre', 'url', 'region', 'score', 'sp_popularity', 'sp_date', 'sp_img', 'sp_album_id', 'sp_artist_id'] csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames) csv_writer.writeheader() csv_writer.writerows(albums) with open(script_loc + '/results/canada.json', 'w+') as json_file: json.dump(albums, json_file, indent=4)
[ "scrape.AlbumScraper", "csv.DictWriter", "requests.post", "datetime.datetime.strptime", "time.sleep", "os.path.realpath", "datetime.datetime.now", "json.dump" ]
[((5166, 5180), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (5178, 5180), False, 'from datetime import datetime\n'), ((5200, 5227), 'scrape.AlbumScraper', 'scrape.AlbumScraper', (['albums'], {}), '(albums)\n', (5219, 5227), False, 'import scrape\n'), ((1527, 1569), 'requests.post', 'requests.post', (['BASE_URL'], {'json': 'post_request'}), '(BASE_URL, json=post_request)\n', (1540, 1569), False, 'import requests\n'), ((5436, 5462), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (5452, 5462), False, 'import os\n'), ((5708, 5755), 'csv.DictWriter', 'csv.DictWriter', (['csv_file'], {'fieldnames': 'fieldnames'}), '(csv_file, fieldnames=fieldnames)\n', (5722, 5755), False, 'import csv\n'), ((5891, 5929), 'json.dump', 'json.dump', (['albums', 'json_file'], {'indent': '(4)'}), '(albums, json_file, indent=4)\n', (5900, 5929), False, 'import json\n'), ((1654, 1667), 'time.sleep', 'time.sleep', (['(5)'], {}), '(5)\n', (1664, 1667), False, 'import time\n'), ((1680, 1722), 'requests.post', 'requests.post', (['BASE_URL'], {'json': 'post_request'}), '(BASE_URL, json=post_request)\n', (1693, 1722), False, 'import requests\n'), ((3872, 3926), 'datetime.datetime.strptime', 'datetime.strptime', (["r['sp_date']", '"""%Y-%m-%dT00:00.000Z"""'], {}), "(r['sp_date'], '%Y-%m-%dT00:00.000Z')\n", (3889, 3926), False, 'from datetime import datetime\n'), ((5327, 5341), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (5339, 5341), False, 'from datetime import datetime\n'), ((3958, 3972), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (3970, 3972), False, 'from datetime import datetime\n')]
from unittest.mock import patch from django.urls import reverse from rest_framework import test, status from users.models import User from users.tests.factories import UserFactory class TestUserView(test.APITransactionTestCase): """Test cases for the user view.""" def test_user_resource_url(self): self.assertEqual(reverse('user_create'), '/v1/users/') def test_superuser_resource_url(self): self.assertEqual(reverse('superuser_create'), '/v1/users/superusers/') @patch('users.logger.info') def test_user_creation(self, logger_mock): response = self.client.post( reverse('user_create'), { 'name': 'Test user', 'email': '<EMAIL>', 'password': '<PASSWORD>' }, format='json' ) logger_mock.assert_called() self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(User.objects.count(), 1) def test_unauthorized_superuser_creation(self): response = self.client.post( reverse('superuser_create'), { 'name': 'test', 'email': '<EMAIL>', 'password': '<PASSWORD>' }, format='json' ) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) self.assertEqual(User.objects.count(), 0) def test_forbidden_superuser_creation(self): self.user = UserFactory(name='super', email='<EMAIL>') self.client.force_authenticate(self.user) response = self.client.post( reverse('superuser_create'), { 'name': 'test', 'email': '<EMAIL>', 'password': '<PASSWORD>' }, format='json' ) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) self.assertEqual(User.objects.count(), 1) @patch('users.logger.info') def test_superuser_creation(self, logger_mock): self.superuser = UserFactory( name='super', email='<EMAIL>', is_superuser=True ) self.client.force_authenticate(self.superuser) response = self.client.post( reverse('superuser_create'), { 'name': 'Test super', 'email': '<EMAIL>', 'password': '<PASSWORD>' }, format='json' ) self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(User.objects.count(), 2) logger_mock.assert_called()
[ "users.tests.factories.UserFactory", "unittest.mock.patch", "users.models.User.objects.count", "django.urls.reverse" ]
[((504, 530), 'unittest.mock.patch', 'patch', (['"""users.logger.info"""'], {}), "('users.logger.info')\n", (509, 530), False, 'from unittest.mock import patch\n'), ((1969, 1995), 'unittest.mock.patch', 'patch', (['"""users.logger.info"""'], {}), "('users.logger.info')\n", (1974, 1995), False, 'from unittest.mock import patch\n'), ((1492, 1534), 'users.tests.factories.UserFactory', 'UserFactory', ([], {'name': '"""super"""', 'email': '"""<EMAIL>"""'}), "(name='super', email='<EMAIL>')\n", (1503, 1534), False, 'from users.tests.factories import UserFactory\n'), ((2073, 2134), 'users.tests.factories.UserFactory', 'UserFactory', ([], {'name': '"""super"""', 'email': '"""<EMAIL>"""', 'is_superuser': '(True)'}), "(name='super', email='<EMAIL>', is_superuser=True)\n", (2084, 2134), False, 'from users.tests.factories import UserFactory\n'), ((337, 359), 'django.urls.reverse', 'reverse', (['"""user_create"""'], {}), "('user_create')\n", (344, 359), False, 'from django.urls import reverse\n'), ((444, 471), 'django.urls.reverse', 'reverse', (['"""superuser_create"""'], {}), "('superuser_create')\n", (451, 471), False, 'from django.urls import reverse\n'), ((627, 649), 'django.urls.reverse', 'reverse', (['"""user_create"""'], {}), "('user_create')\n", (634, 649), False, 'from django.urls import reverse\n'), ((964, 984), 'users.models.User.objects.count', 'User.objects.count', ([], {}), '()\n', (982, 984), False, 'from users.models import User\n'), ((1091, 1118), 'django.urls.reverse', 'reverse', (['"""superuser_create"""'], {}), "('superuser_create')\n", (1098, 1118), False, 'from django.urls import reverse\n'), ((1397, 1417), 'users.models.User.objects.count', 'User.objects.count', ([], {}), '()\n', (1415, 1417), False, 'from users.models import User\n'), ((1635, 1662), 'django.urls.reverse', 'reverse', (['"""superuser_create"""'], {}), "('superuser_create')\n", (1642, 1662), False, 'from django.urls import reverse\n'), ((1938, 1958), 'users.models.User.objects.count', 'User.objects.count', ([], {}), '()\n', (1956, 1958), False, 'from users.models import User\n'), ((2286, 2313), 'django.urls.reverse', 'reverse', (['"""superuser_create"""'], {}), "('superuser_create')\n", (2293, 2313), False, 'from django.urls import reverse\n'), ((2593, 2613), 'users.models.User.objects.count', 'User.objects.count', ([], {}), '()\n', (2611, 2613), False, 'from users.models import User\n')]
import pytest from thgsp.alg.coloring import dsatur_py, check_coloring, dsatur_cpp, dsatur from thgsp.graphs.generators import rand_udg, torch from thgsp.visual.plotting import draw_cn import matplotlib.pyplot as plt from ..utils4t import devices def test_dsatur_py(): for _ in range(20): N = 13 G = rand_udg(N, 0.3) pos = torch.rand(N, 2) vtx_color = dsatur_py(G) assert check_coloring(G, vtx_color) assert not check_coloring(G, [0] * N) draw_cn(G, pos=pos, node_color=vtx_color) plt.show() def test_dsatur_cpp(): for _ in range(20): N = 13 G = rand_udg(N, 0.3) pos = torch.rand(N, 2) vtx_color = dsatur_cpp(G) assert check_coloring(G, vtx_color) assert not check_coloring(G, [0] * N) draw_cn(G, pos=pos, node_color=vtx_color) plt.show() @pytest.mark.parametrize('device', devices) def test_dsatur(device): N = 10 G = rand_udg(N, 0.2, device=device) pos = torch.rand(N, 2) vtx_color = dsatur(G) assert check_coloring(G, vtx_color) assert not check_coloring(G, [0] * N) draw_cn(G, pos=pos, node_color=vtx_color) plt.show()
[ "thgsp.graphs.generators.rand_udg", "thgsp.graphs.generators.torch.rand", "pytest.mark.parametrize", "thgsp.alg.coloring.dsatur", "thgsp.alg.coloring.dsatur_py", "thgsp.alg.coloring.check_coloring", "thgsp.visual.plotting.draw_cn", "thgsp.alg.coloring.dsatur_cpp", "matplotlib.pyplot.show" ]
[((877, 919), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""device"""', 'devices'], {}), "('device', devices)\n", (900, 919), False, 'import pytest\n'), ((549, 559), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (557, 559), True, 'import matplotlib.pyplot as plt\n'), ((863, 873), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (871, 873), True, 'import matplotlib.pyplot as plt\n'), ((964, 995), 'thgsp.graphs.generators.rand_udg', 'rand_udg', (['N', '(0.2)'], {'device': 'device'}), '(N, 0.2, device=device)\n', (972, 995), False, 'from thgsp.graphs.generators import rand_udg, torch\n'), ((1006, 1022), 'thgsp.graphs.generators.torch.rand', 'torch.rand', (['N', '(2)'], {}), '(N, 2)\n', (1016, 1022), False, 'from thgsp.graphs.generators import rand_udg, torch\n'), ((1039, 1048), 'thgsp.alg.coloring.dsatur', 'dsatur', (['G'], {}), '(G)\n', (1045, 1048), False, 'from thgsp.alg.coloring import dsatur_py, check_coloring, dsatur_cpp, dsatur\n'), ((1060, 1088), 'thgsp.alg.coloring.check_coloring', 'check_coloring', (['G', 'vtx_color'], {}), '(G, vtx_color)\n', (1074, 1088), False, 'from thgsp.alg.coloring import dsatur_py, check_coloring, dsatur_cpp, dsatur\n'), ((1135, 1176), 'thgsp.visual.plotting.draw_cn', 'draw_cn', (['G'], {'pos': 'pos', 'node_color': 'vtx_color'}), '(G, pos=pos, node_color=vtx_color)\n', (1142, 1176), False, 'from thgsp.visual.plotting import draw_cn\n'), ((1181, 1191), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1189, 1191), True, 'import matplotlib.pyplot as plt\n'), ((323, 339), 'thgsp.graphs.generators.rand_udg', 'rand_udg', (['N', '(0.3)'], {}), '(N, 0.3)\n', (331, 339), False, 'from thgsp.graphs.generators import rand_udg, torch\n'), ((354, 370), 'thgsp.graphs.generators.torch.rand', 'torch.rand', (['N', '(2)'], {}), '(N, 2)\n', (364, 370), False, 'from thgsp.graphs.generators import rand_udg, torch\n'), ((391, 403), 'thgsp.alg.coloring.dsatur_py', 'dsatur_py', (['G'], {}), '(G)\n', (400, 403), False, 'from thgsp.alg.coloring import dsatur_py, check_coloring, dsatur_cpp, dsatur\n'), ((419, 447), 'thgsp.alg.coloring.check_coloring', 'check_coloring', (['G', 'vtx_color'], {}), '(G, vtx_color)\n', (433, 447), False, 'from thgsp.alg.coloring import dsatur_py, check_coloring, dsatur_cpp, dsatur\n'), ((502, 543), 'thgsp.visual.plotting.draw_cn', 'draw_cn', (['G'], {'pos': 'pos', 'node_color': 'vtx_color'}), '(G, pos=pos, node_color=vtx_color)\n', (509, 543), False, 'from thgsp.visual.plotting import draw_cn\n'), ((636, 652), 'thgsp.graphs.generators.rand_udg', 'rand_udg', (['N', '(0.3)'], {}), '(N, 0.3)\n', (644, 652), False, 'from thgsp.graphs.generators import rand_udg, torch\n'), ((667, 683), 'thgsp.graphs.generators.torch.rand', 'torch.rand', (['N', '(2)'], {}), '(N, 2)\n', (677, 683), False, 'from thgsp.graphs.generators import rand_udg, torch\n'), ((704, 717), 'thgsp.alg.coloring.dsatur_cpp', 'dsatur_cpp', (['G'], {}), '(G)\n', (714, 717), False, 'from thgsp.alg.coloring import dsatur_py, check_coloring, dsatur_cpp, dsatur\n'), ((733, 761), 'thgsp.alg.coloring.check_coloring', 'check_coloring', (['G', 'vtx_color'], {}), '(G, vtx_color)\n', (747, 761), False, 'from thgsp.alg.coloring import dsatur_py, check_coloring, dsatur_cpp, dsatur\n'), ((816, 857), 'thgsp.visual.plotting.draw_cn', 'draw_cn', (['G'], {'pos': 'pos', 'node_color': 'vtx_color'}), '(G, pos=pos, node_color=vtx_color)\n', (823, 857), False, 'from thgsp.visual.plotting import draw_cn\n'), ((1104, 1130), 'thgsp.alg.coloring.check_coloring', 'check_coloring', (['G', '([0] * N)'], {}), '(G, [0] * N)\n', (1118, 1130), False, 'from thgsp.alg.coloring import dsatur_py, check_coloring, dsatur_cpp, dsatur\n'), ((467, 493), 'thgsp.alg.coloring.check_coloring', 'check_coloring', (['G', '([0] * N)'], {}), '(G, [0] * N)\n', (481, 493), False, 'from thgsp.alg.coloring import dsatur_py, check_coloring, dsatur_cpp, dsatur\n'), ((781, 807), 'thgsp.alg.coloring.check_coloring', 'check_coloring', (['G', '([0] * N)'], {}), '(G, [0] * N)\n', (795, 807), False, 'from thgsp.alg.coloring import dsatur_py, check_coloring, dsatur_cpp, dsatur\n')]
from models.rnn_mlp import RNN_MLP from models.social_attention import SocialAttention from models.cnn_mlp import CNN_MLP from models.spatial_attention import SpatialAttention from models.s2s_spatial_attention import S2sSpatialAtt from models.s2s_social_attention import S2sSocialAtt import time import json import torch import sys import helpers.helpers_training as helpers import helpers.helpers_evaluation as helpers_evaluation import torch.nn as nn import numpy as np import os def main(): device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") torch.manual_seed(42) #loading parameters parameters_path = "./src/parameters/project.json" parameters_project = json.load(open(parameters_path)) data_processed_parameters = json.load(open(parameters_project["data_processed_parameters"])) evaluation_parameters = json.load(open(parameters_project["evaluation_parameters"])) processed_parameters = json.load(open(parameters_project["data_processed_parameters"])) # loading training data data_file = parameters_project["hdf5_samples"] # scene lists for train, eval and test eval_scenes = data_processed_parameters["eval_scenes"] train_eval_scenes = data_processed_parameters["train_scenes"] test_scenes = data_processed_parameters["test_scenes"] train_scenes = [scene for scene in train_eval_scenes if scene not in eval_scenes] scenes = [train_eval_scenes,train_scenes,test_scenes,eval_scenes] report_name = evaluation_parameters["report_name"] model_name = evaluation_parameters["model_name"] models_path = parameters_project["models_evaluation"] + "{}.tar".format(model_name) print("loading trained model {}".format(model_name)) net = None if model_name == "baseline": args_net = { "offsets":0, "offsets_input":0, "use_images":0 } else: checkpoint = torch.load(models_path) args_net = checkpoint["args"] model = args_net["model_name"] net = None if model == "rnn_mlp": net = RNN_MLP(args_net) elif model == "cnn_mlp": net = CNN_MLP(args_net) elif model == "social_attention": net = SocialAttention(args_net) elif model == "spatial_attention": net = SpatialAttention(args_net) elif model == "s2s_social_attention": net = SocialAttention(args_net) elif model == "s2s_spatial_attention": net = S2sSpatialAtt(args_net) # loading trained network net.load_state_dict(checkpoint['state_dict']) net = net.to(device) net.eval() scenes = test_scenes set_type_test = evaluation_parameters["set_type_test"] if set_type_test == "train": scenes = train_scenes elif set_type_test == "eval": scenes = eval_scenes elif set_type_test == "train_eval": scenes = train_eval_scenes times = 0 # sum time for every prediction nb_samples = 0 # number of predictions dir_name = parameters_project["evaluation_reports"] + "{}/".format(report_name) sub_dir_name = parameters_project["evaluation_reports"] + "{}/scene_reports/".format(report_name) if os.path.exists(dir_name): os.system("rm -r {}".format(dir_name)) os.system("mkdir {}".format(dir_name)) if os.path.exists(sub_dir_name): os.system("rm -r {}".format(sub_dir_name)) os.system("mkdir {}".format(sub_dir_name)) s = time.time() for z,scene in enumerate(scenes): sample_id = 0 print(scene) scene_dict = {} # save every sample in the scene # get dataloader data_loader = helpers_evaluation.get_data_loader(parameters_project,data_file,scene,args_net,processed_parameters,evaluation_parameters) sample_id = 0 print(time.time()-s) for batch_idx, data in enumerate(data_loader): inputs, labels,types,points_mask, active_mask,imgs,target_last,input_last = data inputs = inputs.to(device) labels = labels.to(device) imgs = imgs.to(device) b,n,_,_ = inputs.shape if not args_net["offsets_input"]: input_last = np.zeros_like(inputs.cpu().numpy()) outputs = labels if model_name != "baseline": # active mask for training, along batch*numbr_agent axis active_mask = active_mask.to(device) points_mask = list(points_mask) # if not args_net["offsets_input"]: # input_last = np.zeros_like(inputs.cpu().numpy()) start = time.time() if not args_net["use_neighbors"]: outputs,inputs,types,active_mask,points_mask = helpers_evaluation.predict_naive(inputs,types,active_mask,points_mask,net,device,imgs) else: if not args_net["joint_optimisation"]: outputs,inputs,types,active_mask,points_mask = helpers_evaluation.predict_neighbors_disjoint(inputs,types,active_mask,points_mask,net,device) else: outputs = net((inputs,types,active_mask,points_mask,imgs)) end = time.time() - start times += end nb_samples += b*n active_mask = helpers_evaluation.get_active_mask(points_mask[1]) points_mask = torch.FloatTensor(points_mask[1]).to(device) outputs = torch.mul(points_mask,outputs) labels = torch.mul(points_mask,labels) # bon endroit? # active mask per sample in batch if not args_net["offsets"]: target_last = np.zeros_like(labels.detach().cpu().numpy()) for i,l,o,t,p, a, il, tl in zip(inputs, labels, outputs, types, points_mask,active_mask, input_last, target_last): i = i[a].detach().cpu().numpy() l = l[a].detach().cpu().numpy() t = t[a] p = p[a] o = o[a].detach().cpu().numpy() tl = tl[a] il = il[a] # revert offsets i,l,o = helpers.offsets_to_trajectories( i,l,o,args_net["offsets"],args_net["offsets_input"],tl,il) # apply active mask scene_dict[sample_id] = {} scene_dict[sample_id]["inputs"] = i.tolist() scene_dict[sample_id]["labels"] = l.tolist() scene_dict[sample_id]["outputs"] = o.tolist() # scene_dict[sample_id]["active_mask"] = a.cpu().numpy().tolist() scene_dict[sample_id]["types"] = t.tolist() scene_dict[sample_id]["points_mask"] = p.cpu().numpy().tolist() sample_id += 1 json.dump(scene_dict, open(sub_dir_name + "{}_samples.json".format(scene),"w"),indent= 0) timer = { "total_time":times, "nb_trajectories":nb_samples, "time_per_trajectory":times/nb_samples } # save the time json.dump(timer, open(dir_name + "time.json","w"),indent= 0) if __name__ == "__main__": main()
[ "torch.manual_seed", "os.path.exists", "torch.mul", "models.spatial_attention.SpatialAttention", "helpers.helpers_training.offsets_to_trajectories", "models.cnn_mlp.CNN_MLP", "helpers.helpers_evaluation.predict_naive", "torch.load", "models.rnn_mlp.RNN_MLP", "torch.FloatTensor", "helpers.helpers...
[((586, 607), 'torch.manual_seed', 'torch.manual_seed', (['(42)'], {}), '(42)\n', (603, 607), False, 'import torch\n'), ((3296, 3320), 'os.path.exists', 'os.path.exists', (['dir_name'], {}), '(dir_name)\n', (3310, 3320), False, 'import os\n'), ((3419, 3447), 'os.path.exists', 'os.path.exists', (['sub_dir_name'], {}), '(sub_dir_name)\n', (3433, 3447), False, 'import os\n'), ((3556, 3567), 'time.time', 'time.time', ([], {}), '()\n', (3565, 3567), False, 'import time\n'), ((1945, 1968), 'torch.load', 'torch.load', (['models_path'], {}), '(models_path)\n', (1955, 1968), False, 'import torch\n'), ((3779, 3910), 'helpers.helpers_evaluation.get_data_loader', 'helpers_evaluation.get_data_loader', (['parameters_project', 'data_file', 'scene', 'args_net', 'processed_parameters', 'evaluation_parameters'], {}), '(parameters_project, data_file, scene,\n args_net, processed_parameters, evaluation_parameters)\n', (3813, 3910), True, 'import helpers.helpers_evaluation as helpers_evaluation\n'), ((540, 565), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (563, 565), False, 'import torch\n'), ((2117, 2134), 'models.rnn_mlp.RNN_MLP', 'RNN_MLP', (['args_net'], {}), '(args_net)\n', (2124, 2134), False, 'from models.rnn_mlp import RNN_MLP\n'), ((5537, 5587), 'helpers.helpers_evaluation.get_active_mask', 'helpers_evaluation.get_active_mask', (['points_mask[1]'], {}), '(points_mask[1])\n', (5571, 5587), True, 'import helpers.helpers_evaluation as helpers_evaluation\n'), ((5701, 5732), 'torch.mul', 'torch.mul', (['points_mask', 'outputs'], {}), '(points_mask, outputs)\n', (5710, 5732), False, 'import torch\n'), ((5753, 5783), 'torch.mul', 'torch.mul', (['points_mask', 'labels'], {}), '(points_mask, labels)\n', (5762, 5783), False, 'import torch\n'), ((2194, 2211), 'models.cnn_mlp.CNN_MLP', 'CNN_MLP', (['args_net'], {}), '(args_net)\n', (2201, 2211), False, 'from models.cnn_mlp import CNN_MLP\n'), ((3957, 3968), 'time.time', 'time.time', ([], {}), '()\n', (3966, 3968), False, 'import time\n'), ((4832, 4843), 'time.time', 'time.time', ([], {}), '()\n', (4841, 4843), False, 'import time\n'), ((6395, 6496), 'helpers.helpers_training.offsets_to_trajectories', 'helpers.offsets_to_trajectories', (['i', 'l', 'o', "args_net['offsets']", "args_net['offsets_input']", 'tl', 'il'], {}), "(i, l, o, args_net['offsets'], args_net[\n 'offsets_input'], tl, il)\n", (6426, 6496), True, 'import helpers.helpers_training as helpers\n'), ((2277, 2302), 'models.social_attention.SocialAttention', 'SocialAttention', (['args_net'], {}), '(args_net)\n', (2292, 2302), False, 'from models.social_attention import SocialAttention\n'), ((4961, 5057), 'helpers.helpers_evaluation.predict_naive', 'helpers_evaluation.predict_naive', (['inputs', 'types', 'active_mask', 'points_mask', 'net', 'device', 'imgs'], {}), '(inputs, types, active_mask, points_mask,\n net, device, imgs)\n', (4993, 5057), True, 'import helpers.helpers_evaluation as helpers_evaluation\n'), ((5430, 5441), 'time.time', 'time.time', ([], {}), '()\n', (5439, 5441), False, 'import time\n'), ((5614, 5647), 'torch.FloatTensor', 'torch.FloatTensor', (['points_mask[1]'], {}), '(points_mask[1])\n', (5631, 5647), False, 'import torch\n'), ((2364, 2390), 'models.spatial_attention.SpatialAttention', 'SpatialAttention', (['args_net'], {}), '(args_net)\n', (2380, 2390), False, 'from models.spatial_attention import SpatialAttention\n'), ((5203, 5306), 'helpers.helpers_evaluation.predict_neighbors_disjoint', 'helpers_evaluation.predict_neighbors_disjoint', (['inputs', 'types', 'active_mask', 'points_mask', 'net', 'device'], {}), '(inputs, types, active_mask,\n points_mask, net, device)\n', (5248, 5306), True, 'import helpers.helpers_evaluation as helpers_evaluation\n'), ((2455, 2480), 'models.social_attention.SocialAttention', 'SocialAttention', (['args_net'], {}), '(args_net)\n', (2470, 2480), False, 'from models.social_attention import SocialAttention\n'), ((2546, 2569), 'models.s2s_spatial_attention.S2sSpatialAtt', 'S2sSpatialAtt', (['args_net'], {}), '(args_net)\n', (2559, 2569), False, 'from models.s2s_spatial_attention import S2sSpatialAtt\n')]
from .models import * from rest_framework import serializers from django.contrib.auth.password_validation import validate_password from django.core.exceptions import ValidationError class foodSerializer(serializers.ModelSerializer): class Meta: model = food fields = '__all__' class RegSerializer(serializers.ModelSerializer): class Meta: model = MyUser fields = ['username','mobno','password','gender'] extra_kwargs = {'password': {'write_only': True}} class otpSerializer(serializers.ModelSerializer): class Meta: model = otpstore fields = ['otp','mobno'] class loginSerializer(serializers.Serializer): mobno = serializers.IntegerField() class ProfileSerializer(serializers.ModelSerializer): class Meta: model = MyUser fields = ['first_name','last_name','pic','email','height','weight','target','age','bio','location','address'] def update(self, instance, validated_data): instance.first_name = validated_data.get('first_name', instance.first_name) instance.last_name = validated_data.get('last_name', instance.last_name) instance.username = validated_data.get('username', instance.username) instance.pic = validated_data.get('pic', instance.pic) instance.email = validated_data.get('email', instance.email) instance.height = validated_data.get('height', instance.height) instance.weight = validated_data.get('weight', instance.weight) instance.target = validated_data.get('target', instance.target) instance.age = validated_data.get('age', instance.age) instance.bio = validated_data.get('bio', instance.bio) instance.location = validated_data.get('location', instance.location) instance.address = validated_data.get('address', instance.address) instance.save() return instance class DietSerializer(serializers.ModelSerializer): class Meta: model = MyUser fields = ['diets'] class ExerciseSerializer(serializers.ModelSerializer): class Meta: model = MyUser fields = ['fitness'] class StreakSerializer(serializers.ModelSerializer): class Meta: model = MyUser fields = ['streaks'] class StepsSerializer(serializers.ModelSerializer): step_count = serializers.IntegerField() class Meta: model = MyUser fields = ['steps','step_count'] def update(self, instance, validated_data): st = validated_data['step_count'] d = datetime.date.today() obj = instance.steps.filter(date=d) if not obj: ob = step.objects.create(date=d,step_count=st) instance.steps.add(ob) else: for o in obj: o.step_count = st o.save() instance.save() return instance class liveSerializer(serializers.ModelSerializer): class Meta: model = MyUser fields = ['lives'] # Steps - Only POST # Streak - GET (number , points) # Live Api - GET (live fields, employee name, employee image, roomid,) # exercise plan update - (day name)
[ "rest_framework.serializers.IntegerField" ]
[((694, 720), 'rest_framework.serializers.IntegerField', 'serializers.IntegerField', ([], {}), '()\n', (718, 720), False, 'from rest_framework import serializers\n'), ((2339, 2365), 'rest_framework.serializers.IntegerField', 'serializers.IntegerField', ([], {}), '()\n', (2363, 2365), False, 'from rest_framework import serializers\n')]
# @Author: <NAME> # @Date: 2021-03-22 09:43:07 # @Last Modified by: <NAME> # @Last Modified time: 2021-11-08 15:09:29 #!/usr/bin/env python ## based on: detectron2.modeling.roi_heads.box_head ## based on: detectron2.modeling.roi_heads.fast_rcnn import torch from torch import nn import numpy as np import logging from typing import Dict, List, Tuple, Union from fvcore.nn import giou_loss, smooth_l1_loss import fvcore.nn.weight_init as weight_init from torch import nn from torch.nn import functional as F from detectron2.config import configurable, get_cfg from detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, batched_nms, cat, cross_entropy, nonzero_tuple, get_norm from detectron2.modeling.box_regression import Box2BoxTransform from detectron2.structures import Boxes, Instances from detectron2.utils.events import get_event_storage from detectron2.utils.registry import Registry ## these specific libraries are needed to alter the network architecture from detectron2.modeling.roi_heads import ROI_HEADS_REGISTRY, StandardROIHeads, Res5ROIHeads from detectron2.modeling.roi_heads.box_head import ROI_BOX_HEAD_REGISTRY from detectron2.modeling.roi_heads.fast_rcnn import fast_rcnn_inference, _log_classification_stats from detectron2.modeling.roi_heads.mask_head import ROI_MASK_HEAD_REGISTRY, BaseMaskRCNNHead @ROI_BOX_HEAD_REGISTRY.register() class FastRCNNConvFCHeadDropout(nn.Sequential): """ A head with several 3x3 conv layers (each followed by norm & relu) and then several fc layers (each followed by relu). """ @configurable def __init__( self, input_shape: ShapeSpec, *, conv_dims: List[int], fc_dims: List[int], conv_norm="", dropout_probability: float = 0.5, ): """ NOTE: this interface is experimental. Args: input_shape (ShapeSpec): shape of the input feature. conv_dims (list[int]): the output dimensions of the conv layers fc_dims (list[int]): the output dimensions of the fc layers conv_norm (str or callable): normalization for the conv layers. See :func:`detectron2.layers.get_norm` for supported types. """ super().__init__() assert len(conv_dims) + len(fc_dims) > 0 self._output_size = (input_shape.channels, input_shape.height, input_shape.width) self.conv_norm_relus = [] for k, conv_dim in enumerate(conv_dims): conv = Conv2d( self._output_size[0], conv_dim, kernel_size=3, padding=1, bias=not conv_norm, norm=get_norm(conv_norm, conv_dim), activation=nn.ReLU(), ) self.add_module("conv{}".format(k + 1), conv) self.conv_norm_relus.append(conv) self._output_size = (conv_dim, self._output_size[1], self._output_size[2]) self.fcs = [] for k, fc_dim in enumerate(fc_dims): if k == 0: self.add_module("flatten", nn.Flatten()) dropout = nn.Dropout(p=dropout_probability) self.add_module("dropout{}".format(k + 1), dropout) fc = nn.Linear(int(np.prod(self._output_size)), fc_dim) self.add_module("fc{}".format(k + 1), fc) self.add_module("fc_relu{}".format(k + 1), nn.ReLU()) self.fcs.append(fc) self._output_size = fc_dim for layer in self.conv_norm_relus: weight_init.c2_msra_fill(layer) for layer in self.fcs: weight_init.c2_xavier_fill(layer) @classmethod def from_config(cls, cfg, input_shape): num_conv = cfg.MODEL.ROI_BOX_HEAD.NUM_CONV conv_dim = cfg.MODEL.ROI_BOX_HEAD.CONV_DIM num_fc = cfg.MODEL.ROI_BOX_HEAD.NUM_FC fc_dim = cfg.MODEL.ROI_BOX_HEAD.FC_DIM return { "input_shape": input_shape, "conv_dims": [conv_dim] * num_conv, "fc_dims": [fc_dim] * num_fc, "conv_norm": cfg.MODEL.ROI_BOX_HEAD.NORM, "dropout_probability": cfg.MODEL.ROI_BOX_HEAD.DROPOUT_PROBABILITY, } def forward(self, x): for layer in self: x = layer(x) return x @property @torch.jit.unused def output_shape(self): """ Returns: ShapeSpec: the output feature shape """ o = self._output_size if isinstance(o, int): return ShapeSpec(channels=o) else: return ShapeSpec(channels=o[0], height=o[1], width=o[2]) class FastRCNNOutputLayersDropout(nn.Module): """ Two linear layers for predicting Fast R-CNN outputs: 1. proposal-to-detection box regression deltas 2. classification scores """ @configurable def __init__( self, input_shape: ShapeSpec, *, box2box_transform, num_classes: int, test_score_thresh: float = 0.0, test_nms_thresh: float = 0.5, test_topk_per_image: int = 100, cls_agnostic_bbox_reg: bool = False, smooth_l1_beta: float = 0.0, box_reg_loss_type: str = "smooth_l1", loss_weight: Union[float, Dict[str, float]] = 1.0, softmaxes: bool = False, dropout_probability: float = 0.5, ): """ NOTE: this interface is experimental. Args: input_shape (ShapeSpec): shape of the input feature to this module box2box_transform (Box2BoxTransform or Box2BoxTransformRotated): num_classes (int): number of foreground classes test_score_thresh (float): threshold to filter predictions results. test_nms_thresh (float): NMS threshold for prediction results. test_topk_per_image (int): number of top predictions to produce per image. cls_agnostic_bbox_reg (bool): whether to use class agnostic for bbox regression smooth_l1_beta (float): transition point from L1 to L2 loss. Only used if `box_reg_loss_type` is "smooth_l1" box_reg_loss_type (str): Box regression loss type. One of: "smooth_l1", "giou" loss_weight (float|dict): weights to use for losses. Can be single float for weighting all losses, or a dict of individual weightings. Valid dict keys are: * "loss_cls": applied to classification loss * "loss_box_reg": applied to box regression loss """ super().__init__() if isinstance(input_shape, int): # some backward compatibility input_shape = ShapeSpec(channels=input_shape) self.num_classes = num_classes input_size = input_shape.channels * (input_shape.width or 1) * (input_shape.height or 1) # prediction layer for num_classes foreground classes and one background class (hence + 1) self.dropout1 = nn.Dropout(p=dropout_probability) self.cls_score = nn.Linear(input_size, num_classes + 1) num_bbox_reg_classes = 1 if cls_agnostic_bbox_reg else num_classes box_dim = len(box2box_transform.weights) self.dropout2 = nn.Dropout(p=dropout_probability) self.bbox_pred = nn.Linear(input_size, num_bbox_reg_classes * box_dim) nn.init.normal_(self.cls_score.weight, std=0.01) nn.init.normal_(self.bbox_pred.weight, std=0.001) for l in [self.cls_score, self.bbox_pred]: nn.init.constant_(l.bias, 0) self.box2box_transform = box2box_transform self.smooth_l1_beta = smooth_l1_beta self.test_score_thresh = test_score_thresh self.test_nms_thresh = test_nms_thresh self.test_topk_per_image = test_topk_per_image self.box_reg_loss_type = box_reg_loss_type if isinstance(loss_weight, float): loss_weight = {"loss_cls": loss_weight, "loss_box_reg": loss_weight} self.loss_weight = loss_weight self.softmaxes = softmaxes @classmethod def from_config(cls, cfg, input_shape): return { "input_shape": input_shape, "box2box_transform": Box2BoxTransform(weights=cfg.MODEL.ROI_BOX_HEAD.BBOX_REG_WEIGHTS), # fmt: off "num_classes" : cfg.MODEL.ROI_HEADS.NUM_CLASSES, "cls_agnostic_bbox_reg" : cfg.MODEL.ROI_BOX_HEAD.CLS_AGNOSTIC_BBOX_REG, "smooth_l1_beta" : cfg.MODEL.ROI_BOX_HEAD.SMOOTH_L1_BETA, "test_score_thresh" : cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST, "test_nms_thresh" : cfg.MODEL.ROI_HEADS.NMS_THRESH_TEST, "test_topk_per_image" : cfg.TEST.DETECTIONS_PER_IMAGE, "box_reg_loss_type" : cfg.MODEL.ROI_BOX_HEAD.BBOX_REG_LOSS_TYPE, "loss_weight" : {"loss_box_reg": cfg.MODEL.ROI_BOX_HEAD.BBOX_REG_LOSS_WEIGHT}, "softmaxes" : cfg.MODEL.ROI_HEADS.SOFTMAXES, "dropout_probability" : cfg.MODEL.ROI_BOX_HEAD.DROPOUT_PROBABILITY, # fmt: on } def forward(self, x): """ Args: x: per-region features of shape (N, ...) for N bounding boxes to predict. Returns: (Tensor, Tensor): First tensor: shape (N,K+1), scores for each of the N box. Each row contains the scores for K object categories and 1 background class. Second tensor: bounding box regression deltas for each box. Shape is shape (N,Kx4), or (N,4) for class-agnostic regression. """ if x.dim() > 2: x = torch.flatten(x, start_dim=1) x = self.dropout1(x) scores = self.cls_score(x) x = self.dropout2(x) proposal_deltas = self.bbox_pred(x) return scores, proposal_deltas def losses(self, predictions, proposals): """ Args: predictions: return values of :meth:`forward()`. proposals (list[Instances]): proposals that match the features that were used to compute predictions. The fields ``proposal_boxes``, ``gt_boxes``, ``gt_classes`` are expected. Returns: Dict[str, Tensor]: dict of losses """ scores, proposal_deltas = predictions # parse classification outputs gt_classes = ( cat([p.gt_classes for p in proposals], dim=0) if len(proposals) else torch.empty(0) ) _log_classification_stats(scores, gt_classes) # parse box regression outputs if len(proposals): proposal_boxes = cat([p.proposal_boxes.tensor for p in proposals], dim=0) # Nx4 assert not proposal_boxes.requires_grad, "Proposals should not require gradients!" # If "gt_boxes" does not exist, the proposals must be all negative and # should not be included in regression loss computation. # Here we just use proposal_boxes as an arbitrary placeholder because its # value won't be used in self.box_reg_loss(). gt_boxes = cat( [(p.gt_boxes if p.has("gt_boxes") else p.proposal_boxes).tensor for p in proposals], dim=0, ) else: proposal_boxes = gt_boxes = torch.empty((0, 4), device=proposal_deltas.device) losses = { "loss_cls": cross_entropy(scores, gt_classes, reduction="mean"), "loss_box_reg": self.box_reg_loss( proposal_boxes, gt_boxes, proposal_deltas, gt_classes ), } return {k: v * self.loss_weight.get(k, 1.0) for k, v in losses.items()} def box_reg_loss(self, proposal_boxes, gt_boxes, pred_deltas, gt_classes): """ Args: All boxes are tensors with the same shape Rx(4 or 5). gt_classes is a long tensor of shape R, the gt class label of each proposal. R shall be the number of proposals. """ box_dim = proposal_boxes.shape[1] # 4 or 5 # Regression loss is only computed for foreground proposals (those matched to a GT) fg_inds = nonzero_tuple((gt_classes >= 0) & (gt_classes < self.num_classes))[0] if pred_deltas.shape[1] == box_dim: # cls-agnostic regression fg_pred_deltas = pred_deltas[fg_inds] else: fg_pred_deltas = pred_deltas.view(-1, self.num_classes, box_dim)[ fg_inds, gt_classes[fg_inds] ] if self.box_reg_loss_type == "smooth_l1": gt_pred_deltas = self.box2box_transform.get_deltas( proposal_boxes[fg_inds], gt_boxes[fg_inds], ) loss_box_reg = smooth_l1_loss( fg_pred_deltas, gt_pred_deltas, self.smooth_l1_beta, reduction="sum" ) elif self.box_reg_loss_type == "giou": fg_pred_boxes = self.box2box_transform.apply_deltas( fg_pred_deltas, proposal_boxes[fg_inds] ) loss_box_reg = giou_loss(fg_pred_boxes, gt_boxes[fg_inds], reduction="sum") else: raise ValueError(f"Invalid bbox reg loss type '{self.box_reg_loss_type}'") # The reg loss is normalized using the total number of regions (R), not the number # of foreground regions even though the box regression loss is only defined on # foreground regions. Why? Because doing so gives equal training influence to # each foreground example. To see how, consider two different minibatches: # (1) Contains a single foreground region # (2) Contains 100 foreground regions # If we normalize by the number of foreground regions, the single example in # minibatch (1) will be given 100 times as much influence as each foreground # example in minibatch (2). Normalizing by the total number of regions, R, # means that the single example in minibatch (1) and each of the 100 examples # in minibatch (2) are given equal influence. return loss_box_reg / max(gt_classes.numel(), 1.0) # return 0 if empty def inference(self, predictions: Tuple[torch.Tensor, torch.Tensor], proposals: List[Instances]): """ Args: predictions: return values of :meth:`forward()`. proposals (list[Instances]): proposals that match the features that were used to compute predictions. The ``proposal_boxes`` field is expected. Returns: list[Instances]: same as `fast_rcnn_inference`. list[Tensor]: same as `fast_rcnn_inference`. """ boxes = self.predict_boxes(predictions, proposals) scores = self.predict_probs(predictions, proposals) image_shapes = [x.image_size for x in proposals] return fast_rcnn_inference( boxes, scores, image_shapes, self.test_score_thresh, self.test_nms_thresh, self.test_topk_per_image, self.softmaxes, ) def predict_boxes_for_gt_classes(self, predictions, proposals): """ Args: predictions: return values of :meth:`forward()`. proposals (list[Instances]): proposals that match the features that were used to compute predictions. The fields ``proposal_boxes``, ``gt_classes`` are expected. Returns: list[Tensor]: A list of Tensors of predicted boxes for GT classes in case of class-specific box head. Element i of the list has shape (Ri, B), where Ri is the number of proposals for image i and B is the box dimension (4 or 5) """ if not len(proposals): return [] scores, proposal_deltas = predictions proposal_boxes = cat([p.proposal_boxes.tensor for p in proposals], dim=0) N, B = proposal_boxes.shape predict_boxes = self.box2box_transform.apply_deltas( proposal_deltas, proposal_boxes ) # Nx(KxB) K = predict_boxes.shape[1] // B if K > 1: gt_classes = torch.cat([p.gt_classes for p in proposals], dim=0) # Some proposals are ignored or have a background class. Their gt_classes # cannot be used as index. gt_classes = gt_classes.clamp_(0, K - 1) predict_boxes = predict_boxes.view(N, K, B)[ torch.arange(N, dtype=torch.long, device=predict_boxes.device), gt_classes ] num_prop_per_image = [len(p) for p in proposals] return predict_boxes.split(num_prop_per_image) def predict_boxes( self, predictions: Tuple[torch.Tensor, torch.Tensor], proposals: List[Instances] ): """ Args: predictions: return values of :meth:`forward()`. proposals (list[Instances]): proposals that match the features that were used to compute predictions. The ``proposal_boxes`` field is expected. Returns: list[Tensor]: A list of Tensors of predicted class-specific or class-agnostic boxes for each image. Element i has shape (Ri, K * B) or (Ri, B), where Ri is the number of proposals for image i and B is the box dimension (4 or 5) """ if not len(proposals): return [] _, proposal_deltas = predictions num_prop_per_image = [len(p) for p in proposals] proposal_boxes = cat([p.proposal_boxes.tensor for p in proposals], dim=0) predict_boxes = self.box2box_transform.apply_deltas( proposal_deltas, proposal_boxes, ) # Nx(KxB) return predict_boxes.split(num_prop_per_image) def predict_probs( self, predictions: Tuple[torch.Tensor, torch.Tensor], proposals: List[Instances] ): """ Args: predictions: return values of :meth:`forward()`. proposals (list[Instances]): proposals that match the features that were used to compute predictions. Returns: list[Tensor]: A list of Tensors of predicted class probabilities for each image. Element i has shape (Ri, K + 1), where Ri is the number of proposals for image i. """ scores, _ = predictions num_inst_per_image = [len(p) for p in proposals] probs = F.softmax(scores, dim=-1) return probs.split(num_inst_per_image, dim=0) @ROI_HEADS_REGISTRY.register() class Res5ROIHeadsDropout(Res5ROIHeads): def __init__(self, cfg, input_shape): super().__init__(cfg, input_shape, box_predictor=FastRCNNOutputLayersDropout(cfg, 2048)) @ROI_HEADS_REGISTRY.register() class StandardROIHeadsDropout(StandardROIHeads): def __init__(self, cfg, input_shape): super().__init__(cfg, input_shape, box_predictor=FastRCNNOutputLayersDropout(cfg, 1024)) @ROI_MASK_HEAD_REGISTRY.register() class MaskRCNNConvUpsampleHeadDropout(BaseMaskRCNNHead, nn.Sequential): """ A mask head with several conv layers, plus an upsample layer (with `ConvTranspose2d`). Predictions are made with a final 1x1 conv layer. """ @configurable def __init__(self, input_shape: ShapeSpec, *, num_classes, conv_dims, conv_norm="", dropout_probability: float = 0.5, **kwargs): """ NOTE: this interface is experimental. Args: input_shape (ShapeSpec): shape of the input feature num_classes (int): the number of foreground classes (i.e. background is not included). 1 if using class agnostic prediction. conv_dims (list[int]): a list of N>0 integers representing the output dimensions of N-1 conv layers and the last upsample layer. conv_norm (str or callable): normalization for the conv layers. See :func:`detectron2.layers.get_norm` for supported types. """ super().__init__(**kwargs) assert len(conv_dims) >= 1, "conv_dims have to be non-empty!" self.conv_norm_relus = [] cur_channels = input_shape.channels for k, conv_dim in enumerate(conv_dims[:-1]): conv = Conv2d( cur_channels, conv_dim, kernel_size=3, stride=1, padding=1, bias=not conv_norm, norm=get_norm(conv_norm, conv_dim), activation=nn.ReLU(), ) self.add_module("mask_fcn{}".format(k + 1), conv) self.conv_norm_relus.append(conv) cur_channels = conv_dim self.dropout1 = nn.Dropout(p=dropout_probability) self.deconv = ConvTranspose2d( cur_channels, conv_dims[-1], kernel_size=2, stride=2, padding=0 ) self.add_module("deconv_relu", nn.ReLU()) cur_channels = conv_dims[-1] self.dropout2 = nn.Dropout(p=dropout_probability) self.predictor = Conv2d(cur_channels, num_classes, kernel_size=1, stride=1, padding=0) for layer in self.conv_norm_relus + [self.deconv]: weight_init.c2_msra_fill(layer) # use normal distribution initialization for mask prediction layer nn.init.normal_(self.predictor.weight, std=0.001) if self.predictor.bias is not None: nn.init.constant_(self.predictor.bias, 0) @classmethod def from_config(cls, cfg, input_shape): ret = super().from_config(cfg, input_shape) conv_dim = cfg.MODEL.ROI_MASK_HEAD.CONV_DIM num_conv = cfg.MODEL.ROI_MASK_HEAD.NUM_CONV ret.update( conv_dims=[conv_dim] * (num_conv + 1), # +1 for ConvTranspose conv_norm=cfg.MODEL.ROI_MASK_HEAD.NORM, input_shape=input_shape, ) if cfg.MODEL.ROI_MASK_HEAD.CLS_AGNOSTIC_MASK: ret["num_classes"] = 1 else: ret["num_classes"] = cfg.MODEL.ROI_HEADS.NUM_CLASSES ret["dropout_probability"] = cfg.MODEL.ROI_MASK_HEAD.DROPOUT_PROBABILITY return ret def layers(self, x): for layer in self: x = layer(x) return x
[ "numpy.prod", "torch.nn.ReLU", "torch.nn.Dropout", "detectron2.modeling.roi_heads.fast_rcnn._log_classification_stats", "torch.nn.init.constant_", "detectron2.layers.cross_entropy", "fvcore.nn.smooth_l1_loss", "torch.nn.functional.softmax", "torch.arange", "detectron2.layers.ShapeSpec", "torch.n...
[((1340, 1372), 'detectron2.modeling.roi_heads.box_head.ROI_BOX_HEAD_REGISTRY.register', 'ROI_BOX_HEAD_REGISTRY.register', ([], {}), '()\n', (1370, 1372), False, 'from detectron2.modeling.roi_heads.box_head import ROI_BOX_HEAD_REGISTRY\n'), ((18533, 18562), 'detectron2.modeling.roi_heads.ROI_HEADS_REGISTRY.register', 'ROI_HEADS_REGISTRY.register', ([], {}), '()\n', (18560, 18562), False, 'from detectron2.modeling.roi_heads import ROI_HEADS_REGISTRY, StandardROIHeads, Res5ROIHeads\n'), ((18751, 18780), 'detectron2.modeling.roi_heads.ROI_HEADS_REGISTRY.register', 'ROI_HEADS_REGISTRY.register', ([], {}), '()\n', (18778, 18780), False, 'from detectron2.modeling.roi_heads import ROI_HEADS_REGISTRY, StandardROIHeads, Res5ROIHeads\n'), ((18973, 19006), 'detectron2.modeling.roi_heads.mask_head.ROI_MASK_HEAD_REGISTRY.register', 'ROI_MASK_HEAD_REGISTRY.register', ([], {}), '()\n', (19004, 19006), False, 'from detectron2.modeling.roi_heads.mask_head import ROI_MASK_HEAD_REGISTRY, BaseMaskRCNNHead\n'), ((6937, 6970), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': 'dropout_probability'}), '(p=dropout_probability)\n', (6947, 6970), False, 'from torch import nn\n'), ((6996, 7034), 'torch.nn.Linear', 'nn.Linear', (['input_size', '(num_classes + 1)'], {}), '(input_size, num_classes + 1)\n', (7005, 7034), False, 'from torch import nn\n'), ((7183, 7216), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': 'dropout_probability'}), '(p=dropout_probability)\n', (7193, 7216), False, 'from torch import nn\n'), ((7242, 7295), 'torch.nn.Linear', 'nn.Linear', (['input_size', '(num_bbox_reg_classes * box_dim)'], {}), '(input_size, num_bbox_reg_classes * box_dim)\n', (7251, 7295), False, 'from torch import nn\n'), ((7305, 7353), 'torch.nn.init.normal_', 'nn.init.normal_', (['self.cls_score.weight'], {'std': '(0.01)'}), '(self.cls_score.weight, std=0.01)\n', (7320, 7353), False, 'from torch import nn\n'), ((7362, 7411), 'torch.nn.init.normal_', 'nn.init.normal_', (['self.bbox_pred.weight'], {'std': '(0.001)'}), '(self.bbox_pred.weight, std=0.001)\n', (7377, 7411), False, 'from torch import nn\n'), ((10471, 10516), 'detectron2.modeling.roi_heads.fast_rcnn._log_classification_stats', '_log_classification_stats', (['scores', 'gt_classes'], {}), '(scores, gt_classes)\n', (10496, 10516), False, 'from detectron2.modeling.roi_heads.fast_rcnn import fast_rcnn_inference, _log_classification_stats\n'), ((14819, 14959), 'detectron2.modeling.roi_heads.fast_rcnn.fast_rcnn_inference', 'fast_rcnn_inference', (['boxes', 'scores', 'image_shapes', 'self.test_score_thresh', 'self.test_nms_thresh', 'self.test_topk_per_image', 'self.softmaxes'], {}), '(boxes, scores, image_shapes, self.test_score_thresh,\n self.test_nms_thresh, self.test_topk_per_image, self.softmaxes)\n', (14838, 14959), False, 'from detectron2.modeling.roi_heads.fast_rcnn import fast_rcnn_inference, _log_classification_stats\n'), ((15838, 15894), 'detectron2.layers.cat', 'cat', (['[p.proposal_boxes.tensor for p in proposals]'], {'dim': '(0)'}), '([p.proposal_boxes.tensor for p in proposals], dim=0)\n', (15841, 15894), False, 'from detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, batched_nms, cat, cross_entropy, nonzero_tuple, get_norm\n'), ((17519, 17575), 'detectron2.layers.cat', 'cat', (['[p.proposal_boxes.tensor for p in proposals]'], {'dim': '(0)'}), '([p.proposal_boxes.tensor for p in proposals], dim=0)\n', (17522, 17575), False, 'from detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, batched_nms, cat, cross_entropy, nonzero_tuple, get_norm\n'), ((18449, 18474), 'torch.nn.functional.softmax', 'F.softmax', (['scores'], {'dim': '(-1)'}), '(scores, dim=-1)\n', (18458, 18474), True, 'from torch.nn import functional as F\n'), ((20731, 20764), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': 'dropout_probability'}), '(p=dropout_probability)\n', (20741, 20764), False, 'from torch import nn\n'), ((20788, 20873), 'detectron2.layers.ConvTranspose2d', 'ConvTranspose2d', (['cur_channels', 'conv_dims[-1]'], {'kernel_size': '(2)', 'stride': '(2)', 'padding': '(0)'}), '(cur_channels, conv_dims[-1], kernel_size=2, stride=2, padding=0\n )\n', (20803, 20873), False, 'from detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, batched_nms, cat, cross_entropy, nonzero_tuple, get_norm\n'), ((21003, 21036), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': 'dropout_probability'}), '(p=dropout_probability)\n', (21013, 21036), False, 'from torch import nn\n'), ((21063, 21132), 'detectron2.layers.Conv2d', 'Conv2d', (['cur_channels', 'num_classes'], {'kernel_size': '(1)', 'stride': '(1)', 'padding': '(0)'}), '(cur_channels, num_classes, kernel_size=1, stride=1, padding=0)\n', (21069, 21132), False, 'from detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, batched_nms, cat, cross_entropy, nonzero_tuple, get_norm\n'), ((21320, 21369), 'torch.nn.init.normal_', 'nn.init.normal_', (['self.predictor.weight'], {'std': '(0.001)'}), '(self.predictor.weight, std=0.001)\n', (21335, 21369), False, 'from torch import nn\n'), ((3098, 3131), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': 'dropout_probability'}), '(p=dropout_probability)\n', (3108, 3131), False, 'from torch import nn\n'), ((3511, 3542), 'fvcore.nn.weight_init.c2_msra_fill', 'weight_init.c2_msra_fill', (['layer'], {}), '(layer)\n', (3535, 3542), True, 'import fvcore.nn.weight_init as weight_init\n'), ((3586, 3619), 'fvcore.nn.weight_init.c2_xavier_fill', 'weight_init.c2_xavier_fill', (['layer'], {}), '(layer)\n', (3612, 3619), True, 'import fvcore.nn.weight_init as weight_init\n'), ((4498, 4519), 'detectron2.layers.ShapeSpec', 'ShapeSpec', ([], {'channels': 'o'}), '(channels=o)\n', (4507, 4519), False, 'from detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, batched_nms, cat, cross_entropy, nonzero_tuple, get_norm\n'), ((4553, 4602), 'detectron2.layers.ShapeSpec', 'ShapeSpec', ([], {'channels': 'o[0]', 'height': 'o[1]', 'width': 'o[2]'}), '(channels=o[0], height=o[1], width=o[2])\n', (4562, 4602), False, 'from detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, batched_nms, cat, cross_entropy, nonzero_tuple, get_norm\n'), ((6646, 6677), 'detectron2.layers.ShapeSpec', 'ShapeSpec', ([], {'channels': 'input_shape'}), '(channels=input_shape)\n', (6655, 6677), False, 'from detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, batched_nms, cat, cross_entropy, nonzero_tuple, get_norm\n'), ((7475, 7503), 'torch.nn.init.constant_', 'nn.init.constant_', (['l.bias', '(0)'], {}), '(l.bias, 0)\n', (7492, 7503), False, 'from torch import nn\n'), ((8156, 8221), 'detectron2.modeling.box_regression.Box2BoxTransform', 'Box2BoxTransform', ([], {'weights': 'cfg.MODEL.ROI_BOX_HEAD.BBOX_REG_WEIGHTS'}), '(weights=cfg.MODEL.ROI_BOX_HEAD.BBOX_REG_WEIGHTS)\n', (8172, 8221), False, 'from detectron2.modeling.box_regression import Box2BoxTransform\n'), ((9612, 9641), 'torch.flatten', 'torch.flatten', (['x'], {'start_dim': '(1)'}), '(x, start_dim=1)\n', (9625, 9641), False, 'import torch\n'), ((10369, 10414), 'detectron2.layers.cat', 'cat', (['[p.gt_classes for p in proposals]'], {'dim': '(0)'}), '([p.gt_classes for p in proposals], dim=0)\n', (10372, 10414), False, 'from detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, batched_nms, cat, cross_entropy, nonzero_tuple, get_norm\n'), ((10438, 10452), 'torch.empty', 'torch.empty', (['(0)'], {}), '(0)\n', (10449, 10452), False, 'import torch\n'), ((10613, 10669), 'detectron2.layers.cat', 'cat', (['[p.proposal_boxes.tensor for p in proposals]'], {'dim': '(0)'}), '([p.proposal_boxes.tensor for p in proposals], dim=0)\n', (10616, 10669), False, 'from detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, batched_nms, cat, cross_entropy, nonzero_tuple, get_norm\n'), ((11288, 11338), 'torch.empty', 'torch.empty', (['(0, 4)'], {'device': 'proposal_deltas.device'}), '((0, 4), device=proposal_deltas.device)\n', (11299, 11338), False, 'import torch\n'), ((11383, 11434), 'detectron2.layers.cross_entropy', 'cross_entropy', (['scores', 'gt_classes'], {'reduction': '"""mean"""'}), "(scores, gt_classes, reduction='mean')\n", (11396, 11434), False, 'from detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, batched_nms, cat, cross_entropy, nonzero_tuple, get_norm\n'), ((12141, 12207), 'detectron2.layers.nonzero_tuple', 'nonzero_tuple', (['((gt_classes >= 0) & (gt_classes < self.num_classes))'], {}), '((gt_classes >= 0) & (gt_classes < self.num_classes))\n', (12154, 12207), False, 'from detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, batched_nms, cat, cross_entropy, nonzero_tuple, get_norm\n'), ((12715, 12803), 'fvcore.nn.smooth_l1_loss', 'smooth_l1_loss', (['fg_pred_deltas', 'gt_pred_deltas', 'self.smooth_l1_beta'], {'reduction': '"""sum"""'}), "(fg_pred_deltas, gt_pred_deltas, self.smooth_l1_beta,\n reduction='sum')\n", (12729, 12803), False, 'from fvcore.nn import giou_loss, smooth_l1_loss\n'), ((16141, 16192), 'torch.cat', 'torch.cat', (['[p.gt_classes for p in proposals]'], {'dim': '(0)'}), '([p.gt_classes for p in proposals], dim=0)\n', (16150, 16192), False, 'import torch\n'), ((20930, 20939), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (20937, 20939), False, 'from torch import nn\n'), ((21205, 21236), 'fvcore.nn.weight_init.c2_msra_fill', 'weight_init.c2_msra_fill', (['layer'], {}), '(layer)\n', (21229, 21236), True, 'import fvcore.nn.weight_init as weight_init\n'), ((21426, 21467), 'torch.nn.init.constant_', 'nn.init.constant_', (['self.predictor.bias', '(0)'], {}), '(self.predictor.bias, 0)\n', (21443, 21467), False, 'from torch import nn\n'), ((3373, 3382), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (3380, 3382), False, 'from torch import nn\n'), ((13039, 13099), 'fvcore.nn.giou_loss', 'giou_loss', (['fg_pred_boxes', 'gt_boxes[fg_inds]'], {'reduction': '"""sum"""'}), "(fg_pred_boxes, gt_boxes[fg_inds], reduction='sum')\n", (13048, 13099), False, 'from fvcore.nn import giou_loss, smooth_l1_loss\n'), ((2654, 2683), 'detectron2.layers.get_norm', 'get_norm', (['conv_norm', 'conv_dim'], {}), '(conv_norm, conv_dim)\n', (2662, 2683), False, 'from detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, batched_nms, cat, cross_entropy, nonzero_tuple, get_norm\n'), ((2712, 2721), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (2719, 2721), False, 'from torch import nn\n'), ((3062, 3074), 'torch.nn.Flatten', 'nn.Flatten', ([], {}), '()\n', (3072, 3074), False, 'from torch import nn\n'), ((3227, 3253), 'numpy.prod', 'np.prod', (['self._output_size'], {}), '(self._output_size)\n', (3234, 3253), True, 'import numpy as np\n'), ((16445, 16507), 'torch.arange', 'torch.arange', (['N'], {'dtype': 'torch.long', 'device': 'predict_boxes.device'}), '(N, dtype=torch.long, device=predict_boxes.device)\n', (16457, 16507), False, 'import torch\n'), ((20479, 20508), 'detectron2.layers.get_norm', 'get_norm', (['conv_norm', 'conv_dim'], {}), '(conv_norm, conv_dim)\n', (20487, 20508), False, 'from detectron2.layers import Conv2d, ConvTranspose2d, ShapeSpec, batched_nms, cat, cross_entropy, nonzero_tuple, get_norm\n'), ((20537, 20546), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (20544, 20546), False, 'from torch import nn\n')]
from dataclasses import dataclass, field from typing import Dict, List, Optional from .node_action import NodeAction from .node_id_filter import NodeIdFilter @dataclass class NodeRunCommandAction(NodeAction): action: str = field(default="RUN_COMMAND", init=False) path: str arguments: Optional[List[str]] = None environment: Optional[Dict[str, str]] = None nodeIdFilter: Optional[NodeIdFilter] = None nodeTypes: Optional[List[str]] = None
[ "dataclasses.field" ]
[((230, 270), 'dataclasses.field', 'field', ([], {'default': '"""RUN_COMMAND"""', 'init': '(False)'}), "(default='RUN_COMMAND', init=False)\n", (235, 270), False, 'from dataclasses import dataclass, field\n')]
#thomas feiring model import math import numpy as np import pandas as pd #enter the year for which you need prediction starting 2019 year=2019 number_of_days=365 day=0 df = pd.read_csv('groundtruth.csv') u=df['Mean'] X_t= u[0] sd=df['St dev'] print("Month,Year,Inflow") #lag -1 correlation lag=df['co relation'] np.random.seed(9001) for i in range(number_of_days): rn=np.random.normal(0,1,1)[0] z_t=(X_t-u[day])/sd[day] z_t1=lag[day]*z_t+rn*math.sqrt(1-lag[day]*lag[day]) X_t1=u[(day+1)%365]+z_t1*sd[(day+1)%365] print(day+1,",",year,",",X_t1) if(day==364): year=year+1 day=0 day=day+1 X_t=X_t1
[ "numpy.random.normal", "math.sqrt", "numpy.random.seed", "pandas.read_csv" ]
[((174, 204), 'pandas.read_csv', 'pd.read_csv', (['"""groundtruth.csv"""'], {}), "('groundtruth.csv')\n", (185, 204), True, 'import pandas as pd\n'), ((313, 333), 'numpy.random.seed', 'np.random.seed', (['(9001)'], {}), '(9001)\n', (327, 333), True, 'import numpy as np\n'), ((373, 398), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)', '(1)'], {}), '(0, 1, 1)\n', (389, 398), True, 'import numpy as np\n'), ((454, 488), 'math.sqrt', 'math.sqrt', (['(1 - lag[day] * lag[day])'], {}), '(1 - lag[day] * lag[day])\n', (463, 488), False, 'import math\n')]
"""REST client handling, including GitHubStream base class.""" import requests from os import environ from typing import Any, Dict, List, Optional, Iterable, cast from singer_sdk.streams import RESTStream class GitHubStream(RESTStream): """GitHub stream class.""" MAX_PER_PAGE = 1000 MAX_RESULTS_LIMIT: Optional[int] = None DEFAULT_API_BASE_URL = "https://api.github.com" LOG_REQUEST_METRIC_URLS = True @property def url_base(self) -> str: return self.config.get("api_url_base", self.DEFAULT_API_BASE_URL) primary_keys = ["id"] replication_key: Optional[str] = None tolerated_http_errors: List[int] = [] @property def http_headers(self) -> dict: """Return the http headers needed.""" headers = {"Accept": "application/vnd.github.v3+json"} if "user_agent" in self.config: headers["User-Agent"] = cast(str, self.config.get("user_agent")) if "auth_token" in self.config: headers["Authorization"] = f"token {self.config['auth_token']}" elif "GITHUB_TOKEN" in environ: self.logger.info( "Found 'GITHUB_TOKEN' environment variable for authentication." ) headers["Authorization"] = f"token {environ['GITHUB_TOKEN']}" else: self.logger.info( "No auth token detected. " "For higher rate limits, please specify `auth_token` in config." ) return headers def get_next_page_token( self, response: requests.Response, previous_token: Optional[Any] ) -> Optional[Any]: """Return a token for identifying next page or None if no more pages.""" if ( previous_token and self.MAX_RESULTS_LIMIT and ( cast(int, previous_token) * self.MAX_PER_PAGE >= self.MAX_RESULTS_LIMIT ) ): return None resp_json = response.json() if isinstance(resp_json, list): results = resp_json else: results = resp_json.get("items") if results: # Paginate as long as the response has items return (previous_token or 1) + 1 return None def get_url_params( self, context: Optional[dict], next_page_token: Optional[Any] ) -> Dict[str, Any]: """Return a dictionary of values to be used in URL parameterization.""" params: dict = {"per_page": self.MAX_PER_PAGE} if next_page_token: params["page"] = next_page_token if self.replication_key: params["sort"] = "updated" params["direction"] = "asc" since = self.get_starting_timestamp(context) if since: params["since"] = since return params def _request_with_backoff( self, prepared_request, context: Optional[dict] ) -> requests.Response: """Override private method _request_with_backoff to account for expected 404 Not Found erros.""" # TODO - Adapt Singer response = self.requests_session.send(prepared_request) if self._LOG_REQUEST_METRICS: extra_tags = {} if self._LOG_REQUEST_METRIC_URLS: extra_tags["url"] = cast(str, prepared_request.path_url) self._write_request_duration_log( endpoint=self.path, response=response, context=context, extra_tags=extra_tags, ) if response.status_code in self.tolerated_http_errors: self.logger.info( "Request returned a tolerated error for {}".format(prepared_request.url) ) self.logger.info( f"Reason: {response.status_code} - {str(response.content)}" ) return response if response.status_code in [401, 403]: self.logger.info("Failed request for {}".format(prepared_request.url)) self.logger.info( f"Reason: {response.status_code} - {str(response.content)}" ) raise RuntimeError( "Requested resource was unauthorized, forbidden, or not found." ) elif response.status_code >= 400: raise RuntimeError( f"Error making request to API: {prepared_request.url} " f"[{response.status_code} - {str(response.content)}]".replace( "\\n", "\n" ) ) self.logger.debug("Response received successfully.") return response def parse_response(self, response: requests.Response) -> Iterable[dict]: """Parse the response and return an iterator of result rows.""" # TODO - Split into handle_reponse and parse_response. if response.status_code in self.tolerated_http_errors: return [] resp_json = response.json() if isinstance(resp_json, list): results = resp_json elif resp_json.get("items") is not None: results = resp_json.get("items") else: results = [resp_json] for row in results: yield row
[ "typing.cast" ]
[((3295, 3331), 'typing.cast', 'cast', (['str', 'prepared_request.path_url'], {}), '(str, prepared_request.path_url)\n', (3299, 3331), False, 'from typing import Any, Dict, List, Optional, Iterable, cast\n'), ((1818, 1843), 'typing.cast', 'cast', (['int', 'previous_token'], {}), '(int, previous_token)\n', (1822, 1843), False, 'from typing import Any, Dict, List, Optional, Iterable, cast\n')]
#!/usr/bin/env python """ Update autogenerated source files from yaml database. Copyright (c) 2019, vit9696 """ from __future__ import print_function import update_products import fnmatch import operator import os import unicodedata import sys import yaml def remove_accents(input_str): nfkd_form = unicodedata.normalize('NFKD', input_str) return u"".join([c for c in nfkd_form if not unicodedata.combining(c)]) def load_db(dbpath): """ Load yaml database and return in a list. """ if not os.path.exists(dbpath): print("Cannot find %s directory, rerun from MacInfoPkg directory!" % dbpath) sys.exit(1) db = [] for root, dirs, files in os.walk(dbpath): for file in fnmatch.filter(files, '*.yaml'): path = os.path.join(root, file) with open(path, 'r') as fh: try: r = yaml.safe_load(fh) if r.get('SystemProductName', None) is None: print("WARN: Missing SystemProductName in %s, skipping!" % path) continue db.append(r) except yaml.YAMLError as e: print("Failed to parse file %s - %s" % (path, e)) sys.exit(1) if len(db) == 0: print("Empty database!") sys.exit(1) # Sorting is required for fast lookup. return sorted(db, key=operator.itemgetter('SystemProductName')) def gather_products(db): """ Obtain all product codes from the database """ products = [] for info in db: pp = info.get('AppleModelCode', None) if pp is None: continue for p in pp: if p == '': print("ERROR: %s in contains empty AppleModelCode, skipping!" % info['SystemProductName']) sys.exit(1) if p == '000' or p == '0000': print("WARN: %s in contains zero AppleModelCode, skipping!" % info['SystemProductName']) continue if p in products: print("ERROR: %s shares AppleModelCode %s with other model!" % (info['SystemProductName'], p)) sys.exit(1) products.append(p) return products def validate_products(db, dbpd): usedproducts = gather_products(db) knownproducts = dbpd for product in usedproducts: if knownproducts.get(product, None) is None: print("ERROR: Model %s is used in DataBase but not present in Products!" % product) sys.exit(1) if knownproducts[product][update_products.KEY_STATUS] != update_products.STATUS_OK: print("ERROR: Model %s is used in DataBase but not valid in Products!" % product) sys.exit(1) to_add = {} for product in knownproducts: if knownproducts[product][update_products.KEY_STATUS] != update_products.STATUS_OK: continue name = knownproducts[product][update_products.KEY_NAME] if name.find('Mac') < 0 and name.find('Xserve') < 0: continue if len(product) > 3 and product not in usedproducts: print("WARN: Model %s (%s) is known but is not used in DataBase!" % (product, name)) if to_add.get(name, None) is None: to_add[name] = [] to_add[name].append(product) continue if len(to_add) > 0: for sysname in to_add: for info in db: if sysname in info['Specifications']['SystemReportName']: print("New AppleModelCode for {}:".format(info['SystemProductName'])) for model in to_add[sysname]: print(" - \"{}\"".format(model)) def export_db_macinfolib(db, path, year=0): """ Export yaml database to MacInfoLib format. TODO: use jinja2? """ with open(path, 'w') as fh: print('// DO NOT EDIT! This is an autogenerated file.', file=fh) print('#include "MacInfoInternal.h"', file=fh) print('CONST MAC_INFO_INTERNAL_ENTRY gMacInfoModels[] = {', file=fh) for info in db: if max(info['AppleModelYear']) < year: continue print(' {\n' ' .SystemProductName = "%s",\n' ' .BoardProduct = "%s",\n' ' .BoardRevision = %s,\n' ' .SmcRevision = {%s},\n' ' .SmcBranch = {%s},\n' ' .SmcPlatform = {%s},\n' ' .BIOSVersion = "%s",\n' ' .BIOSReleaseDate = "%s",\n' ' .SystemVersion = "%s",\n' ' .SystemSKUNumber = "%s",\n' ' .SystemFamily = "%s",\n' ' .BoardVersion = "%s",\n' ' .BoardAssetTag = "%s",\n' ' .BoardLocationInChassis = "%s",\n' ' .SmcGeneration = 0x%X,\n' ' .BoardType = 0x%X,\n' ' .ChassisType = 0x%X,\n' ' .MemoryFormFactor = 0x%X,\n' ' .PlatformFeature = %s,\n' ' .ChassisAssetTag = "%s",\n' ' .FirmwareFeatures = 0x%XULL,\n' ' .FirmwareFeaturesMask = 0x%XULL,\n' ' },' % ( info['SystemProductName'], info['BoardProduct'][0] if isinstance(info['BoardProduct'], list) else info['BoardProduct'], '0x{:X}'.format(info['BoardRevision']) if 'BoardRevision' in info else 'MAC_INFO_BOARD_REVISION_MISSING', ', '.join(map(str, info.get('SmcRevision', [0x00]))), ', '.join(map(str, info.get('SmcBranch', [0x00]))), ', '.join(map(str, info.get('SmcPlatform', [0x00]))), info['BIOSVersion'], info['BIOSReleaseDate'], info['SystemVersion'], info['SystemSKUNumber'], info['SystemFamily'], info['BoardVersion'], info['BoardAssetTag'], info['BoardLocationInChassis'], info['SmcGeneration'], info['BoardType'], info['ChassisType'], info['MemoryFormFactor'], '0x{:X}'.format(info['PlatformFeature']) if 'PlatformFeature' in info else 'MAC_INFO_PLATFORM_FEATURE_MISSING', info['ChassisAssetTag'], info.get('ExtendedFirmwareFeatures', info.get('FirmwareFeatures', 0)), info.get('ExtendedFirmwareFeaturesMask', info.get('FirmwareFeaturesMask', 0)) ), file=fh) print('};', file=fh) print('CONST UINTN gMacInfoModelCount = ARRAY_SIZE (gMacInfoModels);', file=fh) print('CONST UINTN gMacInfoDefaultModel = 0;', file=fh) def export_db_macserial(db, dbpd, path, year=0): """ Export yaml database to macserial format. TODO: use jinja2? """ with open(path, 'w') as fh: print('#ifndef GENSERIAL_MODELINFO_AUTOGEN_H', file=fh) print('#define GENSERIAL_MODELINFO_AUTOGEN_H\n', file=fh) print('// DO NOT EDIT! This is an autogenerated file.\n', file=fh) print('#include "macserial.h"\n', file=fh) print('typedef enum {', file=fh) for info in db: print(' {}, // {}'.format( info['SystemProductName'].replace(',', '_'), info['Specifications']['CPU'][0] ), file=fh) print('} AppleModel;\n', file=fh) print('#define APPLE_MODEL_MAX {}\n'.format(len(db)), file=fh) print('static PLATFORMDATA ApplePlatformData[] = {', file=fh) for info in db: print(' {{ "{}", "{}" }},'.format( info['SystemProductName'], info['SystemSerialNumber'] ), file=fh) print('};\n', file=fh) print('#define APPLE_MODEL_CODE_MAX {}'.format(max(len(info['AppleModelCode']) for info in db)), file=fh) print('static const char *AppleModelCode[][APPLE_MODEL_CODE_MAX] = {', file=fh) for info in db: print(' /* {:14} */ {{"{}"}},'.format( info['SystemProductName'], '", "'.join(info['AppleModelCode']) ), file=fh) print('};\n', file=fh) print('#define APPLE_BOARD_CODE_MAX {}'.format(max(len(info['AppleBoardCode']) for info in db)), file=fh) print('static const char *AppleBoardCode[][APPLE_BOARD_CODE_MAX] = {', file=fh) for info in db: print(' /* {:14} */ {{"{}"}},'.format( info['SystemProductName'], '", "'.join(info['AppleBoardCode']) ), file=fh) print('};\n', file=fh) print('#define APPLE_MODEL_YEAR_MAX {}'.format(max(len(info['AppleModelYear']) for info in db)), file=fh) print('static uint32_t AppleModelYear[][APPLE_MODEL_YEAR_MAX] = {', file=fh) for info in db: print(' /* {:14} */ {{{}}},'.format( info['SystemProductName'], ', '.join(str(year) for year in info['AppleModelYear']) ), file=fh) print('};\n', file=fh) print('static uint32_t ApplePreferredModelYear[] = {', file=fh) for info in db: print(' /* {:14} */ {},'.format( info['SystemProductName'], info.get('MacserialModelYear', 0) ), file=fh) print('};\n', file=fh) print('static APPLE_MODEL_DESC AppleModelDesc[] = {', file=fh) models = sorted(dbpd.keys()) models.sort(key=len) for model in models: if dbpd[model][update_products.KEY_STATUS] == update_products.STATUS_OK: print(' {{"{}", "{}"}},'.format( model, remove_accents(dbpd[model][update_products.KEY_NAME]) ), file=fh) print('};\n', file=fh) print('#endif // GENSERIAL_MODELINFO_AUTOGEN_H', file=fh) if __name__ == '__main__': db = load_db('DataBase') dbpd = update_products.load_products() # Run test phase to validate the library validate_products(db, dbpd) export_db_macinfolib(db, os.devnull) export_db_macserial(db, dbpd, os.devnull) # Export new models export_db_macinfolib(db, 'Library/MacInfoLib/AutoGenerated.c', 2012) export_db_macserial(db, dbpd, 'macserial/src/modelinfo_autogen.h')
[ "os.path.exists", "update_products.load_products", "unicodedata.combining", "os.path.join", "yaml.safe_load", "unicodedata.normalize", "sys.exit", "fnmatch.filter", "operator.itemgetter", "os.walk" ]
[((307, 347), 'unicodedata.normalize', 'unicodedata.normalize', (['"""NFKD"""', 'input_str'], {}), "('NFKD', input_str)\n", (328, 347), False, 'import unicodedata\n'), ((669, 684), 'os.walk', 'os.walk', (['dbpath'], {}), '(dbpath)\n', (676, 684), False, 'import os\n'), ((8974, 9005), 'update_products.load_products', 'update_products.load_products', ([], {}), '()\n', (9003, 9005), False, 'import update_products\n'), ((509, 531), 'os.path.exists', 'os.path.exists', (['dbpath'], {}), '(dbpath)\n', (523, 531), False, 'import os\n'), ((618, 629), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (626, 629), False, 'import sys\n'), ((702, 733), 'fnmatch.filter', 'fnmatch.filter', (['files', '"""*.yaml"""'], {}), "(files, '*.yaml')\n", (716, 733), False, 'import fnmatch\n'), ((1218, 1229), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (1226, 1229), False, 'import sys\n'), ((748, 772), 'os.path.join', 'os.path.join', (['root', 'file'], {}), '(root, file)\n', (760, 772), False, 'import os\n'), ((1296, 1336), 'operator.itemgetter', 'operator.itemgetter', (['"""SystemProductName"""'], {}), "('SystemProductName')\n", (1315, 1336), False, 'import operator\n'), ((2296, 2307), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (2304, 2307), False, 'import sys\n'), ((2490, 2501), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (2498, 2501), False, 'import sys\n'), ((1673, 1684), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (1681, 1684), False, 'import sys\n'), ((1970, 1981), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (1978, 1981), False, 'import sys\n'), ((395, 419), 'unicodedata.combining', 'unicodedata.combining', (['c'], {}), '(c)\n', (416, 419), False, 'import unicodedata\n'), ((836, 854), 'yaml.safe_load', 'yaml.safe_load', (['fh'], {}), '(fh)\n', (850, 854), False, 'import yaml\n'), ((1153, 1164), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (1161, 1164), False, 'import sys\n')]
""" Reference: [1]: Branlard, Flexible multibody dynamics using joint coordinates and the Rayleigh-Ritz approximation: the general framework behind and beyond Flex, Wind Energy, 2019 """ import numpy as np from .utils import * from .bodies import Body as GenericBody from .bodies import RigidBody as GenericRigidBody from .bodies import FlexibleBody as GenericFlexibleBody from .bodies import BeamBody as GenericBeamBody from .bodies import FASTBeamBody as GenericFASTBeamBody from .bodies import InertialBody as GenericInertialBody # --- To ease comparison with sympy version from numpy import eye, cross, cos ,sin def Matrix(m): return np.asarray(m) def colvec(v): v=np.asarray(v).ravel() return np.array([[v[0]],[v[1]],[v[2]]]) # --------------------------------------------------------------------------------} # --- Connections # --------------------------------------------------------------------------------{ class Connection(): def __init__(self,Type,RelPoint=None,RelOrientation=None,JointRotations=None, OrientAfter=True): if RelOrientation is None: RelOrientation=eye(3) if RelPoint is None: RelPoint=colvec([0,0,0]) self.Type=Type self.s_C_0_inB = RelPoint self.s_C_inB = self.s_C_0_inB self.R_ci_0 = RelOrientation self.R_ci = self.R_ci_0 self.OrientAfter= OrientAfter if self.Type=='Rigid': self.nj=0 elif self.Type=='SphericalJoint': self.JointRotations=JointRotations; self.nj=len(self.JointRotations); else: raise NotImplementedError() def updateKinematics(j,q): j.B_ci=Matrix(np.zeros((6,j.nj))) if j.Type=='Rigid': j.R_ci=j.R_ci_0 elif j.Type=='SphericalJoint': R=eye(3) myq = q [j.I_DOF,0]; #myqdot = qdot[j.I_DOF]; for ir,rot in enumerate(j.JointRotations): if rot=='x': I=np.array([1,0,0]) Rj=R_x( myq[ir] ) elif rot=='y': I=np.array([0,1,0]) Rj=R_y( myq[ir] ) elif rot=='z': I=np.array([0,0,1]) Rj=R_z( myq[ir] ) else: raise Exception() # Setting Bhat column by column j.B_ci[3:,ir] = np.dot(R,I) # NOTE: needs to be done before R updates # Updating rotation matrix R = np.dot(R , Rj ) if j.OrientAfter: j.R_ci = np.dot(R, j.R_ci_0 ) else: j.R_ci = np.dot(j.R_ci_0, R ) # --------------------------------------------------------------------------------} # --- Bodies # --------------------------------------------------------------------------------{ class Body(GenericBody): def __init__(B,name=''): GenericBody.__init__(B, name=name) B.Children = [] B.Connections = [] B.MM = None B.B = [] # Velocity transformation matrix B.updatePosOrientation(colvec([0,0,0]), eye(3)) def updatePosOrientation(o,x_0,R_0b): o.r_O = x_0 # position of body origin in global coordinates o.R_0b=R_0b # transformation matrix from body to global def connectTo(self, Child, Point=None, Type=None, RelOrientation=None, JointRotations=None, OrientAfter=True): if Type =='Rigid': c=Connection(Type, RelPoint=Point, RelOrientation = RelOrientation) else: # TODO first node, last node c=Connection(Type, RelPoint=Point, RelOrientation=RelOrientation, JointRotations=JointRotations, OrientAfter=OrientAfter) self.Children.append(Child) self.Connections.append(c) def setupDOFIndex(o,n): nForMe=o.nf # Setting my dof index o.I_DOF=n+ np.arange(nForMe) # Update n=n+nForMe for child,conn in zip(o.Children,o.Connections): # Connection first nForConn=conn.nj; conn.I_DOF=n+np.arange(nForConn) # Update n=n+nForConn; # Then Children n=child.setupDOFIndex(n) return n #def __repr__(B): # return GenericBody.__repr__(B) @property def R_bc(self): return eye(3); @property def Bhat_x_bc(self): return Matrix(np.zeros((3,0))) @property def Bhat_t_bc(self): return Matrix(np.zeros((3,0))) def updateChildrenKinematicsNonRecursive(p,q): # At this stage all the kinematics of the body p are known # Useful variables R_0p = p.R_0b B_p = p.B r_0p = p.r_O nf_all_children=sum([child.nf for child in p.Children]) for ic,(body_i,conn_pi) in enumerate(zip(p.Children,p.Connections)): # Flexible influence to connection point R_pc = p.R_bc #print('R_pc') #print(R_pc) Bx_pc = p.Bhat_x_bc Bt_pc = p.Bhat_t_bc # Joint influence to next body (R_ci, B_ci) conn_pi.updateKinematics(q) # TODO #print('R_ci',p.name) #print(conn_pi.R_ci) # Full connection p and j R_pi = np.dot(R_pc, conn_pi.R_ci ) if conn_pi.B_ci.shape[1]>0: Bx_pi = np.column_stack((Bx_pc, np.dot(R_pc,conn_pi.B_ci[:3,:]))) Bt_pi = np.column_stack((Bt_pc, np.dot(R_pc,conn_pi.B_ci[3:,:]))) else: Bx_pi = Bx_pc Bt_pi = Bt_pc # Rotation of body i is rotation due to p and j R_0i = np.dot( R_0p , R_pi ) #print('R_pi',p.name) #print(R_pi) #print('R_0p',p.name) #print(R_0p) #print('R_0i',p.name) #print(R_0i) # Position of connection point in P and 0 system r_pi_inP= conn_pi.s_C_inB r_pi = np.dot (R_0p , r_pi_inP ) #print('r_pi') #print(r_pi_inP) #print('r_pi') #print(r_pi) #print('Bx_pi') #print(Bx_pi) #print('Bt_pi') #print(Bt_pi) B_i = fBMatRecursion(B_p, Bx_pi, Bt_pi, R_0p, r_pi) B_i_inI = fB_inB(R_0i, B_i) BB_i_inI = fB_aug(B_i_inI, body_i.nf) body_i.B = B_i body_i.B_inB = B_i_inI body_i.BB_inB = BB_i_inI # --- Updating Position and orientation of child body r_0i = r_0p + r_pi # in 0 system body_i.R_pb = R_pi body_i.updatePosOrientation(r_0i,R_0i) # TODO flexible dofs and velocities/acceleration body_i.gzf = q[body_i.I_DOF,0] # TODO use updateKinematics def getFullM(o,M): if not isinstance(o,GroundBody): MqB = fBMB(o.BB_inB,o.MM) n = MqB.shape[0] M[:n,:n] = M[:n,:n]+MqB for c in o.Children: M=c.getFullM(M) return M def getFullK(o,K): if not isinstance(o,GroundBody): KqB = fBMB(o.BB_inB,o.KK) n = KqB.shape[0] K[:n,:n] = K[:n,:n]+KqB for c in o.Children: K=c.getFullK(K) return K def getFullD(o,D): if not isinstance(o,GroundBody): DqB = fBMB(o.BB_inB,o.DD) n = DqB.shape[0] D[:n,:n] = D[:n,:n]+DqB for c in o.Children: D=c.getFullD(D) return D @property def nf(B): if hasattr(B,'PhiU'): return len(B.PhiU) else: return 0 @property def Mass(B): if B.MM is None: return 0 return B.MM[0,0] def updateKinematics(o,x_0,R_0b,gz,v_0,a_v_0): # Updating position of body origin in global coordinates o.r_O = x_0[0:3] o.gzf = gz # Updating Transformation matrix o.R_0b=R_0b # Updating rigid body velocity and acceleration o.v_O_inB = np.dot(R_0b, v_0[0:3]) o.om_O_inB = np.dot(R_0b, v_0[3:6]) o.a_O_v_inB = np.dot(R_0b, a_v_0[0:3]) o.omp_O_v_inB = np.dot(R_0b, a_v_0[3:6]) # --------------------------------------------------------------------------------} # --- Ground Body # --------------------------------------------------------------------------------{ class GroundBody(Body, GenericInertialBody): def __init__(B): Body.__init__(B, 'Grd') GenericInertialBody.__init__(B) # --------------------------------------------------------------------------------} # --- Rigid Body # --------------------------------------------------------------------------------{ class RigidBody(Body,GenericRigidBody): def __init__(B, name, Mass, J_G, rho_G): """ Creates a rigid body """ Body.__init__(B,name) GenericRigidBody.__init__(B, name, Mass, J_G, rho_G) B.s_G_inB = B.masscenter B.J_G_inB = B.masscenter_inertia B.J_O_inB = translateInertiaMatrixFromCOG(B.J_G_inB, Mass, -B.s_G_inB) B.MM = rigidBodyMassMatrix(Mass, B.J_O_inB, B.s_G_inB) # TODO change interface B.DD = np.zeros((6,6)) B.KK = np.zeros((6,6)) # --------------------------------------------------------------------------------} # --- Beam Body # --------------------------------------------------------------------------------{ class BeamBody(GenericBeamBody, Body): def __init__(B, s_span, s_P0, m, PhiU, PhiV, PhiK, EI, jxxG=None, s_G0=None, s_min=None, s_max=None, bAxialCorr=False, bOrth=False, Mtop=0, bStiffening=True, gravity=None,main_axis='z', massExpected=None ): """ Points P0 - Undeformed mean line of the body """ # --- nherit from BeamBody and Body Body.__init__(B) GenericBeamBody.__init__(B,'dummy', s_span, s_P0, m, EI, PhiU, PhiV, PhiK, jxxG=jxxG, s_G0=s_G0, s_min=s_min, s_max=s_max, bAxialCorr=bAxialCorr, bOrth=bOrth, Mtop=Mtop, bStiffening=bStiffening, gravity=gravity, main_axis=main_axis, massExpected=massExpected ) B.gzf = np.zeros((B.nf,1)) B.gzpf = np.zeros((B.nf,1)) B.gzppf = np.zeros((B.nf,1)) # TODO B.V0 = np.zeros((3,B.nSpan)) B.K0 = np.zeros((3,B.nSpan)) B.rho_G0_inS = np.zeros((3,B.nSpan)) # location of COG in each cross section #[o.PhiV,o.PhiK] = fBeamSlopeCurvature(o.s_span,o.PhiU,o.PhiV,o.PhiK,1e-2); #[o.V0,o.K0] = fBeamSlopeCurvature(o.s_span,o.s_P0,o.V0,o.K0,1e-2) ; #if isempty(o.s_G0); o.s_G0=o.s_P0; end; #if isempty(o.rho_G0_inS); o.rho_G0_inS=np.zeros(3,o.nSpan); end; #if isempty(o.rho_G0 ); # o.rho_G0 =np.zeros(3,o.nSpan); # for i=1:o.nSpan # o.rho_G0(1:3,i) =R_x(o.V0(1,i))*o.rho_G0_inS(:,i); @property def alpha_couplings(self): return np.dot(self.Bhat_t_bc , self.gzf).ravel() @property def R_bc(self): alpha = self.alpha_couplings if self.main_axis=='x': return np.dot(R_y(alpha[1]),R_z(alpha[2])) elif self.main_axis=='z': return np.dot(R_x(alpha[0]),R_y(alpha[1])) else: raise NotImplementedError() def updateKinematics(o,x_0,R_0b,gz,v_0,a_v_0): super(BeamBody,o).updateKinematics(x_0,R_0b,gz,v_0,a_v_0) # --- Calculation of deformations wrt straight beam axis, curvature (K) and velocities (UP) if o.nf>0: o.gzpf = v_0[6:] o.gzppf = a_v_0[6:] # Deflections shape o.U = np.zeros((3,o.nSpan)); o.V = np.zeros((3,o.nSpan)); o.K = np.zeros((3,o.nSpan)); #o.U(1,:) = o.s_span; o.UP = np.zeros((3,o.nSpan)); for j in range(o.nf): o.U [0:3,:] = o.U [0:3,:] + o.gzf[j] * o.PhiU[j][0:3,:] o.UP[0:3,:] = o.UP[0:3,:] + o.gzpf[j] * o.PhiU[j][0:3,:] o.V [0:3,:] = o.V [0:3,:] + o.gzf[j] * o.PhiV[j][0:3,:] o.K [0:3,:] = o.K [0:3,:] + o.gzf[j] * o.PhiK[j][0:3,:] o.V_tot=o.V+o.V0; o.K_tot=o.K+o.K0; # Position of mean line o.s_P=o.s_P0+o.U; # Position of deflected COG # TODO TODO TODO mean_axis not x o.rho_G = np.zeros((3,o.nSpan)) if o.main_axis=='x': o.rho_G[1,:] = o.rho_G0_inS[1,:]*np.cos(o.V_tot[0,:])-o.rho_G0_inS[2,:]*np.sin(o.V_tot[0,:]); o.rho_G[2,:] = o.rho_G0_inS[1,:]*np.sin(o.V_tot[0,:])+o.rho_G0_inS[2,:]*np.cos(o.V_tot[0,:]); else: raise NotImplementedError() o.rho_G[1,:] = o.rho_G0_inS[1,:]*np.cos(o.V_tot[0,:])-o.rho_G0_inS[2,:]*np.sin(o.V_tot[0,:]); o.rho_G[2,:] = o.rho_G0_inS[1,:]*np.sin(o.V_tot[0,:])+o.rho_G0_inS[2,:]*np.cos(o.V_tot[0,:]); o.s_G = o.s_P+o.rho_G; # Alternative: #rho_G2 = zeros(3,o.nSpan); #rho_G2(2,:) = o.rho_G0(2,:).*cos(o.V(1,:))-o.rho_G0(3,:).*sin(o.V(1,:)); #rho_G2(3,:) = o.rho_G0(2,:).*sin(o.V(1,:))+o.rho_G0(3,:).*cos(o.V(1,:)); #compare(o.rho_G,rho_G2,'rho_G'); # Position of connection point print('TODO connection points') #for ic=1:length(o.Connections) # iNode=o.Connections{ic}.ParentNode; # %o.Connections{ic}.s_C_inB = o.U(1:3,iNode); # o.Connections{ic}.s_C_inB = o.s_P(1:3,iNode); @property def nSpan(B): return len(B.s_span) # --------------------------------------------------------------------------------} # --- Uniform Beam Body # --------------------------------------------------------------------------------{ class UniformBeamBody(BeamBody): def __init__(B, name, nShapes, nSpan, L, EI0, m, Mtop=0, jxxG=None, GKt=None, bAxialCorr=True, bCompatibility=False, bStiffnessFromGM=False, bStiffening=True, gravity=None, main_axis='x'): import welib.beams.theory as bt if jxxG is None: jxxG=0 if GKt is None: GKt=0 A=1; rho=A*m; x=np.linspace(0,L,nSpan); # Mode shapes freq,s_span,U,V,K = bt.UniformBeamBendingModes('unloaded-topmass-clamped-free',EI0,rho,A,L,x=x,Mtop=Mtop) PhiU = np.zeros((nShapes,3,nSpan)) # Shape PhiV = np.zeros((nShapes,3,nSpan)) # Slope PhiK = np.zeros((nShapes,3,nSpan)) # Curvature if main_axis=='x': iModeAxis=2 # Setting modes along z elif main_axis=='z': iModeAxis=0 # Setting modes along x for j in np.arange(nShapes): PhiU[j][iModeAxis,:] = U[j,:] PhiV[j][iModeAxis,:] = V[j,:] PhiK[j][iModeAxis,:] = K[j,:] m = m * np.ones(nSpan) jxxG = jxxG * np.ones(nSpan) EI = np.zeros((3,nSpan)) if main_axis=='x': EI[1,:] = EI0 EI[2,:] = EI0 elif main_axis=='z': EI[0,:] = EI0 EI[1,:] = EI0 GKt = GKt * np.ones(nSpan) # --- Straight undeflected shape (and COG) s_P0 = np.zeros((3,nSpan)) if main_axis=='x': s_P0[0,:] = x elif main_axis=='z': s_P0[2,:] = x # Create a beam body super(UniformBeamBody,B).__init__(s_span, s_P0, m, PhiU, PhiV, PhiK, EI, jxxG=jxxG, bAxialCorr=bAxialCorr, Mtop=Mtop, bStiffening=bStiffening, gravity=gravity, main_axis=main_axis) # --------------------------------------------------------------------------------} # --- FAST Beam body # --------------------------------------------------------------------------------{ class FASTBeamBody(BeamBody, GenericFASTBeamBody): def __init__(B, body_type, ED, inp, Mtop=0, shapes=None, nShapes=None, main_axis='x',nSpan=None,bAxialCorr=False,bStiffening=True, spanFrom0=False, massExpected=None ): """ """ if shapes is None: if nShapes==2: shapes=[0,1] elif nShapes==0: shapes=[] elif nShapes==1: shapes=[0] else: raise NotImplementedError('>> TODO') GenericFASTBeamBody.__init__(B, ED, inp, Mtop=Mtop, shapes=shapes, main_axis=main_axis, nSpan=nSpan, bAxialCorr=bAxialCorr, bStiffening=bStiffening, spanFrom0=spanFrom0, massExpected=massExpected ) # We need to inherit from "YAMS" Beam not just generic Beam BeamBody.__init__(B, B.s_span, B.s_P0, B.m, B.PhiU, B.PhiV, B.PhiK, B.EI, jxxG=B.jxxG, s_G0=B.s_G0, # NOTE: r_O, r_b2g is lost here s_min=B.s_min, s_max=B.s_max, bAxialCorr=bAxialCorr, bOrth=B.bOrth, Mtop=Mtop, bStiffening=bStiffening, gravity=B.gravity,main_axis=main_axis, massExpected=massExpected ) # --------------------------------------------------------------------------------} # --- B Matrices # --------------------------------------------------------------------------------{ def fB_inB(R_EI, B_I): """ Transfer a global B_I matrix (body I at point I) into a matrix in it's own coordinate. Simply multiply the top part and bottom part of the B matrix by the 3x3 rotation matrix R_EI e.g. B_N_inN = [R_EN' * B_N(1:3,:); R_EN' * B_N(4:6,:)]; """ if len(B_I)==0: B_I_inI = Matrix(np.array([])) else: B_I_inI = Matrix(np.vstack(( np.dot(R_EI.T, B_I[:3,:]), np.dot(R_EI.T , B_I[3:,:])))) return B_I_inI def fB_aug(B_I_inI, nf_I, nf_Curr=None, nf_Prev=None): """ Augments the B_I_inI matrix, to include nf_I flexible degrees of freedom. This returns the full B matrix on the left side of Eq.(11) from [1], based on the Bx and Bt matrices on the right side of this equation """ if len(B_I_inI)==0: if nf_I>0: BB_I_inI = Matrix(np.vstack( (np.zeros((6,nf_I)), np.eye(nf_I))) ) else: BB_I_inI= Matrix(np.zeros((6,0))) else: if nf_Curr is not None: # Case of several flexible bodies connected to one point (i.e. blades) nf_After=nf_I-nf_Prev-nf_Curr I = np.block( [np.zeros((nf_Curr,nf_Prev)), np.eye(nf_Curr), np.zeros((nf_Curr,nf_After))] ) else: nf_Curr=nf_I I=np.eye(nf_I) BB_I_inI = np.block([ [B_I_inI, np.zeros((6,nf_I))], [np.zeros((nf_Curr,B_I_inI.shape[1])), I]]); return Matrix(BB_I_inI) def fBMatRecursion(Bp, Bhat_x, Bhat_t, R0p, r_pi): """ Recursive formulae for B' and Bhat See discussion after Eq.(12) and (15) from [1] """ # --- Safety checks if len(Bp)==0: n_p = 0 elif len(Bp.shape)==2: n_p = Bp.shape[1] else: raise Exception('Bp needs to be empty or a 2d array') if len(Bhat_x)==0: ni = 0 elif len(Bhat_x.shape)==2: ni = Bhat_x.shape[1] else: raise Exception('Bi needs to be empty or a 2d array') r_pi=r_pi.reshape(3,1) # TODO use Translate here Bi = Matrix(np.zeros((6,ni+n_p))) for j in range(n_p): Bi[:3,j] = Bp[:3,j]+cross(Bp[3:,j],r_pi.ravel()) # Recursive formula for Bt mentioned after Eq.(15) Bi[3:,j] = Bp[3:,j] # Recursive formula for Bx mentioned after Eq.(12) if ni>0: Bi[:3,n_p:] = np.dot(R0p, Bhat_x[:,:]) # Recursive formula for Bx mentioned after Eq.(15) Bi[3:,n_p:] = np.dot(R0p, Bhat_t[:,:]) # Recursive formula for Bt mentioned after Eq.(12) return Bi def fBMatTranslate(Bp,r_pi): """ Rigid translation of a B matrix to another point, i.e. transfer the velocities from a point to another: - translational velocity: v@J = v@I + om@I x r@IJ - rotational velocity : om@J = om@I """ Bi=np.zeros(Bp.shape) if Bp.ndim==1: raise NotImplementedError for j in range(Bp.shape[1]): Bi[0:3,j] = Bp[0:3,j]+np.cross(Bp[3:6,j],r_pi.ravel()); Bi[3:6,j] = Bp[3:6,j] return Bi def fBMB(BB_I_inI,MM): """ Computes the body generalized matrix: B'^t M' B See Eq.(8) of [1] """ MM_I = np.dot(np.transpose(BB_I_inI), MM).dot(BB_I_inI) return MM_I if __name__=='__main__': pass
[ "numpy.eye", "numpy.ones", "numpy.asarray", "numpy.array", "numpy.dot", "numpy.zeros", "numpy.linspace", "numpy.cos", "numpy.sin", "welib.beams.theory.UniformBeamBendingModes", "numpy.transpose", "numpy.arange" ]
[((661, 674), 'numpy.asarray', 'np.asarray', (['m'], {}), '(m)\n', (671, 674), True, 'import numpy as np\n'), ((730, 764), 'numpy.array', 'np.array', (['[[v[0]], [v[1]], [v[2]]]'], {}), '([[v[0]], [v[1]], [v[2]]])\n', (738, 764), True, 'import numpy as np\n'), ((20332, 20350), 'numpy.zeros', 'np.zeros', (['Bp.shape'], {}), '(Bp.shape)\n', (20340, 20350), True, 'import numpy as np\n'), ((4449, 4455), 'numpy.eye', 'eye', (['(3)'], {}), '(3)\n', (4452, 4455), False, 'from numpy import eye, cross, cos, sin\n'), ((8289, 8311), 'numpy.dot', 'np.dot', (['R_0b', 'v_0[0:3]'], {}), '(R_0b, v_0[0:3])\n', (8295, 8311), True, 'import numpy as np\n'), ((8336, 8358), 'numpy.dot', 'np.dot', (['R_0b', 'v_0[3:6]'], {}), '(R_0b, v_0[3:6])\n', (8342, 8358), True, 'import numpy as np\n'), ((8383, 8407), 'numpy.dot', 'np.dot', (['R_0b', 'a_v_0[0:3]'], {}), '(R_0b, a_v_0[0:3])\n', (8389, 8407), True, 'import numpy as np\n'), ((8432, 8456), 'numpy.dot', 'np.dot', (['R_0b', 'a_v_0[3:6]'], {}), '(R_0b, a_v_0[3:6])\n', (8438, 8456), True, 'import numpy as np\n'), ((9455, 9471), 'numpy.zeros', 'np.zeros', (['(6, 6)'], {}), '((6, 6))\n', (9463, 9471), True, 'import numpy as np\n'), ((9486, 9502), 'numpy.zeros', 'np.zeros', (['(6, 6)'], {}), '((6, 6))\n', (9494, 9502), True, 'import numpy as np\n'), ((10478, 10497), 'numpy.zeros', 'np.zeros', (['(B.nf, 1)'], {}), '((B.nf, 1))\n', (10486, 10497), True, 'import numpy as np\n'), ((10515, 10534), 'numpy.zeros', 'np.zeros', (['(B.nf, 1)'], {}), '((B.nf, 1))\n', (10523, 10534), True, 'import numpy as np\n'), ((10552, 10571), 'numpy.zeros', 'np.zeros', (['(B.nf, 1)'], {}), '((B.nf, 1))\n', (10560, 10571), True, 'import numpy as np\n'), ((10610, 10632), 'numpy.zeros', 'np.zeros', (['(3, B.nSpan)'], {}), '((3, B.nSpan))\n', (10618, 10632), True, 'import numpy as np\n'), ((10655, 10677), 'numpy.zeros', 'np.zeros', (['(3, B.nSpan)'], {}), '((3, B.nSpan))\n', (10663, 10677), True, 'import numpy as np\n'), ((10700, 10722), 'numpy.zeros', 'np.zeros', (['(3, B.nSpan)'], {}), '((3, B.nSpan))\n', (10708, 10722), True, 'import numpy as np\n'), ((14570, 14594), 'numpy.linspace', 'np.linspace', (['(0)', 'L', 'nSpan'], {}), '(0, L, nSpan)\n', (14581, 14594), True, 'import numpy as np\n'), ((14644, 14739), 'welib.beams.theory.UniformBeamBendingModes', 'bt.UniformBeamBendingModes', (['"""unloaded-topmass-clamped-free"""', 'EI0', 'rho', 'A', 'L'], {'x': 'x', 'Mtop': 'Mtop'}), "('unloaded-topmass-clamped-free', EI0, rho, A, L,\n x=x, Mtop=Mtop)\n", (14670, 14739), True, 'import welib.beams.theory as bt\n'), ((14745, 14774), 'numpy.zeros', 'np.zeros', (['(nShapes, 3, nSpan)'], {}), '((nShapes, 3, nSpan))\n', (14753, 14774), True, 'import numpy as np\n'), ((14796, 14825), 'numpy.zeros', 'np.zeros', (['(nShapes, 3, nSpan)'], {}), '((nShapes, 3, nSpan))\n', (14804, 14825), True, 'import numpy as np\n'), ((14847, 14876), 'numpy.zeros', 'np.zeros', (['(nShapes, 3, nSpan)'], {}), '((nShapes, 3, nSpan))\n', (14855, 14876), True, 'import numpy as np\n'), ((15066, 15084), 'numpy.arange', 'np.arange', (['nShapes'], {}), '(nShapes)\n', (15075, 15084), True, 'import numpy as np\n'), ((15325, 15345), 'numpy.zeros', 'np.zeros', (['(3, nSpan)'], {}), '((3, nSpan))\n', (15333, 15345), True, 'import numpy as np\n'), ((15626, 15646), 'numpy.zeros', 'np.zeros', (['(3, nSpan)'], {}), '((3, nSpan))\n', (15634, 15646), True, 'import numpy as np\n'), ((19612, 19635), 'numpy.zeros', 'np.zeros', (['(6, ni + n_p)'], {}), '((6, ni + n_p))\n', (19620, 19635), True, 'import numpy as np\n'), ((19881, 19906), 'numpy.dot', 'np.dot', (['R0p', 'Bhat_x[:, :]'], {}), '(R0p, Bhat_x[:, :])\n', (19887, 19906), True, 'import numpy as np\n'), ((19979, 20004), 'numpy.dot', 'np.dot', (['R0p', 'Bhat_t[:, :]'], {}), '(R0p, Bhat_t[:, :])\n', (19985, 20004), True, 'import numpy as np\n'), ((697, 710), 'numpy.asarray', 'np.asarray', (['v'], {}), '(v)\n', (707, 710), True, 'import numpy as np\n'), ((1135, 1141), 'numpy.eye', 'eye', (['(3)'], {}), '(3)\n', (1138, 1141), False, 'from numpy import eye, cross, cos, sin\n'), ((1733, 1752), 'numpy.zeros', 'np.zeros', (['(6, j.nj)'], {}), '((6, j.nj))\n', (1741, 1752), True, 'import numpy as np\n'), ((3226, 3232), 'numpy.eye', 'eye', (['(3)'], {}), '(3)\n', (3229, 3232), False, 'from numpy import eye, cross, cos, sin\n'), ((3989, 4006), 'numpy.arange', 'np.arange', (['nForMe'], {}), '(nForMe)\n', (3998, 4006), True, 'import numpy as np\n'), ((4518, 4534), 'numpy.zeros', 'np.zeros', (['(3, 0)'], {}), '((3, 0))\n', (4526, 4534), True, 'import numpy as np\n'), ((4596, 4612), 'numpy.zeros', 'np.zeros', (['(3, 0)'], {}), '((3, 0))\n', (4604, 4612), True, 'import numpy as np\n'), ((5393, 5419), 'numpy.dot', 'np.dot', (['R_pc', 'conn_pi.R_ci'], {}), '(R_pc, conn_pi.R_ci)\n', (5399, 5419), True, 'import numpy as np\n'), ((5801, 5819), 'numpy.dot', 'np.dot', (['R_0p', 'R_pi'], {}), '(R_0p, R_pi)\n', (5807, 5819), True, 'import numpy as np\n'), ((6122, 6144), 'numpy.dot', 'np.dot', (['R_0p', 'r_pi_inP'], {}), '(R_0p, r_pi_inP)\n', (6128, 6144), True, 'import numpy as np\n'), ((11987, 12009), 'numpy.zeros', 'np.zeros', (['(3, o.nSpan)'], {}), '((3, o.nSpan))\n', (11995, 12009), True, 'import numpy as np\n'), ((12029, 12051), 'numpy.zeros', 'np.zeros', (['(3, o.nSpan)'], {}), '((3, o.nSpan))\n', (12037, 12051), True, 'import numpy as np\n'), ((12071, 12093), 'numpy.zeros', 'np.zeros', (['(3, o.nSpan)'], {}), '((3, o.nSpan))\n', (12079, 12093), True, 'import numpy as np\n'), ((12148, 12170), 'numpy.zeros', 'np.zeros', (['(3, o.nSpan)'], {}), '((3, o.nSpan))\n', (12156, 12170), True, 'import numpy as np\n'), ((12737, 12759), 'numpy.zeros', 'np.zeros', (['(3, o.nSpan)'], {}), '((3, o.nSpan))\n', (12745, 12759), True, 'import numpy as np\n'), ((15252, 15266), 'numpy.ones', 'np.ones', (['nSpan'], {}), '(nSpan)\n', (15259, 15266), True, 'import numpy as np\n'), ((15292, 15306), 'numpy.ones', 'np.ones', (['nSpan'], {}), '(nSpan)\n', (15299, 15306), True, 'import numpy as np\n'), ((15531, 15545), 'numpy.ones', 'np.ones', (['nSpan'], {}), '(nSpan)\n', (15538, 15545), True, 'import numpy as np\n'), ((17939, 17951), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (17947, 17951), True, 'import numpy as np\n'), ((18878, 18890), 'numpy.eye', 'np.eye', (['nf_I'], {}), '(nf_I)\n', (18884, 18890), True, 'import numpy as np\n'), ((1862, 1868), 'numpy.eye', 'eye', (['(3)'], {}), '(3)\n', (1865, 1868), False, 'from numpy import eye, cross, cos, sin\n'), ((4187, 4206), 'numpy.arange', 'np.arange', (['nForConn'], {}), '(nForConn)\n', (4196, 4206), True, 'import numpy as np\n'), ((11292, 11324), 'numpy.dot', 'np.dot', (['self.Bhat_t_bc', 'self.gzf'], {}), '(self.Bhat_t_bc, self.gzf)\n', (11298, 11324), True, 'import numpy as np\n'), ((18536, 18552), 'numpy.zeros', 'np.zeros', (['(6, 0)'], {}), '((6, 0))\n', (18544, 18552), True, 'import numpy as np\n'), ((20677, 20699), 'numpy.transpose', 'np.transpose', (['BB_I_inI'], {}), '(BB_I_inI)\n', (20689, 20699), True, 'import numpy as np\n'), ((2465, 2477), 'numpy.dot', 'np.dot', (['R', 'I'], {}), '(R, I)\n', (2471, 2477), True, 'import numpy as np\n'), ((2587, 2600), 'numpy.dot', 'np.dot', (['R', 'Rj'], {}), '(R, Rj)\n', (2593, 2600), True, 'import numpy as np\n'), ((18000, 18026), 'numpy.dot', 'np.dot', (['R_EI.T', 'B_I[:3, :]'], {}), '(R_EI.T, B_I[:3, :])\n', (18006, 18026), True, 'import numpy as np\n'), ((18027, 18053), 'numpy.dot', 'np.dot', (['R_EI.T', 'B_I[3:, :]'], {}), '(R_EI.T, B_I[3:, :])\n', (18033, 18053), True, 'import numpy as np\n'), ((18747, 18775), 'numpy.zeros', 'np.zeros', (['(nf_Curr, nf_Prev)'], {}), '((nf_Curr, nf_Prev))\n', (18755, 18775), True, 'import numpy as np\n'), ((18776, 18791), 'numpy.eye', 'np.eye', (['nf_Curr'], {}), '(nf_Curr)\n', (18782, 18791), True, 'import numpy as np\n'), ((18793, 18822), 'numpy.zeros', 'np.zeros', (['(nf_Curr, nf_After)'], {}), '((nf_Curr, nf_After))\n', (18801, 18822), True, 'import numpy as np\n'), ((18932, 18951), 'numpy.zeros', 'np.zeros', (['(6, nf_I)'], {}), '((6, nf_I))\n', (18940, 18951), True, 'import numpy as np\n'), ((18954, 18991), 'numpy.zeros', 'np.zeros', (['(nf_Curr, B_I_inI.shape[1])'], {}), '((nf_Curr, B_I_inI.shape[1]))\n', (18962, 18991), True, 'import numpy as np\n'), ((2051, 2070), 'numpy.array', 'np.array', (['[1, 0, 0]'], {}), '([1, 0, 0])\n', (2059, 2070), True, 'import numpy as np\n'), ((2666, 2685), 'numpy.dot', 'np.dot', (['R', 'j.R_ci_0'], {}), '(R, j.R_ci_0)\n', (2672, 2685), True, 'import numpy as np\n'), ((2738, 2757), 'numpy.dot', 'np.dot', (['j.R_ci_0', 'R'], {}), '(j.R_ci_0, R)\n', (2744, 2757), True, 'import numpy as np\n'), ((5510, 5543), 'numpy.dot', 'np.dot', (['R_pc', 'conn_pi.B_ci[:3, :]'], {}), '(R_pc, conn_pi.B_ci[:3, :])\n', (5516, 5543), True, 'import numpy as np\n'), ((5593, 5626), 'numpy.dot', 'np.dot', (['R_pc', 'conn_pi.B_ci[3:, :]'], {}), '(R_pc, conn_pi.B_ci[3:, :])\n', (5599, 5626), True, 'import numpy as np\n'), ((12841, 12862), 'numpy.cos', 'np.cos', (['o.V_tot[0, :]'], {}), '(o.V_tot[0, :])\n', (12847, 12862), True, 'import numpy as np\n'), ((12880, 12901), 'numpy.sin', 'np.sin', (['o.V_tot[0, :]'], {}), '(o.V_tot[0, :])\n', (12886, 12901), True, 'import numpy as np\n'), ((12951, 12972), 'numpy.sin', 'np.sin', (['o.V_tot[0, :]'], {}), '(o.V_tot[0, :])\n', (12957, 12972), True, 'import numpy as np\n'), ((12990, 13011), 'numpy.cos', 'np.cos', (['o.V_tot[0, :]'], {}), '(o.V_tot[0, :])\n', (12996, 13011), True, 'import numpy as np\n'), ((13123, 13144), 'numpy.cos', 'np.cos', (['o.V_tot[0, :]'], {}), '(o.V_tot[0, :])\n', (13129, 13144), True, 'import numpy as np\n'), ((13162, 13183), 'numpy.sin', 'np.sin', (['o.V_tot[0, :]'], {}), '(o.V_tot[0, :])\n', (13168, 13183), True, 'import numpy as np\n'), ((13233, 13254), 'numpy.sin', 'np.sin', (['o.V_tot[0, :]'], {}), '(o.V_tot[0, :])\n', (13239, 13254), True, 'import numpy as np\n'), ((13272, 13293), 'numpy.cos', 'np.cos', (['o.V_tot[0, :]'], {}), '(o.V_tot[0, :])\n', (13278, 13293), True, 'import numpy as np\n'), ((18456, 18475), 'numpy.zeros', 'np.zeros', (['(6, nf_I)'], {}), '((6, nf_I))\n', (18464, 18475), True, 'import numpy as np\n'), ((18476, 18488), 'numpy.eye', 'np.eye', (['nf_I'], {}), '(nf_I)\n', (18482, 18488), True, 'import numpy as np\n'), ((2160, 2179), 'numpy.array', 'np.array', (['[0, 1, 0]'], {}), '([0, 1, 0])\n', (2168, 2179), True, 'import numpy as np\n'), ((2269, 2288), 'numpy.array', 'np.array', (['[0, 0, 1]'], {}), '([0, 0, 1])\n', (2277, 2288), True, 'import numpy as np\n')]
import Global from methods.DBManager import DBManager from handlers.kbeServer.XREditor.Interface import xr_interface_mail #获取邮件列表 def Transactions_Code_6001(self_uid,self_username,languageStr,json_data): #回调json json_back = { "code" : 0, "msg": "", "pam": "" } #logging.info("getphone code:[%s] - [%s] " % (phone, code)) #json_data 结构 page = int(json_data["page"]) #页数 hnum = int(json_data["hnum"]) #一页几行 if page < 0 or hnum < 0: json_back["code"] = 0 #参数异常 json_back["msg"] = Global.LanguageInst.GetMsg("SMSGID_1_4",languageStr) else: # 获取下db的句柄,如果需要操作数据库的话 DB = DBManager() json_back = xr_interface_mail.GetMail(DB,self_uid,page,hnum,languageStr) DB.destroy() return json_back #读邮件 def Transactions_Code_6002(self_uid,self_username,languageStr,json_data): #回调json json_back = { "code" : 0, "msg": "", "pam": "" } #logging.info("getphone code:[%s] - [%s] " % (phone, code)) #json_data 结构 ID = int(json_data["ID"]) #邮件ID if ID < 0: json_back["code"] = 0 #参数异常 json_back["msg"] = Global.LanguageInst.GetMsg("SMSGID_1_4",languageStr) else: # 获取下db的句柄,如果需要操作数据库的话 json_back = xr_interface_mail.ReadMail(self_uid,ID,languageStr) return json_back #删除邮件 def Transactions_Code_6003(self_uid,self_username,languageStr,json_data): #回调json json_back = { "code" : 0, "msg": "", "pam": "" } #logging.info("getphone code:[%s] - [%s] " % (phone, code)) #json_data 结构 ID = int(json_data["ID"]) #邮件ID if ID < 0: json_back["code"] = 0 #参数异常 json_back["msg"] = Global.LanguageInst.GetMsg("SMSGID_1_4",languageStr) else: # 获取下db的句柄,如果需要操作数据库的话 json_back = xr_interface_mail.DetMail(self_uid,ID,languageStr) return json_back #全部已读 def Transactions_Code_6004(self_uid,self_username,languageStr,json_data): #回调json json_back = { "code" : 0, "msg": "", "pam": "" } #logging.info("getphone code:[%s] - [%s] " % (phone, code)) #json_data 结构 #ID = int(json_data["ID"]) #邮件ID DB = DBManager() json_back = xr_interface_mail.ReadAll(DB, self_uid, languageStr) DB.destroy() return json_back #删除已读 def Transactions_Code_6005(self_uid,self_username,languageStr,json_data): #回调json json_back = { "code" : 0, "msg": "", "pam": "" } #logging.info("getphone code:[%s] - [%s] " % (phone, code)) #json_data 结构 #ID = int(json_data["ID"]) #邮件ID DB = DBManager() json_back = xr_interface_mail.DeleteReaded(self_uid, languageStr) DB.destroy() return json_back
[ "handlers.kbeServer.XREditor.Interface.xr_interface_mail.GetMail", "Global.LanguageInst.GetMsg", "methods.DBManager.DBManager", "handlers.kbeServer.XREditor.Interface.xr_interface_mail.ReadMail", "handlers.kbeServer.XREditor.Interface.xr_interface_mail.DetMail", "handlers.kbeServer.XREditor.Interface.xr_i...
[((2255, 2266), 'methods.DBManager.DBManager', 'DBManager', ([], {}), '()\n', (2264, 2266), False, 'from methods.DBManager import DBManager\n'), ((2283, 2335), 'handlers.kbeServer.XREditor.Interface.xr_interface_mail.ReadAll', 'xr_interface_mail.ReadAll', (['DB', 'self_uid', 'languageStr'], {}), '(DB, self_uid, languageStr)\n', (2308, 2335), False, 'from handlers.kbeServer.XREditor.Interface import xr_interface_mail\n'), ((2685, 2696), 'methods.DBManager.DBManager', 'DBManager', ([], {}), '()\n', (2694, 2696), False, 'from methods.DBManager import DBManager\n'), ((2713, 2766), 'handlers.kbeServer.XREditor.Interface.xr_interface_mail.DeleteReaded', 'xr_interface_mail.DeleteReaded', (['self_uid', 'languageStr'], {}), '(self_uid, languageStr)\n', (2743, 2766), False, 'from handlers.kbeServer.XREditor.Interface import xr_interface_mail\n'), ((565, 618), 'Global.LanguageInst.GetMsg', 'Global.LanguageInst.GetMsg', (['"""SMSGID_1_4"""', 'languageStr'], {}), "('SMSGID_1_4', languageStr)\n", (591, 618), False, 'import Global\n'), ((672, 683), 'methods.DBManager.DBManager', 'DBManager', ([], {}), '()\n', (681, 683), False, 'from methods.DBManager import DBManager\n'), ((704, 768), 'handlers.kbeServer.XREditor.Interface.xr_interface_mail.GetMail', 'xr_interface_mail.GetMail', (['DB', 'self_uid', 'page', 'hnum', 'languageStr'], {}), '(DB, self_uid, page, hnum, languageStr)\n', (729, 768), False, 'from handlers.kbeServer.XREditor.Interface import xr_interface_mail\n'), ((1188, 1241), 'Global.LanguageInst.GetMsg', 'Global.LanguageInst.GetMsg', (['"""SMSGID_1_4"""', 'languageStr'], {}), "('SMSGID_1_4', languageStr)\n", (1214, 1241), False, 'import Global\n'), ((1302, 1355), 'handlers.kbeServer.XREditor.Interface.xr_interface_mail.ReadMail', 'xr_interface_mail.ReadMail', (['self_uid', 'ID', 'languageStr'], {}), '(self_uid, ID, languageStr)\n', (1328, 1355), False, 'from handlers.kbeServer.XREditor.Interface import xr_interface_mail\n'), ((1757, 1810), 'Global.LanguageInst.GetMsg', 'Global.LanguageInst.GetMsg', (['"""SMSGID_1_4"""', 'languageStr'], {}), "('SMSGID_1_4', languageStr)\n", (1783, 1810), False, 'import Global\n'), ((1871, 1923), 'handlers.kbeServer.XREditor.Interface.xr_interface_mail.DetMail', 'xr_interface_mail.DetMail', (['self_uid', 'ID', 'languageStr'], {}), '(self_uid, ID, languageStr)\n', (1896, 1923), False, 'from handlers.kbeServer.XREditor.Interface import xr_interface_mail\n')]
#!/usr/bin/env python3.7 # # Please note that the following code is a demo. Edge cases and error # checking are intentionally omitted where they might otherwise distract # us from the core ideas. # "Before we can understand how something can go wrong, we must # learn how it can go right." print('Example from Mastering Bitcoin, pages 69-70.') # A private key must be a whole number from 1 to # 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140, # one less than the order of the base point (or "generator point") G. # See: # https://en.bitcoin.it/wiki/Private_key#Range_of_valid_ECDSA_private_keys private_key = 0x038109007313a5807b2eccc082c8c3fbb988a973cacf1a7df9ce725c31b14776 print(f'\tprivate_key:\n{private_key}') class Point: def __init__(self, x=0, y=0): self.x = x self.y = y # Secp256k1 parameters. See: # https://en.bitcoin.it/wiki/Secp256k1 # https://www.secg.org/sec2-v2.pdf - Section 2.4.1. p = 2**256 - 2**32 - 2**9 - 2**8 - 2**7 - 2**6 - 2**4 - 1 G = Point( 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798, 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8, ) # Elliptic curve point addition. Unneeded side-cases are omitted for # simplicity. See: # https://en.wikipedia.org/wiki/Elliptic_curve_point_multiplication#Point_addition # https://stackoverflow.com/a/31089415 # https://en.wikipedia.org/wiki/Modular_multiplicative_inverse#Using_Euler's_theorem # https://crypto.stanford.edu/pbc/notes/elliptic/explicit.html def ec_point_add(P, Q): if not P: return Q if P == Q: slope = 3*P.x**2 * pow(2*P.y, p-2, p) # 3Px^2 / 2Py else: slope = (Q.y - P.y) * pow(Q.x - P.x, p-2, p) # (Qy - Py) / (Qx - Px) R = Point() R.x = (slope**2 - P.x - Q.x) % p # (slope^2 - Px - Qx) R.y = (slope*(P.x - R.x) - P.y) % p # slope*(Px - Rx) - Py return R # Elliptic curve point multiplication. This is an implimentation of the # Double-and-add algorithm with increasing index described here: # https://en.wikipedia.org/wiki/Elliptic_curve_point_multiplication#Double-and-add def ec_point_multiply(d, P): N = P Q = None while d: if d & 1: Q = ec_point_add(Q, N) N = ec_point_add(N, N) d >>= 1 return Q # Generate the public key. See: # Mastering Bitcoin, page 63. public_key = ec_point_multiply(private_key, G) print(f'\tpublic_key:\nx={public_key.x}\ny={public_key.y}') # The compressed serialisation of the public key. See: # Mastering Bitcoin, pages 73-75. # https://www.ntirawen.com/2019/03/bitcoin-compressed-and-uncompressed.html # https://www.secg.org/sec2-v2.pdf - Section 2.4.1. # https://www.secg.org/sec1-v2.pdf - Section 2.3.3. def serialize(K): if K.y % 2: leading_byte = b'\x03' else: leading_byte = b'\x02' return leading_byte + K.x.to_bytes(32, byteorder='big') serialized_public_key = serialize(public_key) print(f'\tserialized_public_key:\n{serialized_public_key.hex()}') import hashlib # For sha256 and ripemd160. def sha256(data): return hashlib.new('sha256', data).digest() def ripemd160(data): return hashlib.new('ripemd160', data).digest() public_key_hash = ripemd160(sha256(serialized_public_key)) print(f'\tpublic_key_hash:\n{public_key_hash.hex()}') # Calculate the checksum needed for Bitcoin's Base58Check format. See: # Mastering Bitcoin, page 58 # https://en.bitcoin.it/wiki/Technical_background_of_version_1_Bitcoin_addresses#How_to_create_Bitcoin_Address - Steps 5-7. version = b'\x00' checksum = sha256(sha256(version + public_key_hash))[:4] print(f'\tchecksum:\n{checksum.hex()}') # Encode the data in Bitcoin's Base58 format. See: # https://en.bitcoin.it/wiki/Base58Check_encoding#Base58_symbol_chart def base58(data): alphabet = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' x = int.from_bytes(data, byteorder='big') result = [] while x: x, i = divmod(x, 58) result.append(alphabet[i]) for byte in data: if byte: break result.append(alphabet[0]) result.reverse() return ''.join(result) # A Bitcoin address is just the public key hash encoded in Bitcoin's # Base58Check format. See: # Mastering Bitcoin, page 66. address = base58(version + public_key_hash + checksum) print(f'\taddress:\n{address}')
[ "hashlib.new" ]
[((3165, 3192), 'hashlib.new', 'hashlib.new', (['"""sha256"""', 'data'], {}), "('sha256', data)\n", (3176, 3192), False, 'import hashlib\n'), ((3235, 3265), 'hashlib.new', 'hashlib.new', (['"""ripemd160"""', 'data'], {}), "('ripemd160', data)\n", (3246, 3265), False, 'import hashlib\n')]
# coding:utf-8 from flask_wtf import Form from wtforms import SelectField, StringField, TextAreaField, SubmitField, \ PasswordField from wtforms.validators import DataRequired, Length, Email, EqualTo from ..main.forms import CommentForm class CommonForm(Form): types = SelectField(u'博文分类', coerce=int, validators=[DataRequired()]) source = SelectField(u'博文来源', coerce=int, validators=[DataRequired()]) class SubmitArticlesForm(CommonForm): title = StringField(u'标题', validators=[DataRequired(), Length(1, 64)]) content = TextAreaField(u'博文内容', validators=[DataRequired()]) summary = TextAreaField(u'博文摘要', validators=[DataRequired()]) class ManageArticlesForm(CommonForm): pass class DeleteArticleForm(Form): articleId = StringField(validators=[DataRequired()]) class DeleteArticlesForm(Form): articleIds = StringField(validators=[DataRequired()]) class DeleteCommentsForm(Form): commentIds = StringField(validators=[DataRequired()]) class AdminCommentForm(CommentForm): article = StringField(validators=[DataRequired()]) class AddArticleTypeForm(Form): name = StringField(u'分类名称', validators=[DataRequired(), Length(1, 64)]) introduction = TextAreaField(u'分类介绍') setting_hide = SelectField(u'属性', coerce=int, validators=[DataRequired()]) menus = SelectField(u'所属导航', coerce=int, validators=[DataRequired()]) # You must add coerce=int, or the SelectFile validate function only validate the int data class EditArticleTypeForm(AddArticleTypeForm): articleType_id = StringField(validators=[DataRequired()]) class AddArticleTypeNavForm(Form): name = StringField(u'导航名称', validators=[DataRequired(), Length(1, 64)]) class EditArticleNavTypeForm(AddArticleTypeNavForm): nav_id = StringField(validators=[DataRequired()]) class SortArticleNavTypeForm(AddArticleTypeNavForm): order = StringField(u'序号', validators=[DataRequired()]) class CustomBlogInfoForm(Form): title = StringField(u'博客标题', validators=[DataRequired()]) signature = TextAreaField(u'个性签名', validators=[DataRequired()]) navbar = SelectField(u'导航样式', coerce=int, validators=[DataRequired()]) class AddBlogPluginForm(Form): title = StringField(u'插件名称', validators=[DataRequired()]) note = TextAreaField(u'备注') content = TextAreaField(u'内容', validators=[DataRequired()]) class ChangePasswordForm(Form): old_password = PasswordField(u'原来密码', validators=[DataRequired()]) password = PasswordField(u'<PASSWORD>', validators=[ DataRequired(), EqualTo('password2', message=u'两次输入密码不一致!')]) password2 = PasswordField(u'<PASSWORD>', validators=[DataRequired()]) class EditUserInfoForm(Form): username = StringField(u'昵称', validators=[DataRequired()]) email = StringField(u'电子邮件', validators=[DataRequired(), Length(1, 64), Email()]) password = PasswordField(u'<PASSWORD>', validators=[DataRequired()])
[ "wtforms.validators.Email", "wtforms.validators.EqualTo", "wtforms.validators.Length", "wtforms.validators.DataRequired", "wtforms.TextAreaField" ]
[((1209, 1231), 'wtforms.TextAreaField', 'TextAreaField', (['u"""分类介绍"""'], {}), "(u'分类介绍')\n", (1222, 1231), False, 'from wtforms import SelectField, StringField, TextAreaField, SubmitField, PasswordField\n'), ((2268, 2288), 'wtforms.TextAreaField', 'TextAreaField', (['u"""备注"""'], {}), "(u'备注')\n", (2281, 2288), False, 'from wtforms import SelectField, StringField, TextAreaField, SubmitField, PasswordField\n'), ((332, 346), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (344, 346), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((407, 421), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (419, 421), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((503, 517), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (515, 517), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((519, 532), 'wtforms.validators.Length', 'Length', (['(1)', '(64)'], {}), '(1, 64)\n', (525, 532), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((588, 602), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (600, 602), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((654, 668), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (666, 668), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((785, 799), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (797, 799), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((877, 891), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (889, 891), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((969, 983), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (981, 983), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((1063, 1077), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (1075, 1077), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((1166, 1180), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (1178, 1180), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((1182, 1195), 'wtforms.validators.Length', 'Length', (['(1)', '(64)'], {}), '(1, 64)\n', (1188, 1195), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((1298, 1312), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (1310, 1312), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((1376, 1390), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (1388, 1390), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((1569, 1583), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (1581, 1583), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((1675, 1689), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (1687, 1689), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((1691, 1704), 'wtforms.validators.Length', 'Length', (['(1)', '(64)'], {}), '(1, 64)\n', (1697, 1704), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((1791, 1805), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (1803, 1805), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((1910, 1924), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (1922, 1924), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((2010, 2024), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (2022, 2024), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((2078, 2092), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (2090, 2092), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((2153, 2167), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (2165, 2167), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((2248, 2262), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (2260, 2262), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((2340, 2354), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (2352, 2354), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((2449, 2463), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (2461, 2463), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((2523, 2537), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (2535, 2537), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((2539, 2582), 'wtforms.validators.EqualTo', 'EqualTo', (['"""password2"""'], {'message': 'u"""两次输入密码不一致!"""'}), "('password2', message=u'两次输入密码不一致!')\n", (2546, 2582), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((2642, 2656), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (2654, 2656), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((2741, 2755), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (2753, 2755), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((2807, 2821), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (2819, 2821), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((2823, 2836), 'wtforms.validators.Length', 'Length', (['(1)', '(64)'], {}), '(1, 64)\n', (2829, 2836), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((2838, 2845), 'wtforms.validators.Email', 'Email', ([], {}), '()\n', (2843, 2845), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n'), ((2896, 2910), 'wtforms.validators.DataRequired', 'DataRequired', ([], {}), '()\n', (2908, 2910), False, 'from wtforms.validators import DataRequired, Length, Email, EqualTo\n')]
#!/usr/bin/env python3 import json import iohservice if __name__ == "__main__": import random import sys dimension = 10 fquery = "../debug/query" freply = "../debug/reply" for i in range(5): if i == 3: jq = json.dumps( {"query_type":"new_run"} ) iohservice.query(jq, fquery, freply) sol = [random.randint(0,1) for j in range(dimension)] val = iohservice.call(sol, fquery, freply) print("f({}) = {}".format(sol,val)) # Nicely ask the server to stop. print("Send an EXIT query...", file=sys.stderr, end="") jq = json.dumps( {"query_type":"stop"}, indent=4) iohservice.query(jq, fquery, freply)
[ "iohservice.call", "json.dumps", "random.randint", "iohservice.query" ]
[((617, 661), 'json.dumps', 'json.dumps', (["{'query_type': 'stop'}"], {'indent': '(4)'}), "({'query_type': 'stop'}, indent=4)\n", (627, 661), False, 'import json\n'), ((666, 702), 'iohservice.query', 'iohservice.query', (['jq', 'fquery', 'freply'], {}), '(jq, fquery, freply)\n', (682, 702), False, 'import iohservice\n'), ((429, 465), 'iohservice.call', 'iohservice.call', (['sol', 'fquery', 'freply'], {}), '(sol, fquery, freply)\n', (444, 465), False, 'import iohservice\n'), ((255, 292), 'json.dumps', 'json.dumps', (["{'query_type': 'new_run'}"], {}), "({'query_type': 'new_run'})\n", (265, 292), False, 'import json\n'), ((306, 342), 'iohservice.query', 'iohservice.query', (['jq', 'fquery', 'freply'], {}), '(jq, fquery, freply)\n', (322, 342), False, 'import iohservice\n'), ((367, 387), 'random.randint', 'random.randint', (['(0)', '(1)'], {}), '(0, 1)\n', (381, 387), False, 'import random\n')]
import unittest import numpy as np from sklearn import exceptions # from sklearn.datasets import load_boston as load from skcosmo.datasets import load_csd_1000r as load from skcosmo.feature_selection import CUR class TestCUR(unittest.TestCase): def setUp(self): self.X, _ = load(return_X_y=True) def test_bad_transform(self): selector = CUR(n_to_select=2) with self.assertRaises(exceptions.NotFittedError): _ = selector.transform(self.X) def test_restart(self): """ This test checks that the model can be restarted with a new instance """ ref_selector = CUR(n_to_select=self.X.shape[-1] - 3).fit(X=self.X) ref_idx = ref_selector.selected_idx_ selector = CUR(n_to_select=1) selector.fit(self.X) for i in range(self.X.shape[-1] - 3): selector.n_to_select += 1 selector.fit(self.X, warm_start=True) self.assertEqual(selector.selected_idx_[i], ref_idx[i]) def test_non_it(self): """ This test checks that the model can be run non-iteratively """ C = self.X.T @ self.X _, UC = np.linalg.eigh(C) ref_idx = np.argsort(-(UC[:, -1] ** 2.0))[:-1] selector = CUR(n_to_select=self.X.shape[-1] - 1, iterative=False) selector.fit(self.X) self.assertTrue(np.allclose(selector.selected_idx_, ref_idx)) if __name__ == "__main__": unittest.main(verbosity=2)
[ "numpy.linalg.eigh", "numpy.allclose", "numpy.argsort", "skcosmo.datasets.load_csd_1000r", "unittest.main", "skcosmo.feature_selection.CUR" ]
[((1455, 1481), 'unittest.main', 'unittest.main', ([], {'verbosity': '(2)'}), '(verbosity=2)\n', (1468, 1481), False, 'import unittest\n'), ((290, 311), 'skcosmo.datasets.load_csd_1000r', 'load', ([], {'return_X_y': '(True)'}), '(return_X_y=True)\n', (294, 311), True, 'from skcosmo.datasets import load_csd_1000r as load\n'), ((366, 384), 'skcosmo.feature_selection.CUR', 'CUR', ([], {'n_to_select': '(2)'}), '(n_to_select=2)\n', (369, 384), False, 'from skcosmo.feature_selection import CUR\n'), ((758, 776), 'skcosmo.feature_selection.CUR', 'CUR', ([], {'n_to_select': '(1)'}), '(n_to_select=1)\n', (761, 776), False, 'from skcosmo.feature_selection import CUR\n'), ((1174, 1191), 'numpy.linalg.eigh', 'np.linalg.eigh', (['C'], {}), '(C)\n', (1188, 1191), True, 'import numpy as np\n'), ((1267, 1321), 'skcosmo.feature_selection.CUR', 'CUR', ([], {'n_to_select': '(self.X.shape[-1] - 1)', 'iterative': '(False)'}), '(n_to_select=self.X.shape[-1] - 1, iterative=False)\n', (1270, 1321), False, 'from skcosmo.feature_selection import CUR\n'), ((1210, 1239), 'numpy.argsort', 'np.argsort', (['(-UC[:, -1] ** 2.0)'], {}), '(-UC[:, -1] ** 2.0)\n', (1220, 1239), True, 'import numpy as np\n'), ((1376, 1420), 'numpy.allclose', 'np.allclose', (['selector.selected_idx_', 'ref_idx'], {}), '(selector.selected_idx_, ref_idx)\n', (1387, 1420), True, 'import numpy as np\n'), ((641, 678), 'skcosmo.feature_selection.CUR', 'CUR', ([], {'n_to_select': '(self.X.shape[-1] - 3)'}), '(n_to_select=self.X.shape[-1] - 3)\n', (644, 678), False, 'from skcosmo.feature_selection import CUR\n')]
from django.shortcuts import render,redirect from django.urls import reverse_lazy,reverse from django.contrib.auth.forms import UserCreationForm from django.views.generic import CreateView,DetailView,UpdateView,DeleteView,TemplateView from django.contrib.auth import authenticate,login from django.http import HttpResponseRedirect from halls.forms import VideoForm,SearchForm from django.forms.utils import ErrorList from django.http import Http404,JsonResponse from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin import urllib import requests # Create your views here. from halls.models import Hall,Video YOUTUBE_API_KEY='Your Youtube API Key' def home(request): popular_halls=[Hall.objects.get(pk=5),Hall.objects.get(pk=6),Hall.objects.get(pk=8),Hall.objects.get(pk=10)] recent_halls=Hall.objects.all().order_by('id')[:3] return render(request,'halls/home.html',context={'recent_halls':recent_halls,'popular_halls':popular_halls}) class about(TemplateView): template_name="halls/about.html" @login_required() def dashboard(request): halls=Hall.objects.filter(user=request.user) return render(request,'halls/dashboard.html',context={'halls':halls}) @login_required() def video_search(request): search_form=SearchForm(request.GET) if search_form.is_valid(): encoded_search_term=urllib.parse.quote(search_form.cleaned_data['search_form']) response=requests.get(f'https://youtube.googleapis.com/youtube/v3/search?part=snippet&maxResults=5&q={ encoded_search_term }&key={ YOUTUBE_API_KEY }') jsonreturn=search_form.cleaned_data['search_form'] return JsonResponse(response.json()) return JsonResponse({'error':'Not able to validate form'}) @login_required() def add_video(request,pk): form=VideoForm() search_form=SearchForm() hall=Hall.objects.get(pk=pk) if not hall.user==request.user: raise Http404 if request.method=='POST': form=VideoForm(request.POST) if form.is_valid(): video=Video() video.hall=hall video.url=form.cleaned_data['url'] parsed_url=urllib.parse.urlparse(video.url) video_id=urllib.parse.parse_qs(parsed_url.query).get('v') if video_id: video.youtube_id=video_id[0] response=requests.get(f'https://youtube.googleapis.com/youtube/v3/search?part=snippet&q={ video_id[0] }&key={YOUTUBE_API_KEY}') json=response.json() title=json['items'][0]['snippet']['title'] video.title=title video.save() return redirect('detail_hall',pk) else: errors = form._errors.setdefault("url", ErrorList()) errors.append('Needs to be a Youtube URL') return render(request,'halls/add_video.html',context={'form':form,'search_form':search_form,'hall':hall}) class SignUp(CreateView): form_class=UserCreationForm success_url=reverse_lazy('dashboard') template_name='registration/signup.html' # def form_valid(self, form): # valid=super().form_valid(form) # username, password = form.cleaned_data.get('username'), form.cleaned_data.get('password1') # user = authenticate(username=username, password=password) # This returns None # login(self.request, user) # return valid def form_valid(self, form): #save the new user first form.save() #get the username and password # username, password = form.cleaned_data.get('username'), form.cleaned_data.get('password1') # or username = self.request.POST['username'] password = self.request.POST['<PASSWORD>'] #authenticate user then login user = authenticate(username=username, password=password) login(self.request, user) return HttpResponseRedirect(reverse('dashboard')) class CreateHall(CreateView,LoginRequiredMixin): model=Hall fields=['title'] success_url=reverse_lazy('dashboard') template_name='halls/create_hall.html' def form_valid(self,form): form.instance.user=self.request.user view=super().form_valid(form) return view class DetailHall(DetailView): model=Hall context_object_name='hall_detail' class UpdateHall(UpdateView,LoginRequiredMixin): model=Hall fields=['title'] context_object_name='update_hall' success_url=reverse_lazy('dashboard') def get_object(self): hall=super().get_object() if hall.user.id != self.request.user.id: raise Http404 else: return hall class DeleteHall(DeleteView,LoginRequiredMixin): model=Hall context_object_name='delete_hall' success_url=reverse_lazy('dashboard') def get_object(self): hall=super().get_object() if hall.user.id != self.request.user.id: raise Http404 else: return hall class DeleteVideo(DeleteView,LoginRequiredMixin): model=Video context_object_name='delete_video' template_name='halls/delete_video.html' success_url=reverse_lazy('dashboard') def get_object(self): video=super().get_object() if video.hall.user != self.request.user: raise Http404 else: return video
[ "urllib.parse.parse_qs", "django.urls.reverse", "django.forms.utils.ErrorList", "django.shortcuts.render", "halls.forms.VideoForm", "halls.models.Hall.objects.all", "django.shortcuts.redirect", "django.urls.reverse_lazy", "halls.forms.SearchForm", "django.contrib.auth.authenticate", "halls.model...
[((1076, 1092), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {}), '()\n', (1090, 1092), False, 'from django.contrib.auth.decorators import login_required\n'), ((1241, 1257), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {}), '()\n', (1255, 1257), False, 'from django.contrib.auth.decorators import login_required\n'), ((1772, 1788), 'django.contrib.auth.decorators.login_required', 'login_required', ([], {}), '()\n', (1786, 1788), False, 'from django.contrib.auth.decorators import login_required\n'), ((908, 1018), 'django.shortcuts.render', 'render', (['request', '"""halls/home.html"""'], {'context': "{'recent_halls': recent_halls, 'popular_halls': popular_halls}"}), "(request, 'halls/home.html', context={'recent_halls': recent_halls,\n 'popular_halls': popular_halls})\n", (914, 1018), False, 'from django.shortcuts import render, redirect\n'), ((1127, 1165), 'halls.models.Hall.objects.filter', 'Hall.objects.filter', ([], {'user': 'request.user'}), '(user=request.user)\n', (1146, 1165), False, 'from halls.models import Hall, Video\n'), ((1177, 1242), 'django.shortcuts.render', 'render', (['request', '"""halls/dashboard.html"""'], {'context': "{'halls': halls}"}), "(request, 'halls/dashboard.html', context={'halls': halls})\n", (1183, 1242), False, 'from django.shortcuts import render, redirect\n'), ((1301, 1324), 'halls.forms.SearchForm', 'SearchForm', (['request.GET'], {}), '(request.GET)\n', (1311, 1324), False, 'from halls.forms import VideoForm, SearchForm\n'), ((1718, 1770), 'django.http.JsonResponse', 'JsonResponse', (["{'error': 'Not able to validate form'}"], {}), "({'error': 'Not able to validate form'})\n", (1730, 1770), False, 'from django.http import Http404, JsonResponse\n'), ((1825, 1836), 'halls.forms.VideoForm', 'VideoForm', ([], {}), '()\n', (1834, 1836), False, 'from halls.forms import VideoForm, SearchForm\n'), ((1853, 1865), 'halls.forms.SearchForm', 'SearchForm', ([], {}), '()\n', (1863, 1865), False, 'from halls.forms import VideoForm, SearchForm\n'), ((1875, 1898), 'halls.models.Hall.objects.get', 'Hall.objects.get', ([], {'pk': 'pk'}), '(pk=pk)\n', (1891, 1898), False, 'from halls.models import Hall, Video\n'), ((2861, 2970), 'django.shortcuts.render', 'render', (['request', '"""halls/add_video.html"""'], {'context': "{'form': form, 'search_form': search_form, 'hall': hall}"}), "(request, 'halls/add_video.html', context={'form': form,\n 'search_form': search_form, 'hall': hall})\n", (2867, 2970), False, 'from django.shortcuts import render, redirect\n'), ((3035, 3060), 'django.urls.reverse_lazy', 'reverse_lazy', (['"""dashboard"""'], {}), "('dashboard')\n", (3047, 3060), False, 'from django.urls import reverse_lazy, reverse\n'), ((4067, 4092), 'django.urls.reverse_lazy', 'reverse_lazy', (['"""dashboard"""'], {}), "('dashboard')\n", (4079, 4092), False, 'from django.urls import reverse_lazy, reverse\n'), ((4494, 4519), 'django.urls.reverse_lazy', 'reverse_lazy', (['"""dashboard"""'], {}), "('dashboard')\n", (4506, 4519), False, 'from django.urls import reverse_lazy, reverse\n'), ((4812, 4837), 'django.urls.reverse_lazy', 'reverse_lazy', (['"""dashboard"""'], {}), "('dashboard')\n", (4824, 4837), False, 'from django.urls import reverse_lazy, reverse\n'), ((5177, 5202), 'django.urls.reverse_lazy', 'reverse_lazy', (['"""dashboard"""'], {}), "('dashboard')\n", (5189, 5202), False, 'from django.urls import reverse_lazy, reverse\n'), ((747, 769), 'halls.models.Hall.objects.get', 'Hall.objects.get', ([], {'pk': '(5)'}), '(pk=5)\n', (763, 769), False, 'from halls.models import Hall, Video\n'), ((770, 792), 'halls.models.Hall.objects.get', 'Hall.objects.get', ([], {'pk': '(6)'}), '(pk=6)\n', (786, 792), False, 'from halls.models import Hall, Video\n'), ((793, 815), 'halls.models.Hall.objects.get', 'Hall.objects.get', ([], {'pk': '(8)'}), '(pk=8)\n', (809, 815), False, 'from halls.models import Hall, Video\n'), ((816, 839), 'halls.models.Hall.objects.get', 'Hall.objects.get', ([], {'pk': '(10)'}), '(pk=10)\n', (832, 839), False, 'from halls.models import Hall, Video\n'), ((1384, 1443), 'urllib.parse.quote', 'urllib.parse.quote', (["search_form.cleaned_data['search_form']"], {}), "(search_form.cleaned_data['search_form'])\n", (1402, 1443), False, 'import urllib\n'), ((1461, 1608), 'requests.get', 'requests.get', (['f"""https://youtube.googleapis.com/youtube/v3/search?part=snippet&maxResults=5&q={encoded_search_term}&key={YOUTUBE_API_KEY}"""'], {}), "(\n f'https://youtube.googleapis.com/youtube/v3/search?part=snippet&maxResults=5&q={encoded_search_term}&key={YOUTUBE_API_KEY}'\n )\n", (1473, 1608), False, 'import requests\n'), ((2001, 2024), 'halls.forms.VideoForm', 'VideoForm', (['request.POST'], {}), '(request.POST)\n', (2010, 2024), False, 'from halls.forms import VideoForm, SearchForm\n'), ((3823, 3873), 'django.contrib.auth.authenticate', 'authenticate', ([], {'username': 'username', 'password': 'password'}), '(username=username, password=password)\n', (3835, 3873), False, 'from django.contrib.auth import authenticate, login\n'), ((3882, 3907), 'django.contrib.auth.login', 'login', (['self.request', 'user'], {}), '(self.request, user)\n', (3887, 3907), False, 'from django.contrib.auth import authenticate, login\n'), ((2071, 2078), 'halls.models.Video', 'Video', ([], {}), '()\n', (2076, 2078), False, 'from halls.models import Hall, Video\n'), ((2177, 2209), 'urllib.parse.urlparse', 'urllib.parse.urlparse', (['video.url'], {}), '(video.url)\n', (2198, 2209), False, 'import urllib\n'), ((3944, 3964), 'django.urls.reverse', 'reverse', (['"""dashboard"""'], {}), "('dashboard')\n", (3951, 3964), False, 'from django.urls import reverse_lazy, reverse\n'), ((858, 876), 'halls.models.Hall.objects.all', 'Hall.objects.all', ([], {}), '()\n', (874, 876), False, 'from halls.models import Hall, Video\n'), ((2375, 2501), 'requests.get', 'requests.get', (['f"""https://youtube.googleapis.com/youtube/v3/search?part=snippet&q={video_id[0]}&key={YOUTUBE_API_KEY}"""'], {}), "(\n f'https://youtube.googleapis.com/youtube/v3/search?part=snippet&q={video_id[0]}&key={YOUTUBE_API_KEY}'\n )\n", (2387, 2501), False, 'import requests\n'), ((2676, 2703), 'django.shortcuts.redirect', 'redirect', (['"""detail_hall"""', 'pk'], {}), "('detail_hall', pk)\n", (2684, 2703), False, 'from django.shortcuts import render, redirect\n'), ((2231, 2270), 'urllib.parse.parse_qs', 'urllib.parse.parse_qs', (['parsed_url.query'], {}), '(parsed_url.query)\n', (2252, 2270), False, 'import urllib\n'), ((2778, 2789), 'django.forms.utils.ErrorList', 'ErrorList', ([], {}), '()\n', (2787, 2789), False, 'from django.forms.utils import ErrorList\n')]
import warnings import numpy as np from sklearn.covariance import oas, ledoit_wolf, fast_mcd, empirical_covariance from .test import is_square # Mapping different estimator on the sklearn toolbox def _lwf(X): """Wrapper for sklearn ledoit wolf covariance estimator""" C, _ = ledoit_wolf(X.T) return C def _oas(X): """Wrapper for sklearn oas covariance estimator""" C, _ = oas(X.T) return C def _scm(X): """Wrapper for sklearn sample covariance estimator""" return empirical_covariance(X.T) def _mcd(X): """Wrapper for sklearn mcd covariance estimator""" _, C, _, _ = fast_mcd(X.T) return C def _sch(X): """Schaefer-Strimmer covariance estimator Shrinkage estimator using method from [1]_: .. math:: \hat{\Sigma} = (1 - \gamma)\Sigma_{scm} + \gamma T where :math:`T` is the diagonal target matrix: .. math:: T_{i,j} = \{ \Sigma_{scm}^{ii} \text{if} i = j, 0 \text{otherwise} \} Note that the optimal :math:`\gamma` is estimated by the authors' method. :param X: Multi-channel time-series, (n_channels, n_times) :returns: Schaefer-Strimmer shrinkage covariance matrix, (n_channels, n_channels) Notes ----- .. versionadded:: 0.2.8 References ---------- .. [1] <NAME>., and <NAME>. 2005. A shrinkage approach to large-scale covariance estimation and implications for functional genomics. Statist. Appl. Genet. Mol. Biol. 4:32. """ # noqa n_times = X.shape[1] X_c = (X.T - X.T.mean(axis=0)).T C_scm = 1. / n_times * X_c @ X_c.T # Compute optimal gamma, the weigthing between SCM and srinkage estimator R = (n_times / ((n_times - 1.) * np.outer(X.std(axis=1), X.std(axis=1)))) R *= C_scm var_R = (X_c ** 2) @ (X_c ** 2).T - 2 * C_scm * (X_c @ X_c.T) var_R += n_times * C_scm ** 2 Xvar = np.outer(X.var(axis=1), X.var(axis=1)) var_R *= n_times / ((n_times - 1) ** 3 * Xvar) R -= np.diag(np.diag(R)) var_R -= np.diag(np.diag(var_R)) gamma = max(0, min(1, var_R.sum() / (R ** 2).sum())) sigma = (1. - gamma) * (n_times / (n_times - 1.)) * C_scm shrinkage = gamma * (n_times / (n_times - 1.)) * np.diag(np.diag(C_scm)) return sigma + shrinkage def _check_est(est): """Check if a given estimator is valid""" # Check estimator exist and return the correct function estimators = { 'cov': np.cov, 'scm': _scm, 'lwf': _lwf, 'oas': _oas, 'mcd': _mcd, 'sch': _sch, 'corr': np.corrcoef } if callable(est): # All good (cross your fingers) pass elif est in estimators.keys(): # Map the corresponding estimator est = estimators[est] else: # raise an error raise ValueError( """%s is not an valid estimator ! Valid estimators are : %s or a callable function""" % (est, (' , ').join(estimators.keys()))) return est def covariances(X, estimator='cov'): """Estimation of covariance matrix. Parameters ---------- X : ndarray, shape (n_matrices, n_channels, n_times) Multi-channel time-series. estimator : {'cov', 'scm', 'lwf', 'oas', 'mcd', 'sch', 'corr'} \ (default: 'scm') Covariance matrix estimator: * 'cov' for numpy based covariance matrix, https://numpy.org/doc/stable/reference/generated/numpy.cov.html * 'scm' for sample covariance matrix, https://scikit-learn.org/stable/modules/generated/sklearn.covariance.empirical_covariance.html * 'lwf' for shrunk Ledoit-Wolf covariance matrix https://scikit-learn.org/stable/modules/generated/sklearn.covariance.ledoit_wolf.html * 'oas' for oracle approximating shrunk covariance matrix, https://scikit-learn.org/stable/modules/generated/sklearn.covariance.OAS.html * 'mcd' for minimum covariance determinant matrix, https://scikit-learn.org/stable/modules/generated/sklearn.covariance.MinCovDet.html * 'sch' for Schaefer-Strimmer covariance, http://doi.org/10.2202/1544-6115.1175, * 'corr' for correlation coefficient matrix, https://numpy.org/doc/stable/reference/generated/numpy.corrcoef.html Returns ------- covmats : ndarray, shape (n_matrices, n_channels, n_channels) Covariance matrices. References ---------- .. [1] https://scikit-learn.org/stable/modules/covariance.html """ # noqa est = _check_est(estimator) n_matrices, n_channels, n_times = X.shape covmats = np.empty((n_matrices, n_channels, n_channels)) for i in range(n_matrices): covmats[i] = est(X[i]) return covmats def covariances_EP(X, P, estimator='cov'): """Special form covariance matrix, concatenating a prototype P. Parameters ---------- X : ndarray, shape (n_matrices, n_channels, n_times) Multi-channel time-series. P : ndarray, shape (n_channels_proto, n_times) Multi-channel prototype. estimator : {'cov', 'scm', 'lwf', 'oas', 'mcd', 'sch', 'corr'} \ (default: 'cov') Covariance matrix estimator, see :func:`pyriemann.utils.covariance.covariances`. Returns ------- covmats : ndarray, shape (n_matrices, n_channels + n_channels_proto, \ n_channels + n_channels_proto) Covariance matrices. """ est = _check_est(estimator) n_matrices, n_channels, n_times = X.shape n_channels_proto, n_times_p = P.shape if n_times_p != n_times: raise ValueError( f"X and P do not have the same n_times: {n_times} and {n_times_p}") covmats = np.empty((n_matrices, n_channels + n_channels_proto, n_channels + n_channels_proto)) for i in range(n_matrices): covmats[i] = est(np.concatenate((P, X[i]), axis=0)) return covmats def covariances_X(X, estimator='scm', alpha=0.2): """Special form covariance matrix, embedding input X. Parameters ---------- X : ndarray, shape (n_matrices, n_channels, n_times) Multi-channel time-series. estimator : {'cov', 'scm', 'lwf', 'oas', 'mcd', 'sch', 'corr'} \ (default: 'scm') Covariance matrix estimator, see :func:`pyriemann.utils.covariance.covariances`. alpha : float (default 0.2) Regularization parameter (strictly positive). Returns ------- covmats : ndarray, shape (n_matrices, n_channels + n_times, n_channels + \ n_times) Covariance matrices. References ---------- .. [1] <NAME> and <NAME>, "A special form of SPD covariance matrix for interpretation and visualization of data manipulated with Riemannian geometry", AIP Conference Proceedings 1641, 2015 """ if alpha <= 0: raise ValueError( 'Parameter alpha must be strictly positive (Got %d)' % alpha) est = _check_est(estimator) n_matrices, n_channels, n_times = X.shape Hchannels = np.eye(n_channels) \ - np.outer(np.ones(n_channels), np.ones(n_channels)) / n_channels Htimes = np.eye(n_times) \ - np.outer(np.ones(n_times), np.ones(n_times)) / n_times X = Hchannels @ X @ Htimes # Eq(8), double centering covmats = np.empty( (n_matrices, n_channels + n_times, n_channels + n_times)) for i in range(n_matrices): Y = np.concatenate(( np.concatenate((X[i], alpha * np.eye(n_channels)), axis=1), # top np.concatenate((alpha * np.eye(n_times), X[i].T), axis=1) # bottom ), axis=0) # Eq(9) covmats[i] = est(Y) return covmats / (2 * alpha) # Eq(10) def eegtocov(sig, window=128, overlapp=0.5, padding=True, estimator='cov'): """Convert EEG signal to covariance using sliding window""" est = _check_est(estimator) X = [] if padding: padd = np.zeros((int(window / 2), sig.shape[1])) sig = np.concatenate((padd, sig, padd), axis=0) n_times, n_channels = sig.shape jump = int(window * overlapp) ix = 0 while (ix + window < n_times): X.append(est(sig[ix:ix + window, :].T)) ix = ix + jump return np.array(X) ############################################################################### def cross_spectrum(X, window=128, overlap=0.75, fmin=None, fmax=None, fs=None): """Compute the complex cross-spectral matrices of a real signal X. Parameters ---------- X : ndarray, shape (n_channels, n_times) Multi-channel time-series. window : int (default 128) The length of the FFT window used for spectral estimation. overlap : float (default 0.75) The percentage of overlap between window. fmin : float | None, (default None) The minimal frequency to be returned. fmax : float | None, (default None) The maximal frequency to be returned. fs : float | None, (default None) The sampling frequency of the signal. Returns ------- S : ndarray, shape (n_channels, n_channels, n_freqs) Cross-spectral matrices, for each frequency bin. freqs : ndarray, shape (n_freqs,) The frequencies associated to cross-spectra. References ---------- .. [1] https://en.wikipedia.org/wiki/Cross-spectrum """ window = int(window) if window < 1: raise ValueError('Value window must be a positive integer') if not 0 < overlap < 1: raise ValueError( 'Value overlap must be included in (0, 1) (Got %d)' % overlap) n_channels, n_times = X.shape n_freqs = int(window / 2) + 1 # X real signal => compute half-spectrum step = int((1.0 - overlap) * window) n_windows = int((n_times - window) / step + 1) win = np.hanning(window) # FFT calculation on all windows shape = (n_channels, n_windows, window) strides = X.strides[:-1]+(step*X.strides[-1], X.strides[-1]) Xs = np.lib.stride_tricks.as_strided(X, shape=shape, strides=strides) fdata = np.fft.rfft(Xs * win, n=window).transpose(1, 0, 2) # adjust frequency range to specified range if fs is not None: if fmin is None: fmin = 0 if fmax is None: fmax = fs / 2 if fmax <= fmin: raise ValueError('Parameter fmax must be superior to fmin') if 2.0 * fmax > fs: # check Nyquist-Shannon raise ValueError('Parameter fmax must be inferior to fs/2') f = np.arange(0, n_freqs, dtype=int) * float(fs / window) fix = (f >= fmin) & (f <= fmax) fdata = fdata[:, :, fix] freqs = f[fix] else: if fmin is not None: warnings.warn('Parameter fmin not used because fs is None') if fmax is not None: warnings.warn('Parameter fmax not used because fs is None') freqs = None n_freqs = fdata.shape[2] S = np.zeros((n_channels, n_channels, n_freqs), dtype=complex) for i in range(n_freqs): S[:, :, i] = fdata[:, :, i].conj().T @ fdata[:, :, i] S /= n_windows * np.linalg.norm(win)**2 # normalization to respect Parseval's theorem with the half-spectrum # excepted DC bin (always), and Nyquist bin (when window is even) if window % 2: S[..., 1:] *= 2 else: S[..., 1:-1] *= 2 return S, freqs def cospectrum(X, window=128, overlap=0.75, fmin=None, fmax=None, fs=None): """Compute co-spectral matrices, the real part of cross-spectra. Parameters ---------- X : ndarray, shape (n_channels, n_times) Multi-channel time-series. window : int (default 128) The length of the FFT window used for spectral estimation. overlap : float (default 0.75) The percentage of overlap between window. fmin : float | None, (default None) The minimal frequency to be returned. fmax : float | None, (default None) The maximal frequency to be returned. fs : float | None, (default None) The sampling frequency of the signal. Returns ------- S : ndarray, shape (n_channels, n_channels, n_freqs) Co-spectral matrices, for each frequency bin. freqs : ndarray, shape (n_freqs,) The frequencies associated to cospectra. """ S, freqs = cross_spectrum( X=X, window=window, overlap=overlap, fmin=fmin, fmax=fmax, fs=fs) return S.real, freqs def coherence(X, window=128, overlap=0.75, fmin=None, fmax=None, fs=None, coh='ordinary'): """Compute squared coherence. Parameters ---------- X : ndarray, shape (n_channels, n_times) Multi-channel time-series. window : int (default 128) The length of the FFT window used for spectral estimation. overlap : float (default 0.75) The percentage of overlap between window. fmin : float | None, (default None) The minimal frequency to be returned. fmax : float | None, (default None) The maximal frequency to be returned. fs : float | None, (default None) The sampling frequency of the signal. coh : {'ordinary', 'instantaneous', 'lagged', 'imaginary'}, (default \ 'ordinary') The coherence type, see :class:`pyriemann.estimation.Coherences`. Returns ------- C : ndarray, shape (n_channels, n_channels, n_freqs) Squared coherence matrices, for each frequency bin. freqs : ndarray, shape (n_freqs,) The frequencies associated to coherence. """ S, freqs = cross_spectrum( X, window=window, overlap=overlap, fmin=fmin, fmax=fmax, fs=fs) S2 = np.abs(S)**2 # squared cross-spectral modulus C = np.zeros_like(S2) f_inds = np.arange(0, C.shape[-1], dtype=int) # lagged coh not defined for DC and Nyquist bins, because S is real if coh == 'lagged': if freqs is None: f_inds = np.arange(1, C.shape[-1] - 1, dtype=int) warnings.warn('DC and Nyquist bins are not defined for lagged-' 'coherence: filled with zeros') else: f_inds_ = f_inds[(freqs > 0) & (freqs < fs / 2)] if not np.array_equal(f_inds_, f_inds): warnings.warn('DC and Nyquist bins are not defined for lagged-' 'coherence: filled with zeros') f_inds = f_inds_ for f in f_inds: psd = np.sqrt(np.diag(S2[..., f])) psd_prod = np.outer(psd, psd) if coh == 'ordinary': C[..., f] = S2[..., f] / psd_prod elif coh == 'instantaneous': C[..., f] = (S[..., f].real)**2 / psd_prod elif coh == 'lagged': np.fill_diagonal(S[..., f].real, 0.) # prevent div by zero on diag C[..., f] = (S[..., f].imag)**2 / (psd_prod - (S[..., f].real)**2) elif coh == 'imaginary': C[..., f] = (S[..., f].imag)**2 / psd_prod else: raise ValueError("'%s' is not a supported coherence" % coh) return C, freqs ############################################################################### def normalize(X, norm): """Normalize a set of square matrices, using trace or determinant. Parameters ---------- X : ndarray, shape (..., n, n) The set of square matrices, at least 2D ndarray. Matrices must be invertible for determinant-normalization. norm : {"trace", "determinant"} The type of normalization. Returns ------- Xn : ndarray, shape (..., n, n) The set of normalized matrices, same dimensions as X. """ if not is_square(X): raise ValueError('Matrices must be square') if norm == "trace": denom = np.trace(X, axis1=-2, axis2=-1) elif norm == "determinant": denom = np.abs(np.linalg.det(X)) ** (1 / X.shape[-1]) else: raise ValueError("'%s' is not a supported normalization" % norm) while denom.ndim != X.ndim: denom = denom[..., np.newaxis] Xn = X / denom return Xn def get_nondiag_weight(X): """Compute non-diagonality weights of a set of square matrices, following Eq(B.1) in [1]_. Parameters ---------- X : ndarray, shape (..., n, n) The set of square matrices, at least 2D ndarray. Returns ------- weights : ndarray, shape (...,) The non-diagonality weights for matrices. References ---------- .. [1] <NAME>, <NAME>, <NAME>, "On the blind source separation of human electroencephalogram by approximate joint diagonalization of second order statistics", Clin Neurophysiol, 2008 """ if not is_square(X): raise ValueError('Matrices must be square') X2 = X**2 # sum of squared diagonal elements denom = np.trace(X2, axis1=-2, axis2=-1) # sum of squared off-diagonal elements num = np.sum(X2, axis=(-2, -1)) - denom weights = (1.0 / (X.shape[-1] - 1)) * (num / denom) return weights
[ "numpy.hanning", "numpy.trace", "numpy.array", "numpy.linalg.norm", "numpy.arange", "sklearn.covariance.fast_mcd", "numpy.fft.rfft", "numpy.empty", "numpy.concatenate", "warnings.warn", "numpy.abs", "numpy.eye", "numpy.ones", "sklearn.covariance.oas", "numpy.fill_diagonal", "numpy.lib....
[((288, 304), 'sklearn.covariance.ledoit_wolf', 'ledoit_wolf', (['X.T'], {}), '(X.T)\n', (299, 304), False, 'from sklearn.covariance import oas, ledoit_wolf, fast_mcd, empirical_covariance\n'), ((399, 407), 'sklearn.covariance.oas', 'oas', (['X.T'], {}), '(X.T)\n', (402, 407), False, 'from sklearn.covariance import oas, ledoit_wolf, fast_mcd, empirical_covariance\n'), ((505, 530), 'sklearn.covariance.empirical_covariance', 'empirical_covariance', (['X.T'], {}), '(X.T)\n', (525, 530), False, 'from sklearn.covariance import oas, ledoit_wolf, fast_mcd, empirical_covariance\n'), ((618, 631), 'sklearn.covariance.fast_mcd', 'fast_mcd', (['X.T'], {}), '(X.T)\n', (626, 631), False, 'from sklearn.covariance import oas, ledoit_wolf, fast_mcd, empirical_covariance\n'), ((4619, 4665), 'numpy.empty', 'np.empty', (['(n_matrices, n_channels, n_channels)'], {}), '((n_matrices, n_channels, n_channels))\n', (4627, 4665), True, 'import numpy as np\n'), ((5712, 5800), 'numpy.empty', 'np.empty', (['(n_matrices, n_channels + n_channels_proto, n_channels + n_channels_proto)'], {}), '((n_matrices, n_channels + n_channels_proto, n_channels +\n n_channels_proto))\n', (5720, 5800), True, 'import numpy as np\n'), ((7326, 7392), 'numpy.empty', 'np.empty', (['(n_matrices, n_channels + n_times, n_channels + n_times)'], {}), '((n_matrices, n_channels + n_times, n_channels + n_times))\n', (7334, 7392), True, 'import numpy as np\n'), ((8235, 8246), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (8243, 8246), True, 'import numpy as np\n'), ((9811, 9829), 'numpy.hanning', 'np.hanning', (['window'], {}), '(window)\n', (9821, 9829), True, 'import numpy as np\n'), ((9986, 10050), 'numpy.lib.stride_tricks.as_strided', 'np.lib.stride_tricks.as_strided', (['X'], {'shape': 'shape', 'strides': 'strides'}), '(X, shape=shape, strides=strides)\n', (10017, 10050), True, 'import numpy as np\n'), ((10938, 10996), 'numpy.zeros', 'np.zeros', (['(n_channels, n_channels, n_freqs)'], {'dtype': 'complex'}), '((n_channels, n_channels, n_freqs), dtype=complex)\n', (10946, 10996), True, 'import numpy as np\n'), ((13784, 13801), 'numpy.zeros_like', 'np.zeros_like', (['S2'], {}), '(S2)\n', (13797, 13801), True, 'import numpy as np\n'), ((13815, 13851), 'numpy.arange', 'np.arange', (['(0)', 'C.shape[-1]'], {'dtype': 'int'}), '(0, C.shape[-1], dtype=int)\n', (13824, 13851), True, 'import numpy as np\n'), ((16875, 16907), 'numpy.trace', 'np.trace', (['X2'], {'axis1': '(-2)', 'axis2': '(-1)'}), '(X2, axis1=-2, axis2=-1)\n', (16883, 16907), True, 'import numpy as np\n'), ((1989, 1999), 'numpy.diag', 'np.diag', (['R'], {}), '(R)\n', (1996, 1999), True, 'import numpy as np\n'), ((2022, 2036), 'numpy.diag', 'np.diag', (['var_R'], {}), '(var_R)\n', (2029, 2036), True, 'import numpy as np\n'), ((7062, 7080), 'numpy.eye', 'np.eye', (['n_channels'], {}), '(n_channels)\n', (7068, 7080), True, 'import numpy as np\n'), ((7170, 7185), 'numpy.eye', 'np.eye', (['n_times'], {}), '(n_times)\n', (7176, 7185), True, 'import numpy as np\n'), ((7993, 8034), 'numpy.concatenate', 'np.concatenate', (['(padd, sig, padd)'], {'axis': '(0)'}), '((padd, sig, padd), axis=0)\n', (8007, 8034), True, 'import numpy as np\n'), ((13728, 13737), 'numpy.abs', 'np.abs', (['S'], {}), '(S)\n', (13734, 13737), True, 'import numpy as np\n'), ((14553, 14571), 'numpy.outer', 'np.outer', (['psd', 'psd'], {}), '(psd, psd)\n', (14561, 14571), True, 'import numpy as np\n'), ((15814, 15845), 'numpy.trace', 'np.trace', (['X'], {'axis1': '(-2)', 'axis2': '(-1)'}), '(X, axis1=-2, axis2=-1)\n', (15822, 15845), True, 'import numpy as np\n'), ((16961, 16986), 'numpy.sum', 'np.sum', (['X2'], {'axis': '(-2, -1)'}), '(X2, axis=(-2, -1))\n', (16967, 16986), True, 'import numpy as np\n'), ((2219, 2233), 'numpy.diag', 'np.diag', (['C_scm'], {}), '(C_scm)\n', (2226, 2233), True, 'import numpy as np\n'), ((5878, 5911), 'numpy.concatenate', 'np.concatenate', (['(P, X[i])'], {'axis': '(0)'}), '((P, X[i]), axis=0)\n', (5892, 5911), True, 'import numpy as np\n'), ((10063, 10094), 'numpy.fft.rfft', 'np.fft.rfft', (['(Xs * win)'], {'n': 'window'}), '(Xs * win, n=window)\n', (10074, 10094), True, 'import numpy as np\n'), ((10517, 10549), 'numpy.arange', 'np.arange', (['(0)', 'n_freqs'], {'dtype': 'int'}), '(0, n_freqs, dtype=int)\n', (10526, 10549), True, 'import numpy as np\n'), ((10718, 10777), 'warnings.warn', 'warnings.warn', (['"""Parameter fmin not used because fs is None"""'], {}), "('Parameter fmin not used because fs is None')\n", (10731, 10777), False, 'import warnings\n'), ((10819, 10878), 'warnings.warn', 'warnings.warn', (['"""Parameter fmax not used because fs is None"""'], {}), "('Parameter fmax not used because fs is None')\n", (10832, 10878), False, 'import warnings\n'), ((11109, 11128), 'numpy.linalg.norm', 'np.linalg.norm', (['win'], {}), '(win)\n', (11123, 11128), True, 'import numpy as np\n'), ((13996, 14036), 'numpy.arange', 'np.arange', (['(1)', '(C.shape[-1] - 1)'], {'dtype': 'int'}), '(1, C.shape[-1] - 1, dtype=int)\n', (14005, 14036), True, 'import numpy as np\n'), ((14049, 14151), 'warnings.warn', 'warnings.warn', (['"""DC and Nyquist bins are not defined for lagged-coherence: filled with zeros"""'], {}), "(\n 'DC and Nyquist bins are not defined for lagged-coherence: filled with zeros'\n )\n", (14062, 14151), False, 'import warnings\n'), ((14513, 14532), 'numpy.diag', 'np.diag', (['S2[..., f]'], {}), '(S2[..., f])\n', (14520, 14532), True, 'import numpy as np\n'), ((7102, 7121), 'numpy.ones', 'np.ones', (['n_channels'], {}), '(n_channels)\n', (7109, 7121), True, 'import numpy as np\n'), ((7123, 7142), 'numpy.ones', 'np.ones', (['n_channels'], {}), '(n_channels)\n', (7130, 7142), True, 'import numpy as np\n'), ((7207, 7223), 'numpy.ones', 'np.ones', (['n_times'], {}), '(n_times)\n', (7214, 7223), True, 'import numpy as np\n'), ((7225, 7241), 'numpy.ones', 'np.ones', (['n_times'], {}), '(n_times)\n', (7232, 7241), True, 'import numpy as np\n'), ((14265, 14296), 'numpy.array_equal', 'np.array_equal', (['f_inds_', 'f_inds'], {}), '(f_inds_, f_inds)\n', (14279, 14296), True, 'import numpy as np\n'), ((14314, 14416), 'warnings.warn', 'warnings.warn', (['"""DC and Nyquist bins are not defined for lagged-coherence: filled with zeros"""'], {}), "(\n 'DC and Nyquist bins are not defined for lagged-coherence: filled with zeros'\n )\n", (14327, 14416), False, 'import warnings\n'), ((14782, 14819), 'numpy.fill_diagonal', 'np.fill_diagonal', (['S[..., f].real', '(0.0)'], {}), '(S[..., f].real, 0.0)\n', (14798, 14819), True, 'import numpy as np\n'), ((15901, 15917), 'numpy.linalg.det', 'np.linalg.det', (['X'], {}), '(X)\n', (15914, 15917), True, 'import numpy as np\n'), ((7505, 7523), 'numpy.eye', 'np.eye', (['n_channels'], {}), '(n_channels)\n', (7511, 7523), True, 'import numpy as np\n'), ((7578, 7593), 'numpy.eye', 'np.eye', (['n_times'], {}), '(n_times)\n', (7584, 7593), True, 'import numpy as np\n')]
#!/usr/bin/python from github import collections, functools ''' Decorator that caches a function's return value each time it is called so if it is called later with the same arguments, the cached value is returned, instead of reevaluating the function ''' class Memoized(object): def __init__(self, func): self.func = func self.cache = {} def __call__(self, *args): if not isinstance(args, collections.Hashable): return self.func(*args) if args in self.cache: return self.cache[args] else: value = self.func(*args) self.cache[args] = value return value def __repr__(self): return self.func.__doc__ def __get__(self, obj, objtype): return functools.partial(self.__call__, obj)
[ "github.functools.partial" ]
[((772, 809), 'github.functools.partial', 'functools.partial', (['self.__call__', 'obj'], {}), '(self.__call__, obj)\n', (789, 809), False, 'from github import collections, functools\n')]
from random import randint import numpy as np n = [ 500 ] m = [ n[i] * n[i + 1] for i in range(len(n) - 1) ] k, v1, v2 = 600, 10, 1000 print('%d %d %d 2' % (np.sum(n), np.sum(m), k)) b = 1 for i in range(len(n) - 1): for j in range(0, n[i]): for k in range(0, n[i + 1]): print('%d %d' % (b + j, b + n[i] + k)) b += n[i] for i in n: vx = randint(v1, v1 + v2) for j in range(i): print(' '.join([ str(randint(vx, vx * 2 - 1)) for i in range(k) ])) for i in range(k): print(' '.join([ '0' if i == j else '1' for j in range(k) ]))
[ "numpy.sum", "random.randint" ]
[((371, 391), 'random.randint', 'randint', (['v1', '(v1 + v2)'], {}), '(v1, v1 + v2)\n', (378, 391), False, 'from random import randint\n'), ((159, 168), 'numpy.sum', 'np.sum', (['n'], {}), '(n)\n', (165, 168), True, 'import numpy as np\n'), ((170, 179), 'numpy.sum', 'np.sum', (['m'], {}), '(m)\n', (176, 179), True, 'import numpy as np\n'), ((444, 467), 'random.randint', 'randint', (['vx', '(vx * 2 - 1)'], {}), '(vx, vx * 2 - 1)\n', (451, 467), False, 'from random import randint\n')]
### # Copyright (c) 2002-2004, <NAME> # Copyright (c) 2008-2010, <NAME> # Copyright (c) 2014, <NAME> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions, and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions, and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the author of this software nor the name of # contributors to this software may be used to endorse or promote products # derived from this software without specific prior written consent. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. ### import re import os import sys import json import time import types import string import socket import threading import feedparser import supybot.conf as conf import supybot.utils as utils import supybot.world as world from supybot.commands import * import supybot.utils.minisix as minisix import supybot.ircmsgs as ircmsgs import supybot.ircutils as ircutils import supybot.registry as registry import supybot.callbacks as callbacks from supybot.i18n import PluginInternationalization, internationalizeDocstring _ = PluginInternationalization('RSS') if minisix.PY2: from urllib2 import ProxyHandler else: from urllib.request import ProxyHandler def get_feedName(irc, msg, args, state): if ircutils.isChannel(args[0]): state.errorInvalid('feed name', args[0], 'must not be channel names.') if not registry.isValidRegistryName(args[0]): state.errorInvalid('feed name', args[0], 'Feed names must not include spaces.') state.args.append(callbacks.canonicalName(args.pop(0))) addConverter('feedName', get_feedName) announced_headlines_filename = \ conf.supybot.directories.data.dirize('RSS_announced.flat') def only_one_at_once(f): lock = [False] def newf(*args, **kwargs): if lock[0]: return lock[0] = True try: f(*args, **kwargs) finally: lock[0] = False return newf class InvalidFeedUrl(ValueError): pass class Feed: __slots__ = ('url', 'name', 'data', 'last_update', 'entries', 'etag', 'modified', 'initial', 'lock', 'announced_entries') def __init__(self, name, url, initial, plugin_is_loading=False, announced=None): assert name, name if not url: if not utils.web.httpUrlRe.match(name): raise InvalidFeedUrl(name) url = name self.name = name self.url = url self.initial = initial self.data = None # We don't want to fetch feeds right after the plugin is # loaded (the bot could be starting, and thus already busy) self.last_update = time.time() if plugin_is_loading else 0 self.entries = [] self.etag = None self.modified = None self.lock = threading.Lock() self.announced_entries = announced or \ utils.structures.TruncatableSet() def __repr__(self): return 'Feed(%r, %r, %b, <bool>, %r)' % \ (self.name, self.url, self.initial, self.announced_entries) def get_command(self, plugin): docstring = format(_("""[<number of headlines>] Reports the titles for %s at the RSS feed %u. If <number of headlines> is given, returns only that many headlines. RSS feeds are only looked up every supybot.plugins.RSS.waitPeriod seconds, which defaults to 1800 (30 minutes) since that's what most websites prefer."""), self.name, self.url) def f(self2, irc, msg, args): args.insert(0, self.name) self2.rss(irc, msg, args) f = utils.python.changeFunctionName(f, self.name, docstring) f = types.MethodType(f, plugin) return f _sort_parameters = { 'oldestFirst': (('published_parsed', 'updated_parsed'), False), 'newestFirst': (('published_parsed', 'updated_parsed'), True), 'outdatedFirst': (('updated_parsed', 'published_parsed'), False), 'updatedFirst': (('updated_parsed', 'published_parsed'), True), } def _sort_arguments(order): (fields, reverse) = _sort_parameters[order] def key(entry): for field in fields: if field in entry: return entry[field] raise KeyError('No date field in entry.') return (key, reverse) def sort_feed_items(items, order): """Return feed items, sorted according to sortFeedItems.""" if order == 'asInFeed': return items (key, reverse) = _sort_arguments(order) try: sitems = sorted(items, key=key, reverse=reverse) except KeyError: # feedparser normalizes required timestamp fields in ATOM and RSS # to the "published"/"updated" fields. Feeds missing it are unsortable by date. return items return sitems def load_announces_db(fd): return dict((name, utils.structures.TruncatableSet(entries)) for (name, entries) in json.load(fd).items()) def save_announces_db(db, fd): json.dump(dict((name, list(entries)) for (name, entries) in db), fd) class RSS(callbacks.Plugin): """This plugin is useful both for announcing updates to RSS feeds in a channel, and for retrieving the headlines of RSS feeds via command. Use the "add" command to add feeds to this plugin, and use the "announce" command to determine what feeds should be announced in a given channel.""" threaded = True def __init__(self, irc): self.__parent = super(RSS, self) self.__parent.__init__(irc) # Scheme: {name: url} self.feed_names = callbacks.CanonicalNameDict() # Scheme: {url: feed} self.feeds = {} if os.path.isfile(announced_headlines_filename): with open(announced_headlines_filename) as fd: announced = load_announces_db(fd) else: announced = {} for name in self.registryValue('feeds'): self.assert_feed_does_not_exist(name) self.register_feed_config(name) try: url = self.registryValue(registry.join(['feeds', name])) except registry.NonExistentRegistryEntry: self.log.warning('%s is not a registered feed, removing.',name) continue try: self.register_feed(name, url, True, True, announced.get(name, [])) except InvalidFeedUrl: self.log.error('%s is not a valid feed, removing.', name) continue world.flushers.append(self._flush) def die(self): self._flush() world.flushers.remove(self._flush) self.__parent.die() def _flush(self): l = [(f.name, f.announced_entries) for f in self.feeds.values()] with utils.file.AtomicFile(announced_headlines_filename, 'w', backupDir='/dev/null') as fd: save_announces_db(l, fd) ################## # Feed registering def assert_feed_does_not_exist(self, name, url=None): if self.isCommandMethod(name): s = format(_('I already have a command in this plugin named %s.'), name) raise callbacks.Error(s) if url: feed = self.feeds.get(url) if feed and feed.name != feed.url: s = format(_('I already have a feed with that URL named %s.'), feed.name) raise callbacks.Error(s) def register_feed_config(self, name, url=''): self.registryValue('feeds').add(name) group = self.registryValue('feeds', value=False) conf.registerGlobalValue(group, name, registry.String(url, '')) feed_group = conf.registerGroup(group, name) conf.registerChannelValue(feed_group, 'format', registry.String('', _("""Feed-specific format. Defaults to supybot.plugins.RSS.format if empty."""))) conf.registerChannelValue(feed_group, 'announceFormat', registry.String('', _("""Feed-specific announce format. Defaults to supybot.plugins.RSS.announceFormat if empty."""))) conf.registerGlobalValue(feed_group, 'waitPeriod', registry.NonNegativeInteger(0, _("""If set to a non-zero value, overrides supybot.plugins.RSS.waitPeriod for this particular feed."""))) def register_feed(self, name, url, initial, plugin_is_loading, announced=[]): self.feed_names[name] = url self.feeds[url] = Feed(name, url, initial, plugin_is_loading, announced) def remove_feed(self, feed): del self.feed_names[feed.name] del self.feeds[feed.url] conf.supybot.plugins.RSS.feeds().remove(feed.name) conf.supybot.plugins.RSS.feeds.unregister(feed.name) ################## # Methods handling def isCommandMethod(self, name): if not self.__parent.isCommandMethod(name): return bool(self.get_feed(name)) else: return True def listCommands(self): return self.__parent.listCommands(self.feed_names.keys()) def getCommandMethod(self, command): try: return self.__parent.getCommandMethod(command) except AttributeError: return self.get_feed(command[0]).get_command(self) def __call__(self, irc, msg): self.__parent.__call__(irc, msg) threading.Thread(target=self.update_feeds).start() ################## # Status accessors def get_feed(self, name): return self.feeds.get(self.feed_names.get(name, name), None) def is_expired(self, feed): assert feed period = self.registryValue('waitPeriod') if feed.name != feed.url: # Named feed specific_period = self.registryValue('feeds.%s.waitPeriod' % feed.name) if specific_period: period = specific_period event_horizon = time.time() - period return feed.last_update < event_horizon ############### # Feed fetching def update_feed(self, feed): handlers = [] if utils.web.proxy(): handlers.append(ProxyHandler( {'http': utils.force(utils.web.proxy())})) handlers.append(ProxyHandler( {'https': utils.force(utils.web.proxy())})) with feed.lock: d = feedparser.parse(feed.url, etag=feed.etag, modified=feed.modified, handlers=handlers) if 'status' not in d or d.status != 304: # Not modified if 'etag' in d: feed.etag = d.etag if 'modified' in d: feed.modified = d.modified feed.data = d.feed feed.entries = d.entries feed.last_update = time.time() (initial, feed.initial) = (feed.initial, False) self.announce_feed(feed, initial) def update_feed_in_thread(self, feed): feed.last_update = time.time() t = world.SupyThread(target=self.update_feed, name=format('Fetching feed %u', feed.url), args=(feed,)) t.setDaemon(True) t.start() def update_feed_if_needed(self, feed): if self.is_expired(feed): self.update_feed(feed) @only_one_at_once def update_feeds(self): announced_feeds = set() for irc in world.ircs: for channel in irc.state.channels: announced_feeds |= self.registryValue('announce', channel) for name in announced_feeds: feed = self.get_feed(name) if not feed: self.log.warning('Feed %s is announced but does not exist.', name) continue self.update_feed_if_needed(feed) def get_new_entries(self, feed): # http://validator.w3.org/feed/docs/rss2.html#hrelementsOfLtitemgt get_id = lambda entry: entry.id if hasattr(entry, 'id') else ( entry.title if hasattr(entry, 'title') else entry.description) with feed.lock: entries = feed.entries new_entries = [entry for entry in entries if get_id(entry) not in feed.announced_entries] if not new_entries: return [] feed.announced_entries |= set(get_id(entry) for entry in new_entries) # We keep a little more because we don't want to re-announce # oldest entries if one of the newest gets removed. feed.announced_entries.truncate(10*len(entries)) return new_entries def announce_feed(self, feed, initial): new_entries = self.get_new_entries(feed) order = self.registryValue('sortFeedItems') new_entries = sort_feed_items(new_entries, order) for irc in world.ircs: for channel in irc.state.channels: if feed.name not in self.registryValue('announce', channel): continue if initial: n = self.registryValue('initialAnnounceHeadlines', channel) if n: announced_entries = new_entries[-n:] else: announced_entries = [] else: announced_entries = new_entries for entry in announced_entries: self.announce_entry(irc, channel, feed, entry) ################# # Entry rendering def should_send_entry(self, channel, entry): whitelist = self.registryValue('keywordWhitelist', channel) blacklist = self.registryValue('keywordBlacklist', channel) # fix shadowing by "from supybot.commands import *" try: all = __builtins__.all any = __builtins__.any except AttributeError: all = __builtins__['all'] any = __builtins__['any'] if whitelist: if all(kw not in entry.title and kw not in entry.description for kw in whitelist): return False if blacklist: if any(kw in entry.title or kw in entry.description for kw in blacklist): return False return True _normalize_entry = utils.str.multipleReplacer( {'\r': ' ', '\n': ' ', '\x00': ''}) def format_entry(self, channel, feed, entry, is_announce): key_name = 'announceFormat' if is_announce else 'format' if feed.name in self.registryValue('feeds'): specific_key_name = registry.join(['feeds', feed.name, key_name]) template = self.registryValue(specific_key_name, channel) or \ self.registryValue(key_name, channel) else: template = self.registryValue(key_name, channel) date = entry.get('published_parsed') date = utils.str.timestamp(date) s = string.Template(template).substitute( entry, feed_name=feed.name, date=date) return self._normalize_entry(s) def announce_entry(self, irc, channel, feed, entry): if self.should_send_entry(channel, entry): s = self.format_entry(channel, feed, entry, True) if self.registryValue('notice', channel): m = ircmsgs.notice(channel, s) else: m = ircmsgs.privmsg(channel, s) irc.queueMsg(m) ########## # Commands @internationalizeDocstring def add(self, irc, msg, args, name, url): """<name> <url> Adds a command to this plugin that will look up the RSS feed at the given URL. """ self.assert_feed_does_not_exist(name, url) self.register_feed_config(name, url) self.register_feed(name, url, True, False) irc.replySuccess() add = wrap(add, ['feedName', 'url']) @internationalizeDocstring def remove(self, irc, msg, args, name): """<name> Removes the command for looking up RSS feeds at <name> from this plugin. """ feed = self.get_feed(name) if not feed: irc.error(_('That\'s not a valid RSS feed command name.')) return self.remove_feed(feed) irc.replySuccess() remove = wrap(remove, ['feedName']) class announce(callbacks.Commands): @internationalizeDocstring def list(self, irc, msg, args, channel): """[<channel>] Returns the list of feeds announced in <channel>. <channel> is only necessary if the message isn't sent in the channel itself. """ announce = conf.supybot.plugins.RSS.announce feeds = format('%L', list(announce.get(channel)())) irc.reply(feeds or _('I am currently not announcing any feeds.')) list = wrap(list, ['channel',]) @internationalizeDocstring def add(self, irc, msg, args, channel, feeds): """[<channel>] <name|url> [<name|url> ...] Adds the list of feeds to the current list of announced feeds in <channel>. Valid feeds include the names of registered feeds as well as URLs for RSS feeds. <channel> is only necessary if the message isn't sent in the channel itself. """ plugin = irc.getCallback('RSS') invalid_feeds = [x for x in feeds if not plugin.get_feed(x) and not utils.web.urlRe.match(x)] if invalid_feeds: irc.error(format(_('These feeds are unknown: %L'), invalid_feeds), Raise=True) announce = conf.supybot.plugins.RSS.announce S = announce.get(channel)() for name in feeds: S.add(name) announce.get(channel).setValue(S) irc.replySuccess() for name in feeds: feed = plugin.get_feed(name) if not feed: plugin.register_feed_config(name, name) plugin.register_feed(name, name, True, False) feed = plugin.get_feed(name) plugin.announce_feed(feed, True) add = wrap(add, [('checkChannelCapability', 'op'), many(first('url', 'feedName'))]) @internationalizeDocstring def remove(self, irc, msg, args, channel, feeds): """[<channel>] <name|url> [<name|url> ...] Removes the list of feeds from the current list of announced feeds in <channel>. Valid feeds include the names of registered feeds as well as URLs for RSS feeds. <channel> is only necessary if the message isn't sent in the channel itself. """ announce = conf.supybot.plugins.RSS.announce S = announce.get(channel)() for feed in feeds: S.discard(feed) announce.get(channel).setValue(S) irc.replySuccess() remove = wrap(remove, [('checkChannelCapability', 'op'), many(first('url', 'feedName'))]) @internationalizeDocstring def rss(self, irc, msg, args, url, n): """<name|url> [<number of headlines>] Gets the title components of the given RSS feed. If <number of headlines> is given, return only that many headlines. """ self.log.debug('Fetching %u', url) feed = self.get_feed(url) if not feed: feed = Feed(url, url, True) if irc.isChannel(msg.args[0]): channel = msg.args[0] else: channel = None self.update_feed_if_needed(feed) entries = feed.entries if not entries: irc.error(_('Couldn\'t get RSS feed.')) return n = n or self.registryValue('defaultNumberOfHeadlines', channel) entries = list(filter(lambda e:self.should_send_entry(channel, e), feed.entries)) entries = entries[:n] headlines = map(lambda e:self.format_entry(channel, feed, e, False), entries) sep = self.registryValue('headlineSeparator', channel) irc.replies(headlines, joiner=sep) rss = wrap(rss, [first('url', 'feedName'), additional('int')]) @internationalizeDocstring def info(self, irc, msg, args, url): """<url|feed> Returns information from the given RSS feed, namely the title, URL, description, and last update date, if available. """ try: url = self.registryValue('feeds.%s' % url) except registry.NonExistentRegistryEntry: pass feed = self.get_feed(url) if not feed: feed = Feed(url, url, True) self.update_feed_if_needed(feed) info = feed.data if not info: irc.error(_('I couldn\'t retrieve that RSS feed.')) return # check the 'modified_parsed' key, if it's there, convert it here first if 'modified' in info: seconds = time.mktime(info['modified_parsed']) now = time.mktime(time.gmtime()) when = utils.timeElapsed(now - seconds) + ' ago' else: when = _('time unavailable') title = info.get('title', _('unavailable')) desc = info.get('description', _('unavailable')) link = info.get('link', _('unavailable')) # The rest of the entries are all available in the channel key response = format(_('Title: %s; URL: %u; ' 'Description: %s; Last updated: %s.'), title, link, desc, when) irc.reply(utils.str.normalizeWhitespace(response)) info = wrap(info, [first('url', 'feedName')]) RSS = internationalizeDocstring(RSS) Class = RSS # vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
[ "supybot.registry.isValidRegistryName", "supybot.utils.str.multipleReplacer", "supybot.utils.file.AtomicFile", "supybot.registry.join", "supybot.world.flushers.remove", "supybot.utils.str.timestamp", "types.MethodType", "supybot.callbacks.CanonicalNameDict", "supybot.i18n.internationalizeDocstring",...
[((2160, 2193), 'supybot.i18n.PluginInternationalization', 'PluginInternationalization', (['"""RSS"""'], {}), "('RSS')\n", (2186, 2193), False, 'from supybot.i18n import PluginInternationalization, internationalizeDocstring\n'), ((2761, 2819), 'supybot.conf.supybot.directories.data.dirize', 'conf.supybot.directories.data.dirize', (['"""RSS_announced.flat"""'], {}), "('RSS_announced.flat')\n", (2797, 2819), True, 'import supybot.conf as conf\n'), ((23123, 23153), 'supybot.i18n.internationalizeDocstring', 'internationalizeDocstring', (['RSS'], {}), '(RSS)\n', (23148, 23153), False, 'from supybot.i18n import PluginInternationalization, internationalizeDocstring\n'), ((2347, 2374), 'supybot.ircutils.isChannel', 'ircutils.isChannel', (['args[0]'], {}), '(args[0])\n', (2365, 2374), True, 'import supybot.ircutils as ircutils\n'), ((15544, 15606), 'supybot.utils.str.multipleReplacer', 'utils.str.multipleReplacer', (["{'\\r': ' ', '\\n': ' ', '\\x00': ''}"], {}), "({'\\r': ' ', '\\n': ' ', '\\x00': ''})\n", (15570, 15606), True, 'import supybot.utils as utils\n'), ((2466, 2503), 'supybot.registry.isValidRegistryName', 'registry.isValidRegistryName', (['args[0]'], {}), '(args[0])\n', (2494, 2503), True, 'import supybot.registry as registry\n'), ((3935, 3951), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (3949, 3951), False, 'import threading\n'), ((4753, 4809), 'supybot.utils.python.changeFunctionName', 'utils.python.changeFunctionName', (['f', 'self.name', 'docstring'], {}), '(f, self.name, docstring)\n', (4784, 4809), True, 'import supybot.utils as utils\n'), ((4822, 4849), 'types.MethodType', 'types.MethodType', (['f', 'plugin'], {}), '(f, plugin)\n', (4838, 4849), False, 'import types\n'), ((6719, 6748), 'supybot.callbacks.CanonicalNameDict', 'callbacks.CanonicalNameDict', ([], {}), '()\n', (6746, 6748), True, 'import supybot.callbacks as callbacks\n'), ((6814, 6858), 'os.path.isfile', 'os.path.isfile', (['announced_headlines_filename'], {}), '(announced_headlines_filename)\n', (6828, 6858), False, 'import os\n'), ((7644, 7678), 'supybot.world.flushers.append', 'world.flushers.append', (['self._flush'], {}), '(self._flush)\n', (7665, 7678), True, 'import supybot.world as world\n'), ((7729, 7763), 'supybot.world.flushers.remove', 'world.flushers.remove', (['self._flush'], {}), '(self._flush)\n', (7750, 7763), True, 'import supybot.world as world\n'), ((8852, 8883), 'supybot.conf.registerGroup', 'conf.registerGroup', (['group', 'name'], {}), '(group, name)\n', (8870, 8883), True, 'import supybot.conf as conf\n'), ((9934, 9986), 'supybot.conf.supybot.plugins.RSS.feeds.unregister', 'conf.supybot.plugins.RSS.feeds.unregister', (['feed.name'], {}), '(feed.name)\n', (9975, 9986), True, 'import supybot.conf as conf\n'), ((11301, 11318), 'supybot.utils.web.proxy', 'utils.web.proxy', ([], {}), '()\n', (11316, 11318), True, 'import supybot.utils as utils\n'), ((12187, 12198), 'time.time', 'time.time', ([], {}), '()\n', (12196, 12198), False, 'import time\n'), ((16147, 16172), 'supybot.utils.str.timestamp', 'utils.str.timestamp', (['date'], {}), '(date)\n', (16166, 16172), True, 'import supybot.utils as utils\n'), ((3795, 3806), 'time.time', 'time.time', ([], {}), '()\n', (3804, 3806), False, 'import time\n'), ((4016, 4049), 'supybot.utils.structures.TruncatableSet', 'utils.structures.TruncatableSet', ([], {}), '()\n', (4047, 4049), True, 'import supybot.utils as utils\n'), ((7901, 7980), 'supybot.utils.file.AtomicFile', 'utils.file.AtomicFile', (['announced_headlines_filename', '"""w"""'], {'backupDir': '"""/dev/null"""'}), "(announced_headlines_filename, 'w', backupDir='/dev/null')\n", (7922, 7980), True, 'import supybot.utils as utils\n'), ((8329, 8347), 'supybot.callbacks.Error', 'callbacks.Error', (['s'], {}), '(s)\n', (8344, 8347), True, 'import supybot.callbacks as callbacks\n'), ((8805, 8829), 'supybot.registry.String', 'registry.String', (['url', '""""""'], {}), "(url, '')\n", (8820, 8829), True, 'import supybot.registry as registry\n'), ((11124, 11135), 'time.time', 'time.time', ([], {}), '()\n', (11133, 11135), False, 'import time\n'), ((11563, 11653), 'feedparser.parse', 'feedparser.parse', (['feed.url'], {'etag': 'feed.etag', 'modified': 'feed.modified', 'handlers': 'handlers'}), '(feed.url, etag=feed.etag, modified=feed.modified, handlers\n =handlers)\n', (11579, 11653), False, 'import feedparser\n'), ((15833, 15878), 'supybot.registry.join', 'registry.join', (["['feeds', feed.name, key_name]"], {}), "(['feeds', feed.name, key_name])\n", (15846, 15878), True, 'import supybot.registry as registry\n'), ((22410, 22446), 'time.mktime', 'time.mktime', (["info['modified_parsed']"], {}), "(info['modified_parsed'])\n", (22421, 22446), False, 'import time\n'), ((23026, 23065), 'supybot.utils.str.normalizeWhitespace', 'utils.str.normalizeWhitespace', (['response'], {}), '(response)\n', (23055, 23065), True, 'import supybot.utils as utils\n'), ((3432, 3463), 'supybot.utils.web.httpUrlRe.match', 'utils.web.httpUrlRe.match', (['name'], {}), '(name)\n', (3457, 3463), True, 'import supybot.utils as utils\n'), ((5993, 6033), 'supybot.utils.structures.TruncatableSet', 'utils.structures.TruncatableSet', (['entries'], {}), '(entries)\n', (6024, 6033), True, 'import supybot.utils as utils\n'), ((8586, 8604), 'supybot.callbacks.Error', 'callbacks.Error', (['s'], {}), '(s)\n', (8601, 8604), True, 'import supybot.callbacks as callbacks\n'), ((9875, 9907), 'supybot.conf.supybot.plugins.RSS.feeds', 'conf.supybot.plugins.RSS.feeds', ([], {}), '()\n', (9905, 9907), True, 'import supybot.conf as conf\n'), ((10594, 10636), 'threading.Thread', 'threading.Thread', ([], {'target': 'self.update_feeds'}), '(target=self.update_feeds)\n', (10610, 10636), False, 'import threading\n'), ((12002, 12013), 'time.time', 'time.time', ([], {}), '()\n', (12011, 12013), False, 'import time\n'), ((16185, 16210), 'string.Template', 'string.Template', (['template'], {}), '(template)\n', (16200, 16210), False, 'import string\n'), ((16595, 16621), 'supybot.ircmsgs.notice', 'ircmsgs.notice', (['channel', 's'], {}), '(channel, s)\n', (16609, 16621), True, 'import supybot.ircmsgs as ircmsgs\n'), ((16660, 16687), 'supybot.ircmsgs.privmsg', 'ircmsgs.privmsg', (['channel', 's'], {}), '(channel, s)\n', (16675, 16687), True, 'import supybot.ircmsgs as ircmsgs\n'), ((22477, 22490), 'time.gmtime', 'time.gmtime', ([], {}), '()\n', (22488, 22490), False, 'import time\n'), ((22511, 22543), 'supybot.utils.timeElapsed', 'utils.timeElapsed', (['(now - seconds)'], {}), '(now - seconds)\n', (22528, 22543), True, 'import supybot.utils as utils\n'), ((7211, 7241), 'supybot.registry.join', 'registry.join', (["['feeds', name]"], {}), "(['feeds', name])\n", (7224, 7241), True, 'import supybot.registry as registry\n'), ((6074, 6087), 'json.load', 'json.load', (['fd'], {}), '(fd)\n', (6083, 6087), False, 'import json\n'), ((11399, 11416), 'supybot.utils.web.proxy', 'utils.web.proxy', ([], {}), '()\n', (11414, 11416), True, 'import supybot.utils as utils\n'), ((11501, 11518), 'supybot.utils.web.proxy', 'utils.web.proxy', ([], {}), '()\n', (11516, 11518), True, 'import supybot.utils as utils\n'), ((18773, 18797), 'supybot.utils.web.urlRe.match', 'utils.web.urlRe.match', (['x'], {}), '(x)\n', (18794, 18797), True, 'import supybot.utils as utils\n')]
# coding=utf-8 # # catkin_lint # Copyright (c) 2013-2021 <NAME> # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the Fraunhofer organization nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED # TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import unittest import os from tempfile import mkdtemp from shutil import rmtree from time import time from catkin_pkg.package import Package from .helper import patch, requires_module import catkin_lint.environment as environment class DummyDist(object): def get_release_package_xml(self, name): return '''<package format="2"> <name>%s</name> <version>0.0.0</version> <description>Mock package</description> <maintainer email="<EMAIL>"><NAME></maintainer> <license>none</license> </package>''' % name def get_dummy_index_url(): return "http://127.0.0.1:9" def get_dummy_index(url): return None def get_dummy_cached_distribution(index, dist_name, cache=None, allow_lazy_load=False): return DummyDist() class EnvironmentTest(unittest.TestCase): def fake_package(self, name, srcdir): pkgdir = os.path.join(srcdir, name) os.makedirs(pkgdir) with open(os.path.join(pkgdir, "package.xml"), "w") as f: f.write( '<package format="2"><name>%s</name><version>0.0.0</version>' '<description>Mock package</description>' '<maintainer email="<EMAIL>"><NAME></maintainer>' '<license>none</license>' '</package>' % name ) def setUp(self): self.old_environ = os.environ os.environ["ROS_DISTRO"] = "dummy" self.cachedir = mkdtemp() environment._cache_dir = self.cachedir environment._clear_cache() self.ws_srcdir = mkdtemp() self.fake_package("alpha", self.ws_srcdir) self.fake_package("beta", self.ws_srcdir) self.fake_package("gamma", self.ws_srcdir) def tearDown(self): os.environ = self.old_environ rmtree(self.ws_srcdir, ignore_errors=True) rmtree(self.cachedir, ignore_errors=True) def test_invalid_cache(self): """Test cache versioning""" environment._cache = environment.Cache() environment._cache.packages = {"bogus": True} environment._cache.version = environment.CACHE_VERSION - 1 environment._store_cache() environment._cache = None environment._load_cache() self.assertNotIn("bogus", environment._cache.packages) self.assertEqual(environment._cache.version, environment.CACHE_VERSION) def test_local_packages(self): """Test catkin environment for local packages""" env = environment.CatkinEnvironment(use_rosdep=False, use_rosdistro=False, quiet=True) self.assertRaises(KeyError, env.get_manifest, "alpha") env.add_path(self.ws_srcdir) self.assertIsInstance(env.get_manifest("alpha"), Package) rmtree(os.path.join(self.ws_srcdir, "alpha")) self.assertRaises(KeyError, env.get_manifest, "alpha") @requires_module("rosdistro") @patch("rosdistro.get_index_url", get_dummy_index_url) @patch("rosdistro.get_index", get_dummy_index) @patch("rosdistro.get_cached_distribution", get_dummy_cached_distribution) def test_rostdistro_packages(self): """Test catkin environment for rosdistro packages""" now = time() old = now - environment.DOWNLOAD_CACHE_EXPIRY // 2 expired = now - 2 * environment.DOWNLOAD_CACHE_EXPIRY env = environment.CatkinEnvironment(use_rosdep=False, use_rosdistro=True, quiet=True) self.assertIsInstance(env.get_manifest("foo"), Package) self.assertGreaterEqual(environment._cache.packages["dummy"]["foo"].timestamp, now) environment._cache.packages["dummy"]["foo"].timestamp = old self.assertIsInstance(env.get_manifest("foo"), Package) self.assertEqual(environment._cache.packages["dummy"]["foo"].timestamp, old) environment._cache.packages["dummy"]["foo"].timestamp = expired self.assertIsInstance(env.get_manifest("foo"), Package) self.assertGreaterEqual(environment._cache.packages["dummy"]["foo"].timestamp, now)
[ "catkin_lint.environment.CatkinEnvironment", "catkin_lint.environment.Cache", "os.makedirs", "catkin_lint.environment._store_cache", "time.time", "os.path.join", "catkin_lint.environment._load_cache", "tempfile.mkdtemp", "shutil.rmtree", "catkin_lint.environment._clear_cache" ]
[((2468, 2494), 'os.path.join', 'os.path.join', (['srcdir', 'name'], {}), '(srcdir, name)\n', (2480, 2494), False, 'import os\n'), ((2503, 2522), 'os.makedirs', 'os.makedirs', (['pkgdir'], {}), '(pkgdir)\n', (2514, 2522), False, 'import os\n'), ((3032, 3041), 'tempfile.mkdtemp', 'mkdtemp', ([], {}), '()\n', (3039, 3041), False, 'from tempfile import mkdtemp\n'), ((3097, 3123), 'catkin_lint.environment._clear_cache', 'environment._clear_cache', ([], {}), '()\n', (3121, 3123), True, 'import catkin_lint.environment as environment\n'), ((3150, 3159), 'tempfile.mkdtemp', 'mkdtemp', ([], {}), '()\n', (3157, 3159), False, 'from tempfile import mkdtemp\n'), ((3383, 3425), 'shutil.rmtree', 'rmtree', (['self.ws_srcdir'], {'ignore_errors': '(True)'}), '(self.ws_srcdir, ignore_errors=True)\n', (3389, 3425), False, 'from shutil import rmtree\n'), ((3434, 3475), 'shutil.rmtree', 'rmtree', (['self.cachedir'], {'ignore_errors': '(True)'}), '(self.cachedir, ignore_errors=True)\n', (3440, 3475), False, 'from shutil import rmtree\n'), ((3576, 3595), 'catkin_lint.environment.Cache', 'environment.Cache', ([], {}), '()\n', (3593, 3595), True, 'import catkin_lint.environment as environment\n'), ((3725, 3751), 'catkin_lint.environment._store_cache', 'environment._store_cache', ([], {}), '()\n', (3749, 3751), True, 'import catkin_lint.environment as environment\n'), ((3794, 3819), 'catkin_lint.environment._load_cache', 'environment._load_cache', ([], {}), '()\n', (3817, 3819), True, 'import catkin_lint.environment as environment\n'), ((4070, 4155), 'catkin_lint.environment.CatkinEnvironment', 'environment.CatkinEnvironment', ([], {'use_rosdep': '(False)', 'use_rosdistro': '(False)', 'quiet': '(True)'}), '(use_rosdep=False, use_rosdistro=False, quiet=True\n )\n', (4099, 4155), True, 'import catkin_lint.environment as environment\n'), ((4773, 4779), 'time.time', 'time', ([], {}), '()\n', (4777, 4779), False, 'from time import time\n'), ((4915, 4994), 'catkin_lint.environment.CatkinEnvironment', 'environment.CatkinEnvironment', ([], {'use_rosdep': '(False)', 'use_rosdistro': '(True)', 'quiet': '(True)'}), '(use_rosdep=False, use_rosdistro=True, quiet=True)\n', (4944, 4994), True, 'import catkin_lint.environment as environment\n'), ((4332, 4369), 'os.path.join', 'os.path.join', (['self.ws_srcdir', '"""alpha"""'], {}), "(self.ws_srcdir, 'alpha')\n", (4344, 4369), False, 'import os\n'), ((2541, 2576), 'os.path.join', 'os.path.join', (['pkgdir', '"""package.xml"""'], {}), "(pkgdir, 'package.xml')\n", (2553, 2576), False, 'import os\n')]
""" Created by: <NAME>, 12 May 2020 Code to predict rates of adoption using Top_Features identified """ from Build_Model import (format_magpi, format_dataset, split_train_test, create_random_forest, predict_test_data, evaluate_fit, list_top_features, plot_top_features, plot_predicted_actual, plot_tree) from sklearn.ensemble import RandomForestRegressor as RFR from sklearn.model_selection import train_test_split from sklearn.tree import export_graphviz from sklearn.metrics import r2_score from tkinter import filedialog, Tk import matplotlib.pyplot as plt import pandas as pd import numpy as np import argparse import pydot import csv ''' TO ADD: include uncertainty parameters for each factor ''' def main_test_model(): """ Build RFR Inputs """ # constants maxfeatures = float(1/3); # user inputs parser = argparse.ArgumentParser() parser.add_argument('-nd', action='store', dest='num_devices', nargs='*', type=int, required=True, help='number of devices included in dataset') parser.add_argument('-nq', action='store', dest='num_questions', nargs='*', type=int, required=True, help='number of questions per device in dataset') parser.add_argument('-ts', action='store', dest='testsize', nargs='*', type=int, default=0.25, help='proportion of the dataset used to train (build) the model, and proportion to test model? Default = 0.25 test, 0.75 train') parser.add_argument('-t', action='store', dest='trees', nargs='*', type=int, default=1000, help='number of trees in random forest regression. Default = 1000') parser.add_argument('-rs', action='store', dest='randomstate', nargs='*', type=int, default=42, help='random state. Default = 42') parser.add_argument('-c', action='store', dest='color', nargs='*', type=str, default='orchid', help='choose bar colors. Default = orchid. Documentation: https://matplotlib.org/2.0.2/api/colors_api.html') args = parser.parse_args() # input file to build model root = Tk() root.filename = filedialog.askopenfilename(initialdir="C:\Documents", title="Select File", filetype=(("csv", "*.csv"),("all files","*.*"))) filename_build = root.filename root.destroy() # call functions to build model df_build = format_magpi(filename_build,args.num_devices[0],args.num_questions[0]) features_build, labels_build, feature_list_build = format_dataset(df_build) train_features_build, train_labels_build, test_features_build, test_labels_build = split_train_test(features_build, labels_build, args.testsize, args.randomstate) rf = create_random_forest(args.trees, args.randomstate, maxfeatures, train_features_build, train_labels_build) """ Test RFR Inputs """ # input file to test model root = Tk() root.filename = filedialog.askopenfilename(initialdir="C:\Documents", title="Select File", filetype=(("csv", "*.csv"),("all files","*.*"))) filename_test = root.filename root.destroy() df_test = format_magpi(filename_test, args.num_devices[0], args.num_questions[0]) features_test, labels_test, feature_list_test = format_dataset(df_test) predictions = predict_test_data(rf, features_test) errors, accuracy, rsquared = evaluate_fit(predictions, labels_test) importances = list_top_features(rf, feature_list_test) plot_top_features(importances, feature_list_test, args.color) plot_predicted_actual(labels_test, predictions, rsquared) plot_tree(rf, feature_list_test) if __name__ == "__main__": main_test_model()
[ "Build_Model.format_magpi", "Build_Model.plot_tree", "argparse.ArgumentParser", "Build_Model.create_random_forest", "Build_Model.evaluate_fit", "tkinter.Tk", "Build_Model.format_dataset", "Build_Model.split_train_test", "Build_Model.list_top_features", "Build_Model.plot_predicted_actual", "Build...
[((826, 851), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (849, 851), False, 'import argparse\n'), ((1942, 1946), 'tkinter.Tk', 'Tk', ([], {}), '()\n', (1944, 1946), False, 'from tkinter import filedialog, Tk\n'), ((1964, 2094), 'tkinter.filedialog.askopenfilename', 'filedialog.askopenfilename', ([], {'initialdir': '"""C:\\\\Documents"""', 'title': '"""Select File"""', 'filetype': "(('csv', '*.csv'), ('all files', '*.*'))"}), "(initialdir='C:\\\\Documents', title='Select File',\n filetype=(('csv', '*.csv'), ('all files', '*.*')))\n", (1990, 2094), False, 'from tkinter import filedialog, Tk\n'), ((2184, 2256), 'Build_Model.format_magpi', 'format_magpi', (['filename_build', 'args.num_devices[0]', 'args.num_questions[0]'], {}), '(filename_build, args.num_devices[0], args.num_questions[0])\n', (2196, 2256), False, 'from Build_Model import format_magpi, format_dataset, split_train_test, create_random_forest, predict_test_data, evaluate_fit, list_top_features, plot_top_features, plot_predicted_actual, plot_tree\n'), ((2307, 2331), 'Build_Model.format_dataset', 'format_dataset', (['df_build'], {}), '(df_build)\n', (2321, 2331), False, 'from Build_Model import format_magpi, format_dataset, split_train_test, create_random_forest, predict_test_data, evaluate_fit, list_top_features, plot_top_features, plot_predicted_actual, plot_tree\n'), ((2416, 2495), 'Build_Model.split_train_test', 'split_train_test', (['features_build', 'labels_build', 'args.testsize', 'args.randomstate'], {}), '(features_build, labels_build, args.testsize, args.randomstate)\n', (2432, 2495), False, 'from Build_Model import format_magpi, format_dataset, split_train_test, create_random_forest, predict_test_data, evaluate_fit, list_top_features, plot_top_features, plot_predicted_actual, plot_tree\n'), ((2502, 2611), 'Build_Model.create_random_forest', 'create_random_forest', (['args.trees', 'args.randomstate', 'maxfeatures', 'train_features_build', 'train_labels_build'], {}), '(args.trees, args.randomstate, maxfeatures,\n train_features_build, train_labels_build)\n', (2522, 2611), False, 'from Build_Model import format_magpi, format_dataset, split_train_test, create_random_forest, predict_test_data, evaluate_fit, list_top_features, plot_top_features, plot_predicted_actual, plot_tree\n'), ((2672, 2676), 'tkinter.Tk', 'Tk', ([], {}), '()\n', (2674, 2676), False, 'from tkinter import filedialog, Tk\n'), ((2694, 2824), 'tkinter.filedialog.askopenfilename', 'filedialog.askopenfilename', ([], {'initialdir': '"""C:\\\\Documents"""', 'title': '"""Select File"""', 'filetype': "(('csv', '*.csv'), ('all files', '*.*'))"}), "(initialdir='C:\\\\Documents', title='Select File',\n filetype=(('csv', '*.csv'), ('all files', '*.*')))\n", (2720, 2824), False, 'from tkinter import filedialog, Tk\n'), ((2879, 2950), 'Build_Model.format_magpi', 'format_magpi', (['filename_test', 'args.num_devices[0]', 'args.num_questions[0]'], {}), '(filename_test, args.num_devices[0], args.num_questions[0])\n', (2891, 2950), False, 'from Build_Model import format_magpi, format_dataset, split_train_test, create_random_forest, predict_test_data, evaluate_fit, list_top_features, plot_top_features, plot_predicted_actual, plot_tree\n'), ((3000, 3023), 'Build_Model.format_dataset', 'format_dataset', (['df_test'], {}), '(df_test)\n', (3014, 3023), False, 'from Build_Model import format_magpi, format_dataset, split_train_test, create_random_forest, predict_test_data, evaluate_fit, list_top_features, plot_top_features, plot_predicted_actual, plot_tree\n'), ((3039, 3075), 'Build_Model.predict_test_data', 'predict_test_data', (['rf', 'features_test'], {}), '(rf, features_test)\n', (3056, 3075), False, 'from Build_Model import format_magpi, format_dataset, split_train_test, create_random_forest, predict_test_data, evaluate_fit, list_top_features, plot_top_features, plot_predicted_actual, plot_tree\n'), ((3106, 3144), 'Build_Model.evaluate_fit', 'evaluate_fit', (['predictions', 'labels_test'], {}), '(predictions, labels_test)\n', (3118, 3144), False, 'from Build_Model import format_magpi, format_dataset, split_train_test, create_random_forest, predict_test_data, evaluate_fit, list_top_features, plot_top_features, plot_predicted_actual, plot_tree\n'), ((3160, 3200), 'Build_Model.list_top_features', 'list_top_features', (['rf', 'feature_list_test'], {}), '(rf, feature_list_test)\n', (3177, 3200), False, 'from Build_Model import format_magpi, format_dataset, split_train_test, create_random_forest, predict_test_data, evaluate_fit, list_top_features, plot_top_features, plot_predicted_actual, plot_tree\n'), ((3202, 3263), 'Build_Model.plot_top_features', 'plot_top_features', (['importances', 'feature_list_test', 'args.color'], {}), '(importances, feature_list_test, args.color)\n', (3219, 3263), False, 'from Build_Model import format_magpi, format_dataset, split_train_test, create_random_forest, predict_test_data, evaluate_fit, list_top_features, plot_top_features, plot_predicted_actual, plot_tree\n'), ((3265, 3322), 'Build_Model.plot_predicted_actual', 'plot_predicted_actual', (['labels_test', 'predictions', 'rsquared'], {}), '(labels_test, predictions, rsquared)\n', (3286, 3322), False, 'from Build_Model import format_magpi, format_dataset, split_train_test, create_random_forest, predict_test_data, evaluate_fit, list_top_features, plot_top_features, plot_predicted_actual, plot_tree\n'), ((3324, 3356), 'Build_Model.plot_tree', 'plot_tree', (['rf', 'feature_list_test'], {}), '(rf, feature_list_test)\n', (3333, 3356), False, 'from Build_Model import format_magpi, format_dataset, split_train_test, create_random_forest, predict_test_data, evaluate_fit, list_top_features, plot_top_features, plot_predicted_actual, plot_tree\n')]
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import absolute_import, division, print_function, unicode_literals import os from pants.base.build_environment import get_buildroot from pants.base.workunit import WorkUnitLabel from pants.util.dirutil import safe_mkdir_for from pants.contrib.cpp.tasks.cpp_task import CppTask class CppCompile(CppTask): """Compile C++ sources into object files.""" @classmethod def register_options(cls, register): super(CppCompile, cls).register_options(register) register('--cc-options', advanced=True, type=list, default=[], fingerprint=True, help='Append these options to the compiler command line.') register('--cc-extensions', advanced=True, type=list, fingerprint=True, default=['.cc', '.cxx', '.cpp'], help=('The list of extensions to consider when determining if a file is a ' 'C++ source file.')) @classmethod def product_types(cls): return ['objs'] @property def cache_target_dirs(self): return True def execute(self): """Compile all sources in a given target to object files.""" def is_cc(source): _, ext = os.path.splitext(source) return ext in self.get_options().cc_extensions targets = self.context.targets(self.is_cpp) # Compile source files to objects. with self.invalidated(targets, invalidate_dependents=True) as invalidation_check: obj_mapping = self.context.products.get('objs') for vt in invalidation_check.all_vts: for source in vt.target.sources_relative_to_buildroot(): if is_cc(source): if not vt.valid: with self.context.new_workunit(name='cpp-compile', labels=[WorkUnitLabel.MULTITOOL]): # TODO: Parallelise the compilation. # TODO: Only recompile source files that have changed since the # object file was last written. Also use the output from # gcc -M to track dependencies on headers. self._compile(vt.target, vt.results_dir, source) objpath = self._objpath(vt.target, vt.results_dir, source) obj_mapping.add(vt.target, vt.results_dir).append(objpath) def _objpath(self, target, results_dir, source): abs_source_root = os.path.join(get_buildroot(), target.target_base) abs_source = os.path.join(get_buildroot(), source) rel_source = os.path.relpath(abs_source, abs_source_root) root, _ = os.path.splitext(rel_source) obj_name = root + '.o' return os.path.join(results_dir, obj_name) def _compile(self, target, results_dir, source): """Compile given source to an object file.""" obj = self._objpath(target, results_dir, source) safe_mkdir_for(obj) abs_source = os.path.join(get_buildroot(), source) # TODO: include dir should include dependent work dir when headers are copied there. include_dirs = [] for dep in target.dependencies: if self.is_library(dep): include_dirs.extend([os.path.join(get_buildroot(), dep.target_base)]) cmd = [self.cpp_toolchain.compiler] cmd.extend(['-c']) cmd.extend(('-I{0}'.format(i) for i in include_dirs)) cmd.extend(['-o' + obj, abs_source]) cmd.extend(self.get_options().cc_options) # TODO: submit_async_work with self.run_command, [(cmd)] as a Work object. with self.context.new_workunit(name='cpp-compile', labels=[WorkUnitLabel.COMPILER]) as workunit: self.run_command(cmd, workunit) self.context.log.info('Built c++ object: {0}'.format(obj))
[ "os.path.join", "os.path.splitext", "os.path.relpath", "pants.base.build_environment.get_buildroot", "pants.util.dirutil.safe_mkdir_for" ]
[((2537, 2581), 'os.path.relpath', 'os.path.relpath', (['abs_source', 'abs_source_root'], {}), '(abs_source, abs_source_root)\n', (2552, 2581), False, 'import os\n'), ((2596, 2624), 'os.path.splitext', 'os.path.splitext', (['rel_source'], {}), '(rel_source)\n', (2612, 2624), False, 'import os\n'), ((2664, 2699), 'os.path.join', 'os.path.join', (['results_dir', 'obj_name'], {}), '(results_dir, obj_name)\n', (2676, 2699), False, 'import os\n'), ((2859, 2878), 'pants.util.dirutil.safe_mkdir_for', 'safe_mkdir_for', (['obj'], {}), '(obj)\n', (2873, 2878), False, 'from pants.util.dirutil import safe_mkdir_for\n'), ((1284, 1308), 'os.path.splitext', 'os.path.splitext', (['source'], {}), '(source)\n', (1300, 1308), False, 'import os\n'), ((2428, 2443), 'pants.base.build_environment.get_buildroot', 'get_buildroot', ([], {}), '()\n', (2441, 2443), False, 'from pants.base.build_environment import get_buildroot\n'), ((2495, 2510), 'pants.base.build_environment.get_buildroot', 'get_buildroot', ([], {}), '()\n', (2508, 2510), False, 'from pants.base.build_environment import get_buildroot\n'), ((2910, 2925), 'pants.base.build_environment.get_buildroot', 'get_buildroot', ([], {}), '()\n', (2923, 2925), False, 'from pants.base.build_environment import get_buildroot\n'), ((3156, 3171), 'pants.base.build_environment.get_buildroot', 'get_buildroot', ([], {}), '()\n', (3169, 3171), False, 'from pants.base.build_environment import get_buildroot\n')]
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance # with the License. A copy of the License is located at # # http://aws.amazon.com/apache2.0/ # # or in the "LICENSE.txt" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES # OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions and # limitations under the License. from future.moves.collections import OrderedDict from pcluster.config.param_types import ( AdditionalIamPoliciesParam, BoolParam, ClusterSection, ComputeAvailabilityZoneParam, DisableHyperThreadingParam, EBSSettingsParam, EFSSection, ExtraJsonParam, FloatParam, IntParam, JsonParam, MaintainInitialSizeParam, MasterAvailabilityZoneParam, QueueSizeParam, Section, SettingsParam, SharedDirParam, SpotBidPercentageParam, SpotPriceParam, ) from pcluster.config.validators import ( cluster_validator, compute_instance_type_validator, dcv_enabled_validator, disable_hyperthreading_validator, ebs_settings_validator, ec2_ami_validator, ec2_ebs_snapshot_validator, ec2_iam_policies_validator, ec2_iam_role_validator, ec2_instance_type_validator, ec2_key_pair_validator, ec2_placement_group_validator, ec2_security_group_validator, ec2_subnet_id_validator, ec2_volume_validator, ec2_vpc_id_validator, efa_validator, efs_id_validator, efs_validator, fsx_id_validator, fsx_imported_file_chunk_size_validator, fsx_os_support, fsx_storage_capacity_validator, fsx_validator, intel_hpc_validator, kms_key_validator, raid_volume_iops_validator, s3_bucket_validator, scheduler_validator, shared_dir_validator, url_validator, ) from pcluster.constants import CIDR_ALL_IPS # This file contains a definition of all the sections and the parameters configurable by the user # in the configuration file. # For each section you can define: # # - type, the class to use to represent this section (default: Section) # - key, the key used in configuration file that identifies the section type # (e.g [cluster default] -> "cluster" is the key) # - default_label, the label to use for the section when initializing from CFN or from default values. # (e.g [cluster default] -> "default" is the key) # - validator, a function to use to validate the section. # It is called for all the parameters once all of them are initialized. # - cfn_param_mapping, the CFN parameters to use for the to/from_cfn conversion. # it is used for sections that are converted to a single CFN parameter, e.g. RAID, EFS, FSX # - params, a dictionary containing all the parameters available for that section # For each parameter you can define: # # - type the class to use to represent this section (default: Param, a string parameter) # - cfn_param_mapping the CFN parameters to use for the to/from_cfn conversion. # - allowed_values, a list of allowed values or a regex. It is evaluated at parsing time. # - validators, a list of functions to use to validate the param. # It is called for all the parameters once all of them are initialized. # - default, a default value for the internal representation, if not specified the value will be None # - referred_section, it is a special attribute used only for *SettingsParam, # the parameters that refers to other sections in the file (e.g. vpc_settings) # fmt: off # Utility dictionary containing all the common regex used in the section mapping. ALLOWED_VALUES = { "ami_id": r"^ami-[0-9a-z]{8}$|^ami-[0-9a-z]{17}$", "cidr": r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/(0|1[6-9]|2[0-9]|3[0-2])$", "efs_fs_id": r"^fs-[0-9a-z]{8}$|^fs-[0-9a-z]{17}|NONE$", "file_path": r"\/?[\w:]+", "fsx_fs_id": r"^fs-[0-9a-z]{17}|NONE$", "greater_than_25": r"^([0-9]+[0-9]{2}|[3-9][0-9]|2[5-9])$", "security_group_id": r"^sg-[0-9a-z]{8}$|^sg-[0-9a-z]{17}$", "snapshot_id": r"^snap-[0-9a-z]{8}$|^snap-[0-9a-z]{17}$", "subnet_id": r"^subnet-[0-9a-z]{8}$|^subnet-[0-9a-z]{17}$", "volume_id": r"^vol-[0-9a-z]{8}$|^vol-[0-9a-z]{17}$", "volume_types": ["standard", "io1", "gp2", "st1", "sc1"], "vpc_id": r"^vpc-[0-9a-z]{8}$|^vpc-[0-9a-z]{17}$", "deployment_type": ["SCRATCH_1", "SCRATCH_2", "PERSISTENT_1"], "per_unit_storage_throughput": [50, 100, 200], } AWS = { "type": Section, "key": "aws", "params": { "aws_access_key_id": {}, "aws_secret_access_key": {}, "aws_region_name": { "default": "us-east-1", # TODO add regex }, } } GLOBAL = { "type": Section, "key": "global", "params": { "cluster_template": { # TODO This could be a SettingsParam referring to a CLUSTER section "default": "default", }, "update_check": { "type": BoolParam, "default": True, }, "sanity_check": { "type": BoolParam, "default": True, }, } } ALIASES = { "type": Section, "key": "aliases", "params": { "ssh": { "default": "ssh {CFN_USER}@{MASTER_IP} {ARGS}" }, } } SCALING = { "type": Section, "key": "scaling", "default_label": "default", "params": { "scaledown_idletime": { "type": IntParam, "default": 10, "cfn_param_mapping": "ScaleDownIdleTime", } } } VPC = { "type": Section, "key": "vpc", "default_label": "default", "params": { "vpc_id": { "cfn_param_mapping": "VPCId", "allowed_values": ALLOWED_VALUES["vpc_id"], "validators": [ec2_vpc_id_validator], }, "master_subnet_id": { "cfn_param_mapping": "MasterSubnetId", "allowed_values": ALLOWED_VALUES["subnet_id"], "validators": [ec2_subnet_id_validator], }, "ssh_from": { "default": CIDR_ALL_IPS, "allowed_values": ALLOWED_VALUES["cidr"], "cfn_param_mapping": "AccessFrom", }, "additional_sg": { "cfn_param_mapping": "AdditionalSG", "allowed_values": ALLOWED_VALUES["security_group_id"], "validators": [ec2_security_group_validator], }, "compute_subnet_id": { "cfn_param_mapping": "ComputeSubnetId", "allowed_values": ALLOWED_VALUES["subnet_id"], "validators": [ec2_subnet_id_validator], }, "compute_subnet_cidr": { "cfn_param_mapping": "ComputeSubnetCidr", "allowed_values": ALLOWED_VALUES["cidr"], }, "use_public_ips": { "type": BoolParam, "default": True, "cfn_param_mapping": "UsePublicIps", }, "vpc_security_group_id": { "cfn_param_mapping": "VPCSecurityGroupId", "allowed_values": ALLOWED_VALUES["security_group_id"], "validators": [ec2_security_group_validator], }, "master_availability_zone": { # NOTE: this is not exposed as a configuration parameter "type": MasterAvailabilityZoneParam, "cfn_param_mapping": "AvailabilityZone", }, "compute_availability_zone": { # NOTE: this is not exposed as a configuration parameter "type": ComputeAvailabilityZoneParam, } }, } EBS = { "type": Section, "key": "ebs", "default_label": "default", "params": { "shared_dir": { "allowed_values": ALLOWED_VALUES["file_path"], "cfn_param_mapping": "SharedDir", "validators": [shared_dir_validator], }, "ebs_snapshot_id": { "allowed_values": ALLOWED_VALUES["snapshot_id"], "cfn_param_mapping": "EBSSnapshotId", "validators": [ec2_ebs_snapshot_validator], }, "volume_type": { "default": "gp2", "allowed_values": ALLOWED_VALUES["volume_types"], "cfn_param_mapping": "VolumeType", }, "volume_size": { "type": IntParam, "default": 20, "cfn_param_mapping": "VolumeSize", }, "volume_iops": { "type": IntParam, "default": 100, "cfn_param_mapping": "VolumeIOPS", }, "encrypted": { "type": BoolParam, "cfn_param_mapping": "EBSEncryption", "default": False, }, "ebs_kms_key_id": { "cfn_param_mapping": "EBSKMSKeyId", "validators": [kms_key_validator], }, "ebs_volume_id": { "cfn_param_mapping": "EBSVolumeId", "allowed_values": ALLOWED_VALUES["volume_id"], "validators": [ec2_volume_validator], }, }, } EFS = { "key": "efs", "type": EFSSection, "default_label": "default", "validators": [efs_validator], "cfn_param_mapping": "EFSOptions", # All the parameters in the section are converted into a single CFN parameter "params": OrderedDict( # Use OrderedDict because the parameters must respect the order in the CFN parameter [ ("shared_dir", { "allowed_values": ALLOWED_VALUES["file_path"], "validators": [shared_dir_validator], }), ("efs_fs_id", { "allowed_values": ALLOWED_VALUES["efs_fs_id"], "validators": [efs_id_validator], }), ("performance_mode", { "default": "generalPurpose", "allowed_values": ["generalPurpose", "maxIO"], }), ("efs_kms_key_id", { "validators": [kms_key_validator], }), ("provisioned_throughput", { "allowed_values": r"^([0-9]{1,3}|10[0-1][0-9]|102[0-4])(\.[0-9])?$", # 0.0 to 1024.0 "type": FloatParam, }), ("encrypted", { "type": BoolParam, "default": False, }), ("throughput_mode", { "default": "bursting", "allowed_values": ["provisioned", "bursting"], }), ] ) } RAID = { "type": Section, "key": "raid", "default_label": "default", "cfn_param_mapping": "RAIDOptions", # All the parameters in the section are converted into a single CFN parameter "params": OrderedDict( # Use OrderedDict because the parameters must respect the order in the CFN parameter [ ("shared_dir", { "allowed_values": ALLOWED_VALUES["file_path"], "validators": [shared_dir_validator], }), ("raid_type", { "type": IntParam, "allowed_values": [0, 1], }), ("num_of_raid_volumes", { "type": IntParam, "allowed_values": "^[1-5]$", }), ("volume_type", { "default": "gp2", "allowed_values": ALLOWED_VALUES["volume_types"], }), ("volume_size", { "type": IntParam, "default": 20, }), ("volume_iops", { "type": IntParam, "default": 100, "validators": [raid_volume_iops_validator], }), ("encrypted", { "type": BoolParam, "default": False, }), ("ebs_kms_key_id", { "validators": [kms_key_validator], }), ] ) } FSX = { "type": Section, "key": "fsx", "default_label": "default", "validators": [fsx_validator, fsx_storage_capacity_validator], "cfn_param_mapping": "FSXOptions", # All the parameters in the section are converted into a single CFN parameter "params": OrderedDict( # Use OrderedDict because the parameters must respect the order in the CFN parameter [ ("shared_dir", { "allowed_values": ALLOWED_VALUES["file_path"], "validators": [shared_dir_validator], }), ("fsx_fs_id", { "allowed_values": ALLOWED_VALUES["fsx_fs_id"], "validators": [fsx_id_validator], }), ("storage_capacity", { "type": IntParam, }), ("fsx_kms_key_id", { "validators": [kms_key_validator], }), ("imported_file_chunk_size", { "type": IntParam, "validators": [fsx_imported_file_chunk_size_validator] }), ("export_path", { "validators": [s3_bucket_validator], }), ("import_path", { "validators": [s3_bucket_validator], }), ("weekly_maintenance_start_time", { "allowed_values": r"NONE|^[1-7]:([01]\d|2[0-3]):?([0-5]\d)$", }), ("deployment_type", { "allowed_values": ALLOWED_VALUES["deployment_type"], }), ("per_unit_storage_throughput", { "type": IntParam, "allowed_values": ALLOWED_VALUES["per_unit_storage_throughput"], }), ] ) } DCV = { "type": Section, "key": "dcv", "default_label": "default", "cfn_param_mapping": "DCVOptions", # All the parameters in the section are converted into a single CFN parameter "params": OrderedDict( # Use OrderedDict because the parameters must respect the order in the CFN parameter [ ("enable", { "allowed_values": ["master"], "validators": [dcv_enabled_validator], }), ("port", { "type": IntParam, "default": 8443, }), ("access_from", { "default": CIDR_ALL_IPS, "allowed_values": ALLOWED_VALUES["cidr"], }), ] ) } CW_LOG = { "type": Section, "key": "cw_log", "default_label": "default", "cfn_param_mapping": "CWLogOptions", # Stringify params into single CFN parameter "params": OrderedDict([ ("enable", { "type": BoolParam, "default": True, }), ("retention_days", { "type": IntParam, "default": 14, "cfn_param_mapping": "CWLogEventRententionDays", "allowed_values": [ 1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1827, 3653 ] }), ]) } CLUSTER = { "type": ClusterSection, "key": "cluster", "default_label": "default", "validators": [cluster_validator], "params": OrderedDict( [ # OrderedDict due to conditional defaults values ("key_name", { "cfn_param_mapping": "KeyName", "validators": [ec2_key_pair_validator], }), ("base_os", { "default": "alinux", "cfn_param_mapping": "BaseOS", "allowed_values": ["alinux", "alinux2", "ubuntu1604", "ubuntu1804", "centos6", "centos7"], }), ("scheduler", { "default": "sge", "cfn_param_mapping": "Scheduler", "allowed_values": ["awsbatch", "sge", "slurm", "torque"], "validators": [scheduler_validator], }), ("placement_group", { "cfn_param_mapping": "PlacementGroup", "validators": [ec2_placement_group_validator], }), ("placement", { "default": "compute", "cfn_param_mapping": "Placement", "allowed_values": ["cluster", "compute"], }), # Master ("master_instance_type", { "default": "t2.micro", "cfn_param_mapping": "MasterInstanceType", "validators": [ec2_instance_type_validator], }), ("master_root_volume_size", { "type": IntParam, "default": 25, "allowed_values": ALLOWED_VALUES["greater_than_25"], "cfn_param_mapping": "MasterRootVolumeSize", }), # Compute fleet ("compute_instance_type", { "default": lambda section: "optimal" if section and section.get_param_value("scheduler") == "awsbatch" else "t2.micro", "cfn_param_mapping": "ComputeInstanceType", "validators": [compute_instance_type_validator], }), ("compute_root_volume_size", { "type": IntParam, "default": 25, "allowed_values": ALLOWED_VALUES["greater_than_25"], "cfn_param_mapping": "ComputeRootVolumeSize", }), ("initial_queue_size", { "type": QueueSizeParam, "default": 0, "cfn_param_mapping": "DesiredSize", # TODO verify the update case }), ("max_queue_size", { "type": QueueSizeParam, "default": 10, "cfn_param_mapping": "MaxSize", }), ("maintain_initial_size", { "type": MaintainInitialSizeParam, "default": False, "cfn_param_mapping": "MinSize", }), ("min_vcpus", { "type": QueueSizeParam, "default": 0, "cfn_param_mapping": "MinSize", }), ("desired_vcpus", { "type": QueueSizeParam, "default": 4, "cfn_param_mapping": "DesiredSize", }), ("max_vcpus", { "type": QueueSizeParam, "default": 10, "cfn_param_mapping": "MaxSize", }), ("cluster_type", { "default": "ondemand", "allowed_values": ["ondemand", "spot"], "cfn_param_mapping": "ClusterType", }), ("spot_price", { "type": SpotPriceParam, "default": 0, "cfn_param_mapping": "SpotPrice", }), ("spot_bid_percentage", { "type": SpotBidPercentageParam, "default": 0, "cfn_param_mapping": "SpotPrice", "allowed_values": r"^(100|[1-9][0-9]|[0-9])$", # 0 <= value <= 100 }), # Access and networking ("proxy_server", { "cfn_param_mapping": "ProxyServer", }), ("ec2_iam_role", { "cfn_param_mapping": "EC2IAMRoleName", "validators": [ec2_iam_role_validator], # TODO add regex }), ("s3_read_resource", { "cfn_param_mapping": "S3ReadResource", }), ("s3_read_write_resource", { "cfn_param_mapping": "S3ReadWriteResource", }), ( "disable_hyperthreading", { "type": DisableHyperThreadingParam, "default": False, "cfn_param_mapping": "Cores", "validators": [disable_hyperthreading_validator], }, ), # Customization ("template_url", { # TODO add regex "validators": [url_validator], }), ("shared_dir", { "type": SharedDirParam, "allowed_values": ALLOWED_VALUES["file_path"], "cfn_param_mapping": "SharedDir", "default": "/shared", "validators": [shared_dir_validator], }), ("enable_efa", { "allowed_values": ["compute"], "cfn_param_mapping": "EFA", "validators": [efa_validator], }), ("ephemeral_dir", { "allowed_values": ALLOWED_VALUES["file_path"], "default": "/scratch", "cfn_param_mapping": "EphemeralDir", }), ("encrypted_ephemeral", { "default": False, "type": BoolParam, "cfn_param_mapping": "EncryptedEphemeral", }), ("custom_ami", { "cfn_param_mapping": "CustomAMI", "allowed_values": ALLOWED_VALUES["ami_id"], "validators": [ec2_ami_validator], }), ("pre_install", { "cfn_param_mapping": "PreInstallScript", # TODO add regex "validators": [url_validator], }), ("pre_install_args", { "cfn_param_mapping": "PreInstallArgs", }), ("post_install", { "cfn_param_mapping": "PostInstallScript", # TODO add regex "validators": [url_validator], }), ("post_install_args", { "cfn_param_mapping": "PostInstallArgs", }), ("extra_json", { "type": ExtraJsonParam, "cfn_param_mapping": "ExtraJson", }), ("additional_cfn_template", { "cfn_param_mapping": "AdditionalCfnTemplate", # TODO add regex "validators": [url_validator], }), ("tags", { "type": JsonParam, }), ("custom_chef_cookbook", { "cfn_param_mapping": "CustomChefCookbook", # TODO add regex "validators": [url_validator], }), ("custom_awsbatch_template_url", { "cfn_param_mapping": "CustomAWSBatchTemplateURL", # TODO add regex "validators": [url_validator], }), ("enable_intel_hpc_platform", { "default": False, "type": BoolParam, "cfn_param_mapping": "IntelHPCPlatform", "validators": [intel_hpc_validator], }), # Settings ("scaling_settings", { "type": SettingsParam, "default": "default", # set a value to create always the internal structure for the scaling section "referred_section": SCALING, }), ("vpc_settings", { "type": SettingsParam, "default": "default", # set a value to create always the internal structure for the vpc section "referred_section": VPC, }), ("ebs_settings", { "type": EBSSettingsParam, "referred_section": EBS, "validators": [ebs_settings_validator], }), ("efs_settings", { "type": SettingsParam, "referred_section": EFS, }), ("raid_settings", { "type": SettingsParam, "referred_section": RAID, }), ("fsx_settings", { "type": SettingsParam, "referred_section": FSX, "validators": [fsx_os_support], }), ("dcv_settings", { "type": SettingsParam, "referred_section": DCV, }), ("cw_log_settings", { "type": SettingsParam, "referred_section": CW_LOG, }), # Moved from the "Access and Networking" section because its configuration is # dependent on multiple other parameters from within this section. ("additional_iam_policies", { "type": AdditionalIamPoliciesParam, "cfn_param_mapping": "EC2IAMPolicies", "validators": [ec2_iam_policies_validator], }), ] ) } # fmt: on
[ "future.moves.collections.OrderedDict" ]
[((9320, 9998), 'future.moves.collections.OrderedDict', 'OrderedDict', (["[('shared_dir', {'allowed_values': ALLOWED_VALUES['file_path'],\n 'validators': [shared_dir_validator]}), ('efs_fs_id', {'allowed_values':\n ALLOWED_VALUES['efs_fs_id'], 'validators': [efs_id_validator]}), (\n 'performance_mode', {'default': 'generalPurpose', 'allowed_values': [\n 'generalPurpose', 'maxIO']}), ('efs_kms_key_id', {'validators': [\n kms_key_validator]}), ('provisioned_throughput', {'allowed_values':\n '^([0-9]{1,3}|10[0-1][0-9]|102[0-4])(\\\\.[0-9])?$', 'type': FloatParam}),\n ('encrypted', {'type': BoolParam, 'default': False}), (\n 'throughput_mode', {'default': 'bursting', 'allowed_values': [\n 'provisioned', 'bursting']})]"], {}), "([('shared_dir', {'allowed_values': ALLOWED_VALUES['file_path'],\n 'validators': [shared_dir_validator]}), ('efs_fs_id', {'allowed_values':\n ALLOWED_VALUES['efs_fs_id'], 'validators': [efs_id_validator]}), (\n 'performance_mode', {'default': 'generalPurpose', 'allowed_values': [\n 'generalPurpose', 'maxIO']}), ('efs_kms_key_id', {'validators': [\n kms_key_validator]}), ('provisioned_throughput', {'allowed_values':\n '^([0-9]{1,3}|10[0-1][0-9]|102[0-4])(\\\\.[0-9])?$', 'type': FloatParam}),\n ('encrypted', {'type': BoolParam, 'default': False}), (\n 'throughput_mode', {'default': 'bursting', 'allowed_values': [\n 'provisioned', 'bursting']})])\n", (9331, 9998), False, 'from future.moves.collections import OrderedDict\n'), ((10700, 11332), 'future.moves.collections.OrderedDict', 'OrderedDict', (["[('shared_dir', {'allowed_values': ALLOWED_VALUES['file_path'],\n 'validators': [shared_dir_validator]}), ('raid_type', {'type': IntParam,\n 'allowed_values': [0, 1]}), ('num_of_raid_volumes', {'type': IntParam,\n 'allowed_values': '^[1-5]$'}), ('volume_type', {'default': 'gp2',\n 'allowed_values': ALLOWED_VALUES['volume_types']}), ('volume_size', {\n 'type': IntParam, 'default': 20}), ('volume_iops', {'type': IntParam,\n 'default': 100, 'validators': [raid_volume_iops_validator]}), (\n 'encrypted', {'type': BoolParam, 'default': False}), ('ebs_kms_key_id',\n {'validators': [kms_key_validator]})]"], {}), "([('shared_dir', {'allowed_values': ALLOWED_VALUES['file_path'],\n 'validators': [shared_dir_validator]}), ('raid_type', {'type': IntParam,\n 'allowed_values': [0, 1]}), ('num_of_raid_volumes', {'type': IntParam,\n 'allowed_values': '^[1-5]$'}), ('volume_type', {'default': 'gp2',\n 'allowed_values': ALLOWED_VALUES['volume_types']}), ('volume_size', {\n 'type': IntParam, 'default': 20}), ('volume_iops', {'type': IntParam,\n 'default': 100, 'validators': [raid_volume_iops_validator]}), (\n 'encrypted', {'type': BoolParam, 'default': False}), ('ebs_kms_key_id',\n {'validators': [kms_key_validator]})])\n", (10711, 11332), False, 'from future.moves.collections import OrderedDict\n'), ((12164, 13045), 'future.moves.collections.OrderedDict', 'OrderedDict', (["[('shared_dir', {'allowed_values': ALLOWED_VALUES['file_path'],\n 'validators': [shared_dir_validator]}), ('fsx_fs_id', {'allowed_values':\n ALLOWED_VALUES['fsx_fs_id'], 'validators': [fsx_id_validator]}), (\n 'storage_capacity', {'type': IntParam}), ('fsx_kms_key_id', {\n 'validators': [kms_key_validator]}), ('imported_file_chunk_size', {\n 'type': IntParam, 'validators': [fsx_imported_file_chunk_size_validator\n ]}), ('export_path', {'validators': [s3_bucket_validator]}), (\n 'import_path', {'validators': [s3_bucket_validator]}), (\n 'weekly_maintenance_start_time', {'allowed_values':\n 'NONE|^[1-7]:([01]\\\\d|2[0-3]):?([0-5]\\\\d)$'}), ('deployment_type', {\n 'allowed_values': ALLOWED_VALUES['deployment_type']}), (\n 'per_unit_storage_throughput', {'type': IntParam, 'allowed_values':\n ALLOWED_VALUES['per_unit_storage_throughput']})]"], {}), "([('shared_dir', {'allowed_values': ALLOWED_VALUES['file_path'],\n 'validators': [shared_dir_validator]}), ('fsx_fs_id', {'allowed_values':\n ALLOWED_VALUES['fsx_fs_id'], 'validators': [fsx_id_validator]}), (\n 'storage_capacity', {'type': IntParam}), ('fsx_kms_key_id', {\n 'validators': [kms_key_validator]}), ('imported_file_chunk_size', {\n 'type': IntParam, 'validators': [fsx_imported_file_chunk_size_validator\n ]}), ('export_path', {'validators': [s3_bucket_validator]}), (\n 'import_path', {'validators': [s3_bucket_validator]}), (\n 'weekly_maintenance_start_time', {'allowed_values':\n 'NONE|^[1-7]:([01]\\\\d|2[0-3]):?([0-5]\\\\d)$'}), ('deployment_type', {\n 'allowed_values': ALLOWED_VALUES['deployment_type']}), (\n 'per_unit_storage_throughput', {'type': IntParam, 'allowed_values':\n ALLOWED_VALUES['per_unit_storage_throughput']})])\n", (12175, 13045), False, 'from future.moves.collections import OrderedDict\n'), ((13807, 14049), 'future.moves.collections.OrderedDict', 'OrderedDict', (["[('enable', {'allowed_values': ['master'], 'validators': [\n dcv_enabled_validator]}), ('port', {'type': IntParam, 'default': 8443}),\n ('access_from', {'default': CIDR_ALL_IPS, 'allowed_values':\n ALLOWED_VALUES['cidr']})]"], {}), "([('enable', {'allowed_values': ['master'], 'validators': [\n dcv_enabled_validator]}), ('port', {'type': IntParam, 'default': 8443}),\n ('access_from', {'default': CIDR_ALL_IPS, 'allowed_values':\n ALLOWED_VALUES['cidr']})])\n", (13818, 14049), False, 'from future.moves.collections import OrderedDict\n'), ((14514, 14790), 'future.moves.collections.OrderedDict', 'OrderedDict', (["[('enable', {'type': BoolParam, 'default': True}), ('retention_days', {\n 'type': IntParam, 'default': 14, 'cfn_param_mapping':\n 'CWLogEventRententionDays', 'allowed_values': [1, 3, 5, 7, 14, 30, 60, \n 90, 120, 150, 180, 365, 400, 545, 731, 1827, 3653]})]"], {}), "([('enable', {'type': BoolParam, 'default': True}), (\n 'retention_days', {'type': IntParam, 'default': 14, 'cfn_param_mapping':\n 'CWLogEventRententionDays', 'allowed_values': [1, 3, 5, 7, 14, 30, 60, \n 90, 120, 150, 180, 365, 400, 545, 731, 1827, 3653]})])\n", (14525, 14790), False, 'from future.moves.collections import OrderedDict\n')]
#!/usr/bin/env python # Copyright 2019 Xilinx Inc. # # 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. import sys import time import glob from apps.aks.libs import aks def usage(exe): print("[INFO] Usage: ") print("[INFO] ---------------------- ") print("[INFO] ", exe, " <Image Directory Path>") def main(imageDirectory): fileExtension = ('*.jpg', '*.JPEG', '*.png') images = [] for ext in fileExtension: images.extend(glob.glob(imageDirectory + '/' + ext)) kernelDir = "kernel_zoo" graphJson = "graph_zoo/graph_googlenet.json" graphName = "googlenet" sysMan = aks.SysManager() sysMan.loadKernels(kernelDir) sysMan.loadGraphs(graphJson) graph = sysMan.getGraph(graphName) print("[INFO] Starting enqueue... ") print("[INFO] Running", len(images), "images") t0 = time.time() for i, img in enumerate(images): sysMan.enqueueJob(graph, img) sysMan.waitForAllResults() t1 = time.time() print("[INFO] Overall FPS : ", len(images)/(t1-t0)) sysMan.report(graph) if __name__ == "__main__": if (len(sys.argv) != 2): print("[ERROR] Invalid Usage!") usage(sys.argv[0]) else: main(sys.argv[1])
[ "apps.aks.libs.aks.SysManager", "time.time", "glob.glob" ]
[((1089, 1105), 'apps.aks.libs.aks.SysManager', 'aks.SysManager', ([], {}), '()\n', (1103, 1105), False, 'from apps.aks.libs import aks\n'), ((1302, 1313), 'time.time', 'time.time', ([], {}), '()\n', (1311, 1313), False, 'import time\n'), ((1420, 1431), 'time.time', 'time.time', ([], {}), '()\n', (1429, 1431), False, 'import time\n'), ((937, 974), 'glob.glob', 'glob.glob', (["(imageDirectory + '/' + ext)"], {}), "(imageDirectory + '/' + ext)\n", (946, 974), False, 'import glob\n')]
#!/usr/bin/env python3 """ Restore The Combine from a backup stored in the AWS S3 service. Restores The Combine database and backend files from a compressed tarball stored in the AWS S3 service. This script only applies to instances of The Combine running in a Kubernetes cluster. It can restore backups made from instances running under Kubernetes or Docker. This script requires the following environment variables to be set: AWS_ACCESS_KEY_ID The Access Key for the AWS S3 bucket where the backups are stored AWS_SECRET_ACCESS_KEY: The Secret Key (password) for the Access Key above AWS_ACCOUNT: The 12-digit AWS Account number for the S3 bucket AWS_DEFAULT_REGION: The AWS region for the S3 bucket backend_files_subdir sub-directory where The Combine backend stores its local files (relative to the home directory of the user) db_files_subdir sub-directory where the database dump is stored aws_bucket AWS S3 bucket for backups """ import argparse import logging import os from pathlib import Path import re import sys import tarfile import tempfile from typing import List, Tuple from aws_backup import AwsBackup from combine_app import CombineApp import humanfriendly from script_step import ScriptStep def parse_args() -> argparse.Namespace: """Define command line arguments for parser.""" parser = argparse.ArgumentParser( description="Restore TheCombine database and backend files from a file in AWS S3.", formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) parser.add_argument( "--verbose", action="store_true", help="Print intermediate values to aid in debugging" ) parser.add_argument( "--clean", action="store_true", help="Clean out Backend files before restoring from backup" ) parser.add_argument("--file", help="name of file in AWS S3 to be restored.") return parser.parse_args() def aws_strip_bucket(obj_name: str) -> str: """Strip the bucket name from the beginning of the supplied object name.""" match = re.match(r"^[^/]+/(.*)", obj_name) if match is not None: return match.group(1) return obj_name def main() -> None: """Restore TheCombine from a backup stored in the AWS S3 service.""" args = parse_args() if args.verbose: logging.basicConfig(format="%(levelname)s:%(message)s", level=logging.INFO) else: logging.basicConfig(format="%(levelname)s:%(message)s", level=logging.WARNING) combine = CombineApp() aws = AwsBackup(bucket=os.environ["aws_bucket"]) step = ScriptStep() step.print("Prepare for the restore.") with tempfile.TemporaryDirectory() as restore_dir: restore_file = "combine-backup.tar.gz" if args.file: backup = args.file else: # Get the list of backups backup_list_output = aws.list().stdout.strip().split("\n") if len(backup_list_output) == 0: print(f"No backups available from {os.environ['aws_bucket']}") sys.exit(0) # Convert the list of backups to a more useful structure aws_backup_list: List[Tuple[str, str]] = [] for backup_row in backup_list_output: backup_components = backup_row.split() aws_backup_list.append( ( humanfriendly.format_size(int(backup_components[2])), aws_strip_bucket(backup_components[3]), ) ) # Print out the list of backups to choose from. In the process, # update each line in the backup list to be the AWS S3 object name # and its (human-friendly) size. print("Backup List:") for i, backup_entry in enumerate(aws_backup_list): print(f"{i+1}: {backup_entry[1]} ({backup_entry[0]})") backup_num = int( input("Enter the number of the backup you would like to restore (0 = None):") ) if backup_num == 0: print("No backup selected. Exiting.") sys.exit(0) backup = aws_backup_list[backup_num - 1][1] step.print(f"Fetch the selected backup, {backup}.") aws.pull(backup, Path(restore_dir) / restore_file) step.print("Unpack the backup.") os.chdir(restore_dir) with tarfile.open(restore_file, "r:gz") as tar: tar.extractall() step.print("Restore the database.") db_pod = combine.get_pod_id(CombineApp.Component.Database) if not db_pod: print("Cannot find the database container.", file=sys.stderr) sys.exit(1) combine.kubectl( [ "cp", os.environ["db_files_subdir"], f"{db_pod}:/", ] ) combine.exec( db_pod, [ "mongorestore", "--drop", "--gzip", "--quiet", ], ) combine.exec( db_pod, [ "rm", "-rf", os.environ["db_files_subdir"], ], ) step.print("Copy the backend files.") backend_pod = combine.get_pod_id(CombineApp.Component.Backend) if not backend_pod: print("Cannot find the backend container.", file=sys.stderr) sys.exit(1) # if --clean option was used, delete the existing backend files if args.clean: # we run the rm command inside a bash shell so that the shell will do wildcard # expansion combine.exec( backend_pod, [ "/bin/bash", "-c", f"rm -rf /home/app/{os.environ['backend_files_subdir']}/*", ], ) combine.kubectl( ["cp", os.environ["backend_files_subdir"], f"{backend_pod}:/home/app", "--no-preserve"] ) if __name__ == "__main__": main()
[ "combine_app.CombineApp", "logging.basicConfig", "tempfile.TemporaryDirectory", "tarfile.open", "argparse.ArgumentParser", "script_step.ScriptStep", "pathlib.Path", "re.match", "os.chdir", "aws_backup.AwsBackup", "sys.exit" ]
[((1452, 1624), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Restore TheCombine database and backend files from a file in AWS S3."""', 'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), "(description=\n 'Restore TheCombine database and backend files from a file in AWS S3.',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n", (1475, 1624), False, 'import argparse\n'), ((2146, 2179), 're.match', 're.match', (['"""^[^/]+/(.*)"""', 'obj_name'], {}), "('^[^/]+/(.*)', obj_name)\n", (2154, 2179), False, 'import re\n'), ((2592, 2604), 'combine_app.CombineApp', 'CombineApp', ([], {}), '()\n', (2602, 2604), False, 'from combine_app import CombineApp\n'), ((2615, 2657), 'aws_backup.AwsBackup', 'AwsBackup', ([], {'bucket': "os.environ['aws_bucket']"}), "(bucket=os.environ['aws_bucket'])\n", (2624, 2657), False, 'from aws_backup import AwsBackup\n'), ((2669, 2681), 'script_step.ScriptStep', 'ScriptStep', ([], {}), '()\n', (2679, 2681), False, 'from script_step import ScriptStep\n'), ((2405, 2480), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(levelname)s:%(message)s"""', 'level': 'logging.INFO'}), "(format='%(levelname)s:%(message)s', level=logging.INFO)\n", (2424, 2480), False, 'import logging\n'), ((2499, 2577), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(levelname)s:%(message)s"""', 'level': 'logging.WARNING'}), "(format='%(levelname)s:%(message)s', level=logging.WARNING)\n", (2518, 2577), False, 'import logging\n'), ((2735, 2764), 'tempfile.TemporaryDirectory', 'tempfile.TemporaryDirectory', ([], {}), '()\n', (2762, 2764), False, 'import tempfile\n'), ((4484, 4505), 'os.chdir', 'os.chdir', (['restore_dir'], {}), '(restore_dir)\n', (4492, 4505), False, 'import os\n'), ((4519, 4553), 'tarfile.open', 'tarfile.open', (['restore_file', '"""r:gz"""'], {}), "(restore_file, 'r:gz')\n", (4531, 4553), False, 'import tarfile\n'), ((4812, 4823), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (4820, 4823), False, 'import sys\n'), ((5584, 5595), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (5592, 5595), False, 'import sys\n'), ((3146, 3157), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (3154, 3157), False, 'import sys\n'), ((4245, 4256), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (4253, 4256), False, 'import sys\n'), ((4400, 4417), 'pathlib.Path', 'Path', (['restore_dir'], {}), '(restore_dir)\n', (4404, 4417), False, 'from pathlib import Path\n')]
""" Description taken from official website: https://datasets.kensho.com/datasets/spgispeech SPGISpeech consists of 5,000 hours of recorded company earnings calls and their respective transcriptions. The original calls were split into slices ranging from 5 to 15 seconds in length to allow easy training for speech recognition systems. Calls represent a broad cross-section of international business English; SPGISpeech contains approximately 50,000 speakers, one of the largest numbers of any speech corpus, and offers a variety of L1 and L2 English accents. The format of each WAV file is single channel, 16kHz, 16 bit audio. Transcription text represents the output of several stages of manual post-processing. As such, the text contains polished English orthography following a detailed style guide, including proper casing, punctuation, and denormalized non-standard words such as numbers and acronyms, making SPGISpeech suited for training fully formatted end-to-end models. Official reference: <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., Balam, J., <NAME>., <NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (2021). SPGISpeech: 5, 000 hours of transcribed financial audio for fully formatted end-to-end speech recognition. ArXiv, abs/2104.02014. ArXiv link: https://arxiv.org/abs/2104.02014 """ import logging import string from pathlib import Path from typing import Dict, Union from tqdm.auto import tqdm from lhotse.audio import Recording, RecordingSet from lhotse.parallel import parallel_map from lhotse.recipes.utils import manifests_exist, read_manifests_if_cached from lhotse.supervision import SupervisionSet, SupervisionSegment from lhotse.utils import Pathlike, Seconds def download_spgispeech( target_dir: Pathlike = ".", ) -> None: """ Download and untar the dataset. NOTE: This function just returns with a message since SPGISpeech is not available for direct download. :param target_dir: Pathlike, the path of the dir to storage the dataset. """ logging.info( "SPGISpeech is not available for direct download. Please fill out the form at" " https://datasets.kensho.com/datasets/spgispeech to download the corpus." ) def normalize(text: str) -> str: # Remove all punctuation text = text.translate(str.maketrans("", "", string.punctuation)) # Convert all upper case to lower case text = text.lower() return text def prepare_spgispeech( corpus_dir: Pathlike, output_dir: Pathlike, normalize_text: bool = True, num_jobs: int = 1, ) -> Dict[str, Dict[str, Union[RecordingSet, SupervisionSet]]]: """ Returns the manifests which consist of the Recordings and Supervisions. When all the manifests are available in the ``output_dir``, it will simply read and return them. :param corpus_dir: Pathlike, the path of the data dir. :param output_dir: Pathlike, the path where to write the manifests. :param normalize_text: Bool, if True, normalize the text (similar to ESPNet recipe). :param num_jobs: int, the number of jobs to use for parallel processing. :return: a Dict whose key is the dataset part, and the value is Dicts with the keys 'audio' and 'supervisions'. .. note:: Unlike other recipes, output_dir is not Optional here because we write the manifests to the output directory while processing to avoid OOM issues, since it is a large dataset. .. caution:: The `normalize_text` option removes all punctuation and converts all upper case to lower case. This includes removing possibly important punctuations such as dashes and apostrophes. """ corpus_dir = Path(corpus_dir) assert corpus_dir.is_dir(), f"No such directory: {corpus_dir}" audio_dir = ( corpus_dir if (corpus_dir / "train").is_dir() else corpus_dir / "spgispeech" ) dataset_parts = ["train", "val"] manifests = {} output_dir = Path(output_dir) output_dir.mkdir(parents=True, exist_ok=True) # Maybe the manifests already exist: we can read them and save a bit of preparation time. manifests = read_manifests_if_cached( dataset_parts=dataset_parts, output_dir=output_dir, prefix="spgispeech", suffix="jsonl.gz", lazy=True, ) for part in dataset_parts: logging.info(f"Processing SPGISpeech subset: {part}") if manifests_exist( part=part, output_dir=output_dir, prefix="spgispeech", suffix="jsonl.gz" ): logging.info(f"SPGISpeech subset: {part} already prepared - skipping.") continue # Read the recordings and write them into manifest. We additionally store the # duration of the recordings in a dict which will be used later to create the # supervisions. global audio_read_worker durations = {} def audio_read_worker(p: Path) -> Recording: r = Recording.from_file(p, recording_id=f"{p.parent.stem}_{p.stem}") durations[r.id] = r.duration return r with RecordingSet.open_writer( output_dir / f"spgispeech_recordings_{part}.jsonl.gz" ) as rec_writer: for recording in tqdm( parallel_map( audio_read_worker, (audio_dir / part).rglob("*.wav"), num_jobs=num_jobs, ), desc="Processing SPGISpeech recordings", ): rec_writer.write(recording) # Read supervisions and write them to manifest with SupervisionSet.open_writer( output_dir / f"spgispeech_supervisions_{part}.jsonl.gz" ) as sup_writer, open(corpus_dir / f"{part}.csv", "r") as f: # Skip the header next(f) for line in tqdm(f, desc="Processing utterances"): parts = line.strip().split("|") # 07a785e9237c389c1354bb60abca42d5/1.wav -> 07a785e9237c389c1354bb60abca42d5_1 recording_id = parts[0].replace("/", "_").replace(".wav", "") text = parts[2] if normalize_text: text = normalize(text) spkid = recording_id.split("_")[0] segment = SupervisionSegment( id=recording_id, recording_id=recording_id, text=text, speaker=spkid, start=0, duration=durations[recording_id], language="English", ) sup_writer.write(segment) manifests[part] = { "recordings": RecordingSet.from_jsonl_lazy(rec_writer.path), "supervisions": SupervisionSet.from_jsonl_lazy(sup_writer.path), } return manifests
[ "lhotse.supervision.SupervisionSegment", "lhotse.recipes.utils.manifests_exist", "lhotse.audio.RecordingSet.open_writer", "pathlib.Path", "lhotse.audio.Recording.from_file", "lhotse.audio.RecordingSet.from_jsonl_lazy", "lhotse.recipes.utils.read_manifests_if_cached", "lhotse.supervision.SupervisionSet...
[((2027, 2201), 'logging.info', 'logging.info', (['"""SPGISpeech is not available for direct download. Please fill out the form at https://datasets.kensho.com/datasets/spgispeech to download the corpus."""'], {}), "(\n 'SPGISpeech is not available for direct download. Please fill out the form at https://datasets.kensho.com/datasets/spgispeech to download the corpus.'\n )\n", (2039, 2201), False, 'import logging\n'), ((3678, 3694), 'pathlib.Path', 'Path', (['corpus_dir'], {}), '(corpus_dir)\n', (3682, 3694), False, 'from pathlib import Path\n'), ((3947, 3963), 'pathlib.Path', 'Path', (['output_dir'], {}), '(output_dir)\n', (3951, 3963), False, 'from pathlib import Path\n'), ((4124, 4255), 'lhotse.recipes.utils.read_manifests_if_cached', 'read_manifests_if_cached', ([], {'dataset_parts': 'dataset_parts', 'output_dir': 'output_dir', 'prefix': '"""spgispeech"""', 'suffix': '"""jsonl.gz"""', 'lazy': '(True)'}), "(dataset_parts=dataset_parts, output_dir=output_dir,\n prefix='spgispeech', suffix='jsonl.gz', lazy=True)\n", (4148, 4255), False, 'from lhotse.recipes.utils import manifests_exist, read_manifests_if_cached\n'), ((4339, 4392), 'logging.info', 'logging.info', (['f"""Processing SPGISpeech subset: {part}"""'], {}), "(f'Processing SPGISpeech subset: {part}')\n", (4351, 4392), False, 'import logging\n'), ((4404, 4497), 'lhotse.recipes.utils.manifests_exist', 'manifests_exist', ([], {'part': 'part', 'output_dir': 'output_dir', 'prefix': '"""spgispeech"""', 'suffix': '"""jsonl.gz"""'}), "(part=part, output_dir=output_dir, prefix='spgispeech',\n suffix='jsonl.gz')\n", (4419, 4497), False, 'from lhotse.recipes.utils import manifests_exist, read_manifests_if_cached\n'), ((4529, 4600), 'logging.info', 'logging.info', (['f"""SPGISpeech subset: {part} already prepared - skipping."""'], {}), "(f'SPGISpeech subset: {part} already prepared - skipping.')\n", (4541, 4600), False, 'import logging\n'), ((4945, 5009), 'lhotse.audio.Recording.from_file', 'Recording.from_file', (['p'], {'recording_id': 'f"""{p.parent.stem}_{p.stem}"""'}), "(p, recording_id=f'{p.parent.stem}_{p.stem}')\n", (4964, 5009), False, 'from lhotse.audio import Recording, RecordingSet\n'), ((5086, 5165), 'lhotse.audio.RecordingSet.open_writer', 'RecordingSet.open_writer', (["(output_dir / f'spgispeech_recordings_{part}.jsonl.gz')"], {}), "(output_dir / f'spgispeech_recordings_{part}.jsonl.gz')\n", (5110, 5165), False, 'from lhotse.audio import Recording, RecordingSet\n'), ((5605, 5692), 'lhotse.supervision.SupervisionSet.open_writer', 'SupervisionSet.open_writer', (["(output_dir / f'spgispeech_supervisions_{part}.jsonl.gz')"], {}), "(output_dir /\n f'spgispeech_supervisions_{part}.jsonl.gz')\n", (5631, 5692), False, 'from lhotse.supervision import SupervisionSet, SupervisionSegment\n'), ((5844, 5881), 'tqdm.auto.tqdm', 'tqdm', (['f'], {'desc': '"""Processing utterances"""'}), "(f, desc='Processing utterances')\n", (5848, 5881), False, 'from tqdm.auto import tqdm\n'), ((6699, 6744), 'lhotse.audio.RecordingSet.from_jsonl_lazy', 'RecordingSet.from_jsonl_lazy', (['rec_writer.path'], {}), '(rec_writer.path)\n', (6727, 6744), False, 'from lhotse.audio import Recording, RecordingSet\n'), ((6774, 6821), 'lhotse.supervision.SupervisionSet.from_jsonl_lazy', 'SupervisionSet.from_jsonl_lazy', (['sup_writer.path'], {}), '(sup_writer.path)\n', (6804, 6821), False, 'from lhotse.supervision import SupervisionSet, SupervisionSegment\n'), ((6291, 6451), 'lhotse.supervision.SupervisionSegment', 'SupervisionSegment', ([], {'id': 'recording_id', 'recording_id': 'recording_id', 'text': 'text', 'speaker': 'spkid', 'start': '(0)', 'duration': 'durations[recording_id]', 'language': '"""English"""'}), "(id=recording_id, recording_id=recording_id, text=text,\n speaker=spkid, start=0, duration=durations[recording_id], language=\n 'English')\n", (6309, 6451), False, 'from lhotse.supervision import SupervisionSet, SupervisionSegment\n')]
import os from django import template from django.conf import settings from django.template import Template, Context from django.utils.safestring import mark_safe from django.utils.text import normalize_newlines from wagtailmenus.models import FlatMenu from xr_pages import services from xr_pages.svg_icons import svg_icon_map register = template.Library() @register.simple_tag(takes_context=True) def get_site(context): request = context.get("request", None) return services.get_site(request) @register.simple_tag(takes_context=True) def get_home_page(context): request = context.get("request", None) return services.get_home_page(request) @register.simple_tag(takes_context=True) def get_local_group_list_page(context): request = context.get("request", None) return services.get_local_group_list_page(request) @register.simple_tag(takes_context=True) def get_local_groups(context): return services.get_local_groups @register.inclusion_tag("xr_pages/templatetags/inline_svg_text.html") def inline_svg_text(text, font_size=None): text = normalize_newlines(text) text_lines = text.split("\n") return { "text_lines": text_lines, "font_size": font_size, "text_y": "{}".format(len(text_lines) / 2), } @register.simple_tag(takes_context=True) def get_footer_menus(context): try: site = context["request"].site footer_menus = FlatMenu.objects.filter(handle__startswith="footer_", site=site) except (KeyError, AttributeError): return None return list(footer_menus) @register.simple_tag(takes_context=True) def svg_icon(context, icon_name, size=32, css_classes="", aria_label=""): if icon_name not in svg_icon_map: return "" embedded_svg_icons = context.get("_embedded_svg_icons", set()) svg_context = Context( { "name": icon_name, "size": size, "css_classes": css_classes, "aria_label": aria_label, } ) if icon_name in embedded_svg_icons: # The icon was already embedded. Render a <use> tag instead. svg_context["svg"] = mark_safe( '<svg viewbox="0 0 100 100"><use href="#svg-icon-{name}"/></svg>'.format( name=icon_name ) ) else: # The icon is not yet embedded. Render the svg. icon_filename = svg_icon_map[icon_name] icon_directory = "xr_pages/svg_icons/icons/" icon_path = os.path.join(settings.BASE_DIR, icon_directory, icon_filename) if not os.path.isfile(icon_path): return "" with open(icon_path) as svg_file: svg_context["svg"] = mark_safe(svg_file.read()) # Remember, that we already embedded this svg icon. # Every time we render with the same context, the icon won't be embedded again but a <use> tag will be rendered instead. embedded_svg_icons.add(icon_name) context["_embedded_svg_icons"] = embedded_svg_icons svg_template = Template( """ <i class="svg-container svg-container__{{ name }} {{ css_classes }}" style="width:{{ size }}px; height:{{ size }}px" {% if aria_label %} aria-label="{{ aria_label }}" aria-hidden="true" {% endif %} >{{ svg }}</i> """ ) html = svg_template.render(svg_context) return html @register.inclusion_tag( "xr_pages/templatetags/social_media_page_links.html", takes_context=True ) def render_social_media_links_for_group( context, group, size=32, css_classes="", show_label=False ): social_media_links = [] for attr_name in ["facebook", "twitter", "youtube", "instagram", "mastodon"]: url = None if hasattr(group, attr_name): url = getattr(group, attr_name) if url: social_media_links.append( { "url": url, "icon_name": attr_name, "verbose_name": attr_name.capitalize(), } ) return { "_embedded_svg_icons": context.get("_embedded_svg_icons", set()), "social_media_links": social_media_links, "size": size, "css_classes": css_classes, "show_label": show_label, }
[ "wagtailmenus.models.FlatMenu.objects.filter", "django.template.Template", "os.path.join", "os.path.isfile", "xr_pages.services.get_local_group_list_page", "django.template.Library", "django.template.Context", "django.utils.text.normalize_newlines", "xr_pages.services.get_home_page", "xr_pages.ser...
[((341, 359), 'django.template.Library', 'template.Library', ([], {}), '()\n', (357, 359), False, 'from django import template\n'), ((480, 506), 'xr_pages.services.get_site', 'services.get_site', (['request'], {}), '(request)\n', (497, 506), False, 'from xr_pages import services\n'), ((632, 663), 'xr_pages.services.get_home_page', 'services.get_home_page', (['request'], {}), '(request)\n', (654, 663), False, 'from xr_pages import services\n'), ((801, 844), 'xr_pages.services.get_local_group_list_page', 'services.get_local_group_list_page', (['request'], {}), '(request)\n', (835, 844), False, 'from xr_pages import services\n'), ((1082, 1106), 'django.utils.text.normalize_newlines', 'normalize_newlines', (['text'], {}), '(text)\n', (1100, 1106), False, 'from django.utils.text import normalize_newlines\n'), ((1838, 1938), 'django.template.Context', 'Context', (["{'name': icon_name, 'size': size, 'css_classes': css_classes, 'aria_label':\n aria_label}"], {}), "({'name': icon_name, 'size': size, 'css_classes': css_classes,\n 'aria_label': aria_label})\n", (1845, 1938), False, 'from django.template import Template, Context\n'), ((3031, 3359), 'django.template.Template', 'Template', (['"""\n <i class="svg-container svg-container__{{ name }} {{ css_classes }}"\n style="width:{{ size }}px; height:{{ size }}px"\n {% if aria_label %}\n aria-label="{{ aria_label }}"\n aria-hidden="true"\n {% endif %}\n >{{ svg }}</i>\n """'], {}), '(\n """\n <i class="svg-container svg-container__{{ name }} {{ css_classes }}"\n style="width:{{ size }}px; height:{{ size }}px"\n {% if aria_label %}\n aria-label="{{ aria_label }}"\n aria-hidden="true"\n {% endif %}\n >{{ svg }}</i>\n """\n )\n', (3039, 3359), False, 'from django.template import Template, Context\n'), ((1425, 1489), 'wagtailmenus.models.FlatMenu.objects.filter', 'FlatMenu.objects.filter', ([], {'handle__startswith': '"""footer_"""', 'site': 'site'}), "(handle__startswith='footer_', site=site)\n", (1448, 1489), False, 'from wagtailmenus.models import FlatMenu\n'), ((2488, 2550), 'os.path.join', 'os.path.join', (['settings.BASE_DIR', 'icon_directory', 'icon_filename'], {}), '(settings.BASE_DIR, icon_directory, icon_filename)\n', (2500, 2550), False, 'import os\n'), ((2567, 2592), 'os.path.isfile', 'os.path.isfile', (['icon_path'], {}), '(icon_path)\n', (2581, 2592), False, 'import os\n')]
from django.contrib import admin from .models import Person admin.site.register(Person) # Register your models here.
[ "django.contrib.admin.site.register" ]
[((61, 88), 'django.contrib.admin.site.register', 'admin.site.register', (['Person'], {}), '(Person)\n', (80, 88), False, 'from django.contrib import admin\n')]
#################################################################################################### ## ## Project: Embedded Learning Library (ELL) ## File: demoHelper.py ## Authors: <NAME> ## <NAME> ## ## Requires: Python 3.x ## #################################################################################################### import os import sys import argparse import cv2 import numpy as np import time import math script_path = os.path.dirname(os.path.abspath(__file__)) # Helper class that interfaces with ELL models to get predictions and provides handy conversion from opencv to ELL buffers and # rendering utilities class DemoHelper: def __init__(self, threshold=0.15): """ Helper class to store information about the model we want to use. threshold - specifies a prediction threshold """ self.threshold = threshold self.start = time.time() self.frame_count = 0 self.fps = 0 self.camera = 0 self.image_filename = None self.image_folder = None self.images = None self.image_pos = 0 self.capture_device = None self.frame = None self.save_images = None self.image_index = 0 self.model_file = None self.model = None self.model_name = "model" self.compiled_model = None self.compiled_module = None self.compiled_func = None self.labels_file = None self.model_file = None self.iterations = None # limit number of iterations through the loop. self.current = None self.total_time = 0 self.time_count = 0 self.warm_up = True self.input_shape = None self.output_shape = None self.output_size = 0 self.bgr = False self.results = None self.nogui = False def add_arguments(self, arg_parser): """ Adds common commandline arguments for ELL tutorials and demos and returns an object with the relevant values set from those arguments. Note: This method is designed for subclasses, so they can can add MORE arguments before calling parse_args. """ # required arguments arg_parser.add_argument("labels", help="path to the labels file for evaluating the model, or comma separated list if using more than one model") # options arg_parser.add_argument("--save", help="save images captured by the camera", action='store_true') arg_parser.add_argument("--threshold", type=float, help="threshold for the minimum prediction score. A lower threshold will show more prediction labels, but they have a higher chance of being completely wrong.", default=self.threshold) arg_parser.add_argument("--bgr", help="specify True if input data should be in BGR format (default False)", default = self.bgr) arg_parser.add_argument("--nogui", help="disable GUI to enable automated testing of a batch of images", action='store_true') arg_parser.add_argument("--iterations", type=int, help="when used with --nogui this tests multiple iterations of each image to get better timing information") # mutually exclusive options group = arg_parser.add_mutually_exclusive_group() group.add_argument("--camera", type=int, help="the camera id of the webcam", default=0) group.add_argument("--image", help="path to an image file. If set, evaluates the model using the image, instead of a webcam") group.add_argument("--folder", help="path to an image folder. If set, evaluates the model using the images found there") group2 = arg_parser.add_mutually_exclusive_group() group2.add_argument("--model", help="path to a model file") group2.add_argument("--compiledModel", help="path to the compiled model's Python module") group2.add_argument("--models", help="list of comma separated paths to model files") group2.add_argument("--compiledModels", help="list of comma separated paths to the compiled models' Python modules") def parse_arguments(self, argv, helpString): arg_parser = argparse.ArgumentParser(helpString) self.add_arguments(arg_parser) args = arg_parser.parse_args(argv) self.initialize(args) def value_from_arg(self, argValue, defaultValue): if (argValue is not None): return argValue return defaultValue def initialize(self, args): # called after parse_args to extract args from the arg_parser. # process required arguments self.labels_file = args.labels # process options self.save_images = self.value_from_arg(args.save, None) self.threshold = self.value_from_arg(args.threshold, None) self.iterations = self.value_from_arg(args.iterations, None) self.current = self.iterations self.camera = self.value_from_arg(args.iterations, 0) self.image_filename = self.value_from_arg(args.image, None) self.image_folder = self.value_from_arg(args.folder, None) self.bgr = args.bgr self.nogui = args.nogui if self.nogui and self.iterations == None: self.iterations = 1 # process image source options if (args.camera): self.image_filename = None self.image_folder = None elif (args.image): self.camera = None self.image_folder = None elif (args.folder): self.camera = None # load the labels self.labels = self.load_labels(self.labels_file) # process model options and load the model self.model_file = args.model self.compiled_model = args.compiledModel if (self.model_file == None): # this is the compiled model route, so load the wrapped module self.model_name = os.path.split(self.compiled_model)[1] self.import_compiled_model(self.compiled_model, self.model_name) else: # this is the "interpreted" model route, so we need the ELL runtime. self.model_name = os.path.splitext(os.path.basename(self.model_file))[0] self.import_ell_map() self.input_size = (self.input_shape.rows, self.input_shape.columns) print("Found input_shape [%d,%d,%d]" % (self.input_shape.rows, self.input_shape.columns, self.input_shape.channels)) return True def load_ell(self): print("### Loading ELL modules...") import find_ell import ell return ell def import_ell_map(self): ell = self.load_ell() sys.path.append(script_path) sys.path.append(os.getcwd()) print("loading model: " + self.model_file) self.model = ell.model.Map(self.model_file) self.input_shape = self.model.GetInputShape() self.output_shape = self.model.GetOutputShape() self.output_size = int(self.output_shape.rows * self.output_shape.columns * self.output_shape.channels) def import_compiled_model(self, compiledModulePath, name): moduleDirectory = os.path.dirname(compiledModulePath) print('Looking for: ' + name + ' in ' + moduleDirectory) if (not os.path.isdir('build')) and (not os.path.isdir(moduleDirectory + '/build')): raise Exception("you don't have a 'build' directory in '" + compiledModulePath + "', have you compiled this project yet?") func_name = 'predict' if func_name == "": raise Exception("Could not construct func name. Is the --compiledModel argument correct?") # Import the compiled model wrapper. Add the possible build directories. sys.path.append(script_path) sys.path.append(moduleDirectory) sys.path.append(os.path.join(moduleDirectory, 'build')) sys.path.append(os.path.join(moduleDirectory, 'build/Release')) sys.path.append(os.path.join(script_path, 'build')) sys.path.append(os.path.join(script_path, 'build/Release')) sys.path.append(os.path.join(os.getcwd(), 'build')) sys.path.append(os.path.join(os.getcwd(), 'build/Release')) try: self.compiled_module = __import__(name) inputShapeGetter = getattr(self.compiled_module, "get_default_input_shape") outputShapeGetter = getattr(self.compiled_module, "get_default_output_shape") self.input_shape = inputShapeGetter() self.output_shape = outputShapeGetter() self.output_size = int(self.output_shape.rows * self.output_shape.columns * self.output_shape.channels) try: self.compiled_func = getattr(self.compiled_module, func_name) except AttributeError: raise Exception(func_name + " function not found in compiled module") except: errorType, value, traceback = sys.exc_info() print("### Exception: " + str(errorType) + ": " + str(value)) print("====================================================================") print("Compiled ELL python module is not loading") print("It is possible that you need to add LibOpenBLAS to your system path (See Install-*.md) from root of this repo") raise Exception("Compiled model failed to load") def show_image(self, frameToShow, save): try: cv2.imshow('frame', frameToShow) except cv2.error as e: # OpenCV may not have been built with GTK or Carbon support pass if save and self.save_images: name = 'frame' + str(self.image_index) + ".png" cv2.imwrite(name, frameToShow) self.image_index = self.image_index + 1 def load_labels(self, fileName): labels = [] with open(fileName) as f: labels = f.read().splitlines() return labels def predict(self, data): if self.current != None: self.current = self.current - 1 start = time.time() if self.model == None: self.results = self.compiled_func(data) else: self.results = self.model.Compute(data, dtype=np.float32) end = time.time() diff = end - start # if warm up is true then discard the first time if self.time_count == 1 and self.warm_up: self.warm_up = False self.total_time = 0 self.time_count = 0 self.total_time = self.total_time + diff self.time_count = self.time_count + 1 return self.results def get_times(self): """Returns the average prediction time, if available.""" average_time = None if self.time_count > 0: average_time = self.total_time/self.time_count return average_time def report_times(self, node_level=True): """Prints the average prediction time and additional profiling info, if available.""" average_time = self.get_times() if average_time is not None: print("Average prediction time: " + str(average_time)) # if the model is compiled with profiling enabled, report the additional info if hasattr(self.compiled_module, self.model_name + "_PrintModelProfilingInfo"): getattr(self.compiled_module, self.model_name + "_PrintModelProfilingInfo")() if node_level: if hasattr(self.compiled_module, self.model_name + "_PrintNodeProfilingInfo"): getattr(self.compiled_module, self.model_name + "_PrintNodeProfilingInfo")() def get_top_n_predictions(self, predictions, N = 5): """Return at most the top N predictions as a list of tuples that meet the threshold. The first of element of each tuple represents the index or class of the prediction and the second element represents that probability or confidence value. """ map = [(i,predictions[i]) for i in range(len(predictions)) if predictions[i] >= self.threshold] map.sort(key=lambda tup: tup[1], reverse=True) result = map[:N] return result def get_label(self, i): if (i < len(self.labels)): return self.labels[i] return "" def get_predictor_map(self, predictor, intervalMs=0): ell = self.load_ell() """Creates an ELL map from an ELL predictor""" return ell.neural.utilities.ell_map_from_float_predictor(predictor) def compile(self, predictor, platform, path): path += '/model' prediction_function = self.get_predictor_map(predictor) prediction_function.Compile(platform, 'model', 'step', path, dtype=np.float32) from ..util.commands import run_llc, run_swig run_swig(path + '.i') run_llc(path + '.ll') def save_ell_predictor_to_file(self, predictor, filePath, intervalMs=0): """Saves an ELL predictor to file so that it can be compiled to run on a device, with an optional stepInterval in milliseconds""" ell_map = self.get_predictor_map(predictor, intervalMs) ell_map.Save(filePath) def init_image_source(self): # Start video capture device or load static image if self.camera is not None: self.capture_device = cv2.VideoCapture(self.camera) elif self.image_filename: self.frame = cv2.imread(self.image_filename) if (type(self.frame) == type(None)): raise Exception('image from %s failed to load' % (self.image_filename)) elif self.image_folder: self.frame = self.load_next_image() def load_next_image(self): if self.image_folder is None: return self.frame # find images in the self.image_folder and cycle through them. if self.images == None: self.images = os.listdir(self.image_folder) frame = None while frame is None and self.image_pos < len(self.images): filename = os.path.join(self.image_folder, self.images[self.image_pos]) frame = cv2.imread(filename) self.image_pos += 1 if not frame is None: return frame return self.frame def get_next_frame(self): if self.capture_device is not None: # if predictor is too slow frames get buffered, this is designed to flush that buffer for i in range(self.get_wait()): ret, self.frame = self.capture_device.read() if (not ret): raise Exception('your capture device is not returning images') return self.frame else: return np.copy(self.frame) def resize_image(self, image, newSize): # Shape: [rows, cols, channels] """Crops, resizes image to outputshape. Returns image as numpy array in in RGB order.""" if image.shape[0] > image.shape[1]: # Tall (more rows than cols) rowStart = int((image.shape[0] - image.shape[1]) / 2) rowEnd = rowStart + image.shape[1] colStart = 0 colEnd = image.shape[1] else: # Wide (more cols than rows) rowStart = 0 rowEnd = image.shape[0] colStart = int((image.shape[1] - image.shape[0]) / 2) colEnd = colStart + image.shape[0] cropped = image[rowStart:rowEnd, colStart:colEnd] resized = cv2.resize(cropped, newSize) return resized def prepare_image_for_predictor(self, image): """Crops, resizes image to outputshape. Returns image as numpy array in in RGB order.""" resized = self.resize_image(image, self.input_size) if not self.bgr: resized = cv2.cvtColor(resized, cv2.COLOR_BGR2RGB) resized = resized.astype(np.float).ravel() return resized def draw_label(self, image, label): """Helper to draw text label onto an image""" self.draw_header(image, label) return def draw_header(self, image, text): """Helper to draw header text block onto an image""" self.draw_text_block(image, text, (0, 0), (50, 200, 50)) return def draw_footer(self, image, text): """Helper to draw footer text block onto an image""" self.draw_text_block(image, text, (0, image.shape[0] - 40), (200, 100, 100)) return def draw_text_block(self, image, text, blockTopLeft=(0,0), blockColor=(50, 200, 50), blockHeight=40, fontScale=0.7): """Helper to draw a filled rectangle with text onto an image""" cv2.rectangle( image, blockTopLeft, (image.shape[1], blockTopLeft[1] + blockHeight), blockColor, cv2.FILLED) cv2.putText(image, text, (blockTopLeft[0] + int(blockHeight / 4), blockTopLeft[1] + int(blockHeight * 0.667)), cv2.FONT_HERSHEY_COMPLEX_SMALL, fontScale, (0, 0, 0), 1, cv2.LINE_AA) def draw_fps(self, image): """Helper to draw frame per second onto image""" now = time.time() if self.frame_count > 0: diff = now - self.start if diff >= 1: self.fps = round(self.frame_count / diff, 1) self.frame_count = 0 self.start = now label = "fps " + str(self.fps) labelSize, baseline = cv2.getTextSize( label, cv2.FONT_HERSHEY_SIMPLEX, 0.4, 1) width = image.shape[1] height = image.shape[0] pos = (width - labelSize[0] - 5, labelSize[1] + 5) cv2.putText(image, label, pos, cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0, 0, 128), 1, cv2.LINE_AA) self.frame_count = self.frame_count + 1 def get_wait(self): speed = self.fps if (speed == 0): speed = 1 if (speed > 1): return 1 return 3 def done(self): if self.current is not None and self.current > 0: return False # on slow devices this helps let the images to show up on screen result = False try: if self.nogui: if self.images is not None and self.image_pos < len(self.images): self.frame = self.load_next_image() self.current = self.iterations return False return True for i in range(self.get_wait()): key = cv2.waitKey(1) & 0xFF if key == 27: result = True break if key == ord(' '): self.frame = self.load_next_image() except cv2.error as e: # OpenCV may not have been built with GTK or Carbon support pass return result
[ "cv2.rectangle", "cv2.imshow", "sys.exc_info", "sys.path.append", "os.listdir", "ell.model.Map", "argparse.ArgumentParser", "ell.neural.utilities.ell_map_from_float_predictor", "os.path.split", "os.path.isdir", "cv2.waitKey", "cv2.putText", "os.path.dirname", "cv2.cvtColor", "cv2.getText...
[((475, 500), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (490, 500), False, 'import os\n'), ((914, 925), 'time.time', 'time.time', ([], {}), '()\n', (923, 925), False, 'import time\n'), ((4155, 4190), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['helpString'], {}), '(helpString)\n', (4178, 4190), False, 'import argparse\n'), ((6685, 6713), 'sys.path.append', 'sys.path.append', (['script_path'], {}), '(script_path)\n', (6700, 6713), False, 'import sys\n'), ((6823, 6853), 'ell.model.Map', 'ell.model.Map', (['self.model_file'], {}), '(self.model_file)\n', (6836, 6853), False, 'import ell\n'), ((7166, 7201), 'os.path.dirname', 'os.path.dirname', (['compiledModulePath'], {}), '(compiledModulePath)\n', (7181, 7201), False, 'import os\n'), ((7755, 7783), 'sys.path.append', 'sys.path.append', (['script_path'], {}), '(script_path)\n', (7770, 7783), False, 'import sys\n'), ((7792, 7824), 'sys.path.append', 'sys.path.append', (['moduleDirectory'], {}), '(moduleDirectory)\n', (7807, 7824), False, 'import sys\n'), ((10114, 10125), 'time.time', 'time.time', ([], {}), '()\n', (10123, 10125), False, 'import time\n'), ((10307, 10318), 'time.time', 'time.time', ([], {}), '()\n', (10316, 10318), False, 'import time\n'), ((12486, 12546), 'ell.neural.utilities.ell_map_from_float_predictor', 'ell.neural.utilities.ell_map_from_float_predictor', (['predictor'], {}), '(predictor)\n', (12535, 12546), False, 'import ell\n'), ((15480, 15508), 'cv2.resize', 'cv2.resize', (['cropped', 'newSize'], {}), '(cropped, newSize)\n', (15490, 15508), False, 'import cv2\n'), ((16645, 16756), 'cv2.rectangle', 'cv2.rectangle', (['image', 'blockTopLeft', '(image.shape[1], blockTopLeft[1] + blockHeight)', 'blockColor', 'cv2.FILLED'], {}), '(image, blockTopLeft, (image.shape[1], blockTopLeft[1] +\n blockHeight), blockColor, cv2.FILLED)\n', (16658, 16756), False, 'import cv2\n'), ((17079, 17090), 'time.time', 'time.time', ([], {}), '()\n', (17088, 17090), False, 'import time\n'), ((17387, 17443), 'cv2.getTextSize', 'cv2.getTextSize', (['label', 'cv2.FONT_HERSHEY_SIMPLEX', '(0.4)', '(1)'], {}), '(label, cv2.FONT_HERSHEY_SIMPLEX, 0.4, 1)\n', (17402, 17443), False, 'import cv2\n'), ((17587, 17682), 'cv2.putText', 'cv2.putText', (['image', 'label', 'pos', 'cv2.FONT_HERSHEY_SIMPLEX', '(0.4)', '(0, 0, 128)', '(1)', 'cv2.LINE_AA'], {}), '(image, label, pos, cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0, 0, 128), \n 1, cv2.LINE_AA)\n', (17598, 17682), False, 'import cv2\n'), ((6738, 6749), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (6747, 6749), False, 'import os\n'), ((7849, 7887), 'os.path.join', 'os.path.join', (['moduleDirectory', '"""build"""'], {}), "(moduleDirectory, 'build')\n", (7861, 7887), False, 'import os\n'), ((7913, 7959), 'os.path.join', 'os.path.join', (['moduleDirectory', '"""build/Release"""'], {}), "(moduleDirectory, 'build/Release')\n", (7925, 7959), False, 'import os\n'), ((7985, 8019), 'os.path.join', 'os.path.join', (['script_path', '"""build"""'], {}), "(script_path, 'build')\n", (7997, 8019), False, 'import os\n'), ((8045, 8087), 'os.path.join', 'os.path.join', (['script_path', '"""build/Release"""'], {}), "(script_path, 'build/Release')\n", (8057, 8087), False, 'import os\n'), ((9475, 9507), 'cv2.imshow', 'cv2.imshow', (['"""frame"""', 'frameToShow'], {}), "('frame', frameToShow)\n", (9485, 9507), False, 'import cv2\n'), ((9751, 9781), 'cv2.imwrite', 'cv2.imwrite', (['name', 'frameToShow'], {}), '(name, frameToShow)\n', (9762, 9781), False, 'import cv2\n'), ((13361, 13390), 'cv2.VideoCapture', 'cv2.VideoCapture', (['self.camera'], {}), '(self.camera)\n', (13377, 13390), False, 'import cv2\n'), ((13932, 13961), 'os.listdir', 'os.listdir', (['self.image_folder'], {}), '(self.image_folder)\n', (13942, 13961), False, 'import os\n'), ((14073, 14133), 'os.path.join', 'os.path.join', (['self.image_folder', 'self.images[self.image_pos]'], {}), '(self.image_folder, self.images[self.image_pos])\n', (14085, 14133), False, 'import os\n'), ((14154, 14174), 'cv2.imread', 'cv2.imread', (['filename'], {}), '(filename)\n', (14164, 14174), False, 'import cv2\n'), ((14735, 14754), 'numpy.copy', 'np.copy', (['self.frame'], {}), '(self.frame)\n', (14742, 14754), True, 'import numpy as np\n'), ((15795, 15835), 'cv2.cvtColor', 'cv2.cvtColor', (['resized', 'cv2.COLOR_BGR2RGB'], {}), '(resized, cv2.COLOR_BGR2RGB)\n', (15807, 15835), False, 'import cv2\n'), ((5912, 5946), 'os.path.split', 'os.path.split', (['self.compiled_model'], {}), '(self.compiled_model)\n', (5925, 5946), False, 'import os\n'), ((7283, 7305), 'os.path.isdir', 'os.path.isdir', (['"""build"""'], {}), "('build')\n", (7296, 7305), False, 'import os\n'), ((7316, 7357), 'os.path.isdir', 'os.path.isdir', (["(moduleDirectory + '/build')"], {}), "(moduleDirectory + '/build')\n", (7329, 7357), False, 'import os\n'), ((8126, 8137), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (8135, 8137), False, 'import os\n'), ((8186, 8197), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (8195, 8197), False, 'import os\n'), ((8970, 8984), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (8982, 8984), False, 'import sys\n'), ((13450, 13481), 'cv2.imread', 'cv2.imread', (['self.image_filename'], {}), '(self.image_filename)\n', (13460, 13481), False, 'import cv2\n'), ((6169, 6202), 'os.path.basename', 'os.path.basename', (['self.model_file'], {}), '(self.model_file)\n', (6185, 6202), False, 'import os\n'), ((18492, 18506), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (18503, 18506), False, 'import cv2\n')]
#!/bin/env python from __future__ import division, print_function , unicode_literals, absolute_import import os, sys, subprocess crow_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) eigen_cflags = "" try: has_pkg_eigen = subprocess.call(["pkg-config","--exists","eigen3"]) == 0 except: has_pkg_eigen = False if has_pkg_eigen: eigen_cflags = subprocess.check_output(["pkg-config","eigen3","--cflags"]) libmesh_eigen = os.path.abspath(os.path.join(crow_dir,os.pardir,"moose","libmesh","contrib","eigen","eigen")) if os.path.exists(libmesh_eigen): eigen_cflags = "-I"+libmesh_eigen if os.path.exists(os.path.join(crow_dir,"contrib","include","Eigen")): eigen_cflags = "" print(eigen_cflags)
[ "subprocess.check_output", "os.path.exists", "os.path.join", "subprocess.call", "os.path.abspath" ]
[((545, 574), 'os.path.exists', 'os.path.exists', (['libmesh_eigen'], {}), '(libmesh_eigen)\n', (559, 574), False, 'import os, sys, subprocess\n'), ((370, 431), 'subprocess.check_output', 'subprocess.check_output', (["['pkg-config', 'eigen3', '--cflags']"], {}), "(['pkg-config', 'eigen3', '--cflags'])\n", (393, 431), False, 'import os, sys, subprocess\n'), ((463, 549), 'os.path.join', 'os.path.join', (['crow_dir', 'os.pardir', '"""moose"""', '"""libmesh"""', '"""contrib"""', '"""eigen"""', '"""eigen"""'], {}), "(crow_dir, os.pardir, 'moose', 'libmesh', 'contrib', 'eigen',\n 'eigen')\n", (475, 549), False, 'import os, sys, subprocess\n'), ((631, 684), 'os.path.join', 'os.path.join', (['crow_dir', '"""contrib"""', '"""include"""', '"""Eigen"""'], {}), "(crow_dir, 'contrib', 'include', 'Eigen')\n", (643, 684), False, 'import os, sys, subprocess\n'), ((174, 199), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (189, 199), False, 'import os, sys, subprocess\n'), ((245, 298), 'subprocess.call', 'subprocess.call', (["['pkg-config', '--exists', 'eigen3']"], {}), "(['pkg-config', '--exists', 'eigen3'])\n", (260, 298), False, 'import os, sys, subprocess\n')]
from api_common.api_router import router from func_common.get_currenttime import getcurrenttime from func_common.filepathforchecksec import get_filepaths import os ''' 弱口令检测API,不包含暴力枚举破解,只进行收集弱口令检测 ''' @router.get("/checkpasswd", name="账号密码检查", description="用于账号密码检查的api,查看是否有弱密码泄露,username为用户名参数,filename为文件参数") async def checkpasswd(username,filename): file_tmp_path = filename.rsplit(".",1)[0] filepath = f"firmware/extract/{username}/{file_tmp_path}/_{filename}.extracted" passwd_path_result = [] shadow_path_result = [] passwd_result = [] shadow_result = [] final_result = [] try: password_dict = open("dict/weak_password.txt","r") dict_data = password_dict.readlines() result = str if os.path.isdir(filepath): filepath_result = get_filepaths(filepath) for i in filepath_result: if i.split('/')[len(i.split('/'))-1] == "passwd": passwd_path_result.append(i) if i.split('/')[len(i.split('/'))-1] == "shadow": shadow_path_result.append(i) if passwd_path_result: passwd_fopen = open(passwd_path_result[0],"r") if shadow_path_result: shadow_fopen = open(shadow_path_result[0],"r") for line in passwd_fopen.readlines(): passwd_result.append(line.rsplit("\n")[0]) for line in shadow_fopen.readlines(): shadow_result.append(line.rsplit("\n")[0]) for passwordline in passwd_result: if passwordline.split(':')[1] == "": final_result.append(passwordline.split(":")[0] + "高危,此账号未设置密码") elif passwordline.split(':')[1] == "*": final_result.append(passwordline.split(":")[0] + "此账户密码经过加密") elif passwordline.split(':')[1] == "!": final_result.append(passwordline.split(":")[0] + "此账户密码经过加密") elif passwordline.split(':')[1] == "x": for shadowline in shadow_result: if shadowline.split(":")[0] == passwordline.split(":")[0]: for data in dict_data: if data.split(":")[0] == shadowline.split(":")[1]: final_result.append(shadowline.split(":")[0] + ":" + data.split(":")[1]) if final_result is not None: return {"code":"200","status":True,"msg":final_result,"datetime":getcurrenttime()} else: return {"code":"503","status":False,"msg":"未找到泄露密码","datetime":getcurrenttime()} except: return {"code":"500","status":False,"msg":"未知错误","datetime":getcurrenttime()}
[ "func_common.get_currenttime.getcurrenttime", "os.path.isdir", "func_common.filepathforchecksec.get_filepaths", "api_common.api_router.router.get" ]
[((205, 319), 'api_common.api_router.router.get', 'router.get', (['"""/checkpasswd"""'], {'name': '"""账号密码检查"""', 'description': '"""用于账号密码检查的api,查看是否有弱密码泄露,username为用户名参数,filename为文件参数"""'}), "('/checkpasswd', name='账号密码检查', description=\n '用于账号密码检查的api,查看是否有弱密码泄露,username为用户名参数,filename为文件参数')\n", (215, 319), False, 'from api_common.api_router import router\n'), ((757, 780), 'os.path.isdir', 'os.path.isdir', (['filepath'], {}), '(filepath)\n', (770, 780), False, 'import os\n'), ((811, 834), 'func_common.filepathforchecksec.get_filepaths', 'get_filepaths', (['filepath'], {}), '(filepath)\n', (824, 834), False, 'from func_common.filepathforchecksec import get_filepaths\n'), ((2424, 2440), 'func_common.get_currenttime.getcurrenttime', 'getcurrenttime', ([], {}), '()\n', (2438, 2440), False, 'from func_common.get_currenttime import getcurrenttime\n'), ((2545, 2561), 'func_common.get_currenttime.getcurrenttime', 'getcurrenttime', ([], {}), '()\n', (2559, 2561), False, 'from func_common.get_currenttime import getcurrenttime\n'), ((2638, 2654), 'func_common.get_currenttime.getcurrenttime', 'getcurrenttime', ([], {}), '()\n', (2652, 2654), False, 'from func_common.get_currenttime import getcurrenttime\n')]
#!/usr/bin/python import urllib2 def getContent(url): """ Retrives url content """ try: content = urllib2.urlopen(url) except IOError: return "" return content.read()
[ "urllib2.urlopen" ]
[((126, 146), 'urllib2.urlopen', 'urllib2.urlopen', (['url'], {}), '(url)\n', (141, 146), False, 'import urllib2\n')]
from __future__ import absolute_import, division, print_function import pytest import torch from pyro.ops.linalg import rinverse from tests.common import assert_equal @pytest.mark.parametrize("A", [ torch.tensor([[17.]]), torch.tensor([[1., 2.], [2., -3.]]), torch.tensor([[1., 2, 0], [2, -2, 4], [0, 4, 5]]), torch.tensor([[1., 2, 0, 7], [2, -2, 4, -1], [0, 4, 5, 8], [7, -1, 8, 1]]), torch.tensor([[1., 2, 0, 7, 0], [2, -2, 4, -1, 2], [0, 4, 5, 8, -4], [7, -1, 8, 1, -3], [0, 2, -4, -3, -1]]), torch.eye(40) ]) @pytest.mark.parametrize("use_sym", [True, False]) def test_sym_rinverse(A, use_sym): d = A.shape[-1] assert_equal(rinverse(A, sym=use_sym), torch.inverse(A), prec=1e-8) assert_equal(torch.mm(A, rinverse(A, sym=use_sym)), torch.eye(d), prec=1e-8) batched_A = A.unsqueeze(0).unsqueeze(0).expand(5, 4, d, d) expected_A = torch.inverse(A).unsqueeze(0).unsqueeze(0).expand(5, 4, d, d) assert_equal(rinverse(batched_A, sym=use_sym), expected_A, prec=1e-8)
[ "torch.eye", "pytest.mark.parametrize", "torch.tensor", "pyro.ops.linalg.rinverse", "torch.inverse" ]
[((546, 595), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""use_sym"""', '[True, False]'], {}), "('use_sym', [True, False])\n", (569, 595), False, 'import pytest\n'), ((668, 692), 'pyro.ops.linalg.rinverse', 'rinverse', (['A'], {'sym': 'use_sym'}), '(A, sym=use_sym)\n', (676, 692), False, 'from pyro.ops.linalg import rinverse\n'), ((694, 710), 'torch.inverse', 'torch.inverse', (['A'], {}), '(A)\n', (707, 710), False, 'import torch\n'), ((779, 791), 'torch.eye', 'torch.eye', (['d'], {}), '(d)\n', (788, 791), False, 'import torch\n'), ((963, 995), 'pyro.ops.linalg.rinverse', 'rinverse', (['batched_A'], {'sym': 'use_sym'}), '(batched_A, sym=use_sym)\n', (971, 995), False, 'from pyro.ops.linalg import rinverse\n'), ((207, 229), 'torch.tensor', 'torch.tensor', (['[[17.0]]'], {}), '([[17.0]])\n', (219, 229), False, 'import torch\n'), ((234, 273), 'torch.tensor', 'torch.tensor', (['[[1.0, 2.0], [2.0, -3.0]]'], {}), '([[1.0, 2.0], [2.0, -3.0]])\n', (246, 273), False, 'import torch\n'), ((275, 325), 'torch.tensor', 'torch.tensor', (['[[1.0, 2, 0], [2, -2, 4], [0, 4, 5]]'], {}), '([[1.0, 2, 0], [2, -2, 4], [0, 4, 5]])\n', (287, 325), False, 'import torch\n'), ((330, 405), 'torch.tensor', 'torch.tensor', (['[[1.0, 2, 0, 7], [2, -2, 4, -1], [0, 4, 5, 8], [7, -1, 8, 1]]'], {}), '([[1.0, 2, 0, 7], [2, -2, 4, -1], [0, 4, 5, 8], [7, -1, 8, 1]])\n', (342, 405), False, 'import torch\n'), ((410, 524), 'torch.tensor', 'torch.tensor', (['[[1.0, 2, 0, 7, 0], [2, -2, 4, -1, 2], [0, 4, 5, 8, -4], [7, -1, 8, 1, -3],\n [0, 2, -4, -3, -1]]'], {}), '([[1.0, 2, 0, 7, 0], [2, -2, 4, -1, 2], [0, 4, 5, 8, -4], [7, -\n 1, 8, 1, -3], [0, 2, -4, -3, -1]])\n', (422, 524), False, 'import torch\n'), ((524, 537), 'torch.eye', 'torch.eye', (['(40)'], {}), '(40)\n', (533, 537), False, 'import torch\n'), ((752, 776), 'pyro.ops.linalg.rinverse', 'rinverse', (['A'], {'sym': 'use_sym'}), '(A, sym=use_sym)\n', (760, 776), False, 'from pyro.ops.linalg import rinverse\n'), ((884, 900), 'torch.inverse', 'torch.inverse', (['A'], {}), '(A)\n', (897, 900), False, 'import torch\n')]
import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib.patches import FancyArrowPatch, Arc def get_angle_plot(line1, line2, radius=1, color=None, origin=(0, 0), len_x_axis=1, len_y_axis=1): l1xy = line1.get_xydata() # Angle between line1 and x-axis l1_xs = l1xy[:, 0] l1_ys = l1xy[:, 1] angle1 = np.degrees(np.arctan2(np.diff(l1_ys), np.diff(l1_xs))) l2xy = line2.get_xydata() # Angle between line2 and x-axis l2_xs = l2xy[:, 0] l2_ys = l2xy[:, 1] angle2 = np.degrees(np.arctan2(np.diff(l2_ys), np.diff(l2_xs))) theta1 = min(angle1, angle2) theta2 = max(angle1, angle2) if color is None: color = line1.get_color() # Uses the color of line 1 if color parameter is not passed. return Arc(origin, len_x_axis * radius, len_y_axis * radius, 0, theta1, theta2, color=color) def ssto_fbd(include_drag=True): fig, ax = plt.subplots(1, 1, figsize=(6, 6)) ax.axis('off') ax.set_xlim(-0.1, 1.1) ax.set_ylim(-0.1, 1.1) # plt.plot((0, 200), (200, 200), linestyle='--', color='#CCCCCC') def y_ssto(x): return -(x-1)**2+1, 2-2*x x = np.linspace(0.0, 1, 100) y, _ = y_ssto(x) plt.plot(x, y, 'b-', alpha=0.3) # Add the axes x = x[0] y = y[0] dx = 0.5 dy = 0 xhat = FancyArrowPatch((x, y), (x+dx, y+dy), arrowstyle='->', mutation_scale=10) ax.add_patch(xhat) plt.text(x+dx/2.0, y+dy/2.0-0.05, 'x') dx = 0 dy = 0.5 yhat = FancyArrowPatch((x, y), (x+dx, y+dy), arrowstyle='->', mutation_scale=10) ax.add_patch(yhat) plt.text(x+dx/2.0-0.05, y+dy/2.0, 'y') # Add the launch vehicle x = 0.5 y, dy_dx = y_ssto(x) plt.plot(x, y, 'ro', ms=10) # Draw and label the gravity vector L = 0.2 gvec = FancyArrowPatch((x, y), (x, y-L), arrowstyle='->', mutation_scale=10) plt.Line2D((x, x), (y, y-L), visible=False) # Local vertical ax.add_patch(gvec) plt.text(x-0.05, y-L, 'g') # Draw and label the velocity vector dx = 0.3 dy = dy_dx * dx vvec = FancyArrowPatch((x, y), (x+dx, y+dy), arrowstyle='->', mutation_scale=10) vvec_line = plt.Line2D((x, x+dx), (y, y+dy), visible=False) ax.add_patch(vvec) plt.text(x+dx, y+dy-0.05, 'v') # Draw and label the drag vector if include_drag: dx = -0.2 dy = dy_dx * dx dvec = FancyArrowPatch((x, y), (x+dx, y+dy), arrowstyle='->', mutation_scale=10) plt.Line2D((x, x+dx), (y, y+dy), visible=False) ax.add_patch(dvec) plt.text(x+dx, y+dy+0.05, 'D') # Draw and label the thrust vector dx = 0.2 dy = 0.6 * dy_dx * dx tvec = FancyArrowPatch((x, y), (x+dx, y+dy), arrowstyle='->', mutation_scale=10) tvec_line = plt.Line2D((x, x + dx), (y, y + dy), visible=False) ax.add_patch(tvec) plt.text(x+dx, y+dy-0.05, 'T') # Draw the local horizon dx = 0.4 dy = 0 lh_line, = plt.plot((x, x+dx), (y, y+dy), linestyle='--', color='k', zorder=-1000) # Draw and label the thrust angle theta_plot = get_angle_plot(lh_line, vvec_line, color='k', origin=(x, y), radius=0.6) ax.add_patch(theta_plot) ax.text(x+0.1, y+0.02, r'$\theta$') # Draw and label the flight path angle gamma_plot = get_angle_plot(lh_line, tvec_line, color='k', origin=(x, y), radius=0.3) ax.add_patch(gamma_plot) ax.text(x+0.26, y+0.06, r'$\gamma$') plt.savefig('ssto_fbd.png') plt.show() if __name__ == '__main__': ssto_fbd()
[ "matplotlib.pyplot.text", "matplotlib.pyplot.savefig", "matplotlib.patches.Arc", "matplotlib.use", "matplotlib.pyplot.plot", "matplotlib.patches.FancyArrowPatch", "numpy.diff", "numpy.linspace", "matplotlib.pyplot.Line2D", "matplotlib.pyplot.subplots", "matplotlib.pyplot.show" ]
[((38, 59), 'matplotlib.use', 'matplotlib.use', (['"""Agg"""'], {}), "('Agg')\n", (52, 59), False, 'import matplotlib\n'), ((825, 914), 'matplotlib.patches.Arc', 'Arc', (['origin', '(len_x_axis * radius)', '(len_y_axis * radius)', '(0)', 'theta1', 'theta2'], {'color': 'color'}), '(origin, len_x_axis * radius, len_y_axis * radius, 0, theta1, theta2,\n color=color)\n', (828, 914), False, 'from matplotlib.patches import FancyArrowPatch, Arc\n'), ((960, 994), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(6, 6)'}), '(1, 1, figsize=(6, 6))\n', (972, 994), True, 'import matplotlib.pyplot as plt\n'), ((1203, 1227), 'numpy.linspace', 'np.linspace', (['(0.0)', '(1)', '(100)'], {}), '(0.0, 1, 100)\n', (1214, 1227), True, 'import numpy as np\n'), ((1254, 1285), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""b-"""'], {'alpha': '(0.3)'}), "(x, y, 'b-', alpha=0.3)\n", (1262, 1285), True, 'import matplotlib.pyplot as plt\n'), ((1367, 1444), 'matplotlib.patches.FancyArrowPatch', 'FancyArrowPatch', (['(x, y)', '(x + dx, y + dy)'], {'arrowstyle': '"""->"""', 'mutation_scale': '(10)'}), "((x, y), (x + dx, y + dy), arrowstyle='->', mutation_scale=10)\n", (1382, 1444), False, 'from matplotlib.patches import FancyArrowPatch, Arc\n'), ((1468, 1516), 'matplotlib.pyplot.text', 'plt.text', (['(x + dx / 2.0)', '(y + dy / 2.0 - 0.05)', '"""x"""'], {}), "(x + dx / 2.0, y + dy / 2.0 - 0.05, 'x')\n", (1476, 1516), True, 'import matplotlib.pyplot as plt\n'), ((1542, 1619), 'matplotlib.patches.FancyArrowPatch', 'FancyArrowPatch', (['(x, y)', '(x + dx, y + dy)'], {'arrowstyle': '"""->"""', 'mutation_scale': '(10)'}), "((x, y), (x + dx, y + dy), arrowstyle='->', mutation_scale=10)\n", (1557, 1619), False, 'from matplotlib.patches import FancyArrowPatch, Arc\n'), ((1643, 1691), 'matplotlib.pyplot.text', 'plt.text', (['(x + dx / 2.0 - 0.05)', '(y + dy / 2.0)', '"""y"""'], {}), "(x + dx / 2.0 - 0.05, y + dy / 2.0, 'y')\n", (1651, 1691), True, 'import matplotlib.pyplot as plt\n'), ((1753, 1780), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""ro"""'], {'ms': '(10)'}), "(x, y, 'ro', ms=10)\n", (1761, 1780), True, 'import matplotlib.pyplot as plt\n'), ((1845, 1916), 'matplotlib.patches.FancyArrowPatch', 'FancyArrowPatch', (['(x, y)', '(x, y - L)'], {'arrowstyle': '"""->"""', 'mutation_scale': '(10)'}), "((x, y), (x, y - L), arrowstyle='->', mutation_scale=10)\n", (1860, 1916), False, 'from matplotlib.patches import FancyArrowPatch, Arc\n'), ((1919, 1964), 'matplotlib.pyplot.Line2D', 'plt.Line2D', (['(x, x)', '(y, y - L)'], {'visible': '(False)'}), '((x, x), (y, y - L), visible=False)\n', (1929, 1964), True, 'import matplotlib.pyplot as plt\n'), ((2008, 2038), 'matplotlib.pyplot.text', 'plt.text', (['(x - 0.05)', '(y - L)', '"""g"""'], {}), "(x - 0.05, y - L, 'g')\n", (2016, 2038), True, 'import matplotlib.pyplot as plt\n'), ((2121, 2198), 'matplotlib.patches.FancyArrowPatch', 'FancyArrowPatch', (['(x, y)', '(x + dx, y + dy)'], {'arrowstyle': '"""->"""', 'mutation_scale': '(10)'}), "((x, y), (x + dx, y + dy), arrowstyle='->', mutation_scale=10)\n", (2136, 2198), False, 'from matplotlib.patches import FancyArrowPatch, Arc\n'), ((2211, 2262), 'matplotlib.pyplot.Line2D', 'plt.Line2D', (['(x, x + dx)', '(y, y + dy)'], {'visible': '(False)'}), '((x, x + dx), (y, y + dy), visible=False)\n', (2221, 2262), True, 'import matplotlib.pyplot as plt\n'), ((2286, 2322), 'matplotlib.pyplot.text', 'plt.text', (['(x + dx)', '(y + dy - 0.05)', '"""v"""'], {}), "(x + dx, y + dy - 0.05, 'v')\n", (2294, 2322), True, 'import matplotlib.pyplot as plt\n'), ((2719, 2796), 'matplotlib.patches.FancyArrowPatch', 'FancyArrowPatch', (['(x, y)', '(x + dx, y + dy)'], {'arrowstyle': '"""->"""', 'mutation_scale': '(10)'}), "((x, y), (x + dx, y + dy), arrowstyle='->', mutation_scale=10)\n", (2734, 2796), False, 'from matplotlib.patches import FancyArrowPatch, Arc\n'), ((2809, 2860), 'matplotlib.pyplot.Line2D', 'plt.Line2D', (['(x, x + dx)', '(y, y + dy)'], {'visible': '(False)'}), '((x, x + dx), (y, y + dy), visible=False)\n', (2819, 2860), True, 'import matplotlib.pyplot as plt\n'), ((2888, 2924), 'matplotlib.pyplot.text', 'plt.text', (['(x + dx)', '(y + dy - 0.05)', '"""T"""'], {}), "(x + dx, y + dy - 0.05, 'T')\n", (2896, 2924), True, 'import matplotlib.pyplot as plt\n'), ((2988, 3063), 'matplotlib.pyplot.plot', 'plt.plot', (['(x, x + dx)', '(y, y + dy)'], {'linestyle': '"""--"""', 'color': '"""k"""', 'zorder': '(-1000)'}), "((x, x + dx), (y, y + dy), linestyle='--', color='k', zorder=-1000)\n", (2996, 3063), True, 'import matplotlib.pyplot as plt\n'), ((3467, 3494), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""ssto_fbd.png"""'], {}), "('ssto_fbd.png')\n", (3478, 3494), True, 'import matplotlib.pyplot as plt\n'), ((3500, 3510), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3508, 3510), True, 'import matplotlib.pyplot as plt\n'), ((2433, 2510), 'matplotlib.patches.FancyArrowPatch', 'FancyArrowPatch', (['(x, y)', '(x + dx, y + dy)'], {'arrowstyle': '"""->"""', 'mutation_scale': '(10)'}), "((x, y), (x + dx, y + dy), arrowstyle='->', mutation_scale=10)\n", (2448, 2510), False, 'from matplotlib.patches import FancyArrowPatch, Arc\n'), ((2515, 2566), 'matplotlib.pyplot.Line2D', 'plt.Line2D', (['(x, x + dx)', '(y, y + dy)'], {'visible': '(False)'}), '((x, x + dx), (y, y + dy), visible=False)\n', (2525, 2566), True, 'import matplotlib.pyplot as plt\n'), ((2598, 2634), 'matplotlib.pyplot.text', 'plt.text', (['(x + dx)', '(y + dy + 0.05)', '"""D"""'], {}), "(x + dx, y + dy + 0.05, 'D')\n", (2606, 2634), True, 'import matplotlib.pyplot as plt\n'), ((413, 427), 'numpy.diff', 'np.diff', (['l1_ys'], {}), '(l1_ys)\n', (420, 427), True, 'import numpy as np\n'), ((429, 443), 'numpy.diff', 'np.diff', (['l1_xs'], {}), '(l1_xs)\n', (436, 443), True, 'import numpy as np\n'), ((595, 609), 'numpy.diff', 'np.diff', (['l2_ys'], {}), '(l2_ys)\n', (602, 609), True, 'import numpy as np\n'), ((611, 625), 'numpy.diff', 'np.diff', (['l2_xs'], {}), '(l2_xs)\n', (618, 625), True, 'import numpy as np\n')]
# Pomito - Pomodoro timer in steroids # A simple console UI plugin import cmd import logging import click from pomito.plugins import ui # pylint: disable=invalid-name logger = logging.getLogger("pomito.plugins.ui.console") _POMODORO_SERVICE = None def _get_pomodoro_service(): """Gets pomodoro service.""" if _POMODORO_SERVICE is None: raise RuntimeError("Console.pomodoro_service is not initialized.") return _POMODORO_SERVICE def _set_pomodoro_service(pomodoro_service): """Sets pomodoro service.""" # pylint: disable=global-statement global _POMODORO_SERVICE _POMODORO_SERVICE = pomodoro_service @click.group() def pomito_shell(): """Command group for pomito interactive shell.""" pass @pomito_shell.command("start") @click.argument('task_id', type=int) def _pomito_start(task_id): """Starts a pomito session.""" pomodoro_service = _get_pomodoro_service() task = pomodoro_service.get_task_by_id(task_id) pomodoro_service.start_session(task) @pomito_shell.command("stop") def _pomito_stop(): """Stops a pomito session.""" pomodoro_service = _get_pomodoro_service() pomodoro_service.stop_session() @pomito_shell.command("list") @click.argument('task_filter', type=str, required=False) def _pomito_list(task_filter=None): """Lists available tasks.""" pomodoro_service = _get_pomodoro_service() tasks = pomodoro_service.get_tasks_by_filter(task_filter) count = 0 for t in tasks: if task_filter == None and count > 10: click.echo("\nShowing first 10 tasks, use `list *`"\ + "to show all tasks.") break click.echo(t) count += 1 @pomito_shell.command("quit") @click.pass_context def _pomito_quit(ctx): """Quit pomito shell.""" click.echo("Good bye!") ctx.exit(1) @pomito_shell.command("EOF") @click.pass_context def __pomito_eof(ctx): """Quit pomito shell for ^D.""" click.echo("Good bye!") ctx.exit(1) class Console(ui.UIPlugin, cmd.Cmd): """Interactive shell for pomito app.""" intro = "Welcome to Pomito shell.\n\ Type 'help' or '?' to list available commands." # TODO should the prompt be two lines # [<timer> <Task>] # > prompt = "pomito> " def __init__(self, pomodoro_service): self._stop_signalled = False self._message_queue = [] _set_pomodoro_service(pomodoro_service) cmd.Cmd.__init__(self) def initialize(self): pass def do_parse(self, args): """Parse pomito shell commands.""" try: pomito_shell.main(args=args.split()) except SystemExit as e: if e.code == 1: self._stop_signalled = True return def completenames(self, text, *ignored): import sys cmdname = "_pomito_" + text return [c[8:] for c in dir(sys.modules[__name__])\ if c.startswith(cmdname)] def precmd(self, line): return "parse {0}".format(line) def postcmd(self, stop, line): return self._stop_signalled def _print_message(self, msg): print(msg) return def notify_session_started(self): self._print_message("Pomodoro session started.") self._message_queue.append("Pomodoro session started.") return def notify_session_end(self, reason): self._print_message("Pomodoro session ended.") self._message_queue.append("Pomodoro session ended.") return def notify_break_started(self, break_type): self._print_message("Pomodoro break started: {0}".format(break_type)) self._message_queue.append("Pomodoro break started: {0}".format(break_type)) return def notify_break_end(self, reason): self._print_message("Pomodoro break ended: {0}".format(reason)) self._message_queue.append("Pomodoro break ended: {0}".format(reason)) return def run(self): if len(self._message_queue) > 0: print("-- msg: {0}".format(self._message_queue.pop())) try: self.cmdloop() except KeyboardInterrupt: self._print_message("Got keyboard interrupt.") return
[ "logging.getLogger", "click.argument", "click.group", "click.echo", "cmd.Cmd.__init__" ]
[((180, 226), 'logging.getLogger', 'logging.getLogger', (['"""pomito.plugins.ui.console"""'], {}), "('pomito.plugins.ui.console')\n", (197, 226), False, 'import logging\n'), ((643, 656), 'click.group', 'click.group', ([], {}), '()\n', (654, 656), False, 'import click\n'), ((773, 808), 'click.argument', 'click.argument', (['"""task_id"""'], {'type': 'int'}), "('task_id', type=int)\n", (787, 808), False, 'import click\n'), ((1212, 1267), 'click.argument', 'click.argument', (['"""task_filter"""'], {'type': 'str', 'required': '(False)'}), "('task_filter', type=str, required=False)\n", (1226, 1267), False, 'import click\n'), ((1805, 1828), 'click.echo', 'click.echo', (['"""Good bye!"""'], {}), "('Good bye!')\n", (1815, 1828), False, 'import click\n'), ((1958, 1981), 'click.echo', 'click.echo', (['"""Good bye!"""'], {}), "('Good bye!')\n", (1968, 1981), False, 'import click\n'), ((1665, 1678), 'click.echo', 'click.echo', (['t'], {}), '(t)\n', (1675, 1678), False, 'import click\n'), ((2436, 2458), 'cmd.Cmd.__init__', 'cmd.Cmd.__init__', (['self'], {}), '(self)\n', (2452, 2458), False, 'import cmd\n'), ((1539, 1617), 'click.echo', 'click.echo', (['("""\nShowing first 10 tasks, use `list *`""" + \'to show all tasks.\')'], {}), '("""\nShowing first 10 tasks, use `list *`""" + \'to show all tasks.\')\n', (1549, 1617), False, 'import click\n')]
import unittest import numpy import chainer from chainer import cuda from chainer import functions from chainer import gradient_check from chainer import testing from chainer.testing import attr @testing.parameterize(*testing.product({ 'use_cudnn': ['always', 'never'], })) class TestSpatialTransformerGrid(unittest.TestCase): def setUp(self): B = 3 self.theta = numpy.random.uniform(size=(B, 2, 3)).astype(numpy.float32) self.output_shape = (5, 6) self.grads = numpy.random.uniform( size=(B, 2) + self.output_shape).astype(self.theta.dtype) self.check_backward_options = { 'atol': 1e-4, 'rtol': 1e-3} def check_forward(self, theta, output_shape): grid = functions.spatial_transformer_grid(theta, output_shape).data theta = cuda.to_cpu(theta) B = theta.shape[0] H, W = output_shape expected = [] for b in range(B): for i in numpy.linspace(-1., 1., H): for j in numpy.linspace(-1., 1., W): coord = numpy.array([j, i, 1]) expected.append(self.theta[b].dot(coord)) expected = numpy.array( expected).reshape(B, H, W, 2).transpose(0, 3, 1, 2) testing.assert_allclose(grid, expected) self.assertEqual(grid.dtype, theta.dtype) def test_forward_cpu(self): self.check_forward(self.theta, self.output_shape) @attr.gpu def test_forward_gpu(self): self.check_forward(cuda.to_gpu(self.theta), self.output_shape) def check_backward(self, theta, output_shape, grads): with chainer.using_config('use_cudnn', self.use_cudnn): gradient_check.check_backward( functions.SpatialTransformerGrid(output_shape), (theta,), (grads,), dtype=numpy.float64, **self.check_backward_options) def test_backward_cpu(self): self.check_backward(self.theta, self.output_shape, self.grads) @attr.gpu def test_backward_gpu(self): with chainer.using_config('use_cudnn', self.use_cudnn): self.check_backward(cuda.to_gpu(self.theta), self.output_shape, cuda.to_gpu(self.grads)) testing.run_module(__name__, __file__)
[ "chainer.testing.run_module", "chainer.functions.SpatialTransformerGrid", "chainer.cuda.to_cpu", "chainer.testing.product", "numpy.linspace", "numpy.array", "numpy.random.uniform", "chainer.functions.spatial_transformer_grid", "chainer.testing.assert_allclose", "chainer.cuda.to_gpu", "chainer.us...
[((2252, 2290), 'chainer.testing.run_module', 'testing.run_module', (['__name__', '__file__'], {}), '(__name__, __file__)\n', (2270, 2290), False, 'from chainer import testing\n'), ((824, 842), 'chainer.cuda.to_cpu', 'cuda.to_cpu', (['theta'], {}), '(theta)\n', (835, 842), False, 'from chainer import cuda\n'), ((1267, 1306), 'chainer.testing.assert_allclose', 'testing.assert_allclose', (['grid', 'expected'], {}), '(grid, expected)\n', (1290, 1306), False, 'from chainer import testing\n'), ((222, 273), 'chainer.testing.product', 'testing.product', (["{'use_cudnn': ['always', 'never']}"], {}), "({'use_cudnn': ['always', 'never']})\n", (237, 273), False, 'from chainer import testing\n'), ((746, 801), 'chainer.functions.spatial_transformer_grid', 'functions.spatial_transformer_grid', (['theta', 'output_shape'], {}), '(theta, output_shape)\n', (780, 801), False, 'from chainer import functions\n'), ((969, 997), 'numpy.linspace', 'numpy.linspace', (['(-1.0)', '(1.0)', 'H'], {}), '(-1.0, 1.0, H)\n', (983, 997), False, 'import numpy\n'), ((1522, 1545), 'chainer.cuda.to_gpu', 'cuda.to_gpu', (['self.theta'], {}), '(self.theta)\n', (1533, 1545), False, 'from chainer import cuda\n'), ((1638, 1687), 'chainer.using_config', 'chainer.using_config', (['"""use_cudnn"""', 'self.use_cudnn'], {}), "('use_cudnn', self.use_cudnn)\n", (1658, 1687), False, 'import chainer\n'), ((2066, 2115), 'chainer.using_config', 'chainer.using_config', (['"""use_cudnn"""', 'self.use_cudnn'], {}), "('use_cudnn', self.use_cudnn)\n", (2086, 2115), False, 'import chainer\n'), ((392, 428), 'numpy.random.uniform', 'numpy.random.uniform', ([], {'size': '(B, 2, 3)'}), '(size=(B, 2, 3))\n', (412, 428), False, 'import numpy\n'), ((507, 560), 'numpy.random.uniform', 'numpy.random.uniform', ([], {'size': '((B, 2) + self.output_shape)'}), '(size=(B, 2) + self.output_shape)\n', (527, 560), False, 'import numpy\n'), ((1022, 1050), 'numpy.linspace', 'numpy.linspace', (['(-1.0)', '(1.0)', 'W'], {}), '(-1.0, 1.0, W)\n', (1036, 1050), False, 'import numpy\n'), ((1748, 1794), 'chainer.functions.SpatialTransformerGrid', 'functions.SpatialTransformerGrid', (['output_shape'], {}), '(output_shape)\n', (1780, 1794), False, 'from chainer import functions\n'), ((2149, 2172), 'chainer.cuda.to_gpu', 'cuda.to_gpu', (['self.theta'], {}), '(self.theta)\n', (2160, 2172), False, 'from chainer import cuda\n'), ((2225, 2248), 'chainer.cuda.to_gpu', 'cuda.to_gpu', (['self.grads'], {}), '(self.grads)\n', (2236, 2248), False, 'from chainer import cuda\n'), ((1078, 1100), 'numpy.array', 'numpy.array', (['[j, i, 1]'], {}), '([j, i, 1])\n', (1089, 1100), False, 'import numpy\n'), ((1182, 1203), 'numpy.array', 'numpy.array', (['expected'], {}), '(expected)\n', (1193, 1203), False, 'import numpy\n')]
import os import time import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable from torch.utils.data import DataLoader import torchvision.transforms as transforms import torchvision.datasets as datasets from torchvision.models import resnet152 TRAIN_TRANSFORM = transforms.Compose([ transforms.Resize(240), transforms.RandomResizedCrop(224), ]) SIZE_TRANSFORM = transforms.Compose([ transforms.Resize(240), transforms.CenterCrop(224) ]) PREPROCESSING_TRANSFORM = transforms.Compose([ transforms.ToTensor(), transforms.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)) ]) MODEL_LOCATION = 'model/transfer.model' DATA_LOCATION = 'data/hymenoptera_data/train' CLASSES = ( 'ant', 'bee', ) def train_network(): start_time = time.clock() # define network net = resnet152(pretrained=True) for parameter in net.parameters(): parameter.required_grad = False net.fc = nn.Linear(net.fc.in_features, 2) net.cuda() trainset = datasets.ImageFolder( DATA_LOCATION, transforms.Compose([TRAIN_TRANSFORM, PREPROCESSING_TRANSFORM]) ) trainloader = DataLoader(trainset, batch_size=4, shuffle=True, num_workers=2) # define loss function and optimizer criterion = nn.CrossEntropyLoss() lr = 0.001 optimizer = optim.SGD(net.parameters(), lr=lr, momentum=0.9) # stochastic gradient descent # train for _ in range(4): for _ in range(2): for data in trainloader: inputs, labels = data inputs, labels = Variable(inputs.cuda()), Variable(labels.cuda()) optimizer.zero_grad() outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() lr *= 0.2 for param_group in optimizer.param_groups: param_group['lr'] = lr # save model if MODEL_LOCATION: path = os.path.abspath(MODEL_LOCATION) print('Saving model to %s' % path) if not os.path.exists(os.path.dirname(path)): os.makedirs(os.path.dirname(path)) torch.save(net, path) print('model trained in %sms' % (time.clock() - start_time)) return net def get_network(): path = os.path.abspath(MODEL_LOCATION) if MODEL_LOCATION and os.path.exists(path): print('Loading model from file at %s' % path) net = torch.load(path).cuda() else: print('No saved model found, training a new one.') net = train_network() return net
[ "torchvision.transforms.CenterCrop", "torchvision.transforms.Compose", "os.path.exists", "torch.nn.CrossEntropyLoss", "time.clock", "torch.load", "torchvision.transforms.Resize", "os.path.dirname", "torchvision.models.resnet152", "torch.nn.Linear", "torch.utils.data.DataLoader", "os.path.abspa...
[((819, 831), 'time.clock', 'time.clock', ([], {}), '()\n', (829, 831), False, 'import time\n'), ((863, 889), 'torchvision.models.resnet152', 'resnet152', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (872, 889), False, 'from torchvision.models import resnet152\n'), ((982, 1014), 'torch.nn.Linear', 'nn.Linear', (['net.fc.in_features', '(2)'], {}), '(net.fc.in_features, 2)\n', (991, 1014), True, 'import torch.nn as nn\n'), ((1187, 1250), 'torch.utils.data.DataLoader', 'DataLoader', (['trainset'], {'batch_size': '(4)', 'shuffle': '(True)', 'num_workers': '(2)'}), '(trainset, batch_size=4, shuffle=True, num_workers=2)\n', (1197, 1250), False, 'from torch.utils.data import DataLoader\n'), ((1309, 1330), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (1328, 1330), True, 'import torch.nn as nn\n'), ((2334, 2365), 'os.path.abspath', 'os.path.abspath', (['MODEL_LOCATION'], {}), '(MODEL_LOCATION)\n', (2349, 2365), False, 'import os\n'), ((330, 352), 'torchvision.transforms.Resize', 'transforms.Resize', (['(240)'], {}), '(240)\n', (347, 352), True, 'import torchvision.transforms as transforms\n'), ((358, 391), 'torchvision.transforms.RandomResizedCrop', 'transforms.RandomResizedCrop', (['(224)'], {}), '(224)\n', (386, 391), True, 'import torchvision.transforms as transforms\n'), ((439, 461), 'torchvision.transforms.Resize', 'transforms.Resize', (['(240)'], {}), '(240)\n', (456, 461), True, 'import torchvision.transforms as transforms\n'), ((467, 493), 'torchvision.transforms.CenterCrop', 'transforms.CenterCrop', (['(224)'], {}), '(224)\n', (488, 493), True, 'import torchvision.transforms as transforms\n'), ((549, 570), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (568, 570), True, 'import torchvision.transforms as transforms\n'), ((576, 651), 'torchvision.transforms.Normalize', 'transforms.Normalize', ([], {'mean': '(0.485, 0.456, 0.406)', 'std': '(0.229, 0.224, 0.225)'}), '(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225))\n', (596, 651), True, 'import torchvision.transforms as transforms\n'), ((1100, 1162), 'torchvision.transforms.Compose', 'transforms.Compose', (['[TRAIN_TRANSFORM, PREPROCESSING_TRANSFORM]'], {}), '([TRAIN_TRANSFORM, PREPROCESSING_TRANSFORM])\n', (1118, 1162), True, 'import torchvision.transforms as transforms\n'), ((2015, 2046), 'os.path.abspath', 'os.path.abspath', (['MODEL_LOCATION'], {}), '(MODEL_LOCATION)\n', (2030, 2046), False, 'import os\n'), ((2199, 2220), 'torch.save', 'torch.save', (['net', 'path'], {}), '(net, path)\n', (2209, 2220), False, 'import torch\n'), ((2392, 2412), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (2406, 2412), False, 'import os\n'), ((2120, 2141), 'os.path.dirname', 'os.path.dirname', (['path'], {}), '(path)\n', (2135, 2141), False, 'import os\n'), ((2168, 2189), 'os.path.dirname', 'os.path.dirname', (['path'], {}), '(path)\n', (2183, 2189), False, 'import os\n'), ((2259, 2271), 'time.clock', 'time.clock', ([], {}), '()\n', (2269, 2271), False, 'import time\n'), ((2482, 2498), 'torch.load', 'torch.load', (['path'], {}), '(path)\n', (2492, 2498), False, 'import torch\n')]
""" Compute numerical solution for Poisson with background. Produces Fig. 7 from the Feldman & Cousins paper. """ import numpy as np from scipy.stats import poisson import matplotlib.pyplot as plt from gammapy.stats import ( fc_construct_acceptance_intervals_pdfs, fc_fix_limits, fc_get_limits, ) background = 3.0 n_bins_x = 100 step_width_mu = 0.005 mu_min = 0 mu_max = 50 cl = 0.90 x_bins = np.arange(0, n_bins_x) mu_bins = np.linspace(mu_min, mu_max, int(mu_max / step_width_mu + 1), endpoint=True) matrix = [poisson(mu + background).pmf(x_bins) for mu in mu_bins] acceptance_intervals = fc_construct_acceptance_intervals_pdfs(matrix, cl) LowerLimitNum, UpperLimitNum, _ = fc_get_limits(mu_bins, x_bins, acceptance_intervals) fc_fix_limits(LowerLimitNum, UpperLimitNum) fig = plt.figure() ax = fig.add_subplot(111) plt.plot(UpperLimitNum, mu_bins, ls="-", color="red") plt.plot(LowerLimitNum, mu_bins, ls="-", color="red") plt.grid(True) ax.yaxis.set_label_coords(-0.08, 0.5) plt.xticks(range(15)) plt.yticks(range(15)) ax.set_xlabel(r"Measured n") ax.set_ylabel(r"Signal Mean $\mu$") plt.axis([0, 15, 0, 15]) plt.show()
[ "gammapy.stats.fc_fix_limits", "matplotlib.pyplot.grid", "matplotlib.pyplot.plot", "gammapy.stats.fc_get_limits", "matplotlib.pyplot.figure", "scipy.stats.poisson", "matplotlib.pyplot.axis", "gammapy.stats.fc_construct_acceptance_intervals_pdfs", "numpy.arange", "matplotlib.pyplot.show" ]
[((409, 431), 'numpy.arange', 'np.arange', (['(0)', 'n_bins_x'], {}), '(0, n_bins_x)\n', (418, 431), True, 'import numpy as np\n'), ((609, 659), 'gammapy.stats.fc_construct_acceptance_intervals_pdfs', 'fc_construct_acceptance_intervals_pdfs', (['matrix', 'cl'], {}), '(matrix, cl)\n', (647, 659), False, 'from gammapy.stats import fc_construct_acceptance_intervals_pdfs, fc_fix_limits, fc_get_limits\n'), ((695, 747), 'gammapy.stats.fc_get_limits', 'fc_get_limits', (['mu_bins', 'x_bins', 'acceptance_intervals'], {}), '(mu_bins, x_bins, acceptance_intervals)\n', (708, 747), False, 'from gammapy.stats import fc_construct_acceptance_intervals_pdfs, fc_fix_limits, fc_get_limits\n'), ((749, 792), 'gammapy.stats.fc_fix_limits', 'fc_fix_limits', (['LowerLimitNum', 'UpperLimitNum'], {}), '(LowerLimitNum, UpperLimitNum)\n', (762, 792), False, 'from gammapy.stats import fc_construct_acceptance_intervals_pdfs, fc_fix_limits, fc_get_limits\n'), ((800, 812), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (810, 812), True, 'import matplotlib.pyplot as plt\n'), ((840, 893), 'matplotlib.pyplot.plot', 'plt.plot', (['UpperLimitNum', 'mu_bins'], {'ls': '"""-"""', 'color': '"""red"""'}), "(UpperLimitNum, mu_bins, ls='-', color='red')\n", (848, 893), True, 'import matplotlib.pyplot as plt\n'), ((894, 947), 'matplotlib.pyplot.plot', 'plt.plot', (['LowerLimitNum', 'mu_bins'], {'ls': '"""-"""', 'color': '"""red"""'}), "(LowerLimitNum, mu_bins, ls='-', color='red')\n", (902, 947), True, 'import matplotlib.pyplot as plt\n'), ((949, 963), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (957, 963), True, 'import matplotlib.pyplot as plt\n'), ((1111, 1135), 'matplotlib.pyplot.axis', 'plt.axis', (['[0, 15, 0, 15]'], {}), '([0, 15, 0, 15])\n', (1119, 1135), True, 'import matplotlib.pyplot as plt\n'), ((1136, 1146), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1144, 1146), True, 'import matplotlib.pyplot as plt\n'), ((529, 553), 'scipy.stats.poisson', 'poisson', (['(mu + background)'], {}), '(mu + background)\n', (536, 553), False, 'from scipy.stats import poisson\n')]
# Copyright (C) 2019 by eHealth Africa : http://www.eHealthAfrica.org # # See the NOTICE file distributed with this work for additional information # regarding copyright ownership. # # 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. import pytest from aether.python.tests import ( EXAMPLE_ALL_TYPES, EXAMPLE_ANNOTATED_SCHEMA, EXAMPLE_AUTOGEN_SCHEMA, EXAMPLE_SIMPLE_SCHEMA ) from aether.python.avro.schema import Node from aether.python.avro.generation import SampleGenerator @pytest.mark.unit @pytest.fixture(scope='module') def AutoSchema(): return Node(EXAMPLE_AUTOGEN_SCHEMA) @pytest.mark.unit @pytest.fixture(scope='module') def SimpleSchema(): return Node(EXAMPLE_SIMPLE_SCHEMA) @pytest.mark.unit @pytest.fixture(scope='module') def ComplexSchema(): return Node(EXAMPLE_ANNOTATED_SCHEMA) @pytest.mark.unit @pytest.fixture(scope='function') def SimpleGenerator(): return SampleGenerator(EXAMPLE_SIMPLE_SCHEMA) @pytest.mark.unit @pytest.fixture(scope='function') def ComplexGenerator(): return SampleGenerator(EXAMPLE_ANNOTATED_SCHEMA) @pytest.mark.unit @pytest.fixture(scope='function') def AllTypesGenerator(): return SampleGenerator(EXAMPLE_ALL_TYPES)
[ "pytest.fixture", "aether.python.avro.schema.Node", "aether.python.avro.generation.SampleGenerator" ]
[((1011, 1041), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (1025, 1041), False, 'import pytest\n'), ((1121, 1151), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (1135, 1151), False, 'import pytest\n'), ((1232, 1262), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (1246, 1262), False, 'import pytest\n'), ((1347, 1379), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (1361, 1379), False, 'import pytest\n'), ((1474, 1506), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (1488, 1506), False, 'import pytest\n'), ((1605, 1637), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""function"""'}), "(scope='function')\n", (1619, 1637), False, 'import pytest\n'), ((1071, 1099), 'aether.python.avro.schema.Node', 'Node', (['EXAMPLE_AUTOGEN_SCHEMA'], {}), '(EXAMPLE_AUTOGEN_SCHEMA)\n', (1075, 1099), False, 'from aether.python.avro.schema import Node\n'), ((1183, 1210), 'aether.python.avro.schema.Node', 'Node', (['EXAMPLE_SIMPLE_SCHEMA'], {}), '(EXAMPLE_SIMPLE_SCHEMA)\n', (1187, 1210), False, 'from aether.python.avro.schema import Node\n'), ((1295, 1325), 'aether.python.avro.schema.Node', 'Node', (['EXAMPLE_ANNOTATED_SCHEMA'], {}), '(EXAMPLE_ANNOTATED_SCHEMA)\n', (1299, 1325), False, 'from aether.python.avro.schema import Node\n'), ((1414, 1452), 'aether.python.avro.generation.SampleGenerator', 'SampleGenerator', (['EXAMPLE_SIMPLE_SCHEMA'], {}), '(EXAMPLE_SIMPLE_SCHEMA)\n', (1429, 1452), False, 'from aether.python.avro.generation import SampleGenerator\n'), ((1542, 1583), 'aether.python.avro.generation.SampleGenerator', 'SampleGenerator', (['EXAMPLE_ANNOTATED_SCHEMA'], {}), '(EXAMPLE_ANNOTATED_SCHEMA)\n', (1557, 1583), False, 'from aether.python.avro.generation import SampleGenerator\n'), ((1674, 1708), 'aether.python.avro.generation.SampleGenerator', 'SampleGenerator', (['EXAMPLE_ALL_TYPES'], {}), '(EXAMPLE_ALL_TYPES)\n', (1689, 1708), False, 'from aether.python.avro.generation import SampleGenerator\n')]
import os import argparse import pandas as pd import numpy as np import sys import json DEFAULT_PROJECT_REPO = os.path.sep.join(__file__.split(os.path.sep)[:-2]) PROJECT_REPO_DIR = os.path.abspath( os.environ.get('PROJECT_REPO_DIR', DEFAULT_PROJECT_REPO)) sys.path.append(os.path.join(PROJECT_REPO_DIR, 'src')) from feature_transformation import (parse_id_cols, remove_col_names_from_list_if_not_in_df, parse_time_col, parse_feature_cols) def merge_data_dicts(data_dicts_list): # get a single consolidated data dict for all features and another for outcomes # combine all the labs, demographics and vitals jsons into a single json features_data_dict = dict() features_data_dict['schema']= dict() features_dict_merged = [] for data_dict in data_dicts_list: features_dict_merged += data_dict['schema']['fields'] feat_names = list() features_data_dict['schema']['fields'] = [] for feat_dict in features_dict_merged: if feat_dict['name'] not in feat_names: features_data_dict['schema']['fields'].append(feat_dict) feat_names.append(feat_dict['name']) return features_data_dict def get_all_features_data(labs_df, labs_data_dict, vitals_df, vitals_data_dict, demographics_df, demographics_data_dict): '''Returns the merged labs, vitals and demographics features into a single table and the data dict''' time_col = parse_time_col(vitals_data_dict) id_cols = parse_id_cols(vitals_data_dict) # merge the labs and vitals highfreq_df = pd.merge(vitals_df, labs_df, on=id_cols +[time_col], how='outer') highfreq_data_dict = merge_data_dicts([labs_data_dict, vitals_data_dict]) highfreq_data_dict['fields'] = highfreq_data_dict['schema']['fields'] cols_to_keep = parse_id_cols(highfreq_data_dict) + [parse_time_col(highfreq_data_dict)] + parse_feature_cols(highfreq_data_dict) highfreq_df = highfreq_df[cols_to_keep].copy() # merge the highfrequency features with the static features features_df = pd.merge(highfreq_df, demographics_df, on=id_cols, how='inner') features_data_dict = merge_data_dicts([highfreq_data_dict, demographics_data_dict]) features_data_dict['fields'] = features_data_dict['schema']['fields'] return features_df, features_data_dict if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--collapsed_tslice_folder', type=str, help='folder where collapsed features from each tslice are stored') parser.add_argument('--tslice_folder', type=str, help='folder where raw features and static features from each tslice are stored') parser.add_argument('--tslice_list', type=str, help='list of all the tslices used for training the classifier') parser.add_argument('--static_data_dict_dir', type=str, help='directory where data dict for demographics and outcomes') parser.add_argument('--output_dir', type=str, help='folder to save merged features and outcomes from all tslices') args = parser.parse_args() # get all the collapsed labs, collapsed vitals, demographics and outcomes data dicts with open(os.path.join(args.static_data_dict_dir, 'Spec-Demographics.json'), 'r') as f1: demographics_data_dict = json.load(f1) demographics_data_dict['fields'] = demographics_data_dict['schema']['fields'] with open(os.path.join(args.static_data_dict_dir, 'Spec-Outcomes_TransferToICU.json'), 'r') as f2: outcomes_data_dict = json.load(f2) id_cols = parse_id_cols(demographics_data_dict) # get all the collapsed labs, collapsed vitals, demographics and outcomes in all the tslice folders print('Merging collapsed vitals, collapsed labs, demographics and outcomes in all the tslice folders = %s into a single features table and a single outcomes table...'%args.tslice_list) features_df_all_slices_list = list() outcomes_df_all_slices_list = list() mews_df_all_slices_list = list() for tslice in args.tslice_list.split(' '): curr_tslice_folder = args.tslice_folder+tslice curr_collapsed_tslice_folder = args.collapsed_tslice_folder+tslice collapsed_labs_df = pd.read_csv(os.path.join(curr_collapsed_tslice_folder, 'CollapsedLabsPerSequence.csv')) collapsed_vitals_df = pd.read_csv(os.path.join(curr_collapsed_tslice_folder, 'CollapsedVitalsPerSequence.csv')) demographics_df = pd.read_csv(os.path.join(curr_tslice_folder, 'demographics_before_icu_filtered_%s_hours.csv'%tslice)) mews_df = pd.read_csv(os.path.join(curr_collapsed_tslice_folder, 'MewsScoresPerSequence.csv')) collapsed_vitals_labs_df = pd.merge(collapsed_vitals_df, collapsed_labs_df, on=id_cols, how='inner') # merge the collapsed feaatures and static features in each tslice features_df = pd.merge(collapsed_vitals_labs_df, demographics_df, on=id_cols, how='inner') outcomes_df = pd.read_csv(os.path.join(curr_tslice_folder, 'clinical_deterioration_outcomes_filtered_%s_hours.csv'%tslice)) feature_cols = features_df.columns outcome_cols = outcomes_df.columns mews_cols = mews_df.columns # append fearures from all tslices features_df_all_slices_list.append(features_df.values) outcomes_df_all_slices_list.append(outcomes_df.values) mews_df_all_slices_list.append(mews_df.values) del collapsed_vitals_labs_df features_df_all_slices = pd.DataFrame(np.concatenate(features_df_all_slices_list), columns=feature_cols) outcomes_df_all_slices = pd.DataFrame(np.concatenate(outcomes_df_all_slices_list), columns=outcome_cols) mews_df_all_slices = pd.DataFrame(np.concatenate(mews_df_all_slices_list), columns=mews_cols) # get collapsed vitals and labs dict print('Merging collapsed vitals, collapsed labs, demographics and outcomes data dicts into a single features data dict and a single outcomes data dict...') with open(os.path.join(curr_collapsed_tslice_folder, 'Spec_CollapsedLabsPerSequence.json'), 'r') as f3: collapsed_labs_data_dict = json.load(f3) with open(os.path.join(curr_collapsed_tslice_folder, 'Spec_CollapsedVitalsPerSequence.json'), 'r') as f4: collapsed_vitals_data_dict = json.load(f4) with open(os.path.join(curr_collapsed_tslice_folder, 'Spec_MewsScoresPerSequence.json'), 'r') as f5: mews_data_dict = json.load(f5) # get a single consolidated data dict for all features and another for outcomes # combine all the labs, demographics and vitals jsons into a single json features_data_dict = dict() features_data_dict['schema']= dict() features_dict_merged = collapsed_labs_data_dict['schema']['fields'] + collapsed_vitals_data_dict['schema']['fields'] + demographics_data_dict['schema']['fields'] feat_names = list() features_data_dict['schema']['fields'] = [] for feat_dict in features_dict_merged: if feat_dict['name'] not in feat_names: features_data_dict['schema']['fields'].append(feat_dict) feat_names.append(feat_dict['name']) # convert the features to numpy float 32 to avoid memory issues feature_cols = parse_feature_cols(features_data_dict['schema']) feature_type_dict = dict.fromkeys(feature_cols) for k in feature_type_dict.keys(): feature_type_dict[k] = np.float32 features_df_all_slices = features_df_all_slices.astype(feature_type_dict) # save to disk features_csv = os.path.join(args.output_dir, 'features.csv') outcomes_csv = os.path.join(args.output_dir, 'outcomes.csv') mews_csv = os.path.join(args.output_dir, 'mews.csv') features_json = os.path.join(args.output_dir, 'Spec_features.json') outcomes_json = os.path.join(args.output_dir, 'Spec_outcomes.json') mews_json = os.path.join(args.output_dir, 'Spec_mews.json') print('saving features and outcomes to :\n%s\n%s\n%s'%(features_csv, outcomes_csv, mews_csv)) features_df_all_slices.to_csv(features_csv, index=False) outcomes_df_all_slices.to_csv(outcomes_csv, index=False) mews_df_all_slices.to_csv(mews_csv, index=False) print('saving features and outcomes dict to :\n%s\n%s\n%s'%(features_json, outcomes_json, mews_json)) with open(features_json, "w") as outfile_feats: json.dump(features_data_dict, outfile_feats) with open(outcomes_json, "w") as outfile_outcomes: json.dump(outcomes_data_dict, outfile_outcomes) with open(mews_json, "w") as outfile_mews: json.dump(mews_data_dict, outfile_mews)
[ "argparse.ArgumentParser", "feature_transformation.parse_id_cols", "pandas.merge", "os.path.join", "os.environ.get", "numpy.concatenate", "feature_transformation.parse_feature_cols", "json.load", "feature_transformation.parse_time_col", "json.dump" ]
[((202, 258), 'os.environ.get', 'os.environ.get', (['"""PROJECT_REPO_DIR"""', 'DEFAULT_PROJECT_REPO'], {}), "('PROJECT_REPO_DIR', DEFAULT_PROJECT_REPO)\n", (216, 258), False, 'import os\n'), ((277, 314), 'os.path.join', 'os.path.join', (['PROJECT_REPO_DIR', '"""src"""'], {}), "(PROJECT_REPO_DIR, 'src')\n", (289, 314), False, 'import os\n'), ((1416, 1448), 'feature_transformation.parse_time_col', 'parse_time_col', (['vitals_data_dict'], {}), '(vitals_data_dict)\n', (1430, 1448), False, 'from feature_transformation import parse_id_cols, remove_col_names_from_list_if_not_in_df, parse_time_col, parse_feature_cols\n'), ((1463, 1494), 'feature_transformation.parse_id_cols', 'parse_id_cols', (['vitals_data_dict'], {}), '(vitals_data_dict)\n', (1476, 1494), False, 'from feature_transformation import parse_id_cols, remove_col_names_from_list_if_not_in_df, parse_time_col, parse_feature_cols\n'), ((1546, 1612), 'pandas.merge', 'pd.merge', (['vitals_df', 'labs_df'], {'on': '(id_cols + [time_col])', 'how': '"""outer"""'}), "(vitals_df, labs_df, on=id_cols + [time_col], how='outer')\n", (1554, 1612), True, 'import pandas as pd\n'), ((2032, 2095), 'pandas.merge', 'pd.merge', (['highfreq_df', 'demographics_df'], {'on': 'id_cols', 'how': '"""inner"""'}), "(highfreq_df, demographics_df, on=id_cols, how='inner')\n", (2040, 2095), True, 'import pandas as pd\n'), ((2344, 2369), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2367, 2369), False, 'import argparse\n'), ((3569, 3606), 'feature_transformation.parse_id_cols', 'parse_id_cols', (['demographics_data_dict'], {}), '(demographics_data_dict)\n', (3582, 3606), False, 'from feature_transformation import parse_id_cols, remove_col_names_from_list_if_not_in_df, parse_time_col, parse_feature_cols\n'), ((7250, 7298), 'feature_transformation.parse_feature_cols', 'parse_feature_cols', (["features_data_dict['schema']"], {}), "(features_data_dict['schema'])\n", (7268, 7298), False, 'from feature_transformation import parse_id_cols, remove_col_names_from_list_if_not_in_df, parse_time_col, parse_feature_cols\n'), ((7553, 7598), 'os.path.join', 'os.path.join', (['args.output_dir', '"""features.csv"""'], {}), "(args.output_dir, 'features.csv')\n", (7565, 7598), False, 'import os\n'), ((7618, 7663), 'os.path.join', 'os.path.join', (['args.output_dir', '"""outcomes.csv"""'], {}), "(args.output_dir, 'outcomes.csv')\n", (7630, 7663), False, 'import os\n'), ((7679, 7720), 'os.path.join', 'os.path.join', (['args.output_dir', '"""mews.csv"""'], {}), "(args.output_dir, 'mews.csv')\n", (7691, 7720), False, 'import os\n'), ((7741, 7792), 'os.path.join', 'os.path.join', (['args.output_dir', '"""Spec_features.json"""'], {}), "(args.output_dir, 'Spec_features.json')\n", (7753, 7792), False, 'import os\n'), ((7813, 7864), 'os.path.join', 'os.path.join', (['args.output_dir', '"""Spec_outcomes.json"""'], {}), "(args.output_dir, 'Spec_outcomes.json')\n", (7825, 7864), False, 'import os\n'), ((7881, 7928), 'os.path.join', 'os.path.join', (['args.output_dir', '"""Spec_mews.json"""'], {}), "(args.output_dir, 'Spec_mews.json')\n", (7893, 7928), False, 'import os\n'), ((1858, 1896), 'feature_transformation.parse_feature_cols', 'parse_feature_cols', (['highfreq_data_dict'], {}), '(highfreq_data_dict)\n', (1876, 1896), False, 'from feature_transformation import parse_id_cols, remove_col_names_from_list_if_not_in_df, parse_time_col, parse_feature_cols\n'), ((3307, 3320), 'json.load', 'json.load', (['f1'], {}), '(f1)\n', (3316, 3320), False, 'import json\n'), ((3536, 3549), 'json.load', 'json.load', (['f2'], {}), '(f2)\n', (3545, 3549), False, 'import json\n'), ((4698, 4771), 'pandas.merge', 'pd.merge', (['collapsed_vitals_df', 'collapsed_labs_df'], {'on': 'id_cols', 'how': '"""inner"""'}), "(collapsed_vitals_df, collapsed_labs_df, on=id_cols, how='inner')\n", (4706, 4771), True, 'import pandas as pd\n'), ((4870, 4946), 'pandas.merge', 'pd.merge', (['collapsed_vitals_labs_df', 'demographics_df'], {'on': 'id_cols', 'how': '"""inner"""'}), "(collapsed_vitals_labs_df, demographics_df, on=id_cols, how='inner')\n", (4878, 4946), True, 'import pandas as pd\n'), ((5518, 5561), 'numpy.concatenate', 'np.concatenate', (['features_df_all_slices_list'], {}), '(features_df_all_slices_list)\n', (5532, 5561), True, 'import numpy as np\n'), ((5627, 5670), 'numpy.concatenate', 'np.concatenate', (['outcomes_df_all_slices_list'], {}), '(outcomes_df_all_slices_list)\n', (5641, 5670), True, 'import numpy as np\n'), ((5732, 5771), 'numpy.concatenate', 'np.concatenate', (['mews_df_all_slices_list'], {}), '(mews_df_all_slices_list)\n', (5746, 5771), True, 'import numpy as np\n'), ((6141, 6154), 'json.load', 'json.load', (['f3'], {}), '(f3)\n', (6150, 6154), False, 'import json\n'), ((6303, 6316), 'json.load', 'json.load', (['f4'], {}), '(f4)\n', (6312, 6316), False, 'import json\n'), ((6452, 6465), 'json.load', 'json.load', (['f5'], {}), '(f5)\n', (6461, 6465), False, 'import json\n'), ((8374, 8418), 'json.dump', 'json.dump', (['features_data_dict', 'outfile_feats'], {}), '(features_data_dict, outfile_feats)\n', (8383, 8418), False, 'import json\n'), ((8483, 8530), 'json.dump', 'json.dump', (['outcomes_data_dict', 'outfile_outcomes'], {}), '(outcomes_data_dict, outfile_outcomes)\n', (8492, 8530), False, 'import json\n'), ((8591, 8630), 'json.dump', 'json.dump', (['mews_data_dict', 'outfile_mews'], {}), '(mews_data_dict, outfile_mews)\n', (8600, 8630), False, 'import json\n'), ((1783, 1816), 'feature_transformation.parse_id_cols', 'parse_id_cols', (['highfreq_data_dict'], {}), '(highfreq_data_dict)\n', (1796, 1816), False, 'from feature_transformation import parse_id_cols, remove_col_names_from_list_if_not_in_df, parse_time_col, parse_feature_cols\n'), ((3195, 3260), 'os.path.join', 'os.path.join', (['args.static_data_dict_dir', '"""Spec-Demographics.json"""'], {}), "(args.static_data_dict_dir, 'Spec-Demographics.json')\n", (3207, 3260), False, 'import os\n'), ((3418, 3493), 'os.path.join', 'os.path.join', (['args.static_data_dict_dir', '"""Spec-Outcomes_TransferToICU.json"""'], {}), "(args.static_data_dict_dir, 'Spec-Outcomes_TransferToICU.json')\n", (3430, 3493), False, 'import os\n'), ((4236, 4310), 'os.path.join', 'os.path.join', (['curr_collapsed_tslice_folder', '"""CollapsedLabsPerSequence.csv"""'], {}), "(curr_collapsed_tslice_folder, 'CollapsedLabsPerSequence.csv')\n", (4248, 4310), False, 'import os\n'), ((4354, 4430), 'os.path.join', 'os.path.join', (['curr_collapsed_tslice_folder', '"""CollapsedVitalsPerSequence.csv"""'], {}), "(curr_collapsed_tslice_folder, 'CollapsedVitalsPerSequence.csv')\n", (4366, 4430), False, 'import os\n'), ((4470, 4565), 'os.path.join', 'os.path.join', (['curr_tslice_folder', "('demographics_before_icu_filtered_%s_hours.csv' % tslice)"], {}), "(curr_tslice_folder, \n 'demographics_before_icu_filtered_%s_hours.csv' % tslice)\n", (4482, 4565), False, 'import os\n'), ((4590, 4661), 'os.path.join', 'os.path.join', (['curr_collapsed_tslice_folder', '"""MewsScoresPerSequence.csv"""'], {}), "(curr_collapsed_tslice_folder, 'MewsScoresPerSequence.csv')\n", (4602, 4661), False, 'import os\n'), ((4981, 5084), 'os.path.join', 'os.path.join', (['curr_tslice_folder', "('clinical_deterioration_outcomes_filtered_%s_hours.csv' % tslice)"], {}), "(curr_tslice_folder, \n 'clinical_deterioration_outcomes_filtered_%s_hours.csv' % tslice)\n", (4993, 5084), False, 'import os\n'), ((6012, 6097), 'os.path.join', 'os.path.join', (['curr_collapsed_tslice_folder', '"""Spec_CollapsedLabsPerSequence.json"""'], {}), "(curr_collapsed_tslice_folder, 'Spec_CollapsedLabsPerSequence.json'\n )\n", (6024, 6097), False, 'import os\n'), ((6170, 6256), 'os.path.join', 'os.path.join', (['curr_collapsed_tslice_folder', '"""Spec_CollapsedVitalsPerSequence.json"""'], {}), "(curr_collapsed_tslice_folder,\n 'Spec_CollapsedVitalsPerSequence.json')\n", (6182, 6256), False, 'import os\n'), ((6336, 6413), 'os.path.join', 'os.path.join', (['curr_collapsed_tslice_folder', '"""Spec_MewsScoresPerSequence.json"""'], {}), "(curr_collapsed_tslice_folder, 'Spec_MewsScoresPerSequence.json')\n", (6348, 6413), False, 'import os\n'), ((1820, 1854), 'feature_transformation.parse_time_col', 'parse_time_col', (['highfreq_data_dict'], {}), '(highfreq_data_dict)\n', (1834, 1854), False, 'from feature_transformation import parse_id_cols, remove_col_names_from_list_if_not_in_df, parse_time_col, parse_feature_cols\n')]
import frappe from frappe.desk.reportview import get_match_cond, get_filters_cond from frappe.utils import unique @frappe.whitelist() def get_sales_person(doctype, txt, searchfield, start, page_len, filters): conditions = [] sales_persons = frappe.db.sql(""" SELECT SP.name as name from `tabSales Person` AS SP INNER JOIN `tabSales Team` AS ST ON ST.sales_person = SP.name INNER JOIN `tabSales Invoice` AS SI ON SI.name = ST.parent and SI.docstatus = 1 and SI.agent_commision_record = 0 WHERE SP.enabled = 1 """, as_dict=1) sales_persons_has_si = [] for i in sales_persons: if i.name not in sales_persons_has_si: sales_persons_has_si.append(i.name) return frappe.db.sql("""select SP.name from `tabSales Person` AS SP where SP.enabled = 1 and SP.name like %(txt)s and SP.name in {names} {fcond} {mcond} order by if(locate(%(_txt)s, SP.name), locate(%(_txt)s, SP.name), 99999), SP.idx desc, SP.name limit %(start)s, %(page_len)s""".format(**{ 'fcond': get_filters_cond(doctype, filters, conditions), 'names': tuple(sales_persons_has_si), 'mcond': get_match_cond(doctype) }), { 'txt': "%%%s%%" % txt, '_txt': txt.replace("%", ""), 'start': start, 'page_len': page_len }) def get_fields(doctype, fields=[]): meta = frappe.get_meta(doctype) fields.extend(meta.get_search_fields()) if meta.title_field and not meta.title_field.strip() in fields: fields.insert(1, meta.title_field.strip()) return unique(fields)
[ "frappe.utils.unique", "frappe.whitelist", "frappe.desk.reportview.get_filters_cond", "frappe.db.sql", "frappe.desk.reportview.get_match_cond", "frappe.get_meta" ]
[((115, 133), 'frappe.whitelist', 'frappe.whitelist', ([], {}), '()\n', (131, 133), False, 'import frappe\n'), ((249, 597), 'frappe.db.sql', 'frappe.db.sql', (['""" SELECT SP.name as name from `tabSales Person` AS SP \n INNER JOIN `tabSales Team` AS ST ON ST.sales_person = SP.name\n INNER JOIN `tabSales Invoice` AS SI ON SI.name = ST.parent and SI.docstatus = 1 and SI.agent_commision_record = 0\n WHERE SP.enabled = 1 """'], {'as_dict': '(1)'}), '(\n """ SELECT SP.name as name from `tabSales Person` AS SP \n INNER JOIN `tabSales Team` AS ST ON ST.sales_person = SP.name\n INNER JOIN `tabSales Invoice` AS SI ON SI.name = ST.parent and SI.docstatus = 1 and SI.agent_commision_record = 0\n WHERE SP.enabled = 1 """\n , as_dict=1)\n', (262, 597), False, 'import frappe\n'), ((1478, 1502), 'frappe.get_meta', 'frappe.get_meta', (['doctype'], {}), '(doctype)\n', (1493, 1502), False, 'import frappe\n'), ((1679, 1693), 'frappe.utils.unique', 'unique', (['fields'], {}), '(fields)\n', (1685, 1693), False, 'from frappe.utils import unique\n'), ((1155, 1201), 'frappe.desk.reportview.get_filters_cond', 'get_filters_cond', (['doctype', 'filters', 'conditions'], {}), '(doctype, filters, conditions)\n', (1171, 1201), False, 'from frappe.desk.reportview import get_match_cond, get_filters_cond\n'), ((1266, 1289), 'frappe.desk.reportview.get_match_cond', 'get_match_cond', (['doctype'], {}), '(doctype)\n', (1280, 1289), False, 'from frappe.desk.reportview import get_match_cond, get_filters_cond\n')]
import os from flask import Flask from flask_cache import Cache from flask_login import LoginManager import dmapiclient from dmutils import init_app, init_frontend_app from dmcontent.content_loader import ContentLoader from config import configs cache = Cache() login_manager = LoginManager() data_api_client = dmapiclient.DataAPIClient() content_loader = ContentLoader('app/content') content_loader.load_manifest('g-cloud-6', 'services', 'search_filters') content_loader.load_manifest('g-cloud-6', 'services', 'display_service') content_loader.load_manifest('digital-outcomes-and-specialists', 'briefs', 'display_brief') content_loader.load_manifest('digital-service-professionals', 'briefs', 'display_brief') def create_app(config_name): asset_path = os.environ.get('ASSET_PATH', configs[config_name].ASSET_PATH) application = Flask(__name__, static_url_path=asset_path) init_app( application, configs[config_name], data_api_client=data_api_client, login_manager=login_manager, cache=cache, ) from .main import main as main_blueprint from .status import status as status_blueprint from .buyers import buyers as buyers_blueprint url_prefix = application.config['URL_PREFIX'] application.register_blueprint(status_blueprint, url_prefix=url_prefix) application.register_blueprint(main_blueprint, url_prefix=url_prefix) application.register_blueprint(buyers_blueprint, url_prefix=url_prefix) login_manager.login_view = 'main.render_login' login_manager.login_message_category = "must_login" init_frontend_app(application, data_api_client, login_manager) return application
[ "flask_login.LoginManager", "flask_cache.Cache", "flask.Flask", "dmutils.init_frontend_app", "os.environ.get", "dmutils.init_app", "dmcontent.content_loader.ContentLoader", "dmapiclient.DataAPIClient" ]
[((258, 265), 'flask_cache.Cache', 'Cache', ([], {}), '()\n', (263, 265), False, 'from flask_cache import Cache\n'), ((282, 296), 'flask_login.LoginManager', 'LoginManager', ([], {}), '()\n', (294, 296), False, 'from flask_login import LoginManager\n'), ((315, 342), 'dmapiclient.DataAPIClient', 'dmapiclient.DataAPIClient', ([], {}), '()\n', (340, 342), False, 'import dmapiclient\n'), ((361, 389), 'dmcontent.content_loader.ContentLoader', 'ContentLoader', (['"""app/content"""'], {}), "('app/content')\n", (374, 389), False, 'from dmcontent.content_loader import ContentLoader\n'), ((764, 825), 'os.environ.get', 'os.environ.get', (['"""ASSET_PATH"""', 'configs[config_name].ASSET_PATH'], {}), "('ASSET_PATH', configs[config_name].ASSET_PATH)\n", (778, 825), False, 'import os\n'), ((844, 887), 'flask.Flask', 'Flask', (['__name__'], {'static_url_path': 'asset_path'}), '(__name__, static_url_path=asset_path)\n', (849, 887), False, 'from flask import Flask\n'), ((893, 1015), 'dmutils.init_app', 'init_app', (['application', 'configs[config_name]'], {'data_api_client': 'data_api_client', 'login_manager': 'login_manager', 'cache': 'cache'}), '(application, configs[config_name], data_api_client=data_api_client,\n login_manager=login_manager, cache=cache)\n', (901, 1015), False, 'from dmutils import init_app, init_frontend_app\n'), ((1597, 1659), 'dmutils.init_frontend_app', 'init_frontend_app', (['application', 'data_api_client', 'login_manager'], {}), '(application, data_api_client, login_manager)\n', (1614, 1659), False, 'from dmutils import init_app, init_frontend_app\n')]
#!/usr/bin/python import subprocess import os.path import platform def git(*args): return subprocess.check_call(['git'] + list(args)) def gitupdate(repo, mPath): if os.path.exists(mPath) == False: git("clone", repo, mPath) else: git("pull", repo, mPath) def Restore(*args): return subprocess.check_call(['dotnet', 'restore'] + list(args)) print(platform.system()) gitupdate("https://github.com/kozit/kozit.git", "kozit/") gitupdate("https://github.com/kozit/kozitScript.git", "kozitScript/") gitupdate("https://github.com/kozit/libraries.git", "libraries/") gitupdate("https://github.com/kozit/installer.git", "installer/")
[ "platform.system" ]
[((382, 399), 'platform.system', 'platform.system', ([], {}), '()\n', (397, 399), False, 'import platform\n')]
#------------------------------------------------------------------------------- # Name: setup.py # Purpose: Standard module installation script # Licence: MIT License # This file is subject to the terms and conditions of the MIT License. # For further details, please refer to LICENSE.txt #------------------------------------------------------------------------------- """ This script will install the PyZDDE library into your Lib/site-packages directory as a standard Python module. It can then be imported like any other module package. """ from setuptools import setup, find_packages with open('README.rst') as fh: long_description = fh.read() setup( name='PyZDDE', version='2.0.3', description='Zemax / OpticStudio standalone extension using Python', long_description=long_description, author='<NAME>', author_email='<EMAIL>', license='MIT', keywords='zemax opticstudio extensions dde optics', url='https://github.com/indranilsinharoy/PyZDDE', packages=find_packages(), include_package_data=True, classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Science/Research', 'Natural Language :: English', 'Environment :: Win32 (MS Windows)', 'License :: OSI Approved :: MIT License', 'Operating System :: Microsoft :: Windows :: Windows XP', 'Operating System :: Microsoft :: Windows :: Windows 7', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Scientific/Engineering', ], )
[ "setuptools.find_packages" ]
[((1047, 1062), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (1060, 1062), False, 'from setuptools import setup, find_packages\n')]
# -*- coding: utf-8 -*- from jetfactory.controller import BaseController, Injector, route, input_load, output_dump from jetfactory.schema import ParamsSchema from jet_guestbook.service import VisitService, VisitorService from jet_guestbook.schema import Visit, Visitor, VisitNew class Controller(BaseController): def __init__(self): self.visit = VisitService() self.visitor = VisitorService() self.log.debug('Guestbook opening') def on_ready(self): self.log.debug(f'Guestbook opened at {self.pkg.path}') async def on_request(self, request): self.log.debug(f'Request received: {request}') @route('/', 'GET', 'List of entries') @input_load(query=ParamsSchema) @output_dump(Visit, many=True) async def visits_get(self, query): return await self.visit.get_many(**query) @route('/visitors', 'GET', 'List of visitors') @input_load(query=ParamsSchema) @output_dump(Visitor, many=True) async def visitors_get(self, query): return await self.visitor.get_many(query) @route('/visitors/<visitor_id>', 'GET', 'Visitor details') @output_dump(Visitor) async def visitor_get(self, visitor_id): return await self.visitor.get_by_pk(visitor_id) @route('/visitors/<visitor_id>/visits', 'GET', 'Visits by visitor') @input_load(query=ParamsSchema) @output_dump(Visit) async def visitor_entries(self, visitor_id, query): query.update({'visitor': visitor_id}) return await self.visit.get_many(**query) @route('/<visit_id>', 'GET', 'Visit details') @output_dump(Visit) async def visit_get(self, visit_id): return await self.visit.get_by_pk(visit_id) @route('/<visit_id>', 'PUT', 'Update entry', inject=[Injector.remote_addr]) @input_load(body=Visit) @output_dump(Visit) async def visit_update(self, remote_addr, body, visit_id): return await self.visit.visit_update(remote_addr, visit_id, body) @route('/<visit_id>', 'DELETE', 'Delete entry', inject=[Injector.remote_addr]) @output_dump(Visit) async def visit_delete(self, remote_addr, visit_id): return await self.visit.visit_delete(remote_addr, visit_id) @route('/count', 'GET', 'Entry count') @output_dump(Visit) async def visit_count(self, query): return {'count': await self.visit.count(**query)} @route('/', 'POST', 'Create entry', inject=[Injector.remote_addr]) @input_load(body=VisitNew) @output_dump(Visit) async def visit_add(self, body, remote_addr): return await self.visit.visit_add(remote_addr, body)
[ "jetfactory.controller.output_dump", "jetfactory.controller.route", "jetfactory.controller.input_load", "jet_guestbook.service.VisitorService", "jet_guestbook.service.VisitService" ]
[((652, 688), 'jetfactory.controller.route', 'route', (['"""/"""', '"""GET"""', '"""List of entries"""'], {}), "('/', 'GET', 'List of entries')\n", (657, 688), False, 'from jetfactory.controller import BaseController, Injector, route, input_load, output_dump\n'), ((694, 724), 'jetfactory.controller.input_load', 'input_load', ([], {'query': 'ParamsSchema'}), '(query=ParamsSchema)\n', (704, 724), False, 'from jetfactory.controller import BaseController, Injector, route, input_load, output_dump\n'), ((730, 759), 'jetfactory.controller.output_dump', 'output_dump', (['Visit'], {'many': '(True)'}), '(Visit, many=True)\n', (741, 759), False, 'from jetfactory.controller import BaseController, Injector, route, input_load, output_dump\n'), ((855, 900), 'jetfactory.controller.route', 'route', (['"""/visitors"""', '"""GET"""', '"""List of visitors"""'], {}), "('/visitors', 'GET', 'List of visitors')\n", (860, 900), False, 'from jetfactory.controller import BaseController, Injector, route, input_load, output_dump\n'), ((906, 936), 'jetfactory.controller.input_load', 'input_load', ([], {'query': 'ParamsSchema'}), '(query=ParamsSchema)\n', (916, 936), False, 'from jetfactory.controller import BaseController, Injector, route, input_load, output_dump\n'), ((942, 973), 'jetfactory.controller.output_dump', 'output_dump', (['Visitor'], {'many': '(True)'}), '(Visitor, many=True)\n', (953, 973), False, 'from jetfactory.controller import BaseController, Injector, route, input_load, output_dump\n'), ((1071, 1128), 'jetfactory.controller.route', 'route', (['"""/visitors/<visitor_id>"""', '"""GET"""', '"""Visitor details"""'], {}), "('/visitors/<visitor_id>', 'GET', 'Visitor details')\n", (1076, 1128), False, 'from jetfactory.controller import BaseController, Injector, route, input_load, output_dump\n'), ((1134, 1154), 'jetfactory.controller.output_dump', 'output_dump', (['Visitor'], {}), '(Visitor)\n', (1145, 1154), False, 'from jetfactory.controller import BaseController, Injector, route, input_load, output_dump\n'), ((1262, 1328), 'jetfactory.controller.route', 'route', (['"""/visitors/<visitor_id>/visits"""', '"""GET"""', '"""Visits by visitor"""'], {}), "('/visitors/<visitor_id>/visits', 'GET', 'Visits by visitor')\n", (1267, 1328), False, 'from jetfactory.controller import BaseController, Injector, route, input_load, output_dump\n'), ((1334, 1364), 'jetfactory.controller.input_load', 'input_load', ([], {'query': 'ParamsSchema'}), '(query=ParamsSchema)\n', (1344, 1364), False, 'from jetfactory.controller import BaseController, Injector, route, input_load, output_dump\n'), ((1370, 1388), 'jetfactory.controller.output_dump', 'output_dump', (['Visit'], {}), '(Visit)\n', (1381, 1388), False, 'from jetfactory.controller import BaseController, Injector, route, input_load, output_dump\n'), ((1547, 1591), 'jetfactory.controller.route', 'route', (['"""/<visit_id>"""', '"""GET"""', '"""Visit details"""'], {}), "('/<visit_id>', 'GET', 'Visit details')\n", (1552, 1591), False, 'from jetfactory.controller import BaseController, Injector, route, input_load, output_dump\n'), ((1597, 1615), 'jetfactory.controller.output_dump', 'output_dump', (['Visit'], {}), '(Visit)\n', (1608, 1615), False, 'from jetfactory.controller import BaseController, Injector, route, input_load, output_dump\n'), ((1715, 1789), 'jetfactory.controller.route', 'route', (['"""/<visit_id>"""', '"""PUT"""', '"""Update entry"""'], {'inject': '[Injector.remote_addr]'}), "('/<visit_id>', 'PUT', 'Update entry', inject=[Injector.remote_addr])\n", (1720, 1789), False, 'from jetfactory.controller import BaseController, Injector, route, input_load, output_dump\n'), ((1795, 1817), 'jetfactory.controller.input_load', 'input_load', ([], {'body': 'Visit'}), '(body=Visit)\n', (1805, 1817), False, 'from jetfactory.controller import BaseController, Injector, route, input_load, output_dump\n'), ((1823, 1841), 'jetfactory.controller.output_dump', 'output_dump', (['Visit'], {}), '(Visit)\n', (1834, 1841), False, 'from jetfactory.controller import BaseController, Injector, route, input_load, output_dump\n'), ((1985, 2062), 'jetfactory.controller.route', 'route', (['"""/<visit_id>"""', '"""DELETE"""', '"""Delete entry"""'], {'inject': '[Injector.remote_addr]'}), "('/<visit_id>', 'DELETE', 'Delete entry', inject=[Injector.remote_addr])\n", (1990, 2062), False, 'from jetfactory.controller import BaseController, Injector, route, input_load, output_dump\n'), ((2068, 2086), 'jetfactory.controller.output_dump', 'output_dump', (['Visit'], {}), '(Visit)\n', (2079, 2086), False, 'from jetfactory.controller import BaseController, Injector, route, input_load, output_dump\n'), ((2218, 2255), 'jetfactory.controller.route', 'route', (['"""/count"""', '"""GET"""', '"""Entry count"""'], {}), "('/count', 'GET', 'Entry count')\n", (2223, 2255), False, 'from jetfactory.controller import BaseController, Injector, route, input_load, output_dump\n'), ((2261, 2279), 'jetfactory.controller.output_dump', 'output_dump', (['Visit'], {}), '(Visit)\n', (2272, 2279), False, 'from jetfactory.controller import BaseController, Injector, route, input_load, output_dump\n'), ((2384, 2449), 'jetfactory.controller.route', 'route', (['"""/"""', '"""POST"""', '"""Create entry"""'], {'inject': '[Injector.remote_addr]'}), "('/', 'POST', 'Create entry', inject=[Injector.remote_addr])\n", (2389, 2449), False, 'from jetfactory.controller import BaseController, Injector, route, input_load, output_dump\n'), ((2455, 2480), 'jetfactory.controller.input_load', 'input_load', ([], {'body': 'VisitNew'}), '(body=VisitNew)\n', (2465, 2480), False, 'from jetfactory.controller import BaseController, Injector, route, input_load, output_dump\n'), ((2486, 2504), 'jetfactory.controller.output_dump', 'output_dump', (['Visit'], {}), '(Visit)\n', (2497, 2504), False, 'from jetfactory.controller import BaseController, Injector, route, input_load, output_dump\n'), ((362, 376), 'jet_guestbook.service.VisitService', 'VisitService', ([], {}), '()\n', (374, 376), False, 'from jet_guestbook.service import VisitService, VisitorService\n'), ((400, 416), 'jet_guestbook.service.VisitorService', 'VisitorService', ([], {}), '()\n', (414, 416), False, 'from jet_guestbook.service import VisitService, VisitorService\n')]
# -*- coding: utf-8 -*- """Celery configurations.""" import os from celery import Celery broker = os.environ.get("BROKER_URL", "redis://localhost:6379") backend = os.environ.get("BACKEND_URL", "redis://localhost:6379") app = Celery( __name__, broker=broker, backend=backend, include=["worker.tasks"], ) app.conf.update(result_expires=3600)
[ "celery.Celery", "os.environ.get" ]
[((100, 154), 'os.environ.get', 'os.environ.get', (['"""BROKER_URL"""', '"""redis://localhost:6379"""'], {}), "('BROKER_URL', 'redis://localhost:6379')\n", (114, 154), False, 'import os\n'), ((165, 220), 'os.environ.get', 'os.environ.get', (['"""BACKEND_URL"""', '"""redis://localhost:6379"""'], {}), "('BACKEND_URL', 'redis://localhost:6379')\n", (179, 220), False, 'import os\n'), ((229, 303), 'celery.Celery', 'Celery', (['__name__'], {'broker': 'broker', 'backend': 'backend', 'include': "['worker.tasks']"}), "(__name__, broker=broker, backend=backend, include=['worker.tasks'])\n", (235, 303), False, 'from celery import Celery\n')]
from setuptools import setup setup(name='alexa-goingson', version='0.1', description='San Francisco Event Recommendations for Amazon Echo', url='http://github.com/kazistan/alexa-goingson', author='<NAME>', author_email='<EMAIL>', license='MIT', packages=['baydata'], install_requires=[ 'requests', 'bs4', 're', 'sys', 'pandas', 'argparse', ], zip_safe=False)
[ "setuptools.setup" ]
[((30, 378), 'setuptools.setup', 'setup', ([], {'name': '"""alexa-goingson"""', 'version': '"""0.1"""', 'description': '"""San Francisco Event Recommendations for Amazon Echo"""', 'url': '"""http://github.com/kazistan/alexa-goingson"""', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'license': '"""MIT"""', 'packages': "['baydata']", 'install_requires': "['requests', 'bs4', 're', 'sys', 'pandas', 'argparse']", 'zip_safe': '(False)'}), "(name='alexa-goingson', version='0.1', description=\n 'San Francisco Event Recommendations for Amazon Echo', url=\n 'http://github.com/kazistan/alexa-goingson', author='<NAME>',\n author_email='<EMAIL>', license='MIT', packages=['baydata'],\n install_requires=['requests', 'bs4', 're', 'sys', 'pandas', 'argparse'],\n zip_safe=False)\n", (35, 378), False, 'from setuptools import setup\n')]
import os from shutil import copytree, copy2 from glob import glob import torchvision import torch from tensorboardX import SummaryWriter from sklearn import metrics def copy_source_code(path): if not os.path.isdir(path): os.makedirs(path) denylist = ["./__pycache__/"] folders = glob(r'./*/') # For copying python files for file_ in glob(r'./*.py'): copy2(file_, path) # For copying json files for file_ in glob(r'./*.json'): copy2(file_, path) for folder in folders: if folder not in denylist: # Remove first char which is . due to the glob copytree(folder, path + folder[1:]) class LoggerUtils(): """docstring for LoggerUtils""" def __init__(self, config): super(LoggerUtils, self).__init__() log_path = config["log_path"] tb_path = log_path + "/tensorboard" if not os.path.exists(tb_path) or not os.path.isdir(tb_path): os.mkdir(tb_path) self.config = config self.writer = SummaryWriter(tb_path) def save_image_batch(self, batch_image, path): torchvision.utils.save_image(batch_image, '{}/{}'.format( self.config["log_path"], path), nrow=8, padding=2) def save_model(self, model, path): torch.save(model.state_dict(), path) def log_model_stats(self, model): pass def log_console(self, message): print(message) def log_metrics(self, category, y_pred, y_true, iteration): #self.log_scalar(category + "/metrics/roc_auc", metrics.roc_auc_score(y_true, y_pred), iteration) #self.log_scalar(category + "/metrics/f1", metrics.f1_score(y_true, y_pred > 0.5), iteration) #self.log_scalar(category + "/metrics/precision", metrics.precision_score(y_true, y_pred > 0.5), iteration) #self.log_scalar(category + "/metrics/recall", metrics.recall_score(y_true, y_pred > 0.5), iteration) #self.log_scalar(category + "/metrics/auprc", metrics.average_precision_score(y_true, y_pred), iteration) pass def log_scalar(self, category, value, iteration): self.writer.add_scalar(category, value, iteration) def log_histogram(self, category, vector, step): self.writer.add_histogram(category, vector, step)
[ "os.path.exists", "tensorboardX.SummaryWriter", "os.makedirs", "shutil.copy2", "shutil.copytree", "os.path.isdir", "os.mkdir", "glob.glob" ]
[((317, 329), 'glob.glob', 'glob', (['"""./*/"""'], {}), "('./*/')\n", (321, 329), False, 'from glob import glob\n'), ((383, 397), 'glob.glob', 'glob', (['"""./*.py"""'], {}), "('./*.py')\n", (387, 397), False, 'from glob import glob\n'), ((478, 494), 'glob.glob', 'glob', (['"""./*.json"""'], {}), "('./*.json')\n", (482, 494), False, 'from glob import glob\n'), ((217, 236), 'os.path.isdir', 'os.path.isdir', (['path'], {}), '(path)\n', (230, 236), False, 'import os\n'), ((247, 264), 'os.makedirs', 'os.makedirs', (['path'], {}), '(path)\n', (258, 264), False, 'import os\n'), ((409, 427), 'shutil.copy2', 'copy2', (['file_', 'path'], {}), '(file_, path)\n', (414, 427), False, 'from shutil import copytree, copy2\n'), ((506, 524), 'shutil.copy2', 'copy2', (['file_', 'path'], {}), '(file_, path)\n', (511, 524), False, 'from shutil import copytree, copy2\n'), ((1082, 1104), 'tensorboardX.SummaryWriter', 'SummaryWriter', (['tb_path'], {}), '(tb_path)\n', (1095, 1104), False, 'from tensorboardX import SummaryWriter\n'), ((664, 699), 'shutil.copytree', 'copytree', (['folder', '(path + folder[1:])'], {}), '(folder, path + folder[1:])\n', (672, 699), False, 'from shutil import copytree, copy2\n'), ((1011, 1028), 'os.mkdir', 'os.mkdir', (['tb_path'], {}), '(tb_path)\n', (1019, 1028), False, 'import os\n'), ((943, 966), 'os.path.exists', 'os.path.exists', (['tb_path'], {}), '(tb_path)\n', (957, 966), False, 'import os\n'), ((974, 996), 'os.path.isdir', 'os.path.isdir', (['tb_path'], {}), '(tb_path)\n', (987, 996), False, 'import os\n')]
# boto3-lambda/src/lambda_functions.py import boto3 import json import os from helpers import Zipper from helpers import lambda_client, iam_client from settings import PYTHON_LAMBDA_API_PERMISSION_STATEMENT_ID, LAMBDA_POLICY_NAME, LAMBDA_ROLE, LAMBDA_TIMEOUT, LAMBDA_MEMORY, PYTHON_36_RUNTIME, PYTHON_LAMBDA_NAME def remove_permission(): try: response = lambda_client().remove_permission( FunctionName=PYTHON_LAMBDA_NAME, StatementId=PYTHON_LAMBDA_API_PERMISSION_STATEMENT_ID, ) return response except lambda_client().exceptions.ResourceNotFoundException as e: pass def get_or_create_access_policy_for_lambda(policy_name): policy = find_policy(policy_name) if not policy: s3_access_policy_document = { "Version": "2012-10-17", "Statement": [ { "Action": [ "s3:*", "logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents", "cloudwatch:PutMetricData", ], "Effect": "Allow", "Resource": "*", } ], } return iam_client().create_policy( PolicyName=policy_name, PolicyDocument=json.dumps(s3_access_policy_document), Description="Allows lambda function to access s3 resources", )["Policy"] return policy def find_policy(policy_name): for p in iam_client().list_policies(Scope="Local").get("Policies"): if p.get("PolicyName") == policy_name: return p def find_role(lambda_role): try: role = iam_client().get_role(RoleName=lambda_role) if role.get("Role", False): return role.get("Role") except iam_client().exceptions.NoSuchEntityException: pass def get_or_create_execution_role_lambda(arn, lambda_role): role = find_role(lambda_role) if role: return role lambda_execution_assumption_role = { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"}, "Action": "sts:AssumeRole", } ], } return iam_client().create_role( RoleName=lambda_role, AssumeRolePolicyDocument=json.dumps(lambda_execution_assumption_role), Description="Gives necessary permissions for lambda to be executed", )["Role"] def attach_access_policy_to_execution_role(lambda_role, policy_arn): return iam_client().attach_role_policy(RoleName=lambda_role, PolicyArn=policy_arn) def deploy_lambda_function(function_name, runtime, handler, role_arn, source_folder): folder_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), source_folder ) zip_file = Zipper().make_bytes(path=folder_path) return lambda_client().create_function( FunctionName=function_name, Runtime=runtime, Role=role_arn, Handler=handler, Code={"ZipFile": zip_file,}, Timeout=LAMBDA_TIMEOUT, MemorySize=LAMBDA_MEMORY, Publish=False, ) def remove_function(lambda_name): try: return lambda_client().delete_function(FunctionName=lambda_name) except lambda_client().exceptions.ResourceNotFoundException: pass def invoke_function(lambda_name): return lambda_client().invoke(FunctionName=lambda_name) def create_lambda(): policy = get_or_create_access_policy_for_lambda(LAMBDA_POLICY_NAME) policy_arn = policy.get("Arn") role = get_or_create_execution_role_lambda(policy_arn, LAMBDA_ROLE) role_arn = role.get("Arn") role_policy = attach_access_policy_to_execution_role(LAMBDA_ROLE, policy_arn) return role_arn def deploy_lambda(role_arn): return deploy_lambda_function( PYTHON_LAMBDA_NAME, PYTHON_36_RUNTIME, "hello_world.handler", role_arn, "python_lambdas", )
[ "helpers.lambda_client", "json.dumps", "helpers.iam_client", "os.path.abspath", "helpers.Zipper" ]
[((2671, 2683), 'helpers.iam_client', 'iam_client', ([], {}), '()\n', (2681, 2683), False, 'from helpers import lambda_client, iam_client\n'), ((2891, 2916), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (2906, 2916), False, 'import os\n'), ((2954, 2962), 'helpers.Zipper', 'Zipper', ([], {}), '()\n', (2960, 2962), False, 'from helpers import Zipper\n'), ((3003, 3018), 'helpers.lambda_client', 'lambda_client', ([], {}), '()\n', (3016, 3018), False, 'from helpers import lambda_client, iam_client\n'), ((3520, 3535), 'helpers.lambda_client', 'lambda_client', ([], {}), '()\n', (3533, 3535), False, 'from helpers import lambda_client, iam_client\n'), ((367, 382), 'helpers.lambda_client', 'lambda_client', ([], {}), '()\n', (380, 382), False, 'from helpers import lambda_client, iam_client\n'), ((559, 574), 'helpers.lambda_client', 'lambda_client', ([], {}), '()\n', (572, 574), False, 'from helpers import lambda_client, iam_client\n'), ((1749, 1761), 'helpers.iam_client', 'iam_client', ([], {}), '()\n', (1759, 1761), False, 'from helpers import lambda_client, iam_client\n'), ((1876, 1888), 'helpers.iam_client', 'iam_client', ([], {}), '()\n', (1886, 1888), False, 'from helpers import lambda_client, iam_client\n'), ((2363, 2375), 'helpers.iam_client', 'iam_client', ([], {}), '()\n', (2373, 2375), False, 'from helpers import lambda_client, iam_client\n'), ((2452, 2496), 'json.dumps', 'json.dumps', (['lambda_execution_assumption_role'], {}), '(lambda_execution_assumption_role)\n', (2462, 2496), False, 'import json\n'), ((3337, 3352), 'helpers.lambda_client', 'lambda_client', ([], {}), '()\n', (3350, 3352), False, 'from helpers import lambda_client, iam_client\n'), ((3406, 3421), 'helpers.lambda_client', 'lambda_client', ([], {}), '()\n', (3419, 3421), False, 'from helpers import lambda_client, iam_client\n'), ((1281, 1293), 'helpers.iam_client', 'iam_client', ([], {}), '()\n', (1291, 1293), False, 'from helpers import lambda_client, iam_client\n'), ((1372, 1409), 'json.dumps', 'json.dumps', (['s3_access_policy_document'], {}), '(s3_access_policy_document)\n', (1382, 1409), False, 'import json\n'), ((1568, 1580), 'helpers.iam_client', 'iam_client', ([], {}), '()\n', (1578, 1580), False, 'from helpers import lambda_client, iam_client\n')]
from cyder.base.tests import ModelTestMixin, TestCase from cyder.cydhcp.vrf.models import Vrf class VrfTests(TestCase, ModelTestMixin): @property def objs(self): """Create objects for test_create_delete.""" return ( Vrf.objects.create(name='a'), Vrf.objects.create(name='bbbbbbbbbbbbb'), Vrf.objects.create(name='Hello, world.'), )
[ "cyder.cydhcp.vrf.models.Vrf.objects.create" ]
[((254, 282), 'cyder.cydhcp.vrf.models.Vrf.objects.create', 'Vrf.objects.create', ([], {'name': '"""a"""'}), "(name='a')\n", (272, 282), False, 'from cyder.cydhcp.vrf.models import Vrf\n'), ((296, 336), 'cyder.cydhcp.vrf.models.Vrf.objects.create', 'Vrf.objects.create', ([], {'name': '"""bbbbbbbbbbbbb"""'}), "(name='bbbbbbbbbbbbb')\n", (314, 336), False, 'from cyder.cydhcp.vrf.models import Vrf\n'), ((350, 390), 'cyder.cydhcp.vrf.models.Vrf.objects.create', 'Vrf.objects.create', ([], {'name': '"""Hello, world."""'}), "(name='Hello, world.')\n", (368, 390), False, 'from cyder.cydhcp.vrf.models import Vrf\n')]
from collections import namedtuple import numpy as np import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F class DQN(nn.Module): def __init__(self): super(DQN, self).__init__() self.linear1 = nn.Linear(4, 64) self.linear2 = nn.Linear(64, 64) self.linear3 = nn.Linear(64, 64) self.linear4 = nn.Linear(64, 4) def forward(self, x): x = F.relu(self.linear1(x)) x = F.relu(self.linear2(x)) x = F.relu(self.linear3(x)) x = self.linear4(x) return x
[ "torch.nn.Linear" ]
[((255, 271), 'torch.nn.Linear', 'nn.Linear', (['(4)', '(64)'], {}), '(4, 64)\n', (264, 271), True, 'import torch.nn as nn\n'), ((295, 312), 'torch.nn.Linear', 'nn.Linear', (['(64)', '(64)'], {}), '(64, 64)\n', (304, 312), True, 'import torch.nn as nn\n'), ((336, 353), 'torch.nn.Linear', 'nn.Linear', (['(64)', '(64)'], {}), '(64, 64)\n', (345, 353), True, 'import torch.nn as nn\n'), ((377, 393), 'torch.nn.Linear', 'nn.Linear', (['(64)', '(4)'], {}), '(64, 4)\n', (386, 393), True, 'import torch.nn as nn\n')]
import os import tempfile from unittest import TestCase from semantic_release import ImproperConfigurationError from semantic_release.pypi import upload_to_pypi from . import mock, wrapped_config_get class PypiTests(TestCase): @mock.patch("semantic_release.pypi.run") @mock.patch.dict( "os.environ", {"PYPI_USERNAME": "username", "PYPI_PASSWORD": "password", "HOME": "/tmp/1234"}, ) def test_upload_with_password(self, mock_run): upload_to_pypi() self.assertEqual( mock_run.call_args_list, [mock.call("twine upload -u 'username' -p 'password' \"dist/*\"")], ) @mock.patch("semantic_release.pypi.run") @mock.patch.dict( "os.environ", {"PYPI_USERNAME": "username", "PYPI_PASSWORD": "password", "HOME": "/tmp/1234"}, ) @mock.patch( "semantic_release.pypi.config.get", wrapped_config_get(repository="corp-repo") ) def test_upload_with_repository(self, mock_run): upload_to_pypi() self.assertEqual( mock_run.call_args_list, [ mock.call( "twine upload -u 'username' -p 'password' -r 'corp-repo' \"dist/*\"" ) ], ) @mock.patch("semantic_release.pypi.run") @mock.patch.dict("os.environ", {"PYPI_TOKEN": "pypi-x"}) def test_upload_with_token(self, mock_run): upload_to_pypi() self.assertEqual( mock_run.call_args_list, [mock.call("twine upload -u '__token__' -p 'pypi-x' \"dist/*\"")], ) @mock.patch("semantic_release.pypi.run") @mock.patch.dict( "os.environ", { "PYPI_TOKEN": "pypi-x", "PYPI_USERNAME": "username", "PYPI_PASSWORD": "password", }, ) def test_upload_prefers_token_over_password(self, mock_run): upload_to_pypi() self.assertEqual( mock_run.call_args_list, [mock.call("twine upload -u '__token__' -p 'pypi-x' \"dist/*\"")], ) @mock.patch("semantic_release.pypi.run") @mock.patch.dict("os.environ", {"PYPI_TOKEN": "pypi-x"}) def test_upload_with_custom_path(self, mock_run): upload_to_pypi(path="custom-dist") self.assertEqual( mock_run.call_args_list, [mock.call("twine upload -u '__token__' -p 'pypi-x' \"custom-dist/*\"")], ) @mock.patch("semantic_release.pypi.run") @mock.patch.dict("os.environ", {"PYPI_TOKEN": "pypi-x"}) def test_upload_with_custom_globs(self, mock_run): upload_to_pypi(glob_patterns=["*.tar.gz", "*.whl"]) self.assertEqual( mock_run.call_args_list, [ mock.call( "twine upload -u '__token__' -p 'pypi-x' \"dist/*.tar.gz\" \"dist/*.whl\"" ) ], ) @mock.patch("semantic_release.pypi.run") @mock.patch.dict("os.environ", {}) def test_upload_with_pypirc_file_exists(self, mock_run): tmpdir = tempfile.mkdtemp() os.environ["HOME"] = tmpdir with open(os.path.join(tmpdir, ".pypirc"), "w") as pypirc_fp: pypirc_fp.write("hello") upload_to_pypi(path="custom-dist") self.assertEqual( mock_run.call_args_list, [mock.call('twine upload "custom-dist/*"')], ) @mock.patch.dict("os.environ", {"PYPI_TOKEN": "invalid"}) def test_raises_error_when_token_invalid(self): with self.assertRaises(ImproperConfigurationError): upload_to_pypi() @mock.patch.dict("os.environ", {"HOME": "/tmp/1234"}) def test_raises_error_when_missing_credentials(self): with self.assertRaises(ImproperConfigurationError): upload_to_pypi()
[ "os.path.join", "tempfile.mkdtemp", "semantic_release.pypi.upload_to_pypi" ]
[((474, 490), 'semantic_release.pypi.upload_to_pypi', 'upload_to_pypi', ([], {}), '()\n', (488, 490), False, 'from semantic_release.pypi import upload_to_pypi\n'), ((1000, 1016), 'semantic_release.pypi.upload_to_pypi', 'upload_to_pypi', ([], {}), '()\n', (1014, 1016), False, 'from semantic_release.pypi import upload_to_pypi\n'), ((1416, 1432), 'semantic_release.pypi.upload_to_pypi', 'upload_to_pypi', ([], {}), '()\n', (1430, 1432), False, 'from semantic_release.pypi import upload_to_pypi\n'), ((1893, 1909), 'semantic_release.pypi.upload_to_pypi', 'upload_to_pypi', ([], {}), '()\n', (1907, 1909), False, 'from semantic_release.pypi import upload_to_pypi\n'), ((2231, 2265), 'semantic_release.pypi.upload_to_pypi', 'upload_to_pypi', ([], {'path': '"""custom-dist"""'}), "(path='custom-dist')\n", (2245, 2265), False, 'from semantic_release.pypi import upload_to_pypi\n'), ((2595, 2646), 'semantic_release.pypi.upload_to_pypi', 'upload_to_pypi', ([], {'glob_patterns': "['*.tar.gz', '*.whl']"}), "(glob_patterns=['*.tar.gz', '*.whl'])\n", (2609, 2646), False, 'from semantic_release.pypi import upload_to_pypi\n'), ((3052, 3070), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (3068, 3070), False, 'import tempfile\n'), ((3222, 3256), 'semantic_release.pypi.upload_to_pypi', 'upload_to_pypi', ([], {'path': '"""custom-dist"""'}), "(path='custom-dist')\n", (3236, 3256), False, 'from semantic_release.pypi import upload_to_pypi\n'), ((3575, 3591), 'semantic_release.pypi.upload_to_pypi', 'upload_to_pypi', ([], {}), '()\n', (3589, 3591), False, 'from semantic_release.pypi import upload_to_pypi\n'), ((3781, 3797), 'semantic_release.pypi.upload_to_pypi', 'upload_to_pypi', ([], {}), '()\n', (3795, 3797), False, 'from semantic_release.pypi import upload_to_pypi\n'), ((3125, 3156), 'os.path.join', 'os.path.join', (['tmpdir', '""".pypirc"""'], {}), "(tmpdir, '.pypirc')\n", (3137, 3156), False, 'import os\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- import wx class ImagePrintout(wx.Printout): def __init__(self, image): wx.Printout.__init__(self) self._image = image self._bitmap = None def HasPage(self, page_num): return page_num == 1 def OnPreparePrinting(self): dc = self.GetDC() dc_width, dc_height = dc.GetSize() image_height, image_width, _ = self._image.shape width_scale = dc_width / image_width height_scale = dc_height / image_height full_fill_scale = min(width_scale, height_scale) width_scale_after_rotate = dc_width / image_height height_scale_after_rotate = dc_height / image_width full_fill_scale_after_rotate = min(width_scale_after_rotate, height_scale_after_rotate) wx_image = wx.Image(image_width, image_height) image_data = self._image.tostring() wx_image.SetData(image_data) if full_fill_scale_after_rotate > full_fill_scale: wx_image = wx_image.Rotate90(False).Scale(image_height * full_fill_scale_after_rotate, image_width * full_fill_scale_after_rotate) else: wx_image = wx_image.Scale(image_width * full_fill_scale, image_height * full_fill_scale) self._bitmap = wx_image.ConvertToBitmap() def OnPrintPage(self, page_num): dc = self.GetDC() dc.SetPen(wx.Pen('black', 0)) dc.SetBrush(wx.TRANSPARENT_BRUSH) dc.DrawBitmap(self._bitmap, 0, 0) return True
[ "wx.Printout.__init__", "wx.Pen", "wx.Image" ]
[((132, 158), 'wx.Printout.__init__', 'wx.Printout.__init__', (['self'], {}), '(self)\n', (152, 158), False, 'import wx\n'), ((827, 862), 'wx.Image', 'wx.Image', (['image_width', 'image_height'], {}), '(image_width, image_height)\n', (835, 862), False, 'import wx\n'), ((1450, 1468), 'wx.Pen', 'wx.Pen', (['"""black"""', '(0)'], {}), "('black', 0)\n", (1456, 1468), False, 'import wx\n')]
from collections import OrderedDict from typing import Dict, Sequence, Type import torch import torch.nn as nn import torch.nn.functional as F from .mtl import MTLModel, MTLTaskConfig def make_hidden(sizes: Sequence[int], activation: Type[nn.Module]) -> nn.Module: if len(sizes) == 0: return nn.Identity() return nn.Sequential( *( nn.Sequential( nn.Linear(sizes[i], sizes[i + 1]), activation(), ) for i in range(len(sizes) - 1) ) ) class SimpleMTLModel(MTLModel): def __init__( self, tasks: Dict[str, MTLTaskConfig], input_dim: int, opt_lr: float = 0.001, shared_units: Sequence[int] = [512], task_units: Sequence[int] = [512], ): super().__init__(tasks=tasks) self.opt_lr = opt_lr self.save_hyperparameters("opt_lr", "shared_units", "task_units") shared_sizes = [input_dim] + list(shared_units) self.shared = make_hidden(shared_sizes, nn.ReLU) self.add_module("shared", self.shared) self.task_layer = {} self.task_output = {} task_sizes = [shared_sizes[-1]] + list(task_units) for name, task in self.tasks.items(): self.task_layer[name] = make_hidden(task_sizes, nn.ReLU) self.task_output[name] = nn.Linear(task_sizes[-1], task.output_dim) submod = nn.Sequential( OrderedDict( { "embeddings": self.task_layer[name], "output": self.task_output[name], } ) ) self.add_module(name, submod) def forward(self, x: torch.Tensor, **kwargs) -> Dict[str, torch.Tensor]: x = F.relu(self.shared(x)) task_embeddings = {k: self.task_layer[k](x) for k in self.tasks} if kwargs.pop("embeddings_only", False): return task_embeddings out = {k: F.relu(v) for k, v in task_embeddings.items()} return {k: self.task_output[k](out[k]) for k in self.tasks} def configure_optimizers(self): return torch.optim.Adam(self.parameters(), lr=self.opt_lr)
[ "torch.nn.Identity", "collections.OrderedDict", "torch.nn.functional.relu", "torch.nn.Linear" ]
[((308, 321), 'torch.nn.Identity', 'nn.Identity', ([], {}), '()\n', (319, 321), True, 'import torch.nn as nn\n'), ((1372, 1414), 'torch.nn.Linear', 'nn.Linear', (['task_sizes[-1]', 'task.output_dim'], {}), '(task_sizes[-1], task.output_dim)\n', (1381, 1414), True, 'import torch.nn as nn\n'), ((2005, 2014), 'torch.nn.functional.relu', 'F.relu', (['v'], {}), '(v)\n', (2011, 2014), True, 'import torch.nn.functional as F\n'), ((1467, 1556), 'collections.OrderedDict', 'OrderedDict', (["{'embeddings': self.task_layer[name], 'output': self.task_output[name]}"], {}), "({'embeddings': self.task_layer[name], 'output': self.\n task_output[name]})\n", (1478, 1556), False, 'from collections import OrderedDict\n'), ((402, 435), 'torch.nn.Linear', 'nn.Linear', (['sizes[i]', 'sizes[i + 1]'], {}), '(sizes[i], sizes[i + 1])\n', (411, 435), True, 'import torch.nn as nn\n')]
from collections import ( defaultdict, ) from contextlib import ( asynccontextmanager, ) from datetime import ( datetime, ) from typing import ( Iterable, ) import psutil from core.db_entities import ( DBTable, DstDatabase, ) from core.enums import ( TransferringStagesEnum, ) from core.helpers import ( dates_list_to_str, logger, ) class StatisticManager: def __init__( self, database: DstDatabase, ): self._database = database self._time_indications = defaultdict(list) self._memory_usage_indications = defaultdict(list) def set_indication_time(self, stage): """ Add stage indication time Stage from TransferringStagesEnum """ self._time_indications[stage].append(datetime.now()) def set_indication_memory(self, stage): """ Add stage memory usage indication """ self._memory_usage_indications[stage].append( dict(psutil.virtual_memory()._asdict()) ) def print_transferring_indications(self): """ Output transferring indications to log """ for stage in TransferringStagesEnum.values.keys(): if stage in self._time_indications: logger.info( f"{TransferringStagesEnum.values.get(stage)} --- " f"{dates_list_to_str(self._time_indications[stage])}" ) if stage in self._memory_usage_indications: logger.info( f"{TransferringStagesEnum.values.get(stage)} --- " f"{self._memory_usage_indications[stage]}" ) def print_records_transfer_statistic(self): """ Output transferred tables rows count """ tables: Iterable[DBTable] = self._database.tables.values() tables_counts = { table.name: (table.transferred_pks_count, len(table.need_transfer_pks)) for table in tables } sorted_tables_counts = ( sorted(tables_counts, key=lambda t_n: tables_counts[t_n][0]) ) for table_name in sorted_tables_counts: logger.info( f"{table_name} --- {tables_counts[table_name][0]} / " f"{tables_counts[table_name][1]}" ) @asynccontextmanager async def statistic_indexer( statistic_manager: StatisticManager, stage: int, ): """ Statistic indexer context manager """ statistic_manager.set_indication_time(stage) statistic_manager.set_indication_memory(stage) yield statistic_manager.set_indication_time(stage) statistic_manager.set_indication_memory(stage)
[ "core.enums.TransferringStagesEnum.values.get", "psutil.virtual_memory", "core.helpers.logger.info", "datetime.datetime.now", "collections.defaultdict", "core.enums.TransferringStagesEnum.values.keys", "core.helpers.dates_list_to_str" ]
[((534, 551), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (545, 551), False, 'from collections import defaultdict\n'), ((593, 610), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (604, 610), False, 'from collections import defaultdict\n'), ((1182, 1218), 'core.enums.TransferringStagesEnum.values.keys', 'TransferringStagesEnum.values.keys', ([], {}), '()\n', (1216, 1218), False, 'from core.enums import TransferringStagesEnum\n'), ((800, 814), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (812, 814), False, 'from datetime import datetime\n'), ((2213, 2319), 'core.helpers.logger.info', 'logger.info', (['f"""{table_name} --- {tables_counts[table_name][0]} / {tables_counts[table_name][1]}"""'], {}), "(\n f'{table_name} --- {tables_counts[table_name][0]} / {tables_counts[table_name][1]}'\n )\n", (2224, 2319), False, 'from core.helpers import dates_list_to_str, logger\n'), ((998, 1021), 'psutil.virtual_memory', 'psutil.virtual_memory', ([], {}), '()\n', (1019, 1021), False, 'import psutil\n'), ((1320, 1360), 'core.enums.TransferringStagesEnum.values.get', 'TransferringStagesEnum.values.get', (['stage'], {}), '(stage)\n', (1353, 1360), False, 'from core.enums import TransferringStagesEnum\n'), ((1391, 1439), 'core.helpers.dates_list_to_str', 'dates_list_to_str', (['self._time_indications[stage]'], {}), '(self._time_indications[stage])\n', (1408, 1439), False, 'from core.helpers import dates_list_to_str, logger\n'), ((1569, 1609), 'core.enums.TransferringStagesEnum.values.get', 'TransferringStagesEnum.values.get', (['stage'], {}), '(stage)\n', (1602, 1609), False, 'from core.enums import TransferringStagesEnum\n')]
# Copyright 2013 OpenStack Foundation # Copyright 2014 NEC Corporation # All Rights Reserved. # # 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 tempest.api.compute import base from tempest import exceptions from tempest import test class QuotasAdminNegativeV3Test(base.BaseV3ComputeAdminTest): force_tenant_isolation = True @classmethod def resource_setup(cls): super(QuotasAdminNegativeV3Test, cls).resource_setup() cls.client = cls.quotas_client cls.adm_client = cls.quotas_admin_client # NOTE(afazekas): these test cases should always create and use a new # tenant most of them should be skipped if we can't do that cls.demo_tenant_id = cls.isolated_creds.get_primary_creds().tenant_id # TODO(afazekas): Add dedicated tenant to the skiped quota tests # it can be moved into the setUpClass as well @test.attr(type=['negative', 'gate']) def test_create_server_when_cpu_quota_is_full(self): # Disallow server creation when tenant's vcpu quota is full resp, quota_set = self.adm_client.get_quota_set(self.demo_tenant_id) default_vcpu_quota = quota_set['cores'] vcpu_quota = 0 # Set the quota to zero to conserve resources resp, quota_set = self.adm_client.update_quota_set(self.demo_tenant_id, force=True, cores=vcpu_quota) self.addCleanup(self.adm_client.update_quota_set, self.demo_tenant_id, cores=default_vcpu_quota) self.assertRaises((exceptions.Unauthorized, exceptions.OverLimit), self.create_test_server) @test.attr(type=['negative', 'gate']) def test_create_server_when_memory_quota_is_full(self): # Disallow server creation when tenant's memory quota is full resp, quota_set = self.adm_client.get_quota_set(self.demo_tenant_id) default_mem_quota = quota_set['ram'] mem_quota = 0 # Set the quota to zero to conserve resources self.adm_client.update_quota_set(self.demo_tenant_id, force=True, ram=mem_quota) self.addCleanup(self.adm_client.update_quota_set, self.demo_tenant_id, ram=default_mem_quota) self.assertRaises((exceptions.Unauthorized, exceptions.OverLimit), self.create_test_server) @test.attr(type=['negative', 'gate']) def test_update_quota_normal_user(self): self.assertRaises(exceptions.Unauthorized, self.client.update_quota_set, self.demo_tenant_id, ram=0) @test.attr(type=['negative', 'gate']) def test_create_server_when_instances_quota_is_full(self): # Once instances quota limit is reached, disallow server creation resp, quota_set = self.adm_client.get_quota_set(self.demo_tenant_id) default_instances_quota = quota_set['instances'] instances_quota = 0 # Set quota to zero to disallow server creation self.adm_client.update_quota_set(self.demo_tenant_id, force=True, instances=instances_quota) self.addCleanup(self.adm_client.update_quota_set, self.demo_tenant_id, instances=default_instances_quota) self.assertRaises((exceptions.Unauthorized, exceptions.OverLimit), self.create_test_server)
[ "tempest.test.attr" ]
[((1408, 1444), 'tempest.test.attr', 'test.attr', ([], {'type': "['negative', 'gate']"}), "(type=['negative', 'gate'])\n", (1417, 1444), False, 'from tempest import test\n'), ((2256, 2292), 'tempest.test.attr', 'test.attr', ([], {'type': "['negative', 'gate']"}), "(type=['negative', 'gate'])\n", (2265, 2292), False, 'from tempest import test\n'), ((3045, 3081), 'tempest.test.attr', 'test.attr', ([], {'type': "['negative', 'gate']"}), "(type=['negative', 'gate'])\n", (3054, 3081), False, 'from tempest import test\n'), ((3320, 3356), 'tempest.test.attr', 'test.attr', ([], {'type': "['negative', 'gate']"}), "(type=['negative', 'gate'])\n", (3329, 3356), False, 'from tempest import test\n')]
from pystac.catalog import Catalog import pystac from pystac import (STACError, Extensions) from pystac.collection import Collection from pystac.extensions.base import (CatalogExtension, ExtensionDefinition, ExtendedObject) def create_single_file_stac(catalog): """Creates a Single File STAC from a STAC catalog. This method will recursively collect any collections and items in the catalog and return a new catalog with the same properties as the old one, with cleared links and the 'collections' and 'features' property of the Single File STAC holding each of the respective collected STAC objects. Collections will be filtered to only those referenced by items via the collection_id. All links in the items and collections will be cleared in the Single File STAC. Args: catalog (Catalog): Catalog to walk while constructin the Single File STAC """ collections = {} items = [] for root, _, cat_items in catalog.walk(): if issubclass(type(root), Collection): new_collection = root.clone() new_collection.clear_links() collections[root.id] = new_collection for item in cat_items: new_item = item.clone() new_item.clear_links() items.append(new_item) filtered_collections = [] for item in items: if item.collection_id in collections: filtered_collections.append(collections[item.collection_id]) collections.pop(item.collection_id) result = catalog.clone() result.clear_links() result.ext.enable(Extensions.SINGLE_FILE_STAC) result.ext[Extensions.SINGLE_FILE_STAC].apply(features=items, collections=filtered_collections) return result class SingleFileSTACCatalogExt(CatalogExtension): """An extension of Catalog that provides a set of Collections and Items as a single file catalog. A SingleFileSTAC is a self contained catalog that contains everything that would normally be in a linked set of STAC files. Args: catalog (Catalog): The catalog to be extended. Attributes: catalog (Catalog): The catalog that is being extended. Note: Using SingleFileSTACCatalogExt to directly wrap a Catalog will add the 'proj' extension ID to the catalog's stac_extensions. """ def __init__(self, catalog): if catalog.stac_extensions is None: catalog.stac_extensions = [Extensions.SINGLE_FILE_STAC] elif Extensions.SINGLE_FILE_STAC not in catalog.stac_extensions: catalog.stac_extensions.append(Extensions.SINGLE_FILE_STAC) self.catalog = catalog def apply(self, features, collections=None): """ Args: features (List[Item]): List of items contained by this SingleFileSTAC. collections (List[Collection]): Optional list of collections that are used by any of teh Items in the catalog. """ self.features = features self.collections = collections @classmethod def enable_extension(cls, catalog): # Ensure the 'type' property is correct so that the Catalog is valid GeoJSON. catalog.extra_fields['type'] = 'FeatureCollection' @property def features(self): """Get or sets a list of :class:`~pystac.Item` contained in this Single File STAC. Returns: List[Item] """ features = self.catalog.extra_fields.get('features') if features is None: raise STACError('Invalid Single File STAC: does not have "features" property.') return [pystac.read_dict(feature) for feature in features] @features.setter def features(self, v): self.catalog.extra_fields['features'] = [item.to_dict() for item in v] @property def collections(self): """Get or sets a list of :class:`~pystac.Collection` objects contained in this Single File STAC. Returns: List[Band] """ collections = self.catalog.extra_fields.get('collections') if collections is not None: collections = [pystac.read_dict(col) for col in collections] return collections @collections.setter def collections(self, v): if v is not None: self.catalog.extra_fields['collections'] = [col.to_dict() for col in v] else: self.catalog.extra_fields.pop('collections', None) @classmethod def _object_links(cls): return [] @classmethod def from_catalog(cls, catalog): return SingleFileSTACCatalogExt(catalog) SFS_EXTENSION_DEFINITION = ExtensionDefinition(Extensions.SINGLE_FILE_STAC, [ExtendedObject(Catalog, SingleFileSTACCatalogExt)])
[ "pystac.STACError", "pystac.read_dict", "pystac.extensions.base.ExtendedObject" ]
[((4773, 4822), 'pystac.extensions.base.ExtendedObject', 'ExtendedObject', (['Catalog', 'SingleFileSTACCatalogExt'], {}), '(Catalog, SingleFileSTACCatalogExt)\n', (4787, 4822), False, 'from pystac.extensions.base import CatalogExtension, ExtensionDefinition, ExtendedObject\n'), ((3556, 3629), 'pystac.STACError', 'STACError', (['"""Invalid Single File STAC: does not have "features" property."""'], {}), '(\'Invalid Single File STAC: does not have "features" property.\')\n', (3565, 3629), False, 'from pystac import STACError, Extensions\n'), ((3647, 3672), 'pystac.read_dict', 'pystac.read_dict', (['feature'], {}), '(feature)\n', (3663, 3672), False, 'import pystac\n'), ((4165, 4186), 'pystac.read_dict', 'pystac.read_dict', (['col'], {}), '(col)\n', (4181, 4186), False, 'import pystac\n')]
# Copyright (c) 2018 Cloudify Platform Ltd. All rights reserved # # 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. """ SQS.queue ~~~~~~~~ AWS SQS Queue interface """ # Standard imports import json # Third party imports from botocore.exceptions import ClientError, ParamValidationError # Local imports from cloudify_aws.common._compat import text_type from cloudify_aws.common import decorators, utils from cloudify_aws.sqs import SQSBase RESOURCE_TYPE = 'SQS Queue' RESOURCE_NAME = 'QueueName' QUEUE_URL = 'QueueUrl' QUEUE_URLS = 'QueueUrls' QUEUE_ARN = 'QueueArn' POLICY = 'Policy' class SQSQueue(SQSBase): """ AWS SQS Queue interface """ def __init__(self, ctx_node, resource_id=None, client=None, logger=None): SQSBase.__init__(self, ctx_node, resource_id, client, logger) self.type_name = RESOURCE_TYPE @property def properties(self): """Gets the properties of an external resource""" if not self.resource_id: return try: resource = \ self.client.list_queues( QueueNamePrefix=self.resource_id) except (ParamValidationError, ClientError): pass else: return resource.get(QUEUE_URLS, [None])[0] return None @property def status(self): """Gets the status of an external resource""" return None def create(self, params): """ Create a new AWS SQS Queue. """ return self.make_client_call('create_queue', params) def delete(self, params=None): """ Deletes an existing AWS SQS Queue. """ self.logger.debug('Deleting %s with parameters: %s' % (self.type_name, params)) self.client.delete_queue(**params) @decorators.aws_resource(SQSQueue, RESOURCE_TYPE) def prepare(ctx, resource_config, **_): """Prepares an AWS SQS Queue""" # Save the parameters ctx.instance.runtime_properties['resource_config'] = resource_config @decorators.aws_resource(SQSQueue, RESOURCE_TYPE) def create(ctx, iface, resource_config, **_): """Creates an AWS SQS Queue""" # Create a copy of the resource config for clean manipulation. params = \ dict() if not resource_config else resource_config.copy() resource_id = \ utils.get_resource_id( ctx.node, ctx.instance, params.get(RESOURCE_NAME), use_instance_id=True ) params[RESOURCE_NAME] = resource_id utils.update_resource_id(ctx.instance, resource_id) queue_attributes = params.get('Attributes', {}) queue_attributes_policy = queue_attributes.get('Policy') if not isinstance(queue_attributes_policy, text_type): queue_attributes[POLICY] = json.dumps(queue_attributes_policy) # Actually create the resource create_response = iface.create(params) # Attempt to retrieve the ARN. try: resource_attributes = iface.client.get_queue_attributes( QueueUrl=create_response[QUEUE_URL], AttributeNames=[QUEUE_ARN]) except ClientError: utils.update_resource_arn( ctx.instance, None) else: utils.update_resource_arn( ctx.instance, resource_attributes.get('Attributes', {}).get(QUEUE_ARN)) utils.update_resource_id(ctx.instance, create_response[QUEUE_URL]) @decorators.aws_resource(SQSQueue, RESOURCE_TYPE, ignore_properties=True) def delete(iface, resource_config, **_): """Deletes an AWS SQS Queue""" # Create a copy of the resource config for clean manipulation. params = dict() if not resource_config else resource_config.copy() # Add the required QueueUrl parameter. if QUEUE_URL not in params: params.update({QUEUE_URL: iface.resource_id}) # Actually delete the resource iface.delete(params)
[ "cloudify_aws.common.utils.update_resource_arn", "json.dumps", "cloudify_aws.sqs.SQSBase.__init__", "cloudify_aws.common.decorators.aws_resource", "cloudify_aws.common.utils.update_resource_id" ]
[((2334, 2382), 'cloudify_aws.common.decorators.aws_resource', 'decorators.aws_resource', (['SQSQueue', 'RESOURCE_TYPE'], {}), '(SQSQueue, RESOURCE_TYPE)\n', (2357, 2382), False, 'from cloudify_aws.common import decorators, utils\n'), ((2561, 2609), 'cloudify_aws.common.decorators.aws_resource', 'decorators.aws_resource', (['SQSQueue', 'RESOURCE_TYPE'], {}), '(SQSQueue, RESOURCE_TYPE)\n', (2584, 2609), False, 'from cloudify_aws.common import decorators, utils\n'), ((3955, 4027), 'cloudify_aws.common.decorators.aws_resource', 'decorators.aws_resource', (['SQSQueue', 'RESOURCE_TYPE'], {'ignore_properties': '(True)'}), '(SQSQueue, RESOURCE_TYPE, ignore_properties=True)\n', (3978, 4027), False, 'from cloudify_aws.common import decorators, utils\n'), ((3064, 3115), 'cloudify_aws.common.utils.update_resource_id', 'utils.update_resource_id', (['ctx.instance', 'resource_id'], {}), '(ctx.instance, resource_id)\n', (3088, 3115), False, 'from cloudify_aws.common import decorators, utils\n'), ((3885, 3951), 'cloudify_aws.common.utils.update_resource_id', 'utils.update_resource_id', (['ctx.instance', 'create_response[QUEUE_URL]'], {}), '(ctx.instance, create_response[QUEUE_URL])\n', (3909, 3951), False, 'from cloudify_aws.common import decorators, utils\n'), ((1257, 1318), 'cloudify_aws.sqs.SQSBase.__init__', 'SQSBase.__init__', (['self', 'ctx_node', 'resource_id', 'client', 'logger'], {}), '(self, ctx_node, resource_id, client, logger)\n', (1273, 1318), False, 'from cloudify_aws.sqs import SQSBase\n'), ((3324, 3359), 'json.dumps', 'json.dumps', (['queue_attributes_policy'], {}), '(queue_attributes_policy)\n', (3334, 3359), False, 'import json\n'), ((3669, 3714), 'cloudify_aws.common.utils.update_resource_arn', 'utils.update_resource_arn', (['ctx.instance', 'None'], {}), '(ctx.instance, None)\n', (3694, 3714), False, 'from cloudify_aws.common import decorators, utils\n')]
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2016-12-18 00:17 from __future__ import unicode_literals import c3nav.mapdata.fields from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('mapdata', '0023_escalatorslope'), ] operations = [ migrations.CreateModel( name='OneWay', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.SlugField(unique=True, verbose_name='Name')), ('geometry', c3nav.mapdata.fields.GeometryField()), ('level', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='oneways', to='mapdata.Level', verbose_name='level')), ('package', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='oneways', to='mapdata.Package', verbose_name='map package')), ], options={ 'default_related_name': 'oneways', 'verbose_name_plural': 'Oneways', 'verbose_name': 'Oneway', }, ), ]
[ "django.db.models.SlugField", "django.db.models.AutoField", "django.db.models.ForeignKey" ]
[((452, 545), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (468, 545), False, 'from django.db import migrations, models\n'), ((569, 619), 'django.db.models.SlugField', 'models.SlugField', ([], {'unique': '(True)', 'verbose_name': '"""Name"""'}), "(unique=True, verbose_name='Name')\n", (585, 619), False, 'from django.db import migrations, models\n'), ((716, 849), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.CASCADE', 'related_name': '"""oneways"""', 'to': '"""mapdata.Level"""', 'verbose_name': '"""level"""'}), "(on_delete=django.db.models.deletion.CASCADE, related_name\n ='oneways', to='mapdata.Level', verbose_name='level')\n", (733, 849), False, 'from django.db import migrations, models\n'), ((875, 1016), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.CASCADE', 'related_name': '"""oneways"""', 'to': '"""mapdata.Package"""', 'verbose_name': '"""map package"""'}), "(on_delete=django.db.models.deletion.CASCADE, related_name\n ='oneways', to='mapdata.Package', verbose_name='map package')\n", (892, 1016), False, 'from django.db import migrations, models\n')]
"""Login to BUPT's network""" #!/usr/env/python3 # -*- coding: UTF-8 -*- import datetime import logging import logging.handlers import os import socket import sys import time import requests IS_WINDOWS_10 = os.name == 'nt' and sys.getwindowsversion().major == 10 if IS_WINDOWS_10: from win10toast import ToastNotifier STUDENT_ID = '1234567890' # 10 位数学号 PASSWORD = '<PASSWORD>' # 身份证号后 6 位 NETWORK_LINE = 'CUC-BRAS' # 宽带线路,默认为中国联通 LOG_PATH = 'portal_login.log' # 日志文件的路径 PROBE_URL = 'https://baidu.com' # SSL needed. PROBE_MAX_TIMEOUT = 4 MAX_TIME_TO_LOGIN = 30 def set_logger(log_path): """Log into log file at `log_path`, at level `INFO`""" logging.basicConfig( level=logging.INFO, format='[%(levelname)s] %(asctime)s %(filename)s:%(lineno)d %(message)s') file_handler = logging.handlers.TimedRotatingFileHandler( log_path, when='midnight', interval=1, backupCount=10, encoding='utf8', atTime=datetime.time(3, 30)) file_handler.setFormatter(logging.Formatter( '[%(levelname)s] %(asctime)s %(filename)s:%(lineno)d %(message)s')) logging.getLogger(None).addHandler(file_handler) logging.info("Start ....") def get_primary_ip() -> str: socket.setdefaulttimeout(PROBE_MAX_TIMEOUT) with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as test_socket: try: test_socket.connect(('8.8.8.8', 53)) primary_ip = test_socket.getsockname()[0] except socket.timeout: primary_ip = '127.0.0.1' return primary_ip def do_need_login() -> bool: try: requests.get(PROBE_URL, timeout=PROBE_MAX_TIMEOUT) return False except requests.exceptions.ConnectTimeout: return True class Notifier(object): def __init__(self): if IS_WINDOWS_10: self.toaster = ToastNotifier() def notify(self, text): """Send to text to both logging and toast hub.""" logging.info(text) if IS_WINDOWS_10: self.toaster.show_toast( '校园网认证', text, duration=None, threaded=True) def main(): """Core""" set_logger(LOG_PATH) notifier = Notifier() primary_ip = get_primary_ip() if primary_ip[:3] == '10.': do_need_isp_auth = False if do_need_login(): response_in = requests.post('http://10.3.8.216/login', data={ 'user': STUDENT_ID, 'pass': PASSWORD }) if '无需认证' in response_in.text or '成功' in response_in.text: notifier.notify('准入认证通过') response_out = requests.post('http://10.3.8.211', data={ 'DDDDD': STUDENT_ID, 'upass': PASSWORD, 'R1': '0' }) if '成功登录' in response_out.text: notifier.notify('准出认证通过') do_need_isp_auth = True else: notifier.notify('准出认证失败') else: notifier.notify('准入认证失败') else: notifier.notify('无需准入、准出认证') do_need_isp_auth = True if do_need_isp_auth: requests.post('http://10.3.8.217/login', data={ 'user': STUDENT_ID, 'pass': PASSWORD, 'NETWORK_LINE': NETWORK_LINE }) for i in range(MAX_TIME_TO_LOGIN): if requests.get('http://10.3.8.217/dial').json()['code'] == 0: do_need_isp_auth = True break time.sleep(1) if do_need_isp_auth: notifier.notify('宽带认证通过') else: notifier.notify('宽带认证失败') else: notifier.notify('不进行宽带认证') else: notifier.notify('非校园网,无需认证') if __name__ == '__main__': main()
[ "logging.basicConfig", "logging.getLogger", "requests.post", "sys.getwindowsversion", "datetime.time", "socket.socket", "logging.Formatter", "win10toast.ToastNotifier", "requests.get", "time.sleep", "logging.info", "socket.setdefaulttimeout" ]
[((666, 784), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'format': '"""[%(levelname)s] %(asctime)s %(filename)s:%(lineno)d %(message)s"""'}), "(level=logging.INFO, format=\n '[%(levelname)s] %(asctime)s %(filename)s:%(lineno)d %(message)s')\n", (685, 784), False, 'import logging\n'), ((1150, 1176), 'logging.info', 'logging.info', (['"""Start ...."""'], {}), "('Start ....')\n", (1162, 1176), False, 'import logging\n'), ((1212, 1255), 'socket.setdefaulttimeout', 'socket.setdefaulttimeout', (['PROBE_MAX_TIMEOUT'], {}), '(PROBE_MAX_TIMEOUT)\n', (1236, 1255), False, 'import socket\n'), ((998, 1087), 'logging.Formatter', 'logging.Formatter', (['"""[%(levelname)s] %(asctime)s %(filename)s:%(lineno)d %(message)s"""'], {}), "(\n '[%(levelname)s] %(asctime)s %(filename)s:%(lineno)d %(message)s')\n", (1015, 1087), False, 'import logging\n'), ((1265, 1313), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_DGRAM'], {}), '(socket.AF_INET, socket.SOCK_DGRAM)\n', (1278, 1313), False, 'import socket\n'), ((1584, 1634), 'requests.get', 'requests.get', (['PROBE_URL'], {'timeout': 'PROBE_MAX_TIMEOUT'}), '(PROBE_URL, timeout=PROBE_MAX_TIMEOUT)\n', (1596, 1634), False, 'import requests\n'), ((1937, 1955), 'logging.info', 'logging.info', (['text'], {}), '(text)\n', (1949, 1955), False, 'import logging\n'), ((229, 252), 'sys.getwindowsversion', 'sys.getwindowsversion', ([], {}), '()\n', (250, 252), False, 'import sys\n'), ((946, 966), 'datetime.time', 'datetime.time', (['(3)', '(30)'], {}), '(3, 30)\n', (959, 966), False, 'import datetime\n'), ((1097, 1120), 'logging.getLogger', 'logging.getLogger', (['None'], {}), '(None)\n', (1114, 1120), False, 'import logging\n'), ((1826, 1841), 'win10toast.ToastNotifier', 'ToastNotifier', ([], {}), '()\n', (1839, 1841), False, 'from win10toast import ToastNotifier\n'), ((2313, 2402), 'requests.post', 'requests.post', (['"""http://10.3.8.216/login"""'], {'data': "{'user': STUDENT_ID, 'pass': PASSWORD}"}), "('http://10.3.8.216/login', data={'user': STUDENT_ID, 'pass':\n PASSWORD})\n", (2326, 2402), False, 'import requests\n'), ((3158, 3277), 'requests.post', 'requests.post', (['"""http://10.3.8.217/login"""'], {'data': "{'user': STUDENT_ID, 'pass': PASSWORD, 'NETWORK_LINE': NETWORK_LINE}"}), "('http://10.3.8.217/login', data={'user': STUDENT_ID, 'pass':\n PASSWORD, 'NETWORK_LINE': NETWORK_LINE})\n", (3171, 3277), False, 'import requests\n'), ((2589, 2685), 'requests.post', 'requests.post', (['"""http://10.3.8.211"""'], {'data': "{'DDDDD': STUDENT_ID, 'upass': PASSWORD, 'R1': '0'}"}), "('http://10.3.8.211', data={'DDDDD': STUDENT_ID, 'upass':\n PASSWORD, 'R1': '0'})\n", (2602, 2685), False, 'import requests\n'), ((3548, 3561), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (3558, 3561), False, 'import time\n'), ((3402, 3440), 'requests.get', 'requests.get', (['"""http://10.3.8.217/dial"""'], {}), "('http://10.3.8.217/dial')\n", (3414, 3440), False, 'import requests\n')]
import hashlib import typing from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list from .formats.join import JoinTable from .join_common import Structure, context_column, foreign_column, local_column from .join_key import KeyResolver from .sql import SqlQuery, SqlTableExpr, table_fields, update_excluded from .string import indent def create_queue( id: str, table_id: str, structure: Structure, resolver: KeyResolver, tables: typing.Dict[str, JoinTable], context: typing.List[str], ): table = tables[table_id] dep = table.join foreign_table = tables[dep] if table.lock_id is not None: lock_id = table.lock_id else: digest = hashlib.md5(f"{id}__{table_id}".encode("utf-8")).digest() lock_id = int.from_bytes(digest[0:2], "big", signed=True) lock_base = lock_id * (2 ** 48) queue_table = structure.queue_table(table_id) column_names = [column.name for column in table.key] if table.key else ["_"] local_columns = [local_column(column) for column in column_names] foreign_columns = [foreign_column(column) for column in table.join_key] context_columns = [context_column(setting) for setting in context] columns = ( [ f"{SqlObject(SqlId('l'), SqlId(column))} AS {local_column(column)}" for column in column_names ] + [ f"{SqlObject(SqlId('f'), SqlId(column))} AS {foreign_column(column)}" for column in table.join_key ] + [f"NULL::text AS {context_column(setting)}" for setting in context] + ["NULL::bigint AS seq", "NULL::bigint AS lock", "NULL::bigint AS count"] ) yield f""" CREATE TABLE {queue_table} AS SELECT {sql_list(columns)} FROM {table.sql} AS l CROSS JOIN {foreign_table.sql} AS f WITH NO DATA """.strip() yield f""" ALTER TABLE {queue_table} ADD PRIMARY KEY ({sql_list(local_columns + context_columns)}), ALTER count SET NOT NULL, ALTER count SET DEFAULT 0, ALTER lock ADD GENERATED BY DEFAULT AS IDENTITY, ALTER lock SET NOT NULL, ALTER seq ADD GENERATED BY DEFAULT AS IDENTITY, ALTER seq SET NOT NULL """.strip() yield f""" COMMENT ON TABLE {queue_table} IS {SqlString(f"Asynchronous processing of changes to {table.sql}")} """.strip() for column in column_names: yield f""" COMMENT ON COLUMN {queue_table}.{local_column(column)} IS {SqlString(f"{table.sql} key: {SqlId(column)}")} """ for column in table.join_key: yield f""" COMMENT ON COLUMN {queue_table}.{foreign_column(column)} IS {SqlString(f"{foreign_table.sql} iterator: {SqlId(column)}")} """ yield f""" COMMENT ON COLUMN {queue_table}.seq IS 'Order to process' """.strip() yield f""" COMMENT ON COLUMN {queue_table}.lock IS 'Lock ID (add to base value {lock_base})' """.strip() yield f""" COMMENT ON COLUMN {queue_table}.count IS 'Count of records processed' """.strip() yield f""" CREATE INDEX ON {queue_table} (seq) """.strip() foreign_key_table = SqlObject(SqlId("_foreign_key")) item = SqlId("_item") new_item = SqlId("_new_item") new_fields = ["''" for _ in context] + ["0", "0", "_item.count + count(*) OVER ()"] get_item = f""" SELECT {table_fields(item, local_columns)}, {table_fields(SqlId("k"), [SqlId(column) for column in table.join_key])}, {sql_list(new_fields)} INTO _new_item FROM {SqlObject(foreign_key_table)} AS k ORDER BY {table_fields(SqlId("k"), table.join_key)} DESC """.strip() if table.join_on is not None: join = f""" JOIN (VALUES ({table_fields(item, local_columns)})) AS {SqlId(table_id)} ({sql_list(SqlId(col.name) for col in table.key)}) ON {table.join_on} """.strip() else: join = "" key1_query = f""" SELECT {SqlId(dep)}.* FROM {foreign_table.sql} AS {SqlId(dep)} {join} ORDER BY {sql_list(SqlObject(SqlId(dep), SqlId(name)) for name in table.join_key)} LIMIT max_records """.strip() gather1 = resolver.sql( foreign_key_table, exprs=[SqlTableExpr(foreign_key_table, key1_query)], last_expr=get_item, ) key2_query = f""" SELECT {SqlId(dep)}.* FROM {foreign_table.sql} AS {SqlId(dep)} {join} WHERE ({table_fields(item, foreign_columns)}) < ({table_fields(SqlId(dep), (SqlId(column) for column in table.join_key))}) ORDER BY {sql_list(SqlObject(SqlId(dep), SqlId(name)) for name in table.join_key)} LIMIT max_records """.strip() gather2 = resolver.sql( foreign_key_table, exprs=[SqlTableExpr(foreign_key_table, key2_query)], last_expr=get_item, ) context_vars = "\n".join( f"{SqlId(f'_context_{setting}')} text := current_setting({SqlString(setting)}, true);" for setting in context ) set_context = "\n".join( f"PERFORM set_config({SqlString(setting)}, _item.{context_column(setting)}, true);" for setting in context ) unset_context = "\n".join( f"PERFORM set_config({SqlString(setting)}, {SqlId(f'_context_{setting}')}, true);" for setting in context ) process_function = structure.queue_process_function(table_id) yield f""" CREATE FUNCTION {process_function} (max_records bigint) RETURNS bool LANGUAGE plpgsql AS $$ DECLARE _item {queue_table}; _new_item {queue_table}; {context_vars} BEGIN -- find item SELECT (q.*) INTO _item FROM {queue_table} AS q WHERE pg_try_advisory_xact_lock({lock_base} + q.lock) ORDER BY q.seq LIMIT 1; IF _item IS NULL THEN -- if no item found, exit RETURN false; END IF; {indent(set_context, 2)} IF ({table_fields(item, (foreign_column(column) for column in table.join_key))}) IS NULL THEN -- if there is no iterator, start at the beginning {indent(gather1, 3)} ELSE -- if there is an iterator, start at the iterator {indent(gather2, 3)} END IF; IF _new_item IS NULL THEN -- if the iterator was at the end, remove the queue item DELETE FROM {queue_table} AS q WHERE ({table_fields(SqlId("q"), local_columns + context_columns)}, q.seq) = ({table_fields(item, local_columns + context_columns)}, _item.seq); ELSE -- update the queue item with the new iterator UPDATE {queue_table} AS q SET {sql_list(f'{column} = (_new_item).{column}' for column in foreign_columns)}, count = _new_item.count, seq = nextval(pg_get_serial_sequence({SqlString(str(queue_table))}, 'seq')) WHERE ({table_fields(SqlId("q"), local_columns)}, q.seq) = ({table_fields(item, local_columns)}, _item.seq); END IF; {indent(unset_context, 2)} -- notify listeners that the queue has been updated NOTIFY {SqlId(str(queue_table))}; RETURN true; END; $$ """.strip() yield f""" COMMENT ON FUNCTION {process_function} IS {SqlString(f"Refresh for {queue_table}")} """.strip() def enqueue_sql( id: str, context: typing.List[str], table: JoinTable, structure: Structure, key_query: str, exprs: typing.List[SqlTableExpr], last_expr: typing.Optional[str], ): queue_table = structure.queue_table(id) column_names = [column.name for column in table.key] if table.key else ["_"] local_columns = [local_column(column) for column in column_names] context_columns = [context_column(setting) for setting in context] if table.key: order = ( f"ORDER BY {sql_list(SqlNumber(i + 1) for i, _ in enumerate(table.key))}" ) else: order = "" if context: settings = sql_list( f"coalesce(current_setting({SqlString(f'context.{setting}')}, true), '')" for setting in context ) key_query = f""" SELECT *, {settings} FROM ( {indent(key_query, 1)} ) AS t """.strip() insert = f""" INSERT INTO {queue_table} ({sql_list(local_columns + context_columns)}) {key_query} {order} ON CONFLICT ({sql_list(local_columns + context_columns)}) DO UPDATE SET {update_excluded(foreign_column(column) for column in table.join_key)}, count = excluded.count, seq = excluded.seq """.strip() query = SqlQuery(insert, expressions=exprs) if last_expr is not None: query.append(SqlId("_other"), last_expr) return f""" {query}; NOTIFY {SqlId(str(queue_table))}; """.strip()
[ "pg_sql.SqlId", "pg_sql.SqlObject", "pg_sql.SqlString", "pg_sql.SqlNumber", "pg_sql.sql_list" ]
[((3099, 3113), 'pg_sql.SqlId', 'SqlId', (['"""_item"""'], {}), "('_item')\n", (3104, 3113), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((3129, 3147), 'pg_sql.SqlId', 'SqlId', (['"""_new_item"""'], {}), "('_new_item')\n", (3134, 3147), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((3064, 3085), 'pg_sql.SqlId', 'SqlId', (['"""_foreign_key"""'], {}), "('_foreign_key')\n", (3069, 3085), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((8296, 8311), 'pg_sql.SqlId', 'SqlId', (['"""_other"""'], {}), "('_other')\n", (8301, 8311), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((3398, 3418), 'pg_sql.sql_list', 'sql_list', (['new_fields'], {}), '(new_fields)\n', (3406, 3418), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((3441, 3469), 'pg_sql.SqlObject', 'SqlObject', (['foreign_key_table'], {}), '(foreign_key_table)\n', (3450, 3469), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((3823, 3833), 'pg_sql.SqlId', 'SqlId', (['dep'], {}), '(dep)\n', (3828, 3833), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((3864, 3874), 'pg_sql.SqlId', 'SqlId', (['dep'], {}), '(dep)\n', (3869, 3874), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((4183, 4193), 'pg_sql.SqlId', 'SqlId', (['dep'], {}), '(dep)\n', (4188, 4193), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((4224, 4234), 'pg_sql.SqlId', 'SqlId', (['dep'], {}), '(dep)\n', (4229, 4234), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((4664, 4692), 'pg_sql.SqlId', 'SqlId', (['f"""_context_{setting}"""'], {}), "(f'_context_{setting}')\n", (4669, 4692), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((4719, 4737), 'pg_sql.SqlString', 'SqlString', (['setting'], {}), '(setting)\n', (4728, 4737), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((4844, 4862), 'pg_sql.SqlString', 'SqlString', (['setting'], {}), '(setting)\n', (4853, 4862), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((5004, 5022), 'pg_sql.SqlString', 'SqlString', (['setting'], {}), '(setting)\n', (5013, 5022), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((5026, 5054), 'pg_sql.SqlId', 'SqlId', (['f"""_context_{setting}"""'], {}), "(f'_context_{setting}')\n", (5031, 5054), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((7934, 7975), 'pg_sql.sql_list', 'sql_list', (['(local_columns + context_columns)'], {}), '(local_columns + context_columns)\n', (7942, 7975), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((8012, 8053), 'pg_sql.sql_list', 'sql_list', (['(local_columns + context_columns)'], {}), '(local_columns + context_columns)\n', (8020, 8053), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((1748, 1765), 'pg_sql.sql_list', 'sql_list', (['columns'], {}), '(columns)\n', (1756, 1765), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((1920, 1961), 'pg_sql.sql_list', 'sql_list', (['(local_columns + context_columns)'], {}), '(local_columns + context_columns)\n', (1928, 1961), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((2242, 2305), 'pg_sql.SqlString', 'SqlString', (['f"""Asynchronous processing of changes to {table.sql}"""'], {}), "(f'Asynchronous processing of changes to {table.sql}')\n", (2251, 2305), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((3335, 3345), 'pg_sql.SqlId', 'SqlId', (['"""k"""'], {}), "('k')\n", (3340, 3345), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((3499, 3509), 'pg_sql.SqlId', 'SqlId', (['"""k"""'], {}), "('k')\n", (3504, 3509), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((3660, 3675), 'pg_sql.SqlId', 'SqlId', (['table_id'], {}), '(table_id)\n', (3665, 3675), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((4313, 4323), 'pg_sql.SqlId', 'SqlId', (['dep'], {}), '(dep)\n', (4318, 4323), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((6346, 6420), 'pg_sql.sql_list', 'sql_list', (["(f'{column} = (_new_item).{column}' for column in foreign_columns)"], {}), "(f'{column} = (_new_item).{column}' for column in foreign_columns)\n", (6354, 6420), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((6909, 6948), 'pg_sql.SqlString', 'SqlString', (['f"""Refresh for {queue_table}"""'], {}), "(f'Refresh for {queue_table}')\n", (6918, 6948), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((7501, 7517), 'pg_sql.SqlNumber', 'SqlNumber', (['(i + 1)'], {}), '(i + 1)\n', (7510, 7517), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((7679, 7710), 'pg_sql.SqlString', 'SqlString', (['f"""context.{setting}"""'], {}), "(f'context.{setting}')\n", (7688, 7710), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((3348, 3361), 'pg_sql.SqlId', 'SqlId', (['column'], {}), '(column)\n', (3353, 3361), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((4326, 4339), 'pg_sql.SqlId', 'SqlId', (['column'], {}), '(column)\n', (4331, 4339), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((6099, 6109), 'pg_sql.SqlId', 'SqlId', (['"""q"""'], {}), "('q')\n", (6104, 6109), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((6577, 6587), 'pg_sql.SqlId', 'SqlId', (['"""q"""'], {}), "('q')\n", (6582, 6587), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((1267, 1277), 'pg_sql.SqlId', 'SqlId', (['"""l"""'], {}), "('l')\n", (1272, 1277), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((1279, 1292), 'pg_sql.SqlId', 'SqlId', (['column'], {}), '(column)\n', (1284, 1292), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((1408, 1418), 'pg_sql.SqlId', 'SqlId', (['"""f"""'], {}), "('f')\n", (1413, 1418), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((1420, 1433), 'pg_sql.SqlId', 'SqlId', (['column'], {}), '(column)\n', (1425, 1433), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((2468, 2481), 'pg_sql.SqlId', 'SqlId', (['column'], {}), '(column)\n', (2473, 2481), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((2648, 2661), 'pg_sql.SqlId', 'SqlId', (['column'], {}), '(column)\n', (2653, 2661), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((3688, 3703), 'pg_sql.SqlId', 'SqlId', (['col.name'], {}), '(col.name)\n', (3693, 3703), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((3919, 3929), 'pg_sql.SqlId', 'SqlId', (['dep'], {}), '(dep)\n', (3924, 3929), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((3931, 3942), 'pg_sql.SqlId', 'SqlId', (['name'], {}), '(name)\n', (3936, 3942), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((4402, 4412), 'pg_sql.SqlId', 'SqlId', (['dep'], {}), '(dep)\n', (4407, 4412), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n'), ((4414, 4425), 'pg_sql.SqlId', 'SqlId', (['name'], {}), '(name)\n', (4419, 4425), False, 'from pg_sql import SqlId, SqlNumber, SqlObject, SqlString, sql_list\n')]
import pytest import optuna from optuna import type_checking if type_checking.TYPE_CHECKING: from optuna.trial import Trial # NOQA MIN_RESOURCE = 1 MAX_RESOURCE = 16 REDUCTION_FACTOR = 2 N_BRACKETS = 4 EARLY_STOPPING_RATE_LOW = 0 EARLY_STOPPING_RATE_HIGH = 3 N_REPORTS = 10 EXPECTED_N_TRIALS_PER_BRACKET = 10 def test_hyperband_experimental_warning() -> None: with pytest.warns(optuna.exceptions.ExperimentalWarning): optuna.pruners.HyperbandPruner( min_resource=MIN_RESOURCE, max_resource=MAX_RESOURCE, reduction_factor=REDUCTION_FACTOR ) def test_hyperband_deprecation_warning() -> None: with pytest.deprecated_call(): optuna.pruners.HyperbandPruner( min_resource=MIN_RESOURCE, max_resource=MAX_RESOURCE, reduction_factor=REDUCTION_FACTOR, n_brackets=N_BRACKETS, ) def test_hyperband_pruner_intermediate_values(): # type: () -> None pruner = optuna.pruners.HyperbandPruner( min_resource=MIN_RESOURCE, max_resource=MAX_RESOURCE, reduction_factor=REDUCTION_FACTOR ) study = optuna.study.create_study(sampler=optuna.samplers.RandomSampler(), pruner=pruner) def objective(trial): # type: (Trial) -> float for i in range(N_REPORTS): trial.report(i, step=i) return 1.0 study.optimize(objective, n_trials=N_BRACKETS * EXPECTED_N_TRIALS_PER_BRACKET) trials = study.trials assert len(trials) == N_BRACKETS * EXPECTED_N_TRIALS_PER_BRACKET def test_bracket_study(): # type: () -> None pruner = optuna.pruners.HyperbandPruner( min_resource=MIN_RESOURCE, max_resource=MAX_RESOURCE, reduction_factor=REDUCTION_FACTOR ) study = optuna.study.create_study(sampler=optuna.samplers.RandomSampler(), pruner=pruner) bracket_study = pruner._create_bracket_study(study, 0) with pytest.raises(AttributeError): bracket_study.optimize(lambda *args: 1.0) for attr in ("set_user_attr", "set_system_attr"): with pytest.raises(AttributeError): getattr(bracket_study, attr)("abc", 100) for attr in ("user_attrs", "system_attrs"): with pytest.raises(AttributeError): getattr(bracket_study, attr) with pytest.raises(AttributeError): bracket_study.trials_dataframe() bracket_study.get_trials() bracket_study.direction bracket_study._storage bracket_study._study_id bracket_study.pruner bracket_study.study_name # As `_BracketStudy` is defined inside `HyperbandPruner`, # we cannot do `assert isinstance(bracket_study, _BracketStudy)`. # This is why the below line is ignored by mypy checks. bracket_study._bracket_id # type: ignore
[ "optuna.samplers.RandomSampler", "pytest.deprecated_call", "pytest.raises", "optuna.pruners.HyperbandPruner", "pytest.warns" ]
[((968, 1092), 'optuna.pruners.HyperbandPruner', 'optuna.pruners.HyperbandPruner', ([], {'min_resource': 'MIN_RESOURCE', 'max_resource': 'MAX_RESOURCE', 'reduction_factor': 'REDUCTION_FACTOR'}), '(min_resource=MIN_RESOURCE, max_resource=\n MAX_RESOURCE, reduction_factor=REDUCTION_FACTOR)\n', (998, 1092), False, 'import optuna\n'), ((1594, 1718), 'optuna.pruners.HyperbandPruner', 'optuna.pruners.HyperbandPruner', ([], {'min_resource': 'MIN_RESOURCE', 'max_resource': 'MAX_RESOURCE', 'reduction_factor': 'REDUCTION_FACTOR'}), '(min_resource=MIN_RESOURCE, max_resource=\n MAX_RESOURCE, reduction_factor=REDUCTION_FACTOR)\n', (1624, 1718), False, 'import optuna\n'), ((380, 431), 'pytest.warns', 'pytest.warns', (['optuna.exceptions.ExperimentalWarning'], {}), '(optuna.exceptions.ExperimentalWarning)\n', (392, 431), False, 'import pytest\n'), ((441, 565), 'optuna.pruners.HyperbandPruner', 'optuna.pruners.HyperbandPruner', ([], {'min_resource': 'MIN_RESOURCE', 'max_resource': 'MAX_RESOURCE', 'reduction_factor': 'REDUCTION_FACTOR'}), '(min_resource=MIN_RESOURCE, max_resource=\n MAX_RESOURCE, reduction_factor=REDUCTION_FACTOR)\n', (471, 565), False, 'import optuna\n'), ((644, 668), 'pytest.deprecated_call', 'pytest.deprecated_call', ([], {}), '()\n', (666, 668), False, 'import pytest\n'), ((678, 825), 'optuna.pruners.HyperbandPruner', 'optuna.pruners.HyperbandPruner', ([], {'min_resource': 'MIN_RESOURCE', 'max_resource': 'MAX_RESOURCE', 'reduction_factor': 'REDUCTION_FACTOR', 'n_brackets': 'N_BRACKETS'}), '(min_resource=MIN_RESOURCE, max_resource=\n MAX_RESOURCE, reduction_factor=REDUCTION_FACTOR, n_brackets=N_BRACKETS)\n', (708, 825), False, 'import optuna\n'), ((1891, 1920), 'pytest.raises', 'pytest.raises', (['AttributeError'], {}), '(AttributeError)\n', (1904, 1920), False, 'import pytest\n'), ((2268, 2297), 'pytest.raises', 'pytest.raises', (['AttributeError'], {}), '(AttributeError)\n', (2281, 2297), False, 'import pytest\n'), ((1149, 1180), 'optuna.samplers.RandomSampler', 'optuna.samplers.RandomSampler', ([], {}), '()\n', (1178, 1180), False, 'import optuna\n'), ((1774, 1805), 'optuna.samplers.RandomSampler', 'optuna.samplers.RandomSampler', ([], {}), '()\n', (1803, 1805), False, 'import optuna\n'), ((2040, 2069), 'pytest.raises', 'pytest.raises', (['AttributeError'], {}), '(AttributeError)\n', (2053, 2069), False, 'import pytest\n'), ((2186, 2215), 'pytest.raises', 'pytest.raises', (['AttributeError'], {}), '(AttributeError)\n', (2199, 2215), False, 'import pytest\n')]
# -*- coding: utf-8 -*- # czat/urls.py from django.conf.urls import url from . import views # import widoków aplikacji app_name = 'czat' # przestrzeń nazw aplikacji urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^loguj/$', views.loguj, name='loguj'), url(r'^wyloguj/$', views.wyloguj, name='wyloguj'), url(r'^wiadomosci/$', views.wiadomosci, name='wiadomosci'), ]
[ "django.conf.urls.url" ]
[((189, 225), 'django.conf.urls.url', 'url', (['"""^$"""', 'views.index'], {'name': '"""index"""'}), "('^$', views.index, name='index')\n", (192, 225), False, 'from django.conf.urls import url\n'), ((232, 274), 'django.conf.urls.url', 'url', (['"""^loguj/$"""', 'views.loguj'], {'name': '"""loguj"""'}), "('^loguj/$', views.loguj, name='loguj')\n", (235, 274), False, 'from django.conf.urls import url\n'), ((281, 329), 'django.conf.urls.url', 'url', (['"""^wyloguj/$"""', 'views.wyloguj'], {'name': '"""wyloguj"""'}), "('^wyloguj/$', views.wyloguj, name='wyloguj')\n", (284, 329), False, 'from django.conf.urls import url\n'), ((336, 393), 'django.conf.urls.url', 'url', (['"""^wiadomosci/$"""', 'views.wiadomosci'], {'name': '"""wiadomosci"""'}), "('^wiadomosci/$', views.wiadomosci, name='wiadomosci')\n", (339, 393), False, 'from django.conf.urls import url\n')]
#!/usr/bin/python # export PYTHONPATH=/home/lukas/anaconda3/envs/detectron/bin/python # import some common libraries from genericpath import isdir import numpy as np import os import json import cv2 import time import csv import detectron2 from detectron2 import model_zoo from detectron2.engine import DefaultPredictor from detectron2.config import get_cfg from detectron2.data import MetadataCatalog, DatasetCatalog from detectron2.utils.visualizer import Visualizer from dataclasses import dataclass @dataclass class Params: target_path: str = '/home/lukas/Documents/Datasets/flat_dataset/run1' model: str = 'COCO-PanopticSegmentation/panoptic_fpn_R_101_3x.yaml' output_label_file: str = '' # Leave empty to not write labels. rio: bool = False def create_labels(meta_data, output_file: str = ""): sizes = [ 'L', 'M', 'L', 'M', 'L', 'L', 'L', 'L', 'L', 'M', 'M', 'M', 'S', 'L', 'S', 'M', 'M', 'L', 'M', 'L', 'L', 'L', 'L', 'L', 'M', 'S', 'S', 'S', 'S', 'S', 'M', 'M', 'S', 'M', 'M', 'S', 'S', 'M', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'S', 'M', 'L', 'M', 'L', 'M', 'M', 'M', 'S', 'S', 'S', 'S', 'S', 'M', 'M', 'S', 'M', 'L', 'S', 'M', 'M', 'S', 'M', 'S', 'S' ] if (output_file): with open(output_file, 'w') as csvfile: writer = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) writer.writerow( ["InstanceID", "ClassID", "PanopticID", "Name", "Size"]) writer.writerow([0, 0, 0, "Unknown", "M"]) id = 1 for label in meta_data.stuff_classes: writer.writerow([id, id, 0, label, 'L']) id += 1 for i, label in enumerate(meta_data.thing_classes): writer.writerow([id, id, 1, label, sizes[i]]) id += 1 return len(meta_data.stuff_classes), "Saved %i labels in '%s'." % ( id, output_file) else: return len(meta_data.stuff_classes), "" def create_predictions(params: Params): # Verify. if not os.path.isdir(params.target_path): print("Error: Directory '%s' does not exist." % params.target_path) return print("Processing target '%s'." % params.target_path) # Setup model. print("Setting up Detectron2 model... ", end="", flush="True") cfg = get_cfg() cfg.merge_from_file(model_zoo.get_config_file(params.model)) cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url(params.model) cfg.MODEL.DEVICE = 'cpu' predictor = DefaultPredictor(cfg) print("done!") # Setup labels. print("Setting up labels... ", end="", flush="True") meta_data = MetadataCatalog.get(cfg.DATASETS.TRAIN[0]) label_offset, msg = create_labels(meta_data, params.output_label_file) print("done!") if msg: print(msg) # Get files to parse. files = [ o for o in os.listdir(params.target_path) if os.path.isfile(os.path.join(params.target_path, o)) ] if params.rio: files = [f for f in files if f.endswith('.color.jpg')] else: files = [f for f in files if f.endswith('.color.jpg')] times = [] # Run inference. msg = "Predicting %i images... " % len(files) for i, im_file in enumerate(files): print(msg + '%.1f%%' % (i / len(files) * 100, ), end='\r', flush=True) im = cv2.imread(os.path.join(params.target_path, im_file)) if params.rio: im = cv2.rotate(im, cv2.ROTATE_90_CLOCKWISE) # Predict. t1 = time.perf_counter() panoptic_seg, segments_info = predictor(im)["panoptic_seg"] t2 = time.perf_counter() times.append(t2 - t1) # Write output. if params.rio: file_id = im_file[:12] else: file_id = im_file[:6] id_img = panoptic_seg.numpy() cv2.imwrite( os.path.join(params.target_path, file_id + "_predicted2.png"), id_img) for segment_info in segments_info: if segment_info['isthing']: segment_info['category_id'] += label_offset segment_info['category_id'] += 1 # Compensate for unknown class. with open(os.path.join(params.target_path, file_id + "_labels.json"), 'w') as json_file: json.dump(segments_info, json_file) print(msg + "done!") # Finish. times = np.array(times, dtype=float) * 1000 print("Average inference time was %.1f +/- %.1f ms per frame." % (np.mean(times), np.std(times))) print("Finished parsing '%s'." % params.target_path) if __name__ == '__main__': # Params. params = Params() params.model = "COCO-PanopticSegmentation/panoptic_fpn_R_101_3x.yaml" params.target_path = '/home/lukas/Documents/Datasets/flat_dataset/run2' params.output_label_file = '' #'/home/lukas/Documents/Datasets/flat_dataset/detectron_labels.csv' params.rio = True # Run if params.rio: base_dir = '/home/lukas/Documents/Datasets/3RScan' dirs = [ x for x in os.listdir(base_dir) if os.path.isdir(base_dir + "/" + x) and x != 'not_used' ] for d in dirs: params.target_path = os.path.join(base_dir, d, "sequence") create_predictions(params) else: create_predictions(params)
[ "numpy.mean", "os.listdir", "detectron2.config.get_cfg", "csv.writer", "os.path.join", "time.perf_counter", "cv2.rotate", "numpy.array", "detectron2.model_zoo.get_checkpoint_url", "os.path.isdir", "detectron2.model_zoo.get_config_file", "detectron2.data.MetadataCatalog.get", "numpy.std", "...
[((2523, 2532), 'detectron2.config.get_cfg', 'get_cfg', ([], {}), '()\n', (2530, 2532), False, 'from detectron2.config import get_cfg\n'), ((2622, 2664), 'detectron2.model_zoo.get_checkpoint_url', 'model_zoo.get_checkpoint_url', (['params.model'], {}), '(params.model)\n', (2650, 2664), False, 'from detectron2 import model_zoo\n'), ((2710, 2731), 'detectron2.engine.DefaultPredictor', 'DefaultPredictor', (['cfg'], {}), '(cfg)\n', (2726, 2731), False, 'from detectron2.engine import DefaultPredictor\n'), ((2845, 2887), 'detectron2.data.MetadataCatalog.get', 'MetadataCatalog.get', (['cfg.DATASETS.TRAIN[0]'], {}), '(cfg.DATASETS.TRAIN[0])\n', (2864, 2887), False, 'from detectron2.data import MetadataCatalog, DatasetCatalog\n'), ((2242, 2275), 'os.path.isdir', 'os.path.isdir', (['params.target_path'], {}), '(params.target_path)\n', (2255, 2275), False, 'import os\n'), ((2557, 2596), 'detectron2.model_zoo.get_config_file', 'model_zoo.get_config_file', (['params.model'], {}), '(params.model)\n', (2582, 2596), False, 'from detectron2 import model_zoo\n'), ((3715, 3734), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (3732, 3734), False, 'import time\n'), ((3816, 3835), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (3833, 3835), False, 'import time\n'), ((4588, 4616), 'numpy.array', 'np.array', (['times'], {'dtype': 'float'}), '(times, dtype=float)\n', (4596, 4616), True, 'import numpy as np\n'), ((1382, 1458), 'csv.writer', 'csv.writer', (['csvfile'], {'delimiter': '""","""', 'quotechar': '"""|"""', 'quoting': 'csv.QUOTE_MINIMAL'}), "(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)\n", (1392, 1458), False, 'import csv\n'), ((3073, 3103), 'os.listdir', 'os.listdir', (['params.target_path'], {}), '(params.target_path)\n', (3083, 3103), False, 'import os\n'), ((3558, 3599), 'os.path.join', 'os.path.join', (['params.target_path', 'im_file'], {}), '(params.target_path, im_file)\n', (3570, 3599), False, 'import os\n'), ((3642, 3681), 'cv2.rotate', 'cv2.rotate', (['im', 'cv2.ROTATE_90_CLOCKWISE'], {}), '(im, cv2.ROTATE_90_CLOCKWISE)\n', (3652, 3681), False, 'import cv2\n'), ((4068, 4129), 'os.path.join', 'os.path.join', (['params.target_path', "(file_id + '_predicted2.png')"], {}), "(params.target_path, file_id + '_predicted2.png')\n", (4080, 4129), False, 'import os\n'), ((4500, 4535), 'json.dump', 'json.dump', (['segments_info', 'json_file'], {}), '(segments_info, json_file)\n', (4509, 4535), False, 'import json\n'), ((5418, 5455), 'os.path.join', 'os.path.join', (['base_dir', 'd', '"""sequence"""'], {}), "(base_dir, d, 'sequence')\n", (5430, 5455), False, 'import os\n'), ((3130, 3165), 'os.path.join', 'os.path.join', (['params.target_path', 'o'], {}), '(params.target_path, o)\n', (3142, 3165), False, 'import os\n'), ((4391, 4449), 'os.path.join', 'os.path.join', (['params.target_path', "(file_id + '_labels.json')"], {}), "(params.target_path, file_id + '_labels.json')\n", (4403, 4449), False, 'import os\n'), ((4704, 4718), 'numpy.mean', 'np.mean', (['times'], {}), '(times)\n', (4711, 4718), True, 'import numpy as np\n'), ((4720, 4733), 'numpy.std', 'np.std', (['times'], {}), '(times)\n', (4726, 4733), True, 'import numpy as np\n'), ((5262, 5282), 'os.listdir', 'os.listdir', (['base_dir'], {}), '(base_dir)\n', (5272, 5282), False, 'import os\n'), ((5298, 5331), 'os.path.isdir', 'os.path.isdir', (["(base_dir + '/' + x)"], {}), "(base_dir + '/' + x)\n", (5311, 5331), False, 'import os\n')]
from Tweets2Graph import Tweets2Graph from datetime import datetime import networkx as nx import matplotlib.pyplot as plt import os import time from dotenv import load_dotenv load_dotenv() if __name__ == "__main__": from examples import generate_csv #generate_csv.generate(10,10,33) backend = Tweets2Graph(interactions=["retweet","quote","reply"], username="screen_name") backend.from_stream(hashtags=["#covid"],skip_error=False) time.sleep(10^100) print("Loading data",datetime.now()) #backend.from_folder("examples/csv/") backend.from_user(users=["ollo_tv"]) print("Number of tweets", backend.data.shape) print("Fit",datetime.now()) backend.fit() print("Transform", datetime.now()) graph = backend.transform() print("show",datetime.now()) nx.draw(graph,with_labels=False,node_size=5,font_size=2,font_color="red",node_color="black") plt.show() print("Transform",datetime.now()) graph = backend.transform() print("END",datetime.now()) nx.draw(graph,with_labels=True,node_size=5,font_size=15,font_color="red",node_color="black") plt.show() print("something else?")
[ "Tweets2Graph.Tweets2Graph", "time.sleep", "dotenv.load_dotenv", "datetime.datetime.now", "networkx.draw", "matplotlib.pyplot.show" ]
[((175, 188), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (186, 188), False, 'from dotenv import load_dotenv\n'), ((307, 392), 'Tweets2Graph.Tweets2Graph', 'Tweets2Graph', ([], {'interactions': "['retweet', 'quote', 'reply']", 'username': '"""screen_name"""'}), "(interactions=['retweet', 'quote', 'reply'], username='screen_name'\n )\n", (319, 392), False, 'from Tweets2Graph import Tweets2Graph\n'), ((480, 500), 'time.sleep', 'time.sleep', (['(10 ^ 100)'], {}), '(10 ^ 100)\n', (490, 500), False, 'import time\n'), ((831, 933), 'networkx.draw', 'nx.draw', (['graph'], {'with_labels': '(False)', 'node_size': '(5)', 'font_size': '(2)', 'font_color': '"""red"""', 'node_color': '"""black"""'}), "(graph, with_labels=False, node_size=5, font_size=2, font_color=\n 'red', node_color='black')\n", (838, 933), True, 'import networkx as nx\n'), ((928, 938), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (936, 938), True, 'import matplotlib.pyplot as plt\n'), ((1045, 1147), 'networkx.draw', 'nx.draw', (['graph'], {'with_labels': '(True)', 'node_size': '(5)', 'font_size': '(15)', 'font_color': '"""red"""', 'node_color': '"""black"""'}), "(graph, with_labels=True, node_size=5, font_size=15, font_color=\n 'red', node_color='black')\n", (1052, 1147), True, 'import networkx as nx\n'), ((1142, 1152), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1150, 1152), True, 'import matplotlib.pyplot as plt\n'), ((524, 538), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (536, 538), False, 'from datetime import datetime\n'), ((689, 703), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (701, 703), False, 'from datetime import datetime\n'), ((746, 760), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (758, 760), False, 'from datetime import datetime\n'), ((811, 825), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (823, 825), False, 'from datetime import datetime\n'), ((961, 975), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (973, 975), False, 'from datetime import datetime\n'), ((1025, 1039), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1037, 1039), False, 'from datetime import datetime\n')]
from django.db import models from django.forms import ModelForm from django.utils.translation import ugettext_lazy as _ from django.conf import settings from django.core.validators import FileExtensionValidator from .xmltools import analyze_file, include_sync_button import uuid def default_color(): return '#076AAB' class Project(models.Model): name = models.CharField(_("Name"), max_length=100) picture = models.FileField(_("Picture"), null=True, blank=True) description = models.CharField(_("Description"), max_length=200, null=True, blank=True) password = models.CharField( _("Password"), max_length=50, null=True, blank=True) pin = models.CharField(_("PIN"), max_length=6, unique=True) id = models.UUIDField(_("Id"), primary_key=True, default=uuid.uuid4, editable=False) email = models.EmailField(_("Email"), null=True, blank=True) @classmethod def create_and_save(cls, name, picture, description): proj = cls.objects.create( name=name, picture=picture, description=description, password=password) proj.save() return proj def __str__(self): return self.name class Meta: verbose_name = _("Project") verbose_name_plural = _("Projects") class File(models.Model): # Format: YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] timestamp = models.DateTimeField( _("Timestamp"), auto_now_add=True, auto_now=False) project = models.ForeignKey(Project, on_delete=models.CASCADE) # https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ManyToManyField.symmetrical ancestors = models.ManyToManyField("self", symmetrical=False) description = models.CharField(_("Description"), max_length=200, null=True, blank=True) number_scripts = models.IntegerField(_("number_scripts"), default=0) number_sprites = models.IntegerField(_("number_sprites"), default=0) color = models.CharField(_("color"), max_length=7, default=default_color()) class Meta: abstract = True class SnapFile(File): # validates only naming of file file = models.FileField(_("File"), blank=True, validators=[ FileExtensionValidator(['xml', 'XML'])]) # thumbnail = models.ImageField(_("Thumbnail"), null=True, blank=True) user = models.CharField(_("user"), max_length=30, null=True) @classmethod def create_and_save(cls, project, file, ancestors=None, user=None, description=''): snap = cls.objects.create( project=project, file=file, user=user, description=description) if (ancestors): snap.ancestors.set(ancestors) snap.save() return snap def xml_job(self): include_sync_button(self.get_media_path(), proj_id=self.project.id, me=self.id) stats = analyze_file(self.get_media_path()) self.number_scripts = stats[0] self.number_sprites = stats[1] self.save() def as_dict(self): ancestor_ids = [x.id for x in self.ancestors.all()] file_url = settings.MEDIA_URL + str(self.file) return { 'id': self.id, 'description': self.description, 'ancestors': ancestor_ids, 'file_url': file_url, 'timestamp': str(self.timestamp), 'number_scripts': self.number_scripts, 'number_sprites': self.number_sprites, 'color': self.color } def get_media_path(self): return settings.MEDIA_URL + str(self.file) class Meta: verbose_name = _("SnapFile") verbose_name_plural = _("SnapFiles") class ProjectForm(ModelForm): class Meta: model = Project fields = ['name', 'description', 'password', 'email'] labels = { 'description': _('Description (optional)'), 'password': _('Password (optional)'), 'email': _('email (optional), for restoring password and pin'), } class SnapFileForm(ModelForm): class Meta: model = SnapFile fields = ['file', 'description'] labels = { 'file': _('File (optional)'), 'description': _('Description (optional)'), }
[ "django.core.validators.FileExtensionValidator", "django.utils.translation.ugettext_lazy", "django.db.models.ManyToManyField", "django.db.models.ForeignKey" ]
[((1511, 1563), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Project'], {'on_delete': 'models.CASCADE'}), '(Project, on_delete=models.CASCADE)\n', (1528, 1563), False, 'from django.db import models\n'), ((1688, 1737), 'django.db.models.ManyToManyField', 'models.ManyToManyField', (['"""self"""'], {'symmetrical': '(False)'}), "('self', symmetrical=False)\n", (1710, 1737), False, 'from django.db import models\n'), ((382, 391), 'django.utils.translation.ugettext_lazy', '_', (['"""Name"""'], {}), "('Name')\n", (383, 391), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((440, 452), 'django.utils.translation.ugettext_lazy', '_', (['"""Picture"""'], {}), "('Picture')\n", (441, 452), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((512, 528), 'django.utils.translation.ugettext_lazy', '_', (['"""Description"""'], {}), "('Description')\n", (513, 528), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((645, 658), 'django.utils.translation.ugettext_lazy', '_', (['"""Password"""'], {}), "('Password')\n", (646, 658), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((725, 733), 'django.utils.translation.ugettext_lazy', '_', (['"""PIN"""'], {}), "('PIN')\n", (726, 733), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((788, 795), 'django.utils.translation.ugettext_lazy', '_', (['"""Id"""'], {}), "('Id')\n", (789, 795), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((907, 917), 'django.utils.translation.ugettext_lazy', '_', (['"""Email"""'], {}), "('Email')\n", (908, 917), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((1266, 1278), 'django.utils.translation.ugettext_lazy', '_', (['"""Project"""'], {}), "('Project')\n", (1267, 1278), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((1309, 1322), 'django.utils.translation.ugettext_lazy', '_', (['"""Projects"""'], {}), "('Projects')\n", (1310, 1322), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((1446, 1460), 'django.utils.translation.ugettext_lazy', '_', (['"""Timestamp"""'], {}), "('Timestamp')\n", (1447, 1460), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((1773, 1789), 'django.utils.translation.ugettext_lazy', '_', (['"""Description"""'], {}), "('Description')\n", (1774, 1789), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((1906, 1925), 'django.utils.translation.ugettext_lazy', '_', (['"""number_scripts"""'], {}), "('number_scripts')\n", (1907, 1925), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((1979, 1998), 'django.utils.translation.ugettext_lazy', '_', (['"""number_sprites"""'], {}), "('number_sprites')\n", (1980, 1998), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((2040, 2050), 'django.utils.translation.ugettext_lazy', '_', (['"""color"""'], {}), "('color')\n", (2041, 2050), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((2220, 2229), 'django.utils.translation.ugettext_lazy', '_', (['"""File"""'], {}), "('File')\n", (2221, 2229), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((2428, 2437), 'django.utils.translation.ugettext_lazy', '_', (['"""user"""'], {}), "('user')\n", (2429, 2437), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((3695, 3708), 'django.utils.translation.ugettext_lazy', '_', (['"""SnapFile"""'], {}), "('SnapFile')\n", (3696, 3708), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((3739, 3753), 'django.utils.translation.ugettext_lazy', '_', (['"""SnapFiles"""'], {}), "('SnapFiles')\n", (3740, 3753), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((3934, 3961), 'django.utils.translation.ugettext_lazy', '_', (['"""Description (optional)"""'], {}), "('Description (optional)')\n", (3935, 3961), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((3987, 4011), 'django.utils.translation.ugettext_lazy', '_', (['"""Password (optional)"""'], {}), "('Password (optional)')\n", (3988, 4011), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((4034, 4087), 'django.utils.translation.ugettext_lazy', '_', (['"""email (optional), for restoring password and pin"""'], {}), "('email (optional), for restoring password and pin')\n", (4035, 4087), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((4253, 4273), 'django.utils.translation.ugettext_lazy', '_', (['"""File (optional)"""'], {}), "('File (optional)')\n", (4254, 4273), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((4302, 4329), 'django.utils.translation.ugettext_lazy', '_', (['"""Description (optional)"""'], {}), "('Description (optional)')\n", (4303, 4329), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((2284, 2322), 'django.core.validators.FileExtensionValidator', 'FileExtensionValidator', (["['xml', 'XML']"], {}), "(['xml', 'XML'])\n", (2306, 2322), False, 'from django.core.validators import FileExtensionValidator\n')]
# -*- coding: utf-8 -*- from setuptools import setup # type: ignore setup( name='pylookyloo', version='1.11-dev', author='<NAME>', author_email='<EMAIL>', maintainer='<NAME>', url='https://github.com/Lookyloo/lookyloo/client', description='Python client for Lookyloo', packages=['pylookyloo'], entry_points={"console_scripts": ["lookyloo = pylookyloo:main"]}, install_requires=['requests'], classifiers=[ 'License :: OSI Approved :: BSD License', 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Operating System :: POSIX :: Linux', 'Intended Audience :: Science/Research', 'Intended Audience :: Telecommunications Industry', 'Intended Audience :: Information Technology', 'Programming Language :: Python :: 3', 'Topic :: Security', 'Topic :: Internet', ] )
[ "setuptools.setup" ]
[((71, 833), 'setuptools.setup', 'setup', ([], {'name': '"""pylookyloo"""', 'version': '"""1.11-dev"""', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'maintainer': '"""<NAME>"""', 'url': '"""https://github.com/Lookyloo/lookyloo/client"""', 'description': '"""Python client for Lookyloo"""', 'packages': "['pylookyloo']", 'entry_points': "{'console_scripts': ['lookyloo = pylookyloo:main']}", 'install_requires': "['requests']", 'classifiers': "['License :: OSI Approved :: BSD License',\n 'Development Status :: 5 - Production/Stable', 'Environment :: Console',\n 'Operating System :: POSIX :: Linux',\n 'Intended Audience :: Science/Research',\n 'Intended Audience :: Telecommunications Industry',\n 'Intended Audience :: Information Technology',\n 'Programming Language :: Python :: 3', 'Topic :: Security',\n 'Topic :: Internet']"}), "(name='pylookyloo', version='1.11-dev', author='<NAME>', author_email=\n '<EMAIL>', maintainer='<NAME>', url=\n 'https://github.com/Lookyloo/lookyloo/client', description=\n 'Python client for Lookyloo', packages=['pylookyloo'], entry_points={\n 'console_scripts': ['lookyloo = pylookyloo:main']}, install_requires=[\n 'requests'], classifiers=['License :: OSI Approved :: BSD License',\n 'Development Status :: 5 - Production/Stable', 'Environment :: Console',\n 'Operating System :: POSIX :: Linux',\n 'Intended Audience :: Science/Research',\n 'Intended Audience :: Telecommunications Industry',\n 'Intended Audience :: Information Technology',\n 'Programming Language :: Python :: 3', 'Topic :: Security',\n 'Topic :: Internet'])\n", (76, 833), False, 'from setuptools import setup\n')]
import logging import pymongo from bson import regex from watchmen.common.cache.cache_manage import cacheman, TOPIC_DICT_BY_NAME from watchmen.common.data_page import DataPage from watchmen.common.utils.data_utils import build_data_pages from watchmen.database.mongo.index import build_code_options from watchmen.database.storage.storage_interface import StorageInterface log = logging.getLogger("app." + __name__) log.info("mongo template initialized") # @singleton class MongoStorage(StorageInterface): client = None def __init__(self, client, table_provider): self.client = client self.table = table_provider def build_mongo_where_expression(self, where: dict): """ Build where, the common sql pattern is "column_name operator value", but we use dict, so the pattern is {column_name: {operator: value}}. if operator is =, then can use {column_name: value} About and|or , use {"and": List( {column_name1: {operator: value}} {column_name2: {operator: value}} ) } support Nested: {"or": List( {column_name1: {operator: value}} {column_name2: {operator: value}} {"and": List( {column_name3:{operator: value}} {column_name4:{operator: value}} ) } ) } """ for key, value in where.items(): if key == "and" or key == "or": if isinstance(value, list): filters = [] for express in value: result = self.build_mongo_where_expression(express) filters.append(result) if key == "and": return {"$and": filters} if key == "or": return {"$or": filters} else: if isinstance(value, dict): for k, v in value.items(): if k == "=": return {key: {"$eq": v}} if k == "!=": return {key: {"$ne": v}} if k == "like": return {key: regex.Regex(v)} if k == "in": return {key: {"$in": v}} if k == "not-in": return {key: {"$nin": v}} if k == ">": return {key: {"$gt": v}} if k == ">=": return {key: {"$gte": v}} if k == "<": return {key: {"$lt": v}} if k == "<=": return {key: {"$lte": v}} if k == "between": if (isinstance(v, tuple)) and len(v) == 2: return {key: {"$gte": v[0], "$lt": v[1]}} else: return {key: {"$eq": value}} def build_mongo_update_expression(self, updates): """ # used in pull_update, just allowed to update one field """ for key, value in updates.items(): if isinstance(value, dict): for k, v in value.items(): if k == "in": return {key: {"$in": v}} def build_mongo_updates_expression_for_insert(self, updates): new_updates = {} for key, value in updates.items(): if isinstance(value, dict): if "_sum" in value: new_updates[key] = value["_sum"] elif "_count" in value: new_updates[key] = value["_count"] elif "_avg" in value: new_updates[key] = value["_avg"] else: new_updates[key] = value else: new_updates[key] = value return new_updates def build_mongo_updates_expression_for_update(self, updates): new_updates = {} new_updates["$set"] = {} for key, value in updates.items(): if isinstance(value, dict): if "_sum" in value: new_updates['$inc'] = {key: value["_sum"]} elif "_count" in value: new_updates['$inc'][key] = value["_count"] elif "_avg" in value: pass else: new_updates["$set"][key] = value else: if key == "version_": new_updates["$set"][key] = updates.get(key) + 1 else: new_updates["$set"][key] = value return new_updates def build_mongo_order(self, order_: list): result = [] for item in order_: if isinstance(item, tuple): if item[1] == "desc": new_ = (item[0], pymongo.DESCENDING) result.append(new_) if item[1] == "asc": new_ = (item[0], pymongo.ASCENDING) result.append(new_) return result def insert_one(self, one, model, name): collection = self.client.get_collection(name) collection.insert_one(self.__convert_to_dict(one)) return model.parse_obj(one) def insert_all(self, data, model, name): collection = self.client.get_collection(name) collection.insert_many(self.__convert_list_to_dict(data)) return data def update_one(self, one, model, name) -> any: collection = self.client.get_collection(name) primary_key = self.table.get_primary_key(name) one_dict = self.__convert_to_dict(one) query_dict = {primary_key: one_dict.get(primary_key)} collection.update_one(query_dict, {"$set": one_dict}) return model.parse_obj(one) def update_one_first(self, where, updates, model, name): collection = self.client.get_collection(name) query_dict = self.build_mongo_where_expression(where) collection.update_one(query_dict, {"$set": self.__convert_to_dict(updates)}) return model.parse_obj(updates) def update_one_with_condition(self, where, one, model, name): collections = self.client.get_collection(name) collections.update_one(self.build_mongo_where_expression(where), {"$set": self.__convert_to_dict(one)}) def update_(self, where, updates, model, name): collections = self.client.get_collection(name) collections.update_many(self.build_mongo_where_expression(where), {"$set": self.__convert_to_dict(updates)}) def pull_update(self, where, updates, model, name): collections = self.client.get_collection(name) collections.update_many(self.build_mongo_where_expression(where), {"$pull": self.build_mongo_update_expression(self.__convert_to_dict(updates))}) def delete_by_id(self, id_, name): collection = self.client.get_collection(name) key = self.table.get_primary_key(name) collection.delete_one({key: id_}) def delete_one(self, where, name): collection = self.client.get_collection(name) collection.delete_one(self.build_mongo_where_expression(where)) def delete_(self, where, model, name): collection = self.client.get_collection(name) collection.delete_many(self.build_mongo_where_expression(where)) def find_by_id(self, id_, model, name): collections = self.client.get_collection(name) primary_key = self.table.get_primary_key(name) result = collections.find_one({primary_key: id_}) if result is None: return else: return model.parse_obj(result) def find_one(self, where: dict, model, name: str): collection = self.client.get_collection(name) result = collection.find_one(self.build_mongo_where_expression(where)) if result is None: return else: return model.parse_obj(result) def drop_(self, name: str): return self.client.get_collection(name).drop() def find_(self, where: dict, model, name: str) -> list: collection = self.client.get_collection(name) cursor = collection.find(self.build_mongo_where_expression(where)) result_list = list(cursor) return [model.parse_obj(result) for result in result_list] def list_all(self, model, name: str): collection = self.client.get_collection(name) cursor = collection.find() result_list = list(cursor) return [model.parse_obj(result) for result in result_list] def list_(self, where, model, name: str) -> list: collection = self.client.get_collection(name) cursor = collection.find(self.build_mongo_where_expression(where)) result_list = list(cursor) return [model.parse_obj(result) for result in result_list] def page_all(self, sort, pageable, model, name) -> DataPage: codec_options = build_code_options() collection = self.client.get_collection(name, codec_options=codec_options) total = collection.find().count() skips = pageable.pageSize * (pageable.pageNumber - 1) cursor = collection.find().skip(skips).limit(pageable.pageSize).sort(self.build_mongo_order(sort)) return build_data_pages(pageable, [model.parse_obj(result) for result in list(cursor)], total) def page_(self, where, sort, pageable, model, name) -> DataPage: codec_options = build_code_options() collection = self.client.get_collection(name, codec_options=codec_options) mongo_where = self.build_mongo_where_expression(where) total = collection.find(mongo_where).count() skips = pageable.pageSize * (pageable.pageNumber - 1) if sort is not None: cursor = collection.find(mongo_where).skip(skips).limit(pageable.pageSize).sort( self.build_mongo_order(sort)) else: cursor = collection.find(mongo_where).skip(skips).limit(pageable.pageSize) if model is not None: return build_data_pages(pageable, [model.parse_obj(result) for result in list(cursor)], total) else: results = [] for doc in cursor: del doc['_id'] results.append(doc) return build_data_pages(pageable, results, total) def __convert_list_to_dict(self, items: list): result = [] for item in items: result.append(self.__convert_to_dict(item)) return result def __convert_to_dict(self, instance) -> dict: if type(instance) is not dict: return instance.dict(by_alias=True) else: return instance def get_topic_factors(self, topic_name): topic = self._get_topic(topic_name) factors = topic['factors'] return factors def check_topic_type(self, topic_name): topic = self._get_topic(topic_name) return topic['type'] def _get_topic(self, topic_name) -> any: if cacheman[TOPIC_DICT_BY_NAME].get(topic_name) is not None: return cacheman[TOPIC_DICT_BY_NAME].get(topic_name) codec_options = build_code_options() topic_collection = self.client.get_collection("topics", codec_options=codec_options) result = topic_collection.find_one({"name": topic_name}) if result is None: raise Exception("not find topic {0}".format(topic_name)) else: cacheman[TOPIC_DICT_BY_NAME].set(topic_name, result) return result def clear_metadata(self): pass
[ "logging.getLogger", "watchmen.common.utils.data_utils.build_data_pages", "bson.regex.Regex", "watchmen.database.mongo.index.build_code_options" ]
[((392, 428), 'logging.getLogger', 'logging.getLogger', (["('app.' + __name__)"], {}), "('app.' + __name__)\n", (409, 428), False, 'import logging\n'), ((9722, 9742), 'watchmen.database.mongo.index.build_code_options', 'build_code_options', ([], {}), '()\n', (9740, 9742), False, 'from watchmen.database.mongo.index import build_code_options\n'), ((10242, 10262), 'watchmen.database.mongo.index.build_code_options', 'build_code_options', ([], {}), '()\n', (10260, 10262), False, 'from watchmen.database.mongo.index import build_code_options\n'), ((12001, 12021), 'watchmen.database.mongo.index.build_code_options', 'build_code_options', ([], {}), '()\n', (12019, 12021), False, 'from watchmen.database.mongo.index import build_code_options\n'), ((11105, 11147), 'watchmen.common.utils.data_utils.build_data_pages', 'build_data_pages', (['pageable', 'results', 'total'], {}), '(pageable, results, total)\n', (11121, 11147), False, 'from watchmen.common.utils.data_utils import build_data_pages\n'), ((2649, 2663), 'bson.regex.Regex', 'regex.Regex', (['v'], {}), '(v)\n', (2660, 2663), False, 'from bson import regex\n')]
from collections import defaultdict import json import datetime import uuid from unidecode import unidecode import re import rdflib from rdflib import Dataset, URIRef, Literal, XSD, Namespace, RDFS, BNode, SKOS, OWL from rdfalchemy import rdfSubject, rdfMultiple, rdfSingle from shapely.geometry import Point, MultiPoint from shapely import wkt create = Namespace("https://data.create.humanities.uva.nl/") schema = Namespace("http://schema.org/") sem = Namespace("http://semanticweb.cs.vu.nl/2009/11/sem/") bio = Namespace("http://purl.org/vocab/bio/0.1/") foaf = Namespace("http://xmlns.com/foaf/0.1/") void = Namespace("http://rdfs.org/ns/void#") dcterms = Namespace("http://purl.org/dc/terms/") rdflib.graph.DATASET_DEFAULT_GRAPH_ID = create rdflib.NORMALIZE_LITERALS = False juso = Namespace("http://rdfs.co/juso/") qb = Namespace("http://purl.org/linked-data/cube#") hg = Namespace("http://rdf.histograph.io/") geo = Namespace("http://www.opengis.net/ont/geosparql#") lp = Namespace("https://resolver.clariah.org/hisgis/lp/") lpOnt = Namespace("https://resolver.clariah.org/hisgis/lp/ontology/") lpGeo = Namespace("https://resolver.clariah.org/hisgis/lp/geometry/") lpPlace = Namespace("https://resolver.clariah.org/hisgis/lp/place/") lpAdres = Namespace("https://resolver.clariah.org/hisgis/lp/adres/") lpStraat = Namespace("https://resolver.clariah.org/hisgis/lp/straat/") lpBuurt = Namespace("https://resolver.clariah.org/hisgis/lp/buurt/") lpPerceel = Namespace("https://resolver.clariah.org/hisgis/lp/perceel/") lpSectie = Namespace("https://resolver.clariah.org/hisgis/lp/sectie/") label2adres = dict() class Entity(rdfSubject): rdf_type = URIRef('urn:entity') label = rdfMultiple(RDFS.label) name = rdfMultiple(schema.name) url = rdfSingle(schema.url) hasGeometry = rdfSingle(geo.hasGeometry) startDate = rdfSingle(schema.startDate) hasTimeStamp = rdfSingle(sem.hasTimeStamp) hasBeginTimeStamp = rdfSingle(sem.hasBeginTimeStamp) hasEndTimeStamp = rdfSingle(sem.hasEndTimeStamp) hasEarliestBeginTimeStamp = rdfSingle(sem.hasEarliestBeginTimeStamp) hasLatestBeginTimeStamp = rdfSingle(sem.hasLatestBeginTimeStamp) hasEarliestEndTimeStamp = rdfSingle(sem.hasEarliestEndTimeStamp) hasLatestEndTimeStamp = rdfSingle(sem.hasLatestEndTimeStamp) class Geometry(Entity): rdf_type = geo.Geometry asWKT = rdfSingle(geo.asWKT) class Huis(Entity): rdf_type = lpOnt.Huis adres = rdfMultiple(lpOnt.adres) class Adres(Entity): rdf_type = lpOnt.Adres label = rdfSingle(RDFS.label) # Literal prefLabel = rdfSingle(SKOS.prefLabel) # Literal straat = rdfSingle(lpOnt.straat) # URI huisnummer = rdfSingle(lpOnt.huisnummer) # Literal huisnummertoevoeging = rdfSingle(lpOnt.huisnummertoevoeging) # Literal buurt = rdfSingle(lpOnt.buurt) # URI buurtnummer = rdfSingle(lpOnt.buurtnummer) # Literal buurtnummertoevoeging = rdfSingle(lpOnt.buurtnummertoevoeging) # Literal perceel = rdfSingle(lpOnt.perceel) # URI class Straat(Entity): rdf_type = lpOnt.Straat label = rdfSingle(RDFS.label) # Literal class Buurt(Entity): rdf_type = lpOnt.Buurt label = rdfSingle(RDFS.label) # Literal class Sectie(Entity): rdf_type = lpOnt.Sectie label = rdfSingle(RDFS.label) # Literal class Perceel(Entity): rdf_type = lpOnt.Perceel label = rdfSingle(RDFS.label) # Literal sectie = rdfSingle(lpOnt.sectie) # URI perceelnummer = rdfSingle(lpOnt.perceelnummer) # Literal perceelnummertoevoeging = rdfSingle( lpOnt.perceelnummertoevoeging) # Literal def unique(*args): identifier = "".join(str(i) for i in args) # order matters unique_id = uuid.uuid5(uuid.NAMESPACE_X500, identifier) return BNode(unique_id) def getResource(*args, ns): identifier = "-".join(str(i) for i in args if i) # order matters identifier = identifier.replace(' ', '-') identifier = identifier.replace('.', '') identifier = identifier.lower() identifier = unidecode(identifier) return ns.term(identifier) def getAdresResource(name: str, years: tuple, lps): uniqueLabel = unidecode(name) name = name.replace('BUURT ', '').replace('SECTIE ', '') uniqueLabel = uniqueLabel.replace(' ', '-') uniqueLabel = uniqueLabel.replace('.', '') uniqueLabel = uniqueLabel.lower() uriLabel = re.sub(r'^(?:buurt-)|(?:sectie-)', '', uniqueLabel) adres = label2adres.get((uniqueLabel, years, lps)) if adres is None: uri = lpAdres.term(f"{uriLabel}-{'-'.join(years)}") earliestBegin = Literal(f"{min(years)}-01-01", datatype=XSD.date) latestBegin = Literal(f"{min(years)}-12-31", datatype=XSD.date) earliestEnd = Literal(f"{max(years)}-01-01", datatype=XSD.date) latestEnd = Literal(f"{max(years)}-12-31", datatype=XSD.date) minYear, maxYear = min(years), max(years) if minYear == maxYear: label = f"{name} ({minYear})" else: label = f"{name} ({minYear}-{maxYear})" # Get rid of the buurt in the prefLabel for 1876 if "1876" in years: prefLabel = re.sub(r'^[A-Z]{1,2} ', '', name) else: prefLabel = name # Remove space in huisnummertoevoeging # E.g. Bilderdijkstraat 9 a --> Bilderdijkstraat 9a prefLabel = re.sub(r'(\d) ([a-z])$', r'\1\2', prefLabel) adres = Adres( uri, # hasEarliestBeginTimeStamp=earliestBegin, hasLatestBeginTimeStamp=latestBegin, hasEarliestEndTimeStamp=earliestEnd, # hasLatestEndTimeStamp=latestEnd, label=label, prefLabel=prefLabel) label2adres[(uniqueLabel, years, lps)] = adres return adres def getAdres(adresData, label, point2wkt): # years = [int(i) for i in adresData.keys()] # earliestBegin = Literal(f"{min(years)}-01-01", datatype=XSD.date) # latestBegin = Literal(f"{min(years)}-12-31", datatype=XSD.date) # earliestEnd = Literal(f"{max(years)}-01-01", datatype=XSD.date) # latestEnd = Literal(f"{max(years)}-12-31", datatype=XSD.date) # adres = Adres(getAdresUri(label), # hasEarliestBeginTimeStamp=earliestBegin, # hasLatestBeginTimeStamp=latestBegin, # hasEarliestEndTimeStamp=earliestEnd, # hasLatestEndTimeStamp=latestEnd) years = tuple(sorted(adresData.keys())) addresses = [] for year, data in adresData.items(): points = [] for lp in data['geometry']: lp = str(lp) point = Point(wkt.loads(point2wkt[lp])) points.append((lp, point)) lps, geoms = zip(*points) if len(lps) > 1: p = MultiPoint(points=geoms).to_wkt() else: p = geoms[0].to_wkt() wktLiteral = Literal(p, datatype=geo.wktLiteral) adres = getAdresResource(label, years, lps) for lp in lps: huis = Huis(lpPlace.term(lp)) huis.adres = [adres] geometry = Geometry(lpGeo.term("-".join(lps)), asWKT=wktLiteral, label=lps) adres.hasGeometry = geometry if year in ['1943', '1909', '1876']: if straatnaam := data['straat']['naam']: straatUri = URIRef( data['straat']['adamlink'] ) if data['straat']['adamlink'] else getResource(straatnaam, ns=lpStraat) adres.straat = Straat(straatUri, label=straatnaam) if huisnummer := data['huisnummer']: adres.huisnummer = huisnummer if huisnummertoevoeging := data['huisnummertoevoeging']: adres.huisnummertoevoeging = huisnummertoevoeging if year in ['1876', '1853']: if buurtnaam := data['buurt']['naam']: buurtUri = URIRef( data['buurt']['adamlink'] ) if data['buurt']['adamlink'] else getResource(buurtnaam, ns=lpBuurt) adres.buurt = Buurt(buurtUri, label=buurtnaam) if year == '1853': if buurtnummer := data['buurtnummer']: adres.buurtnummer = buurtnummer if buurtnummertoevoeging := data['buurtnummertoevoeging']: adres.buurtnummertoevoeging = buurtnummertoevoeging if year in ['1832']: perceelsectie = data['perceelsectie'] sectie = Sectie(getResource(perceelsectie, ns=lpSectie), label=perceelsectie) perceelnummer = data['perceelnummer'] perceelnummertoevoeging = data['perceelnummertoevoeging'] perceelLabel = "".join([ str(i) for i in [perceelsectie, perceelnummer, perceelnummertoevoeging] if i ]) perceel = Perceel(getResource(perceelsectie, perceelnummer, perceelnummertoevoeging, ns=lpPerceel), perceelnummer=perceelnummer, perceelnummertoevoeging=perceelnummertoevoeging, sectie=sectie, label=perceelLabel) adres.perceel = perceel addresses.append(adres) return addresses def main(source, target, geometryfile='data/point2wkt.json'): with open(source) as infile: data = json.load(infile) with open(geometryfile) as infile: point2wkt = json.load(infile) ds = Dataset() dataset = lp.term('') g = rdfSubject.db = ds.graph(identifier=lp) ### Custom triples / Ontology g.add((lpOnt.Adres, OWL.equivalentClass, schema.PostalAddress)) g.add((lpOnt.Straat, OWL.equivalentClass, hg.Street)) g.add((lpOnt.Buurt, OWL.equivalentClass, hg.Neighbourhood)) g.add((lpOnt.adres, OWL.equivalentProperty, schema.address)) ######## # Data # ######## adres2locatie = defaultdict(lambda: defaultdict(list)) for n, adresLabel in enumerate(data, 1): if n % 5000 == 0: print(f"{n}/{len(data)}", end='\r') # break # # geometry # wkt = point2wkt.get(locatiepunt) # wktLiteral = Literal(wkt, datatype=geo.wktLiteral) # geometry = Geometry(lpGeo.term(str(locatiepunt)), # asWKT=wktLiteral, # label=[str(locatiepunt)]) addresses = getAdres(data[adresLabel], adresLabel, point2wkt) # adres2locatie[adres][year].append(geometry) # observations.append(locpdetail) # locp.observation = observations # addresses.append( # Role( # None, # label=address.label, # address=address, # hasLatestBeginTimeStamp=locpdetail.hasLatestBeginTimeStamp, # hasEarliestEndTimeStamp=locpdetail.hasEarliestEndTimeStamp, # startDate=Literal(year, datatype=XSD.gYear))) ds.bind('create', create) ds.bind('schema', schema) ds.bind('sem', sem) ds.bind('geo', geo) ds.bind('juso', juso) ds.bind('qb', qb) ds.bind('void', void) print("Serializing!") ds.serialize(target, format='trig') if __name__ == "__main__": main(source='concordans.json', target='locatiepunten2021.trig')
[ "rdfalchemy.rdfSingle", "uuid.uuid5", "rdfalchemy.rdfMultiple", "shapely.wkt.loads", "rdflib.Literal", "json.load", "rdflib.BNode", "collections.defaultdict", "unidecode.unidecode", "rdflib.Namespace", "re.sub", "rdflib.Dataset", "rdflib.URIRef", "shapely.geometry.MultiPoint" ]
[((357, 408), 'rdflib.Namespace', 'Namespace', (['"""https://data.create.humanities.uva.nl/"""'], {}), "('https://data.create.humanities.uva.nl/')\n", (366, 408), False, 'from rdflib import Dataset, URIRef, Literal, XSD, Namespace, RDFS, BNode, SKOS, OWL\n'), ((418, 449), 'rdflib.Namespace', 'Namespace', (['"""http://schema.org/"""'], {}), "('http://schema.org/')\n", (427, 449), False, 'from rdflib import Dataset, URIRef, Literal, XSD, Namespace, RDFS, BNode, SKOS, OWL\n'), ((456, 509), 'rdflib.Namespace', 'Namespace', (['"""http://semanticweb.cs.vu.nl/2009/11/sem/"""'], {}), "('http://semanticweb.cs.vu.nl/2009/11/sem/')\n", (465, 509), False, 'from rdflib import Dataset, URIRef, Literal, XSD, Namespace, RDFS, BNode, SKOS, OWL\n'), ((516, 559), 'rdflib.Namespace', 'Namespace', (['"""http://purl.org/vocab/bio/0.1/"""'], {}), "('http://purl.org/vocab/bio/0.1/')\n", (525, 559), False, 'from rdflib import Dataset, URIRef, Literal, XSD, Namespace, RDFS, BNode, SKOS, OWL\n'), ((567, 606), 'rdflib.Namespace', 'Namespace', (['"""http://xmlns.com/foaf/0.1/"""'], {}), "('http://xmlns.com/foaf/0.1/')\n", (576, 606), False, 'from rdflib import Dataset, URIRef, Literal, XSD, Namespace, RDFS, BNode, SKOS, OWL\n'), ((614, 651), 'rdflib.Namespace', 'Namespace', (['"""http://rdfs.org/ns/void#"""'], {}), "('http://rdfs.org/ns/void#')\n", (623, 651), False, 'from rdflib import Dataset, URIRef, Literal, XSD, Namespace, RDFS, BNode, SKOS, OWL\n'), ((662, 700), 'rdflib.Namespace', 'Namespace', (['"""http://purl.org/dc/terms/"""'], {}), "('http://purl.org/dc/terms/')\n", (671, 700), False, 'from rdflib import Dataset, URIRef, Literal, XSD, Namespace, RDFS, BNode, SKOS, OWL\n'), ((791, 824), 'rdflib.Namespace', 'Namespace', (['"""http://rdfs.co/juso/"""'], {}), "('http://rdfs.co/juso/')\n", (800, 824), False, 'from rdflib import Dataset, URIRef, Literal, XSD, Namespace, RDFS, BNode, SKOS, OWL\n'), ((830, 876), 'rdflib.Namespace', 'Namespace', (['"""http://purl.org/linked-data/cube#"""'], {}), "('http://purl.org/linked-data/cube#')\n", (839, 876), False, 'from rdflib import Dataset, URIRef, Literal, XSD, Namespace, RDFS, BNode, SKOS, OWL\n'), ((882, 920), 'rdflib.Namespace', 'Namespace', (['"""http://rdf.histograph.io/"""'], {}), "('http://rdf.histograph.io/')\n", (891, 920), False, 'from rdflib import Dataset, URIRef, Literal, XSD, Namespace, RDFS, BNode, SKOS, OWL\n'), ((927, 977), 'rdflib.Namespace', 'Namespace', (['"""http://www.opengis.net/ont/geosparql#"""'], {}), "('http://www.opengis.net/ont/geosparql#')\n", (936, 977), False, 'from rdflib import Dataset, URIRef, Literal, XSD, Namespace, RDFS, BNode, SKOS, OWL\n'), ((984, 1036), 'rdflib.Namespace', 'Namespace', (['"""https://resolver.clariah.org/hisgis/lp/"""'], {}), "('https://resolver.clariah.org/hisgis/lp/')\n", (993, 1036), False, 'from rdflib import Dataset, URIRef, Literal, XSD, Namespace, RDFS, BNode, SKOS, OWL\n'), ((1045, 1106), 'rdflib.Namespace', 'Namespace', (['"""https://resolver.clariah.org/hisgis/lp/ontology/"""'], {}), "('https://resolver.clariah.org/hisgis/lp/ontology/')\n", (1054, 1106), False, 'from rdflib import Dataset, URIRef, Literal, XSD, Namespace, RDFS, BNode, SKOS, OWL\n'), ((1115, 1176), 'rdflib.Namespace', 'Namespace', (['"""https://resolver.clariah.org/hisgis/lp/geometry/"""'], {}), "('https://resolver.clariah.org/hisgis/lp/geometry/')\n", (1124, 1176), False, 'from rdflib import Dataset, URIRef, Literal, XSD, Namespace, RDFS, BNode, SKOS, OWL\n'), ((1187, 1245), 'rdflib.Namespace', 'Namespace', (['"""https://resolver.clariah.org/hisgis/lp/place/"""'], {}), "('https://resolver.clariah.org/hisgis/lp/place/')\n", (1196, 1245), False, 'from rdflib import Dataset, URIRef, Literal, XSD, Namespace, RDFS, BNode, SKOS, OWL\n'), ((1257, 1315), 'rdflib.Namespace', 'Namespace', (['"""https://resolver.clariah.org/hisgis/lp/adres/"""'], {}), "('https://resolver.clariah.org/hisgis/lp/adres/')\n", (1266, 1315), False, 'from rdflib import Dataset, URIRef, Literal, XSD, Namespace, RDFS, BNode, SKOS, OWL\n'), ((1327, 1386), 'rdflib.Namespace', 'Namespace', (['"""https://resolver.clariah.org/hisgis/lp/straat/"""'], {}), "('https://resolver.clariah.org/hisgis/lp/straat/')\n", (1336, 1386), False, 'from rdflib import Dataset, URIRef, Literal, XSD, Namespace, RDFS, BNode, SKOS, OWL\n'), ((1397, 1455), 'rdflib.Namespace', 'Namespace', (['"""https://resolver.clariah.org/hisgis/lp/buurt/"""'], {}), "('https://resolver.clariah.org/hisgis/lp/buurt/')\n", (1406, 1455), False, 'from rdflib import Dataset, URIRef, Literal, XSD, Namespace, RDFS, BNode, SKOS, OWL\n'), ((1468, 1528), 'rdflib.Namespace', 'Namespace', (['"""https://resolver.clariah.org/hisgis/lp/perceel/"""'], {}), "('https://resolver.clariah.org/hisgis/lp/perceel/')\n", (1477, 1528), False, 'from rdflib import Dataset, URIRef, Literal, XSD, Namespace, RDFS, BNode, SKOS, OWL\n'), ((1540, 1599), 'rdflib.Namespace', 'Namespace', (['"""https://resolver.clariah.org/hisgis/lp/sectie/"""'], {}), "('https://resolver.clariah.org/hisgis/lp/sectie/')\n", (1549, 1599), False, 'from rdflib import Dataset, URIRef, Literal, XSD, Namespace, RDFS, BNode, SKOS, OWL\n'), ((1665, 1685), 'rdflib.URIRef', 'URIRef', (['"""urn:entity"""'], {}), "('urn:entity')\n", (1671, 1685), False, 'from rdflib import Dataset, URIRef, Literal, XSD, Namespace, RDFS, BNode, SKOS, OWL\n'), ((1699, 1722), 'rdfalchemy.rdfMultiple', 'rdfMultiple', (['RDFS.label'], {}), '(RDFS.label)\n', (1710, 1722), False, 'from rdfalchemy import rdfSubject, rdfMultiple, rdfSingle\n'), ((1734, 1758), 'rdfalchemy.rdfMultiple', 'rdfMultiple', (['schema.name'], {}), '(schema.name)\n', (1745, 1758), False, 'from rdfalchemy import rdfSubject, rdfMultiple, rdfSingle\n'), ((1769, 1790), 'rdfalchemy.rdfSingle', 'rdfSingle', (['schema.url'], {}), '(schema.url)\n', (1778, 1790), False, 'from rdfalchemy import rdfSubject, rdfMultiple, rdfSingle\n'), ((1810, 1836), 'rdfalchemy.rdfSingle', 'rdfSingle', (['geo.hasGeometry'], {}), '(geo.hasGeometry)\n', (1819, 1836), False, 'from rdfalchemy import rdfSubject, rdfMultiple, rdfSingle\n'), ((1854, 1881), 'rdfalchemy.rdfSingle', 'rdfSingle', (['schema.startDate'], {}), '(schema.startDate)\n', (1863, 1881), False, 'from rdfalchemy import rdfSubject, rdfMultiple, rdfSingle\n'), ((1901, 1928), 'rdfalchemy.rdfSingle', 'rdfSingle', (['sem.hasTimeStamp'], {}), '(sem.hasTimeStamp)\n', (1910, 1928), False, 'from rdfalchemy import rdfSubject, rdfMultiple, rdfSingle\n'), ((1953, 1985), 'rdfalchemy.rdfSingle', 'rdfSingle', (['sem.hasBeginTimeStamp'], {}), '(sem.hasBeginTimeStamp)\n', (1962, 1985), False, 'from rdfalchemy import rdfSubject, rdfMultiple, rdfSingle\n'), ((2008, 2038), 'rdfalchemy.rdfSingle', 'rdfSingle', (['sem.hasEndTimeStamp'], {}), '(sem.hasEndTimeStamp)\n', (2017, 2038), False, 'from rdfalchemy import rdfSubject, rdfMultiple, rdfSingle\n'), ((2071, 2111), 'rdfalchemy.rdfSingle', 'rdfSingle', (['sem.hasEarliestBeginTimeStamp'], {}), '(sem.hasEarliestBeginTimeStamp)\n', (2080, 2111), False, 'from rdfalchemy import rdfSubject, rdfMultiple, rdfSingle\n'), ((2142, 2180), 'rdfalchemy.rdfSingle', 'rdfSingle', (['sem.hasLatestBeginTimeStamp'], {}), '(sem.hasLatestBeginTimeStamp)\n', (2151, 2180), False, 'from rdfalchemy import rdfSubject, rdfMultiple, rdfSingle\n'), ((2211, 2249), 'rdfalchemy.rdfSingle', 'rdfSingle', (['sem.hasEarliestEndTimeStamp'], {}), '(sem.hasEarliestEndTimeStamp)\n', (2220, 2249), False, 'from rdfalchemy import rdfSubject, rdfMultiple, rdfSingle\n'), ((2278, 2314), 'rdfalchemy.rdfSingle', 'rdfSingle', (['sem.hasLatestEndTimeStamp'], {}), '(sem.hasLatestEndTimeStamp)\n', (2287, 2314), False, 'from rdfalchemy import rdfSubject, rdfMultiple, rdfSingle\n'), ((2382, 2402), 'rdfalchemy.rdfSingle', 'rdfSingle', (['geo.asWKT'], {}), '(geo.asWKT)\n', (2391, 2402), False, 'from rdfalchemy import rdfSubject, rdfMultiple, rdfSingle\n'), ((2464, 2488), 'rdfalchemy.rdfMultiple', 'rdfMultiple', (['lpOnt.adres'], {}), '(lpOnt.adres)\n', (2475, 2488), False, 'from rdfalchemy import rdfSubject, rdfMultiple, rdfSingle\n'), ((2552, 2573), 'rdfalchemy.rdfSingle', 'rdfSingle', (['RDFS.label'], {}), '(RDFS.label)\n', (2561, 2573), False, 'from rdfalchemy import rdfSubject, rdfMultiple, rdfSingle\n'), ((2601, 2626), 'rdfalchemy.rdfSingle', 'rdfSingle', (['SKOS.prefLabel'], {}), '(SKOS.prefLabel)\n', (2610, 2626), False, 'from rdfalchemy import rdfSubject, rdfMultiple, rdfSingle\n'), ((2652, 2675), 'rdfalchemy.rdfSingle', 'rdfSingle', (['lpOnt.straat'], {}), '(lpOnt.straat)\n', (2661, 2675), False, 'from rdfalchemy import rdfSubject, rdfMultiple, rdfSingle\n'), ((2700, 2727), 'rdfalchemy.rdfSingle', 'rdfSingle', (['lpOnt.huisnummer'], {}), '(lpOnt.huisnummer)\n', (2709, 2727), False, 'from rdfalchemy import rdfSubject, rdfMultiple, rdfSingle\n'), ((2766, 2803), 'rdfalchemy.rdfSingle', 'rdfSingle', (['lpOnt.huisnummertoevoeging'], {}), '(lpOnt.huisnummertoevoeging)\n', (2775, 2803), False, 'from rdfalchemy import rdfSubject, rdfMultiple, rdfSingle\n'), ((2828, 2850), 'rdfalchemy.rdfSingle', 'rdfSingle', (['lpOnt.buurt'], {}), '(lpOnt.buurt)\n', (2837, 2850), False, 'from rdfalchemy import rdfSubject, rdfMultiple, rdfSingle\n'), ((2876, 2904), 'rdfalchemy.rdfSingle', 'rdfSingle', (['lpOnt.buurtnummer'], {}), '(lpOnt.buurtnummer)\n', (2885, 2904), False, 'from rdfalchemy import rdfSubject, rdfMultiple, rdfSingle\n'), ((2944, 2982), 'rdfalchemy.rdfSingle', 'rdfSingle', (['lpOnt.buurtnummertoevoeging'], {}), '(lpOnt.buurtnummertoevoeging)\n', (2953, 2982), False, 'from rdfalchemy import rdfSubject, rdfMultiple, rdfSingle\n'), ((3009, 3033), 'rdfalchemy.rdfSingle', 'rdfSingle', (['lpOnt.perceel'], {}), '(lpOnt.perceel)\n', (3018, 3033), False, 'from rdfalchemy import rdfSubject, rdfMultiple, rdfSingle\n'), ((3106, 3127), 'rdfalchemy.rdfSingle', 'rdfSingle', (['RDFS.label'], {}), '(RDFS.label)\n', (3115, 3127), False, 'from rdfalchemy import rdfSubject, rdfMultiple, rdfSingle\n'), ((3202, 3223), 'rdfalchemy.rdfSingle', 'rdfSingle', (['RDFS.label'], {}), '(RDFS.label)\n', (3211, 3223), False, 'from rdfalchemy import rdfSubject, rdfMultiple, rdfSingle\n'), ((3300, 3321), 'rdfalchemy.rdfSingle', 'rdfSingle', (['RDFS.label'], {}), '(RDFS.label)\n', (3309, 3321), False, 'from rdfalchemy import rdfSubject, rdfMultiple, rdfSingle\n'), ((3400, 3421), 'rdfalchemy.rdfSingle', 'rdfSingle', (['RDFS.label'], {}), '(RDFS.label)\n', (3409, 3421), False, 'from rdfalchemy import rdfSubject, rdfMultiple, rdfSingle\n'), ((3447, 3470), 'rdfalchemy.rdfSingle', 'rdfSingle', (['lpOnt.sectie'], {}), '(lpOnt.sectie)\n', (3456, 3470), False, 'from rdfalchemy import rdfSubject, rdfMultiple, rdfSingle\n'), ((3498, 3528), 'rdfalchemy.rdfSingle', 'rdfSingle', (['lpOnt.perceelnummer'], {}), '(lpOnt.perceelnummer)\n', (3507, 3528), False, 'from rdfalchemy import rdfSubject, rdfMultiple, rdfSingle\n'), ((3570, 3610), 'rdfalchemy.rdfSingle', 'rdfSingle', (['lpOnt.perceelnummertoevoeging'], {}), '(lpOnt.perceelnummertoevoeging)\n', (3579, 3610), False, 'from rdfalchemy import rdfSubject, rdfMultiple, rdfSingle\n'), ((3733, 3776), 'uuid.uuid5', 'uuid.uuid5', (['uuid.NAMESPACE_X500', 'identifier'], {}), '(uuid.NAMESPACE_X500, identifier)\n', (3743, 3776), False, 'import uuid\n'), ((3789, 3805), 'rdflib.BNode', 'BNode', (['unique_id'], {}), '(unique_id)\n', (3794, 3805), False, 'from rdflib import Dataset, URIRef, Literal, XSD, Namespace, RDFS, BNode, SKOS, OWL\n'), ((4050, 4071), 'unidecode.unidecode', 'unidecode', (['identifier'], {}), '(identifier)\n', (4059, 4071), False, 'from unidecode import unidecode\n'), ((4176, 4191), 'unidecode.unidecode', 'unidecode', (['name'], {}), '(name)\n', (4185, 4191), False, 'from unidecode import unidecode\n'), ((4404, 4454), 're.sub', 're.sub', (['"""^(?:buurt-)|(?:sectie-)"""', '""""""', 'uniqueLabel'], {}), "('^(?:buurt-)|(?:sectie-)', '', uniqueLabel)\n", (4410, 4454), False, 'import re\n'), ((9854, 9863), 'rdflib.Dataset', 'Dataset', ([], {}), '()\n', (9861, 9863), False, 'from rdflib import Dataset, URIRef, Literal, XSD, Namespace, RDFS, BNode, SKOS, OWL\n'), ((5390, 5435), 're.sub', 're.sub', (['"""(\\\\d) ([a-z])$"""', '"""\\\\1\\\\2"""', 'prefLabel'], {}), "('(\\\\d) ([a-z])$', '\\\\1\\\\2', prefLabel)\n", (5396, 5435), False, 'import re\n'), ((6916, 6951), 'rdflib.Literal', 'Literal', (['p'], {'datatype': 'geo.wktLiteral'}), '(p, datatype=geo.wktLiteral)\n', (6923, 6951), False, 'from rdflib import Dataset, URIRef, Literal, XSD, Namespace, RDFS, BNode, SKOS, OWL\n'), ((9748, 9765), 'json.load', 'json.load', (['infile'], {}), '(infile)\n', (9757, 9765), False, 'import json\n'), ((9826, 9843), 'json.load', 'json.load', (['infile'], {}), '(infile)\n', (9835, 9843), False, 'import json\n'), ((5185, 5217), 're.sub', 're.sub', (['"""^[A-Z]{1,2} """', '""""""', 'name'], {}), "('^[A-Z]{1,2} ', '', name)\n", (5191, 5217), False, 'import re\n'), ((10313, 10330), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (10324, 10330), False, 'from collections import defaultdict\n'), ((6671, 6695), 'shapely.wkt.loads', 'wkt.loads', (['point2wkt[lp]'], {}), '(point2wkt[lp])\n', (6680, 6695), False, 'from shapely import wkt\n'), ((6813, 6837), 'shapely.geometry.MultiPoint', 'MultiPoint', ([], {'points': 'geoms'}), '(points=geoms)\n', (6823, 6837), False, 'from shapely.geometry import Point, MultiPoint\n'), ((7411, 7445), 'rdflib.URIRef', 'URIRef', (["data['straat']['adamlink']"], {}), "(data['straat']['adamlink'])\n", (7417, 7445), False, 'from rdflib import Dataset, URIRef, Literal, XSD, Namespace, RDFS, BNode, SKOS, OWL\n'), ((8036, 8069), 'rdflib.URIRef', 'URIRef', (["data['buurt']['adamlink']"], {}), "(data['buurt']['adamlink'])\n", (8042, 8069), False, 'from rdflib import Dataset, URIRef, Literal, XSD, Namespace, RDFS, BNode, SKOS, OWL\n')]
import plotly.figure_factory as FF import numpy as np from scipy.spatial import Delaunay class СharacteristicQuadrilateral: def __init__(self, a): self.x0 = (a[0] - a[2])*1j self.y0 = a[0] + a[2] self.z0 = -a[1]*1j self.x1 = (a[0]-a[2]-a[3])*1j self.y1 = a[0]+a[2]+a[3] self.z1 = -a[1]*1j self.x2 = (a[0] - a[2] - 2*a[3])*1j self.y2 = a[0] + a[2] + 2*a[3] self.z2 = (a[3] - a[1])*1j self.x3 = (a[0] - a[2] - 2*a[3])*1j self.y3 = a[0] + a[2] + 4*a[3] self.z3 = (3*a[3] - a[1])*1j def create_trisurf_with_parameters(self, u, v, x, y, z, name): points2D = np.vstack([u, v]).T tri = Delaunay(points2D) simplices = tri.simplices return FF.create_trisurf(x=x, y=y, z=z, colormap=['rgb(50, 0, 75)', 'rgb(200, 0, 200)', '#c8dcc8'], show_colorbar=True, simplices=simplices, title=name) def get_uv(self, min, max): u=np.linspace(min, max, 60) v=np.linspace(min, max, 60) u,v=np.meshgrid(u,v) u=u.flatten() v=v.flatten() return u, v def conformal_replacement(self, u, v, r0, r1, r2, r3): return (r0*(1-u-v*1j)**3+3*(r1*(1-u-v*1j)**2)*(u+v*1j)+3*(r2*(1-u-v*1j))*(v*1j+u)**2+r3*(u+v*1j)**3).real def quasiconformal_replacement(self, u, v, k, r0, r1, r2, r3): return r0.real*(1 - 3*u + 3*u**2 - 3*v**2*k**2 - u**3 + 3*u*v**2*k**2) - r0.imag*(-3*v*k+6*u*v*k - 3*u**2*v*k + v**3*k**3) - \ (-3*r1.real*(1 - 2*u + u**2 - v**2*k**2) + 3*r1.imag*(-2*v*k + 2*u*v*k))*u + (-3*r1.imag*(1 - 2*u+ u**2 - v**2*k**2) - \ 3*r1.real*(-2*v*k+2*u*v*k))*v*k - (-3*r2.real*(1 - u) - 3*r2.imag*v*k)*(u**2 - v**2*k**2) + 2*(-3*r2.imag*(1 - u) + \ 3*r2.real*v*k)*u*v*k + r3.real*(u**3 - 3*u*v**2*k**2) - r3.imag*(3*u**2*v*k - v**3*k**3) def create_minimal_surface_conformal_replacement(self, name): u,v = self.get_uv(0,1) x = self.conformal_replacement(u, v, self.x0,self.x1,self.x2,self.x3) y = self.conformal_replacement(u, v, self.y0,self.y1,self.y2,self.y3) z = self.conformal_replacement(u, v, self.z0,self.z1,self.z2,self.z3) return self.create_trisurf_with_parameters(u, v, x, y, z, name) def create_minimal_surface_quasiconformal_replacement(self, name, k): u,v = self.get_uv(0,1) x = self.quasiconformal_replacement(u, v, k, self.x0,self.x1,self.x2,self.x3) y = self.quasiconformal_replacement(u, v, k, self.y0,self.y1,self.y2,self.y3) z = self.quasiconformal_replacement(u, v, k, self.z0,self.z1,self.z2,self.z3) return self.create_trisurf_with_parameters(u, v, x, y, z, name)
[ "plotly.figure_factory.create_trisurf", "numpy.linspace", "numpy.vstack", "scipy.spatial.Delaunay", "numpy.meshgrid" ]
[((703, 721), 'scipy.spatial.Delaunay', 'Delaunay', (['points2D'], {}), '(points2D)\n', (711, 721), False, 'from scipy.spatial import Delaunay\n'), ((771, 924), 'plotly.figure_factory.create_trisurf', 'FF.create_trisurf', ([], {'x': 'x', 'y': 'y', 'z': 'z', 'colormap': "['rgb(50, 0, 75)', 'rgb(200, 0, 200)', '#c8dcc8']", 'show_colorbar': '(True)', 'simplices': 'simplices', 'title': 'name'}), "(x=x, y=y, z=z, colormap=['rgb(50, 0, 75)',\n 'rgb(200, 0, 200)', '#c8dcc8'], show_colorbar=True, simplices=simplices,\n title=name)\n", (788, 924), True, 'import plotly.figure_factory as FF\n'), ((1089, 1114), 'numpy.linspace', 'np.linspace', (['min', 'max', '(60)'], {}), '(min, max, 60)\n', (1100, 1114), True, 'import numpy as np\n'), ((1125, 1150), 'numpy.linspace', 'np.linspace', (['min', 'max', '(60)'], {}), '(min, max, 60)\n', (1136, 1150), True, 'import numpy as np\n'), ((1163, 1180), 'numpy.meshgrid', 'np.meshgrid', (['u', 'v'], {}), '(u, v)\n', (1174, 1180), True, 'import numpy as np\n'), ((669, 686), 'numpy.vstack', 'np.vstack', (['[u, v]'], {}), '([u, v])\n', (678, 686), True, 'import numpy as np\n')]
from django.contrib.auth.hashers import make_password from django.contrib.auth.validators import UnicodeUsernameValidator from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import gettext_lazy as _ from django.conf import settings from multiselectfield import MultiSelectField class Test(models.Model): question = models.TextField("Входные данные", blank=True) answer = models.TextField("Выходные данные", blank=True) task = models.ForeignKey('Task', verbose_name='Тест', on_delete=models.CASCADE, related_name='test') is_visible = models.BooleanField(_('Является видимым'), default=False) class TaskDetail(models.Model): is_done = models.BooleanField(_('Является сделанным'), default=False) students = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='Учащийся', on_delete=models.CASCADE) task = models.ForeignKey('Task', verbose_name='Задание', on_delete=models.CASCADE, related_name='task_detail') last_code = models.TextField(_("Последний запущенный код"), blank=True) LANGUAGES = (('python3', 'Python'), ('cpp', 'C++'), ('c', 'C'), ('csharp', 'C#'), ('perl', 'Perl'), ('pascal', 'Pascal')) class Task(models.Model): name = models.CharField(_("Название задания"), max_length=64, blank=True) theory = models.TextField(_("Теоретическое введение"), blank=True) mission = models.TextField(_("Техническое задание"), blank=True) sprint = models.ForeignKey('Sprint', on_delete=models.CASCADE, related_name='tasks') students = models.ManyToManyField(settings.AUTH_USER_MODEL, verbose_name='Учащиеся', through=TaskDetail) languages = MultiSelectField(choices=LANGUAGES, default='python') def __str__(self): return self.name class Sprint(models.Model): name = models.CharField(_("Название спринта"), max_length=64, blank=True) grade = models.ForeignKey('Grade', on_delete=models.CASCADE, verbose_name='Класс', related_name='sprints') class Meta: verbose_name = 'Блок' verbose_name_plural = 'Блоки' def __str__(self): return self.name class Grade(models.Model): name = models.CharField(_("Название класса"), max_length=64, blank=True) grades = models.ManyToManyField(settings.AUTH_USER_MODEL, verbose_name='Пользователи', related_name='grades') class Meta: verbose_name = 'Класс' verbose_name_plural = 'Классы' def __str__(self): return self.name class User(AbstractUser): middle_name = models.CharField(_("Отчество"), max_length=64, blank=True) date_of_birth = models.DateField('Дата рождения', default="2000-01-01") school = models.CharField(_("Учебное заведение"), max_length=64, blank=True) # def save(self, *args, **kwargs): # super().save(*args, **kwargs) # # import http.client # import mimetypes # conn = http.client.HTTPConnection("127.0.0.1", 8000) # boundary = '' # payload = '' # headers = { # 'Authorization': 'Bearer <KEY>GUsw3esk5keM48M', # 'Content-type': 'multipart/form-data; boundary={}'.format(boundary) # } # conn.request("GET", "/auth/users/reset_password/", payload, headers) # res = conn.getresponse() # data = res.read() # print(data.decode("utf-8")) # print(data) # self.email_user(self, self.username + "||" + self.password + "||" + "message", **kwargs) class Meta: verbose_name = 'Пользователь' verbose_name_plural = 'Пользователи' def get_full_name(self): if self.groups.filter(name='Учителя').exists(): admin_panel_name = 'УЧИТЕЛЬ | ' + self.email + ' (' + self.last_name + ' ' + self.first_name[ 0:1] + '.' + self.middle_name[ 0:1] + '.)' elif self.groups.filter(name='Ученики').exists(): admin_panel_name = '' + self.email + ' (' + self.last_name + ' ' + self.first_name[ 0:1] + '.' + self.middle_name[0:1] + '.)' else: admin_panel_name = 'none | ' + self.email + ' (' + self.last_name + ' ' + self.first_name[ 0:1] + '.' + self.middle_name[ 0:1] + '.)' return admin_panel_name def __str__(self): return self.get_full_name()
[ "multiselectfield.MultiSelectField", "django.db.models.DateField", "django.db.models.TextField", "django.db.models.ForeignKey", "django.utils.translation.gettext_lazy", "django.db.models.ManyToManyField" ]
[((380, 426), 'django.db.models.TextField', 'models.TextField', (['"""Входные данные"""'], {'blank': '(True)'}), "('Входные данные', blank=True)\n", (396, 426), False, 'from django.db import models\n'), ((440, 487), 'django.db.models.TextField', 'models.TextField', (['"""Выходные данные"""'], {'blank': '(True)'}), "('Выходные данные', blank=True)\n", (456, 487), False, 'from django.db import models\n'), ((499, 596), 'django.db.models.ForeignKey', 'models.ForeignKey', (['"""Task"""'], {'verbose_name': '"""Тест"""', 'on_delete': 'models.CASCADE', 'related_name': '"""test"""'}), "('Task', verbose_name='Тест', on_delete=models.CASCADE,\n related_name='test')\n", (516, 596), False, 'from django.db import models\n'), ((791, 889), 'django.db.models.ForeignKey', 'models.ForeignKey', (['settings.AUTH_USER_MODEL'], {'verbose_name': '"""Учащийся"""', 'on_delete': 'models.CASCADE'}), "(settings.AUTH_USER_MODEL, verbose_name='Учащийся',\n on_delete=models.CASCADE)\n", (808, 889), False, 'from django.db import models\n'), ((897, 1004), 'django.db.models.ForeignKey', 'models.ForeignKey', (['"""Task"""'], {'verbose_name': '"""Задание"""', 'on_delete': 'models.CASCADE', 'related_name': '"""task_detail"""'}), "('Task', verbose_name='Задание', on_delete=models.CASCADE,\n related_name='task_detail')\n", (914, 1004), False, 'from django.db import models\n'), ((1525, 1600), 'django.db.models.ForeignKey', 'models.ForeignKey', (['"""Sprint"""'], {'on_delete': 'models.CASCADE', 'related_name': '"""tasks"""'}), "('Sprint', on_delete=models.CASCADE, related_name='tasks')\n", (1542, 1600), False, 'from django.db import models\n'), ((1616, 1713), 'django.db.models.ManyToManyField', 'models.ManyToManyField', (['settings.AUTH_USER_MODEL'], {'verbose_name': '"""Учащиеся"""', 'through': 'TaskDetail'}), "(settings.AUTH_USER_MODEL, verbose_name='Учащиеся',\n through=TaskDetail)\n", (1638, 1713), False, 'from django.db import models\n'), ((1726, 1779), 'multiselectfield.MultiSelectField', 'MultiSelectField', ([], {'choices': 'LANGUAGES', 'default': '"""python"""'}), "(choices=LANGUAGES, default='python')\n", (1742, 1779), False, 'from multiselectfield import MultiSelectField\n'), ((1949, 2051), 'django.db.models.ForeignKey', 'models.ForeignKey', (['"""Grade"""'], {'on_delete': 'models.CASCADE', 'verbose_name': '"""Класс"""', 'related_name': '"""sprints"""'}), "('Grade', on_delete=models.CASCADE, verbose_name='Класс',\n related_name='sprints')\n", (1966, 2051), False, 'from django.db import models\n'), ((2301, 2406), 'django.db.models.ManyToManyField', 'models.ManyToManyField', (['settings.AUTH_USER_MODEL'], {'verbose_name': '"""Пользователи"""', 'related_name': '"""grades"""'}), "(settings.AUTH_USER_MODEL, verbose_name=\n 'Пользователи', related_name='grades')\n", (2323, 2406), False, 'from django.db import models\n'), ((2663, 2718), 'django.db.models.DateField', 'models.DateField', (['"""Дата рождения"""'], {'default': '"""2000-01-01"""'}), "('Дата рождения', default='2000-01-01')\n", (2679, 2718), False, 'from django.db import models\n'), ((630, 651), 'django.utils.translation.gettext_lazy', '_', (['"""Является видимым"""'], {}), "('Является видимым')\n", (631, 651), True, 'from django.utils.translation import gettext_lazy as _\n'), ((736, 759), 'django.utils.translation.gettext_lazy', '_', (['"""Является сделанным"""'], {}), "('Является сделанным')\n", (737, 759), True, 'from django.utils.translation import gettext_lazy as _\n'), ((1034, 1063), 'django.utils.translation.gettext_lazy', '_', (['"""Последний запущенный код"""'], {}), "('Последний запущенный код')\n", (1035, 1063), True, 'from django.utils.translation import gettext_lazy as _\n'), ((1322, 1343), 'django.utils.translation.gettext_lazy', '_', (['"""Название задания"""'], {}), "('Название задания')\n", (1323, 1343), True, 'from django.utils.translation import gettext_lazy as _\n'), ((1402, 1429), 'django.utils.translation.gettext_lazy', '_', (['"""Теоретическое введение"""'], {}), "('Теоретическое введение')\n", (1403, 1429), True, 'from django.utils.translation import gettext_lazy as _\n'), ((1474, 1498), 'django.utils.translation.gettext_lazy', '_', (['"""Техническое задание"""'], {}), "('Техническое задание')\n", (1475, 1498), True, 'from django.utils.translation import gettext_lazy as _\n'), ((1887, 1908), 'django.utils.translation.gettext_lazy', '_', (['"""Название спринта"""'], {}), "('Название спринта')\n", (1888, 1908), True, 'from django.utils.translation import gettext_lazy as _\n'), ((2239, 2259), 'django.utils.translation.gettext_lazy', '_', (['"""Название класса"""'], {}), "('Название класса')\n", (2240, 2259), True, 'from django.utils.translation import gettext_lazy as _\n'), ((2601, 2614), 'django.utils.translation.gettext_lazy', '_', (['"""Отчество"""'], {}), "('Отчество')\n", (2602, 2614), True, 'from django.utils.translation import gettext_lazy as _\n'), ((2749, 2771), 'django.utils.translation.gettext_lazy', '_', (['"""Учебное заведение"""'], {}), "('Учебное заведение')\n", (2750, 2771), True, 'from django.utils.translation import gettext_lazy as _\n')]
# PyQt5 modules from PyQt5.QtGui import QColor, QPainter, QRadialGradient, QBrush from PyQt5.QtCore import Qt, QTimer, QSize, pyqtSlot, pyqtProperty from PyQt5.QtWidgets import QWidget, QApplication class LedWidget(QWidget): def __init__(self, parent=None): super(LedWidget, self).__init__(parent) self._diamX = 0 self._diamY = 0 self._diameter = 20 self._color = QColor("gray") self._alignment = Qt.AlignCenter self._state = True self._flashing = False self._flashRate = 100 self._timer = QTimer() self._timer.timeout.connect(self.toggleState) self.setDiameter(self._diameter) def paintEvent(self, event): painter = QPainter() x = 0 y = 0 if self._alignment & Qt.AlignLeft: x = 0 elif self._alignment & Qt.AlignRight: x = self.width() - self._diameter elif self._alignment & Qt.AlignHCenter: x = (self.width() - self._diameter) / 2 elif self._alignment & Qt.AlignJustify: x = 0 if self._alignment & Qt.AlignTop: y = 0 elif self._alignment & Qt.AlignBottom: y = self.height() - self._diameter elif self._alignment & Qt.AlignVCenter: y = (self.height() - self._diameter) / 2 gradient = QRadialGradient(x + self._diameter / 2, y + self._diameter / 2, self._diameter * 0.4, self._diameter * 0.4, self._diameter * 0.4) gradient.setColorAt(0, Qt.white) if self._state: gradient.setColorAt(1, self._color) else: gradient.setColorAt(1, Qt.black) painter.begin(self) brush = QBrush(gradient) painter.setPen(self._color) painter.setRenderHint(QPainter.Antialiasing, True) painter.setBrush(brush) painter.drawEllipse(x, y, self._diameter - 1, self._diameter - 1) if self._flashRate > 0 and self._flashing: self._timer.start(self._flashRate) else: self._timer.stop() painter.end() def minimumSizeHint(self): return QSize(self._diameter, self._diameter) def sizeHint(self): return QSize(self._diameter, self._diameter) def getDiameter(self): return self._diameter @pyqtSlot(int) def setDiameter(self, value): self._diameter = value self.update() def getColor(self): return self._color @pyqtSlot(QColor) def setColor(self, value): self._color = value self.update() def getAlignment(self): return self._alignment @pyqtSlot(Qt.Alignment) def setAlignment(self, value): self._alignment = value self.update() def getState(self): return self._alignment @pyqtSlot(bool) def setState(self, value): self._state = value self.update() @pyqtSlot() def toggleState(self): self._state = not self._state self.update() def isFlashing(self): return self._flashing @pyqtSlot(bool) def setFlashing(self, value): self._flashing = value self.update() def getFlashRate(self): return self._flashRate @pyqtSlot(int) def setFlashRate(self, value): self._flashRate = value self.update() @pyqtSlot() def startFlashing(self): self.setFlashing(True) @pyqtSlot() def stopFlashing(self): self.setFlashing(False) diameter = pyqtProperty(int, getDiameter, setDiameter) color = pyqtProperty(QColor, getColor, setColor) alignment = pyqtProperty(Qt.Alignment, getAlignment, setAlignment) state = pyqtProperty(bool, getState, setState) flashing = pyqtProperty(bool, isFlashing, setFlashing) flashRate = pyqtProperty(int, getFlashRate, setFlashRate) if __name__ == "__main__": import sys app = QApplication(sys.argv) led = LedWidget() led.show() sys.exit(app.exec_())
[ "PyQt5.QtCore.pyqtProperty", "PyQt5.QtGui.QPainter", "PyQt5.QtCore.QTimer", "PyQt5.QtGui.QColor", "PyQt5.QtGui.QBrush", "PyQt5.QtCore.pyqtSlot", "PyQt5.QtWidgets.QApplication", "PyQt5.QtGui.QRadialGradient", "PyQt5.QtCore.QSize" ]
[((2366, 2379), 'PyQt5.QtCore.pyqtSlot', 'pyqtSlot', (['int'], {}), '(int)\n', (2374, 2379), False, 'from PyQt5.QtCore import Qt, QTimer, QSize, pyqtSlot, pyqtProperty\n'), ((2525, 2541), 'PyQt5.QtCore.pyqtSlot', 'pyqtSlot', (['QColor'], {}), '(QColor)\n', (2533, 2541), False, 'from PyQt5.QtCore import Qt, QTimer, QSize, pyqtSlot, pyqtProperty\n'), ((2689, 2711), 'PyQt5.QtCore.pyqtSlot', 'pyqtSlot', (['Qt.Alignment'], {}), '(Qt.Alignment)\n', (2697, 2711), False, 'from PyQt5.QtCore import Qt, QTimer, QSize, pyqtSlot, pyqtProperty\n'), ((2863, 2877), 'PyQt5.QtCore.pyqtSlot', 'pyqtSlot', (['bool'], {}), '(bool)\n', (2871, 2877), False, 'from PyQt5.QtCore import Qt, QTimer, QSize, pyqtSlot, pyqtProperty\n'), ((2965, 2975), 'PyQt5.QtCore.pyqtSlot', 'pyqtSlot', ([], {}), '()\n', (2973, 2975), False, 'from PyQt5.QtCore import Qt, QTimer, QSize, pyqtSlot, pyqtProperty\n'), ((3126, 3140), 'PyQt5.QtCore.pyqtSlot', 'pyqtSlot', (['bool'], {}), '(bool)\n', (3134, 3140), False, 'from PyQt5.QtCore import Qt, QTimer, QSize, pyqtSlot, pyqtProperty\n'), ((3294, 3307), 'PyQt5.QtCore.pyqtSlot', 'pyqtSlot', (['int'], {}), '(int)\n', (3302, 3307), False, 'from PyQt5.QtCore import Qt, QTimer, QSize, pyqtSlot, pyqtProperty\n'), ((3403, 3413), 'PyQt5.QtCore.pyqtSlot', 'pyqtSlot', ([], {}), '()\n', (3411, 3413), False, 'from PyQt5.QtCore import Qt, QTimer, QSize, pyqtSlot, pyqtProperty\n'), ((3480, 3490), 'PyQt5.QtCore.pyqtSlot', 'pyqtSlot', ([], {}), '()\n', (3488, 3490), False, 'from PyQt5.QtCore import Qt, QTimer, QSize, pyqtSlot, pyqtProperty\n'), ((3567, 3610), 'PyQt5.QtCore.pyqtProperty', 'pyqtProperty', (['int', 'getDiameter', 'setDiameter'], {}), '(int, getDiameter, setDiameter)\n', (3579, 3610), False, 'from PyQt5.QtCore import Qt, QTimer, QSize, pyqtSlot, pyqtProperty\n'), ((3623, 3663), 'PyQt5.QtCore.pyqtProperty', 'pyqtProperty', (['QColor', 'getColor', 'setColor'], {}), '(QColor, getColor, setColor)\n', (3635, 3663), False, 'from PyQt5.QtCore import Qt, QTimer, QSize, pyqtSlot, pyqtProperty\n'), ((3680, 3734), 'PyQt5.QtCore.pyqtProperty', 'pyqtProperty', (['Qt.Alignment', 'getAlignment', 'setAlignment'], {}), '(Qt.Alignment, getAlignment, setAlignment)\n', (3692, 3734), False, 'from PyQt5.QtCore import Qt, QTimer, QSize, pyqtSlot, pyqtProperty\n'), ((3747, 3785), 'PyQt5.QtCore.pyqtProperty', 'pyqtProperty', (['bool', 'getState', 'setState'], {}), '(bool, getState, setState)\n', (3759, 3785), False, 'from PyQt5.QtCore import Qt, QTimer, QSize, pyqtSlot, pyqtProperty\n'), ((3801, 3844), 'PyQt5.QtCore.pyqtProperty', 'pyqtProperty', (['bool', 'isFlashing', 'setFlashing'], {}), '(bool, isFlashing, setFlashing)\n', (3813, 3844), False, 'from PyQt5.QtCore import Qt, QTimer, QSize, pyqtSlot, pyqtProperty\n'), ((3861, 3906), 'PyQt5.QtCore.pyqtProperty', 'pyqtProperty', (['int', 'getFlashRate', 'setFlashRate'], {}), '(int, getFlashRate, setFlashRate)\n', (3873, 3906), False, 'from PyQt5.QtCore import Qt, QTimer, QSize, pyqtSlot, pyqtProperty\n'), ((3962, 3984), 'PyQt5.QtWidgets.QApplication', 'QApplication', (['sys.argv'], {}), '(sys.argv)\n', (3974, 3984), False, 'from PyQt5.QtWidgets import QWidget, QApplication\n'), ((413, 427), 'PyQt5.QtGui.QColor', 'QColor', (['"""gray"""'], {}), "('gray')\n", (419, 427), False, 'from PyQt5.QtGui import QColor, QPainter, QRadialGradient, QBrush\n'), ((580, 588), 'PyQt5.QtCore.QTimer', 'QTimer', ([], {}), '()\n', (586, 588), False, 'from PyQt5.QtCore import Qt, QTimer, QSize, pyqtSlot, pyqtProperty\n'), ((737, 747), 'PyQt5.QtGui.QPainter', 'QPainter', ([], {}), '()\n', (745, 747), False, 'from PyQt5.QtGui import QColor, QPainter, QRadialGradient, QBrush\n'), ((1371, 1505), 'PyQt5.QtGui.QRadialGradient', 'QRadialGradient', (['(x + self._diameter / 2)', '(y + self._diameter / 2)', '(self._diameter * 0.4)', '(self._diameter * 0.4)', '(self._diameter * 0.4)'], {}), '(x + self._diameter / 2, y + self._diameter / 2, self.\n _diameter * 0.4, self._diameter * 0.4, self._diameter * 0.4)\n', (1386, 1505), False, 'from PyQt5.QtGui import QColor, QPainter, QRadialGradient, QBrush\n'), ((1754, 1770), 'PyQt5.QtGui.QBrush', 'QBrush', (['gradient'], {}), '(gradient)\n', (1760, 1770), False, 'from PyQt5.QtGui import QColor, QPainter, QRadialGradient, QBrush\n'), ((2186, 2223), 'PyQt5.QtCore.QSize', 'QSize', (['self._diameter', 'self._diameter'], {}), '(self._diameter, self._diameter)\n', (2191, 2223), False, 'from PyQt5.QtCore import Qt, QTimer, QSize, pyqtSlot, pyqtProperty\n'), ((2264, 2301), 'PyQt5.QtCore.QSize', 'QSize', (['self._diameter', 'self._diameter'], {}), '(self._diameter, self._diameter)\n', (2269, 2301), False, 'from PyQt5.QtCore import Qt, QTimer, QSize, pyqtSlot, pyqtProperty\n')]
### The point of this module is that, ### when you import it, you get the "vendor" directory ### on your python's sys.path. import sys import os.path import site already_vendorified = False def vendorify(): global already_vendorified if already_vendorified: return ROOT = os.path.dirname(os.path.abspath(__file__)) path = lambda *a: os.path.join(ROOT, *a) prev_sys_path = list(sys.path) site.addsitedir(path('.')) # Move the new items to the front of sys.path. new_sys_path = [] for item in list(sys.path): if item not in prev_sys_path: new_sys_path.append(item) sys.path.remove(item) sys.path[:0] = new_sys_path # Remark that we have already vendorified already_vendorified = True
[ "sys.path.remove" ]
[((644, 665), 'sys.path.remove', 'sys.path.remove', (['item'], {}), '(item)\n', (659, 665), False, 'import sys\n')]