max_stars_repo_path
stringlengths
4
286
max_stars_repo_name
stringlengths
5
119
max_stars_count
int64
0
191k
id
stringlengths
1
7
content
stringlengths
6
1.03M
content_cleaned
stringlengths
6
1.03M
language
stringclasses
111 values
language_score
float64
0.03
1
comments
stringlengths
0
556k
edu_score
float64
0.32
5.03
edu_int_score
int64
0
5
public_data/serializers.py
MTES-MCT/sparte
0
0
<reponame>MTES-MCT/sparte from rest_framework_gis import serializers from rest_framework import serializers as s from .models import ( Artificialisee2015to2018, Artificielle2018, CommunesSybarval, CouvertureSol, EnveloppeUrbaine2018, Ocsge, Renaturee2018to2015, Sybarval, Voirie2018, ZonesBaties2018, UsageSol, ) def get_label(code="", label=""): if code is None: code = "-" if label is None: label = "inconnu" return f"{code} {label[:30]}" class Artificialisee2015to2018Serializer(serializers.GeoFeatureModelSerializer): usage_2015 = s.SerializerMethodField() usage_2018 = s.SerializerMethodField() couverture_2015 = s.SerializerMethodField() couverture_2018 = s.SerializerMethodField() def get_usage_2015(self, obj): return get_label(code=obj.us_2015, label=obj.us_2015_label) def get_usage_2018(self, obj): return get_label(code=obj.us_2018, label=obj.us_2018_label) def get_couverture_2015(self, obj): return get_label(code=obj.cs_2015, label=obj.cs_2015_label) def get_couverture_2018(self, obj): return get_label(code=obj.cs_2018, label=obj.cs_2018_label) class Meta: fields = ( "id", "surface", "usage_2015", "usage_2018", "couverture_2015", "couverture_2018", ) geo_field = "mpoly" model = Artificialisee2015to2018 class Artificielle2018Serializer(serializers.GeoFeatureModelSerializer): couverture = s.SerializerMethodField() def get_couverture(self, obj): return get_label(code=obj.couverture, label=obj.couverture_label) class Meta: fields = ( "id", "surface", "couverture", ) geo_field = "mpoly" model = Artificielle2018 class CommunesSybarvalSerializer(serializers.GeoFeatureModelSerializer): """Marker GeoJSON serializer.""" class Meta: """Marker serializer meta class.""" fields = ( "nom", "code_insee", "surface", ) geo_field = "mpoly" model = CommunesSybarval class EnveloppeUrbaine2018Serializer(serializers.GeoFeatureModelSerializer): couverture = s.SerializerMethodField() def get_couverture(self, obj): return get_label(code=obj.couverture, label=obj.couverture_label) class Meta: fields = ( "id", "couverture", "surface", ) geo_field = "mpoly" model = EnveloppeUrbaine2018 class OcsgeSerializer(serializers.GeoFeatureModelSerializer): couverture = s.SerializerMethodField() usage = s.SerializerMethodField() def get_couverture(self, obj): return get_label(code=obj.couverture, label=obj.couverture_label) def get_usage(self, obj): return get_label(code=obj.usage, label=obj.usage_label) class Meta: fields = ( "id", "couverture", "usage", "millesime", "map_color", "year", ) geo_field = "mpoly" model = Ocsge class Renaturee2018to2015Serializer(serializers.GeoFeatureModelSerializer): usage_2015 = s.SerializerMethodField() usage_2018 = s.SerializerMethodField() couverture_2015 = s.SerializerMethodField() couverture_2018 = s.SerializerMethodField() def get_usage_2015(self, obj): return get_label(code=obj.us_2015, label=obj.us_2015_label) def get_usage_2018(self, obj): return get_label(code=obj.us_2018, label=obj.us_2018_label) def get_couverture_2015(self, obj): return get_label(code=obj.cs_2015, label=obj.cs_2015_label) def get_couverture_2018(self, obj): return get_label(code=obj.cs_2018, label=obj.cs_2018_label) class Meta: fields = ( "id", "surface", "usage_2015", "usage_2018", "couverture_2015", "couverture_2018", ) geo_field = "mpoly" model = Renaturee2018to2015 class SybarvalSerializer(serializers.GeoFeatureModelSerializer): class Meta: fields = ( "id", "surface", ) geo_field = "mpoly" model = Sybarval class Voirie2018Serializer(serializers.GeoFeatureModelSerializer): couverture = s.SerializerMethodField() usage = s.SerializerMethodField() def get_couverture(self, obj): return get_label(code=obj.couverture, label=obj.couverture_label) def get_usage(self, obj): return get_label(code=obj.usage, label=obj.usage_label) class Meta: fields = ( "id", "surface", "couverture", "usage", ) geo_field = "mpoly" model = Voirie2018 class ZonesBaties2018Serializer(serializers.GeoFeatureModelSerializer): couverture = s.SerializerMethodField() usage = s.SerializerMethodField() def get_couverture(self, obj): return get_label(code=obj.couverture, label=obj.couverture_label) def get_usage(self, obj): return get_label(code=obj.usage, label=obj.usage_label) class Meta: fields = ( "id", "couverture", "usage", "surface", ) geo_field = "mpoly" model = ZonesBaties2018 class CouvertureSolSerializer(serializers.ModelSerializer): class Meta: fields = ( "id", "parent", "code", "label", "is_artificial", ) model = CouvertureSol class UsageSolSerializer(serializers.ModelSerializer): class Meta: fields = ( "id", "parent", "code", "label", ) model = UsageSol
from rest_framework_gis import serializers from rest_framework import serializers as s from .models import ( Artificialisee2015to2018, Artificielle2018, CommunesSybarval, CouvertureSol, EnveloppeUrbaine2018, Ocsge, Renaturee2018to2015, Sybarval, Voirie2018, ZonesBaties2018, UsageSol, ) def get_label(code="", label=""): if code is None: code = "-" if label is None: label = "inconnu" return f"{code} {label[:30]}" class Artificialisee2015to2018Serializer(serializers.GeoFeatureModelSerializer): usage_2015 = s.SerializerMethodField() usage_2018 = s.SerializerMethodField() couverture_2015 = s.SerializerMethodField() couverture_2018 = s.SerializerMethodField() def get_usage_2015(self, obj): return get_label(code=obj.us_2015, label=obj.us_2015_label) def get_usage_2018(self, obj): return get_label(code=obj.us_2018, label=obj.us_2018_label) def get_couverture_2015(self, obj): return get_label(code=obj.cs_2015, label=obj.cs_2015_label) def get_couverture_2018(self, obj): return get_label(code=obj.cs_2018, label=obj.cs_2018_label) class Meta: fields = ( "id", "surface", "usage_2015", "usage_2018", "couverture_2015", "couverture_2018", ) geo_field = "mpoly" model = Artificialisee2015to2018 class Artificielle2018Serializer(serializers.GeoFeatureModelSerializer): couverture = s.SerializerMethodField() def get_couverture(self, obj): return get_label(code=obj.couverture, label=obj.couverture_label) class Meta: fields = ( "id", "surface", "couverture", ) geo_field = "mpoly" model = Artificielle2018 class CommunesSybarvalSerializer(serializers.GeoFeatureModelSerializer): """Marker GeoJSON serializer.""" class Meta: """Marker serializer meta class.""" fields = ( "nom", "code_insee", "surface", ) geo_field = "mpoly" model = CommunesSybarval class EnveloppeUrbaine2018Serializer(serializers.GeoFeatureModelSerializer): couverture = s.SerializerMethodField() def get_couverture(self, obj): return get_label(code=obj.couverture, label=obj.couverture_label) class Meta: fields = ( "id", "couverture", "surface", ) geo_field = "mpoly" model = EnveloppeUrbaine2018 class OcsgeSerializer(serializers.GeoFeatureModelSerializer): couverture = s.SerializerMethodField() usage = s.SerializerMethodField() def get_couverture(self, obj): return get_label(code=obj.couverture, label=obj.couverture_label) def get_usage(self, obj): return get_label(code=obj.usage, label=obj.usage_label) class Meta: fields = ( "id", "couverture", "usage", "millesime", "map_color", "year", ) geo_field = "mpoly" model = Ocsge class Renaturee2018to2015Serializer(serializers.GeoFeatureModelSerializer): usage_2015 = s.SerializerMethodField() usage_2018 = s.SerializerMethodField() couverture_2015 = s.SerializerMethodField() couverture_2018 = s.SerializerMethodField() def get_usage_2015(self, obj): return get_label(code=obj.us_2015, label=obj.us_2015_label) def get_usage_2018(self, obj): return get_label(code=obj.us_2018, label=obj.us_2018_label) def get_couverture_2015(self, obj): return get_label(code=obj.cs_2015, label=obj.cs_2015_label) def get_couverture_2018(self, obj): return get_label(code=obj.cs_2018, label=obj.cs_2018_label) class Meta: fields = ( "id", "surface", "usage_2015", "usage_2018", "couverture_2015", "couverture_2018", ) geo_field = "mpoly" model = Renaturee2018to2015 class SybarvalSerializer(serializers.GeoFeatureModelSerializer): class Meta: fields = ( "id", "surface", ) geo_field = "mpoly" model = Sybarval class Voirie2018Serializer(serializers.GeoFeatureModelSerializer): couverture = s.SerializerMethodField() usage = s.SerializerMethodField() def get_couverture(self, obj): return get_label(code=obj.couverture, label=obj.couverture_label) def get_usage(self, obj): return get_label(code=obj.usage, label=obj.usage_label) class Meta: fields = ( "id", "surface", "couverture", "usage", ) geo_field = "mpoly" model = Voirie2018 class ZonesBaties2018Serializer(serializers.GeoFeatureModelSerializer): couverture = s.SerializerMethodField() usage = s.SerializerMethodField() def get_couverture(self, obj): return get_label(code=obj.couverture, label=obj.couverture_label) def get_usage(self, obj): return get_label(code=obj.usage, label=obj.usage_label) class Meta: fields = ( "id", "couverture", "usage", "surface", ) geo_field = "mpoly" model = ZonesBaties2018 class CouvertureSolSerializer(serializers.ModelSerializer): class Meta: fields = ( "id", "parent", "code", "label", "is_artificial", ) model = CouvertureSol class UsageSolSerializer(serializers.ModelSerializer): class Meta: fields = ( "id", "parent", "code", "label", ) model = UsageSol
en
0.404844
Marker GeoJSON serializer. Marker serializer meta class.
2.186829
2
quick_search/admin.py
naman1901/django-quick-search
0
1
from django.contrib import admin from .models import SearchResult # Register your models here. class SearchResultAdmin(admin.ModelAdmin): fields = ["query", "heading", "url", "text"] admin.site.register(SearchResult, SearchResultAdmin)
from django.contrib import admin from .models import SearchResult # Register your models here. class SearchResultAdmin(admin.ModelAdmin): fields = ["query", "heading", "url", "text"] admin.site.register(SearchResult, SearchResultAdmin)
en
0.968259
# Register your models here.
1.640673
2
rasa/train.py
Amirali-Shirkh/rasa-for-botfront
0
2
import asyncio import os import tempfile from contextlib import ExitStack from typing import Text, Optional, List, Union, Dict from rasa.importers.importer import TrainingDataImporter from rasa import model from rasa.model import FingerprintComparisonResult from rasa.core.domain import Domain from rasa.utils.common import TempDirectoryPath from rasa.cli.utils import ( print_success, print_warning, print_error, bcolors, print_color, ) from rasa.constants import DEFAULT_MODELS_PATH, DEFAULT_CORE_SUBDIRECTORY_NAME def train( domain: Text, config: Text, training_files: Union[Text, List[Text]], output: Text = DEFAULT_MODELS_PATH, force_training: bool = False, fixed_model_name: Optional[Text] = None, persist_nlu_training_data: bool = False, additional_arguments: Optional[Dict] = None, loop: Optional[asyncio.AbstractEventLoop] = None, ) -> Optional[Text]: if loop is None: try: loop = asyncio.get_event_loop() except RuntimeError: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) return loop.run_until_complete( train_async( domain=domain, config=config, training_files=training_files, output_path=output, force_training=force_training, fixed_model_name=fixed_model_name, persist_nlu_training_data=persist_nlu_training_data, additional_arguments=additional_arguments, ) ) async def train_async( domain: Union[Domain, Text], config: Dict[Text, Text], training_files: Optional[Union[Text, List[Text]]], output_path: Text = DEFAULT_MODELS_PATH, force_training: bool = False, fixed_model_name: Optional[Text] = None, persist_nlu_training_data: bool = False, additional_arguments: Optional[Dict] = None, ) -> Optional[Text]: """Trains a Rasa model (Core and NLU). Args: domain: Path to the domain file. config: Dict of paths to the config for Core and NLU. Keys are language codes training_files: Paths to the training data for Core and NLU. output_path: Output path. force_training: If `True` retrain model even if data has not changed. fixed_model_name: Name of model to be stored. persist_nlu_training_data: `True` if the NLU training data should be persisted with the model. additional_arguments: Additional training parameters. Returns: Path of the trained model archive. """ # file_importer = TrainingDataImporter.load_from_config( # config, domain, training_files # ) with ExitStack() as stack: train_path = stack.enter_context(TempDirectoryPath(tempfile.mkdtemp())) # bf mod from rasa_addons.importers import BotfrontFileImporter file_importer = BotfrontFileImporter(config, domain, training_files) # domain = await file_importer.get_domain() # if domain.is_empty(): # return await handle_domain_if_not_exists( # file_importer, output_path, fixed_model_name # ) # /bf mod return await _train_async_internal( file_importer, train_path, output_path, force_training, fixed_model_name, persist_nlu_training_data, additional_arguments, ) async def handle_domain_if_not_exists( file_importer: TrainingDataImporter, output_path, fixed_model_name ): nlu_model_only = await _train_nlu_with_validated_data( file_importer, output=output_path, fixed_model_name=fixed_model_name ) print_warning( "Core training was skipped because no valid domain file was found. Only an nlu-model was created." "Please specify a valid domain using '--domain' argument or check if the provided domain file exists." ) return nlu_model_only async def _train_async_internal( file_importer: TrainingDataImporter, train_path: Text, output_path: Text, force_training: bool, fixed_model_name: Optional[Text], persist_nlu_training_data: bool, additional_arguments: Optional[Dict], ) -> Optional[Text]: """Trains a Rasa model (Core and NLU). Use only from `train_async`. Args: file_importer: `TrainingDataImporter` which supplies the training data. train_path: Directory in which to train the model. output_path: Output path. force_training: If `True` retrain model even if data has not changed. persist_nlu_training_data: `True` if the NLU training data should be persisted with the model. fixed_model_name: Name of model to be stored. additional_arguments: Additional training parameters. Returns: Path of the trained model archive. """ stories, nlu_data = await asyncio.gather( file_importer.get_stories(), file_importer.get_nlu_data() ) # if stories.is_empty() and nlu_data.is_empty(): # print_error( # "No training data given. Please provide stories and NLU data in " # "order to train a Rasa model using the '--data' argument." # ) # return # if nlu_data.is_empty(): # print_warning("No NLU data present. Just a Rasa Core model will be trained.") # return await _train_core_with_validated_data( # file_importer, # output=output_path, # fixed_model_name=fixed_model_name, # additional_arguments=additional_arguments, # ) new_fingerprint = await model.model_fingerprint(file_importer) old_model = model.get_latest_model(output_path) fingerprint_comparison = FingerprintComparisonResult(force_training=force_training) if not force_training: fingerprint_comparison = model.should_retrain( new_fingerprint, old_model, train_path ) # bf mod > if fingerprint_comparison.nlu == True: # replace True with list of all langs fingerprint_comparison.nlu = list(new_fingerprint.get("nlu-config", {}).keys()) domain = await file_importer.get_domain() core_untrainable = domain.is_empty() or stories.is_empty() nlu_untrainable = [l for l, d in nlu_data.items() if d.is_empty()] fingerprint_comparison.core = fingerprint_comparison.core and not core_untrainable fingerprint_comparison.nlu = [l for l in fingerprint_comparison.nlu if l not in nlu_untrainable] if core_untrainable: print_color("Skipping Core training since domain or stories are empty.", color=bcolors.OKBLUE) for lang in nlu_untrainable: print_color("No NLU data found for language <{}>, skipping training...".format(lang), color=bcolors.OKBLUE) # </ bf mod if fingerprint_comparison.is_training_required(): await _do_training( file_importer, output_path=output_path, train_path=train_path, fingerprint_comparison_result=fingerprint_comparison, fixed_model_name=fixed_model_name, persist_nlu_training_data=persist_nlu_training_data, additional_arguments=additional_arguments, ) return model.package_model( fingerprint=new_fingerprint, output_directory=output_path, train_path=train_path, fixed_model_name=fixed_model_name, ) print_success( "Nothing changed. You can use the old model stored at '{}'." "".format(os.path.abspath(old_model)) ) return old_model async def _do_training( file_importer: TrainingDataImporter, output_path: Text, train_path: Text, fingerprint_comparison_result: Optional[FingerprintComparisonResult] = None, fixed_model_name: Optional[Text] = None, persist_nlu_training_data: bool = False, additional_arguments: Optional[Dict] = None, ): if not fingerprint_comparison_result: fingerprint_comparison_result = FingerprintComparisonResult() if fingerprint_comparison_result.should_retrain_core(): await _train_core_with_validated_data( file_importer, output=output_path, train_path=train_path, fixed_model_name=fixed_model_name, additional_arguments=additional_arguments, ) elif fingerprint_comparison_result.should_retrain_nlg(): print_color( "Core stories/configuration did not change. " "Only the templates section has been changed. A new model with " "the updated templates will be created.", color=bcolors.OKBLUE, ) await model.update_model_with_new_domain(file_importer, train_path) else: print_color( "Core stories/configuration did not change. No need to retrain Core model.", color=bcolors.OKBLUE, ) if fingerprint_comparison_result.should_retrain_nlu(): await _train_nlu_with_validated_data( file_importer, output=output_path, train_path=train_path, fixed_model_name=fixed_model_name, retrain_nlu=fingerprint_comparison_result.nlu, persist_nlu_training_data=persist_nlu_training_data, ) else: print_color( "NLU data/configuration did not change. No need to retrain NLU model.", color=bcolors.OKBLUE, ) def train_core( domain: Union[Domain, Text], config: Text, stories: Text, output: Text, train_path: Optional[Text] = None, fixed_model_name: Optional[Text] = None, additional_arguments: Optional[Dict] = None, ) -> Optional[Text]: loop = asyncio.get_event_loop() return loop.run_until_complete( train_core_async( domain=domain, config=config, stories=stories, output=output, train_path=train_path, fixed_model_name=fixed_model_name, additional_arguments=additional_arguments, ) ) async def train_core_async( domain: Union[Domain, Text], config: Text, stories: Text, output: Text, train_path: Optional[Text] = None, fixed_model_name: Optional[Text] = None, additional_arguments: Optional[Dict] = None, ) -> Optional[Text]: """Trains a Core model. Args: domain: Path to the domain file. config: Path to the config file for Core. stories: Path to the Core training data. output: Output path. train_path: If `None` the model will be trained in a temporary directory, otherwise in the provided directory. fixed_model_name: Name of model to be stored. uncompress: If `True` the model will not be compressed. additional_arguments: Additional training parameters. Returns: If `train_path` is given it returns the path to the model archive, otherwise the path to the directory with the trained model files. """ file_importer = TrainingDataImporter.load_core_importer_from_config( config, domain, [stories] ) domain = await file_importer.get_domain() if domain.is_empty(): print_error( "Core training was skipped because no valid domain file was found. " "Please specify a valid domain using '--domain' argument or check if the provided domain file exists." ) return None if not await file_importer.get_stories(): print_error( "No stories given. Please provide stories in order to " "train a Rasa Core model using the '--stories' argument." ) return return await _train_core_with_validated_data( file_importer, output=output, train_path=train_path, fixed_model_name=fixed_model_name, additional_arguments=additional_arguments, ) async def _train_core_with_validated_data( file_importer: TrainingDataImporter, output: Text, train_path: Optional[Text] = None, fixed_model_name: Optional[Text] = None, additional_arguments: Optional[Dict] = None, ) -> Optional[Text]: """Train Core with validated training and config data.""" import rasa.core.train with ExitStack() as stack: if train_path: # If the train path was provided, do nothing on exit. _train_path = train_path else: # Otherwise, create a temp train path and clean it up on exit. _train_path = stack.enter_context(TempDirectoryPath(tempfile.mkdtemp())) # normal (not compare) training print_color("Training Core model...", color=bcolors.OKBLUE) domain, config = await asyncio.gather( file_importer.get_domain(), file_importer.get_config() ) await rasa.core.train( domain_file=domain, training_resource=file_importer, output_path=os.path.join(_train_path, DEFAULT_CORE_SUBDIRECTORY_NAME), policy_config=config, additional_arguments=additional_arguments, ) print_color("Core model training completed.", color=bcolors.OKBLUE) if train_path is None: # Only Core was trained. new_fingerprint = await model.model_fingerprint(file_importer) return model.package_model( fingerprint=new_fingerprint, output_directory=output, train_path=_train_path, fixed_model_name=fixed_model_name, model_prefix="core-", ) return _train_path def train_nlu( config: Text, nlu_data: Text, output: Text, train_path: Optional[Text] = None, fixed_model_name: Optional[Text] = None, persist_nlu_training_data: bool = False, ) -> Optional[Text]: """Trains an NLU model. Args: config: Path to the config file for NLU. nlu_data: Path to the NLU training data. output: Output path. train_path: If `None` the model will be trained in a temporary directory, otherwise in the provided directory. fixed_model_name: Name of the model to be stored. persist_nlu_training_data: `True` if the NLU training data should be persisted with the model. Returns: If `train_path` is given it returns the path to the model archive, otherwise the path to the directory with the trained model files. """ loop = asyncio.get_event_loop() return loop.run_until_complete( _train_nlu_async( config, nlu_data, output, train_path, fixed_model_name, persist_nlu_training_data, ) ) async def _train_nlu_async( config: Text, nlu_data: Text, output: Text, train_path: Optional[Text] = None, fixed_model_name: Optional[Text] = None, persist_nlu_training_data: bool = False, ): if not nlu_data: print_error( "No NLU data given. Please provide NLU data in order to train " "a Rasa NLU model using the '--nlu' argument." ) return # training NLU only hence the training files still have to be selected file_importer = TrainingDataImporter.load_nlu_importer_from_config( config, training_data_paths=[nlu_data] ) training_datas = await file_importer.get_nlu_data() if training_datas.is_empty(): print_error( f"Path '{nlu_data}' doesn't contain valid NLU data in it. " "Please verify the data format. " "The NLU model training will be skipped now." ) return return await _train_nlu_with_validated_data( file_importer, output=output, train_path=train_path, fixed_model_name=fixed_model_name, persist_nlu_training_data=persist_nlu_training_data, ) async def _train_nlu_with_validated_data( file_importer: TrainingDataImporter, output: Text, train_path: Optional[Text] = None, fixed_model_name: Optional[Text] = None, persist_nlu_training_data: bool = False, retrain_nlu: Union[bool, List[Text]] = True ) -> Optional[Text]: """Train NLU with validated training and config data.""" import rasa.nlu.train with ExitStack() as stack: models = {} from rasa.nlu import config as cfg_loader if train_path: # If the train path was provided, do nothing on exit. _train_path = train_path else: # Otherwise, create a temp train path and clean it up on exit. _train_path = stack.enter_context(TempDirectoryPath(tempfile.mkdtemp())) # bf mod config = await file_importer.get_nlu_config(retrain_nlu) for lang in config: if config[lang]: print_color("Start training {} NLU model ...".format(lang), color=bcolors.OKBLUE) _, models[lang], _ = await rasa.nlu.train( config[lang], file_importer, _train_path, fixed_model_name="nlu-{}".format(lang), persist_nlu_training_data=persist_nlu_training_data, ) else: print_color("NLU data for language <{}> didn't change, skipping training...".format(lang), color=bcolors.OKBLUE) # /bf mod print_color("NLU model training completed.", color=bcolors.OKBLUE) if train_path is None: # Only NLU was trained new_fingerprint = await model.model_fingerprint(file_importer) return model.package_model( fingerprint=new_fingerprint, output_directory=output, train_path=_train_path, fixed_model_name=fixed_model_name, model_prefix="nlu-", ) return _train_path
import asyncio import os import tempfile from contextlib import ExitStack from typing import Text, Optional, List, Union, Dict from rasa.importers.importer import TrainingDataImporter from rasa import model from rasa.model import FingerprintComparisonResult from rasa.core.domain import Domain from rasa.utils.common import TempDirectoryPath from rasa.cli.utils import ( print_success, print_warning, print_error, bcolors, print_color, ) from rasa.constants import DEFAULT_MODELS_PATH, DEFAULT_CORE_SUBDIRECTORY_NAME def train( domain: Text, config: Text, training_files: Union[Text, List[Text]], output: Text = DEFAULT_MODELS_PATH, force_training: bool = False, fixed_model_name: Optional[Text] = None, persist_nlu_training_data: bool = False, additional_arguments: Optional[Dict] = None, loop: Optional[asyncio.AbstractEventLoop] = None, ) -> Optional[Text]: if loop is None: try: loop = asyncio.get_event_loop() except RuntimeError: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) return loop.run_until_complete( train_async( domain=domain, config=config, training_files=training_files, output_path=output, force_training=force_training, fixed_model_name=fixed_model_name, persist_nlu_training_data=persist_nlu_training_data, additional_arguments=additional_arguments, ) ) async def train_async( domain: Union[Domain, Text], config: Dict[Text, Text], training_files: Optional[Union[Text, List[Text]]], output_path: Text = DEFAULT_MODELS_PATH, force_training: bool = False, fixed_model_name: Optional[Text] = None, persist_nlu_training_data: bool = False, additional_arguments: Optional[Dict] = None, ) -> Optional[Text]: """Trains a Rasa model (Core and NLU). Args: domain: Path to the domain file. config: Dict of paths to the config for Core and NLU. Keys are language codes training_files: Paths to the training data for Core and NLU. output_path: Output path. force_training: If `True` retrain model even if data has not changed. fixed_model_name: Name of model to be stored. persist_nlu_training_data: `True` if the NLU training data should be persisted with the model. additional_arguments: Additional training parameters. Returns: Path of the trained model archive. """ # file_importer = TrainingDataImporter.load_from_config( # config, domain, training_files # ) with ExitStack() as stack: train_path = stack.enter_context(TempDirectoryPath(tempfile.mkdtemp())) # bf mod from rasa_addons.importers import BotfrontFileImporter file_importer = BotfrontFileImporter(config, domain, training_files) # domain = await file_importer.get_domain() # if domain.is_empty(): # return await handle_domain_if_not_exists( # file_importer, output_path, fixed_model_name # ) # /bf mod return await _train_async_internal( file_importer, train_path, output_path, force_training, fixed_model_name, persist_nlu_training_data, additional_arguments, ) async def handle_domain_if_not_exists( file_importer: TrainingDataImporter, output_path, fixed_model_name ): nlu_model_only = await _train_nlu_with_validated_data( file_importer, output=output_path, fixed_model_name=fixed_model_name ) print_warning( "Core training was skipped because no valid domain file was found. Only an nlu-model was created." "Please specify a valid domain using '--domain' argument or check if the provided domain file exists." ) return nlu_model_only async def _train_async_internal( file_importer: TrainingDataImporter, train_path: Text, output_path: Text, force_training: bool, fixed_model_name: Optional[Text], persist_nlu_training_data: bool, additional_arguments: Optional[Dict], ) -> Optional[Text]: """Trains a Rasa model (Core and NLU). Use only from `train_async`. Args: file_importer: `TrainingDataImporter` which supplies the training data. train_path: Directory in which to train the model. output_path: Output path. force_training: If `True` retrain model even if data has not changed. persist_nlu_training_data: `True` if the NLU training data should be persisted with the model. fixed_model_name: Name of model to be stored. additional_arguments: Additional training parameters. Returns: Path of the trained model archive. """ stories, nlu_data = await asyncio.gather( file_importer.get_stories(), file_importer.get_nlu_data() ) # if stories.is_empty() and nlu_data.is_empty(): # print_error( # "No training data given. Please provide stories and NLU data in " # "order to train a Rasa model using the '--data' argument." # ) # return # if nlu_data.is_empty(): # print_warning("No NLU data present. Just a Rasa Core model will be trained.") # return await _train_core_with_validated_data( # file_importer, # output=output_path, # fixed_model_name=fixed_model_name, # additional_arguments=additional_arguments, # ) new_fingerprint = await model.model_fingerprint(file_importer) old_model = model.get_latest_model(output_path) fingerprint_comparison = FingerprintComparisonResult(force_training=force_training) if not force_training: fingerprint_comparison = model.should_retrain( new_fingerprint, old_model, train_path ) # bf mod > if fingerprint_comparison.nlu == True: # replace True with list of all langs fingerprint_comparison.nlu = list(new_fingerprint.get("nlu-config", {}).keys()) domain = await file_importer.get_domain() core_untrainable = domain.is_empty() or stories.is_empty() nlu_untrainable = [l for l, d in nlu_data.items() if d.is_empty()] fingerprint_comparison.core = fingerprint_comparison.core and not core_untrainable fingerprint_comparison.nlu = [l for l in fingerprint_comparison.nlu if l not in nlu_untrainable] if core_untrainable: print_color("Skipping Core training since domain or stories are empty.", color=bcolors.OKBLUE) for lang in nlu_untrainable: print_color("No NLU data found for language <{}>, skipping training...".format(lang), color=bcolors.OKBLUE) # </ bf mod if fingerprint_comparison.is_training_required(): await _do_training( file_importer, output_path=output_path, train_path=train_path, fingerprint_comparison_result=fingerprint_comparison, fixed_model_name=fixed_model_name, persist_nlu_training_data=persist_nlu_training_data, additional_arguments=additional_arguments, ) return model.package_model( fingerprint=new_fingerprint, output_directory=output_path, train_path=train_path, fixed_model_name=fixed_model_name, ) print_success( "Nothing changed. You can use the old model stored at '{}'." "".format(os.path.abspath(old_model)) ) return old_model async def _do_training( file_importer: TrainingDataImporter, output_path: Text, train_path: Text, fingerprint_comparison_result: Optional[FingerprintComparisonResult] = None, fixed_model_name: Optional[Text] = None, persist_nlu_training_data: bool = False, additional_arguments: Optional[Dict] = None, ): if not fingerprint_comparison_result: fingerprint_comparison_result = FingerprintComparisonResult() if fingerprint_comparison_result.should_retrain_core(): await _train_core_with_validated_data( file_importer, output=output_path, train_path=train_path, fixed_model_name=fixed_model_name, additional_arguments=additional_arguments, ) elif fingerprint_comparison_result.should_retrain_nlg(): print_color( "Core stories/configuration did not change. " "Only the templates section has been changed. A new model with " "the updated templates will be created.", color=bcolors.OKBLUE, ) await model.update_model_with_new_domain(file_importer, train_path) else: print_color( "Core stories/configuration did not change. No need to retrain Core model.", color=bcolors.OKBLUE, ) if fingerprint_comparison_result.should_retrain_nlu(): await _train_nlu_with_validated_data( file_importer, output=output_path, train_path=train_path, fixed_model_name=fixed_model_name, retrain_nlu=fingerprint_comparison_result.nlu, persist_nlu_training_data=persist_nlu_training_data, ) else: print_color( "NLU data/configuration did not change. No need to retrain NLU model.", color=bcolors.OKBLUE, ) def train_core( domain: Union[Domain, Text], config: Text, stories: Text, output: Text, train_path: Optional[Text] = None, fixed_model_name: Optional[Text] = None, additional_arguments: Optional[Dict] = None, ) -> Optional[Text]: loop = asyncio.get_event_loop() return loop.run_until_complete( train_core_async( domain=domain, config=config, stories=stories, output=output, train_path=train_path, fixed_model_name=fixed_model_name, additional_arguments=additional_arguments, ) ) async def train_core_async( domain: Union[Domain, Text], config: Text, stories: Text, output: Text, train_path: Optional[Text] = None, fixed_model_name: Optional[Text] = None, additional_arguments: Optional[Dict] = None, ) -> Optional[Text]: """Trains a Core model. Args: domain: Path to the domain file. config: Path to the config file for Core. stories: Path to the Core training data. output: Output path. train_path: If `None` the model will be trained in a temporary directory, otherwise in the provided directory. fixed_model_name: Name of model to be stored. uncompress: If `True` the model will not be compressed. additional_arguments: Additional training parameters. Returns: If `train_path` is given it returns the path to the model archive, otherwise the path to the directory with the trained model files. """ file_importer = TrainingDataImporter.load_core_importer_from_config( config, domain, [stories] ) domain = await file_importer.get_domain() if domain.is_empty(): print_error( "Core training was skipped because no valid domain file was found. " "Please specify a valid domain using '--domain' argument or check if the provided domain file exists." ) return None if not await file_importer.get_stories(): print_error( "No stories given. Please provide stories in order to " "train a Rasa Core model using the '--stories' argument." ) return return await _train_core_with_validated_data( file_importer, output=output, train_path=train_path, fixed_model_name=fixed_model_name, additional_arguments=additional_arguments, ) async def _train_core_with_validated_data( file_importer: TrainingDataImporter, output: Text, train_path: Optional[Text] = None, fixed_model_name: Optional[Text] = None, additional_arguments: Optional[Dict] = None, ) -> Optional[Text]: """Train Core with validated training and config data.""" import rasa.core.train with ExitStack() as stack: if train_path: # If the train path was provided, do nothing on exit. _train_path = train_path else: # Otherwise, create a temp train path and clean it up on exit. _train_path = stack.enter_context(TempDirectoryPath(tempfile.mkdtemp())) # normal (not compare) training print_color("Training Core model...", color=bcolors.OKBLUE) domain, config = await asyncio.gather( file_importer.get_domain(), file_importer.get_config() ) await rasa.core.train( domain_file=domain, training_resource=file_importer, output_path=os.path.join(_train_path, DEFAULT_CORE_SUBDIRECTORY_NAME), policy_config=config, additional_arguments=additional_arguments, ) print_color("Core model training completed.", color=bcolors.OKBLUE) if train_path is None: # Only Core was trained. new_fingerprint = await model.model_fingerprint(file_importer) return model.package_model( fingerprint=new_fingerprint, output_directory=output, train_path=_train_path, fixed_model_name=fixed_model_name, model_prefix="core-", ) return _train_path def train_nlu( config: Text, nlu_data: Text, output: Text, train_path: Optional[Text] = None, fixed_model_name: Optional[Text] = None, persist_nlu_training_data: bool = False, ) -> Optional[Text]: """Trains an NLU model. Args: config: Path to the config file for NLU. nlu_data: Path to the NLU training data. output: Output path. train_path: If `None` the model will be trained in a temporary directory, otherwise in the provided directory. fixed_model_name: Name of the model to be stored. persist_nlu_training_data: `True` if the NLU training data should be persisted with the model. Returns: If `train_path` is given it returns the path to the model archive, otherwise the path to the directory with the trained model files. """ loop = asyncio.get_event_loop() return loop.run_until_complete( _train_nlu_async( config, nlu_data, output, train_path, fixed_model_name, persist_nlu_training_data, ) ) async def _train_nlu_async( config: Text, nlu_data: Text, output: Text, train_path: Optional[Text] = None, fixed_model_name: Optional[Text] = None, persist_nlu_training_data: bool = False, ): if not nlu_data: print_error( "No NLU data given. Please provide NLU data in order to train " "a Rasa NLU model using the '--nlu' argument." ) return # training NLU only hence the training files still have to be selected file_importer = TrainingDataImporter.load_nlu_importer_from_config( config, training_data_paths=[nlu_data] ) training_datas = await file_importer.get_nlu_data() if training_datas.is_empty(): print_error( f"Path '{nlu_data}' doesn't contain valid NLU data in it. " "Please verify the data format. " "The NLU model training will be skipped now." ) return return await _train_nlu_with_validated_data( file_importer, output=output, train_path=train_path, fixed_model_name=fixed_model_name, persist_nlu_training_data=persist_nlu_training_data, ) async def _train_nlu_with_validated_data( file_importer: TrainingDataImporter, output: Text, train_path: Optional[Text] = None, fixed_model_name: Optional[Text] = None, persist_nlu_training_data: bool = False, retrain_nlu: Union[bool, List[Text]] = True ) -> Optional[Text]: """Train NLU with validated training and config data.""" import rasa.nlu.train with ExitStack() as stack: models = {} from rasa.nlu import config as cfg_loader if train_path: # If the train path was provided, do nothing on exit. _train_path = train_path else: # Otherwise, create a temp train path and clean it up on exit. _train_path = stack.enter_context(TempDirectoryPath(tempfile.mkdtemp())) # bf mod config = await file_importer.get_nlu_config(retrain_nlu) for lang in config: if config[lang]: print_color("Start training {} NLU model ...".format(lang), color=bcolors.OKBLUE) _, models[lang], _ = await rasa.nlu.train( config[lang], file_importer, _train_path, fixed_model_name="nlu-{}".format(lang), persist_nlu_training_data=persist_nlu_training_data, ) else: print_color("NLU data for language <{}> didn't change, skipping training...".format(lang), color=bcolors.OKBLUE) # /bf mod print_color("NLU model training completed.", color=bcolors.OKBLUE) if train_path is None: # Only NLU was trained new_fingerprint = await model.model_fingerprint(file_importer) return model.package_model( fingerprint=new_fingerprint, output_directory=output, train_path=_train_path, fixed_model_name=fixed_model_name, model_prefix="nlu-", ) return _train_path
en
0.748063
Trains a Rasa model (Core and NLU). Args: domain: Path to the domain file. config: Dict of paths to the config for Core and NLU. Keys are language codes training_files: Paths to the training data for Core and NLU. output_path: Output path. force_training: If `True` retrain model even if data has not changed. fixed_model_name: Name of model to be stored. persist_nlu_training_data: `True` if the NLU training data should be persisted with the model. additional_arguments: Additional training parameters. Returns: Path of the trained model archive. # file_importer = TrainingDataImporter.load_from_config( # config, domain, training_files # ) # bf mod # domain = await file_importer.get_domain() # if domain.is_empty(): # return await handle_domain_if_not_exists( # file_importer, output_path, fixed_model_name # ) # /bf mod Trains a Rasa model (Core and NLU). Use only from `train_async`. Args: file_importer: `TrainingDataImporter` which supplies the training data. train_path: Directory in which to train the model. output_path: Output path. force_training: If `True` retrain model even if data has not changed. persist_nlu_training_data: `True` if the NLU training data should be persisted with the model. fixed_model_name: Name of model to be stored. additional_arguments: Additional training parameters. Returns: Path of the trained model archive. # if stories.is_empty() and nlu_data.is_empty(): # print_error( # "No training data given. Please provide stories and NLU data in " # "order to train a Rasa model using the '--data' argument." # ) # return # if nlu_data.is_empty(): # print_warning("No NLU data present. Just a Rasa Core model will be trained.") # return await _train_core_with_validated_data( # file_importer, # output=output_path, # fixed_model_name=fixed_model_name, # additional_arguments=additional_arguments, # ) # bf mod > # replace True with list of all langs # </ bf mod Trains a Core model. Args: domain: Path to the domain file. config: Path to the config file for Core. stories: Path to the Core training data. output: Output path. train_path: If `None` the model will be trained in a temporary directory, otherwise in the provided directory. fixed_model_name: Name of model to be stored. uncompress: If `True` the model will not be compressed. additional_arguments: Additional training parameters. Returns: If `train_path` is given it returns the path to the model archive, otherwise the path to the directory with the trained model files. Train Core with validated training and config data. # If the train path was provided, do nothing on exit. # Otherwise, create a temp train path and clean it up on exit. # normal (not compare) training # Only Core was trained. Trains an NLU model. Args: config: Path to the config file for NLU. nlu_data: Path to the NLU training data. output: Output path. train_path: If `None` the model will be trained in a temporary directory, otherwise in the provided directory. fixed_model_name: Name of the model to be stored. persist_nlu_training_data: `True` if the NLU training data should be persisted with the model. Returns: If `train_path` is given it returns the path to the model archive, otherwise the path to the directory with the trained model files. # training NLU only hence the training files still have to be selected Train NLU with validated training and config data. # If the train path was provided, do nothing on exit. # Otherwise, create a temp train path and clean it up on exit. # bf mod # /bf mod # Only NLU was trained
2.091617
2
coding_intereview/1475. Final Prices With a Special Discount in a Shop.py
Jahidul007/Python-Bootcamp
2
3
<gh_stars>1-10 class Solution: def finalPrices(self, prices: List[int]) -> List[int]: res = [] for i in range(len(prices)): for j in range(i+1,len(prices)): if prices[j]<=prices[i]: res.append(prices[i]-prices[j]) break if j==len(prices)-1: res.append(prices[i]) res.append(prices[-1]) return res
class Solution: def finalPrices(self, prices: List[int]) -> List[int]: res = [] for i in range(len(prices)): for j in range(i+1,len(prices)): if prices[j]<=prices[i]: res.append(prices[i]-prices[j]) break if j==len(prices)-1: res.append(prices[i]) res.append(prices[-1]) return res
none
1
2.914667
3
rplugin/python3/denite/ui/default.py
timgates42/denite.nvim
0
4
<gh_stars>0 # ============================================================================ # FILE: default.py # AUTHOR: <NAME> <<EMAIL> at g<EMAIL>> # License: MIT license # ============================================================================ import re import typing from denite.util import echo, error, clearmatch, regex_convert_py_vim from denite.util import Nvim, UserContext, Candidates, Candidate from denite.parent import SyncParent class Default(object): @property def is_async(self) -> bool: return self._is_async def __init__(self, vim: Nvim) -> None: self._vim = vim self._denite: typing.Optional[SyncParent] = None self._selected_candidates: typing.List[int] = [] self._candidates: Candidates = [] self._cursor = 0 self._entire_len = 0 self._result: typing.List[typing.Any] = [] self._context: UserContext = {} self._bufnr = -1 self._winid = -1 self._winrestcmd = '' self._initialized = False self._winheight = 0 self._winwidth = 0 self._winminheight = -1 self._is_multi = False self._is_async = False self._matched_pattern = '' self._displayed_texts: typing.List[str] = [] self._statusline_sources = '' self._titlestring = '' self._ruler = False self._prev_action = '' self._prev_status: typing.Dict[str, typing.Any] = {} self._prev_curpos: typing.List[typing.Any] = [] self._save_window_options: typing.Dict[str, typing.Any] = {} self._sources_history: typing.List[typing.Any] = [] self._previous_text = '' self._floating = False self._filter_floating = False self._updated = False self._timers: typing.Dict[str, int] = {} self._matched_range_id = -1 self._matched_char_id = -1 self._check_matchdelete = bool(self._vim.call( 'denite#util#check_matchdelete')) def start(self, sources: typing.List[typing.Any], context: UserContext) -> typing.List[typing.Any]: if not self._denite: # if hasattr(self._vim, 'run_coroutine'): # self._denite = ASyncParent(self._vim) # else: self._denite = SyncParent(self._vim) self._result = [] context['sources_queue'] = [sources] self._start_sources_queue(context) return self._result def do_action(self, action_name: str, command: str = '', is_manual: bool = False) -> None: if is_manual: candidates = self._get_selected_candidates() elif self._get_cursor_candidate(): candidates = [self._get_cursor_candidate()] else: candidates = [] if not self._denite or not candidates or not action_name: return self._prev_action = action_name action = self._denite.get_action( self._context, action_name, candidates) if not action: return post_action = self._context['post_action'] is_quit = action['is_quit'] or post_action == 'quit' if is_quit: self.quit() self._denite.do_action(self._context, action_name, candidates) self._result = candidates if command != '': self._vim.command(command) if is_quit and post_action == 'open': # Re-open denite buffer prev_cursor = self._cursor cursor_candidate = self._get_cursor_candidate() self._init_buffer() self.redraw(False) if cursor_candidate == self._get_candidate(prev_cursor): # Restore the cursor self._move_to_pos(prev_cursor) # Disable quit flag is_quit = False if not is_quit and is_manual: self._selected_candidates = [] self.redraw(action['is_redraw']) if is_manual and self._context['sources_queue']: self._context['input'] = '' self._context['quick_move'] = '' self._start_sources_queue(self._context) return def redraw(self, is_force: bool = True) -> None: self._context['is_redraw'] = is_force if is_force: self._gather_candidates() if self._update_candidates(): self._update_buffer() else: self._update_status() self._context['is_redraw'] = False def quit(self) -> None: if self._denite: self._denite.on_close(self._context) self._quit_buffer() self._result = [] return def _restart(self) -> None: self._context['input'] = '' self._quit_buffer() self._init_denite() self._gather_candidates() self._init_buffer() self._update_candidates() self._update_buffer() def _start_sources_queue(self, context: UserContext) -> None: if not context['sources_queue']: return self._sources_history.append({ 'sources': context['sources_queue'][0], 'path': context['path'], }) self._start(context['sources_queue'][0], context) if context['sources_queue']: context['sources_queue'].pop(0) context['path'] = self._context['path'] def _start(self, sources: typing.List[typing.Any], context: UserContext) -> None: from denite.ui.map import do_map self._vim.command('silent! autocmd! denite') if re.search(r'\[Command Line\]$', self._vim.current.buffer.name): # Ignore command line window. return resume = self._initialized and context['resume'] if resume: # Skip the initialization update = ('immediately', 'immediately_1', 'cursor_pos', 'prev_winid', 'start_filter', 'quick_move') for key in update: self._context[key] = context[key] self._check_move_option() if self._check_do_option(): return self._init_buffer() if context['refresh']: self.redraw() self._move_to_pos(self._cursor) else: if self._context != context: self._context.clear() self._context.update(context) self._context['sources'] = sources self._context['is_redraw'] = False self._is_multi = len(sources) > 1 if not sources: # Ignore empty sources. error(self._vim, 'Empty sources') return self._init_denite() self._gather_candidates() self._update_candidates() self._init_cursor() self._check_move_option() if self._check_do_option(): return self._init_buffer() self._update_displayed_texts() self._update_buffer() self._move_to_pos(self._cursor) if self._context['quick_move'] and do_map(self, 'quick_move', []): return if self._context['start_filter']: do_map(self, 'open_filter_buffer', []) def _init_buffer(self) -> None: self._prev_status = dict() self._displayed_texts = [] self._prev_bufnr = self._vim.current.buffer.number self._prev_curpos = self._vim.call('getcurpos') self._prev_wininfo = self._get_wininfo() self._prev_winid = self._context['prev_winid'] self._winrestcmd = self._vim.call('winrestcmd') self._ruler = self._vim.options['ruler'] self._switch_buffer() self._bufnr = self._vim.current.buffer.number self._winid = self._vim.call('win_getid') self._resize_buffer(True) self._winheight = self._vim.current.window.height self._winwidth = self._vim.current.window.width self._bufvars = self._vim.current.buffer.vars self._bufvars['denite'] = { 'buffer_name': self._context['buffer_name'], } self._bufvars['denite_statusline'] = {} self._vim.vars['denite#_previewed_buffers'] = {} self._save_window_options = {} window_options = { 'colorcolumn', 'concealcursor', 'conceallevel', 'cursorcolumn', 'cursorline', 'foldcolumn', 'foldenable', 'list', 'number', 'relativenumber', 'signcolumn', 'spell', 'winfixheight', 'wrap', } for k in window_options: self._save_window_options[k] = self._vim.current.window.options[k] # Note: Have to use setlocal instead of "current.window.options" # "current.window.options" changes global value instead of local in # neovim. self._vim.command('setlocal colorcolumn=') self._vim.command('setlocal conceallevel=3') self._vim.command('setlocal concealcursor=inv') self._vim.command('setlocal nocursorcolumn') self._vim.command('setlocal nofoldenable') self._vim.command('setlocal foldcolumn=0') self._vim.command('setlocal nolist') self._vim.command('setlocal nonumber') self._vim.command('setlocal norelativenumber') self._vim.command('setlocal nospell') self._vim.command('setlocal winfixheight') self._vim.command('setlocal nowrap') if self._context['prompt']: self._vim.command('setlocal signcolumn=yes') else: self._vim.command('setlocal signcolumn=auto') if self._context['cursorline']: self._vim.command('setlocal cursorline') options = self._vim.current.buffer.options if self._floating: # Disable ruler self._vim.options['ruler'] = False options['buftype'] = 'nofile' options['bufhidden'] = 'delete' options['swapfile'] = False options['buflisted'] = False options['modeline'] = False options['modifiable'] = False options['filetype'] = 'denite' if self._vim.call('exists', '#WinEnter'): self._vim.command('doautocmd WinEnter') if self._vim.call('exists', '#BufWinEnter'): self._vim.command('doautocmd BufWinEnter') if not self._vim.call('has', 'nvim'): # In Vim8, FileType autocmd is not fired after set filetype option. self._vim.command('silent doautocmd FileType denite') if self._context['auto_action']: self._vim.command('autocmd denite ' 'CursorMoved <buffer> ' 'call denite#call_map("auto_action")') self._init_syntax() def _switch_buffer(self) -> None: split = self._context['split'] if (split != 'no' and self._winid > 0 and self._vim.call('win_gotoid', self._winid)): if split != 'vertical' and not self._floating: # Move the window to bottom self._vim.command('wincmd J') self._winrestcmd = '' return self._floating = split in [ 'floating', 'floating_relative_cursor', 'floating_relative_window', ] self._filter_floating = False if self._vim.current.buffer.options['filetype'] != 'denite': self._titlestring = self._vim.options['titlestring'] command = 'edit' if split == 'tab': self._vim.command('tabnew') elif self._floating: self._split_floating(split) elif self._context['filter_split_direction'] == 'floating': self._filter_floating = True elif split != 'no': command = self._get_direction() command += ' vsplit' if split == 'vertical' else ' split' bufname = '[denite]-' + self._context['buffer_name'] if self._vim.call('exists', '*bufadd'): bufnr = self._vim.call('bufadd', bufname) vertical = 'vertical' if split == 'vertical' else '' command = ( 'buffer' if split in ['no', 'tab', 'floating', 'floating_relative_window', 'floating_relative_cursor'] else 'sbuffer') self._vim.command( 'silent keepalt %s %s %s %s' % ( self._get_direction(), vertical, command, bufnr, ) ) else: self._vim.call( 'denite#util#execute_path', f'silent keepalt {command}', bufname) def _get_direction(self) -> str: direction = str(self._context['direction']) if direction == 'dynamictop' or direction == 'dynamicbottom': self._update_displayed_texts() winwidth = self._vim.call('winwidth', 0) is_fit = not [x for x in self._displayed_texts if self._vim.call('strwidth', x) > winwidth] if direction == 'dynamictop': direction = 'aboveleft' if is_fit else 'topleft' else: direction = 'belowright' if is_fit else 'botright' return direction def _get_wininfo(self) -> typing.List[typing.Any]: return [ self._vim.options['columns'], self._vim.options['lines'], self._vim.call('win_getid'), self._vim.call('tabpagebuflist') ] def _switch_prev_buffer(self) -> None: if (self._prev_bufnr == self._bufnr or self._vim.buffers[self._prev_bufnr].name == ''): self._vim.command('enew') else: self._vim.command('buffer ' + str(self._prev_bufnr)) def _init_syntax(self) -> None: self._vim.command('syntax case ignore') self._vim.command('highlight default link deniteInput ModeMsg') self._vim.command('highlight link deniteMatchedRange ' + self._context['highlight_matched_range']) self._vim.command('highlight link deniteMatchedChar ' + self._context['highlight_matched_char']) self._vim.command('highlight default link ' + 'deniteStatusLinePath Comment') self._vim.command('highlight default link ' + 'deniteStatusLineNumber LineNR') self._vim.command('highlight default link ' + 'deniteSelectedLine Statement') if self._floating: self._vim.current.window.options['winhighlight'] = ( 'Normal:' + self._context['highlight_window_background'] ) self._vim.command(('syntax match deniteSelectedLine /^[%s].*/' + ' contains=deniteConcealedMark') % ( self._context['selected_icon'])) self._vim.command(('syntax match deniteConcealedMark /^[ %s]/' + ' conceal contained') % ( self._context['selected_icon'])) if self._denite: self._denite.init_syntax(self._context, self._is_multi) def _update_candidates(self) -> bool: if not self._denite: return False [self._is_async, pattern, statuses, self._entire_len, self._candidates] = self._denite.filter_candidates(self._context) prev_displayed_texts = self._displayed_texts self._update_displayed_texts() prev_matched_pattern = self._matched_pattern self._matched_pattern = pattern prev_statusline_sources = self._statusline_sources self._statusline_sources = ' '.join(statuses) if self._is_async: self._start_timer('update_candidates') else: self._stop_timer('update_candidates') updated = (self._displayed_texts != prev_displayed_texts or self._matched_pattern != prev_matched_pattern or self._statusline_sources != prev_statusline_sources) if updated: self._updated = True self._start_timer('update_buffer') if self._context['search'] and self._context['input']: self._vim.call('setreg', '/', self._context['input']) return self._updated def _update_displayed_texts(self) -> None: candidates_len = len(self._candidates) if not self._is_async and self._context['auto_resize']: winminheight = self._context['winminheight'] max_height = min(self._context['winheight'], self._get_max_height()) if (winminheight != -1 and candidates_len < winminheight): self._winheight = winminheight elif candidates_len > max_height: self._winheight = max_height elif candidates_len != self._winheight: self._winheight = candidates_len max_source_name_len = 0 if self._candidates: max_source_name_len = max([ len(self._get_display_source_name(x['source_name'])) for x in self._candidates]) self._context['max_source_name_len'] = max_source_name_len self._context['max_source_name_format'] = ( '{:<' + str(self._context['max_source_name_len']) + '}') self._displayed_texts = [ self._get_candidate_display_text(i) for i in range(0, candidates_len) ] def _update_buffer(self) -> None: is_current_buffer = self._bufnr == self._vim.current.buffer.number self._update_status() if self._check_matchdelete and self._context['match_highlight']: matches = [x['id'] for x in self._vim.call('getmatches', self._winid)] if self._matched_range_id in matches: self._vim.call('matchdelete', self._matched_range_id, self._winid) self._matched_range_id = -1 if self._matched_char_id in matches: self._vim.call('matchdelete', self._matched_char_id, self._winid) self._matched_char_id = -1 if self._matched_pattern != '': self._matched_range_id = self._vim.call( 'matchadd', 'deniteMatchedRange', r'\c' + regex_convert_py_vim(self._matched_pattern), 10, -1, {'window': self._winid}) matched_char_pattern = '[{}]'.format(re.sub( r'([\[\]\\^-])', r'\\\1', self._context['input'].replace(' ', '') )) self._matched_char_id = self._vim.call( 'matchadd', 'deniteMatchedChar', matched_char_pattern, 10, -1, {'window': self._winid}) prev_linenr = self._vim.call('line', '.') prev_candidate = self._get_cursor_candidate() buffer = self._vim.buffers[self._bufnr] buffer.options['modifiable'] = True self._vim.vars['denite#_candidates'] = [ x['word'] for x in self._candidates] buffer[:] = self._displayed_texts buffer.options['modifiable'] = False self._previous_text = self._context['input'] self._resize_buffer(is_current_buffer) is_changed = (self._context['reversed'] or (is_current_buffer and self._previous_text != self._context['input'])) if self._updated and is_changed: if not is_current_buffer: save_winid = self._vim.call('win_getid') self._vim.call('win_gotoid', self._winid) self._init_cursor() self._move_to_pos(self._cursor) if not is_current_buffer: self._vim.call('win_gotoid', save_winid) elif is_current_buffer: self._vim.call('cursor', [prev_linenr, 0]) if is_current_buffer: if (self._context['auto_action'] and prev_candidate != self._get_cursor_candidate()): self.do_action(self._context['auto_action']) self._updated = False self._stop_timer('update_buffer') def _update_status(self) -> None: inpt = '' if self._context['input']: inpt = self._context['input'] + ' ' if self._context['error_messages']: inpt = '[ERROR] ' + inpt path = '[' + self._context['path'] + ']' status = { 'input': inpt, 'sources': self._statusline_sources, 'path': path, # Extra 'buffer_name': self._context['buffer_name'], 'line_total': len(self._candidates), } if status == self._prev_status: return self._bufvars['denite_statusline'] = status self._prev_status = status linenr = "printf('%'.(len(line('$'))+2).'d/%d',line('.'),line('$'))" if self._context['statusline']: if self._floating or self._filter_floating: self._vim.options['titlestring'] = ( "%{denite#get_status('input')}%* " + "%{denite#get_status('sources')} " + " %{denite#get_status('path')}%*" + "%{" + linenr + "}%*") else: winnr = self._vim.call('win_id2win', self._winid) self._vim.call('setwinvar', winnr, '&statusline', ( "%#deniteInput#%{denite#get_status('input')}%* " + "%{denite#get_status('sources')} %=" + "%#deniteStatusLinePath# %{denite#get_status('path')}%*" + "%#deniteStatusLineNumber#%{" + linenr + "}%*")) def _get_display_source_name(self, name: str) -> str: source_names = self._context['source_names'] if not self._is_multi or source_names == 'hide': source_name = '' else: short_name = (re.sub(r'([a-zA-Z])[a-zA-Z]+', r'\1', name) if re.search(r'[^a-zA-Z]', name) else name[:2]) source_name = short_name if source_names == 'short' else name return source_name def _get_candidate_display_text(self, index: int) -> str: source_names = self._context['source_names'] candidate = self._candidates[index] terms = [] if self._is_multi and source_names != 'hide': terms.append(self._context['max_source_name_format'].format( self._get_display_source_name(candidate['source_name']))) encoding = self._context['encoding'] abbr = candidate.get('abbr', candidate['word']).encode( encoding, errors='replace').decode(encoding, errors='replace') terms.append(abbr[:int(self._context['max_candidate_width'])]) return (str(self._context['selected_icon']) if index in self._selected_candidates else ' ') + ' '.join(terms).replace('\n', '') def _get_max_height(self) -> int: return int(self._vim.options['lines']) if not self._floating else ( int(self._vim.options['lines']) - int(self._context['winrow']) - int(self._vim.options['cmdheight'])) def _resize_buffer(self, is_current_buffer: bool) -> None: split = self._context['split'] if (split == 'no' or split == 'tab' or self._vim.call('winnr', '$') == 1): return winheight = max(self._winheight, 1) winwidth = max(self._winwidth, 1) is_vertical = split == 'vertical' if not is_current_buffer: restore = self._vim.call('win_getid') self._vim.call('win_gotoid', self._winid) if not is_vertical and self._vim.current.window.height != winheight: if self._floating: wincol = self._context['winrow'] row = wincol if split == 'floating': if self._context['auto_resize'] and row > 1: row += self._context['winheight'] row -= self._winheight self._vim.call('nvim_win_set_config', self._winid, { 'relative': 'editor', 'row': row, 'col': self._context['wincol'], 'width': winwidth, 'height': winheight, }) filter_row = 0 if wincol == 1 else row + winheight filter_col = self._context['wincol'] else: init_pos = self._vim.call('nvim_win_get_config', self._winid) self._vim.call('nvim_win_set_config', self._winid, { 'relative': 'win', 'win': init_pos['win'], 'row': init_pos['row'], 'col': init_pos['col'], 'width': winwidth, 'height': winheight, }) filter_col = init_pos['col'] if init_pos['anchor'] == 'NW': winpos = self._vim.call('nvim_win_get_position', self._winid) filter_row = winpos[0] + winheight filter_winid = self._vim.vars['denite#_filter_winid'] self._context['filter_winrow'] = row if self._vim.call('win_id2win', filter_winid) > 0: self._vim.call('nvim_win_set_config', filter_winid, { 'relative': 'editor', 'row': filter_row, 'col': filter_col, }) self._vim.command('resize ' + str(winheight)) if self._context['reversed']: self._vim.command('normal! zb') elif is_vertical and self._vim.current.window.width != winwidth: self._vim.command('vertical resize ' + str(winwidth)) if not is_current_buffer: self._vim.call('win_gotoid', restore) def _check_do_option(self) -> bool: if self._context['do'] != '': self._do_command(self._context['do']) return True elif (self._candidates and self._context['immediately'] or len(self._candidates) == 1 and self._context['immediately_1']): self._do_immediately() return True return not (self._context['empty'] or self._is_async or self._candidates) def _check_move_option(self) -> None: if self._context['cursor_pos'].isnumeric(): self._cursor = int(self._context['cursor_pos']) + 1 elif re.match(r'\+\d+', self._context['cursor_pos']): for _ in range(int(self._context['cursor_pos'][1:])): self._move_to_next_line() elif re.match(r'-\d+', self._context['cursor_pos']): for _ in range(int(self._context['cursor_pos'][1:])): self._move_to_prev_line() elif self._context['cursor_pos'] == '$': self._move_to_last_line() def _do_immediately(self) -> None: goto = self._winid > 0 and self._vim.call( 'win_gotoid', self._winid) if goto: # Jump to denite window self._init_buffer() self.do_action('default') candidate = self._get_cursor_candidate() if not candidate: return echo(self._vim, 'Normal', '[{}/{}] {}'.format( self._cursor, len(self._candidates), candidate.get('abbr', candidate['word']))) if goto: # Move to the previous window self._vim.command('wincmd p') def _do_command(self, command: str) -> None: self._init_cursor() cursor = 1 while cursor < len(self._candidates): self.do_action('default', command) self._move_to_next_line() self._quit_buffer() def _cleanup(self) -> None: self._stop_timer('update_candidates') self._stop_timer('update_buffer') if self._vim.current.buffer.number == self._bufnr: self._cursor = self._vim.call('line', '.') # Note: Close filter window before preview window self._vim.call('denite#filter#_close_filter_window') if not self._context['has_preview_window']: self._vim.command('pclose!') # Clear previewed buffers for bufnr in self._vim.vars['denite#_previewed_buffers'].keys(): if not self._vim.call('win_findbuf', bufnr): self._vim.command('silent bdelete ' + str(bufnr)) self._vim.vars['denite#_previewed_buffers'] = {} self._vim.command('highlight! link CursorLine CursorLine') if self._floating or self._filter_floating: self._vim.options['titlestring'] = self._titlestring self._vim.options['ruler'] = self._ruler def _close_current_window(self) -> None: if self._vim.call('winnr', '$') == 1: self._vim.command('buffer #') else: self._vim.command('close!') def _quit_buffer(self) -> None: self._cleanup() if self._vim.call('bufwinnr', self._bufnr) < 0: # Denite buffer is already closed return winids = self._vim.call('win_findbuf', self._vim.vars['denite#_filter_bufnr']) if winids: # Quit filter buffer self._vim.call('win_gotoid', winids[0]) self._close_current_window() # Move to denite window self._vim.call('win_gotoid', self._winid) # Restore the window if self._context['split'] == 'no': self._switch_prev_buffer() for k, v in self._save_window_options.items(): self._vim.current.window.options[k] = v else: if self._context['split'] == 'tab': self._vim.command('tabclose!') if self._context['split'] != 'tab': self._close_current_window() self._vim.call('win_gotoid', self._prev_winid) # Restore the position self._vim.call('setpos', '.', self._prev_curpos) if self._get_wininfo() and self._get_wininfo() == self._prev_wininfo: # Note: execute restcmd twice to restore layout properly self._vim.command(self._winrestcmd) self._vim.command(self._winrestcmd) clearmatch(self._vim) def _get_cursor_candidate(self) -> Candidate: return self._get_candidate(self._cursor) def _get_candidate(self, pos: int) -> Candidate: if not self._candidates or pos > len(self._candidates): return {} return self._candidates[pos - 1] def _get_selected_candidates(self) -> Candidates: if not self._selected_candidates: return [self._get_cursor_candidate() ] if self._get_cursor_candidate() else [] return [self._candidates[x] for x in self._selected_candidates] def _init_denite(self) -> None: if self._denite: self._denite.start(self._context) self._denite.on_init(self._context) self._initialized = True self._winheight = self._context['winheight'] self._winwidth = self._context['winwidth'] def _gather_candidates(self) -> None: self._selected_candidates = [] if self._denite: self._denite.gather_candidates(self._context) def _init_cursor(self) -> None: if self._context['reversed']: self._move_to_last_line() else: self._move_to_first_line() def _move_to_pos(self, pos: int) -> None: self._vim.call('cursor', pos, 0) self._cursor = pos if self._context['reversed']: self._vim.command('normal! zb') def _move_to_next_line(self) -> None: if self._cursor < len(self._candidates): self._cursor += 1 def _move_to_prev_line(self) -> None: if self._cursor >= 1: self._cursor -= 1 def _move_to_first_line(self) -> None: self._cursor = 1 def _move_to_last_line(self) -> None: self._cursor = len(self._candidates) def _start_timer(self, key: str) -> None: if key in self._timers: return if key == 'update_candidates': self._timers[key] = self._vim.call( 'denite#helper#_start_update_candidates_timer', self._bufnr) elif key == 'update_buffer': self._timers[key] = self._vim.call( 'denite#helper#_start_update_buffer_timer', self._bufnr) def _stop_timer(self, key: str) -> None: if key not in self._timers: return self._vim.call('timer_stop', self._timers[key]) # Note: After timer_stop is called, self._timers may be removed if key in self._timers: self._timers.pop(key) def _split_floating(self, split: str) -> None: # Use floating window if split == 'floating': self._vim.call( 'nvim_open_win', self._vim.call('bufnr', '%'), True, { 'relative': 'editor', 'row': self._context['winrow'], 'col': self._context['wincol'], 'width': self._context['winwidth'], 'height': self._context['winheight'], }) elif split == 'floating_relative_cursor': opened_pos = (self._vim.call('nvim_win_get_position', 0)[0] + self._vim.call('winline') - 1) if self._context['auto_resize']: height = max(self._winheight, 1) width = max(self._winwidth, 1) else: width = self._context['winwidth'] height = self._context['winheight'] if opened_pos + height + 3 > self._vim.options['lines']: anchor = 'SW' row = 0 self._context['filter_winrow'] = row + opened_pos else: anchor = 'NW' row = 1 self._context['filter_winrow'] = row + height + opened_pos self._vim.call( 'nvim_open_win', self._vim.call('bufnr', '%'), True, { 'relative': 'cursor', 'row': row, 'col': 0, 'width': width, 'height': height, 'anchor': anchor, }) elif split == 'floating_relative_window': self._vim.call( 'nvim_open_win', self._vim.call('bufnr', '%'), True, { 'relative': 'win', 'row': self._context['winrow'], 'col': self._context['wincol'], 'width': self._context['winwidth'], 'height': self._context['winheight'], })
# ============================================================================ # FILE: default.py # AUTHOR: <NAME> <<EMAIL> at g<EMAIL>> # License: MIT license # ============================================================================ import re import typing from denite.util import echo, error, clearmatch, regex_convert_py_vim from denite.util import Nvim, UserContext, Candidates, Candidate from denite.parent import SyncParent class Default(object): @property def is_async(self) -> bool: return self._is_async def __init__(self, vim: Nvim) -> None: self._vim = vim self._denite: typing.Optional[SyncParent] = None self._selected_candidates: typing.List[int] = [] self._candidates: Candidates = [] self._cursor = 0 self._entire_len = 0 self._result: typing.List[typing.Any] = [] self._context: UserContext = {} self._bufnr = -1 self._winid = -1 self._winrestcmd = '' self._initialized = False self._winheight = 0 self._winwidth = 0 self._winminheight = -1 self._is_multi = False self._is_async = False self._matched_pattern = '' self._displayed_texts: typing.List[str] = [] self._statusline_sources = '' self._titlestring = '' self._ruler = False self._prev_action = '' self._prev_status: typing.Dict[str, typing.Any] = {} self._prev_curpos: typing.List[typing.Any] = [] self._save_window_options: typing.Dict[str, typing.Any] = {} self._sources_history: typing.List[typing.Any] = [] self._previous_text = '' self._floating = False self._filter_floating = False self._updated = False self._timers: typing.Dict[str, int] = {} self._matched_range_id = -1 self._matched_char_id = -1 self._check_matchdelete = bool(self._vim.call( 'denite#util#check_matchdelete')) def start(self, sources: typing.List[typing.Any], context: UserContext) -> typing.List[typing.Any]: if not self._denite: # if hasattr(self._vim, 'run_coroutine'): # self._denite = ASyncParent(self._vim) # else: self._denite = SyncParent(self._vim) self._result = [] context['sources_queue'] = [sources] self._start_sources_queue(context) return self._result def do_action(self, action_name: str, command: str = '', is_manual: bool = False) -> None: if is_manual: candidates = self._get_selected_candidates() elif self._get_cursor_candidate(): candidates = [self._get_cursor_candidate()] else: candidates = [] if not self._denite or not candidates or not action_name: return self._prev_action = action_name action = self._denite.get_action( self._context, action_name, candidates) if not action: return post_action = self._context['post_action'] is_quit = action['is_quit'] or post_action == 'quit' if is_quit: self.quit() self._denite.do_action(self._context, action_name, candidates) self._result = candidates if command != '': self._vim.command(command) if is_quit and post_action == 'open': # Re-open denite buffer prev_cursor = self._cursor cursor_candidate = self._get_cursor_candidate() self._init_buffer() self.redraw(False) if cursor_candidate == self._get_candidate(prev_cursor): # Restore the cursor self._move_to_pos(prev_cursor) # Disable quit flag is_quit = False if not is_quit and is_manual: self._selected_candidates = [] self.redraw(action['is_redraw']) if is_manual and self._context['sources_queue']: self._context['input'] = '' self._context['quick_move'] = '' self._start_sources_queue(self._context) return def redraw(self, is_force: bool = True) -> None: self._context['is_redraw'] = is_force if is_force: self._gather_candidates() if self._update_candidates(): self._update_buffer() else: self._update_status() self._context['is_redraw'] = False def quit(self) -> None: if self._denite: self._denite.on_close(self._context) self._quit_buffer() self._result = [] return def _restart(self) -> None: self._context['input'] = '' self._quit_buffer() self._init_denite() self._gather_candidates() self._init_buffer() self._update_candidates() self._update_buffer() def _start_sources_queue(self, context: UserContext) -> None: if not context['sources_queue']: return self._sources_history.append({ 'sources': context['sources_queue'][0], 'path': context['path'], }) self._start(context['sources_queue'][0], context) if context['sources_queue']: context['sources_queue'].pop(0) context['path'] = self._context['path'] def _start(self, sources: typing.List[typing.Any], context: UserContext) -> None: from denite.ui.map import do_map self._vim.command('silent! autocmd! denite') if re.search(r'\[Command Line\]$', self._vim.current.buffer.name): # Ignore command line window. return resume = self._initialized and context['resume'] if resume: # Skip the initialization update = ('immediately', 'immediately_1', 'cursor_pos', 'prev_winid', 'start_filter', 'quick_move') for key in update: self._context[key] = context[key] self._check_move_option() if self._check_do_option(): return self._init_buffer() if context['refresh']: self.redraw() self._move_to_pos(self._cursor) else: if self._context != context: self._context.clear() self._context.update(context) self._context['sources'] = sources self._context['is_redraw'] = False self._is_multi = len(sources) > 1 if not sources: # Ignore empty sources. error(self._vim, 'Empty sources') return self._init_denite() self._gather_candidates() self._update_candidates() self._init_cursor() self._check_move_option() if self._check_do_option(): return self._init_buffer() self._update_displayed_texts() self._update_buffer() self._move_to_pos(self._cursor) if self._context['quick_move'] and do_map(self, 'quick_move', []): return if self._context['start_filter']: do_map(self, 'open_filter_buffer', []) def _init_buffer(self) -> None: self._prev_status = dict() self._displayed_texts = [] self._prev_bufnr = self._vim.current.buffer.number self._prev_curpos = self._vim.call('getcurpos') self._prev_wininfo = self._get_wininfo() self._prev_winid = self._context['prev_winid'] self._winrestcmd = self._vim.call('winrestcmd') self._ruler = self._vim.options['ruler'] self._switch_buffer() self._bufnr = self._vim.current.buffer.number self._winid = self._vim.call('win_getid') self._resize_buffer(True) self._winheight = self._vim.current.window.height self._winwidth = self._vim.current.window.width self._bufvars = self._vim.current.buffer.vars self._bufvars['denite'] = { 'buffer_name': self._context['buffer_name'], } self._bufvars['denite_statusline'] = {} self._vim.vars['denite#_previewed_buffers'] = {} self._save_window_options = {} window_options = { 'colorcolumn', 'concealcursor', 'conceallevel', 'cursorcolumn', 'cursorline', 'foldcolumn', 'foldenable', 'list', 'number', 'relativenumber', 'signcolumn', 'spell', 'winfixheight', 'wrap', } for k in window_options: self._save_window_options[k] = self._vim.current.window.options[k] # Note: Have to use setlocal instead of "current.window.options" # "current.window.options" changes global value instead of local in # neovim. self._vim.command('setlocal colorcolumn=') self._vim.command('setlocal conceallevel=3') self._vim.command('setlocal concealcursor=inv') self._vim.command('setlocal nocursorcolumn') self._vim.command('setlocal nofoldenable') self._vim.command('setlocal foldcolumn=0') self._vim.command('setlocal nolist') self._vim.command('setlocal nonumber') self._vim.command('setlocal norelativenumber') self._vim.command('setlocal nospell') self._vim.command('setlocal winfixheight') self._vim.command('setlocal nowrap') if self._context['prompt']: self._vim.command('setlocal signcolumn=yes') else: self._vim.command('setlocal signcolumn=auto') if self._context['cursorline']: self._vim.command('setlocal cursorline') options = self._vim.current.buffer.options if self._floating: # Disable ruler self._vim.options['ruler'] = False options['buftype'] = 'nofile' options['bufhidden'] = 'delete' options['swapfile'] = False options['buflisted'] = False options['modeline'] = False options['modifiable'] = False options['filetype'] = 'denite' if self._vim.call('exists', '#WinEnter'): self._vim.command('doautocmd WinEnter') if self._vim.call('exists', '#BufWinEnter'): self._vim.command('doautocmd BufWinEnter') if not self._vim.call('has', 'nvim'): # In Vim8, FileType autocmd is not fired after set filetype option. self._vim.command('silent doautocmd FileType denite') if self._context['auto_action']: self._vim.command('autocmd denite ' 'CursorMoved <buffer> ' 'call denite#call_map("auto_action")') self._init_syntax() def _switch_buffer(self) -> None: split = self._context['split'] if (split != 'no' and self._winid > 0 and self._vim.call('win_gotoid', self._winid)): if split != 'vertical' and not self._floating: # Move the window to bottom self._vim.command('wincmd J') self._winrestcmd = '' return self._floating = split in [ 'floating', 'floating_relative_cursor', 'floating_relative_window', ] self._filter_floating = False if self._vim.current.buffer.options['filetype'] != 'denite': self._titlestring = self._vim.options['titlestring'] command = 'edit' if split == 'tab': self._vim.command('tabnew') elif self._floating: self._split_floating(split) elif self._context['filter_split_direction'] == 'floating': self._filter_floating = True elif split != 'no': command = self._get_direction() command += ' vsplit' if split == 'vertical' else ' split' bufname = '[denite]-' + self._context['buffer_name'] if self._vim.call('exists', '*bufadd'): bufnr = self._vim.call('bufadd', bufname) vertical = 'vertical' if split == 'vertical' else '' command = ( 'buffer' if split in ['no', 'tab', 'floating', 'floating_relative_window', 'floating_relative_cursor'] else 'sbuffer') self._vim.command( 'silent keepalt %s %s %s %s' % ( self._get_direction(), vertical, command, bufnr, ) ) else: self._vim.call( 'denite#util#execute_path', f'silent keepalt {command}', bufname) def _get_direction(self) -> str: direction = str(self._context['direction']) if direction == 'dynamictop' or direction == 'dynamicbottom': self._update_displayed_texts() winwidth = self._vim.call('winwidth', 0) is_fit = not [x for x in self._displayed_texts if self._vim.call('strwidth', x) > winwidth] if direction == 'dynamictop': direction = 'aboveleft' if is_fit else 'topleft' else: direction = 'belowright' if is_fit else 'botright' return direction def _get_wininfo(self) -> typing.List[typing.Any]: return [ self._vim.options['columns'], self._vim.options['lines'], self._vim.call('win_getid'), self._vim.call('tabpagebuflist') ] def _switch_prev_buffer(self) -> None: if (self._prev_bufnr == self._bufnr or self._vim.buffers[self._prev_bufnr].name == ''): self._vim.command('enew') else: self._vim.command('buffer ' + str(self._prev_bufnr)) def _init_syntax(self) -> None: self._vim.command('syntax case ignore') self._vim.command('highlight default link deniteInput ModeMsg') self._vim.command('highlight link deniteMatchedRange ' + self._context['highlight_matched_range']) self._vim.command('highlight link deniteMatchedChar ' + self._context['highlight_matched_char']) self._vim.command('highlight default link ' + 'deniteStatusLinePath Comment') self._vim.command('highlight default link ' + 'deniteStatusLineNumber LineNR') self._vim.command('highlight default link ' + 'deniteSelectedLine Statement') if self._floating: self._vim.current.window.options['winhighlight'] = ( 'Normal:' + self._context['highlight_window_background'] ) self._vim.command(('syntax match deniteSelectedLine /^[%s].*/' + ' contains=deniteConcealedMark') % ( self._context['selected_icon'])) self._vim.command(('syntax match deniteConcealedMark /^[ %s]/' + ' conceal contained') % ( self._context['selected_icon'])) if self._denite: self._denite.init_syntax(self._context, self._is_multi) def _update_candidates(self) -> bool: if not self._denite: return False [self._is_async, pattern, statuses, self._entire_len, self._candidates] = self._denite.filter_candidates(self._context) prev_displayed_texts = self._displayed_texts self._update_displayed_texts() prev_matched_pattern = self._matched_pattern self._matched_pattern = pattern prev_statusline_sources = self._statusline_sources self._statusline_sources = ' '.join(statuses) if self._is_async: self._start_timer('update_candidates') else: self._stop_timer('update_candidates') updated = (self._displayed_texts != prev_displayed_texts or self._matched_pattern != prev_matched_pattern or self._statusline_sources != prev_statusline_sources) if updated: self._updated = True self._start_timer('update_buffer') if self._context['search'] and self._context['input']: self._vim.call('setreg', '/', self._context['input']) return self._updated def _update_displayed_texts(self) -> None: candidates_len = len(self._candidates) if not self._is_async and self._context['auto_resize']: winminheight = self._context['winminheight'] max_height = min(self._context['winheight'], self._get_max_height()) if (winminheight != -1 and candidates_len < winminheight): self._winheight = winminheight elif candidates_len > max_height: self._winheight = max_height elif candidates_len != self._winheight: self._winheight = candidates_len max_source_name_len = 0 if self._candidates: max_source_name_len = max([ len(self._get_display_source_name(x['source_name'])) for x in self._candidates]) self._context['max_source_name_len'] = max_source_name_len self._context['max_source_name_format'] = ( '{:<' + str(self._context['max_source_name_len']) + '}') self._displayed_texts = [ self._get_candidate_display_text(i) for i in range(0, candidates_len) ] def _update_buffer(self) -> None: is_current_buffer = self._bufnr == self._vim.current.buffer.number self._update_status() if self._check_matchdelete and self._context['match_highlight']: matches = [x['id'] for x in self._vim.call('getmatches', self._winid)] if self._matched_range_id in matches: self._vim.call('matchdelete', self._matched_range_id, self._winid) self._matched_range_id = -1 if self._matched_char_id in matches: self._vim.call('matchdelete', self._matched_char_id, self._winid) self._matched_char_id = -1 if self._matched_pattern != '': self._matched_range_id = self._vim.call( 'matchadd', 'deniteMatchedRange', r'\c' + regex_convert_py_vim(self._matched_pattern), 10, -1, {'window': self._winid}) matched_char_pattern = '[{}]'.format(re.sub( r'([\[\]\\^-])', r'\\\1', self._context['input'].replace(' ', '') )) self._matched_char_id = self._vim.call( 'matchadd', 'deniteMatchedChar', matched_char_pattern, 10, -1, {'window': self._winid}) prev_linenr = self._vim.call('line', '.') prev_candidate = self._get_cursor_candidate() buffer = self._vim.buffers[self._bufnr] buffer.options['modifiable'] = True self._vim.vars['denite#_candidates'] = [ x['word'] for x in self._candidates] buffer[:] = self._displayed_texts buffer.options['modifiable'] = False self._previous_text = self._context['input'] self._resize_buffer(is_current_buffer) is_changed = (self._context['reversed'] or (is_current_buffer and self._previous_text != self._context['input'])) if self._updated and is_changed: if not is_current_buffer: save_winid = self._vim.call('win_getid') self._vim.call('win_gotoid', self._winid) self._init_cursor() self._move_to_pos(self._cursor) if not is_current_buffer: self._vim.call('win_gotoid', save_winid) elif is_current_buffer: self._vim.call('cursor', [prev_linenr, 0]) if is_current_buffer: if (self._context['auto_action'] and prev_candidate != self._get_cursor_candidate()): self.do_action(self._context['auto_action']) self._updated = False self._stop_timer('update_buffer') def _update_status(self) -> None: inpt = '' if self._context['input']: inpt = self._context['input'] + ' ' if self._context['error_messages']: inpt = '[ERROR] ' + inpt path = '[' + self._context['path'] + ']' status = { 'input': inpt, 'sources': self._statusline_sources, 'path': path, # Extra 'buffer_name': self._context['buffer_name'], 'line_total': len(self._candidates), } if status == self._prev_status: return self._bufvars['denite_statusline'] = status self._prev_status = status linenr = "printf('%'.(len(line('$'))+2).'d/%d',line('.'),line('$'))" if self._context['statusline']: if self._floating or self._filter_floating: self._vim.options['titlestring'] = ( "%{denite#get_status('input')}%* " + "%{denite#get_status('sources')} " + " %{denite#get_status('path')}%*" + "%{" + linenr + "}%*") else: winnr = self._vim.call('win_id2win', self._winid) self._vim.call('setwinvar', winnr, '&statusline', ( "%#deniteInput#%{denite#get_status('input')}%* " + "%{denite#get_status('sources')} %=" + "%#deniteStatusLinePath# %{denite#get_status('path')}%*" + "%#deniteStatusLineNumber#%{" + linenr + "}%*")) def _get_display_source_name(self, name: str) -> str: source_names = self._context['source_names'] if not self._is_multi or source_names == 'hide': source_name = '' else: short_name = (re.sub(r'([a-zA-Z])[a-zA-Z]+', r'\1', name) if re.search(r'[^a-zA-Z]', name) else name[:2]) source_name = short_name if source_names == 'short' else name return source_name def _get_candidate_display_text(self, index: int) -> str: source_names = self._context['source_names'] candidate = self._candidates[index] terms = [] if self._is_multi and source_names != 'hide': terms.append(self._context['max_source_name_format'].format( self._get_display_source_name(candidate['source_name']))) encoding = self._context['encoding'] abbr = candidate.get('abbr', candidate['word']).encode( encoding, errors='replace').decode(encoding, errors='replace') terms.append(abbr[:int(self._context['max_candidate_width'])]) return (str(self._context['selected_icon']) if index in self._selected_candidates else ' ') + ' '.join(terms).replace('\n', '') def _get_max_height(self) -> int: return int(self._vim.options['lines']) if not self._floating else ( int(self._vim.options['lines']) - int(self._context['winrow']) - int(self._vim.options['cmdheight'])) def _resize_buffer(self, is_current_buffer: bool) -> None: split = self._context['split'] if (split == 'no' or split == 'tab' or self._vim.call('winnr', '$') == 1): return winheight = max(self._winheight, 1) winwidth = max(self._winwidth, 1) is_vertical = split == 'vertical' if not is_current_buffer: restore = self._vim.call('win_getid') self._vim.call('win_gotoid', self._winid) if not is_vertical and self._vim.current.window.height != winheight: if self._floating: wincol = self._context['winrow'] row = wincol if split == 'floating': if self._context['auto_resize'] and row > 1: row += self._context['winheight'] row -= self._winheight self._vim.call('nvim_win_set_config', self._winid, { 'relative': 'editor', 'row': row, 'col': self._context['wincol'], 'width': winwidth, 'height': winheight, }) filter_row = 0 if wincol == 1 else row + winheight filter_col = self._context['wincol'] else: init_pos = self._vim.call('nvim_win_get_config', self._winid) self._vim.call('nvim_win_set_config', self._winid, { 'relative': 'win', 'win': init_pos['win'], 'row': init_pos['row'], 'col': init_pos['col'], 'width': winwidth, 'height': winheight, }) filter_col = init_pos['col'] if init_pos['anchor'] == 'NW': winpos = self._vim.call('nvim_win_get_position', self._winid) filter_row = winpos[0] + winheight filter_winid = self._vim.vars['denite#_filter_winid'] self._context['filter_winrow'] = row if self._vim.call('win_id2win', filter_winid) > 0: self._vim.call('nvim_win_set_config', filter_winid, { 'relative': 'editor', 'row': filter_row, 'col': filter_col, }) self._vim.command('resize ' + str(winheight)) if self._context['reversed']: self._vim.command('normal! zb') elif is_vertical and self._vim.current.window.width != winwidth: self._vim.command('vertical resize ' + str(winwidth)) if not is_current_buffer: self._vim.call('win_gotoid', restore) def _check_do_option(self) -> bool: if self._context['do'] != '': self._do_command(self._context['do']) return True elif (self._candidates and self._context['immediately'] or len(self._candidates) == 1 and self._context['immediately_1']): self._do_immediately() return True return not (self._context['empty'] or self._is_async or self._candidates) def _check_move_option(self) -> None: if self._context['cursor_pos'].isnumeric(): self._cursor = int(self._context['cursor_pos']) + 1 elif re.match(r'\+\d+', self._context['cursor_pos']): for _ in range(int(self._context['cursor_pos'][1:])): self._move_to_next_line() elif re.match(r'-\d+', self._context['cursor_pos']): for _ in range(int(self._context['cursor_pos'][1:])): self._move_to_prev_line() elif self._context['cursor_pos'] == '$': self._move_to_last_line() def _do_immediately(self) -> None: goto = self._winid > 0 and self._vim.call( 'win_gotoid', self._winid) if goto: # Jump to denite window self._init_buffer() self.do_action('default') candidate = self._get_cursor_candidate() if not candidate: return echo(self._vim, 'Normal', '[{}/{}] {}'.format( self._cursor, len(self._candidates), candidate.get('abbr', candidate['word']))) if goto: # Move to the previous window self._vim.command('wincmd p') def _do_command(self, command: str) -> None: self._init_cursor() cursor = 1 while cursor < len(self._candidates): self.do_action('default', command) self._move_to_next_line() self._quit_buffer() def _cleanup(self) -> None: self._stop_timer('update_candidates') self._stop_timer('update_buffer') if self._vim.current.buffer.number == self._bufnr: self._cursor = self._vim.call('line', '.') # Note: Close filter window before preview window self._vim.call('denite#filter#_close_filter_window') if not self._context['has_preview_window']: self._vim.command('pclose!') # Clear previewed buffers for bufnr in self._vim.vars['denite#_previewed_buffers'].keys(): if not self._vim.call('win_findbuf', bufnr): self._vim.command('silent bdelete ' + str(bufnr)) self._vim.vars['denite#_previewed_buffers'] = {} self._vim.command('highlight! link CursorLine CursorLine') if self._floating or self._filter_floating: self._vim.options['titlestring'] = self._titlestring self._vim.options['ruler'] = self._ruler def _close_current_window(self) -> None: if self._vim.call('winnr', '$') == 1: self._vim.command('buffer #') else: self._vim.command('close!') def _quit_buffer(self) -> None: self._cleanup() if self._vim.call('bufwinnr', self._bufnr) < 0: # Denite buffer is already closed return winids = self._vim.call('win_findbuf', self._vim.vars['denite#_filter_bufnr']) if winids: # Quit filter buffer self._vim.call('win_gotoid', winids[0]) self._close_current_window() # Move to denite window self._vim.call('win_gotoid', self._winid) # Restore the window if self._context['split'] == 'no': self._switch_prev_buffer() for k, v in self._save_window_options.items(): self._vim.current.window.options[k] = v else: if self._context['split'] == 'tab': self._vim.command('tabclose!') if self._context['split'] != 'tab': self._close_current_window() self._vim.call('win_gotoid', self._prev_winid) # Restore the position self._vim.call('setpos', '.', self._prev_curpos) if self._get_wininfo() and self._get_wininfo() == self._prev_wininfo: # Note: execute restcmd twice to restore layout properly self._vim.command(self._winrestcmd) self._vim.command(self._winrestcmd) clearmatch(self._vim) def _get_cursor_candidate(self) -> Candidate: return self._get_candidate(self._cursor) def _get_candidate(self, pos: int) -> Candidate: if not self._candidates or pos > len(self._candidates): return {} return self._candidates[pos - 1] def _get_selected_candidates(self) -> Candidates: if not self._selected_candidates: return [self._get_cursor_candidate() ] if self._get_cursor_candidate() else [] return [self._candidates[x] for x in self._selected_candidates] def _init_denite(self) -> None: if self._denite: self._denite.start(self._context) self._denite.on_init(self._context) self._initialized = True self._winheight = self._context['winheight'] self._winwidth = self._context['winwidth'] def _gather_candidates(self) -> None: self._selected_candidates = [] if self._denite: self._denite.gather_candidates(self._context) def _init_cursor(self) -> None: if self._context['reversed']: self._move_to_last_line() else: self._move_to_first_line() def _move_to_pos(self, pos: int) -> None: self._vim.call('cursor', pos, 0) self._cursor = pos if self._context['reversed']: self._vim.command('normal! zb') def _move_to_next_line(self) -> None: if self._cursor < len(self._candidates): self._cursor += 1 def _move_to_prev_line(self) -> None: if self._cursor >= 1: self._cursor -= 1 def _move_to_first_line(self) -> None: self._cursor = 1 def _move_to_last_line(self) -> None: self._cursor = len(self._candidates) def _start_timer(self, key: str) -> None: if key in self._timers: return if key == 'update_candidates': self._timers[key] = self._vim.call( 'denite#helper#_start_update_candidates_timer', self._bufnr) elif key == 'update_buffer': self._timers[key] = self._vim.call( 'denite#helper#_start_update_buffer_timer', self._bufnr) def _stop_timer(self, key: str) -> None: if key not in self._timers: return self._vim.call('timer_stop', self._timers[key]) # Note: After timer_stop is called, self._timers may be removed if key in self._timers: self._timers.pop(key) def _split_floating(self, split: str) -> None: # Use floating window if split == 'floating': self._vim.call( 'nvim_open_win', self._vim.call('bufnr', '%'), True, { 'relative': 'editor', 'row': self._context['winrow'], 'col': self._context['wincol'], 'width': self._context['winwidth'], 'height': self._context['winheight'], }) elif split == 'floating_relative_cursor': opened_pos = (self._vim.call('nvim_win_get_position', 0)[0] + self._vim.call('winline') - 1) if self._context['auto_resize']: height = max(self._winheight, 1) width = max(self._winwidth, 1) else: width = self._context['winwidth'] height = self._context['winheight'] if opened_pos + height + 3 > self._vim.options['lines']: anchor = 'SW' row = 0 self._context['filter_winrow'] = row + opened_pos else: anchor = 'NW' row = 1 self._context['filter_winrow'] = row + height + opened_pos self._vim.call( 'nvim_open_win', self._vim.call('bufnr', '%'), True, { 'relative': 'cursor', 'row': row, 'col': 0, 'width': width, 'height': height, 'anchor': anchor, }) elif split == 'floating_relative_window': self._vim.call( 'nvim_open_win', self._vim.call('bufnr', '%'), True, { 'relative': 'win', 'row': self._context['winrow'], 'col': self._context['wincol'], 'width': self._context['winwidth'], 'height': self._context['winheight'], })
en
0.465682
# ============================================================================ # FILE: default.py # AUTHOR: <NAME> <<EMAIL> at g<EMAIL>> # License: MIT license # ============================================================================ #util#check_matchdelete')) # if hasattr(self._vim, 'run_coroutine'): # self._denite = ASyncParent(self._vim) # else: # Re-open denite buffer # Restore the cursor # Disable quit flag # Ignore command line window. # Skip the initialization # Ignore empty sources. #_previewed_buffers'] = {} # Note: Have to use setlocal instead of "current.window.options" # "current.window.options" changes global value instead of local in # neovim. # Disable ruler # In Vim8, FileType autocmd is not fired after set filetype option. #call_map("auto_action")') # Move the window to bottom #util#execute_path', #_candidates'] = [ # Extra #get_status('input')}%* " + #get_status('sources')} " + #get_status('path')}%*" + #deniteInput#%{denite#get_status('input')}%* " + #get_status('sources')} %=" + #deniteStatusLinePath# %{denite#get_status('path')}%*" + #deniteStatusLineNumber#%{" + linenr + "}%*")) #_filter_winid'] # Jump to denite window # Move to the previous window # Note: Close filter window before preview window #filter#_close_filter_window') # Clear previewed buffers #_previewed_buffers'].keys(): #_previewed_buffers'] = {} #') # Denite buffer is already closed #_filter_bufnr']) # Quit filter buffer # Move to denite window # Restore the window # Restore the position # Note: execute restcmd twice to restore layout properly #helper#_start_update_candidates_timer', self._bufnr) #helper#_start_update_buffer_timer', self._bufnr) # Note: After timer_stop is called, self._timers may be removed # Use floating window
1.901279
2
PyDSTool/core/context_managers.py
yuanz271/PyDSTool
0
5
<filename>PyDSTool/core/context_managers.py # -*- coding: utf-8 -*- """Context managers implemented for (mostly) internal use""" import contextlib import functools from io import UnsupportedOperation import os import sys __all__ = ["RedirectStdout", "RedirectStderr"] @contextlib.contextmanager def _stdchannel_redirected(stdchannel, dest_filename, mode="w"): """ A context manager to temporarily redirect stdout or stderr Originally by <NAME>, 2013 (http://marc-abramowitz.com/archives/2013/07/19/python-context-manager-for-redirected-stdout-and-stderr/) """ oldstdchannel = None dest_file = None try: if stdchannel is None: yield iter([None]) else: oldstdchannel = os.dup(stdchannel.fileno()) dest_file = open(dest_filename, mode) os.dup2(dest_file.fileno(), stdchannel.fileno()) yield except (UnsupportedOperation, AttributeError): yield iter([None]) finally: if oldstdchannel is not None: os.dup2(oldstdchannel, stdchannel.fileno()) if dest_file is not None: dest_file.close() RedirectStdout = functools.partial(_stdchannel_redirected, sys.stdout) RedirectStderr = functools.partial(_stdchannel_redirected, sys.stderr) RedirectNoOp = functools.partial(_stdchannel_redirected, None, "")
<filename>PyDSTool/core/context_managers.py # -*- coding: utf-8 -*- """Context managers implemented for (mostly) internal use""" import contextlib import functools from io import UnsupportedOperation import os import sys __all__ = ["RedirectStdout", "RedirectStderr"] @contextlib.contextmanager def _stdchannel_redirected(stdchannel, dest_filename, mode="w"): """ A context manager to temporarily redirect stdout or stderr Originally by <NAME>, 2013 (http://marc-abramowitz.com/archives/2013/07/19/python-context-manager-for-redirected-stdout-and-stderr/) """ oldstdchannel = None dest_file = None try: if stdchannel is None: yield iter([None]) else: oldstdchannel = os.dup(stdchannel.fileno()) dest_file = open(dest_filename, mode) os.dup2(dest_file.fileno(), stdchannel.fileno()) yield except (UnsupportedOperation, AttributeError): yield iter([None]) finally: if oldstdchannel is not None: os.dup2(oldstdchannel, stdchannel.fileno()) if dest_file is not None: dest_file.close() RedirectStdout = functools.partial(_stdchannel_redirected, sys.stdout) RedirectStderr = functools.partial(_stdchannel_redirected, sys.stderr) RedirectNoOp = functools.partial(_stdchannel_redirected, None, "")
en
0.715551
# -*- coding: utf-8 -*- Context managers implemented for (mostly) internal use A context manager to temporarily redirect stdout or stderr Originally by <NAME>, 2013 (http://marc-abramowitz.com/archives/2013/07/19/python-context-manager-for-redirected-stdout-and-stderr/)
2.358697
2
pos_kiosk/hooks.py
Muzzy73/pos_kiosk
1
6
# -*- coding: utf-8 -*- from __future__ import unicode_literals from . import __version__ as app_version app_name = "pos_kiosk" app_title = "Pos Kiosk" app_publisher = "9t9it" app_description = "Kiosk App" app_icon = "octicon octicon-file-directory" app_color = "grey" app_email = "<EMAIL>" app_license = "MIT" # Includes in <head> # ------------------ # include js, css files in header of desk.html # app_include_css = "/assets/pos_kiosk/css/pos_kiosk.css" # app_include_js = "/assets/pos_kiosk/js/pos_kiosk.js" # include js, css files in header of web template # web_include_css = "/assets/pos_kiosk/css/pos_kiosk.css" # web_include_js = "/assets/pos_kiosk/js/pos_kiosk.js" # include js in page # page_js = {"page" : "public/js/file.js"} # page_js = { # "kiosk": ["public/js/pos_page_js.js", "public/js/includes/number_to_words.js"] # } # include js in doctype views # doctype_js = {"doctype" : "public/js/doctype.js"} # doctype_list_js = {"doctype" : "public/js/doctype_list.js"} # doctype_tree_js = {"doctype" : "public/js/doctype_tree.js"} # doctype_calendar_js = {"doctype" : "public/js/doctype_calendar.js"} fixtures = [ { "doctype": "Custom Field", "filters": [ [ "name", "in", [ "Sales Invoice Item-pos_kiosk", "Mode of Payment-logo" ] ] ] } ] # Home Pages # ---------- # application home page (will override Website Settings) # home_page = "login" # website user home page (by Role) # role_home_page = { # "Role": "home_page" # } # Website user home page (by function) # get_website_user_home_page = "pos_kiosk.utils.get_home_page" # Generators # ---------- # automatically create page for each record of this doctype # website_generators = ["Web Page"] # Installation # ------------ # before_install = "pos_kiosk.install.before_install" # after_install = "pos_kiosk.install.after_install" # Desk Notifications # ------------------ # See frappe.core.notifications.get_notification_config # notification_config = "pos_kiosk.notifications.get_notification_config" # Permissions # ----------- # Permissions evaluated in scripted ways # permission_query_conditions = { # "Event": "frappe.desk.doctype.event.event.get_permission_query_conditions", # } # # has_permission = { # "Event": "frappe.desk.doctype.event.event.has_permission", # } # Document Events # --------------- # Hook on document methods and events # doc_events = { # "*": { # "on_update": "method", # "on_cancel": "method", # "on_trash": "method" # } # } # Scheduled Tasks # --------------- # scheduler_events = { # "all": [ # "pos_kiosk.tasks.all" # ], # "daily": [ # "pos_kiosk.tasks.daily" # ], # "hourly": [ # "pos_kiosk.tasks.hourly" # ], # "weekly": [ # "pos_kiosk.tasks.weekly" # ] # "monthly": [ # "pos_kiosk.tasks.monthly" # ] # } # Testing # ------- # before_tests = "pos_kiosk.install.before_tests" # Overriding Whitelisted Methods # ------------------------------ # # override_whitelisted_methods = { # "pos_bahrain.api.get_item_details.get_item_details": "pos_kiosk.api.item.get_item_details" # noqa # }
# -*- coding: utf-8 -*- from __future__ import unicode_literals from . import __version__ as app_version app_name = "pos_kiosk" app_title = "Pos Kiosk" app_publisher = "9t9it" app_description = "Kiosk App" app_icon = "octicon octicon-file-directory" app_color = "grey" app_email = "<EMAIL>" app_license = "MIT" # Includes in <head> # ------------------ # include js, css files in header of desk.html # app_include_css = "/assets/pos_kiosk/css/pos_kiosk.css" # app_include_js = "/assets/pos_kiosk/js/pos_kiosk.js" # include js, css files in header of web template # web_include_css = "/assets/pos_kiosk/css/pos_kiosk.css" # web_include_js = "/assets/pos_kiosk/js/pos_kiosk.js" # include js in page # page_js = {"page" : "public/js/file.js"} # page_js = { # "kiosk": ["public/js/pos_page_js.js", "public/js/includes/number_to_words.js"] # } # include js in doctype views # doctype_js = {"doctype" : "public/js/doctype.js"} # doctype_list_js = {"doctype" : "public/js/doctype_list.js"} # doctype_tree_js = {"doctype" : "public/js/doctype_tree.js"} # doctype_calendar_js = {"doctype" : "public/js/doctype_calendar.js"} fixtures = [ { "doctype": "Custom Field", "filters": [ [ "name", "in", [ "Sales Invoice Item-pos_kiosk", "Mode of Payment-logo" ] ] ] } ] # Home Pages # ---------- # application home page (will override Website Settings) # home_page = "login" # website user home page (by Role) # role_home_page = { # "Role": "home_page" # } # Website user home page (by function) # get_website_user_home_page = "pos_kiosk.utils.get_home_page" # Generators # ---------- # automatically create page for each record of this doctype # website_generators = ["Web Page"] # Installation # ------------ # before_install = "pos_kiosk.install.before_install" # after_install = "pos_kiosk.install.after_install" # Desk Notifications # ------------------ # See frappe.core.notifications.get_notification_config # notification_config = "pos_kiosk.notifications.get_notification_config" # Permissions # ----------- # Permissions evaluated in scripted ways # permission_query_conditions = { # "Event": "frappe.desk.doctype.event.event.get_permission_query_conditions", # } # # has_permission = { # "Event": "frappe.desk.doctype.event.event.has_permission", # } # Document Events # --------------- # Hook on document methods and events # doc_events = { # "*": { # "on_update": "method", # "on_cancel": "method", # "on_trash": "method" # } # } # Scheduled Tasks # --------------- # scheduler_events = { # "all": [ # "pos_kiosk.tasks.all" # ], # "daily": [ # "pos_kiosk.tasks.daily" # ], # "hourly": [ # "pos_kiosk.tasks.hourly" # ], # "weekly": [ # "pos_kiosk.tasks.weekly" # ] # "monthly": [ # "pos_kiosk.tasks.monthly" # ] # } # Testing # ------- # before_tests = "pos_kiosk.install.before_tests" # Overriding Whitelisted Methods # ------------------------------ # # override_whitelisted_methods = { # "pos_bahrain.api.get_item_details.get_item_details": "pos_kiosk.api.item.get_item_details" # noqa # }
en
0.525243
# -*- coding: utf-8 -*- # Includes in <head> # ------------------ # include js, css files in header of desk.html # app_include_css = "/assets/pos_kiosk/css/pos_kiosk.css" # app_include_js = "/assets/pos_kiosk/js/pos_kiosk.js" # include js, css files in header of web template # web_include_css = "/assets/pos_kiosk/css/pos_kiosk.css" # web_include_js = "/assets/pos_kiosk/js/pos_kiosk.js" # include js in page # page_js = {"page" : "public/js/file.js"} # page_js = { # "kiosk": ["public/js/pos_page_js.js", "public/js/includes/number_to_words.js"] # } # include js in doctype views # doctype_js = {"doctype" : "public/js/doctype.js"} # doctype_list_js = {"doctype" : "public/js/doctype_list.js"} # doctype_tree_js = {"doctype" : "public/js/doctype_tree.js"} # doctype_calendar_js = {"doctype" : "public/js/doctype_calendar.js"} # Home Pages # ---------- # application home page (will override Website Settings) # home_page = "login" # website user home page (by Role) # role_home_page = { # "Role": "home_page" # } # Website user home page (by function) # get_website_user_home_page = "pos_kiosk.utils.get_home_page" # Generators # ---------- # automatically create page for each record of this doctype # website_generators = ["Web Page"] # Installation # ------------ # before_install = "pos_kiosk.install.before_install" # after_install = "pos_kiosk.install.after_install" # Desk Notifications # ------------------ # See frappe.core.notifications.get_notification_config # notification_config = "pos_kiosk.notifications.get_notification_config" # Permissions # ----------- # Permissions evaluated in scripted ways # permission_query_conditions = { # "Event": "frappe.desk.doctype.event.event.get_permission_query_conditions", # } # # has_permission = { # "Event": "frappe.desk.doctype.event.event.has_permission", # } # Document Events # --------------- # Hook on document methods and events # doc_events = { # "*": { # "on_update": "method", # "on_cancel": "method", # "on_trash": "method" # } # } # Scheduled Tasks # --------------- # scheduler_events = { # "all": [ # "pos_kiosk.tasks.all" # ], # "daily": [ # "pos_kiosk.tasks.daily" # ], # "hourly": [ # "pos_kiosk.tasks.hourly" # ], # "weekly": [ # "pos_kiosk.tasks.weekly" # ] # "monthly": [ # "pos_kiosk.tasks.monthly" # ] # } # Testing # ------- # before_tests = "pos_kiosk.install.before_tests" # Overriding Whitelisted Methods # ------------------------------ # # override_whitelisted_methods = { # "pos_bahrain.api.get_item_details.get_item_details": "pos_kiosk.api.item.get_item_details" # noqa # }
1.404778
1
pypagai/models/model_lstm.py
gcouti/pypagAI
1
7
<gh_stars>1-10 from keras import Model, Input from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten from keras.optimizers import Adam from pypagai.models.base import KerasModel class SimpleLSTM(KerasModel): """ Use a simple lstm neural network """ @staticmethod def default_config(): config = KerasModel.default_config() config['hidden'] = 32 return config def __init__(self, cfg): super().__init__(cfg) self._cfg_ = cfg def _create_network_(self): hidden = self._cfg_['hidden'] story = Input((self._story_maxlen, ), name='story') question = Input((self._query_maxlen, ), name='question') conc = concatenate([story, question],) conc = Reshape((1, int(conc.shape[1])))(conc) conc = Permute((2, 1))(conc) response = LSTM(hidden, dropout=0.2, recurrent_dropout=0.2)(conc) response = Dense(self._vocab_size, activation='softmax')(response) self._model = Model(inputs=[story, question], outputs=response) self._model.compile(optimizer=Adam(lr=2e-4), loss='sparse_categorical_crossentropy', metrics=['accuracy']) class EmbedLSTM(KerasModel): """ Use a simple lstm neural network """ @staticmethod def default_config(): config = KerasModel.default_config() config['hidden'] = 32 return config def __init__(self, cfg): super().__init__(cfg) self._cfg_ = cfg def _create_network_(self): hidden = self._cfg_['hidden'] story = Input((self._story_maxlen, ), name='story') question = Input((self._query_maxlen, ), name='question') eb_story = Embedding(self._vocab_size, 64)(story) eb_story = Dropout(0.3)(eb_story) eb_question = Embedding(self._vocab_size, 64)(question) eb_question = Dropout(0.3)(eb_question) conc = concatenate([eb_story, eb_question], axis=1) response = LSTM(hidden, dropout=0.2, recurrent_dropout=0.2)(conc) response = Dense(self._vocab_size, activation='softmax')(response) self._model = Model(inputs=[story, question], outputs=response) self._model.compile(optimizer=Adam(lr=2e-4), loss='sparse_categorical_crossentropy', metrics=['accuracy']) class ConvLSTM(KerasModel): """ Use a simple lstm neural network """ @staticmethod def default_config(): config = KerasModel.default_config() config['hidden'] = 32 return config def __init__(self, model_cfg): super().__init__(model_cfg) self._cfg = model_cfg def _create_network_(self): hidden = self._cfg['hidden'] story = Input((self._story_maxlen, ), name='story') question = Input((self._query_maxlen, ), name='question') eb_story = Embedding(self._vocab_size, 64)(story) eb_story = Convolution1D(64, 3, padding='same')(eb_story) eb_story = Convolution1D(32, 3, padding='same')(eb_story) eb_story = Convolution1D(16, 3, padding='same')(eb_story) # eb_story = Flatten()(eb_story) eb_question = Embedding(self._vocab_size, 64)(question) eb_question = Convolution1D(64, 3, padding='same')(eb_question) eb_question = Convolution1D(32, 3, padding='same')(eb_question) eb_question = Convolution1D(16, 3, padding='same')(eb_question) # eb_question = Flatten()(eb_question) conc = concatenate([eb_story, eb_question], axis=1) response = LSTM(hidden, dropout=0.2, recurrent_dropout=0.2)(conc) response = Dense(self._vocab_size, activation='softmax')(response) self._model = Model(inputs=[story, question], outputs=response) self._model.compile(optimizer=Adam(lr=2e-4), loss='sparse_categorical_crossentropy', metrics=['accuracy'])
from keras import Model, Input from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten from keras.optimizers import Adam from pypagai.models.base import KerasModel class SimpleLSTM(KerasModel): """ Use a simple lstm neural network """ @staticmethod def default_config(): config = KerasModel.default_config() config['hidden'] = 32 return config def __init__(self, cfg): super().__init__(cfg) self._cfg_ = cfg def _create_network_(self): hidden = self._cfg_['hidden'] story = Input((self._story_maxlen, ), name='story') question = Input((self._query_maxlen, ), name='question') conc = concatenate([story, question],) conc = Reshape((1, int(conc.shape[1])))(conc) conc = Permute((2, 1))(conc) response = LSTM(hidden, dropout=0.2, recurrent_dropout=0.2)(conc) response = Dense(self._vocab_size, activation='softmax')(response) self._model = Model(inputs=[story, question], outputs=response) self._model.compile(optimizer=Adam(lr=2e-4), loss='sparse_categorical_crossentropy', metrics=['accuracy']) class EmbedLSTM(KerasModel): """ Use a simple lstm neural network """ @staticmethod def default_config(): config = KerasModel.default_config() config['hidden'] = 32 return config def __init__(self, cfg): super().__init__(cfg) self._cfg_ = cfg def _create_network_(self): hidden = self._cfg_['hidden'] story = Input((self._story_maxlen, ), name='story') question = Input((self._query_maxlen, ), name='question') eb_story = Embedding(self._vocab_size, 64)(story) eb_story = Dropout(0.3)(eb_story) eb_question = Embedding(self._vocab_size, 64)(question) eb_question = Dropout(0.3)(eb_question) conc = concatenate([eb_story, eb_question], axis=1) response = LSTM(hidden, dropout=0.2, recurrent_dropout=0.2)(conc) response = Dense(self._vocab_size, activation='softmax')(response) self._model = Model(inputs=[story, question], outputs=response) self._model.compile(optimizer=Adam(lr=2e-4), loss='sparse_categorical_crossentropy', metrics=['accuracy']) class ConvLSTM(KerasModel): """ Use a simple lstm neural network """ @staticmethod def default_config(): config = KerasModel.default_config() config['hidden'] = 32 return config def __init__(self, model_cfg): super().__init__(model_cfg) self._cfg = model_cfg def _create_network_(self): hidden = self._cfg['hidden'] story = Input((self._story_maxlen, ), name='story') question = Input((self._query_maxlen, ), name='question') eb_story = Embedding(self._vocab_size, 64)(story) eb_story = Convolution1D(64, 3, padding='same')(eb_story) eb_story = Convolution1D(32, 3, padding='same')(eb_story) eb_story = Convolution1D(16, 3, padding='same')(eb_story) # eb_story = Flatten()(eb_story) eb_question = Embedding(self._vocab_size, 64)(question) eb_question = Convolution1D(64, 3, padding='same')(eb_question) eb_question = Convolution1D(32, 3, padding='same')(eb_question) eb_question = Convolution1D(16, 3, padding='same')(eb_question) # eb_question = Flatten()(eb_question) conc = concatenate([eb_story, eb_question], axis=1) response = LSTM(hidden, dropout=0.2, recurrent_dropout=0.2)(conc) response = Dense(self._vocab_size, activation='softmax')(response) self._model = Model(inputs=[story, question], outputs=response) self._model.compile(optimizer=Adam(lr=2e-4), loss='sparse_categorical_crossentropy', metrics=['accuracy'])
en
0.751499
Use a simple lstm neural network Use a simple lstm neural network Use a simple lstm neural network # eb_story = Flatten()(eb_story) # eb_question = Flatten()(eb_question)
2.97849
3
lib/variables/latent_variables/__init__.py
joelouismarino/variational_rl
15
8
<filename>lib/variables/latent_variables/__init__.py from .fully_connected import FullyConnectedLatentVariable from .convolutional import ConvolutionalLatentVariable
<filename>lib/variables/latent_variables/__init__.py from .fully_connected import FullyConnectedLatentVariable from .convolutional import ConvolutionalLatentVariable
none
1
1.085513
1
easyai/model/backbone/cls/pnasnet.py
lpj0822/image_point_cloud_det
1
9
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: ''' PNASNet in PyTorch. Paper: Progressive Neural Architecture Search ''' from easyai.base_name.block_name import NormalizationType, ActivationType from easyai.base_name.backbone_name import BackboneName from easyai.model.backbone.utility.base_backbone import * from easyai.model.base_block.utility.utility_block import ConvBNActivationBlock from easyai.model.base_block.cls.pnasnet_block import CellA, CellB __all__ = ['pnasnet_A', 'pnasnet_B'] class PNASNet(BaseBackbone): def __init__(self, data_channel=3, num_cells=6, num_planes=44, block=CellA, bnName=NormalizationType.BatchNormalize2d, activationName=ActivationType.ReLU): super().__init__() self.set_name(BackboneName.PNASNetA) self.data_channel = data_channel self.num_cells = num_cells self.block = block self.activation_name = activationName self.bn_name = bnName self.first_output = num_planes self.in_planes = self.first_output self.create_block_list() def create_block_list(self): self.block_out_channels = [] self.index = 0 layer1 = ConvBNActivationBlock(in_channels=self.data_channel, out_channels=self.first_output, kernel_size=3, stride=1, padding=1, bias=False, bnName=self.bn_name, activationName=self.activation_name) self.add_block_list(layer1.get_name(), layer1, self.first_output) self.make_layer(self.first_output, self.num_cells) self.downsample(self.first_output * 2) self.make_layer(self.first_output * 2, self.num_cells) self.downsample(self.first_output * 4) self.make_layer(self.first_output * 4, self.num_cells) def make_layer(self, planes, num_cells): for _ in range(num_cells): temp_block = self.block(self.in_planes, planes, stride=1, bn_name=self.bn_name, activation_name=self.activation_name) self.add_block_list(temp_block.get_name(), temp_block, planes) self.in_planes = planes def downsample(self, planes): down_block = self.block(self.in_planes, planes, stride=2, bn_name=self.bn_name, activation_name=self.activation_name) self.add_block_list(down_block.get_name(), down_block, planes) self.in_planes = planes def forward(self, x): output_list = [] for block in self._modules.values(): x = block(x) output_list.append(x) return output_list def pnasnet_A(data_channel): model = PNASNet(data_channel=data_channel, num_cells=6, num_planes=44, block=CellA) model.set_name(BackboneName.PNASNetA) return model def pnasnet_B(data_channel): model = PNASNet(data_channel=data_channel, num_cells=6, num_planes=32, block=CellB) model.set_name(BackboneName.PNASNetB) return model
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: ''' PNASNet in PyTorch. Paper: Progressive Neural Architecture Search ''' from easyai.base_name.block_name import NormalizationType, ActivationType from easyai.base_name.backbone_name import BackboneName from easyai.model.backbone.utility.base_backbone import * from easyai.model.base_block.utility.utility_block import ConvBNActivationBlock from easyai.model.base_block.cls.pnasnet_block import CellA, CellB __all__ = ['pnasnet_A', 'pnasnet_B'] class PNASNet(BaseBackbone): def __init__(self, data_channel=3, num_cells=6, num_planes=44, block=CellA, bnName=NormalizationType.BatchNormalize2d, activationName=ActivationType.ReLU): super().__init__() self.set_name(BackboneName.PNASNetA) self.data_channel = data_channel self.num_cells = num_cells self.block = block self.activation_name = activationName self.bn_name = bnName self.first_output = num_planes self.in_planes = self.first_output self.create_block_list() def create_block_list(self): self.block_out_channels = [] self.index = 0 layer1 = ConvBNActivationBlock(in_channels=self.data_channel, out_channels=self.first_output, kernel_size=3, stride=1, padding=1, bias=False, bnName=self.bn_name, activationName=self.activation_name) self.add_block_list(layer1.get_name(), layer1, self.first_output) self.make_layer(self.first_output, self.num_cells) self.downsample(self.first_output * 2) self.make_layer(self.first_output * 2, self.num_cells) self.downsample(self.first_output * 4) self.make_layer(self.first_output * 4, self.num_cells) def make_layer(self, planes, num_cells): for _ in range(num_cells): temp_block = self.block(self.in_planes, planes, stride=1, bn_name=self.bn_name, activation_name=self.activation_name) self.add_block_list(temp_block.get_name(), temp_block, planes) self.in_planes = planes def downsample(self, planes): down_block = self.block(self.in_planes, planes, stride=2, bn_name=self.bn_name, activation_name=self.activation_name) self.add_block_list(down_block.get_name(), down_block, planes) self.in_planes = planes def forward(self, x): output_list = [] for block in self._modules.values(): x = block(x) output_list.append(x) return output_list def pnasnet_A(data_channel): model = PNASNet(data_channel=data_channel, num_cells=6, num_planes=44, block=CellA) model.set_name(BackboneName.PNASNetA) return model def pnasnet_B(data_channel): model = PNASNet(data_channel=data_channel, num_cells=6, num_planes=32, block=CellB) model.set_name(BackboneName.PNASNetB) return model
en
0.536206
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: PNASNet in PyTorch. Paper: Progressive Neural Architecture Search
2.712146
3
map_download/cmd/TerrainDownloader.py
cugxy/map_download
27
10
# -*- coding: utf-8 -*- # coding=utf-8 import json import os import math import logging import requests import time from map_download.cmd.BaseDownloader import DownloadEngine, BaseDownloaderThread, latlng2tile_terrain, BoundBox def get_access_token(token): resp = None request_count = 0 url = "https://api.cesium.com/v1/assets/1/endpoint" while True: if request_count > 4: break try: request_count += 1 param = {'access_token': token} resp = requests.get(url, params=param, timeout=2) if resp.status_code != 200: continue break except Exception as e: resp = None time.sleep(3) if resp is None: return None resp_json = resp.json() return resp_json.get('accessToken') class TerrainDownloaderThread(BaseDownloaderThread): URL = "https://assets.cesium.com/1/{z}/{x}/{y}.terrain?extensions=octvertexnormals-watermask&v=1.1.0" def __init__(self, root_dir, bbox, token, task_q, logger=None, write_db=False): super(TerrainDownloaderThread, self).__init__( root_dir, bbox, task_q, logger, write_db=write_db, db_file_name='Terrain.db') self.token = token self._init_metadata( format='terrain', bounds='%f,%f,%f,%f' % (self.bbox.min_lng, self.bbox.min_lat, self.bbox.max_lng, self.bbox.max_lat)) def get_url(self, x, y, z): return self.URL.format(x=x, y=y, z=z) def _download(self, x, y, z): file_path = '%s/%s/%i/%i/%i.%s' % (self.root_dir, 'Terrain', z, x, y, 'terrain') if os.path.exists(file_path): self._data2DB(x, y, z, file_path) return 0 os.makedirs(os.path.dirname(file_path), exist_ok=True) resp = None requre_count = 0 _url = '' access_token = get_access_token(self.token) if access_token is None: return -1 param = {'extensions': 'octvertexnormals-watermask', 'v': '1.1.0', 'access_token': access_token} while True: if requre_count > 4: break try: _url = self.get_url(x, y, z) resp = requests.get(_url, params=param, stream=True, timeout=2) break except Exception as e: resp = None time.sleep(3) requre_count += 1 if resp is None: return -1 if resp.status_code != 200: return -1 try: with open(file_path, 'wb') as f: for chunk in resp.iter_content(chunk_size=1024): if chunk: f.write(chunk) except Exception as e: return -1 self._data2DB(x, y, z, file_path) return 1 class TerrainDownloadEngine(DownloadEngine): root_dir = '' def __init__(self, root_dir, bbox, token, thread_num, logger=None, write_db=False): super(TerrainDownloadEngine, self).__init__(bbox, thread_num, logger, write_db=write_db) self.root_dir = root_dir self.token = token def bbox2xyz(self, bbox, z): min_x, min_y = latlng2tile_terrain(bbox.min_lat, bbox.min_lng, z) max_x, max_y = latlng2tile_terrain(bbox.max_lat, bbox.max_lng, z) return math.floor(min_x), math.floor(min_y), math.ceil(max_x) + 1, math.ceil(max_y) + 1 def generate_metadata(self): try: metadatas = { "attribution": "© Analytical Graphics Inc., © CGIAR-CSI, Produced using Copernicus data and " "information funded by the European Union - EU-DEM layers", "available": [ [ { "endX": 1, "endY": 0, "startX": 0, "startY": 0 } ], [ { "endX": 3, "endY": 1, "startX": 0, "startY": 0 } ], [ { "endX": 7, "endY": 3, "startX": 0, "startY": 0 } ], [ { "endX": 15, "endY": 7, "startX": 0, "startY": 0 } ], [ { "endX": 31, "endY": 15, "startX": 0, "startY": 0 } ], [ { "endX": 63, "endY": 31, "startX": 0, "startY": 0 } ], [ { "endX": 127, "endY": 63, "startX": 0, "startY": 0 } ], [ { "endX": 255, "endY": 127, "startX": 0, "startY": 0 } ], [ { "endX": 511, "endY": 255, "startX": 0, "startY": 0 } ], [ { "endX": 1023, "endY": 511, "startX": 0, "startY": 0 } ], [ { "endX": 2047, "endY": 1023, "startX": 0, "startY": 0 } ], [ { "endX": 4095, "endY": 2047, "startX": 0, "startY": 0 } ], [ { "endX": 8191, "endY": 4095, "startX": 0, "startY": 0 } ], [ { "endX": 16383, "endY": 8191, "startX": 0, "startY": 0 } ], [ { "endX": 32767, "endY": 16383, "startX": 0, "startY": 0 } ] ], "bounds": [-180, -90, 180, 90, ], "description": "STK World Terrain Premium Tileset, v1.3. 10m - 30m resolution CONUS, 30m resolution " "SRTM between 60N and 60S, 30m Europe. Minimum global coverage of 1000m.", "extensions": ["watermask", "vertexnormals", "octvertexnormals", ], "format": "quantized-mesh-1.0", "maxzoom": 13, "minzoom": 0, "name": "world", "projection": "EPSG:4326", "scheme": "tms", "tilejson": "2.1.0", "tiles": ["{z}/{x}/{y}.terrain?v={version}", ], "version": "1.31376.0" } _dir = os.path.join(self.root_dir, 'Terrain') os.makedirs(_dir, exist_ok=True) metadatas_path = os.path.join(_dir, 'layer.json') with open(metadatas_path, 'w') as f: json.dump(metadatas, f) except Exception as e: if self.logger is not None: self.logger.exception(e) def run(self): try: self.generate_metadata() count = 0 bboxs = self.cut_bbox() for bbox in bboxs: _count = self.get_task_count(bbox) count += _count self.division_done_signal.emit(count) for bbox in bboxs: while True: if not self.running: time.sleep(0.01) else: break task_q = self.get_task_queue(bbox) self.threads = [] for i in range(self.thread_num): thread = TerrainDownloaderThread(self.root_dir, self.bbox, self.token, task_q, self.logger, write_db=self.write_db) thread.sub_progressBar_updated_signal.connect(self.sub_update_progressBar) self.threads.append(thread) for thread in self.threads: thread.start() for thread in self.threads: thread.wait() for t in self.threads: t.stop() t.quit() self.threads = [] self.download_done_signal.emit() except Exception as e: if self.logger is not None: self.logger.error(e) if __name__ == '__main__': if 1: logger = logging.getLogger('down') try: root = r'/Users/cugxy/Documents/data/downloader' formatter = logging.Formatter('%(levelname)s-%(message)s') hdlr = logging.StreamHandler() log_file = os.path.join(root, 'down.log') file_hdlr = logging.FileHandler(log_file) file_hdlr.setFormatter(formatter) logger.addHandler(file_hdlr) logger.addHandler(hdlr) logger.setLevel(logging.INFO) min_lng = -180.0 max_lng = 180.0 min_lat = -90.0 max_lat = 90.0 start_zoom = 0 end_zoom = 5 bbox = BoundBox(max_lat, max_lng, min_lat, min_lng, start_zoom, end_zoom) d = TerrainDownloadEngine(root, bbox, 8, logger) d.start() time.sleep(10000) logger.error('main thread out') except Exception as e: logger.error(e) if 0: accessToken = get_access_token() pass
# -*- coding: utf-8 -*- # coding=utf-8 import json import os import math import logging import requests import time from map_download.cmd.BaseDownloader import DownloadEngine, BaseDownloaderThread, latlng2tile_terrain, BoundBox def get_access_token(token): resp = None request_count = 0 url = "https://api.cesium.com/v1/assets/1/endpoint" while True: if request_count > 4: break try: request_count += 1 param = {'access_token': token} resp = requests.get(url, params=param, timeout=2) if resp.status_code != 200: continue break except Exception as e: resp = None time.sleep(3) if resp is None: return None resp_json = resp.json() return resp_json.get('accessToken') class TerrainDownloaderThread(BaseDownloaderThread): URL = "https://assets.cesium.com/1/{z}/{x}/{y}.terrain?extensions=octvertexnormals-watermask&v=1.1.0" def __init__(self, root_dir, bbox, token, task_q, logger=None, write_db=False): super(TerrainDownloaderThread, self).__init__( root_dir, bbox, task_q, logger, write_db=write_db, db_file_name='Terrain.db') self.token = token self._init_metadata( format='terrain', bounds='%f,%f,%f,%f' % (self.bbox.min_lng, self.bbox.min_lat, self.bbox.max_lng, self.bbox.max_lat)) def get_url(self, x, y, z): return self.URL.format(x=x, y=y, z=z) def _download(self, x, y, z): file_path = '%s/%s/%i/%i/%i.%s' % (self.root_dir, 'Terrain', z, x, y, 'terrain') if os.path.exists(file_path): self._data2DB(x, y, z, file_path) return 0 os.makedirs(os.path.dirname(file_path), exist_ok=True) resp = None requre_count = 0 _url = '' access_token = get_access_token(self.token) if access_token is None: return -1 param = {'extensions': 'octvertexnormals-watermask', 'v': '1.1.0', 'access_token': access_token} while True: if requre_count > 4: break try: _url = self.get_url(x, y, z) resp = requests.get(_url, params=param, stream=True, timeout=2) break except Exception as e: resp = None time.sleep(3) requre_count += 1 if resp is None: return -1 if resp.status_code != 200: return -1 try: with open(file_path, 'wb') as f: for chunk in resp.iter_content(chunk_size=1024): if chunk: f.write(chunk) except Exception as e: return -1 self._data2DB(x, y, z, file_path) return 1 class TerrainDownloadEngine(DownloadEngine): root_dir = '' def __init__(self, root_dir, bbox, token, thread_num, logger=None, write_db=False): super(TerrainDownloadEngine, self).__init__(bbox, thread_num, logger, write_db=write_db) self.root_dir = root_dir self.token = token def bbox2xyz(self, bbox, z): min_x, min_y = latlng2tile_terrain(bbox.min_lat, bbox.min_lng, z) max_x, max_y = latlng2tile_terrain(bbox.max_lat, bbox.max_lng, z) return math.floor(min_x), math.floor(min_y), math.ceil(max_x) + 1, math.ceil(max_y) + 1 def generate_metadata(self): try: metadatas = { "attribution": "© Analytical Graphics Inc., © CGIAR-CSI, Produced using Copernicus data and " "information funded by the European Union - EU-DEM layers", "available": [ [ { "endX": 1, "endY": 0, "startX": 0, "startY": 0 } ], [ { "endX": 3, "endY": 1, "startX": 0, "startY": 0 } ], [ { "endX": 7, "endY": 3, "startX": 0, "startY": 0 } ], [ { "endX": 15, "endY": 7, "startX": 0, "startY": 0 } ], [ { "endX": 31, "endY": 15, "startX": 0, "startY": 0 } ], [ { "endX": 63, "endY": 31, "startX": 0, "startY": 0 } ], [ { "endX": 127, "endY": 63, "startX": 0, "startY": 0 } ], [ { "endX": 255, "endY": 127, "startX": 0, "startY": 0 } ], [ { "endX": 511, "endY": 255, "startX": 0, "startY": 0 } ], [ { "endX": 1023, "endY": 511, "startX": 0, "startY": 0 } ], [ { "endX": 2047, "endY": 1023, "startX": 0, "startY": 0 } ], [ { "endX": 4095, "endY": 2047, "startX": 0, "startY": 0 } ], [ { "endX": 8191, "endY": 4095, "startX": 0, "startY": 0 } ], [ { "endX": 16383, "endY": 8191, "startX": 0, "startY": 0 } ], [ { "endX": 32767, "endY": 16383, "startX": 0, "startY": 0 } ] ], "bounds": [-180, -90, 180, 90, ], "description": "STK World Terrain Premium Tileset, v1.3. 10m - 30m resolution CONUS, 30m resolution " "SRTM between 60N and 60S, 30m Europe. Minimum global coverage of 1000m.", "extensions": ["watermask", "vertexnormals", "octvertexnormals", ], "format": "quantized-mesh-1.0", "maxzoom": 13, "minzoom": 0, "name": "world", "projection": "EPSG:4326", "scheme": "tms", "tilejson": "2.1.0", "tiles": ["{z}/{x}/{y}.terrain?v={version}", ], "version": "1.31376.0" } _dir = os.path.join(self.root_dir, 'Terrain') os.makedirs(_dir, exist_ok=True) metadatas_path = os.path.join(_dir, 'layer.json') with open(metadatas_path, 'w') as f: json.dump(metadatas, f) except Exception as e: if self.logger is not None: self.logger.exception(e) def run(self): try: self.generate_metadata() count = 0 bboxs = self.cut_bbox() for bbox in bboxs: _count = self.get_task_count(bbox) count += _count self.division_done_signal.emit(count) for bbox in bboxs: while True: if not self.running: time.sleep(0.01) else: break task_q = self.get_task_queue(bbox) self.threads = [] for i in range(self.thread_num): thread = TerrainDownloaderThread(self.root_dir, self.bbox, self.token, task_q, self.logger, write_db=self.write_db) thread.sub_progressBar_updated_signal.connect(self.sub_update_progressBar) self.threads.append(thread) for thread in self.threads: thread.start() for thread in self.threads: thread.wait() for t in self.threads: t.stop() t.quit() self.threads = [] self.download_done_signal.emit() except Exception as e: if self.logger is not None: self.logger.error(e) if __name__ == '__main__': if 1: logger = logging.getLogger('down') try: root = r'/Users/cugxy/Documents/data/downloader' formatter = logging.Formatter('%(levelname)s-%(message)s') hdlr = logging.StreamHandler() log_file = os.path.join(root, 'down.log') file_hdlr = logging.FileHandler(log_file) file_hdlr.setFormatter(formatter) logger.addHandler(file_hdlr) logger.addHandler(hdlr) logger.setLevel(logging.INFO) min_lng = -180.0 max_lng = 180.0 min_lat = -90.0 max_lat = 90.0 start_zoom = 0 end_zoom = 5 bbox = BoundBox(max_lat, max_lng, min_lat, min_lng, start_zoom, end_zoom) d = TerrainDownloadEngine(root, bbox, 8, logger) d.start() time.sleep(10000) logger.error('main thread out') except Exception as e: logger.error(e) if 0: accessToken = get_access_token() pass
en
0.730894
# -*- coding: utf-8 -*- # coding=utf-8
2.447342
2
tools/utils.py
vahini01/electoral_rolls
16
11
<reponame>vahini01/electoral_rolls #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 10 23:28:58 2017 @author: dhingratul """ import urllib.request import os from selenium import webdriver from selenium.webdriver.support.ui import Select from bs4 import BeautifulSoup import ssl import requests import wget from PyPDF2 import PdfFileReader def download_file(pdf_url, mdir, filename, flag=False): if flag is True: context = ssl._create_unverified_context() response = urllib.request.urlopen(pdf_url, context=context) else: response = urllib.request.urlopen(pdf_url) filename = mdir + filename file = open(filename, 'wb') file.write(response.read()) if os.stat(filename).st_size == 0: flag = 0 else: flag = 1 file.close() return flag def download_file_R(pdf_url, mdir, filename, file_out): requests.packages.urllib3.disable_warnings() while True: # Keep trying until the webpage successfully downloads try: r = requests.get(pdf_url, verify=False, timeout=10) break # If it downloads, get out and get on with life # If it doesn't download after the timeout period, an exceptions is thrown, and we try again except requests.exceptions.RequestException as e: with open(file_out, "a") as myfile: myfile.write(pdf_url + '\n') filename = mdir + filename with open(filename, 'wb') as f: f.write(r.content) if os.stat(filename).st_size == 0: flag = 0 else: flag = 1 return flag def download_file_W(pdf_url, mdir, filename, flag=False): filename = mdir + filename ssl._create_default_https_context = ssl._create_unverified_context wget.download(pdf_url, filename) if os.stat(filename).st_size == 0: flag = 0 else: flag = 1 return flag def getDriver(url): driver = webdriver.Chrome() driver.get(url) return driver def is_valid_pdf(fn): """Check is the PDF valid """ try: with open(fn, 'rb') as f: pdf = PdfFileReader(f) numpages = pdf.numPages return (numpages > 0) except Exception as e: return False
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 10 23:28:58 2017 @author: dhingratul """ import urllib.request import os from selenium import webdriver from selenium.webdriver.support.ui import Select from bs4 import BeautifulSoup import ssl import requests import wget from PyPDF2 import PdfFileReader def download_file(pdf_url, mdir, filename, flag=False): if flag is True: context = ssl._create_unverified_context() response = urllib.request.urlopen(pdf_url, context=context) else: response = urllib.request.urlopen(pdf_url) filename = mdir + filename file = open(filename, 'wb') file.write(response.read()) if os.stat(filename).st_size == 0: flag = 0 else: flag = 1 file.close() return flag def download_file_R(pdf_url, mdir, filename, file_out): requests.packages.urllib3.disable_warnings() while True: # Keep trying until the webpage successfully downloads try: r = requests.get(pdf_url, verify=False, timeout=10) break # If it downloads, get out and get on with life # If it doesn't download after the timeout period, an exceptions is thrown, and we try again except requests.exceptions.RequestException as e: with open(file_out, "a") as myfile: myfile.write(pdf_url + '\n') filename = mdir + filename with open(filename, 'wb') as f: f.write(r.content) if os.stat(filename).st_size == 0: flag = 0 else: flag = 1 return flag def download_file_W(pdf_url, mdir, filename, flag=False): filename = mdir + filename ssl._create_default_https_context = ssl._create_unverified_context wget.download(pdf_url, filename) if os.stat(filename).st_size == 0: flag = 0 else: flag = 1 return flag def getDriver(url): driver = webdriver.Chrome() driver.get(url) return driver def is_valid_pdf(fn): """Check is the PDF valid """ try: with open(fn, 'rb') as f: pdf = PdfFileReader(f) numpages = pdf.numPages return (numpages > 0) except Exception as e: return False
en
0.882415
#!/usr/bin/env python3 # -*- coding: utf-8 -*- Created on Fri Nov 10 23:28:58 2017 @author: dhingratul # Keep trying until the webpage successfully downloads # If it downloads, get out and get on with life # If it doesn't download after the timeout period, an exceptions is thrown, and we try again Check is the PDF valid
3.105863
3
exp/viz_raw_manhattan.py
ellencwade/coronavirus-2020
0
12
<gh_stars>0 """ Experiment summary ------------------ Treat each province/state in a country cases over time as a vector, do a simple K-Nearest Neighbor between countries. What country has the most similar trajectory to a given country? Plots similar countries """ import sys sys.path.insert(0, '..') from utils import data import os import sklearn import numpy as np import json import matplotlib.pyplot as plt plt.style.use('fivethirtyeight') # ------------ HYPERPARAMETERS ------------- BASE_PATH = '../COVID-19/csse_covid_19_data/' # ------------------------------------------ confirmed = os.path.join( BASE_PATH, 'csse_covid_19_time_series', 'time_series_covid19_confirmed_global.csv') confirmed = data.load_csv_data(confirmed) features = [] targets = [] fig = plt.figure(figsize=(12, 12)) ax = fig.add_subplot(111) cm = plt.get_cmap('jet') NUM_COLORS = 0 LINE_STYLES = ['solid', 'dashed', 'dotted'] NUM_STYLES = len(LINE_STYLES) dist_diff = os.path.join('../exp/results/', 'knn_raw.json') f = open(dist_diff,) dist_diff = json.load(f) for region, dist in dist_diff.items(): plt.style.use('fivethirtyeight') fig = plt.figure(figsize=(12, 12)) ax = fig.add_subplot(111) cm = plt.get_cmap('jet') other_region = dist['manhattan'][0] regions = [region, other_region] for val in regions: df = data.filter_by_attribute( confirmed, "Country/Region", val) cases, labels = data.get_cases_chronologically(df) cases = cases.sum(axis=0) lines = ax.plot(cases, label=val) ax.set_ylabel('# of confirmed cases') ax.set_xlabel("Time (days since Jan 22, 2020)") ax.set_yscale('log') ax.legend() plt.tight_layout() region = region.replace('*', '') other_region = other_region.replace('*', '') plt.title(f'Comparing confirmed cases in {region} and {other_region}') plt.savefig(f'results/raw_manhattan/{region}.png') plt.close() print(region)
""" Experiment summary ------------------ Treat each province/state in a country cases over time as a vector, do a simple K-Nearest Neighbor between countries. What country has the most similar trajectory to a given country? Plots similar countries """ import sys sys.path.insert(0, '..') from utils import data import os import sklearn import numpy as np import json import matplotlib.pyplot as plt plt.style.use('fivethirtyeight') # ------------ HYPERPARAMETERS ------------- BASE_PATH = '../COVID-19/csse_covid_19_data/' # ------------------------------------------ confirmed = os.path.join( BASE_PATH, 'csse_covid_19_time_series', 'time_series_covid19_confirmed_global.csv') confirmed = data.load_csv_data(confirmed) features = [] targets = [] fig = plt.figure(figsize=(12, 12)) ax = fig.add_subplot(111) cm = plt.get_cmap('jet') NUM_COLORS = 0 LINE_STYLES = ['solid', 'dashed', 'dotted'] NUM_STYLES = len(LINE_STYLES) dist_diff = os.path.join('../exp/results/', 'knn_raw.json') f = open(dist_diff,) dist_diff = json.load(f) for region, dist in dist_diff.items(): plt.style.use('fivethirtyeight') fig = plt.figure(figsize=(12, 12)) ax = fig.add_subplot(111) cm = plt.get_cmap('jet') other_region = dist['manhattan'][0] regions = [region, other_region] for val in regions: df = data.filter_by_attribute( confirmed, "Country/Region", val) cases, labels = data.get_cases_chronologically(df) cases = cases.sum(axis=0) lines = ax.plot(cases, label=val) ax.set_ylabel('# of confirmed cases') ax.set_xlabel("Time (days since Jan 22, 2020)") ax.set_yscale('log') ax.legend() plt.tight_layout() region = region.replace('*', '') other_region = other_region.replace('*', '') plt.title(f'Comparing confirmed cases in {region} and {other_region}') plt.savefig(f'results/raw_manhattan/{region}.png') plt.close() print(region)
en
0.734333
Experiment summary ------------------ Treat each province/state in a country cases over time as a vector, do a simple K-Nearest Neighbor between countries. What country has the most similar trajectory to a given country? Plots similar countries # ------------ HYPERPARAMETERS ------------- # ------------------------------------------
3.331203
3
rational/mxnet/rationals.py
steven-lang/rational_activations
0
13
<reponame>steven-lang/rational_activations """ Rational Activation Functions for MXNET ======================================= This module allows you to create Rational Neural Networks using Learnable Rational activation functions with MXNET networks. """ import mxnet as mx from mxnet import initializer from mxnet.gluon import HybridBlock from rational.utils.get_weights import get_parameters from rational.mxnet.versions import _version_a, _version_b, _version_c, _version_d from rational._base.rational_base import Rational_base class Rational(Rational_base, HybridBlock): """ Rational Activation Function, inheriting from ``mxnet.gluon.HybridBlock``. Arguments: approx_func (str): The name of the approximated function for initialisation. The different functions are available in `rational.rationals_config.json`. Default: ``leaky_relu`` degrees (tuple of int): The degrees of the numerator (P) and denominator (Q). Default ``(5, 4)`` cuda (bool): whether to execute on cuda device. NOTE: THIS PARAMETER IS CURRENTLY NOT CONSIDERED. CUDA GPUS ARE USED WHEN IT IS POSSIBLE version (str): Version of Rational to use. Rational(x) = P(x)/Q(x), where P(x) = (a_0 + a_1 * x + a_2 * x^2 + ... + a_n * x^n) and `A`: Q(x) = (1 + |b_0 * x| + | b_1 * x^2| + ... + | b_m * x^{m+1}|) `B`: Q(x) = (1 + |b_0 * x + b_1 * x^2 + ... + b_m * x^{m + 1}|) `C`: Q(x) = (0.1 + |b_0 + b_1 * x + b_2 * x^2 + ... + b_m * x^m|) `D`: like `B` with noised coefficients b_i Default ``A`` trainable (bool): Whether the weights are trainable, i.e, if they are updated during backward pass. Default ``True`` Returns: HybridBlock: Rational hybrid block """ def __init__(self, approx_func='leaky_relu', degrees=(5, 4), cuda=False, version='A', trainable=True, **kwargs): super(Rational, self).__init__(**kwargs) # read initial parameter configuration from external files w_numerator, w_denominator = get_parameters( version, degrees, approx_func) # convert w_numerator and w_denominator to mxnet arrays w_numerator = mx.nd.array(w_numerator) w_denominator = mx.nd.array(w_denominator) # register the amount of weights in numerator and denominator, since we need them during # symbolic execution, but are unable to retrieve them at later stages self.numerator_length = len(w_numerator) self.denominator_length = len(w_denominator) self.training = trainable self.degrees = degrees self.version = version self.init_approximation = approx_func # set specified context (currently not happening, since unclear, how and why helpful) # self.device = gpu() if cuda else cpu() # register and configure weights (numerator and denominator coefficients) with self.name_scope(): self.numerator = self.params.get(name='w_numerator', shape=(len(w_numerator),), init=initializer.Constant( w_numerator), grad_req='write' if trainable else 'null', differentiable=trainable) self.denominator = self.params.get(name='w_denominator', shape=(len(w_denominator),), init=initializer.Constant( w_denominator), grad_req='write' if trainable else 'null', differentiable=trainable) # register whether function is trainable, since this information needs to be passed to # version D self.training = trainable self.init_approximation = approx_func # set rational activation function version self.rational_func = {'A': _version_a, 'B': _version_b, 'C': _version_c, 'D': _version_d} \ .get(version) if self.rational_func is None: raise ValueError( "rational activation function version %s not implemented" % version) def hybrid_forward(self, F, x, numerator, denominator): return self.rational_func(F, x, numerator, denominator, self.training, self.numerator_length, self.denominator_length) def numpy(self): """ Returns a numpy version of this activation function. """ from rational.numpy import Rational as Rational_numpy rational_n = Rational_numpy(self.init_approximation, self.degrees, self.version) rational_n.numerator = self.numerator.data().asnumpy().tolist() rational_n.denominator = self.denominator.data().asnumpy().tolist() return rational_n
""" Rational Activation Functions for MXNET ======================================= This module allows you to create Rational Neural Networks using Learnable Rational activation functions with MXNET networks. """ import mxnet as mx from mxnet import initializer from mxnet.gluon import HybridBlock from rational.utils.get_weights import get_parameters from rational.mxnet.versions import _version_a, _version_b, _version_c, _version_d from rational._base.rational_base import Rational_base class Rational(Rational_base, HybridBlock): """ Rational Activation Function, inheriting from ``mxnet.gluon.HybridBlock``. Arguments: approx_func (str): The name of the approximated function for initialisation. The different functions are available in `rational.rationals_config.json`. Default: ``leaky_relu`` degrees (tuple of int): The degrees of the numerator (P) and denominator (Q). Default ``(5, 4)`` cuda (bool): whether to execute on cuda device. NOTE: THIS PARAMETER IS CURRENTLY NOT CONSIDERED. CUDA GPUS ARE USED WHEN IT IS POSSIBLE version (str): Version of Rational to use. Rational(x) = P(x)/Q(x), where P(x) = (a_0 + a_1 * x + a_2 * x^2 + ... + a_n * x^n) and `A`: Q(x) = (1 + |b_0 * x| + | b_1 * x^2| + ... + | b_m * x^{m+1}|) `B`: Q(x) = (1 + |b_0 * x + b_1 * x^2 + ... + b_m * x^{m + 1}|) `C`: Q(x) = (0.1 + |b_0 + b_1 * x + b_2 * x^2 + ... + b_m * x^m|) `D`: like `B` with noised coefficients b_i Default ``A`` trainable (bool): Whether the weights are trainable, i.e, if they are updated during backward pass. Default ``True`` Returns: HybridBlock: Rational hybrid block """ def __init__(self, approx_func='leaky_relu', degrees=(5, 4), cuda=False, version='A', trainable=True, **kwargs): super(Rational, self).__init__(**kwargs) # read initial parameter configuration from external files w_numerator, w_denominator = get_parameters( version, degrees, approx_func) # convert w_numerator and w_denominator to mxnet arrays w_numerator = mx.nd.array(w_numerator) w_denominator = mx.nd.array(w_denominator) # register the amount of weights in numerator and denominator, since we need them during # symbolic execution, but are unable to retrieve them at later stages self.numerator_length = len(w_numerator) self.denominator_length = len(w_denominator) self.training = trainable self.degrees = degrees self.version = version self.init_approximation = approx_func # set specified context (currently not happening, since unclear, how and why helpful) # self.device = gpu() if cuda else cpu() # register and configure weights (numerator and denominator coefficients) with self.name_scope(): self.numerator = self.params.get(name='w_numerator', shape=(len(w_numerator),), init=initializer.Constant( w_numerator), grad_req='write' if trainable else 'null', differentiable=trainable) self.denominator = self.params.get(name='w_denominator', shape=(len(w_denominator),), init=initializer.Constant( w_denominator), grad_req='write' if trainable else 'null', differentiable=trainable) # register whether function is trainable, since this information needs to be passed to # version D self.training = trainable self.init_approximation = approx_func # set rational activation function version self.rational_func = {'A': _version_a, 'B': _version_b, 'C': _version_c, 'D': _version_d} \ .get(version) if self.rational_func is None: raise ValueError( "rational activation function version %s not implemented" % version) def hybrid_forward(self, F, x, numerator, denominator): return self.rational_func(F, x, numerator, denominator, self.training, self.numerator_length, self.denominator_length) def numpy(self): """ Returns a numpy version of this activation function. """ from rational.numpy import Rational as Rational_numpy rational_n = Rational_numpy(self.init_approximation, self.degrees, self.version) rational_n.numerator = self.numerator.data().asnumpy().tolist() rational_n.denominator = self.denominator.data().asnumpy().tolist() return rational_n
en
0.734892
Rational Activation Functions for MXNET ======================================= This module allows you to create Rational Neural Networks using Learnable Rational activation functions with MXNET networks. Rational Activation Function, inheriting from ``mxnet.gluon.HybridBlock``. Arguments: approx_func (str): The name of the approximated function for initialisation. The different functions are available in `rational.rationals_config.json`. Default: ``leaky_relu`` degrees (tuple of int): The degrees of the numerator (P) and denominator (Q). Default ``(5, 4)`` cuda (bool): whether to execute on cuda device. NOTE: THIS PARAMETER IS CURRENTLY NOT CONSIDERED. CUDA GPUS ARE USED WHEN IT IS POSSIBLE version (str): Version of Rational to use. Rational(x) = P(x)/Q(x), where P(x) = (a_0 + a_1 * x + a_2 * x^2 + ... + a_n * x^n) and `A`: Q(x) = (1 + |b_0 * x| + | b_1 * x^2| + ... + | b_m * x^{m+1}|) `B`: Q(x) = (1 + |b_0 * x + b_1 * x^2 + ... + b_m * x^{m + 1}|) `C`: Q(x) = (0.1 + |b_0 + b_1 * x + b_2 * x^2 + ... + b_m * x^m|) `D`: like `B` with noised coefficients b_i Default ``A`` trainable (bool): Whether the weights are trainable, i.e, if they are updated during backward pass. Default ``True`` Returns: HybridBlock: Rational hybrid block # read initial parameter configuration from external files # convert w_numerator and w_denominator to mxnet arrays # register the amount of weights in numerator and denominator, since we need them during # symbolic execution, but are unable to retrieve them at later stages # set specified context (currently not happening, since unclear, how and why helpful) # self.device = gpu() if cuda else cpu() # register and configure weights (numerator and denominator coefficients) # register whether function is trainable, since this information needs to be passed to # version D # set rational activation function version Returns a numpy version of this activation function.
3.259203
3
torchflare/criterion/utils.py
Neklaustares-tPtwP/torchflare
1
14
<filename>torchflare/criterion/utils.py<gh_stars>1-10 """Utils for criterion.""" import torch import torch.nn.functional as F def normalize(x, axis=-1): """Performs L2-Norm.""" num = x denom = torch.norm(x, 2, axis, keepdim=True).expand_as(x) + 1e-12 return num / denom # Source : https://github.com/earhian/Humpback-Whale-Identification-1st-/blob/master/models/triplet_loss.py def euclidean_dist(x, y): """Computes Euclidean distance.""" m, n = x.size(0), y.size(0) xx = torch.pow(x, 2).sum(1, keepdim=True).expand(m, n) yy = torch.pow(x, 2).sum(1, keepdim=True).expand(m, m).t() dist = xx + yy - 2 * torch.matmul(x, y.t()) dist = dist.clamp(min=1e-12).sqrt() return dist def cosine_dist(x, y): """Computes Cosine Distance.""" x = F.normalize(x, dim=1) y = F.normalize(y, dim=1) dist = 2 - 2 * torch.mm(x, y.t()) return dist
<filename>torchflare/criterion/utils.py<gh_stars>1-10 """Utils for criterion.""" import torch import torch.nn.functional as F def normalize(x, axis=-1): """Performs L2-Norm.""" num = x denom = torch.norm(x, 2, axis, keepdim=True).expand_as(x) + 1e-12 return num / denom # Source : https://github.com/earhian/Humpback-Whale-Identification-1st-/blob/master/models/triplet_loss.py def euclidean_dist(x, y): """Computes Euclidean distance.""" m, n = x.size(0), y.size(0) xx = torch.pow(x, 2).sum(1, keepdim=True).expand(m, n) yy = torch.pow(x, 2).sum(1, keepdim=True).expand(m, m).t() dist = xx + yy - 2 * torch.matmul(x, y.t()) dist = dist.clamp(min=1e-12).sqrt() return dist def cosine_dist(x, y): """Computes Cosine Distance.""" x = F.normalize(x, dim=1) y = F.normalize(y, dim=1) dist = 2 - 2 * torch.mm(x, y.t()) return dist
en
0.637113
Utils for criterion. Performs L2-Norm. # Source : https://github.com/earhian/Humpback-Whale-Identification-1st-/blob/master/models/triplet_loss.py Computes Euclidean distance. Computes Cosine Distance.
2.557829
3
tests/__init__.py
eloo/sensor.sbahn_munich
0
15
"""Tests for the sbahn_munich integration""" line_dict = { "name": "S3", "color": "#333333", "text_color": "#444444", }
"""Tests for the sbahn_munich integration""" line_dict = { "name": "S3", "color": "#333333", "text_color": "#444444", }
en
0.85184
Tests for the sbahn_munich integration
1.027789
1
app/views/web/homestack.py
geudrik/hautomation
0
16
<reponame>geudrik/hautomation #! /usr/bin/env python2.7 # -*- coding: latin-1 -*- from flask import Blueprint from flask import current_app from flask import render_template from flask_login import login_required homestack = Blueprint("homestack", __name__, url_prefix="/homestack") @homestack.route("/", methods=["GET"]) @login_required def home(): return render_template("homestack/home.html")
#! /usr/bin/env python2.7 # -*- coding: latin-1 -*- from flask import Blueprint from flask import current_app from flask import render_template from flask_login import login_required homestack = Blueprint("homestack", __name__, url_prefix="/homestack") @homestack.route("/", methods=["GET"]) @login_required def home(): return render_template("homestack/home.html")
en
0.243397
#! /usr/bin/env python2.7 # -*- coding: latin-1 -*-
2.309625
2
readthedocs/donate/forms.py
gamearming/readthedocs
0
17
"""Forms for RTD donations""" import logging from django import forms from django.conf import settings from django.utils.translation import ugettext_lazy as _ from readthedocs.payments.forms import StripeModelForm, StripeResourceMixin from readthedocs.payments.utils import stripe from .models import Supporter log = logging.getLogger(__name__) class SupporterForm(StripeResourceMixin, StripeModelForm): """Donation support sign up form This extends the basic payment form, giving fields for credit card number, expiry, and CVV. The proper Knockout data bindings are established on :py:class:`StripeModelForm` """ class Meta: model = Supporter fields = ( 'last_4_digits', 'name', 'email', 'dollars', 'logo_url', 'site_url', 'public', ) labels = { 'public': _('Make this donation public'), } help_texts = { 'public': _('Your name and image will be displayed on the donation page'), 'email': _('Your email is used for Gravatar and so we can send you a receipt'), 'logo_url': _("URL of your company's logo, images should be 300x300 pixels or less"), 'dollars': _('Companies donating over $400 can specify a logo URL and site link'), } widgets = { 'dollars': forms.HiddenInput(attrs={ 'data-bind': 'value: dollars' }), 'logo_url': forms.TextInput(attrs={ 'data-bind': 'value: logo_url, enable: urls_enabled' }), 'site_url': forms.TextInput(attrs={ 'data-bind': 'value: site_url, enable: urls_enabled' }), 'last_4_digits': forms.TextInput(attrs={ 'data-bind': 'valueInit: card_digits, value: card_digits' }), } last_4_digits = forms.CharField(widget=forms.HiddenInput(), required=True) name = forms.CharField(required=True) email = forms.CharField(required=True) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(SupporterForm, self).__init__(*args, **kwargs) def validate_stripe(self): """Call stripe for payment (not ideal here) and clean up logo < $200""" dollars = self.cleaned_data['dollars'] if dollars < 200: self.cleaned_data['logo_url'] = None self.cleaned_data['site_url'] = None stripe.Charge.create( amount=int(self.cleaned_data['dollars']) * 100, currency='usd', source=self.cleaned_data['stripe_token'], description='Read the Docs Sustained Engineering', receipt_email=self.cleaned_data['email'] ) def save(self, commit=True): supporter = super(SupporterForm, self).save(commit) if commit and self.user is not None and self.user.is_authenticated(): supporter.user = self.user supporter.save() return supporter class EthicalAdForm(StripeResourceMixin, StripeModelForm): """Payment form for ethical ads This extends the basic payment form, giving fields for credit card number, expiry, and CVV. The proper Knockout data bindings are established on :py:class:`StripeModelForm` """ class Meta: model = Supporter fields = ( 'last_4_digits', 'name', 'email', 'dollars', ) help_texts = { 'email': _('Your email is used so we can send you a receipt'), } widgets = { 'dollars': forms.HiddenInput(attrs={ 'data-bind': 'value: dollars' }), 'last_4_digits': forms.TextInput(attrs={ 'data-bind': 'valueInit: card_digits, value: card_digits' }), } last_4_digits = forms.CharField(widget=forms.HiddenInput(), required=True) name = forms.CharField(required=True) email = forms.CharField(required=True) def validate_stripe(self): stripe.Charge.create( amount=int(self.cleaned_data['dollars']) * 100, currency='usd', source=self.cleaned_data['stripe_token'], description='Read the Docs Sponsorship Payment', receipt_email=self.cleaned_data['email'] )
"""Forms for RTD donations""" import logging from django import forms from django.conf import settings from django.utils.translation import ugettext_lazy as _ from readthedocs.payments.forms import StripeModelForm, StripeResourceMixin from readthedocs.payments.utils import stripe from .models import Supporter log = logging.getLogger(__name__) class SupporterForm(StripeResourceMixin, StripeModelForm): """Donation support sign up form This extends the basic payment form, giving fields for credit card number, expiry, and CVV. The proper Knockout data bindings are established on :py:class:`StripeModelForm` """ class Meta: model = Supporter fields = ( 'last_4_digits', 'name', 'email', 'dollars', 'logo_url', 'site_url', 'public', ) labels = { 'public': _('Make this donation public'), } help_texts = { 'public': _('Your name and image will be displayed on the donation page'), 'email': _('Your email is used for Gravatar and so we can send you a receipt'), 'logo_url': _("URL of your company's logo, images should be 300x300 pixels or less"), 'dollars': _('Companies donating over $400 can specify a logo URL and site link'), } widgets = { 'dollars': forms.HiddenInput(attrs={ 'data-bind': 'value: dollars' }), 'logo_url': forms.TextInput(attrs={ 'data-bind': 'value: logo_url, enable: urls_enabled' }), 'site_url': forms.TextInput(attrs={ 'data-bind': 'value: site_url, enable: urls_enabled' }), 'last_4_digits': forms.TextInput(attrs={ 'data-bind': 'valueInit: card_digits, value: card_digits' }), } last_4_digits = forms.CharField(widget=forms.HiddenInput(), required=True) name = forms.CharField(required=True) email = forms.CharField(required=True) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user') super(SupporterForm, self).__init__(*args, **kwargs) def validate_stripe(self): """Call stripe for payment (not ideal here) and clean up logo < $200""" dollars = self.cleaned_data['dollars'] if dollars < 200: self.cleaned_data['logo_url'] = None self.cleaned_data['site_url'] = None stripe.Charge.create( amount=int(self.cleaned_data['dollars']) * 100, currency='usd', source=self.cleaned_data['stripe_token'], description='Read the Docs Sustained Engineering', receipt_email=self.cleaned_data['email'] ) def save(self, commit=True): supporter = super(SupporterForm, self).save(commit) if commit and self.user is not None and self.user.is_authenticated(): supporter.user = self.user supporter.save() return supporter class EthicalAdForm(StripeResourceMixin, StripeModelForm): """Payment form for ethical ads This extends the basic payment form, giving fields for credit card number, expiry, and CVV. The proper Knockout data bindings are established on :py:class:`StripeModelForm` """ class Meta: model = Supporter fields = ( 'last_4_digits', 'name', 'email', 'dollars', ) help_texts = { 'email': _('Your email is used so we can send you a receipt'), } widgets = { 'dollars': forms.HiddenInput(attrs={ 'data-bind': 'value: dollars' }), 'last_4_digits': forms.TextInput(attrs={ 'data-bind': 'valueInit: card_digits, value: card_digits' }), } last_4_digits = forms.CharField(widget=forms.HiddenInput(), required=True) name = forms.CharField(required=True) email = forms.CharField(required=True) def validate_stripe(self): stripe.Charge.create( amount=int(self.cleaned_data['dollars']) * 100, currency='usd', source=self.cleaned_data['stripe_token'], description='Read the Docs Sponsorship Payment', receipt_email=self.cleaned_data['email'] )
en
0.804586
Forms for RTD donations Donation support sign up form This extends the basic payment form, giving fields for credit card number, expiry, and CVV. The proper Knockout data bindings are established on :py:class:`StripeModelForm` Call stripe for payment (not ideal here) and clean up logo < $200 Payment form for ethical ads This extends the basic payment form, giving fields for credit card number, expiry, and CVV. The proper Knockout data bindings are established on :py:class:`StripeModelForm`
2.358598
2
pandas_datareaders_unofficial/datareaders/google_finance_options.py
movermeyer/pandas_datareaders_unofficial
18
18
#!/usr/bin/env python # -*- coding: utf-8 -*- from .base import DataReaderBase from ..tools import COL, _get_dates, to_float, to_int import pandas as pd #from pandas.tseries.frequencies import to_offset from six.moves import cStringIO as StringIO import logging import traceback import datetime import json import token, tokenize def ymd_to_date(y, m, d): """ Returns date >>> expiration = {u'd': 1, u'm': 12, u'y': 2014} >>> ymd_to_date(**expiration) datetime.date(2014, 12, 1) >>> ymd_to_date(2014, 3, 1) datetime.date(2014, 3, 1) """ return(datetime.date(year=y, month=m, day=d)) def date_to_ymd(date): """ Returns dict like {'y': ..., 'm': ..., 'd': ...} >>> date_to_ymd(datetime.date(year=2010, month=1, day=3)) {'y': 2010, 'm': 1, 'd': 3} """ d = { 'y': date.year, 'm': date.month, 'd': date.day } return(d) def fix_lazy_json(in_text): """ Handle lazy JSON - to fix expecting property name this function fixes the json output from google http://stackoverflow.com/questions/4033633/handling-lazy-json-in-python-expecting-property-name """ tokengen = tokenize.generate_tokens(StringIO(in_text).readline) result = [] for tokid, tokval, _, _, _ in tokengen: # fix unquoted strings if (tokid == token.NAME): if tokval not in ['true', 'false', 'null', '-Infinity', 'Infinity', 'NaN']: tokid = token.STRING tokval = u'"%s"' % tokval # fix single-quoted strings elif (tokid == token.STRING): if tokval.startswith ("'"): tokval = u'"%s"' % tokval[1:-1].replace ('"', '\\"') # remove invalid commas elif (tokid == token.OP) and ((tokval == '}') or (tokval == ']')): if (len(result) > 0) and (result[-1][1] == ','): result.pop() # fix single-quoted strings elif (tokid == token.STRING): if tokval.startswith ("'"): tokval = u'"%s"' % tokval[1:-1].replace ('"', '\\"') result.append((tokid, tokval)) return tokenize.untokenize(result) def json_decode(json_string): try: ret = json.loads(json_string) except: json_string = fix_lazy_json(json_string) ret = json.loads(json_string) return ret class DataReaderGoogleFinanceOptions(DataReaderBase): """ DataReader to fetch data from Google Finance Options see https://www.google.com/finance/option_chain https://github.com/makmac213/python-google-option-chain http://www.drtomstarke.com/index.php/option-chains-from-google-finance-api """ def init(self, *args, **kwargs): self._get_multi = self._get_multi_todict def _get_one(self, name, *args, **kwargs): return(self._get_one_raw(name, 'All', 'json')) def _get_one_raw(self, symbol, typ='All', output='json', y='2014', m='12', d='1'): url = "https://www.google.com/finance/option_chain" params = { 'q': symbol, 'type': typ, 'output': output, } data = self._get_content(url, params) d = {} lst = [] for typ in [u'puts', u'calls']: df_typ = pd.DataFrame(data[typ]) df_typ['Type'] = typ lst.append(df_typ) del data[typ] for i, expiration in enumerate(data['expirations']): params = { 'q': symbol, 'output': output, 'expy': expiration['y'], 'expm': expiration['m'], 'expd': expiration['d'], } data = self._get_content(url, params) for typ in [u'puts', u'calls']: df_typ = pd.DataFrame(data[typ]) df_typ['Type'] = typ lst.append(df_typ) del data[typ] lst.append(df_typ) df = pd.concat(lst, axis=0, ignore_index=True) d_cols = { "a": "Ask", "b": "Bid", "p": "Last", "strike": "Strike", "expiry": "Expiry", "vol": "Volume", "name": "Name" } df = df.rename(columns=d_cols) """ d_cols = { "a": "ask", "b": "bid", "c": "change", "cid": "identity code", "cp": "cp" "cs": change direction. "chg" = up, "chr" = down, "chg"? "e": # I think this tells us something about what country where the stock is traded. "OPRA" means USA. "expiry": expiration date for this option "name": I don't know. I have never seen a value for this "oi": open interest. How many of these are currently being held by others. See, http://www.investopedia.com/terms/o/openinterest.asp "p": price, last "s": option code. Basically, Stock Symbol + 7 if mini option + date + "C" or "P" + price "strike": "strike price for this option" "vol": "the volume of options traded." } """ for col in ['Ask', 'Bid', 'c', 'cp', 'Last', 'Strike']: df[col] = df[col].map(to_float) for col in ['Volume', 'oi', 'cid']: df[col] = df[col].map(to_int) df['Expiry'] = pd.to_datetime(df['Expiry']) data['options'] = df data['underlying_id'] = int(data['underlying_id']) data['expiry'] = ymd_to_date(**data['expiry']) for i, expiration in enumerate(data['expirations']): data['expirations'][i] = ymd_to_date(**expiration) #for col in ['Volume']: # df[col] = df[col].fillna(0) #d = {} #d["options"] = df #return(d) return(data) def _get_content(self, url, params): #response = requests.get(url, params=params) response = self.session.get(url, params=params) if response.status_code == 200: content_json = response.text data = json_decode(content_json) return(data) if __name__ == "__main__": import doctest doctest.testmod()
#!/usr/bin/env python # -*- coding: utf-8 -*- from .base import DataReaderBase from ..tools import COL, _get_dates, to_float, to_int import pandas as pd #from pandas.tseries.frequencies import to_offset from six.moves import cStringIO as StringIO import logging import traceback import datetime import json import token, tokenize def ymd_to_date(y, m, d): """ Returns date >>> expiration = {u'd': 1, u'm': 12, u'y': 2014} >>> ymd_to_date(**expiration) datetime.date(2014, 12, 1) >>> ymd_to_date(2014, 3, 1) datetime.date(2014, 3, 1) """ return(datetime.date(year=y, month=m, day=d)) def date_to_ymd(date): """ Returns dict like {'y': ..., 'm': ..., 'd': ...} >>> date_to_ymd(datetime.date(year=2010, month=1, day=3)) {'y': 2010, 'm': 1, 'd': 3} """ d = { 'y': date.year, 'm': date.month, 'd': date.day } return(d) def fix_lazy_json(in_text): """ Handle lazy JSON - to fix expecting property name this function fixes the json output from google http://stackoverflow.com/questions/4033633/handling-lazy-json-in-python-expecting-property-name """ tokengen = tokenize.generate_tokens(StringIO(in_text).readline) result = [] for tokid, tokval, _, _, _ in tokengen: # fix unquoted strings if (tokid == token.NAME): if tokval not in ['true', 'false', 'null', '-Infinity', 'Infinity', 'NaN']: tokid = token.STRING tokval = u'"%s"' % tokval # fix single-quoted strings elif (tokid == token.STRING): if tokval.startswith ("'"): tokval = u'"%s"' % tokval[1:-1].replace ('"', '\\"') # remove invalid commas elif (tokid == token.OP) and ((tokval == '}') or (tokval == ']')): if (len(result) > 0) and (result[-1][1] == ','): result.pop() # fix single-quoted strings elif (tokid == token.STRING): if tokval.startswith ("'"): tokval = u'"%s"' % tokval[1:-1].replace ('"', '\\"') result.append((tokid, tokval)) return tokenize.untokenize(result) def json_decode(json_string): try: ret = json.loads(json_string) except: json_string = fix_lazy_json(json_string) ret = json.loads(json_string) return ret class DataReaderGoogleFinanceOptions(DataReaderBase): """ DataReader to fetch data from Google Finance Options see https://www.google.com/finance/option_chain https://github.com/makmac213/python-google-option-chain http://www.drtomstarke.com/index.php/option-chains-from-google-finance-api """ def init(self, *args, **kwargs): self._get_multi = self._get_multi_todict def _get_one(self, name, *args, **kwargs): return(self._get_one_raw(name, 'All', 'json')) def _get_one_raw(self, symbol, typ='All', output='json', y='2014', m='12', d='1'): url = "https://www.google.com/finance/option_chain" params = { 'q': symbol, 'type': typ, 'output': output, } data = self._get_content(url, params) d = {} lst = [] for typ in [u'puts', u'calls']: df_typ = pd.DataFrame(data[typ]) df_typ['Type'] = typ lst.append(df_typ) del data[typ] for i, expiration in enumerate(data['expirations']): params = { 'q': symbol, 'output': output, 'expy': expiration['y'], 'expm': expiration['m'], 'expd': expiration['d'], } data = self._get_content(url, params) for typ in [u'puts', u'calls']: df_typ = pd.DataFrame(data[typ]) df_typ['Type'] = typ lst.append(df_typ) del data[typ] lst.append(df_typ) df = pd.concat(lst, axis=0, ignore_index=True) d_cols = { "a": "Ask", "b": "Bid", "p": "Last", "strike": "Strike", "expiry": "Expiry", "vol": "Volume", "name": "Name" } df = df.rename(columns=d_cols) """ d_cols = { "a": "ask", "b": "bid", "c": "change", "cid": "identity code", "cp": "cp" "cs": change direction. "chg" = up, "chr" = down, "chg"? "e": # I think this tells us something about what country where the stock is traded. "OPRA" means USA. "expiry": expiration date for this option "name": I don't know. I have never seen a value for this "oi": open interest. How many of these are currently being held by others. See, http://www.investopedia.com/terms/o/openinterest.asp "p": price, last "s": option code. Basically, Stock Symbol + 7 if mini option + date + "C" or "P" + price "strike": "strike price for this option" "vol": "the volume of options traded." } """ for col in ['Ask', 'Bid', 'c', 'cp', 'Last', 'Strike']: df[col] = df[col].map(to_float) for col in ['Volume', 'oi', 'cid']: df[col] = df[col].map(to_int) df['Expiry'] = pd.to_datetime(df['Expiry']) data['options'] = df data['underlying_id'] = int(data['underlying_id']) data['expiry'] = ymd_to_date(**data['expiry']) for i, expiration in enumerate(data['expirations']): data['expirations'][i] = ymd_to_date(**expiration) #for col in ['Volume']: # df[col] = df[col].fillna(0) #d = {} #d["options"] = df #return(d) return(data) def _get_content(self, url, params): #response = requests.get(url, params=params) response = self.session.get(url, params=params) if response.status_code == 200: content_json = response.text data = json_decode(content_json) return(data) if __name__ == "__main__": import doctest doctest.testmod()
en
0.647081
#!/usr/bin/env python # -*- coding: utf-8 -*- #from pandas.tseries.frequencies import to_offset Returns date >>> expiration = {u'd': 1, u'm': 12, u'y': 2014} >>> ymd_to_date(**expiration) datetime.date(2014, 12, 1) >>> ymd_to_date(2014, 3, 1) datetime.date(2014, 3, 1) Returns dict like {'y': ..., 'm': ..., 'd': ...} >>> date_to_ymd(datetime.date(year=2010, month=1, day=3)) {'y': 2010, 'm': 1, 'd': 3} Handle lazy JSON - to fix expecting property name this function fixes the json output from google http://stackoverflow.com/questions/4033633/handling-lazy-json-in-python-expecting-property-name # fix unquoted strings # fix single-quoted strings # remove invalid commas # fix single-quoted strings DataReader to fetch data from Google Finance Options see https://www.google.com/finance/option_chain https://github.com/makmac213/python-google-option-chain http://www.drtomstarke.com/index.php/option-chains-from-google-finance-api d_cols = { "a": "ask", "b": "bid", "c": "change", "cid": "identity code", "cp": "cp" "cs": change direction. "chg" = up, "chr" = down, "chg"? "e": # I think this tells us something about what country where the stock is traded. "OPRA" means USA. "expiry": expiration date for this option "name": I don't know. I have never seen a value for this "oi": open interest. How many of these are currently being held by others. See, http://www.investopedia.com/terms/o/openinterest.asp "p": price, last "s": option code. Basically, Stock Symbol + 7 if mini option + date + "C" or "P" + price "strike": "strike price for this option" "vol": "the volume of options traded." } #for col in ['Volume']: # df[col] = df[col].fillna(0) #d = {} #d["options"] = df #return(d) #response = requests.get(url, params=params)
2.682168
3
keras_textclassification/data_preprocess/generator_preprocess.py
Vail-qin/Keras-TextClassification
1
19
<reponame>Vail-qin/Keras-TextClassification # !/usr/bin/python # -*- coding: utf-8 -*- # @time : 2019/11/2 21:08 # @author : Mo # @function: from keras_textclassification.data_preprocess.text_preprocess import load_json, save_json from keras_textclassification.conf.path_config import path_model_dir path_fast_text_model_vocab2index = path_model_dir + 'vocab2index.json' path_fast_text_model_l2i_i2l = path_model_dir + 'l2i_i2l.json' import numpy as np import os class PreprocessGenerator: """ 数据预处理, 输入为csv格式, [label,ques] """ def __init__(self): self.l2i_i2l = None if os.path.exists(path_fast_text_model_l2i_i2l): self.l2i_i2l = load_json(path_fast_text_model_l2i_i2l) def prereocess_idx(self, pred): if os.path.exists(path_fast_text_model_l2i_i2l): pred_i2l = {} i2l = self.l2i_i2l['i2l'] for i in range(len(pred)): pred_i2l[i2l[str(i)]] = pred[i] pred_i2l_rank = [sorted(pred_i2l.items(), key=lambda k: k[1], reverse=True)] return pred_i2l_rank else: raise RuntimeError("path_fast_text_model_label2index is None") def prereocess_pred_xid(self, pred): if os.path.exists(path_fast_text_model_l2i_i2l): pred_l2i = {} l2i = self.l2i_i2l['l2i'] for i in range(len(pred)): pred_l2i[pred[i]] = l2i[pred[i]] pred_l2i_rank = [sorted(pred_l2i.items(), key=lambda k: k[1], reverse=True)] return pred_l2i_rank else: raise RuntimeError("path_fast_text_model_label2index is None") def preprocess_get_label_set(self, path): # 首先获取label,set,即存在的具体类 label_set = set() len_all = 0 file_csv = open(path, "r", encoding="utf-8") for line in file_csv: len_all += 1 if len_all > 1: # 第一条是标签'label,ques',不选择 line_sp = line.split(",") label_org = str(line_sp[0]).strip().upper() label_real = "NAN" if label_org=="" else label_org label_set.add(label_real) file_csv.close() return label_set, len_all def preprocess_label_ques_to_idx(self, embedding_type, batch_size, path, embed, rate=1): label_set, len_all = self.preprocess_get_label_set(path) # 获取label转index字典等, 如果label2index存在则不转换了, dev验证集合的时候用 if not os.path.exists(path_fast_text_model_l2i_i2l): count = 0 label2index = {} index2label = {} for label_one in label_set: label2index[label_one] = count index2label[count] = label_one count = count + 1 l2i_i2l = {} l2i_i2l['l2i'] = label2index l2i_i2l['i2l'] = index2label save_json(l2i_i2l, path_fast_text_model_l2i_i2l) else: l2i_i2l = load_json(path_fast_text_model_l2i_i2l) # 读取数据的比例 len_ql = int(rate * len_all) if len_ql <= 500: # sample时候不生效,使得语料足够训练 len_ql = len_all def process_line(line): # 对每一条数据操作,获取label和问句index line_sp = line.split(",") ques = str(line_sp[1]).strip().upper() label = str(line_sp[0]).strip().upper() label = "NAN" if label == "" else label que_embed = embed.sentence2idx(ques) label_zeros = [0] * len(l2i_i2l['l2i']) label_zeros[l2i_i2l['l2i'][label]] = 1 return que_embed, label_zeros while True: file_csv = open(path, "r", encoding="utf-8") cout_all_line = 0 cnt = 0 x, y = [], [] # 跳出循环 if len_ql < cout_all_line: break for line in file_csv: cout_all_line += 1 if cout_all_line > 1: # 第一条是标签'label,ques',不选择 x_line, y_line = process_line(line) x.append(x_line) y.append(y_line) cnt += 1 if cnt == batch_size: if embedding_type in ['bert', 'albert']: x_, y_ = np.array(x), np.array(y) x_1 = np.array([x[0] for x in x_]) x_2 = np.array([x[1] for x in x_]) x_all = [x_1, x_2] elif embedding_type == 'xlnet': x_, y_ = x, np.array(y) x_1 = np.array([x[0][0] for x in x_]) x_2 = np.array([x[1][0] for x in x_]) x_3 = np.array([x[2][0] for x in x_]) x_all = [x_1, x_2, x_3] else: x_all, y_ = np.array(x), np.array(y) cnt = 0 yield (x_all, y_) x, y =[], [] file_csv.close() print("preprocess_label_ques_to_idx ok")
# !/usr/bin/python # -*- coding: utf-8 -*- # @time : 2019/11/2 21:08 # @author : Mo # @function: from keras_textclassification.data_preprocess.text_preprocess import load_json, save_json from keras_textclassification.conf.path_config import path_model_dir path_fast_text_model_vocab2index = path_model_dir + 'vocab2index.json' path_fast_text_model_l2i_i2l = path_model_dir + 'l2i_i2l.json' import numpy as np import os class PreprocessGenerator: """ 数据预处理, 输入为csv格式, [label,ques] """ def __init__(self): self.l2i_i2l = None if os.path.exists(path_fast_text_model_l2i_i2l): self.l2i_i2l = load_json(path_fast_text_model_l2i_i2l) def prereocess_idx(self, pred): if os.path.exists(path_fast_text_model_l2i_i2l): pred_i2l = {} i2l = self.l2i_i2l['i2l'] for i in range(len(pred)): pred_i2l[i2l[str(i)]] = pred[i] pred_i2l_rank = [sorted(pred_i2l.items(), key=lambda k: k[1], reverse=True)] return pred_i2l_rank else: raise RuntimeError("path_fast_text_model_label2index is None") def prereocess_pred_xid(self, pred): if os.path.exists(path_fast_text_model_l2i_i2l): pred_l2i = {} l2i = self.l2i_i2l['l2i'] for i in range(len(pred)): pred_l2i[pred[i]] = l2i[pred[i]] pred_l2i_rank = [sorted(pred_l2i.items(), key=lambda k: k[1], reverse=True)] return pred_l2i_rank else: raise RuntimeError("path_fast_text_model_label2index is None") def preprocess_get_label_set(self, path): # 首先获取label,set,即存在的具体类 label_set = set() len_all = 0 file_csv = open(path, "r", encoding="utf-8") for line in file_csv: len_all += 1 if len_all > 1: # 第一条是标签'label,ques',不选择 line_sp = line.split(",") label_org = str(line_sp[0]).strip().upper() label_real = "NAN" if label_org=="" else label_org label_set.add(label_real) file_csv.close() return label_set, len_all def preprocess_label_ques_to_idx(self, embedding_type, batch_size, path, embed, rate=1): label_set, len_all = self.preprocess_get_label_set(path) # 获取label转index字典等, 如果label2index存在则不转换了, dev验证集合的时候用 if not os.path.exists(path_fast_text_model_l2i_i2l): count = 0 label2index = {} index2label = {} for label_one in label_set: label2index[label_one] = count index2label[count] = label_one count = count + 1 l2i_i2l = {} l2i_i2l['l2i'] = label2index l2i_i2l['i2l'] = index2label save_json(l2i_i2l, path_fast_text_model_l2i_i2l) else: l2i_i2l = load_json(path_fast_text_model_l2i_i2l) # 读取数据的比例 len_ql = int(rate * len_all) if len_ql <= 500: # sample时候不生效,使得语料足够训练 len_ql = len_all def process_line(line): # 对每一条数据操作,获取label和问句index line_sp = line.split(",") ques = str(line_sp[1]).strip().upper() label = str(line_sp[0]).strip().upper() label = "NAN" if label == "" else label que_embed = embed.sentence2idx(ques) label_zeros = [0] * len(l2i_i2l['l2i']) label_zeros[l2i_i2l['l2i'][label]] = 1 return que_embed, label_zeros while True: file_csv = open(path, "r", encoding="utf-8") cout_all_line = 0 cnt = 0 x, y = [], [] # 跳出循环 if len_ql < cout_all_line: break for line in file_csv: cout_all_line += 1 if cout_all_line > 1: # 第一条是标签'label,ques',不选择 x_line, y_line = process_line(line) x.append(x_line) y.append(y_line) cnt += 1 if cnt == batch_size: if embedding_type in ['bert', 'albert']: x_, y_ = np.array(x), np.array(y) x_1 = np.array([x[0] for x in x_]) x_2 = np.array([x[1] for x in x_]) x_all = [x_1, x_2] elif embedding_type == 'xlnet': x_, y_ = x, np.array(y) x_1 = np.array([x[0][0] for x in x_]) x_2 = np.array([x[1][0] for x in x_]) x_3 = np.array([x[2][0] for x in x_]) x_all = [x_1, x_2, x_3] else: x_all, y_ = np.array(x), np.array(y) cnt = 0 yield (x_all, y_) x, y =[], [] file_csv.close() print("preprocess_label_ques_to_idx ok")
zh
0.794658
# !/usr/bin/python # -*- coding: utf-8 -*- # @time : 2019/11/2 21:08 # @author : Mo # @function: 数据预处理, 输入为csv格式, [label,ques] # 首先获取label,set,即存在的具体类 # 第一条是标签'label,ques',不选择 # 获取label转index字典等, 如果label2index存在则不转换了, dev验证集合的时候用 # 读取数据的比例 # sample时候不生效,使得语料足够训练 # 对每一条数据操作,获取label和问句index # 跳出循环 # 第一条是标签'label,ques',不选择
2.462018
2
content/test/gpu/gpu_tests/pixel_expectations.py
metux/chromium-deb
0
20
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from gpu_tests.gpu_test_expectations import GpuTestExpectations # See the GpuTestExpectations class for documentation. class PixelExpectations(GpuTestExpectations): def SetExpectations(self): # Sample Usage: # self.Fail('Pixel_Canvas2DRedBox', # ['mac', 'amd', ('nvidia', 0x1234)], bug=123) # Seems to be flaky on the new AMD R7 240 drivers. self.Flaky('Pixel_GpuRasterization_BlueBox', ['win', ('amd', 0x6613)], bug=653538) # Software compositing is not supported on Android; so we skip these tests # that disables gpu compositing on Android platforms. self.Skip('Pixel_OffscreenCanvasUnaccelerated2D', ['android']) self.Skip('Pixel_OffscreenCanvasUnaccelerated2DWorker', ['android']) self.Skip('Pixel_OffscreenCanvasWebGLSoftwareCompositing', ['android']) self.Skip('Pixel_OffscreenCanvasWebGLSoftwareCompositingWorker', ['android']) self.Skip('Pixel_CanvasDisplayLinearRGBUnaccelerated2D', ['android']) self.Fail('Pixel_ScissorTestWithPreserveDrawingBuffer', ['android'], bug=521588) # TODO(ccameron) fix these on Mac Retina self.Fail('Pixel_CSS3DBlueBox', ['mac'], bug=533690) # TODO(vmiura) check / generate reference images for Android devices self.Fail('Pixel_SolidColorBackground', ['mac', 'android'], bug=624256) self.Fail('Pixel_OffscreenCanvasUnaccelerated2DGPUCompositingWorker', ['mac', ('nvidia', 0xfe9)], bug=706016) self.Fail('Pixel_CSSFilterEffects', ['mac', ('nvidia', 0xfe9)], bug=690277) # TODO(kbr): flakily timing out on this configuration. self.Flaky('*', ['linux', 'intel', 'debug'], bug=648369) self.Flaky('Pixel_Video_MP4', ['android', 'nvidia'], bug=716564) # Flaky for unknown reasons only on macOS. Not planning to investigate # further. self.Flaky('Pixel_ScissorTestWithPreserveDrawingBuffer', ['mac'], bug=660461) self.Flaky('Pixel_OffscreenCanvas2DResizeOnWorker', ['win10', ('intel', 0x1912)], bug=690663) # TODO(zakerinasab): check / generate reference images. self.Fail('Pixel_Canvas2DUntagged', bug=713632) self.Flaky('Pixel_OffscreenCanvasTransferBeforeStyleResize', ['mac', 'linux', 'win', 'android'], bug=735228) self.Flaky('Pixel_OffscreenCanvasTransferAfterStyleResize', ['mac', 'linux', 'win', 'android'], bug=735171) # TODO(junov): update reference images self.Fail('Pixel_CSSFilterEffects', ['mac'], bug=721727) self.Fail('Pixel_CSSFilterEffects_NoOverlays', ['mac'], bug=721727) # TODO(dshwang): remove these after new reference images are generated. self.Fail('Pixel_DirectComposition_Video_MP4', bug=615325) self.Fail('Pixel_DirectComposition_Video_VP9', bug=615325) self.Fail('Pixel_Video_MP4', bug=615325) self.Fail('Pixel_Video_VP9', bug=615325)
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from gpu_tests.gpu_test_expectations import GpuTestExpectations # See the GpuTestExpectations class for documentation. class PixelExpectations(GpuTestExpectations): def SetExpectations(self): # Sample Usage: # self.Fail('Pixel_Canvas2DRedBox', # ['mac', 'amd', ('nvidia', 0x1234)], bug=123) # Seems to be flaky on the new AMD R7 240 drivers. self.Flaky('Pixel_GpuRasterization_BlueBox', ['win', ('amd', 0x6613)], bug=653538) # Software compositing is not supported on Android; so we skip these tests # that disables gpu compositing on Android platforms. self.Skip('Pixel_OffscreenCanvasUnaccelerated2D', ['android']) self.Skip('Pixel_OffscreenCanvasUnaccelerated2DWorker', ['android']) self.Skip('Pixel_OffscreenCanvasWebGLSoftwareCompositing', ['android']) self.Skip('Pixel_OffscreenCanvasWebGLSoftwareCompositingWorker', ['android']) self.Skip('Pixel_CanvasDisplayLinearRGBUnaccelerated2D', ['android']) self.Fail('Pixel_ScissorTestWithPreserveDrawingBuffer', ['android'], bug=521588) # TODO(ccameron) fix these on Mac Retina self.Fail('Pixel_CSS3DBlueBox', ['mac'], bug=533690) # TODO(vmiura) check / generate reference images for Android devices self.Fail('Pixel_SolidColorBackground', ['mac', 'android'], bug=624256) self.Fail('Pixel_OffscreenCanvasUnaccelerated2DGPUCompositingWorker', ['mac', ('nvidia', 0xfe9)], bug=706016) self.Fail('Pixel_CSSFilterEffects', ['mac', ('nvidia', 0xfe9)], bug=690277) # TODO(kbr): flakily timing out on this configuration. self.Flaky('*', ['linux', 'intel', 'debug'], bug=648369) self.Flaky('Pixel_Video_MP4', ['android', 'nvidia'], bug=716564) # Flaky for unknown reasons only on macOS. Not planning to investigate # further. self.Flaky('Pixel_ScissorTestWithPreserveDrawingBuffer', ['mac'], bug=660461) self.Flaky('Pixel_OffscreenCanvas2DResizeOnWorker', ['win10', ('intel', 0x1912)], bug=690663) # TODO(zakerinasab): check / generate reference images. self.Fail('Pixel_Canvas2DUntagged', bug=713632) self.Flaky('Pixel_OffscreenCanvasTransferBeforeStyleResize', ['mac', 'linux', 'win', 'android'], bug=735228) self.Flaky('Pixel_OffscreenCanvasTransferAfterStyleResize', ['mac', 'linux', 'win', 'android'], bug=735171) # TODO(junov): update reference images self.Fail('Pixel_CSSFilterEffects', ['mac'], bug=721727) self.Fail('Pixel_CSSFilterEffects_NoOverlays', ['mac'], bug=721727) # TODO(dshwang): remove these after new reference images are generated. self.Fail('Pixel_DirectComposition_Video_MP4', bug=615325) self.Fail('Pixel_DirectComposition_Video_VP9', bug=615325) self.Fail('Pixel_Video_MP4', bug=615325) self.Fail('Pixel_Video_VP9', bug=615325)
en
0.662764
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # See the GpuTestExpectations class for documentation. # Sample Usage: # self.Fail('Pixel_Canvas2DRedBox', # ['mac', 'amd', ('nvidia', 0x1234)], bug=123) # Seems to be flaky on the new AMD R7 240 drivers. # Software compositing is not supported on Android; so we skip these tests # that disables gpu compositing on Android platforms. # TODO(ccameron) fix these on Mac Retina # TODO(vmiura) check / generate reference images for Android devices # TODO(kbr): flakily timing out on this configuration. # Flaky for unknown reasons only on macOS. Not planning to investigate # further. # TODO(zakerinasab): check / generate reference images. # TODO(junov): update reference images # TODO(dshwang): remove these after new reference images are generated.
1.894099
2
examples/p02_budgets/budget_data_ingest/migrations/0001_initial.py
18F/data-federation-ingest
18
21
<filename>examples/p02_budgets/budget_data_ingest/migrations/0001_initial.py # -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-06-08 22:54 from __future__ import unicode_literals from django.conf import settings import django.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='BudgetItem', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('year', models.IntegerField()), ('agency', models.TextField()), ('data_source', models.TextField()), ('category', models.TextField()), ('dollars_budgeted', models.DecimalField(decimal_places=2, max_digits=14)), ('dollars_spent', models.DecimalField(decimal_places=2, max_digits=14)), ('row_number', models.IntegerField()), ], ), migrations.CreateModel( name='Upload', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ('file_metadata', django.contrib.postgres.fields.jsonb.JSONField(null=True)), ('file', models.FileField(upload_to='')), ('raw', models.BinaryField(null=True)), ('validation_results', django.contrib.postgres.fields.jsonb.JSONField(null=True)), ('status', models.CharField(choices=[('LOADING', 'Loading'), ('PENDING', 'Pending'), ('STAGED', 'Staged'), ('INSERTED', 'Inserted'), ('DELETED', 'Deleted')], default='LOADING', max_length=10)), ('status_changed_at', models.DateTimeField(null=True)), ('replaces', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='replaced_by', to='budget_data_ingest.Upload')), ('status_changed_by', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to=settings.AUTH_USER_MODEL)), ('submitter', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'abstract': False, }, ), migrations.AddField( model_name='budgetitem', name='upload', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='budget_data_ingest.Upload'), ), ]
<filename>examples/p02_budgets/budget_data_ingest/migrations/0001_initial.py # -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-06-08 22:54 from __future__ import unicode_literals from django.conf import settings import django.contrib.postgres.fields.jsonb from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='BudgetItem', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('year', models.IntegerField()), ('agency', models.TextField()), ('data_source', models.TextField()), ('category', models.TextField()), ('dollars_budgeted', models.DecimalField(decimal_places=2, max_digits=14)), ('dollars_spent', models.DecimalField(decimal_places=2, max_digits=14)), ('row_number', models.IntegerField()), ], ), migrations.CreateModel( name='Upload', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ('file_metadata', django.contrib.postgres.fields.jsonb.JSONField(null=True)), ('file', models.FileField(upload_to='')), ('raw', models.BinaryField(null=True)), ('validation_results', django.contrib.postgres.fields.jsonb.JSONField(null=True)), ('status', models.CharField(choices=[('LOADING', 'Loading'), ('PENDING', 'Pending'), ('STAGED', 'Staged'), ('INSERTED', 'Inserted'), ('DELETED', 'Deleted')], default='LOADING', max_length=10)), ('status_changed_at', models.DateTimeField(null=True)), ('replaces', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='replaced_by', to='budget_data_ingest.Upload')), ('status_changed_by', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='+', to=settings.AUTH_USER_MODEL)), ('submitter', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], options={ 'abstract': False, }, ), migrations.AddField( model_name='budgetitem', name='upload', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='budget_data_ingest.Upload'), ), ]
en
0.670743
# -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-06-08 22:54
1.68477
2
setup.py
Kaslanarian/PythonSVM
2
22
import setuptools #enables develop setuptools.setup( name='pysvm', version='0.1', description='PySVM : A NumPy implementation of SVM based on SMO algorithm', author_email="<EMAIL>", packages=['pysvm'], license='MIT License', long_description=open('README.md', encoding='utf-8').read(), install_requires=[ #自动安装依赖 'numpy', 'sklearn' ], url='https://github.com/Kaslanarian/PySVM', )
import setuptools #enables develop setuptools.setup( name='pysvm', version='0.1', description='PySVM : A NumPy implementation of SVM based on SMO algorithm', author_email="<EMAIL>", packages=['pysvm'], license='MIT License', long_description=open('README.md', encoding='utf-8').read(), install_requires=[ #自动安装依赖 'numpy', 'sklearn' ], url='https://github.com/Kaslanarian/PySVM', )
zh
0.409137
#enables develop #自动安装依赖
0.931335
1
Object_detection_image.py
hiperus0988/pyao
1
23
<gh_stars>1-10 ######## Image Object Detection Using Tensorflow-trained Classifier ######### # # Author: <NAME> # Date: 1/15/18 # Description: # This program uses a TensorFlow-trained classifier to perform object detection. # It loads the classifier uses it to perform object detection on an image. # It draws boxes and scores around the objects of interest in the image. ## Some of the code is copied from Google's example at ## https://github.com/tensorflow/models/blob/master/research/object_detection/object_detection_tutorial.ipynb ## and some is copied from Dat Tran's example at ## https://github.com/datitran/object_detector_app/blob/master/object_detection_app.py ## but I changed it to make it more understandable to me. # Import packages import os import cv2 import numpy as np import tensorflow as tf import sys # This is needed since the notebook is stored in the object_detection folder. sys.path.append("..") # Import utilites from utils import label_map_util from utils import visualization_utils as vis_util # Name of the directory containing the object detection module we're using MODEL_NAME = 'inference_graph' IMAGE_NAME = 'test1.jpg' # Grab path to current working directory CWD_PATH = os.getcwd() # Path to frozen detection graph .pb file, which contains the model that is used # for object detection. PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,'frozen_inference_graph.pb') # Path to label map file PATH_TO_LABELS = os.path.join(CWD_PATH,'training','labelmap.pbtxt') # Path to image PATH_TO_IMAGE = os.path.join(CWD_PATH,IMAGE_NAME) # Number of classes the object detector can identify NUM_CLASSES = 6 # Load the label map. # Label maps map indices to category names, so that when our convolution # network predicts `5`, we know that this corresponds to `king`. # Here we use internal utility functions, but anything that returns a # dictionary mapping integers to appropriate string labels would be fine label_map = label_map_util.load_labelmap(PATH_TO_LABELS) categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True) category_index = label_map_util.create_category_index(categories) # Load the Tensorflow model into memory. detection_graph = tf.Graph() with detection_graph.as_default(): od_graph_def = tf.GraphDef() with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name='') sess = tf.Session(graph=detection_graph) # Define input and output tensors (i.e. data) for the object detection classifier # Input tensor is the image image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') # Output tensors are the detection boxes, scores, and classes # Each box represents a part of the image where a particular object was detected detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0') # Each score represents level of confidence for each of the objects. # The score is shown on the result image, together with the class label. detection_scores = detection_graph.get_tensor_by_name('detection_scores:0') detection_classes = detection_graph.get_tensor_by_name('detection_classes:0') # Number of objects detected num_detections = detection_graph.get_tensor_by_name('num_detections:0') # Load image using OpenCV and # expand image dimensions to have shape: [1, None, None, 3] # i.e. a single-column array, where each item in the column has the pixel RGB value image = cv2.imread(PATH_TO_IMAGE) image_expanded = np.expand_dims(image, axis=0) # Perform the actual detection by running the model with the image as input (boxes, scores, classes, num) = sess.run( [detection_boxes, detection_scores, detection_classes, num_detections], feed_dict={image_tensor: image_expanded}) # Draw the results of the detection (aka 'visulaize the results') vis_util.visualize_boxes_and_labels_on_image_array( image, np.squeeze(boxes), np.squeeze(classes).astype(np.int32), np.squeeze(scores), category_index, use_normalized_coordinates=True, line_thickness=8, min_score_thresh=0.60) # All the results have been drawn on image. Now display the image. cv2.imshow('Object detector', image) # Press any key to close the image cv2.waitKey(0) # Clean up cv2.destroyAllWindows()
######## Image Object Detection Using Tensorflow-trained Classifier ######### # # Author: <NAME> # Date: 1/15/18 # Description: # This program uses a TensorFlow-trained classifier to perform object detection. # It loads the classifier uses it to perform object detection on an image. # It draws boxes and scores around the objects of interest in the image. ## Some of the code is copied from Google's example at ## https://github.com/tensorflow/models/blob/master/research/object_detection/object_detection_tutorial.ipynb ## and some is copied from Dat Tran's example at ## https://github.com/datitran/object_detector_app/blob/master/object_detection_app.py ## but I changed it to make it more understandable to me. # Import packages import os import cv2 import numpy as np import tensorflow as tf import sys # This is needed since the notebook is stored in the object_detection folder. sys.path.append("..") # Import utilites from utils import label_map_util from utils import visualization_utils as vis_util # Name of the directory containing the object detection module we're using MODEL_NAME = 'inference_graph' IMAGE_NAME = 'test1.jpg' # Grab path to current working directory CWD_PATH = os.getcwd() # Path to frozen detection graph .pb file, which contains the model that is used # for object detection. PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,'frozen_inference_graph.pb') # Path to label map file PATH_TO_LABELS = os.path.join(CWD_PATH,'training','labelmap.pbtxt') # Path to image PATH_TO_IMAGE = os.path.join(CWD_PATH,IMAGE_NAME) # Number of classes the object detector can identify NUM_CLASSES = 6 # Load the label map. # Label maps map indices to category names, so that when our convolution # network predicts `5`, we know that this corresponds to `king`. # Here we use internal utility functions, but anything that returns a # dictionary mapping integers to appropriate string labels would be fine label_map = label_map_util.load_labelmap(PATH_TO_LABELS) categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True) category_index = label_map_util.create_category_index(categories) # Load the Tensorflow model into memory. detection_graph = tf.Graph() with detection_graph.as_default(): od_graph_def = tf.GraphDef() with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name='') sess = tf.Session(graph=detection_graph) # Define input and output tensors (i.e. data) for the object detection classifier # Input tensor is the image image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') # Output tensors are the detection boxes, scores, and classes # Each box represents a part of the image where a particular object was detected detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0') # Each score represents level of confidence for each of the objects. # The score is shown on the result image, together with the class label. detection_scores = detection_graph.get_tensor_by_name('detection_scores:0') detection_classes = detection_graph.get_tensor_by_name('detection_classes:0') # Number of objects detected num_detections = detection_graph.get_tensor_by_name('num_detections:0') # Load image using OpenCV and # expand image dimensions to have shape: [1, None, None, 3] # i.e. a single-column array, where each item in the column has the pixel RGB value image = cv2.imread(PATH_TO_IMAGE) image_expanded = np.expand_dims(image, axis=0) # Perform the actual detection by running the model with the image as input (boxes, scores, classes, num) = sess.run( [detection_boxes, detection_scores, detection_classes, num_detections], feed_dict={image_tensor: image_expanded}) # Draw the results of the detection (aka 'visulaize the results') vis_util.visualize_boxes_and_labels_on_image_array( image, np.squeeze(boxes), np.squeeze(classes).astype(np.int32), np.squeeze(scores), category_index, use_normalized_coordinates=True, line_thickness=8, min_score_thresh=0.60) # All the results have been drawn on image. Now display the image. cv2.imshow('Object detector', image) # Press any key to close the image cv2.waitKey(0) # Clean up cv2.destroyAllWindows()
en
0.823256
######## Image Object Detection Using Tensorflow-trained Classifier ######### # # Author: <NAME> # Date: 1/15/18 # Description: # This program uses a TensorFlow-trained classifier to perform object detection. # It loads the classifier uses it to perform object detection on an image. # It draws boxes and scores around the objects of interest in the image. ## Some of the code is copied from Google's example at ## https://github.com/tensorflow/models/blob/master/research/object_detection/object_detection_tutorial.ipynb ## and some is copied from Dat Tran's example at ## https://github.com/datitran/object_detector_app/blob/master/object_detection_app.py ## but I changed it to make it more understandable to me. # Import packages # This is needed since the notebook is stored in the object_detection folder. # Import utilites # Name of the directory containing the object detection module we're using # Grab path to current working directory # Path to frozen detection graph .pb file, which contains the model that is used # for object detection. # Path to label map file # Path to image # Number of classes the object detector can identify # Load the label map. # Label maps map indices to category names, so that when our convolution # network predicts `5`, we know that this corresponds to `king`. # Here we use internal utility functions, but anything that returns a # dictionary mapping integers to appropriate string labels would be fine # Load the Tensorflow model into memory. # Define input and output tensors (i.e. data) for the object detection classifier # Input tensor is the image # Output tensors are the detection boxes, scores, and classes # Each box represents a part of the image where a particular object was detected # Each score represents level of confidence for each of the objects. # The score is shown on the result image, together with the class label. # Number of objects detected # Load image using OpenCV and # expand image dimensions to have shape: [1, None, None, 3] # i.e. a single-column array, where each item in the column has the pixel RGB value # Perform the actual detection by running the model with the image as input # Draw the results of the detection (aka 'visulaize the results') # All the results have been drawn on image. Now display the image. # Press any key to close the image # Clean up
3.357402
3
polling_stations/apps/data_collection/management/commands/import_torbay.py
chris48s/UK-Polling-Stations
0
24
from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter class Command(BaseXpressDemocracyClubCsvImporter): council_id = 'E06000027' addresses_name = 'parl.2017-06-08/Version 1/Torbay Democracy_Club__08June2017.tsv' stations_name = 'parl.2017-06-08/Version 1/Torbay Democracy_Club__08June2017.tsv' elections = ['parl.2017-06-08'] csv_delimiter = '\t'
from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter class Command(BaseXpressDemocracyClubCsvImporter): council_id = 'E06000027' addresses_name = 'parl.2017-06-08/Version 1/Torbay Democracy_Club__08June2017.tsv' stations_name = 'parl.2017-06-08/Version 1/Torbay Democracy_Club__08June2017.tsv' elections = ['parl.2017-06-08'] csv_delimiter = '\t'
none
1
1.721196
2
Backend/product/views.py
Bhavya0020/Readopolis
0
25
from django.db.models import Q from django.shortcuts import render from django.http import Http404 # Create your views here. from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.decorators import api_view from .models import Product, Category from .serializers import ProductSerializer, CategorySerializer class LatestProductsList(APIView): def get(self, request, format=None): products = Product.objects.all()[0:4] serializer = ProductSerializer(products,many=True) return Response(serializer.data) class ProductDetail(APIView): def get_object(self, category_slug, product_slug): try: return Product.objects.filter(category__slug=category_slug).get(slug=product_slug) except Product.DoesNotExist: raise Http404 def get(self, request, category_slug, product_slug, format= None): product = self.get_object(category_slug, product_slug) serializer = ProductSerializer(product) return Response(serializer.data) class CategoryDetail(APIView): def get_object(self, category_slug): try: return Category.objects.get(slug=category_slug) except Category.DoesNotExist: raise Http404 def get(self, request, category_slug, format= None): category = self.get_object(category_slug) serializer = CategorySerializer(category) return Response(serializer.data) @api_view(['POST']) def search(request): query = request.data.get('query', '') if query: products = Product.objects.filter(Q(name__icontains=query) | Q(description__icontains=query)) serializer = ProductSerializer(products, many=True) return Response(serializer.data) else: return Response({"products": []})
from django.db.models import Q from django.shortcuts import render from django.http import Http404 # Create your views here. from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.decorators import api_view from .models import Product, Category from .serializers import ProductSerializer, CategorySerializer class LatestProductsList(APIView): def get(self, request, format=None): products = Product.objects.all()[0:4] serializer = ProductSerializer(products,many=True) return Response(serializer.data) class ProductDetail(APIView): def get_object(self, category_slug, product_slug): try: return Product.objects.filter(category__slug=category_slug).get(slug=product_slug) except Product.DoesNotExist: raise Http404 def get(self, request, category_slug, product_slug, format= None): product = self.get_object(category_slug, product_slug) serializer = ProductSerializer(product) return Response(serializer.data) class CategoryDetail(APIView): def get_object(self, category_slug): try: return Category.objects.get(slug=category_slug) except Category.DoesNotExist: raise Http404 def get(self, request, category_slug, format= None): category = self.get_object(category_slug) serializer = CategorySerializer(category) return Response(serializer.data) @api_view(['POST']) def search(request): query = request.data.get('query', '') if query: products = Product.objects.filter(Q(name__icontains=query) | Q(description__icontains=query)) serializer = ProductSerializer(products, many=True) return Response(serializer.data) else: return Response({"products": []})
en
0.968116
# Create your views here.
2.047789
2
model/contact.py
hubogeri/python_training
0
26
from sys import maxsize class Contact: def __init__(self, fname=None, mname=None, lname=None, nick=None, title=None, comp=None, addr=None, home=None, mobile=None, work=None, fax=None, email1=None, email2=None, email3=None, homepage=None, bday=None, bmonth=None, byear=None, aday=None, amonth=None, ayear=None, secaddr=None, secphone=None, note=None, id =None): self.fname = fname self.mname = mname self.lname = lname self.nick = nick self.title = title self.comp = comp self.addr = addr self.home = home self.mobile = mobile self.work = work self.fax = fax self.email1 = email1 self.email2 = email2 self.email3 = email3 self.homepage = homepage self.bday = bday self.bmonth = bmonth self.byear = byear self.aday = aday self.amonth = amonth self.ayear = ayear self.secaddr = secaddr self.secphone = secphone self.note = note self.id = id def __repr__(self): return "%s:%s:%s" % (self.id, self.fname, self.lname) def __eq__(self, other): return (self.id is None or other.id is None or self.id == other.id) and self.fname == other.fname and self.lname == other.lname def id_or_max(self): if self.id: return int(self.id) else: return maxsize
from sys import maxsize class Contact: def __init__(self, fname=None, mname=None, lname=None, nick=None, title=None, comp=None, addr=None, home=None, mobile=None, work=None, fax=None, email1=None, email2=None, email3=None, homepage=None, bday=None, bmonth=None, byear=None, aday=None, amonth=None, ayear=None, secaddr=None, secphone=None, note=None, id =None): self.fname = fname self.mname = mname self.lname = lname self.nick = nick self.title = title self.comp = comp self.addr = addr self.home = home self.mobile = mobile self.work = work self.fax = fax self.email1 = email1 self.email2 = email2 self.email3 = email3 self.homepage = homepage self.bday = bday self.bmonth = bmonth self.byear = byear self.aday = aday self.amonth = amonth self.ayear = ayear self.secaddr = secaddr self.secphone = secphone self.note = note self.id = id def __repr__(self): return "%s:%s:%s" % (self.id, self.fname, self.lname) def __eq__(self, other): return (self.id is None or other.id is None or self.id == other.id) and self.fname == other.fname and self.lname == other.lname def id_or_max(self): if self.id: return int(self.id) else: return maxsize
none
1
3.114625
3
test/IECore/BasicPreset.py
ericmehl/cortex
386
27
########################################################################## # # Copyright (c) 2010-2012, Image Engine Design Inc. 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 Image Engine Design nor the names of any # other contributors to this software 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 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. # ########################################################################## from __future__ import with_statement import os import sys import shutil import unittest import IECore class TestBasicPreset( unittest.TestCase ) : def testCopy( self ) : testObj = IECore.Parameterised( "testParameterised1" ) testObj.parameters().addParameters( [ IECore.BoolParameter( "a", "", True ), IECore.FloatParameter( "b", "", 1.0 ), ] ) testObj2 = IECore.Parameterised( "testParameterised2" ) testObj2.parameters().addParameters( [ IECore.BoolParameter( "a", "", False ), IECore.FloatParameter( "c", "", 0.0 ), ] ) p = IECore.BasicPreset( testObj, testObj.parameters() ) self.assertTrue( p.applicableTo( testObj, testObj.parameters() ) ) self.assertFalse( p.applicableTo( testObj2, testObj2.parameters() ) ) testObj.parameters()["a"].setTypedValue( False ) testObj.parameters()["b"].setTypedValue( 0.0 ) p( testObj, testObj.parameters() ) self.assertEqual( testObj.parameters()["a"].getTypedValue(), True ) self.assertEqual( testObj.parameters()["b"].getTypedValue(), 1.0 ) p2 = IECore.BasicPreset( testObj, testObj.parameters(), parameters=( testObj.parameters()["a"], ) ) self.assertTrue( p2.applicableTo( testObj, testObj.parameters() ) ) self.assertTrue( p2.applicableTo( testObj2, testObj.parameters() ) ) p2( testObj2, testObj2.parameters() ) self.assertEqual( testObj2.parameters()["a"].getTypedValue(), True ) self.assertEqual( testObj2.parameters()["c"].getTypedValue(), 0.0 ) def testLoad( self ) : testObj = IECore.Parameterised( "testParameterised1" ) testObj.parameters().addParameters( [ IECore.BoolParameter( "a", "", True ), IECore.FloatParameter( "b", "", 1.0 ), ] ) testObj2 = IECore.Parameterised( "testParameterised1" ) testObj2.parameters().addParameters( [ IECore.BoolParameter( "a", "", False ), IECore.FloatParameter( "c", "", 0.0 ), ] ) savePath = os.path.abspath( os.path.join( os.path.dirname( __file__ ), "data", "basicPreset" ) ) messageHandler = IECore.CapturingMessageHandler() with messageHandler : p = IECore.BasicPreset( os.path.join( savePath, "basicPresetLoadTest", "basicPresetLoadTest-1.cob" ) ) self.assertEqual( len( messageHandler.messages ), 0 ) self.assertTrue( p.applicableTo( testObj, testObj.parameters() ) ) self.assertFalse( p.applicableTo( testObj2, testObj2.parameters() ) ) testObj.parameters()["a"].setTypedValue( False ) testObj.parameters()["b"].setTypedValue( 0.0 ) p( testObj, testObj.parameters() ) self.assertEqual( testObj.parameters()["a"].getTypedValue(), True ) self.assertEqual( testObj.parameters()["b"].getTypedValue(), 1.0 ) def testSave( self ) : testObj = IECore.Parameterised( "testParameterised1" ) testObj.parameters().addParameters( [ IECore.BoolParameter( "a", "", True ), IECore.FloatParameter( "b", "", 1.0 ), ] ) testObj2 = IECore.Parameterised( "testParameterised1" ) testObj2.parameters().addParameters( [ IECore.BoolParameter( "a", "", False ), IECore.FloatParameter( "c", "", 0.0 ), ] ) savePath = os.path.abspath( os.path.join( os.path.dirname( __file__ ), "data", "basicPreset" ) ) preset = IECore.BasicPreset( testObj, testObj.parameters() ) # Save for the classLoader and check its there, we test the 'loadability' later... preset.save( savePath, "basicPresetTest" ) self.assertTrue( os.path.isfile( os.path.join( savePath, "basicPresetTest", "basicPresetTest-1.cob" ) ) ) self.assertTrue( os.path.isfile( os.path.join( savePath, "basicPresetTest", "basicPresetTest-1.py" ) ) ) # save without the classLoader and check its there preset.save( savePath, "basicPresetTest", classLoadable=False ) self.assertTrue( os.path.isfile( os.path.join( savePath, "basicPresetTest.cob" ) ) ) # reload p = IECore.BasicPreset( os.path.join( savePath, "basicPresetTest.cob" ) ) self.assertTrue( p.applicableTo( testObj, testObj.parameters() ) ) self.assertFalse( p.applicableTo( testObj2, testObj2.parameters() ) ) testObj.parameters()["a"].setTypedValue( False ) testObj.parameters()["b"].setTypedValue( 0.0 ) p( testObj, testObj.parameters() ) self.assertEqual( testObj.parameters()["a"].getTypedValue(), True ) self.assertEqual( testObj.parameters()["b"].getTypedValue(), 1.0 ) preset2 = IECore.BasicPreset( testObj, testObj.parameters(), parameters=( testObj.parameters()["a"], ) ) preset2.save( savePath, "basicPresetTest2", classLoadable=False ) #reload p2 = IECore.BasicPreset( os.path.join( savePath, "basicPresetTest2.cob" ) ) self.assertTrue( p2.applicableTo( testObj, testObj.parameters() ) ) self.assertTrue( p2.applicableTo( testObj2, testObj.parameters() ) ) p2( testObj2, testObj2.parameters() ) self.assertEqual( testObj2.parameters()["a"].getTypedValue(), True ) self.assertEqual( testObj2.parameters()["c"].getTypedValue(), 0.0 ) def testClassLoader( self ) : testObj = IECore.Parameterised( "testParameterised1" ) testObj.parameters().addParameters( [ IECore.BoolParameter( "a", "", True ), IECore.FloatParameter( "b", "", 1.0 ), ] ) savePath = os.path.abspath( os.path.join( os.path.dirname( __file__ ), "data", "basicPreset" ) ) preset = IECore.BasicPreset( testObj, testObj.parameters() ) preset.save( savePath, "basicPresetTestClassLoader" ) # make sure that no messages are emitted during loading messageHandler = IECore.CapturingMessageHandler() with messageHandler : loader = IECore.ClassLoader( IECore.SearchPath( savePath ) ) p = loader.load( "basicPresetTestClassLoader" )() self.assertEqual( len( messageHandler.messages ), 0 ) self.assertTrue( isinstance( p, IECore.BasicPreset ) ) p.metadata() def testClasses( self ) : testObj = IECore.Parameterised( "testParameterised1" ) testObj.parameters().addParameters( [ IECore.BoolParameter( "a", "", True ), IECore.ClassParameter( "b", "", "IECORE_OP_PATHS", os.path.join( "maths", "multiply" ), 2 ), ] ) testObj2 = IECore.Parameterised( "testParameterised2" ) testObj2.parameters().addParameters( [ IECore.ClassParameter( "c", "", "IECORE_OP_PATHS" ), ] ) classes1 = testObj.parameters()["b"].getClass( True ) classes2 = testObj2.parameters()["c"].getClass( True ) self.assertNotEqual( classes1[1:], classes2[1:] ) p = IECore.BasicPreset( testObj, testObj.parameters()["b"] ) self.assertTrue( p.applicableTo( testObj, testObj.parameters()["b"] ) ) self.assertFalse( p.applicableTo( testObj, testObj.parameters() ) ) self.assertTrue( p.applicableTo( testObj2, testObj2.parameters()["c"] ) ) p( testObj2, testObj2.parameters()["c"] ) classes1 = testObj.parameters()["b"].getClass( True ) classes2 = testObj2.parameters()["c"].getClass( True ) self.assertEqual( classes1[1:], classes2[1:] ) def testClassVectors( self ) : testObj = IECore.Parameterised( "testParameterised1" ) testObj.parameters().addParameters( [ IECore.BoolParameter( "a", "", True ), IECore.ClassVectorParameter( "b", "", "IECORE_OP_PATHS" ), ] ) testObj.parameters()["b"].setClasses( [ ( "mult", os.path.join( "maths", "multiply" ), 2 ), ( "coIO", "compoundObjectInOut", 1 ), ] ) testObj2 = IECore.Parameterised( "testParameterised2" ) testObj2.parameters().addParameters( [ IECore.ClassVectorParameter( "c", "", "IECORE_OP_PATHS" ), ] ) classes1 = [ c[1:] for c in testObj.parameters()["b"].getClasses( True ) ] classes2 = [ c[1:] for c in testObj2.parameters()["c"].getClasses( True ) ] self.assertNotEqual( classes1, classes2 ) p = IECore.BasicPreset( testObj, testObj.parameters()["b"] ) self.assertTrue( p.applicableTo( testObj, testObj.parameters()["b"] ) ) self.assertFalse( p.applicableTo( testObj, testObj.parameters() ) ) self.assertTrue( p.applicableTo( testObj2, testObj2.parameters()["c"] ) ) p( testObj2, testObj2.parameters()["c"] ) classes1 = [ c[1:] for c in testObj.parameters()["b"].getClasses( True ) ] classes2 = [ c[1:] for c in testObj2.parameters()["c"].getClasses( True ) ] self.assertEqual( classes1, classes2 ) def testCompoundVectorParameter( self ) : p = IECore.Parameterised( "test" ) p.parameters().addParameters( [ IECore.BoolParameter( "a", "", False ), IECore.CompoundVectorParameter( "c", "", members = [ IECore.StringVectorParameter( "s", "", IECore.StringVectorData() ), IECore.BoolVectorParameter( "b", "", IECore.BoolVectorData() ), ] ) ] ) p["c"]["s"].setValue( IECore.StringVectorData( [ "1", "2", "3" ] ) ) p["c"]["b"].setValue( IECore.BoolVectorData( [ True, False, True ] ) ) v = p.parameters().getValue().copy() preset = IECore.BasicPreset( p, p.parameters() ) self.assertTrue( preset.applicableTo( p, p.parameters() ) ) p.parameters().setValue( p.parameters().defaultValue ) self.assertNotEqual( p.parameters().getValue(), v ) preset( p, p.parameters() ) self.assertEqual( p.parameters().getValue(), v ) def tearDown( self ) : savePath = os.path.abspath( os.path.join( os.path.dirname( __file__ ), "data", "basicPreset" ) ) paths = ( os.path.join( savePath, "basicPresetTest" ), os.path.join( savePath, "basicPresetTest.cob" ), os.path.join( savePath, "basicPresetTest2.cob" ), os.path.join( savePath, "basicPresetTestClassLoader" ), ) for p in paths : if os.path.isdir( p ) : shutil.rmtree( p ) elif os.path.isfile( p ) : os.remove( p ) if __name__ == "__main__": unittest.main()
########################################################################## # # Copyright (c) 2010-2012, Image Engine Design Inc. 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 Image Engine Design nor the names of any # other contributors to this software 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 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. # ########################################################################## from __future__ import with_statement import os import sys import shutil import unittest import IECore class TestBasicPreset( unittest.TestCase ) : def testCopy( self ) : testObj = IECore.Parameterised( "testParameterised1" ) testObj.parameters().addParameters( [ IECore.BoolParameter( "a", "", True ), IECore.FloatParameter( "b", "", 1.0 ), ] ) testObj2 = IECore.Parameterised( "testParameterised2" ) testObj2.parameters().addParameters( [ IECore.BoolParameter( "a", "", False ), IECore.FloatParameter( "c", "", 0.0 ), ] ) p = IECore.BasicPreset( testObj, testObj.parameters() ) self.assertTrue( p.applicableTo( testObj, testObj.parameters() ) ) self.assertFalse( p.applicableTo( testObj2, testObj2.parameters() ) ) testObj.parameters()["a"].setTypedValue( False ) testObj.parameters()["b"].setTypedValue( 0.0 ) p( testObj, testObj.parameters() ) self.assertEqual( testObj.parameters()["a"].getTypedValue(), True ) self.assertEqual( testObj.parameters()["b"].getTypedValue(), 1.0 ) p2 = IECore.BasicPreset( testObj, testObj.parameters(), parameters=( testObj.parameters()["a"], ) ) self.assertTrue( p2.applicableTo( testObj, testObj.parameters() ) ) self.assertTrue( p2.applicableTo( testObj2, testObj.parameters() ) ) p2( testObj2, testObj2.parameters() ) self.assertEqual( testObj2.parameters()["a"].getTypedValue(), True ) self.assertEqual( testObj2.parameters()["c"].getTypedValue(), 0.0 ) def testLoad( self ) : testObj = IECore.Parameterised( "testParameterised1" ) testObj.parameters().addParameters( [ IECore.BoolParameter( "a", "", True ), IECore.FloatParameter( "b", "", 1.0 ), ] ) testObj2 = IECore.Parameterised( "testParameterised1" ) testObj2.parameters().addParameters( [ IECore.BoolParameter( "a", "", False ), IECore.FloatParameter( "c", "", 0.0 ), ] ) savePath = os.path.abspath( os.path.join( os.path.dirname( __file__ ), "data", "basicPreset" ) ) messageHandler = IECore.CapturingMessageHandler() with messageHandler : p = IECore.BasicPreset( os.path.join( savePath, "basicPresetLoadTest", "basicPresetLoadTest-1.cob" ) ) self.assertEqual( len( messageHandler.messages ), 0 ) self.assertTrue( p.applicableTo( testObj, testObj.parameters() ) ) self.assertFalse( p.applicableTo( testObj2, testObj2.parameters() ) ) testObj.parameters()["a"].setTypedValue( False ) testObj.parameters()["b"].setTypedValue( 0.0 ) p( testObj, testObj.parameters() ) self.assertEqual( testObj.parameters()["a"].getTypedValue(), True ) self.assertEqual( testObj.parameters()["b"].getTypedValue(), 1.0 ) def testSave( self ) : testObj = IECore.Parameterised( "testParameterised1" ) testObj.parameters().addParameters( [ IECore.BoolParameter( "a", "", True ), IECore.FloatParameter( "b", "", 1.0 ), ] ) testObj2 = IECore.Parameterised( "testParameterised1" ) testObj2.parameters().addParameters( [ IECore.BoolParameter( "a", "", False ), IECore.FloatParameter( "c", "", 0.0 ), ] ) savePath = os.path.abspath( os.path.join( os.path.dirname( __file__ ), "data", "basicPreset" ) ) preset = IECore.BasicPreset( testObj, testObj.parameters() ) # Save for the classLoader and check its there, we test the 'loadability' later... preset.save( savePath, "basicPresetTest" ) self.assertTrue( os.path.isfile( os.path.join( savePath, "basicPresetTest", "basicPresetTest-1.cob" ) ) ) self.assertTrue( os.path.isfile( os.path.join( savePath, "basicPresetTest", "basicPresetTest-1.py" ) ) ) # save without the classLoader and check its there preset.save( savePath, "basicPresetTest", classLoadable=False ) self.assertTrue( os.path.isfile( os.path.join( savePath, "basicPresetTest.cob" ) ) ) # reload p = IECore.BasicPreset( os.path.join( savePath, "basicPresetTest.cob" ) ) self.assertTrue( p.applicableTo( testObj, testObj.parameters() ) ) self.assertFalse( p.applicableTo( testObj2, testObj2.parameters() ) ) testObj.parameters()["a"].setTypedValue( False ) testObj.parameters()["b"].setTypedValue( 0.0 ) p( testObj, testObj.parameters() ) self.assertEqual( testObj.parameters()["a"].getTypedValue(), True ) self.assertEqual( testObj.parameters()["b"].getTypedValue(), 1.0 ) preset2 = IECore.BasicPreset( testObj, testObj.parameters(), parameters=( testObj.parameters()["a"], ) ) preset2.save( savePath, "basicPresetTest2", classLoadable=False ) #reload p2 = IECore.BasicPreset( os.path.join( savePath, "basicPresetTest2.cob" ) ) self.assertTrue( p2.applicableTo( testObj, testObj.parameters() ) ) self.assertTrue( p2.applicableTo( testObj2, testObj.parameters() ) ) p2( testObj2, testObj2.parameters() ) self.assertEqual( testObj2.parameters()["a"].getTypedValue(), True ) self.assertEqual( testObj2.parameters()["c"].getTypedValue(), 0.0 ) def testClassLoader( self ) : testObj = IECore.Parameterised( "testParameterised1" ) testObj.parameters().addParameters( [ IECore.BoolParameter( "a", "", True ), IECore.FloatParameter( "b", "", 1.0 ), ] ) savePath = os.path.abspath( os.path.join( os.path.dirname( __file__ ), "data", "basicPreset" ) ) preset = IECore.BasicPreset( testObj, testObj.parameters() ) preset.save( savePath, "basicPresetTestClassLoader" ) # make sure that no messages are emitted during loading messageHandler = IECore.CapturingMessageHandler() with messageHandler : loader = IECore.ClassLoader( IECore.SearchPath( savePath ) ) p = loader.load( "basicPresetTestClassLoader" )() self.assertEqual( len( messageHandler.messages ), 0 ) self.assertTrue( isinstance( p, IECore.BasicPreset ) ) p.metadata() def testClasses( self ) : testObj = IECore.Parameterised( "testParameterised1" ) testObj.parameters().addParameters( [ IECore.BoolParameter( "a", "", True ), IECore.ClassParameter( "b", "", "IECORE_OP_PATHS", os.path.join( "maths", "multiply" ), 2 ), ] ) testObj2 = IECore.Parameterised( "testParameterised2" ) testObj2.parameters().addParameters( [ IECore.ClassParameter( "c", "", "IECORE_OP_PATHS" ), ] ) classes1 = testObj.parameters()["b"].getClass( True ) classes2 = testObj2.parameters()["c"].getClass( True ) self.assertNotEqual( classes1[1:], classes2[1:] ) p = IECore.BasicPreset( testObj, testObj.parameters()["b"] ) self.assertTrue( p.applicableTo( testObj, testObj.parameters()["b"] ) ) self.assertFalse( p.applicableTo( testObj, testObj.parameters() ) ) self.assertTrue( p.applicableTo( testObj2, testObj2.parameters()["c"] ) ) p( testObj2, testObj2.parameters()["c"] ) classes1 = testObj.parameters()["b"].getClass( True ) classes2 = testObj2.parameters()["c"].getClass( True ) self.assertEqual( classes1[1:], classes2[1:] ) def testClassVectors( self ) : testObj = IECore.Parameterised( "testParameterised1" ) testObj.parameters().addParameters( [ IECore.BoolParameter( "a", "", True ), IECore.ClassVectorParameter( "b", "", "IECORE_OP_PATHS" ), ] ) testObj.parameters()["b"].setClasses( [ ( "mult", os.path.join( "maths", "multiply" ), 2 ), ( "coIO", "compoundObjectInOut", 1 ), ] ) testObj2 = IECore.Parameterised( "testParameterised2" ) testObj2.parameters().addParameters( [ IECore.ClassVectorParameter( "c", "", "IECORE_OP_PATHS" ), ] ) classes1 = [ c[1:] for c in testObj.parameters()["b"].getClasses( True ) ] classes2 = [ c[1:] for c in testObj2.parameters()["c"].getClasses( True ) ] self.assertNotEqual( classes1, classes2 ) p = IECore.BasicPreset( testObj, testObj.parameters()["b"] ) self.assertTrue( p.applicableTo( testObj, testObj.parameters()["b"] ) ) self.assertFalse( p.applicableTo( testObj, testObj.parameters() ) ) self.assertTrue( p.applicableTo( testObj2, testObj2.parameters()["c"] ) ) p( testObj2, testObj2.parameters()["c"] ) classes1 = [ c[1:] for c in testObj.parameters()["b"].getClasses( True ) ] classes2 = [ c[1:] for c in testObj2.parameters()["c"].getClasses( True ) ] self.assertEqual( classes1, classes2 ) def testCompoundVectorParameter( self ) : p = IECore.Parameterised( "test" ) p.parameters().addParameters( [ IECore.BoolParameter( "a", "", False ), IECore.CompoundVectorParameter( "c", "", members = [ IECore.StringVectorParameter( "s", "", IECore.StringVectorData() ), IECore.BoolVectorParameter( "b", "", IECore.BoolVectorData() ), ] ) ] ) p["c"]["s"].setValue( IECore.StringVectorData( [ "1", "2", "3" ] ) ) p["c"]["b"].setValue( IECore.BoolVectorData( [ True, False, True ] ) ) v = p.parameters().getValue().copy() preset = IECore.BasicPreset( p, p.parameters() ) self.assertTrue( preset.applicableTo( p, p.parameters() ) ) p.parameters().setValue( p.parameters().defaultValue ) self.assertNotEqual( p.parameters().getValue(), v ) preset( p, p.parameters() ) self.assertEqual( p.parameters().getValue(), v ) def tearDown( self ) : savePath = os.path.abspath( os.path.join( os.path.dirname( __file__ ), "data", "basicPreset" ) ) paths = ( os.path.join( savePath, "basicPresetTest" ), os.path.join( savePath, "basicPresetTest.cob" ), os.path.join( savePath, "basicPresetTest2.cob" ), os.path.join( savePath, "basicPresetTestClassLoader" ), ) for p in paths : if os.path.isdir( p ) : shutil.rmtree( p ) elif os.path.isfile( p ) : os.remove( p ) if __name__ == "__main__": unittest.main()
en
0.66242
########################################################################## # # Copyright (c) 2010-2012, Image Engine Design Inc. 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 Image Engine Design nor the names of any # other contributors to this software 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 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. # ########################################################################## # Save for the classLoader and check its there, we test the 'loadability' later... # save without the classLoader and check its there # reload #reload # make sure that no messages are emitted during loading
1.20241
1
rlpy/Domains/Pacman.py
imanolarrieta/RL
1
28
<filename>rlpy/Domains/Pacman.py """Pacman game domain.""" from rlpy.Tools import __rlpy_location__ from .Domain import Domain from .PacmanPackage import layout, pacman, game, ghostAgents from .PacmanPackage import graphicsDisplay import numpy as np from copy import deepcopy import os import time __copyright__ = "Copyright 2013, RLPy http://acl.mit.edu/RLPy" __credits__ = ["<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>"] __license__ = "BSD 3-Clause" __author__ = "<NAME>" class Pacman(Domain): """ Pacman domain, which acts as a wrapper for the Pacman implementation from the BerkeleyX/CS188.1x course project 3. **STATE:** The state vector has a series of dimensions: * [2] The x and y coordinates of pacman * [3 * ng] the x and y coordinates as well as the scare time of each ghost ("scare time" is how long the ghost remains scared after consuming a capsule.) * [nf] binary variables indicating if a food is still on the board or not * [nc] binary variables for each capsule indicating if it is still on the board or not *nf* and *nc* are map-dependent, and *ng* can be set as a parameter. Based on above, total dimensionality of state vector is map-dependent, and given by (2 + 3*ng + nf + nc). **ACTIONS:** Move Pacman [up, down, left, right, stay] **REWARD:** See the Berkeley project website below for more info. .. note:: The visualization runs as fast as your CPU will permit; to slow things down so gameplay is actually visible, de-comment time.sleep() in the showDomain() method. **REFERENCE:** This domain is an RLPy wrapper for the implementation from the `BerkeleyX/CS188.1x course project 3 <https://courses.edx.org/courses/BerkeleyX/CS188.1x/2013_Spring/courseware/Week_9/Project_3_Reinforcement/>`_ See the original `source code (zipped) <https://courses.edx.org/static/content-berkeley-cs188x~2013_Spring/projects/reinforcement/reinforcement.zip>`_ For more details of the domain see the original package in the `Domains/PacmanPackage` folder. """ _max_scared_time = 39 actions = ["Stop", "North", "East", "South", "West"] actions_num = 5 episodeCap = 1000 #: location of layouts shipped with rlpy default_layout_dir = os.path.join( __rlpy_location__, "Domains", "PacmanPackage", "layouts") def __init__(self, noise=.1, timeout=30, layoutFile=os.path.join( default_layout_dir, 'trickyClassic.lay'), numGhostAgents=1000): """ layoutFile: filename of the map file noise: with this probability pacman makes a random move instead the one specified by the action """ self.noise = noise # Specifies which Pacman world you want self.layoutFile = layoutFile # Puts the file in line stripped format layout_file_content = self._tryToLoad(self.layoutFile) self.layout = layout.Layout(layout_file_content) # Number of ghosts self.numGhostAgents = numGhostAgents # Intitializes Pacman game self.game_state = pacman.GameState() self.game_rules = pacman.ClassicGameRules(timeout) self.layout_copy = deepcopy(self.layout) self.game_state.data.initialize(self.layout_copy, self.numGhostAgents) self.num_total_food = len(self.layout_copy.food.asList()) self.num_total_capsules = len(self.layout_copy.capsules) self._defaultSettings() self.restartGraphics = None self.timerswitch = False self.savedtimer = None self.gameDisplay = None self._set_statespace_limits() super(Pacman, self).__init__() def _set_statespace_limits(self): # Makes an array of limits for each dimension in the state vector. statespace_limits = [] # adds pacman x, y locations statespace_limits.append([1, self.layout.width - 2]) statespace_limits.append([1, self.layout.height - 2]) # adds ghost x, y locations and scaredTimer (how long they can be # eaten) for ghost in self.game_state.data.agentStates[1:]: statespace_limits.append([1, self.layout.width - 2]) statespace_limits.append([1, self.layout.height - 2]) statespace_limits.append([0, self._max_scared_time]) statespace_limits += [[0, 1]] * ( self.num_total_food + self.num_total_capsules) self.statespace_limits = np.array(statespace_limits, dtype="float") def _set_state(self, s): """ Takes a vector s and sets the internal game state used by the original pacman package. """ # copies most recent state data = self.game_state.data agent_states = data.agentStates # set pacman position agent_states.configuration.pos = (s[0], s[1]) # set ghost position num_ghosts = len(agent_states) - 1 for i in range(1, num_ghosts + 1): part_s = s[(3 * i) - 1:3 * i] agent_states[i].configuration.pos = (part_s[0], part_s[1]) agent_states[i].scaredTimer = part_s[2] # set food and capsules locations s_food = s[(num_ghosts + 1) * 3:] x = 0 y = 0 i = 0 data.capsules = [] for char in str(self.layout_copy): if char == ".": data.food[x][y] = bool(s_food[i]) i += 1 elif char == "o": coord = (x, self.layout_copy.height - y) if s_food[i]: data.capsules.append(coord) i += 1 elif char == "\n": y += 1 x = -1 x += 1 def _get_state(self): """ get the internal game state represented as a numpy array """ data = self.game_state.data agent_states = self.game_state.data.agentStates num_ghosts = len(agent_states) - 1 s = np.zeros( 2 + num_ghosts * 3 + self.num_total_food + self.num_total_capsules) # get pacman position s[:2] = agent_states[0].configuration.pos # import ipdb; ipdb.set_trace() # get ghost info for i in range(num_ghosts): s[2 + i * 3: 2 + i * 3 + 2] = agent_states[i + 1].configuration.pos s[2 + i * 3 + 2] = agent_states[i + 1].scaredTimer # get food and capsules status i = 2 + num_ghosts * 3 x = 0 y = 0 for char in str(self.layout_copy): if char == ".": s[i] = data.food[x][y] i += 1 elif char == "\n": y += 1 x = -1 elif char == "o": coord = (x, self.layout_copy.height - y) if coord in data.capsules: s[i] = 1. i += 1 x += 1 return s state = property(_get_state, _set_state) def showDomain(self, a, s=None): if s is not None: errStr = 'ERROR: In Pacman.py, attempted to pass a state (s)'\ 'to showDomain(); Pacman only supports internal states.'\ 'If you do pass a state parameter, ensure it is set to None.' raise Exception(errStr) s = self.game_state if self.gameDisplay is None: self.gameDisplay = graphicsDisplay.PacmanGraphics() self.gameDisplay.startGraphics(self) self.gameDisplay.drawStaticObjects(s.data) self.gameDisplay.drawAgentObjects(s.data) elif self._cleanup_graphics: self._cleanup_graphics = False self.gameDisplay.removeAllFood() self.gameDisplay.removeAllCapsules() self.gameDisplay.food = self.gameDisplay.drawFood( self.gameDisplay.layout.food) self.gameDisplay.capsules = self.gameDisplay.drawCapsules( self.gameDisplay.layout.capsules) # converts s vector in pacman gamestate instance and updates # the display every time pacman or a ghost moves. # s.data.food is the correct food matrix s.data.layout.food = s.data.food for agent in range(len(s.data.agentStates)): s.data._agentMoved = agent self.gameDisplay.update(s.data) s._foodEaten = None s._capsuleEaten = None # time.sleep(0.1) # Sleep for 0.1 sec def step(self, a): """ Applies actions from outside the Pacman domain to the given state. Internal states accounted for along with scoring and terminal checking. Returns a tuple of form (reward, new state vector, terminal) """ if self.random_state.random_sample() < self.noise: # Random Move a = self.random_state.choice(self.possibleActions()) a = self.actions[a] next_state_p = self.game_state.generateSuccessor(0, a) next_state = next_state_p # pacman performs action "a" in current state object # pacman.PacmanRules.applyAction(self.game_state, a) # pacman.GhostRules.checkDeath(self.game_state, 0) # the ghosts move randomly for i in range(1, len(self.game_state.data.agentStates)): if next_state.isWin() or next_state.isLose(): break ghostOptions = pacman.GhostRules.getLegalActions(next_state, i) # TODO: use domain random stream randomAction_ind = self.random_state.randint(len(ghostOptions)) randomAction = ghostOptions[randomAction_ind] next_state = next_state.generateSuccessor(i, randomAction) # keep track of eaten stuff for graphics (original code assumes # graphics are updated after every agent's move) next_state.data._foodEaten = next_state_p.data._foodEaten next_state.data._capsuleEaten = next_state_p.data._capsuleEaten # scoring in pacman r = next_state.data.score - self.game_state.data.score self.game_state = next_state terminal = self.isTerminal() return r, self._get_state(), terminal, self.possibleActions() def s0(self): """ re-initializes internal states when an episode starts, returns a s vector """ self.game_state = pacman.GameState() self.game_rules = pacman.ClassicGameRules(timeout=30) self.layout_copy = deepcopy(self.layout) self.game = self.game_rules.newGame( self.layout_copy, pacman, self.ghosts, DummyGraphics(), self.beQuiet, catchExceptions=False) self.game_state.data.initialize(self.layout_copy, self.numGhostAgents) self._cleanup_graphics = True return self.state, self.isTerminal(), self.possibleActions() def possibleActions(self): if self.isTerminal(): # somewhat hacky, but should not matter anyway, maybe clean up in # the future return np.array([0]) # makes an array of possible actions pacman can perform at any given # state possibleActions = [] possibleMoves = pacman.GameState.getLegalActions( self.game_state, agentIndex=0) for a in possibleMoves: possibleActions.append(self.actions.index(a)) return np.array(possibleActions) def isTerminal(self): """ Checks whether the game should terminate at the given state. (Terminate for failure, ie eaten by ghost or out of time, and for success, all food on map eaten.) If game should terminate, returns the proper indication to step function. Accounts for scoring changes in terminal states. """ return self.game_state.data._lose or self.game_state.data._win def _defaultSettings(self): self.ghostNum = 2 self.ghosts = [ghostAgents.RandomGhost( game.Agent) for i in range(self.ghostNum)] self.beQuiet = False def _tryToLoad(self, fullname): # used in getLayout function f = open(fullname) grid = [line.strip() for line in f] f.close() return grid class DummyGraphics(object): def initialize(self, *arg, **kwargs): pass def update(self, *arg, **kwargs): pass def finalize(self, *arg, **kwargs): pass
<filename>rlpy/Domains/Pacman.py """Pacman game domain.""" from rlpy.Tools import __rlpy_location__ from .Domain import Domain from .PacmanPackage import layout, pacman, game, ghostAgents from .PacmanPackage import graphicsDisplay import numpy as np from copy import deepcopy import os import time __copyright__ = "Copyright 2013, RLPy http://acl.mit.edu/RLPy" __credits__ = ["<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>"] __license__ = "BSD 3-Clause" __author__ = "<NAME>" class Pacman(Domain): """ Pacman domain, which acts as a wrapper for the Pacman implementation from the BerkeleyX/CS188.1x course project 3. **STATE:** The state vector has a series of dimensions: * [2] The x and y coordinates of pacman * [3 * ng] the x and y coordinates as well as the scare time of each ghost ("scare time" is how long the ghost remains scared after consuming a capsule.) * [nf] binary variables indicating if a food is still on the board or not * [nc] binary variables for each capsule indicating if it is still on the board or not *nf* and *nc* are map-dependent, and *ng* can be set as a parameter. Based on above, total dimensionality of state vector is map-dependent, and given by (2 + 3*ng + nf + nc). **ACTIONS:** Move Pacman [up, down, left, right, stay] **REWARD:** See the Berkeley project website below for more info. .. note:: The visualization runs as fast as your CPU will permit; to slow things down so gameplay is actually visible, de-comment time.sleep() in the showDomain() method. **REFERENCE:** This domain is an RLPy wrapper for the implementation from the `BerkeleyX/CS188.1x course project 3 <https://courses.edx.org/courses/BerkeleyX/CS188.1x/2013_Spring/courseware/Week_9/Project_3_Reinforcement/>`_ See the original `source code (zipped) <https://courses.edx.org/static/content-berkeley-cs188x~2013_Spring/projects/reinforcement/reinforcement.zip>`_ For more details of the domain see the original package in the `Domains/PacmanPackage` folder. """ _max_scared_time = 39 actions = ["Stop", "North", "East", "South", "West"] actions_num = 5 episodeCap = 1000 #: location of layouts shipped with rlpy default_layout_dir = os.path.join( __rlpy_location__, "Domains", "PacmanPackage", "layouts") def __init__(self, noise=.1, timeout=30, layoutFile=os.path.join( default_layout_dir, 'trickyClassic.lay'), numGhostAgents=1000): """ layoutFile: filename of the map file noise: with this probability pacman makes a random move instead the one specified by the action """ self.noise = noise # Specifies which Pacman world you want self.layoutFile = layoutFile # Puts the file in line stripped format layout_file_content = self._tryToLoad(self.layoutFile) self.layout = layout.Layout(layout_file_content) # Number of ghosts self.numGhostAgents = numGhostAgents # Intitializes Pacman game self.game_state = pacman.GameState() self.game_rules = pacman.ClassicGameRules(timeout) self.layout_copy = deepcopy(self.layout) self.game_state.data.initialize(self.layout_copy, self.numGhostAgents) self.num_total_food = len(self.layout_copy.food.asList()) self.num_total_capsules = len(self.layout_copy.capsules) self._defaultSettings() self.restartGraphics = None self.timerswitch = False self.savedtimer = None self.gameDisplay = None self._set_statespace_limits() super(Pacman, self).__init__() def _set_statespace_limits(self): # Makes an array of limits for each dimension in the state vector. statespace_limits = [] # adds pacman x, y locations statespace_limits.append([1, self.layout.width - 2]) statespace_limits.append([1, self.layout.height - 2]) # adds ghost x, y locations and scaredTimer (how long they can be # eaten) for ghost in self.game_state.data.agentStates[1:]: statespace_limits.append([1, self.layout.width - 2]) statespace_limits.append([1, self.layout.height - 2]) statespace_limits.append([0, self._max_scared_time]) statespace_limits += [[0, 1]] * ( self.num_total_food + self.num_total_capsules) self.statespace_limits = np.array(statespace_limits, dtype="float") def _set_state(self, s): """ Takes a vector s and sets the internal game state used by the original pacman package. """ # copies most recent state data = self.game_state.data agent_states = data.agentStates # set pacman position agent_states.configuration.pos = (s[0], s[1]) # set ghost position num_ghosts = len(agent_states) - 1 for i in range(1, num_ghosts + 1): part_s = s[(3 * i) - 1:3 * i] agent_states[i].configuration.pos = (part_s[0], part_s[1]) agent_states[i].scaredTimer = part_s[2] # set food and capsules locations s_food = s[(num_ghosts + 1) * 3:] x = 0 y = 0 i = 0 data.capsules = [] for char in str(self.layout_copy): if char == ".": data.food[x][y] = bool(s_food[i]) i += 1 elif char == "o": coord = (x, self.layout_copy.height - y) if s_food[i]: data.capsules.append(coord) i += 1 elif char == "\n": y += 1 x = -1 x += 1 def _get_state(self): """ get the internal game state represented as a numpy array """ data = self.game_state.data agent_states = self.game_state.data.agentStates num_ghosts = len(agent_states) - 1 s = np.zeros( 2 + num_ghosts * 3 + self.num_total_food + self.num_total_capsules) # get pacman position s[:2] = agent_states[0].configuration.pos # import ipdb; ipdb.set_trace() # get ghost info for i in range(num_ghosts): s[2 + i * 3: 2 + i * 3 + 2] = agent_states[i + 1].configuration.pos s[2 + i * 3 + 2] = agent_states[i + 1].scaredTimer # get food and capsules status i = 2 + num_ghosts * 3 x = 0 y = 0 for char in str(self.layout_copy): if char == ".": s[i] = data.food[x][y] i += 1 elif char == "\n": y += 1 x = -1 elif char == "o": coord = (x, self.layout_copy.height - y) if coord in data.capsules: s[i] = 1. i += 1 x += 1 return s state = property(_get_state, _set_state) def showDomain(self, a, s=None): if s is not None: errStr = 'ERROR: In Pacman.py, attempted to pass a state (s)'\ 'to showDomain(); Pacman only supports internal states.'\ 'If you do pass a state parameter, ensure it is set to None.' raise Exception(errStr) s = self.game_state if self.gameDisplay is None: self.gameDisplay = graphicsDisplay.PacmanGraphics() self.gameDisplay.startGraphics(self) self.gameDisplay.drawStaticObjects(s.data) self.gameDisplay.drawAgentObjects(s.data) elif self._cleanup_graphics: self._cleanup_graphics = False self.gameDisplay.removeAllFood() self.gameDisplay.removeAllCapsules() self.gameDisplay.food = self.gameDisplay.drawFood( self.gameDisplay.layout.food) self.gameDisplay.capsules = self.gameDisplay.drawCapsules( self.gameDisplay.layout.capsules) # converts s vector in pacman gamestate instance and updates # the display every time pacman or a ghost moves. # s.data.food is the correct food matrix s.data.layout.food = s.data.food for agent in range(len(s.data.agentStates)): s.data._agentMoved = agent self.gameDisplay.update(s.data) s._foodEaten = None s._capsuleEaten = None # time.sleep(0.1) # Sleep for 0.1 sec def step(self, a): """ Applies actions from outside the Pacman domain to the given state. Internal states accounted for along with scoring and terminal checking. Returns a tuple of form (reward, new state vector, terminal) """ if self.random_state.random_sample() < self.noise: # Random Move a = self.random_state.choice(self.possibleActions()) a = self.actions[a] next_state_p = self.game_state.generateSuccessor(0, a) next_state = next_state_p # pacman performs action "a" in current state object # pacman.PacmanRules.applyAction(self.game_state, a) # pacman.GhostRules.checkDeath(self.game_state, 0) # the ghosts move randomly for i in range(1, len(self.game_state.data.agentStates)): if next_state.isWin() or next_state.isLose(): break ghostOptions = pacman.GhostRules.getLegalActions(next_state, i) # TODO: use domain random stream randomAction_ind = self.random_state.randint(len(ghostOptions)) randomAction = ghostOptions[randomAction_ind] next_state = next_state.generateSuccessor(i, randomAction) # keep track of eaten stuff for graphics (original code assumes # graphics are updated after every agent's move) next_state.data._foodEaten = next_state_p.data._foodEaten next_state.data._capsuleEaten = next_state_p.data._capsuleEaten # scoring in pacman r = next_state.data.score - self.game_state.data.score self.game_state = next_state terminal = self.isTerminal() return r, self._get_state(), terminal, self.possibleActions() def s0(self): """ re-initializes internal states when an episode starts, returns a s vector """ self.game_state = pacman.GameState() self.game_rules = pacman.ClassicGameRules(timeout=30) self.layout_copy = deepcopy(self.layout) self.game = self.game_rules.newGame( self.layout_copy, pacman, self.ghosts, DummyGraphics(), self.beQuiet, catchExceptions=False) self.game_state.data.initialize(self.layout_copy, self.numGhostAgents) self._cleanup_graphics = True return self.state, self.isTerminal(), self.possibleActions() def possibleActions(self): if self.isTerminal(): # somewhat hacky, but should not matter anyway, maybe clean up in # the future return np.array([0]) # makes an array of possible actions pacman can perform at any given # state possibleActions = [] possibleMoves = pacman.GameState.getLegalActions( self.game_state, agentIndex=0) for a in possibleMoves: possibleActions.append(self.actions.index(a)) return np.array(possibleActions) def isTerminal(self): """ Checks whether the game should terminate at the given state. (Terminate for failure, ie eaten by ghost or out of time, and for success, all food on map eaten.) If game should terminate, returns the proper indication to step function. Accounts for scoring changes in terminal states. """ return self.game_state.data._lose or self.game_state.data._win def _defaultSettings(self): self.ghostNum = 2 self.ghosts = [ghostAgents.RandomGhost( game.Agent) for i in range(self.ghostNum)] self.beQuiet = False def _tryToLoad(self, fullname): # used in getLayout function f = open(fullname) grid = [line.strip() for line in f] f.close() return grid class DummyGraphics(object): def initialize(self, *arg, **kwargs): pass def update(self, *arg, **kwargs): pass def finalize(self, *arg, **kwargs): pass
en
0.814277
Pacman game domain. Pacman domain, which acts as a wrapper for the Pacman implementation from the BerkeleyX/CS188.1x course project 3. **STATE:** The state vector has a series of dimensions: * [2] The x and y coordinates of pacman * [3 * ng] the x and y coordinates as well as the scare time of each ghost ("scare time" is how long the ghost remains scared after consuming a capsule.) * [nf] binary variables indicating if a food is still on the board or not * [nc] binary variables for each capsule indicating if it is still on the board or not *nf* and *nc* are map-dependent, and *ng* can be set as a parameter. Based on above, total dimensionality of state vector is map-dependent, and given by (2 + 3*ng + nf + nc). **ACTIONS:** Move Pacman [up, down, left, right, stay] **REWARD:** See the Berkeley project website below for more info. .. note:: The visualization runs as fast as your CPU will permit; to slow things down so gameplay is actually visible, de-comment time.sleep() in the showDomain() method. **REFERENCE:** This domain is an RLPy wrapper for the implementation from the `BerkeleyX/CS188.1x course project 3 <https://courses.edx.org/courses/BerkeleyX/CS188.1x/2013_Spring/courseware/Week_9/Project_3_Reinforcement/>`_ See the original `source code (zipped) <https://courses.edx.org/static/content-berkeley-cs188x~2013_Spring/projects/reinforcement/reinforcement.zip>`_ For more details of the domain see the original package in the `Domains/PacmanPackage` folder. #: location of layouts shipped with rlpy layoutFile: filename of the map file noise: with this probability pacman makes a random move instead the one specified by the action # Specifies which Pacman world you want # Puts the file in line stripped format # Number of ghosts # Intitializes Pacman game # Makes an array of limits for each dimension in the state vector. # adds pacman x, y locations # adds ghost x, y locations and scaredTimer (how long they can be # eaten) Takes a vector s and sets the internal game state used by the original pacman package. # copies most recent state # set pacman position # set ghost position # set food and capsules locations get the internal game state represented as a numpy array # get pacman position # import ipdb; ipdb.set_trace() # get ghost info # get food and capsules status # converts s vector in pacman gamestate instance and updates # the display every time pacman or a ghost moves. # s.data.food is the correct food matrix # time.sleep(0.1) # Sleep for 0.1 sec Applies actions from outside the Pacman domain to the given state. Internal states accounted for along with scoring and terminal checking. Returns a tuple of form (reward, new state vector, terminal) # Random Move # pacman performs action "a" in current state object # pacman.PacmanRules.applyAction(self.game_state, a) # pacman.GhostRules.checkDeath(self.game_state, 0) # the ghosts move randomly # TODO: use domain random stream # keep track of eaten stuff for graphics (original code assumes # graphics are updated after every agent's move) # scoring in pacman re-initializes internal states when an episode starts, returns a s vector # somewhat hacky, but should not matter anyway, maybe clean up in # the future # makes an array of possible actions pacman can perform at any given # state Checks whether the game should terminate at the given state. (Terminate for failure, ie eaten by ghost or out of time, and for success, all food on map eaten.) If game should terminate, returns the proper indication to step function. Accounts for scoring changes in terminal states. # used in getLayout function
2.679938
3
core/src/zeit/cms/settings/interfaces.py
rickdg/vivi
5
29
from zeit.cms.i18n import MessageFactory as _ import zope.interface import zope.schema class IGlobalSettings(zope.interface.Interface): """Global CMS settings.""" default_year = zope.schema.Int( title=_("Default year"), min=1900, max=2100) default_volume = zope.schema.Int( title=_("Default volume"), min=1, max=54) def get_working_directory(template): """Return the collection which is the main working directory. template: Template which will be filled with year and volume. In ``template`` the placeholders $year and $volume will be replaced. Example: 'online/$year/$volume/foo' If the respective collection does not exist, it will be created before returning it. """
from zeit.cms.i18n import MessageFactory as _ import zope.interface import zope.schema class IGlobalSettings(zope.interface.Interface): """Global CMS settings.""" default_year = zope.schema.Int( title=_("Default year"), min=1900, max=2100) default_volume = zope.schema.Int( title=_("Default volume"), min=1, max=54) def get_working_directory(template): """Return the collection which is the main working directory. template: Template which will be filled with year and volume. In ``template`` the placeholders $year and $volume will be replaced. Example: 'online/$year/$volume/foo' If the respective collection does not exist, it will be created before returning it. """
en
0.865563
Global CMS settings. Return the collection which is the main working directory. template: Template which will be filled with year and volume. In ``template`` the placeholders $year and $volume will be replaced. Example: 'online/$year/$volume/foo' If the respective collection does not exist, it will be created before returning it.
2.142765
2
abc/abc165/abc165e.py
c-yan/atcoder
1
30
<filename>abc/abc165/abc165e.py N, M = map(int, input().split()) for i in range(1, M + 1): if i % 2 == 1: j = (i - 1) // 2 print(1 + j, M + 1 - j) else: j = (i - 2) // 2 print(M + 2 + j, 2 * M + 1 - j)
<filename>abc/abc165/abc165e.py N, M = map(int, input().split()) for i in range(1, M + 1): if i % 2 == 1: j = (i - 1) // 2 print(1 + j, M + 1 - j) else: j = (i - 2) // 2 print(M + 2 + j, 2 * M + 1 - j)
none
1
2.958316
3
setup.py
giggslam/python-messengerbot-sdk
23
31
<reponame>giggslam/python-messengerbot-sdk<filename>setup.py #!/usr/bin/env python # -*- coding: utf-8 -*- # 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 sys from setuptools import setup from setuptools.command.test import test as TestCommand __version__ = '' with open('facebookbot/__about__.py', 'r') as fd: reg = re.compile(r'__version__ = [\'"]([^\'"]*)[\'"]') for line in fd: m = reg.match(line) if m: __version__ = m.group(1) break def _requirements(): with open('requirements.txt', 'r') as fd: return [name.strip() for name in fd.readlines()] with open('README.rst', 'r') as fd: long_description = fd.read() setup( name="fbsdk", version=__version__, author="<NAME>", author_email="<EMAIL>", maintainer="<NAME>", maintainer_email="<EMAIL>", url="https://github.com/boompieman/fbsdk", description="Facebook Messaging API SDK for Python", long_description=long_description, license='Apache License 2.0', packages=[ "facebookbot", "facebookbot.models" ], install_requires=_requirements(), classifiers=[ "Development Status :: 5 - Production/Stable", "License :: OSI Approved :: Apache Software License", "Intended Audience :: Developers", "Programming Language :: Python :: 3", "Topic :: Software Development" ] )
#!/usr/bin/env python # -*- coding: utf-8 -*- # 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 sys from setuptools import setup from setuptools.command.test import test as TestCommand __version__ = '' with open('facebookbot/__about__.py', 'r') as fd: reg = re.compile(r'__version__ = [\'"]([^\'"]*)[\'"]') for line in fd: m = reg.match(line) if m: __version__ = m.group(1) break def _requirements(): with open('requirements.txt', 'r') as fd: return [name.strip() for name in fd.readlines()] with open('README.rst', 'r') as fd: long_description = fd.read() setup( name="fbsdk", version=__version__, author="<NAME>", author_email="<EMAIL>", maintainer="<NAME>", maintainer_email="<EMAIL>", url="https://github.com/boompieman/fbsdk", description="Facebook Messaging API SDK for Python", long_description=long_description, license='Apache License 2.0', packages=[ "facebookbot", "facebookbot.models" ], install_requires=_requirements(), classifiers=[ "Development Status :: 5 - Production/Stable", "License :: OSI Approved :: Apache Software License", "Intended Audience :: Developers", "Programming Language :: Python :: 3", "Topic :: Software Development" ] )
en
0.839721
#!/usr/bin/env python # -*- coding: utf-8 -*- # 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.
1.686884
2
src/transformers/models/mmbt/modeling_mmbt.py
MaximovaIrina/transformers
1
32
<gh_stars>1-10 # coding=utf-8 # Copyright (c) Facebook, Inc. and its affiliates. # Copyright (c) HuggingFace Inc. team. # # 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. """PyTorch MMBT model. """ import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from ...file_utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings from ...modeling_outputs import BaseModelOutputWithPooling, SequenceClassifierOutput from ...modeling_utils import ModuleUtilsMixin from ...utils import logging logger = logging.get_logger(__name__) _CONFIG_FOR_DOC = "MMBTConfig" class ModalEmbeddings(nn.Module): """Generic Modal Embeddings which takes in an encoder, and a transformer embedding.""" def __init__(self, config, encoder, embeddings): super().__init__() self.config = config self.encoder = encoder self.proj_embeddings = nn.Linear(config.modal_hidden_size, config.hidden_size) self.position_embeddings = embeddings.position_embeddings self.token_type_embeddings = embeddings.token_type_embeddings self.word_embeddings = embeddings.word_embeddings self.LayerNorm = embeddings.LayerNorm self.dropout = nn.Dropout(p=config.hidden_dropout_prob) def forward(self, input_modal, start_token=None, end_token=None, position_ids=None, token_type_ids=None): token_embeddings = self.proj_embeddings(self.encoder(input_modal)) seq_length = token_embeddings.size(1) if start_token is not None: start_token_embeds = self.word_embeddings(start_token) seq_length += 1 token_embeddings = torch.cat([start_token_embeds.unsqueeze(1), token_embeddings], dim=1) if end_token is not None: end_token_embeds = self.word_embeddings(end_token) seq_length += 1 token_embeddings = torch.cat([token_embeddings, end_token_embeds.unsqueeze(1)], dim=1) if position_ids is None: position_ids = torch.arange(seq_length, dtype=torch.long, device=input_modal.device) position_ids = position_ids.unsqueeze(0).expand(input_modal.size(0), seq_length) if token_type_ids is None: token_type_ids = torch.zeros( (input_modal.size(0), seq_length), dtype=torch.long, device=input_modal.device ) position_embeddings = self.position_embeddings(position_ids) token_type_embeddings = self.token_type_embeddings(token_type_ids) embeddings = token_embeddings + position_embeddings + token_type_embeddings embeddings = self.LayerNorm(embeddings) embeddings = self.dropout(embeddings) return embeddings MMBT_START_DOCSTRING = r""" MMBT model was proposed in [Supervised Multimodal Bitransformers for Classifying Images and Text](https://github.com/facebookresearch/mmbt) by <NAME>, <NAME>, <NAME>, <NAME>. It's a supervised multimodal bitransformer model that fuses information from text and other image encoders, and obtain state-of-the-art performance on various multimodal classification benchmark tasks. This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.) This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`MMBTConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. transformer (:class: *~nn.Module*): A text transformer that is used by MMBT. It should have embeddings, encoder, and pooler attributes. encoder (:class: *~nn.Module*): Encoder for the second modality. It should take in a batch of modal inputs and return k, n dimension embeddings. """ MMBT_INPUTS_DOCSTRING = r""" Args: input_modal (`torch.FloatTensor` of shape `(batch_size, ***)`): The other modality data. It will be the shape that the encoder for that type expects. e.g. With an Image Encoder, the shape would be (batch_size, channels, height, width) input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. It does not expect [CLS] token to be added as it's appended to the end of other modality embeddings. Indices can be obtained using [`BertTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) modal_start_tokens (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Optional start token to be added to Other Modality Embedding. [CLS] Most commonly used for classification tasks. modal_end_tokens (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Optional end token to be added to Other Modality Embedding. [SEP] Most commonly used. attention_mask (*optional*) `torch.FloatTensor` of shape `(batch_size, sequence_length)`: Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) token_type_ids (*optional*) `torch.LongTensor` of shape `(batch_size, sequence_length)`: Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`: - 0 corresponds to a *sentence A* token, - 1 corresponds to a *sentence B* token. [What are token type IDs?](../glossary#token-type-ids) modal_token_type_ids (*optional*) `torch.LongTensor` of shape `(batch_size, modal_sequence_length)`: Segment token indices to indicate different portions of the non-text modality. The embeddings from these tokens will be summed with the respective token embeddings for the non-text modality. position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.max_position_embeddings - 1]`. [What are position IDs?](../glossary#position-ids) modal_position_ids (`torch.LongTensor` of shape `(batch_size, modal_sequence_length)`, *optional*): Indices of positions of each input sequence tokens in the position embeddings for the non-text modality. Selected in the range `[0, config.max_position_embeddings - 1]`. [What are position IDs?](../glossary#position-ids) head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*): Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`: - 1 indicates the head is **not masked**, - 0 indicates the head is **masked**. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, embedding_dim)`, *optional*): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix. encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if the model is configured as a decoder. encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( "The bare MMBT Model outputting raw hidden-states without any specific head on top.", MMBT_START_DOCSTRING, ) class MMBTModel(nn.Module, ModuleUtilsMixin): def __init__(self, config, transformer, encoder): super().__init__() self.config = config self.transformer = transformer self.modal_encoder = ModalEmbeddings(config, encoder, transformer.embeddings) @add_start_docstrings_to_model_forward(MMBT_INPUTS_DOCSTRING) @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=_CONFIG_FOR_DOC) def forward( self, input_modal, input_ids=None, modal_start_tokens=None, modal_end_tokens=None, attention_mask=None, token_type_ids=None, modal_token_type_ids=None, position_ids=None, modal_position_ids=None, head_mask=None, inputs_embeds=None, encoder_hidden_states=None, encoder_attention_mask=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" Returns: Examples:: # For example purposes. Not runnable. transformer = BertModel.from_pretrained('bert-base-uncased') encoder = ImageEncoder(args) mmbt = MMBTModel(config, transformer, encoder) """ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") elif input_ids is not None: input_txt_shape = input_ids.size() elif inputs_embeds is not None: input_txt_shape = inputs_embeds.size()[:-1] else: raise ValueError("You have to specify either input_ids or inputs_embeds") device = input_ids.device if input_ids is not None else inputs_embeds.device modal_embeddings = self.modal_encoder( input_modal, start_token=modal_start_tokens, end_token=modal_end_tokens, position_ids=modal_position_ids, token_type_ids=modal_token_type_ids, ) input_modal_shape = modal_embeddings.size()[:-1] if token_type_ids is None: token_type_ids = torch.ones(input_txt_shape, dtype=torch.long, device=device) txt_embeddings = self.transformer.embeddings( input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds ) embedding_output = torch.cat([modal_embeddings, txt_embeddings], 1) input_shape = embedding_output.size()[:-1] if attention_mask is None: attention_mask = torch.ones(input_shape, device=device) else: attention_mask = torch.cat( [torch.ones(input_modal_shape, device=device, dtype=torch.long), attention_mask], dim=1 ) if encoder_attention_mask is None: encoder_attention_mask = torch.ones(input_shape, device=device) else: encoder_attention_mask = torch.cat( [torch.ones(input_modal_shape, device=device), encoder_attention_mask], dim=1 ) extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape, self.device) encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask) head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers) encoder_outputs = self.transformer.encoder( embedding_output, attention_mask=extended_attention_mask, head_mask=head_mask, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_extended_attention_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output = encoder_outputs[0] pooled_output = self.transformer.pooler(sequence_output) if not return_dict: return (sequence_output, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPooling( last_hidden_state=sequence_output, pooler_output=pooled_output, hidden_states=encoder_outputs.hidden_states, attentions=encoder_outputs.attentions, ) def get_input_embeddings(self): return self.embeddings.word_embeddings def set_input_embeddings(self, value): self.embeddings.word_embeddings = value @add_start_docstrings( """ MMBT Model with a sequence classification/regression head on top (a linear layer on top of the pooled output) """, MMBT_START_DOCSTRING, MMBT_INPUTS_DOCSTRING, ) class MMBTForClassification(nn.Module): r""" **labels**: (*optional*) `torch.LongTensor` of shape `(batch_size,)`: Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels > 1` a classification loss is computed (Cross-Entropy). Returns: *Tuple* comprising various elements depending on the configuration (config) and inputs: **loss**: (*optional*, returned when `labels` is provided) `torch.FloatTensor` of shape `(1,)`: Classification (or regression if config.num_labels==1) loss. **logits**: `torch.FloatTensor` of shape `(batch_size, config.num_labels)` Classification (or regression if config.num_labels==1) scores (before SoftMax). **hidden_states**: (*optional*, returned when `output_hidden_states=True`) list of `torch.FloatTensor` (one for the output of each layer + the output of the embeddings) of shape `(batch_size, sequence_length, hidden_size)`: Hidden-states of the model at the output of each layer plus the initial embedding outputs. **attentions**: (*optional*, returned when `output_attentions=True`) list of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`: Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. Examples: ```python # For example purposes. Not runnable. transformer = BertModel.from_pretrained('bert-base-uncased') encoder = ImageEncoder(args) model = MMBTForClassification(config, transformer, encoder) outputs = model(input_modal, input_ids, labels=labels) loss, logits = outputs[:2] ```""" def __init__(self, config, transformer, encoder): super().__init__() self.num_labels = config.num_labels self.mmbt = MMBTModel(config, transformer, encoder) self.dropout = nn.Dropout(config.hidden_dropout_prob) self.classifier = nn.Linear(config.hidden_size, config.num_labels) def forward( self, input_modal, input_ids=None, modal_start_tokens=None, modal_end_tokens=None, attention_mask=None, token_type_ids=None, modal_token_type_ids=None, position_ids=None, modal_position_ids=None, head_mask=None, inputs_embeds=None, labels=None, return_dict=None, ): return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.mmbt( input_modal=input_modal, input_ids=input_ids, modal_start_tokens=modal_start_tokens, modal_end_tokens=modal_end_tokens, attention_mask=attention_mask, token_type_ids=token_type_ids, modal_token_type_ids=modal_token_type_ids, position_ids=position_ids, modal_position_ids=modal_position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, return_dict=return_dict, ) pooled_output = outputs[1] pooled_output = self.dropout(pooled_output) logits = self.classifier(pooled_output) loss = None if labels is not None: if self.num_labels == 1: # We are doing regression loss_fct = MSELoss() loss = loss_fct(logits.view(-1), labels.view(-1)) else: loss_fct = CrossEntropyLoss() loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) if not return_dict: output = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return SequenceClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, )
# coding=utf-8 # Copyright (c) Facebook, Inc. and its affiliates. # Copyright (c) HuggingFace Inc. team. # # 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. """PyTorch MMBT model. """ import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from ...file_utils import add_start_docstrings, add_start_docstrings_to_model_forward, replace_return_docstrings from ...modeling_outputs import BaseModelOutputWithPooling, SequenceClassifierOutput from ...modeling_utils import ModuleUtilsMixin from ...utils import logging logger = logging.get_logger(__name__) _CONFIG_FOR_DOC = "MMBTConfig" class ModalEmbeddings(nn.Module): """Generic Modal Embeddings which takes in an encoder, and a transformer embedding.""" def __init__(self, config, encoder, embeddings): super().__init__() self.config = config self.encoder = encoder self.proj_embeddings = nn.Linear(config.modal_hidden_size, config.hidden_size) self.position_embeddings = embeddings.position_embeddings self.token_type_embeddings = embeddings.token_type_embeddings self.word_embeddings = embeddings.word_embeddings self.LayerNorm = embeddings.LayerNorm self.dropout = nn.Dropout(p=config.hidden_dropout_prob) def forward(self, input_modal, start_token=None, end_token=None, position_ids=None, token_type_ids=None): token_embeddings = self.proj_embeddings(self.encoder(input_modal)) seq_length = token_embeddings.size(1) if start_token is not None: start_token_embeds = self.word_embeddings(start_token) seq_length += 1 token_embeddings = torch.cat([start_token_embeds.unsqueeze(1), token_embeddings], dim=1) if end_token is not None: end_token_embeds = self.word_embeddings(end_token) seq_length += 1 token_embeddings = torch.cat([token_embeddings, end_token_embeds.unsqueeze(1)], dim=1) if position_ids is None: position_ids = torch.arange(seq_length, dtype=torch.long, device=input_modal.device) position_ids = position_ids.unsqueeze(0).expand(input_modal.size(0), seq_length) if token_type_ids is None: token_type_ids = torch.zeros( (input_modal.size(0), seq_length), dtype=torch.long, device=input_modal.device ) position_embeddings = self.position_embeddings(position_ids) token_type_embeddings = self.token_type_embeddings(token_type_ids) embeddings = token_embeddings + position_embeddings + token_type_embeddings embeddings = self.LayerNorm(embeddings) embeddings = self.dropout(embeddings) return embeddings MMBT_START_DOCSTRING = r""" MMBT model was proposed in [Supervised Multimodal Bitransformers for Classifying Images and Text](https://github.com/facebookresearch/mmbt) by <NAME>, <NAME>, <NAME>, <NAME>. It's a supervised multimodal bitransformer model that fuses information from text and other image encoders, and obtain state-of-the-art performance on various multimodal classification benchmark tasks. This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.) This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`MMBTConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. transformer (:class: *~nn.Module*): A text transformer that is used by MMBT. It should have embeddings, encoder, and pooler attributes. encoder (:class: *~nn.Module*): Encoder for the second modality. It should take in a batch of modal inputs and return k, n dimension embeddings. """ MMBT_INPUTS_DOCSTRING = r""" Args: input_modal (`torch.FloatTensor` of shape `(batch_size, ***)`): The other modality data. It will be the shape that the encoder for that type expects. e.g. With an Image Encoder, the shape would be (batch_size, channels, height, width) input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. It does not expect [CLS] token to be added as it's appended to the end of other modality embeddings. Indices can be obtained using [`BertTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) modal_start_tokens (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Optional start token to be added to Other Modality Embedding. [CLS] Most commonly used for classification tasks. modal_end_tokens (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Optional end token to be added to Other Modality Embedding. [SEP] Most commonly used. attention_mask (*optional*) `torch.FloatTensor` of shape `(batch_size, sequence_length)`: Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) token_type_ids (*optional*) `torch.LongTensor` of shape `(batch_size, sequence_length)`: Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`: - 0 corresponds to a *sentence A* token, - 1 corresponds to a *sentence B* token. [What are token type IDs?](../glossary#token-type-ids) modal_token_type_ids (*optional*) `torch.LongTensor` of shape `(batch_size, modal_sequence_length)`: Segment token indices to indicate different portions of the non-text modality. The embeddings from these tokens will be summed with the respective token embeddings for the non-text modality. position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.max_position_embeddings - 1]`. [What are position IDs?](../glossary#position-ids) modal_position_ids (`torch.LongTensor` of shape `(batch_size, modal_sequence_length)`, *optional*): Indices of positions of each input sequence tokens in the position embeddings for the non-text modality. Selected in the range `[0, config.max_position_embeddings - 1]`. [What are position IDs?](../glossary#position-ids) head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*): Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`: - 1 indicates the head is **not masked**, - 0 indicates the head is **masked**. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, embedding_dim)`, *optional*): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix. encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if the model is configured as a decoder. encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( "The bare MMBT Model outputting raw hidden-states without any specific head on top.", MMBT_START_DOCSTRING, ) class MMBTModel(nn.Module, ModuleUtilsMixin): def __init__(self, config, transformer, encoder): super().__init__() self.config = config self.transformer = transformer self.modal_encoder = ModalEmbeddings(config, encoder, transformer.embeddings) @add_start_docstrings_to_model_forward(MMBT_INPUTS_DOCSTRING) @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=_CONFIG_FOR_DOC) def forward( self, input_modal, input_ids=None, modal_start_tokens=None, modal_end_tokens=None, attention_mask=None, token_type_ids=None, modal_token_type_ids=None, position_ids=None, modal_position_ids=None, head_mask=None, inputs_embeds=None, encoder_hidden_states=None, encoder_attention_mask=None, output_attentions=None, output_hidden_states=None, return_dict=None, ): r""" Returns: Examples:: # For example purposes. Not runnable. transformer = BertModel.from_pretrained('bert-base-uncased') encoder = ImageEncoder(args) mmbt = MMBTModel(config, transformer, encoder) """ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = return_dict if return_dict is not None else self.config.use_return_dict if input_ids is not None and inputs_embeds is not None: raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") elif input_ids is not None: input_txt_shape = input_ids.size() elif inputs_embeds is not None: input_txt_shape = inputs_embeds.size()[:-1] else: raise ValueError("You have to specify either input_ids or inputs_embeds") device = input_ids.device if input_ids is not None else inputs_embeds.device modal_embeddings = self.modal_encoder( input_modal, start_token=modal_start_tokens, end_token=modal_end_tokens, position_ids=modal_position_ids, token_type_ids=modal_token_type_ids, ) input_modal_shape = modal_embeddings.size()[:-1] if token_type_ids is None: token_type_ids = torch.ones(input_txt_shape, dtype=torch.long, device=device) txt_embeddings = self.transformer.embeddings( input_ids=input_ids, position_ids=position_ids, token_type_ids=token_type_ids, inputs_embeds=inputs_embeds ) embedding_output = torch.cat([modal_embeddings, txt_embeddings], 1) input_shape = embedding_output.size()[:-1] if attention_mask is None: attention_mask = torch.ones(input_shape, device=device) else: attention_mask = torch.cat( [torch.ones(input_modal_shape, device=device, dtype=torch.long), attention_mask], dim=1 ) if encoder_attention_mask is None: encoder_attention_mask = torch.ones(input_shape, device=device) else: encoder_attention_mask = torch.cat( [torch.ones(input_modal_shape, device=device), encoder_attention_mask], dim=1 ) extended_attention_mask = self.get_extended_attention_mask(attention_mask, input_shape, self.device) encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask) head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers) encoder_outputs = self.transformer.encoder( embedding_output, attention_mask=extended_attention_mask, head_mask=head_mask, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_extended_attention_mask, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) sequence_output = encoder_outputs[0] pooled_output = self.transformer.pooler(sequence_output) if not return_dict: return (sequence_output, pooled_output) + encoder_outputs[1:] return BaseModelOutputWithPooling( last_hidden_state=sequence_output, pooler_output=pooled_output, hidden_states=encoder_outputs.hidden_states, attentions=encoder_outputs.attentions, ) def get_input_embeddings(self): return self.embeddings.word_embeddings def set_input_embeddings(self, value): self.embeddings.word_embeddings = value @add_start_docstrings( """ MMBT Model with a sequence classification/regression head on top (a linear layer on top of the pooled output) """, MMBT_START_DOCSTRING, MMBT_INPUTS_DOCSTRING, ) class MMBTForClassification(nn.Module): r""" **labels**: (*optional*) `torch.LongTensor` of shape `(batch_size,)`: Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels > 1` a classification loss is computed (Cross-Entropy). Returns: *Tuple* comprising various elements depending on the configuration (config) and inputs: **loss**: (*optional*, returned when `labels` is provided) `torch.FloatTensor` of shape `(1,)`: Classification (or regression if config.num_labels==1) loss. **logits**: `torch.FloatTensor` of shape `(batch_size, config.num_labels)` Classification (or regression if config.num_labels==1) scores (before SoftMax). **hidden_states**: (*optional*, returned when `output_hidden_states=True`) list of `torch.FloatTensor` (one for the output of each layer + the output of the embeddings) of shape `(batch_size, sequence_length, hidden_size)`: Hidden-states of the model at the output of each layer plus the initial embedding outputs. **attentions**: (*optional*, returned when `output_attentions=True`) list of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`: Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. Examples: ```python # For example purposes. Not runnable. transformer = BertModel.from_pretrained('bert-base-uncased') encoder = ImageEncoder(args) model = MMBTForClassification(config, transformer, encoder) outputs = model(input_modal, input_ids, labels=labels) loss, logits = outputs[:2] ```""" def __init__(self, config, transformer, encoder): super().__init__() self.num_labels = config.num_labels self.mmbt = MMBTModel(config, transformer, encoder) self.dropout = nn.Dropout(config.hidden_dropout_prob) self.classifier = nn.Linear(config.hidden_size, config.num_labels) def forward( self, input_modal, input_ids=None, modal_start_tokens=None, modal_end_tokens=None, attention_mask=None, token_type_ids=None, modal_token_type_ids=None, position_ids=None, modal_position_ids=None, head_mask=None, inputs_embeds=None, labels=None, return_dict=None, ): return_dict = return_dict if return_dict is not None else self.config.use_return_dict outputs = self.mmbt( input_modal=input_modal, input_ids=input_ids, modal_start_tokens=modal_start_tokens, modal_end_tokens=modal_end_tokens, attention_mask=attention_mask, token_type_ids=token_type_ids, modal_token_type_ids=modal_token_type_ids, position_ids=position_ids, modal_position_ids=modal_position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, return_dict=return_dict, ) pooled_output = outputs[1] pooled_output = self.dropout(pooled_output) logits = self.classifier(pooled_output) loss = None if labels is not None: if self.num_labels == 1: # We are doing regression loss_fct = MSELoss() loss = loss_fct(logits.view(-1), labels.view(-1)) else: loss_fct = CrossEntropyLoss() loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) if not return_dict: output = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return SequenceClassifierOutput( loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions, )
en
0.747682
# coding=utf-8 # Copyright (c) Facebook, Inc. and its affiliates. # Copyright (c) HuggingFace Inc. team. # # 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. PyTorch MMBT model. Generic Modal Embeddings which takes in an encoder, and a transformer embedding. MMBT model was proposed in [Supervised Multimodal Bitransformers for Classifying Images and Text](https://github.com/facebookresearch/mmbt) by <NAME>, <NAME>, <NAME>, <NAME>. It's a supervised multimodal bitransformer model that fuses information from text and other image encoders, and obtain state-of-the-art performance on various multimodal classification benchmark tasks. This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.) This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`MMBTConfig`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. transformer (:class: *~nn.Module*): A text transformer that is used by MMBT. It should have embeddings, encoder, and pooler attributes. encoder (:class: *~nn.Module*): Encoder for the second modality. It should take in a batch of modal inputs and return k, n dimension embeddings. Args: input_modal (`torch.FloatTensor` of shape `(batch_size, ***)`): The other modality data. It will be the shape that the encoder for that type expects. e.g. With an Image Encoder, the shape would be (batch_size, channels, height, width) input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. It does not expect [CLS] token to be added as it's appended to the end of other modality embeddings. Indices can be obtained using [`BertTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) modal_start_tokens (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Optional start token to be added to Other Modality Embedding. [CLS] Most commonly used for classification tasks. modal_end_tokens (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Optional end token to be added to Other Modality Embedding. [SEP] Most commonly used. attention_mask (*optional*) `torch.FloatTensor` of shape `(batch_size, sequence_length)`: Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) token_type_ids (*optional*) `torch.LongTensor` of shape `(batch_size, sequence_length)`: Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0, 1]`: - 0 corresponds to a *sentence A* token, - 1 corresponds to a *sentence B* token. [What are token type IDs?](../glossary#token-type-ids) modal_token_type_ids (*optional*) `torch.LongTensor` of shape `(batch_size, modal_sequence_length)`: Segment token indices to indicate different portions of the non-text modality. The embeddings from these tokens will be summed with the respective token embeddings for the non-text modality. position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.max_position_embeddings - 1]`. [What are position IDs?](../glossary#position-ids) modal_position_ids (`torch.LongTensor` of shape `(batch_size, modal_sequence_length)`, *optional*): Indices of positions of each input sequence tokens in the position embeddings for the non-text modality. Selected in the range `[0, config.max_position_embeddings - 1]`. [What are position IDs?](../glossary#position-ids) head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*): Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`: - 1 indicates the head is **not masked**, - 0 indicates the head is **masked**. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, embedding_dim)`, *optional*): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix. encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if the model is configured as a decoder. encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple. Returns: Examples:: # For example purposes. Not runnable. transformer = BertModel.from_pretrained('bert-base-uncased') encoder = ImageEncoder(args) mmbt = MMBTModel(config, transformer, encoder) MMBT Model with a sequence classification/regression head on top (a linear layer on top of the pooled output) **labels**: (*optional*) `torch.LongTensor` of shape `(batch_size,)`: Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels > 1` a classification loss is computed (Cross-Entropy). Returns: *Tuple* comprising various elements depending on the configuration (config) and inputs: **loss**: (*optional*, returned when `labels` is provided) `torch.FloatTensor` of shape `(1,)`: Classification (or regression if config.num_labels==1) loss. **logits**: `torch.FloatTensor` of shape `(batch_size, config.num_labels)` Classification (or regression if config.num_labels==1) scores (before SoftMax). **hidden_states**: (*optional*, returned when `output_hidden_states=True`) list of `torch.FloatTensor` (one for the output of each layer + the output of the embeddings) of shape `(batch_size, sequence_length, hidden_size)`: Hidden-states of the model at the output of each layer plus the initial embedding outputs. **attentions**: (*optional*, returned when `output_attentions=True`) list of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length, sequence_length)`: Attentions weights after the attention softmax, used to compute the weighted average in the self-attention heads. Examples: ```python # For example purposes. Not runnable. transformer = BertModel.from_pretrained('bert-base-uncased') encoder = ImageEncoder(args) model = MMBTForClassification(config, transformer, encoder) outputs = model(input_modal, input_ids, labels=labels) loss, logits = outputs[:2] ``` # We are doing regression
1.912667
2
eth2/beacon/chains/base.py
mhchia/trinity
0
33
<filename>eth2/beacon/chains/base.py from abc import ( ABC, abstractmethod, ) import logging from typing import ( TYPE_CHECKING, Tuple, Type, ) from eth._utils.datatypes import ( Configurable, ) from eth.db.backends.base import ( BaseAtomicDB, ) from eth.exceptions import ( BlockNotFound, ) from eth.validation import ( validate_word, ) from eth_typing import ( Hash32, ) from eth_utils import ( ValidationError, encode_hex, ) from eth2._utils.ssz import ( validate_imported_block_unchanged, ) from eth2.beacon.db.chain import ( BaseBeaconChainDB, BeaconChainDB, ) from eth2.beacon.exceptions import ( BlockClassError, StateMachineNotFound, ) from eth2.beacon.types.blocks import ( BaseBeaconBlock, ) from eth2.beacon.types.states import ( BeaconState, ) from eth2.beacon.typing import ( FromBlockParams, Slot, ) from eth2.beacon.validation import ( validate_slot, ) if TYPE_CHECKING: from eth2.beacon.state_machines.base import ( # noqa: F401 BaseBeaconStateMachine, ) class BaseBeaconChain(Configurable, ABC): """ The base class for all BeaconChain objects """ chaindb = None # type: BaseBeaconChainDB chaindb_class = None # type: Type[BaseBeaconChainDB] sm_configuration = None # type: Tuple[Tuple[Slot, Type[BaseBeaconStateMachine]], ...] chain_id = None # type: int # # Helpers # @classmethod @abstractmethod def get_chaindb_class(cls) -> Type[BaseBeaconChainDB]: pass # # Chain API # @classmethod @abstractmethod def from_genesis(cls, base_db: BaseAtomicDB, genesis_state: BeaconState, genesis_block: BaseBeaconBlock) -> 'BaseBeaconChain': pass # # State Machine API # @classmethod @abstractmethod def get_state_machine_class( cls, block: BaseBeaconBlock) -> Type['BaseBeaconStateMachine']: pass @abstractmethod def get_state_machine(self, at_block: BaseBeaconBlock=None) -> 'BaseBeaconStateMachine': pass @classmethod @abstractmethod def get_state_machine_class_for_block_slot( cls, slot: Slot) -> Type['BaseBeaconStateMachine']: pass # # Block API # @abstractmethod def get_block_class(self, block_root: Hash32) -> Type[BaseBeaconBlock]: pass @abstractmethod def create_block_from_parent(self, parent_block: BaseBeaconBlock, block_params: FromBlockParams) -> BaseBeaconBlock: pass @abstractmethod def get_block_by_root(self, block_root: Hash32) -> BaseBeaconBlock: pass @abstractmethod def get_canonical_head(self) -> BaseBeaconBlock: pass @abstractmethod def get_score(self, block_root: Hash32) -> int: pass @abstractmethod def ensure_block(self, block: BaseBeaconBlock=None) -> BaseBeaconBlock: pass @abstractmethod def get_block(self) -> BaseBeaconBlock: pass @abstractmethod def get_canonical_block_by_slot(self, slot: Slot) -> BaseBeaconBlock: pass @abstractmethod def get_canonical_block_root(self, slot: Slot) -> Hash32: pass @abstractmethod def import_block( self, block: BaseBeaconBlock, perform_validation: bool=True ) -> Tuple[BaseBeaconBlock, Tuple[BaseBeaconBlock, ...], Tuple[BaseBeaconBlock, ...]]: pass class BeaconChain(BaseBeaconChain): """ A Chain is a combination of one or more ``StateMachine`` classes. Each ``StateMachine`` is associated with a range of slots. The Chain class acts as a wrapper around these other StateMachine classes, delegating operations to the appropriate StateMachine depending on the current block slot number. """ logger = logging.getLogger("eth2.beacon.chains.BeaconChain") chaindb_class = BeaconChainDB # type: Type[BaseBeaconChainDB] def __init__(self, base_db: BaseAtomicDB) -> None: if not self.sm_configuration: raise ValueError( "The Chain class cannot be instantiated with an empty `sm_configuration`" ) else: # TODO implment validate_sm_configuration(self.sm_configuration) # validate_sm_configuration(self.sm_configuration) pass self.chaindb = self.get_chaindb_class()(base_db) # # Helpers # @classmethod def get_chaindb_class(cls) -> Type['BaseBeaconChainDB']: if cls.chaindb_class is None: raise AttributeError("`chaindb_class` not set") return cls.chaindb_class # # Chain API # @classmethod def from_genesis(cls, base_db: BaseAtomicDB, genesis_state: BeaconState, genesis_block: BaseBeaconBlock) -> 'BaseBeaconChain': """ Initialize the ``BeaconChain`` from a genesis state. """ sm_class = cls.get_state_machine_class_for_block_slot(genesis_block.slot) if type(genesis_block) != sm_class.block_class: raise BlockClassError( "Given genesis block class: {}, StateMachine.block_class: {}".format( type(genesis_block), sm_class.block_class ) ) chaindb = cls.get_chaindb_class()(db=base_db) chaindb.persist_state(genesis_state) return cls._from_genesis_block(base_db, genesis_block) @classmethod def _from_genesis_block(cls, base_db: BaseAtomicDB, genesis_block: BaseBeaconBlock) -> 'BaseBeaconChain': """ Initialize the ``BeaconChain`` from the genesis block. """ chaindb = cls.get_chaindb_class()(db=base_db) chaindb.persist_block(genesis_block, genesis_block.__class__) return cls(base_db) # # StateMachine API # @classmethod def get_state_machine_class(cls, block: BaseBeaconBlock) -> Type['BaseBeaconStateMachine']: """ Returns the ``StateMachine`` instance for the given block slot number. """ return cls.get_state_machine_class_for_block_slot(block.slot) @classmethod def get_state_machine_class_for_block_slot( cls, slot: Slot) -> Type['BaseBeaconStateMachine']: """ Return the ``StateMachine`` class for the given block slot number. """ if cls.sm_configuration is None: raise AttributeError("Chain classes must define the StateMachines in sm_configuration") validate_slot(slot) for start_slot, sm_class in reversed(cls.sm_configuration): if slot >= start_slot: return sm_class raise StateMachineNotFound("No StateMachine available for block slot: #{0}".format(slot)) def get_state_machine(self, at_block: BaseBeaconBlock=None) -> 'BaseBeaconStateMachine': """ Return the ``StateMachine`` instance for the given block number. """ block = self.ensure_block(at_block) sm_class = self.get_state_machine_class_for_block_slot(block.slot) return sm_class( chaindb=self.chaindb, block=block, ) # # Block API # def get_block_class(self, block_root: Hash32) -> Type[BaseBeaconBlock]: slot = self.chaindb.get_slot_by_root(block_root) sm_class = self.get_state_machine_class_for_block_slot(slot) block_class = sm_class.block_class return block_class def create_block_from_parent(self, parent_block: BaseBeaconBlock, block_params: FromBlockParams) -> BaseBeaconBlock: """ Passthrough helper to the ``StateMachine`` class of the block descending from the given block. """ return self.get_state_machine_class_for_block_slot( slot=parent_block.slot + 1 if block_params.slot is None else block_params.slot, ).create_block_from_parent(parent_block, block_params) def get_block_by_root(self, block_root: Hash32) -> BaseBeaconBlock: """ Return the requested block as specified by block hash. Raise ``BlockNotFound`` if there's no block with the given hash in the db. """ validate_word(block_root, title="Block Hash") block_class = self.get_block_class(block_root) return self.chaindb.get_block_by_root(block_root, block_class) def get_canonical_head(self) -> BaseBeaconBlock: """ Return the block at the canonical chain head. Raise ``CanonicalHeadNotFound`` if there's no head defined for the canonical chain. """ block_root = self.chaindb.get_canonical_head_root() block_class = self.get_block_class(block_root) return self.chaindb.get_block_by_root(block_root, block_class) def get_score(self, block_root: Hash32) -> int: """ Return the score of the block with the given hash. Raise ``BlockNotFound`` if there is no matching black hash. """ return self.chaindb.get_score(block_root) def ensure_block(self, block: BaseBeaconBlock=None) -> BaseBeaconBlock: """ Return ``block`` if it is not ``None``, otherwise return the block of the canonical head. """ if block is None: head = self.get_canonical_head() return self.create_block_from_parent(head, FromBlockParams()) else: return block def get_block(self) -> BaseBeaconBlock: """ Return the current TIP block. """ return self.get_state_machine().block def get_canonical_block_by_slot(self, slot: Slot) -> BaseBeaconBlock: """ Return the block with the given number in the canonical chain. Raise ``BlockNotFound`` if there's no block with the given number in the canonical chain. """ validate_slot(slot) return self.get_block_by_root(self.chaindb.get_canonical_block_root(slot)) def get_canonical_block_root(self, slot: Slot) -> Hash32: """ Return the block hash with the given number in the canonical chain. Raise ``BlockNotFound`` if there's no block with the given number in the canonical chain. """ return self.chaindb.get_canonical_block_root(slot) def import_block( self, block: BaseBeaconBlock, perform_validation: bool=True ) -> Tuple[BaseBeaconBlock, Tuple[BaseBeaconBlock, ...], Tuple[BaseBeaconBlock, ...]]: """ Import a complete block and returns a 3-tuple - the imported block - a tuple of blocks which are now part of the canonical chain. - a tuple of blocks which were canonical and now are no longer canonical. """ try: parent_block = self.get_block_by_root(block.previous_block_root) except BlockNotFound: raise ValidationError( "Attempt to import block #{}. Cannot import block {} before importing " "its parent block at {}".format( block.slot, block.signed_root, block.previous_block_root, ) ) base_block_for_import = self.create_block_from_parent( parent_block, FromBlockParams(), ) state, imported_block = self.get_state_machine(base_block_for_import).import_block(block) # Validate the imported block. if perform_validation: validate_imported_block_unchanged(imported_block, block) # TODO: Now it just persists all state. Should design how to clean up the old state. self.chaindb.persist_state(state) ( new_canonical_blocks, old_canonical_blocks, ) = self.chaindb.persist_block(imported_block, imported_block.__class__) self.logger.debug( 'IMPORTED_BLOCK: slot %s | signed root %s', imported_block.slot, encode_hex(imported_block.signed_root), ) return imported_block, new_canonical_blocks, old_canonical_blocks
<filename>eth2/beacon/chains/base.py from abc import ( ABC, abstractmethod, ) import logging from typing import ( TYPE_CHECKING, Tuple, Type, ) from eth._utils.datatypes import ( Configurable, ) from eth.db.backends.base import ( BaseAtomicDB, ) from eth.exceptions import ( BlockNotFound, ) from eth.validation import ( validate_word, ) from eth_typing import ( Hash32, ) from eth_utils import ( ValidationError, encode_hex, ) from eth2._utils.ssz import ( validate_imported_block_unchanged, ) from eth2.beacon.db.chain import ( BaseBeaconChainDB, BeaconChainDB, ) from eth2.beacon.exceptions import ( BlockClassError, StateMachineNotFound, ) from eth2.beacon.types.blocks import ( BaseBeaconBlock, ) from eth2.beacon.types.states import ( BeaconState, ) from eth2.beacon.typing import ( FromBlockParams, Slot, ) from eth2.beacon.validation import ( validate_slot, ) if TYPE_CHECKING: from eth2.beacon.state_machines.base import ( # noqa: F401 BaseBeaconStateMachine, ) class BaseBeaconChain(Configurable, ABC): """ The base class for all BeaconChain objects """ chaindb = None # type: BaseBeaconChainDB chaindb_class = None # type: Type[BaseBeaconChainDB] sm_configuration = None # type: Tuple[Tuple[Slot, Type[BaseBeaconStateMachine]], ...] chain_id = None # type: int # # Helpers # @classmethod @abstractmethod def get_chaindb_class(cls) -> Type[BaseBeaconChainDB]: pass # # Chain API # @classmethod @abstractmethod def from_genesis(cls, base_db: BaseAtomicDB, genesis_state: BeaconState, genesis_block: BaseBeaconBlock) -> 'BaseBeaconChain': pass # # State Machine API # @classmethod @abstractmethod def get_state_machine_class( cls, block: BaseBeaconBlock) -> Type['BaseBeaconStateMachine']: pass @abstractmethod def get_state_machine(self, at_block: BaseBeaconBlock=None) -> 'BaseBeaconStateMachine': pass @classmethod @abstractmethod def get_state_machine_class_for_block_slot( cls, slot: Slot) -> Type['BaseBeaconStateMachine']: pass # # Block API # @abstractmethod def get_block_class(self, block_root: Hash32) -> Type[BaseBeaconBlock]: pass @abstractmethod def create_block_from_parent(self, parent_block: BaseBeaconBlock, block_params: FromBlockParams) -> BaseBeaconBlock: pass @abstractmethod def get_block_by_root(self, block_root: Hash32) -> BaseBeaconBlock: pass @abstractmethod def get_canonical_head(self) -> BaseBeaconBlock: pass @abstractmethod def get_score(self, block_root: Hash32) -> int: pass @abstractmethod def ensure_block(self, block: BaseBeaconBlock=None) -> BaseBeaconBlock: pass @abstractmethod def get_block(self) -> BaseBeaconBlock: pass @abstractmethod def get_canonical_block_by_slot(self, slot: Slot) -> BaseBeaconBlock: pass @abstractmethod def get_canonical_block_root(self, slot: Slot) -> Hash32: pass @abstractmethod def import_block( self, block: BaseBeaconBlock, perform_validation: bool=True ) -> Tuple[BaseBeaconBlock, Tuple[BaseBeaconBlock, ...], Tuple[BaseBeaconBlock, ...]]: pass class BeaconChain(BaseBeaconChain): """ A Chain is a combination of one or more ``StateMachine`` classes. Each ``StateMachine`` is associated with a range of slots. The Chain class acts as a wrapper around these other StateMachine classes, delegating operations to the appropriate StateMachine depending on the current block slot number. """ logger = logging.getLogger("eth2.beacon.chains.BeaconChain") chaindb_class = BeaconChainDB # type: Type[BaseBeaconChainDB] def __init__(self, base_db: BaseAtomicDB) -> None: if not self.sm_configuration: raise ValueError( "The Chain class cannot be instantiated with an empty `sm_configuration`" ) else: # TODO implment validate_sm_configuration(self.sm_configuration) # validate_sm_configuration(self.sm_configuration) pass self.chaindb = self.get_chaindb_class()(base_db) # # Helpers # @classmethod def get_chaindb_class(cls) -> Type['BaseBeaconChainDB']: if cls.chaindb_class is None: raise AttributeError("`chaindb_class` not set") return cls.chaindb_class # # Chain API # @classmethod def from_genesis(cls, base_db: BaseAtomicDB, genesis_state: BeaconState, genesis_block: BaseBeaconBlock) -> 'BaseBeaconChain': """ Initialize the ``BeaconChain`` from a genesis state. """ sm_class = cls.get_state_machine_class_for_block_slot(genesis_block.slot) if type(genesis_block) != sm_class.block_class: raise BlockClassError( "Given genesis block class: {}, StateMachine.block_class: {}".format( type(genesis_block), sm_class.block_class ) ) chaindb = cls.get_chaindb_class()(db=base_db) chaindb.persist_state(genesis_state) return cls._from_genesis_block(base_db, genesis_block) @classmethod def _from_genesis_block(cls, base_db: BaseAtomicDB, genesis_block: BaseBeaconBlock) -> 'BaseBeaconChain': """ Initialize the ``BeaconChain`` from the genesis block. """ chaindb = cls.get_chaindb_class()(db=base_db) chaindb.persist_block(genesis_block, genesis_block.__class__) return cls(base_db) # # StateMachine API # @classmethod def get_state_machine_class(cls, block: BaseBeaconBlock) -> Type['BaseBeaconStateMachine']: """ Returns the ``StateMachine`` instance for the given block slot number. """ return cls.get_state_machine_class_for_block_slot(block.slot) @classmethod def get_state_machine_class_for_block_slot( cls, slot: Slot) -> Type['BaseBeaconStateMachine']: """ Return the ``StateMachine`` class for the given block slot number. """ if cls.sm_configuration is None: raise AttributeError("Chain classes must define the StateMachines in sm_configuration") validate_slot(slot) for start_slot, sm_class in reversed(cls.sm_configuration): if slot >= start_slot: return sm_class raise StateMachineNotFound("No StateMachine available for block slot: #{0}".format(slot)) def get_state_machine(self, at_block: BaseBeaconBlock=None) -> 'BaseBeaconStateMachine': """ Return the ``StateMachine`` instance for the given block number. """ block = self.ensure_block(at_block) sm_class = self.get_state_machine_class_for_block_slot(block.slot) return sm_class( chaindb=self.chaindb, block=block, ) # # Block API # def get_block_class(self, block_root: Hash32) -> Type[BaseBeaconBlock]: slot = self.chaindb.get_slot_by_root(block_root) sm_class = self.get_state_machine_class_for_block_slot(slot) block_class = sm_class.block_class return block_class def create_block_from_parent(self, parent_block: BaseBeaconBlock, block_params: FromBlockParams) -> BaseBeaconBlock: """ Passthrough helper to the ``StateMachine`` class of the block descending from the given block. """ return self.get_state_machine_class_for_block_slot( slot=parent_block.slot + 1 if block_params.slot is None else block_params.slot, ).create_block_from_parent(parent_block, block_params) def get_block_by_root(self, block_root: Hash32) -> BaseBeaconBlock: """ Return the requested block as specified by block hash. Raise ``BlockNotFound`` if there's no block with the given hash in the db. """ validate_word(block_root, title="Block Hash") block_class = self.get_block_class(block_root) return self.chaindb.get_block_by_root(block_root, block_class) def get_canonical_head(self) -> BaseBeaconBlock: """ Return the block at the canonical chain head. Raise ``CanonicalHeadNotFound`` if there's no head defined for the canonical chain. """ block_root = self.chaindb.get_canonical_head_root() block_class = self.get_block_class(block_root) return self.chaindb.get_block_by_root(block_root, block_class) def get_score(self, block_root: Hash32) -> int: """ Return the score of the block with the given hash. Raise ``BlockNotFound`` if there is no matching black hash. """ return self.chaindb.get_score(block_root) def ensure_block(self, block: BaseBeaconBlock=None) -> BaseBeaconBlock: """ Return ``block`` if it is not ``None``, otherwise return the block of the canonical head. """ if block is None: head = self.get_canonical_head() return self.create_block_from_parent(head, FromBlockParams()) else: return block def get_block(self) -> BaseBeaconBlock: """ Return the current TIP block. """ return self.get_state_machine().block def get_canonical_block_by_slot(self, slot: Slot) -> BaseBeaconBlock: """ Return the block with the given number in the canonical chain. Raise ``BlockNotFound`` if there's no block with the given number in the canonical chain. """ validate_slot(slot) return self.get_block_by_root(self.chaindb.get_canonical_block_root(slot)) def get_canonical_block_root(self, slot: Slot) -> Hash32: """ Return the block hash with the given number in the canonical chain. Raise ``BlockNotFound`` if there's no block with the given number in the canonical chain. """ return self.chaindb.get_canonical_block_root(slot) def import_block( self, block: BaseBeaconBlock, perform_validation: bool=True ) -> Tuple[BaseBeaconBlock, Tuple[BaseBeaconBlock, ...], Tuple[BaseBeaconBlock, ...]]: """ Import a complete block and returns a 3-tuple - the imported block - a tuple of blocks which are now part of the canonical chain. - a tuple of blocks which were canonical and now are no longer canonical. """ try: parent_block = self.get_block_by_root(block.previous_block_root) except BlockNotFound: raise ValidationError( "Attempt to import block #{}. Cannot import block {} before importing " "its parent block at {}".format( block.slot, block.signed_root, block.previous_block_root, ) ) base_block_for_import = self.create_block_from_parent( parent_block, FromBlockParams(), ) state, imported_block = self.get_state_machine(base_block_for_import).import_block(block) # Validate the imported block. if perform_validation: validate_imported_block_unchanged(imported_block, block) # TODO: Now it just persists all state. Should design how to clean up the old state. self.chaindb.persist_state(state) ( new_canonical_blocks, old_canonical_blocks, ) = self.chaindb.persist_block(imported_block, imported_block.__class__) self.logger.debug( 'IMPORTED_BLOCK: slot %s | signed root %s', imported_block.slot, encode_hex(imported_block.signed_root), ) return imported_block, new_canonical_blocks, old_canonical_blocks
en
0.757754
# noqa: F401 The base class for all BeaconChain objects # type: BaseBeaconChainDB # type: Type[BaseBeaconChainDB] # type: Tuple[Tuple[Slot, Type[BaseBeaconStateMachine]], ...] # type: int # # Helpers # # # Chain API # # # State Machine API # # # Block API # A Chain is a combination of one or more ``StateMachine`` classes. Each ``StateMachine`` is associated with a range of slots. The Chain class acts as a wrapper around these other StateMachine classes, delegating operations to the appropriate StateMachine depending on the current block slot number. # type: Type[BaseBeaconChainDB] # TODO implment validate_sm_configuration(self.sm_configuration) # validate_sm_configuration(self.sm_configuration) # # Helpers # # # Chain API # Initialize the ``BeaconChain`` from a genesis state. Initialize the ``BeaconChain`` from the genesis block. # # StateMachine API # Returns the ``StateMachine`` instance for the given block slot number. Return the ``StateMachine`` class for the given block slot number. #{0}".format(slot)) Return the ``StateMachine`` instance for the given block number. # # Block API # Passthrough helper to the ``StateMachine`` class of the block descending from the given block. Return the requested block as specified by block hash. Raise ``BlockNotFound`` if there's no block with the given hash in the db. Return the block at the canonical chain head. Raise ``CanonicalHeadNotFound`` if there's no head defined for the canonical chain. Return the score of the block with the given hash. Raise ``BlockNotFound`` if there is no matching black hash. Return ``block`` if it is not ``None``, otherwise return the block of the canonical head. Return the current TIP block. Return the block with the given number in the canonical chain. Raise ``BlockNotFound`` if there's no block with the given number in the canonical chain. Return the block hash with the given number in the canonical chain. Raise ``BlockNotFound`` if there's no block with the given number in the canonical chain. Import a complete block and returns a 3-tuple - the imported block - a tuple of blocks which are now part of the canonical chain. - a tuple of blocks which were canonical and now are no longer canonical. #{}. Cannot import block {} before importing " # Validate the imported block. # TODO: Now it just persists all state. Should design how to clean up the old state.
2.179573
2
using_paramiko.py
allupramodreddy/cisco_py
0
34
#!/usr/local/bin/python3 import paramiko,time #using as SSH Client client = paramiko.SSHClient() # check dir(client) to find available options. # auto adjust host key verification with yes or no client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # time for connecting to remote Cisco IOS """ Manually taking input addr = input('Provide IP address to connect to: ') user = input('Username: ') pwd = <PASSWORD>('Password: ')""" # Taking input from files f1 = open("devices.txt","r") f2 = open("commands.txt","r") for line in f1: client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) data = line.split(" ") # print(data) addr = data[0] user = data[1] pwd = data[2] f3 = open(addr+".txt","w+") # print(addr +" "+ user +" " +pwd) client.connect(addr,username=user,password=<PASSWORD>,allow_agent=False,look_for_keys=False) # we have to ask for Shell device_access = client.invoke_shell() for line in f2: device_access.send(line) time.sleep(1) output = device_access.recv(55000).decode('ascii') f3.write(output) """ THIS CODE IS FOR SINGLE COMMAND, FOR MULTIPLE COMMANDS CODE BELOW # send command to the device device_access.send("ter len 0\nshow run \n") time.sleep(2) # receive output from the device, convert it to byte-like format and print it print(device_access.recv(550000).decode('ascii')) # We can print the same to a file too with open("csr1000v.txt","w") as f: f.write(device_access.recv(550000).decode('ascii'))"""
#!/usr/local/bin/python3 import paramiko,time #using as SSH Client client = paramiko.SSHClient() # check dir(client) to find available options. # auto adjust host key verification with yes or no client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # time for connecting to remote Cisco IOS """ Manually taking input addr = input('Provide IP address to connect to: ') user = input('Username: ') pwd = <PASSWORD>('Password: ')""" # Taking input from files f1 = open("devices.txt","r") f2 = open("commands.txt","r") for line in f1: client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) data = line.split(" ") # print(data) addr = data[0] user = data[1] pwd = data[2] f3 = open(addr+".txt","w+") # print(addr +" "+ user +" " +pwd) client.connect(addr,username=user,password=<PASSWORD>,allow_agent=False,look_for_keys=False) # we have to ask for Shell device_access = client.invoke_shell() for line in f2: device_access.send(line) time.sleep(1) output = device_access.recv(55000).decode('ascii') f3.write(output) """ THIS CODE IS FOR SINGLE COMMAND, FOR MULTIPLE COMMANDS CODE BELOW # send command to the device device_access.send("ter len 0\nshow run \n") time.sleep(2) # receive output from the device, convert it to byte-like format and print it print(device_access.recv(550000).decode('ascii')) # We can print the same to a file too with open("csr1000v.txt","w") as f: f.write(device_access.recv(550000).decode('ascii'))"""
en
0.776699
#!/usr/local/bin/python3 #using as SSH Client # check dir(client) to find available options. # auto adjust host key verification with yes or no # time for connecting to remote Cisco IOS Manually taking input addr = input('Provide IP address to connect to: ') user = input('Username: ') pwd = <PASSWORD>('Password: ') # Taking input from files # print(data) # print(addr +" "+ user +" " +pwd) # we have to ask for Shell THIS CODE IS FOR SINGLE COMMAND, FOR MULTIPLE COMMANDS CODE BELOW # send command to the device device_access.send("ter len 0\nshow run \n") time.sleep(2) # receive output from the device, convert it to byte-like format and print it print(device_access.recv(550000).decode('ascii')) # We can print the same to a file too with open("csr1000v.txt","w") as f: f.write(device_access.recv(550000).decode('ascii'))
3.07727
3
old/.history/a_20201125192943.py
pscly/bisai1
0
35
# for n in range(400,500): # i = n // 100 # j = n // 10 % 10 # k = n % 10 # if n == i ** 3 + j ** 3 + k ** 3: # print(n) # 第一道题(16) # input("请输入(第一次):") # s1 = input("请输入(第二次):") # l1 = s1.split(' ') # l2 = [] # for i in l1: # if i.isdigit(): # l2.append(int(i)) # for i in l2: # if not (i % 6): # print(i, end=" ") # 第二道题(17) out_l1 = [] def bian_int_list(l1): re_l1 = [] # 返回出去的列表 for i in l1: re_l1.append(i) def jisuan(str_num): he1 = 0 global out_l1 for i in l1(): he1 += int(i)**2 if he1 > int(str_num): out_l1.append(str_num) return None while 1: in_1 = input("请输入数值:") nums_l1 = in_1.split(' ')
# for n in range(400,500): # i = n // 100 # j = n // 10 % 10 # k = n % 10 # if n == i ** 3 + j ** 3 + k ** 3: # print(n) # 第一道题(16) # input("请输入(第一次):") # s1 = input("请输入(第二次):") # l1 = s1.split(' ') # l2 = [] # for i in l1: # if i.isdigit(): # l2.append(int(i)) # for i in l2: # if not (i % 6): # print(i, end=" ") # 第二道题(17) out_l1 = [] def bian_int_list(l1): re_l1 = [] # 返回出去的列表 for i in l1: re_l1.append(i) def jisuan(str_num): he1 = 0 global out_l1 for i in l1(): he1 += int(i)**2 if he1 > int(str_num): out_l1.append(str_num) return None while 1: in_1 = input("请输入数值:") nums_l1 = in_1.split(' ')
zh
0.149161
# for n in range(400,500): # i = n // 100 # j = n // 10 % 10 # k = n % 10 # if n == i ** 3 + j ** 3 + k ** 3: # print(n) # 第一道题(16) # input("请输入(第一次):") # s1 = input("请输入(第二次):") # l1 = s1.split(' ') # l2 = [] # for i in l1: # if i.isdigit(): # l2.append(int(i)) # for i in l2: # if not (i % 6): # print(i, end=" ") # 第二道题(17) # 返回出去的列表
3.174766
3
graphdb/transformer.py
muggat0n/graphdb
2
36
<filename>graphdb/transformer.py<gh_stars>1-10 """ A query transformer is a function that accepts a program and returns a program, plus a priority level. Higher priority transformers are placed closer to the front of the list. We’re ensuring is a function, because we’re going to evaluate it later 31 . We’ll assume there won’t be an enormous number of transformer additions, and walk the list linearly to add a new one. We’ll leave a note in case this assumption turns out to be false — a binary search is much more time-optimal for long lists, but adds a little complexity and doesn’t really speed up short lists. """ class Transformer: def __init__(self): self.T = [] def transform(self, program): return program """ Dagoba.T = [] # transformers (more than meets the eye) """ """ Dagoba.addTransformer = function(fun, priority) { if(typeof fun != 'function') return Dagoba.error('Invalid transformer function') for(var i = 0; i < Dagoba.T.length; i++) # OPT: binary search if(priority > Dagoba.T[i].priority) break Dagoba.T.splice(i, 0, {priority: priority, fun: fun}) } """ """ Dagoba.transform = function(program) { return Dagoba.T.reduce(function(acc, transformer) { return transformer.fun(acc) }, program) } """ """ Dagoba.addAlias = function(newname, oldname, defaults) { defaults = defaults || [] # default arguments for the alias Dagoba.addPipetype(newname, function() {}) # because there's no method catchall in js Dagoba.addTransformer(function(program) { return program.map(function(step) { if(step[0] != newname) return step return [oldname, Dagoba.extend(step[1], defaults)] }) }, 100) # these need to run early, so they get a high priority } """ """ Dagoba.extend = function(list, defaults) { return Object.keys(defaults).reduce(function(acc, key) { if(typeof list[key] != 'undefined') return acc acc[key] = defaults[key] return acc }, list) } """
<filename>graphdb/transformer.py<gh_stars>1-10 """ A query transformer is a function that accepts a program and returns a program, plus a priority level. Higher priority transformers are placed closer to the front of the list. We’re ensuring is a function, because we’re going to evaluate it later 31 . We’ll assume there won’t be an enormous number of transformer additions, and walk the list linearly to add a new one. We’ll leave a note in case this assumption turns out to be false — a binary search is much more time-optimal for long lists, but adds a little complexity and doesn’t really speed up short lists. """ class Transformer: def __init__(self): self.T = [] def transform(self, program): return program """ Dagoba.T = [] # transformers (more than meets the eye) """ """ Dagoba.addTransformer = function(fun, priority) { if(typeof fun != 'function') return Dagoba.error('Invalid transformer function') for(var i = 0; i < Dagoba.T.length; i++) # OPT: binary search if(priority > Dagoba.T[i].priority) break Dagoba.T.splice(i, 0, {priority: priority, fun: fun}) } """ """ Dagoba.transform = function(program) { return Dagoba.T.reduce(function(acc, transformer) { return transformer.fun(acc) }, program) } """ """ Dagoba.addAlias = function(newname, oldname, defaults) { defaults = defaults || [] # default arguments for the alias Dagoba.addPipetype(newname, function() {}) # because there's no method catchall in js Dagoba.addTransformer(function(program) { return program.map(function(step) { if(step[0] != newname) return step return [oldname, Dagoba.extend(step[1], defaults)] }) }, 100) # these need to run early, so they get a high priority } """ """ Dagoba.extend = function(list, defaults) { return Object.keys(defaults).reduce(function(acc, key) { if(typeof list[key] != 'undefined') return acc acc[key] = defaults[key] return acc }, list) } """
en
0.510097
A query transformer is a function that accepts a program and returns a program, plus a priority level. Higher priority transformers are placed closer to the front of the list. We’re ensuring is a function, because we’re going to evaluate it later 31 . We’ll assume there won’t be an enormous number of transformer additions, and walk the list linearly to add a new one. We’ll leave a note in case this assumption turns out to be false — a binary search is much more time-optimal for long lists, but adds a little complexity and doesn’t really speed up short lists. Dagoba.T = [] # transformers (more than meets the eye) Dagoba.addTransformer = function(fun, priority) { if(typeof fun != 'function') return Dagoba.error('Invalid transformer function') for(var i = 0; i < Dagoba.T.length; i++) # OPT: binary search if(priority > Dagoba.T[i].priority) break Dagoba.T.splice(i, 0, {priority: priority, fun: fun}) } Dagoba.transform = function(program) { return Dagoba.T.reduce(function(acc, transformer) { return transformer.fun(acc) }, program) } Dagoba.addAlias = function(newname, oldname, defaults) { defaults = defaults || [] # default arguments for the alias Dagoba.addPipetype(newname, function() {}) # because there's no method catchall in js Dagoba.addTransformer(function(program) { return program.map(function(step) { if(step[0] != newname) return step return [oldname, Dagoba.extend(step[1], defaults)] }) }, 100) # these need to run early, so they get a high priority } Dagoba.extend = function(list, defaults) { return Object.keys(defaults).reduce(function(acc, key) { if(typeof list[key] != 'undefined') return acc acc[key] = defaults[key] return acc }, list) }
3.072441
3
yzcore/templates/project_template/src/const/_job.py
lixuemin13/yz-core
6
37
<filename>yzcore/templates/project_template/src/const/_job.py #!/usr/bin/python3.6.8+ # -*- coding:utf-8 -*- """ @auth: cml @date: 2020-12-2 @desc: ... """ class JobStatus(object): PENDING = 0 # 任务等待执行 STARTED = 100 # 任务执行开始 PROCESS = 110 POLLING = 120 CALLBACK = 130 SUCCESS = 200 # 任务执行成功 RETRY = 300 # 任务重试 FAILURE = 400 # 任务执行失败 REVOKED = 500 # 任务撤销
<filename>yzcore/templates/project_template/src/const/_job.py #!/usr/bin/python3.6.8+ # -*- coding:utf-8 -*- """ @auth: cml @date: 2020-12-2 @desc: ... """ class JobStatus(object): PENDING = 0 # 任务等待执行 STARTED = 100 # 任务执行开始 PROCESS = 110 POLLING = 120 CALLBACK = 130 SUCCESS = 200 # 任务执行成功 RETRY = 300 # 任务重试 FAILURE = 400 # 任务执行失败 REVOKED = 500 # 任务撤销
zh
0.614843
#!/usr/bin/python3.6.8+ # -*- coding:utf-8 -*- @auth: cml @date: 2020-12-2 @desc: ... # 任务等待执行 # 任务执行开始 # 任务执行成功 # 任务重试 # 任务执行失败 # 任务撤销
1.180593
1
pyboleto/html.py
RenanPalmeira/pyboleto
0
38
<gh_stars>0 # -*- coding: utf-8 -*- """ pyboleto.html ~~~~~~~~~~~~~ Classe Responsável por fazer o output do boleto em html. :copyright: © 2012 by <NAME> :license: BSD, see LICENSE for more details. """ import os import string import sys import codecs import base64 from itertools import chain if sys.version_info < (3,): from itertools import izip_longest as zip_longest zip_longest # chamando para evitar erro de nao uso do zip_longest else: from itertools import zip_longest DIGITS = [ ['n', 'n', 'w', 'w', 'n'], ['w', 'n', 'n', 'n', 'w'], ['n', 'w', 'n', 'n', 'w'], ['w', 'w', 'n', 'n', 'n'], ['n', 'n', 'w', 'n', 'w'], ['w', 'n', 'w', 'n', 'n'], ['n', 'w', 'w', 'n', 'n'], ['n', 'n', 'n', 'w', 'w'], ['w', 'n', 'n', 'w', 'n'], ['n', 'w', 'n', 'w', 'n'], ] class BoletoHTML(object): """Geração do Boleto em HTML Esta classe é responsável por imprimir o boleto em HTML. Outras classes podem ser implementadas no futuro com a mesma interface, para fazer output em LaTeX, etc ... Esta classe pode imprimir boletos em formato de carnê (2 boletos por página) ou em formato de folha cheia. :param file_descr: Um arquivo ou *file-like* class. :param landscape: Formato da folha. Usar ``True`` para boleto tipo carnê. """ def __init__(self, file_descr, landscape=False): # Tamanhos em px self.width = 750 self.widthCanhoto = 0 self.fontSizeTitle = 9 self.heightLine = 27 self.fontSizeValue = 12 self.title = 'Boleto bancário' self.fileDescr = file_descr if landscape: raise NotImplementedError('Em desenvolvimento...') else: tpl = string.Template(self._load_template('head.html')) self.html = tpl.substitute(title=self.title, width=self.width, font_size_value=self.fontSizeValue, height_line=self.heightLine, font_size_title=self.fontSizeTitle) def _load_template(self, template): pyboleto_dir = os.path.dirname(os.path.abspath(__file__)) template_path = os.path.join(pyboleto_dir, 'templates', template) with open(template_path, 'r') as tpl: template_content = tpl.read() return template_content def _load_image(self, logo_image): pyboleto_dir = os.path.dirname(os.path.abspath(__file__)) image_path = os.path.join(pyboleto_dir, 'media', logo_image) return image_path def _drawReciboSacado(self, boletoDados): """Imprime o Recibo do Sacado para modelo de página inteira :param boletoDados: Objeto com os dados do boleto a ser preenchido. Deve ser subclasse de :class:`pyboleto.data.BoletoData` :type boletoDados: :class:`pyboleto.data.BoletoData` """ tpl = string.Template(self._load_template('recibo_sacado.html')) tpl_data = {} # Cabeçalho tpl_data['logo_img'] = '' if boletoDados.logo_image: img = codecs.open(self._load_image(boletoDados.logo_image)) aux = img.read() aux = base64.b64encode(aux) img_base64 = 'data:image/jpeg;base64,{0}'.format(aux) tpl_data['logo_img'] = img_base64 tpl_data['codigo_dv_banco'] = boletoDados.codigo_dv_banco # Corpo tpl_data['cedente'] = boletoDados.cedente tpl_data['agencia_conta_cedente'] = boletoDados.agencia_conta_cedente tpl_data['cedente_documento'] = boletoDados.cedente_documento data_vencimento = boletoDados.data_vencimento tpl_data['data_vencimento'] = data_vencimento.strftime('%d/%m/%Y') tpl_data['sacado'] = boletoDados.sacado[0] tpl_data['nosso_numero_format'] = boletoDados.format_nosso_numero() tpl_data['numero_documento'] = boletoDados.numero_documento data_documento = boletoDados.data_documento tpl_data['data_documento'] = data_documento.strftime('%d/%m/%Y') tpl_data['cedente_endereco'] = boletoDados.cedente_endereco valor_doc = self._formataValorParaExibir(boletoDados.valor_documento) tpl_data['valor_documento'] = valor_doc # Demonstrativo tpl_data['demonstrativo'] = '' for dm in boletoDados.demonstrativo: tpl_data['demonstrativo'] += '<p>{0}</p>'.format(dm) self.html += tpl.substitute(tpl_data) def _drawHorizontalCorteLine(self): self.html += '<hr />' def _drawReciboCaixa(self, boletoDados): """Imprime o Recibo do Caixa :param boletoDados: Objeto com os dados do boleto a ser preenchido. Deve ser subclasse de :class:`pyboleto.data.BoletoData` :type boletoDados: :class:`pyboleto.data.BoletoData` """ tpl = string.Template(self._load_template('recibo_caixa.html')) tpl_data = {} # Cabeçalho tpl_data['logo_img'] = '' if boletoDados.logo_image: img = codecs.open(self._load_image(boletoDados.logo_image)) aux = img.read() aux = base64.b64encode(aux) img_base64 = 'data:image/jpeg;base64,{0}'.format(aux) tpl_data['logo_img'] = img_base64 tpl_data['codigo_dv_banco'] = boletoDados.codigo_dv_banco tpl_data['linha_digitavel'] = boletoDados.linha_digitavel # Corpo data_vencimento = boletoDados.data_vencimento tpl_data['data_vencimento'] = data_vencimento.strftime('%d/%m/%Y') # value em unicode em data.py if isinstance(boletoDados.local_pagamento, unicode): tpl_data['local_pagamento'] = boletoDados.local_pagamento.encode ('utf-8') else: tpl_data['local_pagamento'] = boletoDados.local_pagamento tpl_data['cedente'] = boletoDados.cedente tpl_data['agencia_conta_cedente'] = boletoDados.agencia_conta_cedente data_documento = boletoDados.data_documento tpl_data['data_documento'] = data_documento.strftime('%d/%m/%Y') tpl_data['numero_documento'] = boletoDados.numero_documento tpl_data['especie_documento'] = boletoDados.especie_documento tpl_data['aceite'] = boletoDados.aceite data_process = boletoDados.data_processamento tpl_data['data_processamento'] = data_process.strftime('%d/%m/%Y') tpl_data['nosso_numero_format'] = boletoDados.format_nosso_numero() tpl_data['carteira'] = boletoDados.carteira tpl_data['especie'] = boletoDados.especie tpl_data['quantidade'] = boletoDados.quantidade valor = self._formataValorParaExibir(boletoDados.valor) tpl_data['valor'] = valor valor_doc = self._formataValorParaExibir(boletoDados.valor_documento) tpl_data['valor_documento'] = valor_doc # Instruções tpl_data['instrucoes'] = '' for instrucao in boletoDados.instrucoes: tpl_data['instrucoes'] += '<p>{0}</p>'.format(instrucao) # Rodapé tpl_data['sacado_info'] = '' for linha_sacado in boletoDados.sacado: tpl_data['sacado_info'] += '<p>{0}</p>'.format(linha_sacado) # Código de barras tpl_data['barcode'] = self._codigoBarraI25(boletoDados.barcode) self.html += tpl.substitute(tpl_data) def drawCanhoto(self, html): if html: self.html += str(html) def printPage(self): self.html += '<script>window.print();</script>' def drawBoletoCarneDuplo(self, boletoDados1, boletoDados2=None): """Imprime um boleto tipo carnê com 2 boletos por página. :param boletoDados1: Objeto com os dados do boleto a ser preenchido. Deve ser subclasse de :class:`pyboleto.data.BoletoData` :param boletoDados2: Objeto com os dados do boleto a ser preenchido. Deve ser subclasse de :class:`pyboleto.data.BoletoData` :type boletoDados1: :class:`pyboleto.data.BoletoData` :type boletoDados2: :class:`pyboleto.data.BoletoData` """ raise NotImplementedError('Em desenvolvimento') def drawBoleto(self, boletoDados): """Imprime Boleto Convencional Você pode chamar este método diversas vezes para criar um arquivo com várias páginas, uma por boleto. :param boletoDados: Objeto com os dados do boleto a ser preenchido. Deve ser subclasse de :class:`pyboleto.data.BoletoData` :type boletoDados: :class:`pyboleto.data.BoletoData` """ self._drawReciboSacado(boletoDados) self._drawHorizontalCorteLine() self._drawReciboCaixa(boletoDados) self._drawHorizontalCorteLine() def nextPage(self): """Força início de nova página""" self.html += '</div><div class="pagina">' def save(self): """Fecha boleto e constroi o arquivo""" self.html += '</div></body></html>' if hasattr(self.fileDescr, 'write'): self.fileDescr.write(self.html) else: with open(self.fileDescr, 'w') as fd: fd.write(self.html) def _formataValorParaExibir(self, nfloat): if nfloat: txt = nfloat txt = txt.replace('.', ',') else: txt = "" return txt def _codigoBarraI25(self, code): """Imprime Código de barras otimizado para boletos http://en.wikipedia.org/wiki/Interleaved_2_of_5 """ digits = ['n', 'n s', 'n', 'n s'] if len(code) % 2 != 0: code = '0' + code for digt1, digt2 in self._grouper(2, code): digt1_repr = DIGITS[int(digt1)] digt2_repr = map(lambda x: x + ' s', DIGITS[int(digt2)]) digits.extend(chain(*zip(digt1_repr, digt2_repr))) digits.extend(['w', 'n s', 'n']) result = [] for digit in digits: result.append('<span class="{0}"></span>'.format(digit)) return ''.join(result) def _grouper(self, n, iterable, fillvalue=None): """grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx""" args = [iter(iterable)] * n return zip_longest(fillvalue=fillvalue, *args)
# -*- coding: utf-8 -*- """ pyboleto.html ~~~~~~~~~~~~~ Classe Responsável por fazer o output do boleto em html. :copyright: © 2012 by <NAME> :license: BSD, see LICENSE for more details. """ import os import string import sys import codecs import base64 from itertools import chain if sys.version_info < (3,): from itertools import izip_longest as zip_longest zip_longest # chamando para evitar erro de nao uso do zip_longest else: from itertools import zip_longest DIGITS = [ ['n', 'n', 'w', 'w', 'n'], ['w', 'n', 'n', 'n', 'w'], ['n', 'w', 'n', 'n', 'w'], ['w', 'w', 'n', 'n', 'n'], ['n', 'n', 'w', 'n', 'w'], ['w', 'n', 'w', 'n', 'n'], ['n', 'w', 'w', 'n', 'n'], ['n', 'n', 'n', 'w', 'w'], ['w', 'n', 'n', 'w', 'n'], ['n', 'w', 'n', 'w', 'n'], ] class BoletoHTML(object): """Geração do Boleto em HTML Esta classe é responsável por imprimir o boleto em HTML. Outras classes podem ser implementadas no futuro com a mesma interface, para fazer output em LaTeX, etc ... Esta classe pode imprimir boletos em formato de carnê (2 boletos por página) ou em formato de folha cheia. :param file_descr: Um arquivo ou *file-like* class. :param landscape: Formato da folha. Usar ``True`` para boleto tipo carnê. """ def __init__(self, file_descr, landscape=False): # Tamanhos em px self.width = 750 self.widthCanhoto = 0 self.fontSizeTitle = 9 self.heightLine = 27 self.fontSizeValue = 12 self.title = 'Boleto bancário' self.fileDescr = file_descr if landscape: raise NotImplementedError('Em desenvolvimento...') else: tpl = string.Template(self._load_template('head.html')) self.html = tpl.substitute(title=self.title, width=self.width, font_size_value=self.fontSizeValue, height_line=self.heightLine, font_size_title=self.fontSizeTitle) def _load_template(self, template): pyboleto_dir = os.path.dirname(os.path.abspath(__file__)) template_path = os.path.join(pyboleto_dir, 'templates', template) with open(template_path, 'r') as tpl: template_content = tpl.read() return template_content def _load_image(self, logo_image): pyboleto_dir = os.path.dirname(os.path.abspath(__file__)) image_path = os.path.join(pyboleto_dir, 'media', logo_image) return image_path def _drawReciboSacado(self, boletoDados): """Imprime o Recibo do Sacado para modelo de página inteira :param boletoDados: Objeto com os dados do boleto a ser preenchido. Deve ser subclasse de :class:`pyboleto.data.BoletoData` :type boletoDados: :class:`pyboleto.data.BoletoData` """ tpl = string.Template(self._load_template('recibo_sacado.html')) tpl_data = {} # Cabeçalho tpl_data['logo_img'] = '' if boletoDados.logo_image: img = codecs.open(self._load_image(boletoDados.logo_image)) aux = img.read() aux = base64.b64encode(aux) img_base64 = 'data:image/jpeg;base64,{0}'.format(aux) tpl_data['logo_img'] = img_base64 tpl_data['codigo_dv_banco'] = boletoDados.codigo_dv_banco # Corpo tpl_data['cedente'] = boletoDados.cedente tpl_data['agencia_conta_cedente'] = boletoDados.agencia_conta_cedente tpl_data['cedente_documento'] = boletoDados.cedente_documento data_vencimento = boletoDados.data_vencimento tpl_data['data_vencimento'] = data_vencimento.strftime('%d/%m/%Y') tpl_data['sacado'] = boletoDados.sacado[0] tpl_data['nosso_numero_format'] = boletoDados.format_nosso_numero() tpl_data['numero_documento'] = boletoDados.numero_documento data_documento = boletoDados.data_documento tpl_data['data_documento'] = data_documento.strftime('%d/%m/%Y') tpl_data['cedente_endereco'] = boletoDados.cedente_endereco valor_doc = self._formataValorParaExibir(boletoDados.valor_documento) tpl_data['valor_documento'] = valor_doc # Demonstrativo tpl_data['demonstrativo'] = '' for dm in boletoDados.demonstrativo: tpl_data['demonstrativo'] += '<p>{0}</p>'.format(dm) self.html += tpl.substitute(tpl_data) def _drawHorizontalCorteLine(self): self.html += '<hr />' def _drawReciboCaixa(self, boletoDados): """Imprime o Recibo do Caixa :param boletoDados: Objeto com os dados do boleto a ser preenchido. Deve ser subclasse de :class:`pyboleto.data.BoletoData` :type boletoDados: :class:`pyboleto.data.BoletoData` """ tpl = string.Template(self._load_template('recibo_caixa.html')) tpl_data = {} # Cabeçalho tpl_data['logo_img'] = '' if boletoDados.logo_image: img = codecs.open(self._load_image(boletoDados.logo_image)) aux = img.read() aux = base64.b64encode(aux) img_base64 = 'data:image/jpeg;base64,{0}'.format(aux) tpl_data['logo_img'] = img_base64 tpl_data['codigo_dv_banco'] = boletoDados.codigo_dv_banco tpl_data['linha_digitavel'] = boletoDados.linha_digitavel # Corpo data_vencimento = boletoDados.data_vencimento tpl_data['data_vencimento'] = data_vencimento.strftime('%d/%m/%Y') # value em unicode em data.py if isinstance(boletoDados.local_pagamento, unicode): tpl_data['local_pagamento'] = boletoDados.local_pagamento.encode ('utf-8') else: tpl_data['local_pagamento'] = boletoDados.local_pagamento tpl_data['cedente'] = boletoDados.cedente tpl_data['agencia_conta_cedente'] = boletoDados.agencia_conta_cedente data_documento = boletoDados.data_documento tpl_data['data_documento'] = data_documento.strftime('%d/%m/%Y') tpl_data['numero_documento'] = boletoDados.numero_documento tpl_data['especie_documento'] = boletoDados.especie_documento tpl_data['aceite'] = boletoDados.aceite data_process = boletoDados.data_processamento tpl_data['data_processamento'] = data_process.strftime('%d/%m/%Y') tpl_data['nosso_numero_format'] = boletoDados.format_nosso_numero() tpl_data['carteira'] = boletoDados.carteira tpl_data['especie'] = boletoDados.especie tpl_data['quantidade'] = boletoDados.quantidade valor = self._formataValorParaExibir(boletoDados.valor) tpl_data['valor'] = valor valor_doc = self._formataValorParaExibir(boletoDados.valor_documento) tpl_data['valor_documento'] = valor_doc # Instruções tpl_data['instrucoes'] = '' for instrucao in boletoDados.instrucoes: tpl_data['instrucoes'] += '<p>{0}</p>'.format(instrucao) # Rodapé tpl_data['sacado_info'] = '' for linha_sacado in boletoDados.sacado: tpl_data['sacado_info'] += '<p>{0}</p>'.format(linha_sacado) # Código de barras tpl_data['barcode'] = self._codigoBarraI25(boletoDados.barcode) self.html += tpl.substitute(tpl_data) def drawCanhoto(self, html): if html: self.html += str(html) def printPage(self): self.html += '<script>window.print();</script>' def drawBoletoCarneDuplo(self, boletoDados1, boletoDados2=None): """Imprime um boleto tipo carnê com 2 boletos por página. :param boletoDados1: Objeto com os dados do boleto a ser preenchido. Deve ser subclasse de :class:`pyboleto.data.BoletoData` :param boletoDados2: Objeto com os dados do boleto a ser preenchido. Deve ser subclasse de :class:`pyboleto.data.BoletoData` :type boletoDados1: :class:`pyboleto.data.BoletoData` :type boletoDados2: :class:`pyboleto.data.BoletoData` """ raise NotImplementedError('Em desenvolvimento') def drawBoleto(self, boletoDados): """Imprime Boleto Convencional Você pode chamar este método diversas vezes para criar um arquivo com várias páginas, uma por boleto. :param boletoDados: Objeto com os dados do boleto a ser preenchido. Deve ser subclasse de :class:`pyboleto.data.BoletoData` :type boletoDados: :class:`pyboleto.data.BoletoData` """ self._drawReciboSacado(boletoDados) self._drawHorizontalCorteLine() self._drawReciboCaixa(boletoDados) self._drawHorizontalCorteLine() def nextPage(self): """Força início de nova página""" self.html += '</div><div class="pagina">' def save(self): """Fecha boleto e constroi o arquivo""" self.html += '</div></body></html>' if hasattr(self.fileDescr, 'write'): self.fileDescr.write(self.html) else: with open(self.fileDescr, 'w') as fd: fd.write(self.html) def _formataValorParaExibir(self, nfloat): if nfloat: txt = nfloat txt = txt.replace('.', ',') else: txt = "" return txt def _codigoBarraI25(self, code): """Imprime Código de barras otimizado para boletos http://en.wikipedia.org/wiki/Interleaved_2_of_5 """ digits = ['n', 'n s', 'n', 'n s'] if len(code) % 2 != 0: code = '0' + code for digt1, digt2 in self._grouper(2, code): digt1_repr = DIGITS[int(digt1)] digt2_repr = map(lambda x: x + ' s', DIGITS[int(digt2)]) digits.extend(chain(*zip(digt1_repr, digt2_repr))) digits.extend(['w', 'n s', 'n']) result = [] for digit in digits: result.append('<span class="{0}"></span>'.format(digit)) return ''.join(result) def _grouper(self, n, iterable, fillvalue=None): """grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx""" args = [iter(iterable)] * n return zip_longest(fillvalue=fillvalue, *args)
pt
0.787206
# -*- coding: utf-8 -*- pyboleto.html ~~~~~~~~~~~~~ Classe Responsável por fazer o output do boleto em html. :copyright: © 2012 by <NAME> :license: BSD, see LICENSE for more details. # chamando para evitar erro de nao uso do zip_longest Geração do Boleto em HTML Esta classe é responsável por imprimir o boleto em HTML. Outras classes podem ser implementadas no futuro com a mesma interface, para fazer output em LaTeX, etc ... Esta classe pode imprimir boletos em formato de carnê (2 boletos por página) ou em formato de folha cheia. :param file_descr: Um arquivo ou *file-like* class. :param landscape: Formato da folha. Usar ``True`` para boleto tipo carnê. # Tamanhos em px Imprime o Recibo do Sacado para modelo de página inteira :param boletoDados: Objeto com os dados do boleto a ser preenchido. Deve ser subclasse de :class:`pyboleto.data.BoletoData` :type boletoDados: :class:`pyboleto.data.BoletoData` # Cabeçalho # Corpo # Demonstrativo Imprime o Recibo do Caixa :param boletoDados: Objeto com os dados do boleto a ser preenchido. Deve ser subclasse de :class:`pyboleto.data.BoletoData` :type boletoDados: :class:`pyboleto.data.BoletoData` # Cabeçalho # Corpo # value em unicode em data.py # Instruções # Rodapé # Código de barras Imprime um boleto tipo carnê com 2 boletos por página. :param boletoDados1: Objeto com os dados do boleto a ser preenchido. Deve ser subclasse de :class:`pyboleto.data.BoletoData` :param boletoDados2: Objeto com os dados do boleto a ser preenchido. Deve ser subclasse de :class:`pyboleto.data.BoletoData` :type boletoDados1: :class:`pyboleto.data.BoletoData` :type boletoDados2: :class:`pyboleto.data.BoletoData` Imprime Boleto Convencional Você pode chamar este método diversas vezes para criar um arquivo com várias páginas, uma por boleto. :param boletoDados: Objeto com os dados do boleto a ser preenchido. Deve ser subclasse de :class:`pyboleto.data.BoletoData` :type boletoDados: :class:`pyboleto.data.BoletoData` Força início de nova página Fecha boleto e constroi o arquivo Imprime Código de barras otimizado para boletos http://en.wikipedia.org/wiki/Interleaved_2_of_5 grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
2.890807
3
Courses/1 month/2 week/day 6/Formula.py
emir-naiz/first_git_lesson
0
39
summary = 0 i = 0 while i < 5: summary = summary + i print(summary) i = i + 1
summary = 0 i = 0 while i < 5: summary = summary + i print(summary) i = i + 1
none
1
3.476657
3
tests/image_saver/image_saver_7.py
Vicken-Ghoubiguian/Imtreat
0
40
import imtreat img = imtreat.imageManagerClass.openImageFunction("../images/soleil.png", 0) img = imtreat.definedModesClass.detailEnhanceFunction(img) imtreat.imageManagerClass.saveImageFunction("/Téléchargements/", "image_1", ".png", img)
import imtreat img = imtreat.imageManagerClass.openImageFunction("../images/soleil.png", 0) img = imtreat.definedModesClass.detailEnhanceFunction(img) imtreat.imageManagerClass.saveImageFunction("/Téléchargements/", "image_1", ".png", img)
none
1
2.062492
2
nova/conf/hyperv.py
raubvogel/nova
0
41
<filename>nova/conf/hyperv.py<gh_stars>0 # Copyright (c) 2016 <NAME> # 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 oslo_config import cfg hyperv_opt_group = cfg.OptGroup("hyperv", title='The Hyper-V feature', help=""" The hyperv feature allows you to configure the Hyper-V hypervisor driver to be used within an OpenStack deployment. """) hyperv_opts = [ cfg.FloatOpt('dynamic_memory_ratio', default=1.0, help=""" Dynamic memory ratio Enables dynamic memory allocation (ballooning) when set to a value greater than 1. The value expresses the ratio between the total RAM assigned to an instance and its startup RAM amount. For example a ratio of 2.0 for an instance with 1024MB of RAM implies 512MB of RAM allocated at startup. Possible values: * 1.0: Disables dynamic memory allocation (Default). * Float values greater than 1.0: Enables allocation of total implied RAM divided by this value for startup. """), cfg.BoolOpt('enable_instance_metrics_collection', default=False, help=""" Enable instance metrics collection Enables metrics collections for an instance by using Hyper-V's metric APIs. Collected data can be retrieved by other apps and services, e.g.: Ceilometer. """), cfg.StrOpt('instances_path_share', default="", help=""" Instances path share The name of a Windows share mapped to the "instances_path" dir and used by the resize feature to copy files to the target host. If left blank, an administrative share (hidden network share) will be used, looking for the same "instances_path" used locally. Possible values: * "": An administrative share will be used (Default). * Name of a Windows share. Related options: * "instances_path": The directory which will be used if this option here is left blank. """), cfg.BoolOpt('limit_cpu_features', default=False, help=""" Limit CPU features This flag is needed to support live migration to hosts with different CPU features and checked during instance creation in order to limit the CPU features used by the instance. """), cfg.IntOpt('mounted_disk_query_retry_count', default=10, min=0, help=""" Mounted disk query retry count The number of times to retry checking for a mounted disk. The query runs until the device can be found or the retry count is reached. Possible values: * Positive integer values. Values greater than 1 is recommended (Default: 10). Related options: * Time interval between disk mount retries is declared with "mounted_disk_query_retry_interval" option. """), cfg.IntOpt('mounted_disk_query_retry_interval', default=5, min=0, help=""" Mounted disk query retry interval Interval between checks for a mounted disk, in seconds. Possible values: * Time in seconds (Default: 5). Related options: * This option is meaningful when the mounted_disk_query_retry_count is greater than 1. * The retry loop runs with mounted_disk_query_retry_count and mounted_disk_query_retry_interval configuration options. """), cfg.IntOpt('power_state_check_timeframe', default=60, min=0, help=""" Power state check timeframe The timeframe to be checked for instance power state changes. This option is used to fetch the state of the instance from Hyper-V through the WMI interface, within the specified timeframe. Possible values: * Timeframe in seconds (Default: 60). """), cfg.IntOpt('power_state_event_polling_interval', default=2, min=0, help=""" Power state event polling interval Instance power state change event polling frequency. Sets the listener interval for power state events to the given value. This option enhances the internal lifecycle notifications of instances that reboot themselves. It is unlikely that an operator has to change this value. Possible values: * Time in seconds (Default: 2). """), cfg.StrOpt('qemu_img_cmd', default="qemu-img.exe", help=""" qemu-img command qemu-img is required for some of the image related operations like converting between different image types. You can get it from here: (http://qemu.weilnetz.de/) or you can install the Cloudbase OpenStack Hyper-V Compute Driver (https://cloudbase.it/openstack-hyperv-driver/) which automatically sets the proper path for this config option. You can either give the full path of qemu-img.exe or set its path in the PATH environment variable and leave this option to the default value. Possible values: * Name of the qemu-img executable, in case it is in the same directory as the nova-compute service or its path is in the PATH environment variable (Default). * Path of qemu-img command (DRIVELETTER:\PATH\TO\QEMU-IMG\COMMAND). Related options: * If the config_drive_cdrom option is False, qemu-img will be used to convert the ISO to a VHD, otherwise the config drive will remain an ISO. To use config drive with Hyper-V, you must set the ``mkisofs_cmd`` value to the full path to an ``mkisofs.exe`` installation. """), cfg.StrOpt('vswitch_name', help=""" External virtual switch name The Hyper-V Virtual Switch is a software-based layer-2 Ethernet network switch that is available with the installation of the Hyper-V server role. The switch includes programmatically managed and extensible capabilities to connect virtual machines to both virtual networks and the physical network. In addition, Hyper-V Virtual Switch provides policy enforcement for security, isolation, and service levels. The vSwitch represented by this config option must be an external one (not internal or private). Possible values: * If not provided, the first of a list of available vswitches is used. This list is queried using WQL. * Virtual switch name. """), cfg.IntOpt('wait_soft_reboot_seconds', default=60, min=0, help=""" Wait soft reboot seconds Number of seconds to wait for instance to shut down after soft reboot request is made. We fall back to hard reboot if instance does not shutdown within this window. Possible values: * Time in seconds (Default: 60). """), cfg.BoolOpt('config_drive_cdrom', default=False, help=""" Mount config drive as a CD drive. OpenStack can be configured to write instance metadata to a config drive, which is then attached to the instance before it boots. The config drive can be attached as a disk drive (default) or as a CD drive. Related options: * This option is meaningful with ``force_config_drive`` option set to ``True`` or when the REST API call to create an instance will have ``--config-drive=True`` flag. * ``config_drive_format`` option must be set to ``iso9660`` in order to use CD drive as the config drive image. * To use config drive with Hyper-V, you must set the ``mkisofs_cmd`` value to the full path to an ``mkisofs.exe`` installation. Additionally, you must set the ``qemu_img_cmd`` value to the full path to an ``qemu-img`` command installation. * You can configure the Compute service to always create a configuration drive by setting the ``force_config_drive`` option to ``True``. """), cfg.BoolOpt('config_drive_inject_password', default=False, help=""" Inject password to config drive. When enabled, the admin password will be available from the config drive image. Related options: * This option is meaningful when used with other options that enable config drive usage with Hyper-V, such as ``force_config_drive``. """), cfg.IntOpt('volume_attach_retry_count', default=10, min=0, help=""" Volume attach retry count The number of times to retry attaching a volume. Volume attachment is retried until success or the given retry count is reached. Possible values: * Positive integer values (Default: 10). Related options: * Time interval between attachment attempts is declared with volume_attach_retry_interval option. """), cfg.IntOpt('volume_attach_retry_interval', default=5, min=0, help=""" Volume attach retry interval Interval between volume attachment attempts, in seconds. Possible values: * Time in seconds (Default: 5). Related options: * This options is meaningful when volume_attach_retry_count is greater than 1. * The retry loop runs with volume_attach_retry_count and volume_attach_retry_interval configuration options. """), cfg.BoolOpt('enable_remotefx', default=False, help=""" Enable RemoteFX feature This requires at least one DirectX 11 capable graphics adapter for Windows / Hyper-V Server 2012 R2 or newer and RDS-Virtualization feature has to be enabled. Instances with RemoteFX can be requested with the following flavor extra specs: **os:resolution**. Guest VM screen resolution size. Acceptable values:: 1024x768, 1280x1024, 1600x1200, 1920x1200, 2560x1600, 3840x2160 ``3840x2160`` is only available on Windows / Hyper-V Server 2016. **os:monitors**. Guest VM number of monitors. Acceptable values:: [1, 4] - Windows / Hyper-V Server 2012 R2 [1, 8] - Windows / Hyper-V Server 2016 **os:vram**. Guest VM VRAM amount. Only available on Windows / Hyper-V Server 2016. Acceptable values:: 64, 128, 256, 512, 1024 """), cfg.BoolOpt('use_multipath_io', default=False, help=""" Use multipath connections when attaching iSCSI or FC disks. This requires the Multipath IO Windows feature to be enabled. MPIO must be configured to claim such devices. """), cfg.ListOpt('iscsi_initiator_list', default=[], help=""" List of iSCSI initiators that will be used for estabilishing iSCSI sessions. If none are specified, the Microsoft iSCSI initiator service will choose the initiator. """) ] def register_opts(conf): conf.register_group(hyperv_opt_group) conf.register_opts(hyperv_opts, group=hyperv_opt_group) def list_opts(): return {hyperv_opt_group: hyperv_opts}
<filename>nova/conf/hyperv.py<gh_stars>0 # Copyright (c) 2016 <NAME> # 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 oslo_config import cfg hyperv_opt_group = cfg.OptGroup("hyperv", title='The Hyper-V feature', help=""" The hyperv feature allows you to configure the Hyper-V hypervisor driver to be used within an OpenStack deployment. """) hyperv_opts = [ cfg.FloatOpt('dynamic_memory_ratio', default=1.0, help=""" Dynamic memory ratio Enables dynamic memory allocation (ballooning) when set to a value greater than 1. The value expresses the ratio between the total RAM assigned to an instance and its startup RAM amount. For example a ratio of 2.0 for an instance with 1024MB of RAM implies 512MB of RAM allocated at startup. Possible values: * 1.0: Disables dynamic memory allocation (Default). * Float values greater than 1.0: Enables allocation of total implied RAM divided by this value for startup. """), cfg.BoolOpt('enable_instance_metrics_collection', default=False, help=""" Enable instance metrics collection Enables metrics collections for an instance by using Hyper-V's metric APIs. Collected data can be retrieved by other apps and services, e.g.: Ceilometer. """), cfg.StrOpt('instances_path_share', default="", help=""" Instances path share The name of a Windows share mapped to the "instances_path" dir and used by the resize feature to copy files to the target host. If left blank, an administrative share (hidden network share) will be used, looking for the same "instances_path" used locally. Possible values: * "": An administrative share will be used (Default). * Name of a Windows share. Related options: * "instances_path": The directory which will be used if this option here is left blank. """), cfg.BoolOpt('limit_cpu_features', default=False, help=""" Limit CPU features This flag is needed to support live migration to hosts with different CPU features and checked during instance creation in order to limit the CPU features used by the instance. """), cfg.IntOpt('mounted_disk_query_retry_count', default=10, min=0, help=""" Mounted disk query retry count The number of times to retry checking for a mounted disk. The query runs until the device can be found or the retry count is reached. Possible values: * Positive integer values. Values greater than 1 is recommended (Default: 10). Related options: * Time interval between disk mount retries is declared with "mounted_disk_query_retry_interval" option. """), cfg.IntOpt('mounted_disk_query_retry_interval', default=5, min=0, help=""" Mounted disk query retry interval Interval between checks for a mounted disk, in seconds. Possible values: * Time in seconds (Default: 5). Related options: * This option is meaningful when the mounted_disk_query_retry_count is greater than 1. * The retry loop runs with mounted_disk_query_retry_count and mounted_disk_query_retry_interval configuration options. """), cfg.IntOpt('power_state_check_timeframe', default=60, min=0, help=""" Power state check timeframe The timeframe to be checked for instance power state changes. This option is used to fetch the state of the instance from Hyper-V through the WMI interface, within the specified timeframe. Possible values: * Timeframe in seconds (Default: 60). """), cfg.IntOpt('power_state_event_polling_interval', default=2, min=0, help=""" Power state event polling interval Instance power state change event polling frequency. Sets the listener interval for power state events to the given value. This option enhances the internal lifecycle notifications of instances that reboot themselves. It is unlikely that an operator has to change this value. Possible values: * Time in seconds (Default: 2). """), cfg.StrOpt('qemu_img_cmd', default="qemu-img.exe", help=""" qemu-img command qemu-img is required for some of the image related operations like converting between different image types. You can get it from here: (http://qemu.weilnetz.de/) or you can install the Cloudbase OpenStack Hyper-V Compute Driver (https://cloudbase.it/openstack-hyperv-driver/) which automatically sets the proper path for this config option. You can either give the full path of qemu-img.exe or set its path in the PATH environment variable and leave this option to the default value. Possible values: * Name of the qemu-img executable, in case it is in the same directory as the nova-compute service or its path is in the PATH environment variable (Default). * Path of qemu-img command (DRIVELETTER:\PATH\TO\QEMU-IMG\COMMAND). Related options: * If the config_drive_cdrom option is False, qemu-img will be used to convert the ISO to a VHD, otherwise the config drive will remain an ISO. To use config drive with Hyper-V, you must set the ``mkisofs_cmd`` value to the full path to an ``mkisofs.exe`` installation. """), cfg.StrOpt('vswitch_name', help=""" External virtual switch name The Hyper-V Virtual Switch is a software-based layer-2 Ethernet network switch that is available with the installation of the Hyper-V server role. The switch includes programmatically managed and extensible capabilities to connect virtual machines to both virtual networks and the physical network. In addition, Hyper-V Virtual Switch provides policy enforcement for security, isolation, and service levels. The vSwitch represented by this config option must be an external one (not internal or private). Possible values: * If not provided, the first of a list of available vswitches is used. This list is queried using WQL. * Virtual switch name. """), cfg.IntOpt('wait_soft_reboot_seconds', default=60, min=0, help=""" Wait soft reboot seconds Number of seconds to wait for instance to shut down after soft reboot request is made. We fall back to hard reboot if instance does not shutdown within this window. Possible values: * Time in seconds (Default: 60). """), cfg.BoolOpt('config_drive_cdrom', default=False, help=""" Mount config drive as a CD drive. OpenStack can be configured to write instance metadata to a config drive, which is then attached to the instance before it boots. The config drive can be attached as a disk drive (default) or as a CD drive. Related options: * This option is meaningful with ``force_config_drive`` option set to ``True`` or when the REST API call to create an instance will have ``--config-drive=True`` flag. * ``config_drive_format`` option must be set to ``iso9660`` in order to use CD drive as the config drive image. * To use config drive with Hyper-V, you must set the ``mkisofs_cmd`` value to the full path to an ``mkisofs.exe`` installation. Additionally, you must set the ``qemu_img_cmd`` value to the full path to an ``qemu-img`` command installation. * You can configure the Compute service to always create a configuration drive by setting the ``force_config_drive`` option to ``True``. """), cfg.BoolOpt('config_drive_inject_password', default=False, help=""" Inject password to config drive. When enabled, the admin password will be available from the config drive image. Related options: * This option is meaningful when used with other options that enable config drive usage with Hyper-V, such as ``force_config_drive``. """), cfg.IntOpt('volume_attach_retry_count', default=10, min=0, help=""" Volume attach retry count The number of times to retry attaching a volume. Volume attachment is retried until success or the given retry count is reached. Possible values: * Positive integer values (Default: 10). Related options: * Time interval between attachment attempts is declared with volume_attach_retry_interval option. """), cfg.IntOpt('volume_attach_retry_interval', default=5, min=0, help=""" Volume attach retry interval Interval between volume attachment attempts, in seconds. Possible values: * Time in seconds (Default: 5). Related options: * This options is meaningful when volume_attach_retry_count is greater than 1. * The retry loop runs with volume_attach_retry_count and volume_attach_retry_interval configuration options. """), cfg.BoolOpt('enable_remotefx', default=False, help=""" Enable RemoteFX feature This requires at least one DirectX 11 capable graphics adapter for Windows / Hyper-V Server 2012 R2 or newer and RDS-Virtualization feature has to be enabled. Instances with RemoteFX can be requested with the following flavor extra specs: **os:resolution**. Guest VM screen resolution size. Acceptable values:: 1024x768, 1280x1024, 1600x1200, 1920x1200, 2560x1600, 3840x2160 ``3840x2160`` is only available on Windows / Hyper-V Server 2016. **os:monitors**. Guest VM number of monitors. Acceptable values:: [1, 4] - Windows / Hyper-V Server 2012 R2 [1, 8] - Windows / Hyper-V Server 2016 **os:vram**. Guest VM VRAM amount. Only available on Windows / Hyper-V Server 2016. Acceptable values:: 64, 128, 256, 512, 1024 """), cfg.BoolOpt('use_multipath_io', default=False, help=""" Use multipath connections when attaching iSCSI or FC disks. This requires the Multipath IO Windows feature to be enabled. MPIO must be configured to claim such devices. """), cfg.ListOpt('iscsi_initiator_list', default=[], help=""" List of iSCSI initiators that will be used for estabilishing iSCSI sessions. If none are specified, the Microsoft iSCSI initiator service will choose the initiator. """) ] def register_opts(conf): conf.register_group(hyperv_opt_group) conf.register_opts(hyperv_opts, group=hyperv_opt_group) def list_opts(): return {hyperv_opt_group: hyperv_opts}
en
0.798248
# Copyright (c) 2016 <NAME> # 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. The hyperv feature allows you to configure the Hyper-V hypervisor driver to be used within an OpenStack deployment. Dynamic memory ratio Enables dynamic memory allocation (ballooning) when set to a value greater than 1. The value expresses the ratio between the total RAM assigned to an instance and its startup RAM amount. For example a ratio of 2.0 for an instance with 1024MB of RAM implies 512MB of RAM allocated at startup. Possible values: * 1.0: Disables dynamic memory allocation (Default). * Float values greater than 1.0: Enables allocation of total implied RAM divided by this value for startup. Enable instance metrics collection Enables metrics collections for an instance by using Hyper-V's metric APIs. Collected data can be retrieved by other apps and services, e.g.: Ceilometer. Instances path share The name of a Windows share mapped to the "instances_path" dir and used by the resize feature to copy files to the target host. If left blank, an administrative share (hidden network share) will be used, looking for the same "instances_path" used locally. Possible values: * "": An administrative share will be used (Default). * Name of a Windows share. Related options: * "instances_path": The directory which will be used if this option here is left blank. Limit CPU features This flag is needed to support live migration to hosts with different CPU features and checked during instance creation in order to limit the CPU features used by the instance. Mounted disk query retry count The number of times to retry checking for a mounted disk. The query runs until the device can be found or the retry count is reached. Possible values: * Positive integer values. Values greater than 1 is recommended (Default: 10). Related options: * Time interval between disk mount retries is declared with "mounted_disk_query_retry_interval" option. Mounted disk query retry interval Interval between checks for a mounted disk, in seconds. Possible values: * Time in seconds (Default: 5). Related options: * This option is meaningful when the mounted_disk_query_retry_count is greater than 1. * The retry loop runs with mounted_disk_query_retry_count and mounted_disk_query_retry_interval configuration options. Power state check timeframe The timeframe to be checked for instance power state changes. This option is used to fetch the state of the instance from Hyper-V through the WMI interface, within the specified timeframe. Possible values: * Timeframe in seconds (Default: 60). Power state event polling interval Instance power state change event polling frequency. Sets the listener interval for power state events to the given value. This option enhances the internal lifecycle notifications of instances that reboot themselves. It is unlikely that an operator has to change this value. Possible values: * Time in seconds (Default: 2). qemu-img command qemu-img is required for some of the image related operations like converting between different image types. You can get it from here: (http://qemu.weilnetz.de/) or you can install the Cloudbase OpenStack Hyper-V Compute Driver (https://cloudbase.it/openstack-hyperv-driver/) which automatically sets the proper path for this config option. You can either give the full path of qemu-img.exe or set its path in the PATH environment variable and leave this option to the default value. Possible values: * Name of the qemu-img executable, in case it is in the same directory as the nova-compute service or its path is in the PATH environment variable (Default). * Path of qemu-img command (DRIVELETTER:\PATH\TO\QEMU-IMG\COMMAND). Related options: * If the config_drive_cdrom option is False, qemu-img will be used to convert the ISO to a VHD, otherwise the config drive will remain an ISO. To use config drive with Hyper-V, you must set the ``mkisofs_cmd`` value to the full path to an ``mkisofs.exe`` installation. External virtual switch name The Hyper-V Virtual Switch is a software-based layer-2 Ethernet network switch that is available with the installation of the Hyper-V server role. The switch includes programmatically managed and extensible capabilities to connect virtual machines to both virtual networks and the physical network. In addition, Hyper-V Virtual Switch provides policy enforcement for security, isolation, and service levels. The vSwitch represented by this config option must be an external one (not internal or private). Possible values: * If not provided, the first of a list of available vswitches is used. This list is queried using WQL. * Virtual switch name. Wait soft reboot seconds Number of seconds to wait for instance to shut down after soft reboot request is made. We fall back to hard reboot if instance does not shutdown within this window. Possible values: * Time in seconds (Default: 60). Mount config drive as a CD drive. OpenStack can be configured to write instance metadata to a config drive, which is then attached to the instance before it boots. The config drive can be attached as a disk drive (default) or as a CD drive. Related options: * This option is meaningful with ``force_config_drive`` option set to ``True`` or when the REST API call to create an instance will have ``--config-drive=True`` flag. * ``config_drive_format`` option must be set to ``iso9660`` in order to use CD drive as the config drive image. * To use config drive with Hyper-V, you must set the ``mkisofs_cmd`` value to the full path to an ``mkisofs.exe`` installation. Additionally, you must set the ``qemu_img_cmd`` value to the full path to an ``qemu-img`` command installation. * You can configure the Compute service to always create a configuration drive by setting the ``force_config_drive`` option to ``True``. Inject password to config drive. When enabled, the admin password will be available from the config drive image. Related options: * This option is meaningful when used with other options that enable config drive usage with Hyper-V, such as ``force_config_drive``. Volume attach retry count The number of times to retry attaching a volume. Volume attachment is retried until success or the given retry count is reached. Possible values: * Positive integer values (Default: 10). Related options: * Time interval between attachment attempts is declared with volume_attach_retry_interval option. Volume attach retry interval Interval between volume attachment attempts, in seconds. Possible values: * Time in seconds (Default: 5). Related options: * This options is meaningful when volume_attach_retry_count is greater than 1. * The retry loop runs with volume_attach_retry_count and volume_attach_retry_interval configuration options. Enable RemoteFX feature This requires at least one DirectX 11 capable graphics adapter for Windows / Hyper-V Server 2012 R2 or newer and RDS-Virtualization feature has to be enabled. Instances with RemoteFX can be requested with the following flavor extra specs: **os:resolution**. Guest VM screen resolution size. Acceptable values:: 1024x768, 1280x1024, 1600x1200, 1920x1200, 2560x1600, 3840x2160 ``3840x2160`` is only available on Windows / Hyper-V Server 2016. **os:monitors**. Guest VM number of monitors. Acceptable values:: [1, 4] - Windows / Hyper-V Server 2012 R2 [1, 8] - Windows / Hyper-V Server 2016 **os:vram**. Guest VM VRAM amount. Only available on Windows / Hyper-V Server 2016. Acceptable values:: 64, 128, 256, 512, 1024 Use multipath connections when attaching iSCSI or FC disks. This requires the Multipath IO Windows feature to be enabled. MPIO must be configured to claim such devices. List of iSCSI initiators that will be used for estabilishing iSCSI sessions. If none are specified, the Microsoft iSCSI initiator service will choose the initiator.
2.006344
2
src/fetchWords.py
theyadev/thierry-bot
0
42
import requests words_list = requests.get("https://raw.githubusercontent.com/atebits/Words/master/Words/fr.txt").text words_list = filter(lambda x: len(x) > 4, words_list.split('\n')) path = input("Chemin d'écriture ? (words.txt) ") if path == "": path = "./words.txt" with open(path, "w", encoding="utf-8") as file: file.write('\n'.join(words_list))
import requests words_list = requests.get("https://raw.githubusercontent.com/atebits/Words/master/Words/fr.txt").text words_list = filter(lambda x: len(x) > 4, words_list.split('\n')) path = input("Chemin d'écriture ? (words.txt) ") if path == "": path = "./words.txt" with open(path, "w", encoding="utf-8") as file: file.write('\n'.join(words_list))
none
1
3.118416
3
inspiration/simplegallery/test/upload/variants/test_aws_uploader.py
Zenahr/simple-music-gallery
1
43
import unittest from unittest import mock import os import subprocess from testfixtures import TempDirectory from simplegallery.upload.uploader_factory import get_uploader class AWSUploaderTestCase(unittest.TestCase): def test_no_location(self): uploader = get_uploader('aws') self.assertFalse(uploader.check_location('')) @mock.patch('subprocess.run') def test_upload_gallery(self, subprocess_run): subprocess_run.return_value = subprocess.CompletedProcess([], returncode=0) with TempDirectory() as tempdir: # Setup mock file and uploader tempdir.write('index.html', b'') gallery_path = os.path.join(tempdir.path, 'index.html') uploader = get_uploader('aws') # Test upload to bucket uploader.upload_gallery('s3://testbucket/path/', gallery_path) subprocess_run.assert_called_with( ['aws', 's3', 'sync', gallery_path, 's3://testbucket/path/', '--exclude', '.DS_Store']) # Test upload to bucket without prefix uploader.upload_gallery('testbucket/path/', gallery_path) subprocess_run.assert_called_with( ['aws', 's3', 'sync', gallery_path, 's3://testbucket/path/', '--exclude', '.DS_Store']) # Test upload to bucket without trailing / uploader.upload_gallery('s3://testbucket/path', gallery_path) subprocess_run.assert_called_with( ['aws', 's3', 'sync', gallery_path, 's3://testbucket/path/', '--exclude', '.DS_Store']) if __name__ == '__main__': unittest.main()
import unittest from unittest import mock import os import subprocess from testfixtures import TempDirectory from simplegallery.upload.uploader_factory import get_uploader class AWSUploaderTestCase(unittest.TestCase): def test_no_location(self): uploader = get_uploader('aws') self.assertFalse(uploader.check_location('')) @mock.patch('subprocess.run') def test_upload_gallery(self, subprocess_run): subprocess_run.return_value = subprocess.CompletedProcess([], returncode=0) with TempDirectory() as tempdir: # Setup mock file and uploader tempdir.write('index.html', b'') gallery_path = os.path.join(tempdir.path, 'index.html') uploader = get_uploader('aws') # Test upload to bucket uploader.upload_gallery('s3://testbucket/path/', gallery_path) subprocess_run.assert_called_with( ['aws', 's3', 'sync', gallery_path, 's3://testbucket/path/', '--exclude', '.DS_Store']) # Test upload to bucket without prefix uploader.upload_gallery('testbucket/path/', gallery_path) subprocess_run.assert_called_with( ['aws', 's3', 'sync', gallery_path, 's3://testbucket/path/', '--exclude', '.DS_Store']) # Test upload to bucket without trailing / uploader.upload_gallery('s3://testbucket/path', gallery_path) subprocess_run.assert_called_with( ['aws', 's3', 'sync', gallery_path, 's3://testbucket/path/', '--exclude', '.DS_Store']) if __name__ == '__main__': unittest.main()
en
0.918477
# Setup mock file and uploader # Test upload to bucket # Test upload to bucket without prefix # Test upload to bucket without trailing /
2.360026
2
Qt_interface/add_subject.py
kithsirij/NLP-based-Syllabus-Coverage-Exam-paper-checker-Tool
1
44
<reponame>kithsirij/NLP-based-Syllabus-Coverage-Exam-paper-checker-Tool # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'add_subject.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_Dialog_add_subject(object): def setupUi(self, Dialog_add_subject): Dialog_add_subject.setObjectName(_fromUtf8("Dialog_add_subject")) Dialog_add_subject.resize(568, 374) font = QtGui.QFont() font.setFamily(_fromUtf8("Times New Roman")) font.setPointSize(10) Dialog_add_subject.setFont(font) Dialog_add_subject.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(_fromUtf8("Qt_interface/SE_syllabus/4zIr6y.jpg")), QtGui.QIcon.Normal, QtGui.QIcon.Off) Dialog_add_subject.setWindowIcon(icon) self.lbl_subject_name = QtGui.QLabel(Dialog_add_subject) self.lbl_subject_name.setGeometry(QtCore.QRect(50, 235, 131, 21)) font = QtGui.QFont() font.setFamily(_fromUtf8("Times New Roman")) font.setPointSize(12) self.lbl_subject_name.setFont(font) self.lbl_subject_name.setObjectName(_fromUtf8("lbl_subject_name")) self.label_add_subject = QtGui.QLabel(Dialog_add_subject) self.label_add_subject.setGeometry(QtCore.QRect(220, 30, 151, 31)) font = QtGui.QFont() font.setFamily(_fromUtf8("Times New Roman")) font.setPointSize(14) font.setBold(True) font.setWeight(75) self.label_add_subject.setFont(font) self.label_add_subject.setObjectName(_fromUtf8("label_add_subject")) self.lineEdit_subject_name = QtGui.QLineEdit(Dialog_add_subject) self.lineEdit_subject_name.setGeometry(QtCore.QRect(190, 230, 321, 31)) font = QtGui.QFont() font.setFamily(_fromUtf8("Times New Roman")) font.setPointSize(12) self.lineEdit_subject_name.setFont(font) self.lineEdit_subject_name.setObjectName(_fromUtf8("lineEdit_subject_name")) self.label_year = QtGui.QLabel(Dialog_add_subject) self.label_year.setGeometry(QtCore.QRect(50, 95, 81, 21)) font = QtGui.QFont() font.setFamily(_fromUtf8("Times New Roman")) font.setPointSize(12) self.label_year.setFont(font) self.label_year.setObjectName(_fromUtf8("label_year")) self.label_semester = QtGui.QLabel(Dialog_add_subject) self.label_semester.setGeometry(QtCore.QRect(50, 165, 91, 21)) font = QtGui.QFont() font.setFamily(_fromUtf8("Times New Roman")) font.setPointSize(12) self.label_semester.setFont(font) self.label_semester.setObjectName(_fromUtf8("label_semester")) self.pushButton_save = QtGui.QPushButton(Dialog_add_subject) self.pushButton_save.setGeometry(QtCore.QRect(190, 290, 111, 31)) font = QtGui.QFont() font.setFamily(_fromUtf8("Times New Roman")) font.setPointSize(10) self.pushButton_save.setFont(font) icon1 = QtGui.QIcon() icon1.addPixmap(QtGui.QPixmap(_fromUtf8("Qt_interface/SE_syllabus/Save-as.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton_save.setIcon(icon1) self.pushButton_save.setIconSize(QtCore.QSize(20, 20)) self.pushButton_save.setObjectName(_fromUtf8("pushButton_save")) self.pushButton_cancel = QtGui.QPushButton(Dialog_add_subject) self.pushButton_cancel.setGeometry(QtCore.QRect(340, 290, 111, 31)) font = QtGui.QFont() font.setFamily(_fromUtf8("Times New Roman")) self.pushButton_cancel.setFont(font) icon2 = QtGui.QIcon() icon2.addPixmap(QtGui.QPixmap(_fromUtf8("Qt_interface/SE_syllabus/if_draw-08_725558.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton_cancel.setIcon(icon2) self.pushButton_cancel.setIconSize(QtCore.QSize(20, 20)) self.pushButton_cancel.setObjectName(_fromUtf8("pushButton_cancel")) self.comboBox_year = QtGui.QComboBox(Dialog_add_subject) self.comboBox_year.setGeometry(QtCore.QRect(190, 91, 111, 31)) font = QtGui.QFont() font.setFamily(_fromUtf8("Times New Roman")) font.setPointSize(12) self.comboBox_year.setFont(font) self.comboBox_year.setObjectName(_fromUtf8("comboBox_year")) self.comboBox_semester = QtGui.QComboBox(Dialog_add_subject) self.comboBox_semester.setGeometry(QtCore.QRect(190, 160, 111, 31)) font = QtGui.QFont() font.setFamily(_fromUtf8("Times New Roman")) font.setPointSize(12) self.comboBox_semester.setFont(font) self.comboBox_semester.setObjectName(_fromUtf8("comboBox_semester")) self.retranslateUi(Dialog_add_subject) QtCore.QObject.connect(self.pushButton_cancel, QtCore.SIGNAL(_fromUtf8("clicked()")), self.lineEdit_subject_name.clear) QtCore.QMetaObject.connectSlotsByName(Dialog_add_subject) def retranslateUi(self, Dialog_add_subject): Dialog_add_subject.setWindowTitle(_translate("Dialog_add_subject", "Dialog", None)) self.lbl_subject_name.setText(_translate("Dialog_add_subject", "SUBJECT NAME", None)) self.label_add_subject.setText(_translate("Dialog_add_subject", "ADD SUBJECT", None)) self.label_year.setText(_translate("Dialog_add_subject", "YEAR", None)) self.label_semester.setText(_translate("Dialog_add_subject", "SEMESTER", None)) self.pushButton_save.setText(_translate("Dialog_add_subject", "SAVE", None)) self.pushButton_cancel.setText(_translate("Dialog_add_subject", "CANCEL", None)) if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) Dialog_add_subject = QtGui.QDialog() ui = Ui_Dialog_add_subject() ui.setupUi(Dialog_add_subject) Dialog_add_subject.show() sys.exit(app.exec_())
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'add_subject.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig) class Ui_Dialog_add_subject(object): def setupUi(self, Dialog_add_subject): Dialog_add_subject.setObjectName(_fromUtf8("Dialog_add_subject")) Dialog_add_subject.resize(568, 374) font = QtGui.QFont() font.setFamily(_fromUtf8("Times New Roman")) font.setPointSize(10) Dialog_add_subject.setFont(font) Dialog_add_subject.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(_fromUtf8("Qt_interface/SE_syllabus/4zIr6y.jpg")), QtGui.QIcon.Normal, QtGui.QIcon.Off) Dialog_add_subject.setWindowIcon(icon) self.lbl_subject_name = QtGui.QLabel(Dialog_add_subject) self.lbl_subject_name.setGeometry(QtCore.QRect(50, 235, 131, 21)) font = QtGui.QFont() font.setFamily(_fromUtf8("Times New Roman")) font.setPointSize(12) self.lbl_subject_name.setFont(font) self.lbl_subject_name.setObjectName(_fromUtf8("lbl_subject_name")) self.label_add_subject = QtGui.QLabel(Dialog_add_subject) self.label_add_subject.setGeometry(QtCore.QRect(220, 30, 151, 31)) font = QtGui.QFont() font.setFamily(_fromUtf8("Times New Roman")) font.setPointSize(14) font.setBold(True) font.setWeight(75) self.label_add_subject.setFont(font) self.label_add_subject.setObjectName(_fromUtf8("label_add_subject")) self.lineEdit_subject_name = QtGui.QLineEdit(Dialog_add_subject) self.lineEdit_subject_name.setGeometry(QtCore.QRect(190, 230, 321, 31)) font = QtGui.QFont() font.setFamily(_fromUtf8("Times New Roman")) font.setPointSize(12) self.lineEdit_subject_name.setFont(font) self.lineEdit_subject_name.setObjectName(_fromUtf8("lineEdit_subject_name")) self.label_year = QtGui.QLabel(Dialog_add_subject) self.label_year.setGeometry(QtCore.QRect(50, 95, 81, 21)) font = QtGui.QFont() font.setFamily(_fromUtf8("Times New Roman")) font.setPointSize(12) self.label_year.setFont(font) self.label_year.setObjectName(_fromUtf8("label_year")) self.label_semester = QtGui.QLabel(Dialog_add_subject) self.label_semester.setGeometry(QtCore.QRect(50, 165, 91, 21)) font = QtGui.QFont() font.setFamily(_fromUtf8("Times New Roman")) font.setPointSize(12) self.label_semester.setFont(font) self.label_semester.setObjectName(_fromUtf8("label_semester")) self.pushButton_save = QtGui.QPushButton(Dialog_add_subject) self.pushButton_save.setGeometry(QtCore.QRect(190, 290, 111, 31)) font = QtGui.QFont() font.setFamily(_fromUtf8("Times New Roman")) font.setPointSize(10) self.pushButton_save.setFont(font) icon1 = QtGui.QIcon() icon1.addPixmap(QtGui.QPixmap(_fromUtf8("Qt_interface/SE_syllabus/Save-as.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton_save.setIcon(icon1) self.pushButton_save.setIconSize(QtCore.QSize(20, 20)) self.pushButton_save.setObjectName(_fromUtf8("pushButton_save")) self.pushButton_cancel = QtGui.QPushButton(Dialog_add_subject) self.pushButton_cancel.setGeometry(QtCore.QRect(340, 290, 111, 31)) font = QtGui.QFont() font.setFamily(_fromUtf8("Times New Roman")) self.pushButton_cancel.setFont(font) icon2 = QtGui.QIcon() icon2.addPixmap(QtGui.QPixmap(_fromUtf8("Qt_interface/SE_syllabus/if_draw-08_725558.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton_cancel.setIcon(icon2) self.pushButton_cancel.setIconSize(QtCore.QSize(20, 20)) self.pushButton_cancel.setObjectName(_fromUtf8("pushButton_cancel")) self.comboBox_year = QtGui.QComboBox(Dialog_add_subject) self.comboBox_year.setGeometry(QtCore.QRect(190, 91, 111, 31)) font = QtGui.QFont() font.setFamily(_fromUtf8("Times New Roman")) font.setPointSize(12) self.comboBox_year.setFont(font) self.comboBox_year.setObjectName(_fromUtf8("comboBox_year")) self.comboBox_semester = QtGui.QComboBox(Dialog_add_subject) self.comboBox_semester.setGeometry(QtCore.QRect(190, 160, 111, 31)) font = QtGui.QFont() font.setFamily(_fromUtf8("Times New Roman")) font.setPointSize(12) self.comboBox_semester.setFont(font) self.comboBox_semester.setObjectName(_fromUtf8("comboBox_semester")) self.retranslateUi(Dialog_add_subject) QtCore.QObject.connect(self.pushButton_cancel, QtCore.SIGNAL(_fromUtf8("clicked()")), self.lineEdit_subject_name.clear) QtCore.QMetaObject.connectSlotsByName(Dialog_add_subject) def retranslateUi(self, Dialog_add_subject): Dialog_add_subject.setWindowTitle(_translate("Dialog_add_subject", "Dialog", None)) self.lbl_subject_name.setText(_translate("Dialog_add_subject", "SUBJECT NAME", None)) self.label_add_subject.setText(_translate("Dialog_add_subject", "ADD SUBJECT", None)) self.label_year.setText(_translate("Dialog_add_subject", "YEAR", None)) self.label_semester.setText(_translate("Dialog_add_subject", "SEMESTER", None)) self.pushButton_save.setText(_translate("Dialog_add_subject", "SAVE", None)) self.pushButton_cancel.setText(_translate("Dialog_add_subject", "CANCEL", None)) if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) Dialog_add_subject = QtGui.QDialog() ui = Ui_Dialog_add_subject() ui.setupUi(Dialog_add_subject) Dialog_add_subject.show() sys.exit(app.exec_())
en
0.705043
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'add_subject.ui' # # Created by: PyQt4 UI code generator 4.11.4 # # WARNING! All changes made in this file will be lost!
1.512617
2
tests/syncdb_signals/tests.py
mdj2/django
1
45
<gh_stars>1-10 from django.db.models import signals from django.test import TestCase from django.core import management from django.utils import six from shared_models import models PRE_SYNCDB_ARGS = ['app', 'create_models', 'verbosity', 'interactive', 'db'] SYNCDB_DATABASE = 'default' SYNCDB_VERBOSITY = 1 SYNCDB_INTERACTIVE = False class PreSyncdbReceiver(object): def __init__(self): self.call_counter = 0 self.call_args = None def __call__(self, signal, sender, **kwargs): self.call_counter = self.call_counter + 1 self.call_args = kwargs class OneTimeReceiver(object): """ Special receiver for handle the fact that test runner calls syncdb for several databases and several times for some of them. """ def __init__(self): self.call_counter = 0 self.call_args = None def __call__(self, signal, sender, **kwargs): # Although test runner calls syncdb for several databases, # testing for only one of them is quite sufficient. if kwargs['db'] == SYNCDB_DATABASE: self.call_counter = self.call_counter + 1 self.call_args = kwargs # we need to test only one call of syncdb signals.pre_syncdb.disconnect(pre_syncdb_receiver, sender=models) # We connect receiver here and not in unit test code because we need to # connect receiver before test runner creates database. That is, sequence of # actions would be: # # 1. Test runner imports this module. # 2. We connect receiver. # 3. Test runner calls syncdb for create default database. # 4. Test runner execute our unit test code. pre_syncdb_receiver = OneTimeReceiver() signals.pre_syncdb.connect(pre_syncdb_receiver, sender=models) class SyncdbSignalTests(TestCase): def test_pre_syncdb_call_time(self): self.assertEqual(pre_syncdb_receiver.call_counter, 1) def test_pre_syncdb_args(self): r = PreSyncdbReceiver() signals.pre_syncdb.connect(r, sender=models) management.call_command('syncdb', database=SYNCDB_DATABASE, verbosity=SYNCDB_VERBOSITY, interactive=SYNCDB_INTERACTIVE, load_initial_data=False, stdout=six.StringIO()) args = r.call_args self.assertEqual(r.call_counter, 1) self.assertEqual(set(args), set(PRE_SYNCDB_ARGS)) self.assertEqual(args['app'], models) self.assertEqual(args['verbosity'], SYNCDB_VERBOSITY) self.assertEqual(args['interactive'], SYNCDB_INTERACTIVE) self.assertEqual(args['db'], 'default')
from django.db.models import signals from django.test import TestCase from django.core import management from django.utils import six from shared_models import models PRE_SYNCDB_ARGS = ['app', 'create_models', 'verbosity', 'interactive', 'db'] SYNCDB_DATABASE = 'default' SYNCDB_VERBOSITY = 1 SYNCDB_INTERACTIVE = False class PreSyncdbReceiver(object): def __init__(self): self.call_counter = 0 self.call_args = None def __call__(self, signal, sender, **kwargs): self.call_counter = self.call_counter + 1 self.call_args = kwargs class OneTimeReceiver(object): """ Special receiver for handle the fact that test runner calls syncdb for several databases and several times for some of them. """ def __init__(self): self.call_counter = 0 self.call_args = None def __call__(self, signal, sender, **kwargs): # Although test runner calls syncdb for several databases, # testing for only one of them is quite sufficient. if kwargs['db'] == SYNCDB_DATABASE: self.call_counter = self.call_counter + 1 self.call_args = kwargs # we need to test only one call of syncdb signals.pre_syncdb.disconnect(pre_syncdb_receiver, sender=models) # We connect receiver here and not in unit test code because we need to # connect receiver before test runner creates database. That is, sequence of # actions would be: # # 1. Test runner imports this module. # 2. We connect receiver. # 3. Test runner calls syncdb for create default database. # 4. Test runner execute our unit test code. pre_syncdb_receiver = OneTimeReceiver() signals.pre_syncdb.connect(pre_syncdb_receiver, sender=models) class SyncdbSignalTests(TestCase): def test_pre_syncdb_call_time(self): self.assertEqual(pre_syncdb_receiver.call_counter, 1) def test_pre_syncdb_args(self): r = PreSyncdbReceiver() signals.pre_syncdb.connect(r, sender=models) management.call_command('syncdb', database=SYNCDB_DATABASE, verbosity=SYNCDB_VERBOSITY, interactive=SYNCDB_INTERACTIVE, load_initial_data=False, stdout=six.StringIO()) args = r.call_args self.assertEqual(r.call_counter, 1) self.assertEqual(set(args), set(PRE_SYNCDB_ARGS)) self.assertEqual(args['app'], models) self.assertEqual(args['verbosity'], SYNCDB_VERBOSITY) self.assertEqual(args['interactive'], SYNCDB_INTERACTIVE) self.assertEqual(args['db'], 'default')
en
0.925449
Special receiver for handle the fact that test runner calls syncdb for several databases and several times for some of them. # Although test runner calls syncdb for several databases, # testing for only one of them is quite sufficient. # we need to test only one call of syncdb # We connect receiver here and not in unit test code because we need to # connect receiver before test runner creates database. That is, sequence of # actions would be: # # 1. Test runner imports this module. # 2. We connect receiver. # 3. Test runner calls syncdb for create default database. # 4. Test runner execute our unit test code.
2.484524
2
pytorch_lightning/plugins/environments/slurm_environment.py
gianscarpe/pytorch-lightning
0
46
# Copyright The PyTorch Lightning team. # # 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 logging import os import re from pytorch_lightning.plugins.environments.cluster_environment import ClusterEnvironment log = logging.getLogger(__name__) class SLURMEnvironment(ClusterEnvironment): """Cluster environment for training on a cluster managed by SLURM.""" @property def creates_processes_externally(self) -> bool: return True @staticmethod def detect() -> bool: """Returns ``True`` if the current process was launched on a SLURM cluster.""" return "SLURM_NTASKS" in os.environ @property def main_address(self) -> str: # figure out the root node addr slurm_nodelist = os.environ.get("SLURM_NODELIST") if slurm_nodelist: root_node = slurm_nodelist.split(" ")[0].split(",")[0] else: root_node = "127.0.0.1" root_node = self.resolve_root_node_address(root_node) os.environ["MASTER_ADDR"] = root_node log.debug(f"MASTER_ADDR: {os.environ['MASTER_ADDR']}") return root_node @property def main_port(self) -> int: # ----------------------- # SLURM JOB = PORT number # ----------------------- # this way every process knows what port to use default_port = os.environ.get("SLURM_JOB_ID") if default_port: # use the last 4 numbers in the job id as the id default_port = default_port[-4:] # all ports should be in the 10k+ range default_port = int(default_port) + 15000 else: default_port = 12910 # ----------------------- # PORT NUMBER = MASTER_PORT # ----------------------- # in case the user passed it in if "MASTER_PORT" in os.environ: default_port = os.environ["MASTER_PORT"] else: os.environ["MASTER_PORT"] = str(default_port) log.debug(f"MASTER_PORT: {os.environ['MASTER_PORT']}") return int(default_port) def world_size(self) -> int: return int(os.environ["SLURM_NTASKS"]) def set_world_size(self, size: int) -> None: log.debug("SLURMEnvironment.set_world_size was called, but setting world size is not allowed. Ignored.") def global_rank(self) -> int: return int(os.environ["SLURM_PROCID"]) def set_global_rank(self, rank: int) -> None: log.debug("SLURMEnvironment.set_global_rank was called, but setting global rank is not allowed. Ignored.") def local_rank(self) -> int: return int(os.environ["SLURM_LOCALID"]) def node_rank(self) -> int: return int(os.environ["SLURM_NODEID"]) def resolve_root_node_address(self, root_node: str) -> str: if "[" in root_node: name, numbers = root_node.split("[", maxsplit=1) number = numbers.split(",", maxsplit=1)[0] if "-" in number: number = number.split("-")[0] number = re.sub("[^0-9]", "", number) root_node = name + number return root_node
# Copyright The PyTorch Lightning team. # # 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 logging import os import re from pytorch_lightning.plugins.environments.cluster_environment import ClusterEnvironment log = logging.getLogger(__name__) class SLURMEnvironment(ClusterEnvironment): """Cluster environment for training on a cluster managed by SLURM.""" @property def creates_processes_externally(self) -> bool: return True @staticmethod def detect() -> bool: """Returns ``True`` if the current process was launched on a SLURM cluster.""" return "SLURM_NTASKS" in os.environ @property def main_address(self) -> str: # figure out the root node addr slurm_nodelist = os.environ.get("SLURM_NODELIST") if slurm_nodelist: root_node = slurm_nodelist.split(" ")[0].split(",")[0] else: root_node = "127.0.0.1" root_node = self.resolve_root_node_address(root_node) os.environ["MASTER_ADDR"] = root_node log.debug(f"MASTER_ADDR: {os.environ['MASTER_ADDR']}") return root_node @property def main_port(self) -> int: # ----------------------- # SLURM JOB = PORT number # ----------------------- # this way every process knows what port to use default_port = os.environ.get("SLURM_JOB_ID") if default_port: # use the last 4 numbers in the job id as the id default_port = default_port[-4:] # all ports should be in the 10k+ range default_port = int(default_port) + 15000 else: default_port = 12910 # ----------------------- # PORT NUMBER = MASTER_PORT # ----------------------- # in case the user passed it in if "MASTER_PORT" in os.environ: default_port = os.environ["MASTER_PORT"] else: os.environ["MASTER_PORT"] = str(default_port) log.debug(f"MASTER_PORT: {os.environ['MASTER_PORT']}") return int(default_port) def world_size(self) -> int: return int(os.environ["SLURM_NTASKS"]) def set_world_size(self, size: int) -> None: log.debug("SLURMEnvironment.set_world_size was called, but setting world size is not allowed. Ignored.") def global_rank(self) -> int: return int(os.environ["SLURM_PROCID"]) def set_global_rank(self, rank: int) -> None: log.debug("SLURMEnvironment.set_global_rank was called, but setting global rank is not allowed. Ignored.") def local_rank(self) -> int: return int(os.environ["SLURM_LOCALID"]) def node_rank(self) -> int: return int(os.environ["SLURM_NODEID"]) def resolve_root_node_address(self, root_node: str) -> str: if "[" in root_node: name, numbers = root_node.split("[", maxsplit=1) number = numbers.split(",", maxsplit=1)[0] if "-" in number: number = number.split("-")[0] number = re.sub("[^0-9]", "", number) root_node = name + number return root_node
en
0.851125
# Copyright The PyTorch Lightning team. # # 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. Cluster environment for training on a cluster managed by SLURM. Returns ``True`` if the current process was launched on a SLURM cluster. # figure out the root node addr # ----------------------- # SLURM JOB = PORT number # ----------------------- # this way every process knows what port to use # use the last 4 numbers in the job id as the id # all ports should be in the 10k+ range # ----------------------- # PORT NUMBER = MASTER_PORT # ----------------------- # in case the user passed it in
2.026165
2
examples/mouse.py
ginkage/trackball-python
22
47
<filename>examples/mouse.py #!/usr/bin/env python import time import os import math from trackball import TrackBall print("""Trackball: Mouse Use the trackball as a mouse in Raspbian, with right-click when the switch is pressed. Press Ctrl+C to exit! """) trackball = TrackBall(interrupt_pin=4) trackball.set_rgbw(0, 0, 0, 0) # Check for xte (used to control mouse) use_xte = os.system('which xte') == 0 if use_xte == 0: raise RuntimeError("xte not found. Did you sudo apt install xautomation?") while True: up, down, left, right, switch, state = trackball.read() # Send movements and clicks to xte if switch: cmd = 'xte "mouseclick 1"' os.system(cmd) elif right or up or left or down: x = right - left x = math.copysign(x**2, x) y = down - up y = math.copysign(y**2, y) cmd = 'xte "mousermove {} {}"'.format(int(x), int(y)) os.system(cmd) time.sleep(0.0001)
<filename>examples/mouse.py #!/usr/bin/env python import time import os import math from trackball import TrackBall print("""Trackball: Mouse Use the trackball as a mouse in Raspbian, with right-click when the switch is pressed. Press Ctrl+C to exit! """) trackball = TrackBall(interrupt_pin=4) trackball.set_rgbw(0, 0, 0, 0) # Check for xte (used to control mouse) use_xte = os.system('which xte') == 0 if use_xte == 0: raise RuntimeError("xte not found. Did you sudo apt install xautomation?") while True: up, down, left, right, switch, state = trackball.read() # Send movements and clicks to xte if switch: cmd = 'xte "mouseclick 1"' os.system(cmd) elif right or up or left or down: x = right - left x = math.copysign(x**2, x) y = down - up y = math.copysign(y**2, y) cmd = 'xte "mousermove {} {}"'.format(int(x), int(y)) os.system(cmd) time.sleep(0.0001)
en
0.802014
#!/usr/bin/env python Trackball: Mouse Use the trackball as a mouse in Raspbian, with right-click when the switch is pressed. Press Ctrl+C to exit! # Check for xte (used to control mouse) # Send movements and clicks to xte
3.554374
4
garaged/src/garage/tf/regressors/gaussian_mlp_regressor_model.py
artberryx/LSD
7
48
<filename>garaged/src/garage/tf/regressors/gaussian_mlp_regressor_model.py """GaussianMLPRegressorModel.""" import numpy as np import tensorflow as tf import tensorflow_probability as tfp from garage.experiment import deterministic from garage.tf.models import GaussianMLPModel class GaussianMLPRegressorModel(GaussianMLPModel): """GaussianMLPRegressor based on garage.tf.models.Model class. This class can be used to perform regression by fitting a Gaussian distribution to the outputs. Args: input_shape (tuple[int]): Input shape of the training data. output_dim (int): Output dimension of the model. name (str): Model name, also the variable scope. hidden_sizes (list[int]): Output dimension of dense layer(s) for the MLP for mean. For example, (32, 32) means the MLP consists of two hidden layers, each with 32 hidden units. hidden_nonlinearity (callable): Activation function for intermediate dense layer(s). It should return a tf.Tensor. Set it to None to maintain a linear activation. hidden_w_init (callable): Initializer function for the weight of intermediate dense layer(s). The function should return a tf.Tensor. hidden_b_init (callable): Initializer function for the bias of intermediate dense layer(s). The function should return a tf.Tensor. output_nonlinearity (callable): Activation function for output dense layer. It should return a tf.Tensor. Set it to None to maintain a linear activation. output_w_init (callable): Initializer function for the weight of output dense layer(s). The function should return a tf.Tensor. output_b_init (callable): Initializer function for the bias of output dense layer(s). The function should return a tf.Tensor. learn_std (bool): Is std trainable. init_std (float): Initial value for std. adaptive_std (bool): Is std a neural network. If False, it will be a parameter. std_share_network (bool): Boolean for whether mean and std share the same network. std_hidden_sizes (list[int]): Output dimension of dense layer(s) for the MLP for std. For example, (32, 32) means the MLP consists of two hidden layers, each with 32 hidden units. min_std (float): If not None, the std is at least the value of min_std, to avoid numerical issues. max_std (float): If not None, the std is at most the value of max_std, to avoid numerical issues. std_hidden_nonlinearity (callable): Nonlinearity for each hidden layer in the std network. std_hidden_w_init (callable): Initializer function for the weight of intermediate dense layer(s) in the std network. std_hidden_b_init (callable): Initializer function for the bias of intermediate dense layer(s) in the std network. std_output_nonlinearity (callable): Activation function for output dense layer in the std network. It should return a tf.Tensor. Set it to None to maintain a linear activation. std_output_w_init (callable): Initializer function for the weight of output dense layer(s) in the std network. std_parameterization (str): How the std should be parametrized. There are two options: - exp: the logarithm of the std will be stored, and applied a exponential transformation - softplus: the std will be computed as log(1+exp(x)) layer_normalization (bool): Bool for using layer normalization or not. """ def __init__(self, input_shape, output_dim, name='GaussianMLPRegressorModel', hidden_sizes=(32, 32), hidden_nonlinearity=tf.nn.tanh, hidden_w_init=tf.initializers.glorot_uniform( seed=deterministic.get_tf_seed_stream()), hidden_b_init=tf.zeros_initializer(), output_nonlinearity=None, output_w_init=tf.initializers.glorot_uniform( seed=deterministic.get_tf_seed_stream()), output_b_init=tf.zeros_initializer(), learn_std=True, adaptive_std=False, std_share_network=False, init_std=1.0, min_std=1e-6, max_std=None, std_hidden_sizes=(32, 32), std_hidden_nonlinearity=tf.nn.tanh, std_hidden_w_init=tf.initializers.glorot_uniform( seed=deterministic.get_tf_seed_stream()), std_hidden_b_init=tf.zeros_initializer(), std_output_nonlinearity=None, std_output_w_init=tf.initializers.glorot_uniform( seed=deterministic.get_tf_seed_stream()), std_parameterization='exp', layer_normalization=False): super().__init__(output_dim=output_dim, name=name, hidden_sizes=hidden_sizes, hidden_nonlinearity=hidden_nonlinearity, hidden_w_init=hidden_w_init, hidden_b_init=hidden_b_init, output_nonlinearity=output_nonlinearity, output_w_init=output_w_init, output_b_init=output_b_init, learn_std=learn_std, adaptive_std=adaptive_std, std_share_network=std_share_network, init_std=init_std, min_std=min_std, max_std=max_std, std_hidden_sizes=std_hidden_sizes, std_hidden_nonlinearity=std_hidden_nonlinearity, std_output_nonlinearity=std_output_nonlinearity, std_parameterization=std_parameterization, layer_normalization=layer_normalization) self._input_shape = input_shape def network_output_spec(self): """Network output spec. Return: list[str]: List of key(str) for the network outputs. """ return [ 'normalized_dist', 'normalized_mean', 'normalized_log_std', 'dist', 'mean', 'log_std', 'x_mean', 'x_std', 'y_mean', 'y_std' ] def _build(self, state_input, name=None): """Build model given input placeholder(s). Args: state_input (tf.Tensor): Place holder for state input. name (str): Inner model name, also the variable scope of the inner model, if exist. One example is garage.tf.models.Sequential. Return: tfp.distributions.MultivariateNormalDiag: Normlizaed distribution. tf.Tensor: Normalized mean. tf.Tensor: Normalized log_std. tfp.distributions.MultivariateNormalDiag: Vanilla distribution. tf.Tensor: Vanilla mean. tf.Tensor: Vanilla log_std. tf.Tensor: Mean for data. tf.Tensor: log_std for data. tf.Tensor: Mean for label. tf.Tensor: log_std for label. """ with tf.compat.v1.variable_scope('normalized_vars'): x_mean_var = tf.compat.v1.get_variable( name='x_mean', shape=(1, ) + self._input_shape, dtype=np.float32, initializer=tf.zeros_initializer(), trainable=False) x_std_var = tf.compat.v1.get_variable( name='x_std_var', shape=(1, ) + self._input_shape, dtype=np.float32, initializer=tf.ones_initializer(), trainable=False) y_mean_var = tf.compat.v1.get_variable( name='y_mean_var', shape=(1, self._output_dim), dtype=np.float32, initializer=tf.zeros_initializer(), trainable=False) y_std_var = tf.compat.v1.get_variable( name='y_std_var', shape=(1, self._output_dim), dtype=np.float32, initializer=tf.ones_initializer(), trainable=False) normalized_xs_var = (state_input - x_mean_var) / x_std_var _, normalized_dist_mean, normalized_dist_log_std = super()._build( normalized_xs_var) # Since regressor expects [N, *dims], we need to squeeze the extra # dimension normalized_dist_log_std = tf.squeeze(normalized_dist_log_std, 1) with tf.name_scope('mean_network'): means_var = normalized_dist_mean * y_std_var + y_mean_var with tf.name_scope('std_network'): log_stds_var = normalized_dist_log_std + tf.math.log(y_std_var) normalized_dist = tfp.distributions.MultivariateNormalDiag( loc=normalized_dist_mean, scale_diag=tf.exp(normalized_dist_log_std)) vanilla_dist = tfp.distributions.MultivariateNormalDiag( loc=means_var, scale_diag=tf.exp(log_stds_var)) return (normalized_dist, normalized_dist_mean, normalized_dist_log_std, vanilla_dist, means_var, log_stds_var, x_mean_var, x_std_var, y_mean_var, y_std_var) def clone(self, name): """Return a clone of the model. It copies the configuration and parameters of the primitive. Args: name (str): Name of the newly created model. It has to be different from source model if cloned under the same computational graph. Returns: garage.tf.policies.GaussianMLPModel: Newly cloned model. """ new_regressor = self.__class__( name=name, input_shape=self._input_shape, output_dim=self._output_dim, hidden_sizes=self._hidden_sizes, hidden_nonlinearity=self._hidden_nonlinearity, hidden_w_init=self._hidden_w_init, hidden_b_init=self._hidden_b_init, output_nonlinearity=self._output_nonlinearity, output_w_init=self._output_w_init, output_b_init=self._output_b_init, learn_std=self._learn_std, adaptive_std=self._adaptive_std, std_share_network=self._std_share_network, init_std=self._init_std, min_std=self._min_std, max_std=self._max_std, std_hidden_sizes=self._std_hidden_sizes, std_hidden_nonlinearity=self._std_hidden_nonlinearity, std_hidden_w_init=self._std_hidden_w_init, std_hidden_b_init=self._std_hidden_b_init, std_output_nonlinearity=self._std_output_nonlinearity, std_output_w_init=self._std_output_w_init, std_parameterization=self._std_parameterization, layer_normalization=self._layer_normalization) new_regressor.parameters = self.parameters return new_regressor
<filename>garaged/src/garage/tf/regressors/gaussian_mlp_regressor_model.py """GaussianMLPRegressorModel.""" import numpy as np import tensorflow as tf import tensorflow_probability as tfp from garage.experiment import deterministic from garage.tf.models import GaussianMLPModel class GaussianMLPRegressorModel(GaussianMLPModel): """GaussianMLPRegressor based on garage.tf.models.Model class. This class can be used to perform regression by fitting a Gaussian distribution to the outputs. Args: input_shape (tuple[int]): Input shape of the training data. output_dim (int): Output dimension of the model. name (str): Model name, also the variable scope. hidden_sizes (list[int]): Output dimension of dense layer(s) for the MLP for mean. For example, (32, 32) means the MLP consists of two hidden layers, each with 32 hidden units. hidden_nonlinearity (callable): Activation function for intermediate dense layer(s). It should return a tf.Tensor. Set it to None to maintain a linear activation. hidden_w_init (callable): Initializer function for the weight of intermediate dense layer(s). The function should return a tf.Tensor. hidden_b_init (callable): Initializer function for the bias of intermediate dense layer(s). The function should return a tf.Tensor. output_nonlinearity (callable): Activation function for output dense layer. It should return a tf.Tensor. Set it to None to maintain a linear activation. output_w_init (callable): Initializer function for the weight of output dense layer(s). The function should return a tf.Tensor. output_b_init (callable): Initializer function for the bias of output dense layer(s). The function should return a tf.Tensor. learn_std (bool): Is std trainable. init_std (float): Initial value for std. adaptive_std (bool): Is std a neural network. If False, it will be a parameter. std_share_network (bool): Boolean for whether mean and std share the same network. std_hidden_sizes (list[int]): Output dimension of dense layer(s) for the MLP for std. For example, (32, 32) means the MLP consists of two hidden layers, each with 32 hidden units. min_std (float): If not None, the std is at least the value of min_std, to avoid numerical issues. max_std (float): If not None, the std is at most the value of max_std, to avoid numerical issues. std_hidden_nonlinearity (callable): Nonlinearity for each hidden layer in the std network. std_hidden_w_init (callable): Initializer function for the weight of intermediate dense layer(s) in the std network. std_hidden_b_init (callable): Initializer function for the bias of intermediate dense layer(s) in the std network. std_output_nonlinearity (callable): Activation function for output dense layer in the std network. It should return a tf.Tensor. Set it to None to maintain a linear activation. std_output_w_init (callable): Initializer function for the weight of output dense layer(s) in the std network. std_parameterization (str): How the std should be parametrized. There are two options: - exp: the logarithm of the std will be stored, and applied a exponential transformation - softplus: the std will be computed as log(1+exp(x)) layer_normalization (bool): Bool for using layer normalization or not. """ def __init__(self, input_shape, output_dim, name='GaussianMLPRegressorModel', hidden_sizes=(32, 32), hidden_nonlinearity=tf.nn.tanh, hidden_w_init=tf.initializers.glorot_uniform( seed=deterministic.get_tf_seed_stream()), hidden_b_init=tf.zeros_initializer(), output_nonlinearity=None, output_w_init=tf.initializers.glorot_uniform( seed=deterministic.get_tf_seed_stream()), output_b_init=tf.zeros_initializer(), learn_std=True, adaptive_std=False, std_share_network=False, init_std=1.0, min_std=1e-6, max_std=None, std_hidden_sizes=(32, 32), std_hidden_nonlinearity=tf.nn.tanh, std_hidden_w_init=tf.initializers.glorot_uniform( seed=deterministic.get_tf_seed_stream()), std_hidden_b_init=tf.zeros_initializer(), std_output_nonlinearity=None, std_output_w_init=tf.initializers.glorot_uniform( seed=deterministic.get_tf_seed_stream()), std_parameterization='exp', layer_normalization=False): super().__init__(output_dim=output_dim, name=name, hidden_sizes=hidden_sizes, hidden_nonlinearity=hidden_nonlinearity, hidden_w_init=hidden_w_init, hidden_b_init=hidden_b_init, output_nonlinearity=output_nonlinearity, output_w_init=output_w_init, output_b_init=output_b_init, learn_std=learn_std, adaptive_std=adaptive_std, std_share_network=std_share_network, init_std=init_std, min_std=min_std, max_std=max_std, std_hidden_sizes=std_hidden_sizes, std_hidden_nonlinearity=std_hidden_nonlinearity, std_output_nonlinearity=std_output_nonlinearity, std_parameterization=std_parameterization, layer_normalization=layer_normalization) self._input_shape = input_shape def network_output_spec(self): """Network output spec. Return: list[str]: List of key(str) for the network outputs. """ return [ 'normalized_dist', 'normalized_mean', 'normalized_log_std', 'dist', 'mean', 'log_std', 'x_mean', 'x_std', 'y_mean', 'y_std' ] def _build(self, state_input, name=None): """Build model given input placeholder(s). Args: state_input (tf.Tensor): Place holder for state input. name (str): Inner model name, also the variable scope of the inner model, if exist. One example is garage.tf.models.Sequential. Return: tfp.distributions.MultivariateNormalDiag: Normlizaed distribution. tf.Tensor: Normalized mean. tf.Tensor: Normalized log_std. tfp.distributions.MultivariateNormalDiag: Vanilla distribution. tf.Tensor: Vanilla mean. tf.Tensor: Vanilla log_std. tf.Tensor: Mean for data. tf.Tensor: log_std for data. tf.Tensor: Mean for label. tf.Tensor: log_std for label. """ with tf.compat.v1.variable_scope('normalized_vars'): x_mean_var = tf.compat.v1.get_variable( name='x_mean', shape=(1, ) + self._input_shape, dtype=np.float32, initializer=tf.zeros_initializer(), trainable=False) x_std_var = tf.compat.v1.get_variable( name='x_std_var', shape=(1, ) + self._input_shape, dtype=np.float32, initializer=tf.ones_initializer(), trainable=False) y_mean_var = tf.compat.v1.get_variable( name='y_mean_var', shape=(1, self._output_dim), dtype=np.float32, initializer=tf.zeros_initializer(), trainable=False) y_std_var = tf.compat.v1.get_variable( name='y_std_var', shape=(1, self._output_dim), dtype=np.float32, initializer=tf.ones_initializer(), trainable=False) normalized_xs_var = (state_input - x_mean_var) / x_std_var _, normalized_dist_mean, normalized_dist_log_std = super()._build( normalized_xs_var) # Since regressor expects [N, *dims], we need to squeeze the extra # dimension normalized_dist_log_std = tf.squeeze(normalized_dist_log_std, 1) with tf.name_scope('mean_network'): means_var = normalized_dist_mean * y_std_var + y_mean_var with tf.name_scope('std_network'): log_stds_var = normalized_dist_log_std + tf.math.log(y_std_var) normalized_dist = tfp.distributions.MultivariateNormalDiag( loc=normalized_dist_mean, scale_diag=tf.exp(normalized_dist_log_std)) vanilla_dist = tfp.distributions.MultivariateNormalDiag( loc=means_var, scale_diag=tf.exp(log_stds_var)) return (normalized_dist, normalized_dist_mean, normalized_dist_log_std, vanilla_dist, means_var, log_stds_var, x_mean_var, x_std_var, y_mean_var, y_std_var) def clone(self, name): """Return a clone of the model. It copies the configuration and parameters of the primitive. Args: name (str): Name of the newly created model. It has to be different from source model if cloned under the same computational graph. Returns: garage.tf.policies.GaussianMLPModel: Newly cloned model. """ new_regressor = self.__class__( name=name, input_shape=self._input_shape, output_dim=self._output_dim, hidden_sizes=self._hidden_sizes, hidden_nonlinearity=self._hidden_nonlinearity, hidden_w_init=self._hidden_w_init, hidden_b_init=self._hidden_b_init, output_nonlinearity=self._output_nonlinearity, output_w_init=self._output_w_init, output_b_init=self._output_b_init, learn_std=self._learn_std, adaptive_std=self._adaptive_std, std_share_network=self._std_share_network, init_std=self._init_std, min_std=self._min_std, max_std=self._max_std, std_hidden_sizes=self._std_hidden_sizes, std_hidden_nonlinearity=self._std_hidden_nonlinearity, std_hidden_w_init=self._std_hidden_w_init, std_hidden_b_init=self._std_hidden_b_init, std_output_nonlinearity=self._std_output_nonlinearity, std_output_w_init=self._std_output_w_init, std_parameterization=self._std_parameterization, layer_normalization=self._layer_normalization) new_regressor.parameters = self.parameters return new_regressor
en
0.689634
GaussianMLPRegressorModel. GaussianMLPRegressor based on garage.tf.models.Model class. This class can be used to perform regression by fitting a Gaussian distribution to the outputs. Args: input_shape (tuple[int]): Input shape of the training data. output_dim (int): Output dimension of the model. name (str): Model name, also the variable scope. hidden_sizes (list[int]): Output dimension of dense layer(s) for the MLP for mean. For example, (32, 32) means the MLP consists of two hidden layers, each with 32 hidden units. hidden_nonlinearity (callable): Activation function for intermediate dense layer(s). It should return a tf.Tensor. Set it to None to maintain a linear activation. hidden_w_init (callable): Initializer function for the weight of intermediate dense layer(s). The function should return a tf.Tensor. hidden_b_init (callable): Initializer function for the bias of intermediate dense layer(s). The function should return a tf.Tensor. output_nonlinearity (callable): Activation function for output dense layer. It should return a tf.Tensor. Set it to None to maintain a linear activation. output_w_init (callable): Initializer function for the weight of output dense layer(s). The function should return a tf.Tensor. output_b_init (callable): Initializer function for the bias of output dense layer(s). The function should return a tf.Tensor. learn_std (bool): Is std trainable. init_std (float): Initial value for std. adaptive_std (bool): Is std a neural network. If False, it will be a parameter. std_share_network (bool): Boolean for whether mean and std share the same network. std_hidden_sizes (list[int]): Output dimension of dense layer(s) for the MLP for std. For example, (32, 32) means the MLP consists of two hidden layers, each with 32 hidden units. min_std (float): If not None, the std is at least the value of min_std, to avoid numerical issues. max_std (float): If not None, the std is at most the value of max_std, to avoid numerical issues. std_hidden_nonlinearity (callable): Nonlinearity for each hidden layer in the std network. std_hidden_w_init (callable): Initializer function for the weight of intermediate dense layer(s) in the std network. std_hidden_b_init (callable): Initializer function for the bias of intermediate dense layer(s) in the std network. std_output_nonlinearity (callable): Activation function for output dense layer in the std network. It should return a tf.Tensor. Set it to None to maintain a linear activation. std_output_w_init (callable): Initializer function for the weight of output dense layer(s) in the std network. std_parameterization (str): How the std should be parametrized. There are two options: - exp: the logarithm of the std will be stored, and applied a exponential transformation - softplus: the std will be computed as log(1+exp(x)) layer_normalization (bool): Bool for using layer normalization or not. Network output spec. Return: list[str]: List of key(str) for the network outputs. Build model given input placeholder(s). Args: state_input (tf.Tensor): Place holder for state input. name (str): Inner model name, also the variable scope of the inner model, if exist. One example is garage.tf.models.Sequential. Return: tfp.distributions.MultivariateNormalDiag: Normlizaed distribution. tf.Tensor: Normalized mean. tf.Tensor: Normalized log_std. tfp.distributions.MultivariateNormalDiag: Vanilla distribution. tf.Tensor: Vanilla mean. tf.Tensor: Vanilla log_std. tf.Tensor: Mean for data. tf.Tensor: log_std for data. tf.Tensor: Mean for label. tf.Tensor: log_std for label. # Since regressor expects [N, *dims], we need to squeeze the extra # dimension Return a clone of the model. It copies the configuration and parameters of the primitive. Args: name (str): Name of the newly created model. It has to be different from source model if cloned under the same computational graph. Returns: garage.tf.policies.GaussianMLPModel: Newly cloned model.
2.805858
3
test.py
kim-sunghoon/DiracDeltaNet
0
49
<filename>test.py import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import torch.backends.cudnn as cudnn import torchvision import torchvision.transforms as transforms import torchvision.datasets as datasets import os import argparse from torch.autograd import Variable from extensions.utils import progress_bar from extensions.model_refinery_wrapper import ModelRefineryWrapper from extensions.refinery_loss import RefineryLoss from models import ShuffleNetv2_wrapper from models import DiracDeltaNet_wrapper parser = argparse.ArgumentParser(description='PyTorch imagenet inference') parser.add_argument('--datadir', help='path to dataset') parser.add_argument('--inputdir', help='path to input model') args = parser.parse_args() # Data print('==> Preparing data..') # Data loading code valdir = os.path.join(args.datadir, 'val') normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) transform_test = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), normalize, ]) #imagenet testset = datasets.ImageFolder(valdir, transform_test) num_classes=1000 testloader = torch.utils.data.DataLoader(testset, batch_size=1000, shuffle=False, pin_memory=True, num_workers=30) use_cuda = torch.cuda.is_available() print('Using input path: %s' % args.inputdir) checkpoint = torch.load(args.inputdir) init_net = checkpoint['net'] net=init_net.to('cpu') label_refinery=torch.load('./resnet50.t7') net = ModelRefineryWrapper(net, label_refinery) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") print(device) if torch.cuda.device_count() > 1: print("Let's use", torch.cuda.device_count(), "GPUs!") net = nn.DataParallel(net) net=net.to(device) criterion = RefineryLoss() def accuracy(output, target, topk=(1,)): """Computes the precision@k for the specified values of k""" with torch.no_grad(): maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0, keepdim=True) res.append(correct_k) return res def test(): net.eval() criterion.eval() test_loss = 0 correct_1 = 0 correct_5 = 0 total = 0 for batch_idx, (inputs, targets) in enumerate(testloader): if use_cuda: inputs, targets = inputs.cuda(device), targets.cuda(device) with torch.no_grad(): outputs = net(inputs) loss = criterion(outputs, targets) if isinstance(loss, tuple): loss_value, outputs = loss else: loss_value = loss test_loss += loss_value.item() prec1, prec5 = accuracy(outputs, targets, topk=(1, 5)) total += targets.size(0) correct_1 += prec1 correct_5 += prec5 progress_bar(batch_idx, len(testloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)' % (test_loss/(batch_idx+1), 100.*float(correct_1)/float(total), correct_1, total)) return 100.*float(correct_1)/float(total),100.*float(correct_5)/float(total),test_loss acc1,acc5,loss=test() print('top-1 accuracy: {0:.3f}%, top-5 accuracy: {1:.3f}%'.format(acc1,acc5))
<filename>test.py import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F import torch.backends.cudnn as cudnn import torchvision import torchvision.transforms as transforms import torchvision.datasets as datasets import os import argparse from torch.autograd import Variable from extensions.utils import progress_bar from extensions.model_refinery_wrapper import ModelRefineryWrapper from extensions.refinery_loss import RefineryLoss from models import ShuffleNetv2_wrapper from models import DiracDeltaNet_wrapper parser = argparse.ArgumentParser(description='PyTorch imagenet inference') parser.add_argument('--datadir', help='path to dataset') parser.add_argument('--inputdir', help='path to input model') args = parser.parse_args() # Data print('==> Preparing data..') # Data loading code valdir = os.path.join(args.datadir, 'val') normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) transform_test = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), normalize, ]) #imagenet testset = datasets.ImageFolder(valdir, transform_test) num_classes=1000 testloader = torch.utils.data.DataLoader(testset, batch_size=1000, shuffle=False, pin_memory=True, num_workers=30) use_cuda = torch.cuda.is_available() print('Using input path: %s' % args.inputdir) checkpoint = torch.load(args.inputdir) init_net = checkpoint['net'] net=init_net.to('cpu') label_refinery=torch.load('./resnet50.t7') net = ModelRefineryWrapper(net, label_refinery) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") print(device) if torch.cuda.device_count() > 1: print("Let's use", torch.cuda.device_count(), "GPUs!") net = nn.DataParallel(net) net=net.to(device) criterion = RefineryLoss() def accuracy(output, target, topk=(1,)): """Computes the precision@k for the specified values of k""" with torch.no_grad(): maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0, keepdim=True) res.append(correct_k) return res def test(): net.eval() criterion.eval() test_loss = 0 correct_1 = 0 correct_5 = 0 total = 0 for batch_idx, (inputs, targets) in enumerate(testloader): if use_cuda: inputs, targets = inputs.cuda(device), targets.cuda(device) with torch.no_grad(): outputs = net(inputs) loss = criterion(outputs, targets) if isinstance(loss, tuple): loss_value, outputs = loss else: loss_value = loss test_loss += loss_value.item() prec1, prec5 = accuracy(outputs, targets, topk=(1, 5)) total += targets.size(0) correct_1 += prec1 correct_5 += prec5 progress_bar(batch_idx, len(testloader), 'Loss: %.3f | Acc: %.3f%% (%d/%d)' % (test_loss/(batch_idx+1), 100.*float(correct_1)/float(total), correct_1, total)) return 100.*float(correct_1)/float(total),100.*float(correct_5)/float(total),test_loss acc1,acc5,loss=test() print('top-1 accuracy: {0:.3f}%, top-5 accuracy: {1:.3f}%'.format(acc1,acc5))
en
0.210564
# Data # Data loading code #imagenet Computes the precision@k for the specified values of k
2.126636
2
paccmann_chemistry/utils/hyperparams.py
PaccMann/paccmann_chemistry
9
50
<filename>paccmann_chemistry/utils/hyperparams.py """Model Parameters Module.""" import torch.optim as optim from .search import SamplingSearch, GreedySearch, BeamSearch SEARCH_FACTORY = { 'sampling': SamplingSearch, 'greedy': GreedySearch, 'beam': BeamSearch, } OPTIMIZER_FACTORY = { 'adadelta': optim.Adadelta, 'adagrad': optim.Adagrad, 'adam': optim.Adam, 'adamax': optim.Adamax, 'rmsprop': optim.RMSprop, 'sgd': optim.SGD }
<filename>paccmann_chemistry/utils/hyperparams.py """Model Parameters Module.""" import torch.optim as optim from .search import SamplingSearch, GreedySearch, BeamSearch SEARCH_FACTORY = { 'sampling': SamplingSearch, 'greedy': GreedySearch, 'beam': BeamSearch, } OPTIMIZER_FACTORY = { 'adadelta': optim.Adadelta, 'adagrad': optim.Adagrad, 'adam': optim.Adam, 'adamax': optim.Adamax, 'rmsprop': optim.RMSprop, 'sgd': optim.SGD }
hi
0.053798
Model Parameters Module.
1.984104
2
tests/gpflux/layers/test_latent_variable_layer.py
francescodonato/GPflux
100
51
# # Copyright (c) 2021 The GPflux Contributors. # # 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 abc import numpy as np import pytest import tensorflow as tf import tensorflow_probability as tfp from gpflow.kullback_leiblers import gauss_kl from gpflux.encoders import DirectlyParameterizedNormalDiag from gpflux.layers import LatentVariableLayer, LayerWithObservations, TrackableLayer tf.keras.backend.set_floatx("float64") ############ # Utilities ############ def _zero_one_normal_prior(w_dim): """ N(0, I) prior """ return tfp.distributions.MultivariateNormalDiag(loc=np.zeros(w_dim), scale_diag=np.ones(w_dim)) def get_distributions_with_w_dim(): distributions = [] for d in [1, 5]: mean = np.zeros(d) scale_tri_l = np.eye(d) mvn = tfp.distributions.MultivariateNormalTriL(mean, scale_tri_l) std = np.ones(d) mvn_diag = tfp.distributions.MultivariateNormalDiag(mean, std) distributions.append((mvn, d)) distributions.append((mvn_diag, d)) return distributions ############ # Tests ############ @pytest.mark.parametrize("distribution, w_dim", get_distributions_with_w_dim()) def test_local_kls(distribution, w_dim): lv = LatentVariableLayer(encoder=None, prior=distribution) # test kl is 0 when posteriors == priors posterior = distribution assert lv._local_kls(posterior) == 0 # test kl > 0 when posteriors != priors batch_size = 10 params = distribution.parameters posterior_params = { k: [v + 0.5 for _ in range(batch_size)] for k, v in params.items() if isinstance(v, np.ndarray) } posterior = lv.distribution_class(**posterior_params) local_kls = lv._local_kls(posterior) assert np.all(local_kls > 0) assert local_kls.shape == (batch_size,) @pytest.mark.parametrize("w_dim", [1, 5]) def test_local_kl_gpflow_consistency(w_dim): num_data = 400 means = np.random.randn(num_data, w_dim) encoder = DirectlyParameterizedNormalDiag(num_data, w_dim, means) lv = LatentVariableLayer(encoder=encoder, prior=_zero_one_normal_prior(w_dim)) posteriors = lv._inference_posteriors( [np.random.randn(num_data, 3), np.random.randn(num_data, 2)] ) q_mu = posteriors.parameters["loc"] q_sqrt = posteriors.parameters["scale_diag"] gpflow_local_kls = gauss_kl(q_mu, q_sqrt) tfp_local_kls = tf.reduce_sum(lv._local_kls(posteriors)) np.testing.assert_allclose(tfp_local_kls, gpflow_local_kls, rtol=1e-10) class ArrayMatcher: def __init__(self, expected): self.expected = expected def __eq__(self, actual): return np.allclose(actual, self.expected, equal_nan=True) @pytest.mark.parametrize("w_dim", [1, 5]) def test_latent_variable_layer_losses(mocker, w_dim): num_data, x_dim, y_dim = 43, 3, 1 prior_shape = (w_dim,) posteriors_shape = (num_data, w_dim) prior = tfp.distributions.MultivariateNormalDiag( loc=np.random.randn(*prior_shape), scale_diag=np.random.randn(*prior_shape) ** 2, ) posteriors = tfp.distributions.MultivariateNormalDiag( loc=np.random.randn(*posteriors_shape), scale_diag=np.random.randn(*posteriors_shape) ** 2, ) encoder = mocker.Mock(return_value=(posteriors.loc, posteriors.scale.diag)) lv = LatentVariableLayer(encoder=encoder, prior=prior) inputs = np.full((num_data, x_dim), np.nan) targets = np.full((num_data, y_dim), np.nan) observations = [inputs, targets] encoder_inputs = np.concatenate(observations, axis=-1) _ = lv(inputs) encoder.assert_not_called() assert lv.losses == [0.0] _ = lv(inputs, observations=observations, training=True) # assert_called_once_with uses == for comparison which fails on arrays encoder.assert_called_once_with(ArrayMatcher(encoder_inputs), training=True) expected_loss = [tf.reduce_mean(posteriors.kl_divergence(prior))] np.testing.assert_equal(lv.losses, expected_loss) # also checks shapes match @pytest.mark.parametrize("w_dim", [1, 5]) @pytest.mark.parametrize("seed2", [None, 42]) def test_latent_variable_layer_samples(mocker, test_data, w_dim, seed2): seed = 123 inputs, targets = test_data num_data, x_dim = inputs.shape prior_shape = (w_dim,) posteriors_shape = (num_data, w_dim) prior = tfp.distributions.MultivariateNormalDiag( loc=np.random.randn(*prior_shape), scale_diag=np.random.randn(*prior_shape) ** 2, ) posteriors = tfp.distributions.MultivariateNormalDiag( loc=np.random.randn(*posteriors_shape), scale_diag=np.random.randn(*posteriors_shape) ** 2, ) encoder = mocker.Mock(return_value=(posteriors.loc, posteriors.scale.diag)) lv = LatentVariableLayer(prior=prior, encoder=encoder) tf.random.set_seed(seed) sample_prior = lv(inputs, seed=seed2) tf.random.set_seed(seed) prior_expected = np.concatenate([inputs, prior.sample(num_data, seed=seed2)], axis=-1) np.testing.assert_array_equal(sample_prior, prior_expected) tf.random.set_seed(seed) sample_posterior = lv(inputs, observations=[inputs, targets], training=True, seed=seed2) tf.random.set_seed(seed) posterior_expected = np.concatenate([inputs, posteriors.sample(seed=seed2)], axis=-1) np.testing.assert_array_equal(sample_posterior, posterior_expected) def test_no_tensorflow_metaclass_overwritten(): """ LayerWithObservations is a subclass of tf.keras.layers.Layer (via TrackableLayer); this test ensures that TrackableLayer does not have a metaclass, and hence by adding the ABCMeta to LayerWithObservations we are not accidentally removing some required TensorFlow magic metaclass. """ assert LayerWithObservations.__bases__ == (TrackableLayer,) assert type(TrackableLayer) is type assert type(LayerWithObservations) is abc.ABCMeta
# # Copyright (c) 2021 The GPflux Contributors. # # 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 abc import numpy as np import pytest import tensorflow as tf import tensorflow_probability as tfp from gpflow.kullback_leiblers import gauss_kl from gpflux.encoders import DirectlyParameterizedNormalDiag from gpflux.layers import LatentVariableLayer, LayerWithObservations, TrackableLayer tf.keras.backend.set_floatx("float64") ############ # Utilities ############ def _zero_one_normal_prior(w_dim): """ N(0, I) prior """ return tfp.distributions.MultivariateNormalDiag(loc=np.zeros(w_dim), scale_diag=np.ones(w_dim)) def get_distributions_with_w_dim(): distributions = [] for d in [1, 5]: mean = np.zeros(d) scale_tri_l = np.eye(d) mvn = tfp.distributions.MultivariateNormalTriL(mean, scale_tri_l) std = np.ones(d) mvn_diag = tfp.distributions.MultivariateNormalDiag(mean, std) distributions.append((mvn, d)) distributions.append((mvn_diag, d)) return distributions ############ # Tests ############ @pytest.mark.parametrize("distribution, w_dim", get_distributions_with_w_dim()) def test_local_kls(distribution, w_dim): lv = LatentVariableLayer(encoder=None, prior=distribution) # test kl is 0 when posteriors == priors posterior = distribution assert lv._local_kls(posterior) == 0 # test kl > 0 when posteriors != priors batch_size = 10 params = distribution.parameters posterior_params = { k: [v + 0.5 for _ in range(batch_size)] for k, v in params.items() if isinstance(v, np.ndarray) } posterior = lv.distribution_class(**posterior_params) local_kls = lv._local_kls(posterior) assert np.all(local_kls > 0) assert local_kls.shape == (batch_size,) @pytest.mark.parametrize("w_dim", [1, 5]) def test_local_kl_gpflow_consistency(w_dim): num_data = 400 means = np.random.randn(num_data, w_dim) encoder = DirectlyParameterizedNormalDiag(num_data, w_dim, means) lv = LatentVariableLayer(encoder=encoder, prior=_zero_one_normal_prior(w_dim)) posteriors = lv._inference_posteriors( [np.random.randn(num_data, 3), np.random.randn(num_data, 2)] ) q_mu = posteriors.parameters["loc"] q_sqrt = posteriors.parameters["scale_diag"] gpflow_local_kls = gauss_kl(q_mu, q_sqrt) tfp_local_kls = tf.reduce_sum(lv._local_kls(posteriors)) np.testing.assert_allclose(tfp_local_kls, gpflow_local_kls, rtol=1e-10) class ArrayMatcher: def __init__(self, expected): self.expected = expected def __eq__(self, actual): return np.allclose(actual, self.expected, equal_nan=True) @pytest.mark.parametrize("w_dim", [1, 5]) def test_latent_variable_layer_losses(mocker, w_dim): num_data, x_dim, y_dim = 43, 3, 1 prior_shape = (w_dim,) posteriors_shape = (num_data, w_dim) prior = tfp.distributions.MultivariateNormalDiag( loc=np.random.randn(*prior_shape), scale_diag=np.random.randn(*prior_shape) ** 2, ) posteriors = tfp.distributions.MultivariateNormalDiag( loc=np.random.randn(*posteriors_shape), scale_diag=np.random.randn(*posteriors_shape) ** 2, ) encoder = mocker.Mock(return_value=(posteriors.loc, posteriors.scale.diag)) lv = LatentVariableLayer(encoder=encoder, prior=prior) inputs = np.full((num_data, x_dim), np.nan) targets = np.full((num_data, y_dim), np.nan) observations = [inputs, targets] encoder_inputs = np.concatenate(observations, axis=-1) _ = lv(inputs) encoder.assert_not_called() assert lv.losses == [0.0] _ = lv(inputs, observations=observations, training=True) # assert_called_once_with uses == for comparison which fails on arrays encoder.assert_called_once_with(ArrayMatcher(encoder_inputs), training=True) expected_loss = [tf.reduce_mean(posteriors.kl_divergence(prior))] np.testing.assert_equal(lv.losses, expected_loss) # also checks shapes match @pytest.mark.parametrize("w_dim", [1, 5]) @pytest.mark.parametrize("seed2", [None, 42]) def test_latent_variable_layer_samples(mocker, test_data, w_dim, seed2): seed = 123 inputs, targets = test_data num_data, x_dim = inputs.shape prior_shape = (w_dim,) posteriors_shape = (num_data, w_dim) prior = tfp.distributions.MultivariateNormalDiag( loc=np.random.randn(*prior_shape), scale_diag=np.random.randn(*prior_shape) ** 2, ) posteriors = tfp.distributions.MultivariateNormalDiag( loc=np.random.randn(*posteriors_shape), scale_diag=np.random.randn(*posteriors_shape) ** 2, ) encoder = mocker.Mock(return_value=(posteriors.loc, posteriors.scale.diag)) lv = LatentVariableLayer(prior=prior, encoder=encoder) tf.random.set_seed(seed) sample_prior = lv(inputs, seed=seed2) tf.random.set_seed(seed) prior_expected = np.concatenate([inputs, prior.sample(num_data, seed=seed2)], axis=-1) np.testing.assert_array_equal(sample_prior, prior_expected) tf.random.set_seed(seed) sample_posterior = lv(inputs, observations=[inputs, targets], training=True, seed=seed2) tf.random.set_seed(seed) posterior_expected = np.concatenate([inputs, posteriors.sample(seed=seed2)], axis=-1) np.testing.assert_array_equal(sample_posterior, posterior_expected) def test_no_tensorflow_metaclass_overwritten(): """ LayerWithObservations is a subclass of tf.keras.layers.Layer (via TrackableLayer); this test ensures that TrackableLayer does not have a metaclass, and hence by adding the ABCMeta to LayerWithObservations we are not accidentally removing some required TensorFlow magic metaclass. """ assert LayerWithObservations.__bases__ == (TrackableLayer,) assert type(TrackableLayer) is type assert type(LayerWithObservations) is abc.ABCMeta
en
0.80935
# # Copyright (c) 2021 The GPflux Contributors. # # 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. # ############ # Utilities ############ N(0, I) prior ############ # Tests ############ # test kl is 0 when posteriors == priors # test kl > 0 when posteriors != priors # assert_called_once_with uses == for comparison which fails on arrays # also checks shapes match LayerWithObservations is a subclass of tf.keras.layers.Layer (via TrackableLayer); this test ensures that TrackableLayer does not have a metaclass, and hence by adding the ABCMeta to LayerWithObservations we are not accidentally removing some required TensorFlow magic metaclass.
1.678736
2
aw-actor-trust.py
actingweb/box-actingweb
0
52
<reponame>actingweb/box-actingweb<filename>aw-actor-trust.py #!/usr/bin/env python # from actingweb import actor from actingweb import config from actingweb import trust from actingweb import auth import webapp2 import os from google.appengine.ext.webapp import template import json import logging import datetime import time # /trust handlers # # GET /trust with query parameters (relationship, type, and peerid) to retrieve trust relationships (auth: only creator and admins allowed) # POST /trust with json body to initiate a trust relationship between this # actor and another (reciprocal relationship) (auth: only creator and admins allowed) # POST /trust/{relationship} with json body to create new trust # relationship (see config.py for default relationship and auto-accept, no # auth required) # GET /trust/{relationship}}/{actorid} to get details on a specific relationship (auth: creator, admin, or peer secret) # POST /trust/{relationship}}/{actorid} to send information to a peer about changes in the relationship # PUT /trust/{relationship}}/{actorid} with a json body to change details on a relationship (baseuri, secret, desc) (auth: creator, # admin, or peer secret) # DELETE /trust/{relationship}}/{actorid} to delete a relationship (with # ?peer=true if the delete is from the peer) (auth: creator, admin, or # peer secret) # Handling requests to trust/ class rootHandler(webapp2.RequestHandler): def get(self, id): if self.request.get('_method') == 'POST': self.post(id) return (Config, myself, check) = auth.init_actingweb(appreq=self, id=id, path='trust') if not myself or check.response["code"] != 200: return if not check.checkAuthorisation(path='trust', method='GET'): self.response.set_status(403) return relationship = '' type = '' peerid = '' relationship = self.request.get('relationship') type = self.request.get('type') peerid = self.request.get('peerid') relationships = myself.getTrustRelationships( relationship=relationship, peerid=peerid, type=type) if not relationships: self.response.set_status(404, 'Not found') return pairs = [] for rel in relationships: pairs.append({ 'baseuri': rel.baseuri, 'id': myself.id, 'peerid': rel.peerid, 'relationship': rel.relationship, 'approved': rel.approved, 'peer_approved': rel.peer_approved, 'verified': rel.verified, 'type': rel.type, 'desc': rel.desc, 'secret': rel.secret, }) out = json.dumps(pairs) self.response.write(out) self.response.headers["Content-Type"] = "application/json" self.response.set_status(200, 'Ok') def post(self, id): (Config, myself, check) = auth.init_actingweb(appreq=self, id=id, path='trust') if not myself or check.response["code"] != 200: return if not check.checkAuthorisation(path='trust', method='POST'): self.response.set_status(403) return secret = '' desc = '' relationship = Config.default_relationship type = '' try: params = json.loads(self.request.body.decode('utf-8', 'ignore')) if 'url' in params: url = params['url'] else: url = '' if 'relationship' in params: relationship = params['relationship'] if 'type' in params: type = params['type'] if 'desc' in params: desc = params['desc'] except ValueError: url = self.request.get('url') relationship = self.request.get('relationship') type = self.request.get('type') if len(url) == 0: self.response.set_status(400, 'Missing peer URL') return secret = Config.newToken() new_trust = myself.createReciprocalTrust( url=url, secret=secret, desc=desc, relationship=relationship, type=type) if not new_trust: self.response.set_status(408, 'Unable to create trust relationship') return self.response.headers.add_header( "Location", str(Config.root + myself.id + '/trust/' + new_trust.relationship + '/' + new_trust.peerid)) pair = { 'baseuri': new_trust.baseuri, 'id': myself.id, 'peerid': new_trust.peerid, 'relationship': new_trust.relationship, 'approved': new_trust.approved, 'peer_approved': new_trust.peer_approved, 'verified': new_trust.verified, 'type': new_trust.type, 'desc': new_trust.desc, 'secret': new_trust.secret, } out = json.dumps(pair) self.response.write(out) self.response.headers["Content-Type"] = "application/json" self.response.set_status(201, 'Created') # Handling requests to /trust/*, e.g. /trust/friend class relationshipHandler(webapp2.RequestHandler): def get(self, id, relationship): if self.request.get('_method') == 'POST': self.post(id, relationship) return self.response.set_status(404, "Not found") def put(self, id, relationship): (Config, myself, check) = auth.init_actingweb(appreq=self, id=id, path='trust', subpath=relationship, add_response=False) if not myself: return if relationship != 'trustee': self.response.set_status(404, "Not found") return # Access is the same as /trust if not check.checkAuthorisation(path='trust', method='POST'): self.response.set_status(403) return try: params = json.loads(self.request.body.decode('utf-8', 'ignore')) if 'trustee_root' in params: trustee_root = params['trustee_root'] else: trustee_root = '' if 'creator' in params: creator = params['creator'] else: creator = None except ValueError: self.response.set_status(400, 'No json content') return if len(trustee_root) > 0: myself.setProperty('trustee_root', trustee_root) if creator: myself.modify(creator=creator) self.response.set_status(204, 'No content') def delete(self, id, relationship): (Config, myself, check) = auth.init_actingweb(appreq=self, id=id, path='trust', subpath=relationship, add_response=False) if not myself: return if relationship != 'trustee': self.response.set_status(404, "Not found") return # Access is the same as /trust if not check.checkAuthorisation(path='trust', method='DELETE'): self.response.set_status(403) return myself.deleteProperty('trustee_root') self.response.set_status(204, 'No content') def post(self, id, relationship): (Config, myself, check) = auth.init_actingweb(appreq=self, id=id, path='trust', subpath=relationship, add_response=False) if not myself: return if not check.checkAuthorisation(path='trust', subpath='<type>', method='POST'): self.response.set_status(403) return try: params = json.loads(self.request.body.decode('utf-8', 'ignore')) if 'baseuri' in params: baseuri = params['baseuri'] else: baseuri = '' if 'id' in params: peerid = params['id'] else: peerid = '' if 'type' in params: type = params['type'] else: type = '' if 'secret' in params: secret = params['secret'] else: secret = '' if 'desc' in params: desc = params['desc'] else: desc = '' if 'verify' in params: verificationToken = params['verify'] else: verificationToken = None except ValueError: self.response.set_status(400, 'No json content') return if len(baseuri) == 0 or len(peerid) == 0 or len(type) == 0: self.response.set_status(400, 'Missing mandatory attributes') return if Config.auto_accept_default_relationship and Config.default_relationship == relationship: approved = True else: approved = False # Since we received a request for a relationship, assume that peer has approved new_trust = myself.createVerifiedTrust(baseuri=baseuri, peerid=peerid, approved=approved, secret=secret, verificationToken=verificationToken, type=type, peer_approved=True, relationship=relationship, desc=desc) if not new_trust: self.response.set_status(403, 'Forbidden') return self.response.headers.add_header( "Location", str(Config.root + myself.id + '/trust/' + new_trust.relationship + "/" + new_trust.peerid)) pair = { 'baseuri': new_trust.baseuri, 'id': myself.id, 'peerid': new_trust.peerid, 'relationship': new_trust.relationship, 'approved': new_trust.approved, 'peer_approved': new_trust.peer_approved, 'verified': new_trust.verified, 'type': new_trust.type, 'desc': new_trust.desc, 'secret': new_trust.secret, } out = json.dumps(pair) self.response.write(out) self.response.headers["Content-Type"] = "application/json" if approved: self.response.set_status(201, 'Created') else: self.response.set_status(202, 'Accepted') # Handling requests to specific relationships, e.g. /trust/friend/12f2ae53bd class trustHandler(webapp2.RequestHandler): def get(self, id, relationship, peerid): if self.request.get('_method') == 'PUT': self.put(id, relationship, peerid) return if self.request.get('_method') == 'DELETE': self.delete(id, relationship, peerid) return logging.debug('GET trust headers: ' + str(self.request.headers)) (Config, myself, check) = auth.init_actingweb(appreq=self, id=id, path='trust', subpath=relationship) if not myself or check.response["code"] != 200: return if not check.checkAuthorisation(path='trust', subpath='<type>/<id>', method='GET', peerid=peerid): self.response.set_status(403) return relationships = myself.getTrustRelationships( relationship=relationship, peerid=peerid) if not relationships: self.response.set_status(404, 'Not found') return my_trust = relationships[0] # If the peer did a GET to verify if check.trust and check.trust.peerid == peerid and not my_trust.verified: my_trust.modify(verified=True) verificationToken = my_trust.verificationToken else: verificationToken = '' pair = { 'baseuri': my_trust.baseuri, 'id': myself.id, 'peerid': my_trust.peerid, 'relationship': my_trust.relationship, 'approved': my_trust.approved, 'peer_approved': my_trust.peer_approved, 'verified': my_trust.verified, 'verificationToken': verificationToken, 'type': my_trust.type, 'desc': my_trust.desc, 'secret': my_trust.secret, } out = json.dumps(pair) self.response.write(out) self.response.headers["Content-Type"] = "application/json" if my_trust.approved: self.response.set_status(200, 'Ok') else: self.response.set_status(202, 'Accepted') def post(self, id, relationship, peerid): (Config, myself, check) = auth.init_actingweb(appreq=self, id=id, path='trust', subpath=relationship) if not myself or check.response["code"] != 200: return if not check.checkAuthorisation(path='trust', subpath='<type>/<id>', method='POST', peerid=peerid): self.response.set_status(403) return try: params = json.loads(self.request.body.decode('utf-8', 'ignore')) peer_approved = None if 'approved' in params: if params['approved'] and params['approved'] == True: peer_approved = True except ValueError: self.response.set_status(400, 'No json content') return if myself.modifyTrustAndNotify(relationship=relationship, peerid=peerid, peer_approved=peer_approved): self.response.set_status(204, 'Ok') else: self.response.set_status(405, 'Not modified') def put(self, id, relationship, peerid): (Config, myself, check) = auth.init_actingweb(appreq=self, id=id, path='trust', subpath=relationship) if not myself or check.response["code"] != 200: return if not check.checkAuthorisation(path='trust', subpath='<type>/<id>', method='PUT', peerid=peerid): self.response.set_status(403) return try: params = json.loads(self.request.body.decode('utf-8', 'ignore')) if 'baseuri' in params: baseuri = params['baseuri'] else: baseuri = '' if 'desc' in params: desc = params['desc'] else: desc = '' if 'approved' in params: if params['approved'] == True or params['approved'].lower() == "true": approved = True else: approved = None except ValueError: if not self.request.get('_method') or self.request.get('_method') != "PUT": self.response.set_status(400, 'No json content') return if self.request.get('approved') and len(self.request.get('approved')) > 0: if self.request.get('approved').lower() == "true": approved = True else: approved = None if self.request.get('baseuri') and len(self.request.get('baseuri')) > 0: baseuri = self.request.get('baseuri') else: baseuri = '' if self.request.get('desc') and len(self.request.get('desc')) > 0: desc = self.request.get('desc') else: desc = '' if myself.modifyTrustAndNotify(relationship=relationship, peerid=peerid, baseuri=baseuri, approved=approved, desc=desc): self.response.set_status(204, 'Ok') else: self.response.set_status(405, 'Not modified') def delete(self, id, relationship, peerid): (Config, myself, check) = auth.init_actingweb(appreq=self, id=id, path='trust', subpath=relationship, add_response=False) if not myself or (check.response["code"] != 200 and check.response["code"] != 401): auth.add_auth_response(appreq=self, auth_obj=check) return # We allow non-approved peers to delete even if we haven't approved the relationship yet if not check.checkAuthorisation(path='trust', subpath='<type>/<id>', method='DELETE', peerid=peerid, approved=False): self.response.set_status(403) return isPeer = False if check.trust and check.trust.peerid == peerid: isPeer = True else: # Use of GET param peer=true is a way of forcing no deletion of a peer # relationship even when requestor is not a peer (primarily for testing purposes) peerGet = self.request.get('peer').lower() if peerGet.lower() == "true": isPeer = True Config = config.config() relationships = myself.getTrustRelationships( relationship=relationship, peerid=peerid) if not relationships: self.response.set_status(404, 'Not found') return my_trust = relationships[0] if isPeer: deleted = myself.deleteReciprocalTrust(peerid=peerid, deletePeer=False) else: deleted = myself.deleteReciprocalTrust(peerid=peerid, deletePeer=True) if not deleted: self.response.set_status(502, 'Not able to delete relationship with peer.') return self.response.set_status(204, 'Ok') application = webapp2.WSGIApplication([ webapp2.Route(r'/<id>/trust<:/?>', rootHandler, name='rootHandler'), webapp2.Route(r'/<id>/trust/<relationship><:/?>', relationshipHandler, name='relationshipHandler'), webapp2.Route(r'/<id>/trust/<relationship>/<peerid><:/?>', trustHandler, name='trustHandler'), ], debug=True)
#!/usr/bin/env python # from actingweb import actor from actingweb import config from actingweb import trust from actingweb import auth import webapp2 import os from google.appengine.ext.webapp import template import json import logging import datetime import time # /trust handlers # # GET /trust with query parameters (relationship, type, and peerid) to retrieve trust relationships (auth: only creator and admins allowed) # POST /trust with json body to initiate a trust relationship between this # actor and another (reciprocal relationship) (auth: only creator and admins allowed) # POST /trust/{relationship} with json body to create new trust # relationship (see config.py for default relationship and auto-accept, no # auth required) # GET /trust/{relationship}}/{actorid} to get details on a specific relationship (auth: creator, admin, or peer secret) # POST /trust/{relationship}}/{actorid} to send information to a peer about changes in the relationship # PUT /trust/{relationship}}/{actorid} with a json body to change details on a relationship (baseuri, secret, desc) (auth: creator, # admin, or peer secret) # DELETE /trust/{relationship}}/{actorid} to delete a relationship (with # ?peer=true if the delete is from the peer) (auth: creator, admin, or # peer secret) # Handling requests to trust/ class rootHandler(webapp2.RequestHandler): def get(self, id): if self.request.get('_method') == 'POST': self.post(id) return (Config, myself, check) = auth.init_actingweb(appreq=self, id=id, path='trust') if not myself or check.response["code"] != 200: return if not check.checkAuthorisation(path='trust', method='GET'): self.response.set_status(403) return relationship = '' type = '' peerid = '' relationship = self.request.get('relationship') type = self.request.get('type') peerid = self.request.get('peerid') relationships = myself.getTrustRelationships( relationship=relationship, peerid=peerid, type=type) if not relationships: self.response.set_status(404, 'Not found') return pairs = [] for rel in relationships: pairs.append({ 'baseuri': rel.baseuri, 'id': myself.id, 'peerid': rel.peerid, 'relationship': rel.relationship, 'approved': rel.approved, 'peer_approved': rel.peer_approved, 'verified': rel.verified, 'type': rel.type, 'desc': rel.desc, 'secret': rel.secret, }) out = json.dumps(pairs) self.response.write(out) self.response.headers["Content-Type"] = "application/json" self.response.set_status(200, 'Ok') def post(self, id): (Config, myself, check) = auth.init_actingweb(appreq=self, id=id, path='trust') if not myself or check.response["code"] != 200: return if not check.checkAuthorisation(path='trust', method='POST'): self.response.set_status(403) return secret = '' desc = '' relationship = Config.default_relationship type = '' try: params = json.loads(self.request.body.decode('utf-8', 'ignore')) if 'url' in params: url = params['url'] else: url = '' if 'relationship' in params: relationship = params['relationship'] if 'type' in params: type = params['type'] if 'desc' in params: desc = params['desc'] except ValueError: url = self.request.get('url') relationship = self.request.get('relationship') type = self.request.get('type') if len(url) == 0: self.response.set_status(400, 'Missing peer URL') return secret = Config.newToken() new_trust = myself.createReciprocalTrust( url=url, secret=secret, desc=desc, relationship=relationship, type=type) if not new_trust: self.response.set_status(408, 'Unable to create trust relationship') return self.response.headers.add_header( "Location", str(Config.root + myself.id + '/trust/' + new_trust.relationship + '/' + new_trust.peerid)) pair = { 'baseuri': new_trust.baseuri, 'id': myself.id, 'peerid': new_trust.peerid, 'relationship': new_trust.relationship, 'approved': new_trust.approved, 'peer_approved': new_trust.peer_approved, 'verified': new_trust.verified, 'type': new_trust.type, 'desc': new_trust.desc, 'secret': new_trust.secret, } out = json.dumps(pair) self.response.write(out) self.response.headers["Content-Type"] = "application/json" self.response.set_status(201, 'Created') # Handling requests to /trust/*, e.g. /trust/friend class relationshipHandler(webapp2.RequestHandler): def get(self, id, relationship): if self.request.get('_method') == 'POST': self.post(id, relationship) return self.response.set_status(404, "Not found") def put(self, id, relationship): (Config, myself, check) = auth.init_actingweb(appreq=self, id=id, path='trust', subpath=relationship, add_response=False) if not myself: return if relationship != 'trustee': self.response.set_status(404, "Not found") return # Access is the same as /trust if not check.checkAuthorisation(path='trust', method='POST'): self.response.set_status(403) return try: params = json.loads(self.request.body.decode('utf-8', 'ignore')) if 'trustee_root' in params: trustee_root = params['trustee_root'] else: trustee_root = '' if 'creator' in params: creator = params['creator'] else: creator = None except ValueError: self.response.set_status(400, 'No json content') return if len(trustee_root) > 0: myself.setProperty('trustee_root', trustee_root) if creator: myself.modify(creator=creator) self.response.set_status(204, 'No content') def delete(self, id, relationship): (Config, myself, check) = auth.init_actingweb(appreq=self, id=id, path='trust', subpath=relationship, add_response=False) if not myself: return if relationship != 'trustee': self.response.set_status(404, "Not found") return # Access is the same as /trust if not check.checkAuthorisation(path='trust', method='DELETE'): self.response.set_status(403) return myself.deleteProperty('trustee_root') self.response.set_status(204, 'No content') def post(self, id, relationship): (Config, myself, check) = auth.init_actingweb(appreq=self, id=id, path='trust', subpath=relationship, add_response=False) if not myself: return if not check.checkAuthorisation(path='trust', subpath='<type>', method='POST'): self.response.set_status(403) return try: params = json.loads(self.request.body.decode('utf-8', 'ignore')) if 'baseuri' in params: baseuri = params['baseuri'] else: baseuri = '' if 'id' in params: peerid = params['id'] else: peerid = '' if 'type' in params: type = params['type'] else: type = '' if 'secret' in params: secret = params['secret'] else: secret = '' if 'desc' in params: desc = params['desc'] else: desc = '' if 'verify' in params: verificationToken = params['verify'] else: verificationToken = None except ValueError: self.response.set_status(400, 'No json content') return if len(baseuri) == 0 or len(peerid) == 0 or len(type) == 0: self.response.set_status(400, 'Missing mandatory attributes') return if Config.auto_accept_default_relationship and Config.default_relationship == relationship: approved = True else: approved = False # Since we received a request for a relationship, assume that peer has approved new_trust = myself.createVerifiedTrust(baseuri=baseuri, peerid=peerid, approved=approved, secret=secret, verificationToken=verificationToken, type=type, peer_approved=True, relationship=relationship, desc=desc) if not new_trust: self.response.set_status(403, 'Forbidden') return self.response.headers.add_header( "Location", str(Config.root + myself.id + '/trust/' + new_trust.relationship + "/" + new_trust.peerid)) pair = { 'baseuri': new_trust.baseuri, 'id': myself.id, 'peerid': new_trust.peerid, 'relationship': new_trust.relationship, 'approved': new_trust.approved, 'peer_approved': new_trust.peer_approved, 'verified': new_trust.verified, 'type': new_trust.type, 'desc': new_trust.desc, 'secret': new_trust.secret, } out = json.dumps(pair) self.response.write(out) self.response.headers["Content-Type"] = "application/json" if approved: self.response.set_status(201, 'Created') else: self.response.set_status(202, 'Accepted') # Handling requests to specific relationships, e.g. /trust/friend/12f2ae53bd class trustHandler(webapp2.RequestHandler): def get(self, id, relationship, peerid): if self.request.get('_method') == 'PUT': self.put(id, relationship, peerid) return if self.request.get('_method') == 'DELETE': self.delete(id, relationship, peerid) return logging.debug('GET trust headers: ' + str(self.request.headers)) (Config, myself, check) = auth.init_actingweb(appreq=self, id=id, path='trust', subpath=relationship) if not myself or check.response["code"] != 200: return if not check.checkAuthorisation(path='trust', subpath='<type>/<id>', method='GET', peerid=peerid): self.response.set_status(403) return relationships = myself.getTrustRelationships( relationship=relationship, peerid=peerid) if not relationships: self.response.set_status(404, 'Not found') return my_trust = relationships[0] # If the peer did a GET to verify if check.trust and check.trust.peerid == peerid and not my_trust.verified: my_trust.modify(verified=True) verificationToken = my_trust.verificationToken else: verificationToken = '' pair = { 'baseuri': my_trust.baseuri, 'id': myself.id, 'peerid': my_trust.peerid, 'relationship': my_trust.relationship, 'approved': my_trust.approved, 'peer_approved': my_trust.peer_approved, 'verified': my_trust.verified, 'verificationToken': verificationToken, 'type': my_trust.type, 'desc': my_trust.desc, 'secret': my_trust.secret, } out = json.dumps(pair) self.response.write(out) self.response.headers["Content-Type"] = "application/json" if my_trust.approved: self.response.set_status(200, 'Ok') else: self.response.set_status(202, 'Accepted') def post(self, id, relationship, peerid): (Config, myself, check) = auth.init_actingweb(appreq=self, id=id, path='trust', subpath=relationship) if not myself or check.response["code"] != 200: return if not check.checkAuthorisation(path='trust', subpath='<type>/<id>', method='POST', peerid=peerid): self.response.set_status(403) return try: params = json.loads(self.request.body.decode('utf-8', 'ignore')) peer_approved = None if 'approved' in params: if params['approved'] and params['approved'] == True: peer_approved = True except ValueError: self.response.set_status(400, 'No json content') return if myself.modifyTrustAndNotify(relationship=relationship, peerid=peerid, peer_approved=peer_approved): self.response.set_status(204, 'Ok') else: self.response.set_status(405, 'Not modified') def put(self, id, relationship, peerid): (Config, myself, check) = auth.init_actingweb(appreq=self, id=id, path='trust', subpath=relationship) if not myself or check.response["code"] != 200: return if not check.checkAuthorisation(path='trust', subpath='<type>/<id>', method='PUT', peerid=peerid): self.response.set_status(403) return try: params = json.loads(self.request.body.decode('utf-8', 'ignore')) if 'baseuri' in params: baseuri = params['baseuri'] else: baseuri = '' if 'desc' in params: desc = params['desc'] else: desc = '' if 'approved' in params: if params['approved'] == True or params['approved'].lower() == "true": approved = True else: approved = None except ValueError: if not self.request.get('_method') or self.request.get('_method') != "PUT": self.response.set_status(400, 'No json content') return if self.request.get('approved') and len(self.request.get('approved')) > 0: if self.request.get('approved').lower() == "true": approved = True else: approved = None if self.request.get('baseuri') and len(self.request.get('baseuri')) > 0: baseuri = self.request.get('baseuri') else: baseuri = '' if self.request.get('desc') and len(self.request.get('desc')) > 0: desc = self.request.get('desc') else: desc = '' if myself.modifyTrustAndNotify(relationship=relationship, peerid=peerid, baseuri=baseuri, approved=approved, desc=desc): self.response.set_status(204, 'Ok') else: self.response.set_status(405, 'Not modified') def delete(self, id, relationship, peerid): (Config, myself, check) = auth.init_actingweb(appreq=self, id=id, path='trust', subpath=relationship, add_response=False) if not myself or (check.response["code"] != 200 and check.response["code"] != 401): auth.add_auth_response(appreq=self, auth_obj=check) return # We allow non-approved peers to delete even if we haven't approved the relationship yet if not check.checkAuthorisation(path='trust', subpath='<type>/<id>', method='DELETE', peerid=peerid, approved=False): self.response.set_status(403) return isPeer = False if check.trust and check.trust.peerid == peerid: isPeer = True else: # Use of GET param peer=true is a way of forcing no deletion of a peer # relationship even when requestor is not a peer (primarily for testing purposes) peerGet = self.request.get('peer').lower() if peerGet.lower() == "true": isPeer = True Config = config.config() relationships = myself.getTrustRelationships( relationship=relationship, peerid=peerid) if not relationships: self.response.set_status(404, 'Not found') return my_trust = relationships[0] if isPeer: deleted = myself.deleteReciprocalTrust(peerid=peerid, deletePeer=False) else: deleted = myself.deleteReciprocalTrust(peerid=peerid, deletePeer=True) if not deleted: self.response.set_status(502, 'Not able to delete relationship with peer.') return self.response.set_status(204, 'Ok') application = webapp2.WSGIApplication([ webapp2.Route(r'/<id>/trust<:/?>', rootHandler, name='rootHandler'), webapp2.Route(r'/<id>/trust/<relationship><:/?>', relationshipHandler, name='relationshipHandler'), webapp2.Route(r'/<id>/trust/<relationship>/<peerid><:/?>', trustHandler, name='trustHandler'), ], debug=True)
en
0.865458
#!/usr/bin/env python # # /trust handlers # # GET /trust with query parameters (relationship, type, and peerid) to retrieve trust relationships (auth: only creator and admins allowed) # POST /trust with json body to initiate a trust relationship between this # actor and another (reciprocal relationship) (auth: only creator and admins allowed) # POST /trust/{relationship} with json body to create new trust # relationship (see config.py for default relationship and auto-accept, no # auth required) # GET /trust/{relationship}}/{actorid} to get details on a specific relationship (auth: creator, admin, or peer secret) # POST /trust/{relationship}}/{actorid} to send information to a peer about changes in the relationship # PUT /trust/{relationship}}/{actorid} with a json body to change details on a relationship (baseuri, secret, desc) (auth: creator, # admin, or peer secret) # DELETE /trust/{relationship}}/{actorid} to delete a relationship (with # ?peer=true if the delete is from the peer) (auth: creator, admin, or # peer secret) # Handling requests to trust/ # Handling requests to /trust/*, e.g. /trust/friend # Access is the same as /trust # Access is the same as /trust # Since we received a request for a relationship, assume that peer has approved # Handling requests to specific relationships, e.g. /trust/friend/12f2ae53bd # If the peer did a GET to verify # We allow non-approved peers to delete even if we haven't approved the relationship yet # Use of GET param peer=true is a way of forcing no deletion of a peer # relationship even when requestor is not a peer (primarily for testing purposes)
2.498403
2
src/main/python/rlbot/version.py
IamEld3st/RLBot
0
53
# Store the version here so: # 1) we don't load dependencies by storing it in __init__.py # 2) we can import it in setup.py for the same reason # 3) we can import it into your module module # https://stackoverflow.com/questions/458550/standard-way-to-embed-version-into-python-package __version__ = '1.6.1' release_notes = { '1.6.1': """ Fixed GUI crash when loading certain RLBot config files with relative paths for agents. Fixed agent preset loading to allow multiple agents to saved/loaded correctly if they have the same name. - ima9rd """, '1.6.0':""" Add support for auto starting .NET executables. """, '1.5.1': """ Fixed crash with GUI when no default RLBot.cfg file was found. Updated GUI to launch Rocket League when clicking run if no Rocket League process is found. - ima9rd """, '1.5.0': """ Adding a have_internet helper function to help streamline upgrade checks. - ima9rd """, '1.4.2': """ Adding support for auto-running java bots during tournaments. To take advantage of this in your bot, see https://github.com/RLBot/RLBotJavaExample/wiki/Auto-Launching-Java Plus bug fixes: - Fixed a bug where auto-run executables would crash when trying to write to stderr. - Dragging bots to another team in the GUI no longer breaks the config. """, '1.3.0': """ Accurate ball prediction for Hoops and Dropshot modes! - Kipje13, Marvin, NeverCast, et. al. """, '1.2.6': """ Fixed a bug where field info was not extracted properly during dropshot mode. It was reporting 2 goals rather than the expected 140. """, '1.2.5': """ *************************************************** * Fix for dodge cancels / half flips! - ccman32 * *************************************************** Plus: - Changing the rendering strategy for 3D lines that go past the camera. Formerly it was "draw it, even though it's crazy sometimes", now it will be "don't draw it". - Showing the rate that inputs are received for each player index when you press the [home] key. Toggle back off with the [end] key. - Fixed a bug where party_member_bot could get influenced by real controller input. - Creating new presets in the GUI works better now. - Got rid of the libpng warning seen when using the GUI. - Giving specific error messages when cfg files are messed up. """, '1.2.2': """ - Rearranged the GUI a bit, and made it load and track appearance configs more effectively. - Fixed bug where RUN button behavior in the GUI would not work after killing bots. """, '1.2.0': """ - We now offer a 'RigidBodyTick' thanks to whatisaphone! It's a lower-level representation of physics data which updates at 120Hz and is not subject to interpolation. You can still make a great bot without it, but this feature is quite nice for the scientists among us. See https://github.com/RLBot/RLBotPythonExample/wiki/Rigid-Body-Tick for more details! - Faster way to access ball prediction data in python. - Skyborg """, '1.1.3': """ - Faster way to access ball prediction data in python. - Skyborg - Java bots will now shut down when the python framework quits. This has been necessary recently to avoid buggy situations. - Shutting down the python framework will no longer attempt to kill bots twice in a row. - Clicking on the "Run" button twice in a row in the GUI will no longer spawn duplicate processes. """, '1.1.2': """ Faster way to access ball prediction data in python. - Skyborg """, '1.1.1': """ You can now get information about the ball's status in Dropshot mode thanks to hallo_doei! Read all about it at https://github.com/RLBot/RLBot/wiki/Dropshot Other changes: - The loadout config for orange team is now respected again. - ccman32 - Fixed a bug where the GUI would crash with a "KeyError". - hallo_doei - Avoiding and suppressing some game crashes, and also restoring the ability to get game tick data during replays and the postgame. - tarehart - Fixed a bug where bots would dodge when they intended to double jump. -tarehart """, '1.0.6': """ The latest Rocket League patch broke dodges for our bots; this update fixes it. """, '1.0.5': """ Maximum size for a render message has been decreased again because many people experienced errors related to memory access. The limit is now only double the original. """, '1.0.4': """ - Maximum size for a render message has been increased by a factor of 100. This means you can draw a lot of lines at once without getting errors. - Boost amount for cars will now round up to the nearest integer, so 0.3% boost will now appear as 1 instead of 0. - Fixed a crash that would commonly happen after a match ends. As a side effect, you can no longer see up-to-date player data during instant replays. """, '1.0.3': """ Time for the big 1.0 release! We actually left "beta" a long time ago so this isn't as big a milestone as the number implies, but we DO have two great new features! 1. Setting game state. You can manipulate the position, velocity, etc of the ball and the cars! This can be a great help during bot development, and you can also get creative with it. Visit the wiki for details and documentation - https://github.com/RLBot/RLBot/wiki/Manipulating-Game-State Code written by hallo_doei, ccman32, and tarehart 2. Ball prediction. We now provide a list of future ball positions based on chip's excellent physics modeling. Take advantage of this to do next-level wall reads, catches, and dribbles! You can read about the math involved here: https://samuelpmish.github.io/notes/RocketLeague/ball_bouncing/ Note: currently the wall bounces are only accurate on the standard arena, not hoops or dropshot. Documentation and examples can be found here: https://github.com/RLBot/RLBot/wiki/Ball-Path-Prediction Code written by chip and tarehart Bonus: - You can now play on Salty Shores thanks to hallo_doei - Bug fix for people with spaces in their file path by Zaptive - Subprocess agent for future Rust support by whatisaphone """, '0.0.32': """ More comprehensive fix for Rocket League patch 1.50. Compared to previous version: - Dropshot tile data is fixed - Boost pad data is fixed - Loadout configuration is fixed Thanks to ccman32 and dtracers for delivering this fix quickly! """, '0.0.31': """ Rapid response to Rocket League patch 1.50 with the following known issues: - Dropshot tile data is missing - Boost pad data is missing - Loadout configuration is broken Thanks to ccman32 and dtracers for delivering this short-term fix quickly. We will follow this up with a proper fix as soon as possible. You may also choose to stay on Rocket League 1.49 and RLBot 0.0.30, ask for instructions on discord. """, '0.0.30': """ - New core dll that is less likely to break when Rocket League is patched - ccman32 and hallo-doei - Fixed bug resulting in incorrect quickchat - dtracers - Added more built-in colors to the python rendering manager - Eastvillage - Fix for items with a ':' not showing up in the GUI - hallo-doei - Fix for GUI not saving correct path - hallo-doei - Fix for GUI crash when saving preset then canceling - hallo-doei - Adding file checking before injection (Resolves #167) - Redox - Fixed typo in rlbot.cfg - Redox - Fancy release notes - tarehart and Skyborg """ } release_banner = """ ______ _ ______ _ 10100 | ___ \ | | ___ \ | | 00101 110011 | |_/ / | | |_/ / ___ | |_ 110011 00110110 | /| | | ___ \/ _ \| __| 01101100 010010 | |\ \| |____| |_/ / (_) | |_ 010010 10010 \_| \_\_____/\____/ \___/ \__| 01001 """ def get_current_release_notes(): if __version__ in release_notes: return release_notes[__version__] return '' def get_help_text(): return "Trouble? Ask on Discord at https://discord.gg/5cNbXgG " \ "or report an issue at https://github.com/RLBot/RLBot/issues" def print_current_release_notes(): print(release_banner) print("Version {}".format(__version__)) print(get_current_release_notes()) print(get_help_text()) print("")
# Store the version here so: # 1) we don't load dependencies by storing it in __init__.py # 2) we can import it in setup.py for the same reason # 3) we can import it into your module module # https://stackoverflow.com/questions/458550/standard-way-to-embed-version-into-python-package __version__ = '1.6.1' release_notes = { '1.6.1': """ Fixed GUI crash when loading certain RLBot config files with relative paths for agents. Fixed agent preset loading to allow multiple agents to saved/loaded correctly if they have the same name. - ima9rd """, '1.6.0':""" Add support for auto starting .NET executables. """, '1.5.1': """ Fixed crash with GUI when no default RLBot.cfg file was found. Updated GUI to launch Rocket League when clicking run if no Rocket League process is found. - ima9rd """, '1.5.0': """ Adding a have_internet helper function to help streamline upgrade checks. - ima9rd """, '1.4.2': """ Adding support for auto-running java bots during tournaments. To take advantage of this in your bot, see https://github.com/RLBot/RLBotJavaExample/wiki/Auto-Launching-Java Plus bug fixes: - Fixed a bug where auto-run executables would crash when trying to write to stderr. - Dragging bots to another team in the GUI no longer breaks the config. """, '1.3.0': """ Accurate ball prediction for Hoops and Dropshot modes! - Kipje13, Marvin, NeverCast, et. al. """, '1.2.6': """ Fixed a bug where field info was not extracted properly during dropshot mode. It was reporting 2 goals rather than the expected 140. """, '1.2.5': """ *************************************************** * Fix for dodge cancels / half flips! - ccman32 * *************************************************** Plus: - Changing the rendering strategy for 3D lines that go past the camera. Formerly it was "draw it, even though it's crazy sometimes", now it will be "don't draw it". - Showing the rate that inputs are received for each player index when you press the [home] key. Toggle back off with the [end] key. - Fixed a bug where party_member_bot could get influenced by real controller input. - Creating new presets in the GUI works better now. - Got rid of the libpng warning seen when using the GUI. - Giving specific error messages when cfg files are messed up. """, '1.2.2': """ - Rearranged the GUI a bit, and made it load and track appearance configs more effectively. - Fixed bug where RUN button behavior in the GUI would not work after killing bots. """, '1.2.0': """ - We now offer a 'RigidBodyTick' thanks to whatisaphone! It's a lower-level representation of physics data which updates at 120Hz and is not subject to interpolation. You can still make a great bot without it, but this feature is quite nice for the scientists among us. See https://github.com/RLBot/RLBotPythonExample/wiki/Rigid-Body-Tick for more details! - Faster way to access ball prediction data in python. - Skyborg """, '1.1.3': """ - Faster way to access ball prediction data in python. - Skyborg - Java bots will now shut down when the python framework quits. This has been necessary recently to avoid buggy situations. - Shutting down the python framework will no longer attempt to kill bots twice in a row. - Clicking on the "Run" button twice in a row in the GUI will no longer spawn duplicate processes. """, '1.1.2': """ Faster way to access ball prediction data in python. - Skyborg """, '1.1.1': """ You can now get information about the ball's status in Dropshot mode thanks to hallo_doei! Read all about it at https://github.com/RLBot/RLBot/wiki/Dropshot Other changes: - The loadout config for orange team is now respected again. - ccman32 - Fixed a bug where the GUI would crash with a "KeyError". - hallo_doei - Avoiding and suppressing some game crashes, and also restoring the ability to get game tick data during replays and the postgame. - tarehart - Fixed a bug where bots would dodge when they intended to double jump. -tarehart """, '1.0.6': """ The latest Rocket League patch broke dodges for our bots; this update fixes it. """, '1.0.5': """ Maximum size for a render message has been decreased again because many people experienced errors related to memory access. The limit is now only double the original. """, '1.0.4': """ - Maximum size for a render message has been increased by a factor of 100. This means you can draw a lot of lines at once without getting errors. - Boost amount for cars will now round up to the nearest integer, so 0.3% boost will now appear as 1 instead of 0. - Fixed a crash that would commonly happen after a match ends. As a side effect, you can no longer see up-to-date player data during instant replays. """, '1.0.3': """ Time for the big 1.0 release! We actually left "beta" a long time ago so this isn't as big a milestone as the number implies, but we DO have two great new features! 1. Setting game state. You can manipulate the position, velocity, etc of the ball and the cars! This can be a great help during bot development, and you can also get creative with it. Visit the wiki for details and documentation - https://github.com/RLBot/RLBot/wiki/Manipulating-Game-State Code written by hallo_doei, ccman32, and tarehart 2. Ball prediction. We now provide a list of future ball positions based on chip's excellent physics modeling. Take advantage of this to do next-level wall reads, catches, and dribbles! You can read about the math involved here: https://samuelpmish.github.io/notes/RocketLeague/ball_bouncing/ Note: currently the wall bounces are only accurate on the standard arena, not hoops or dropshot. Documentation and examples can be found here: https://github.com/RLBot/RLBot/wiki/Ball-Path-Prediction Code written by chip and tarehart Bonus: - You can now play on Salty Shores thanks to hallo_doei - Bug fix for people with spaces in their file path by Zaptive - Subprocess agent for future Rust support by whatisaphone """, '0.0.32': """ More comprehensive fix for Rocket League patch 1.50. Compared to previous version: - Dropshot tile data is fixed - Boost pad data is fixed - Loadout configuration is fixed Thanks to ccman32 and dtracers for delivering this fix quickly! """, '0.0.31': """ Rapid response to Rocket League patch 1.50 with the following known issues: - Dropshot tile data is missing - Boost pad data is missing - Loadout configuration is broken Thanks to ccman32 and dtracers for delivering this short-term fix quickly. We will follow this up with a proper fix as soon as possible. You may also choose to stay on Rocket League 1.49 and RLBot 0.0.30, ask for instructions on discord. """, '0.0.30': """ - New core dll that is less likely to break when Rocket League is patched - ccman32 and hallo-doei - Fixed bug resulting in incorrect quickchat - dtracers - Added more built-in colors to the python rendering manager - Eastvillage - Fix for items with a ':' not showing up in the GUI - hallo-doei - Fix for GUI not saving correct path - hallo-doei - Fix for GUI crash when saving preset then canceling - hallo-doei - Adding file checking before injection (Resolves #167) - Redox - Fixed typo in rlbot.cfg - Redox - Fancy release notes - tarehart and Skyborg """ } release_banner = """ ______ _ ______ _ 10100 | ___ \ | | ___ \ | | 00101 110011 | |_/ / | | |_/ / ___ | |_ 110011 00110110 | /| | | ___ \/ _ \| __| 01101100 010010 | |\ \| |____| |_/ / (_) | |_ 010010 10010 \_| \_\_____/\____/ \___/ \__| 01001 """ def get_current_release_notes(): if __version__ in release_notes: return release_notes[__version__] return '' def get_help_text(): return "Trouble? Ask on Discord at https://discord.gg/5cNbXgG " \ "or report an issue at https://github.com/RLBot/RLBot/issues" def print_current_release_notes(): print(release_banner) print("Version {}".format(__version__)) print(get_current_release_notes()) print(get_help_text()) print("")
en
0.86956
# Store the version here so: # 1) we don't load dependencies by storing it in __init__.py # 2) we can import it in setup.py for the same reason # 3) we can import it into your module module # https://stackoverflow.com/questions/458550/standard-way-to-embed-version-into-python-package Fixed GUI crash when loading certain RLBot config files with relative paths for agents. Fixed agent preset loading to allow multiple agents to saved/loaded correctly if they have the same name. - ima9rd Add support for auto starting .NET executables. Fixed crash with GUI when no default RLBot.cfg file was found. Updated GUI to launch Rocket League when clicking run if no Rocket League process is found. - ima9rd Adding a have_internet helper function to help streamline upgrade checks. - ima9rd Adding support for auto-running java bots during tournaments. To take advantage of this in your bot, see https://github.com/RLBot/RLBotJavaExample/wiki/Auto-Launching-Java Plus bug fixes: - Fixed a bug where auto-run executables would crash when trying to write to stderr. - Dragging bots to another team in the GUI no longer breaks the config. Accurate ball prediction for Hoops and Dropshot modes! - Kipje13, Marvin, NeverCast, et. al. Fixed a bug where field info was not extracted properly during dropshot mode. It was reporting 2 goals rather than the expected 140. *************************************************** * Fix for dodge cancels / half flips! - ccman32 * *************************************************** Plus: - Changing the rendering strategy for 3D lines that go past the camera. Formerly it was "draw it, even though it's crazy sometimes", now it will be "don't draw it". - Showing the rate that inputs are received for each player index when you press the [home] key. Toggle back off with the [end] key. - Fixed a bug where party_member_bot could get influenced by real controller input. - Creating new presets in the GUI works better now. - Got rid of the libpng warning seen when using the GUI. - Giving specific error messages when cfg files are messed up. - Rearranged the GUI a bit, and made it load and track appearance configs more effectively. - Fixed bug where RUN button behavior in the GUI would not work after killing bots. - We now offer a 'RigidBodyTick' thanks to whatisaphone! It's a lower-level representation of physics data which updates at 120Hz and is not subject to interpolation. You can still make a great bot without it, but this feature is quite nice for the scientists among us. See https://github.com/RLBot/RLBotPythonExample/wiki/Rigid-Body-Tick for more details! - Faster way to access ball prediction data in python. - Skyborg - Faster way to access ball prediction data in python. - Skyborg - Java bots will now shut down when the python framework quits. This has been necessary recently to avoid buggy situations. - Shutting down the python framework will no longer attempt to kill bots twice in a row. - Clicking on the "Run" button twice in a row in the GUI will no longer spawn duplicate processes. Faster way to access ball prediction data in python. - Skyborg You can now get information about the ball's status in Dropshot mode thanks to hallo_doei! Read all about it at https://github.com/RLBot/RLBot/wiki/Dropshot Other changes: - The loadout config for orange team is now respected again. - ccman32 - Fixed a bug where the GUI would crash with a "KeyError". - hallo_doei - Avoiding and suppressing some game crashes, and also restoring the ability to get game tick data during replays and the postgame. - tarehart - Fixed a bug where bots would dodge when they intended to double jump. -tarehart The latest Rocket League patch broke dodges for our bots; this update fixes it. Maximum size for a render message has been decreased again because many people experienced errors related to memory access. The limit is now only double the original. - Maximum size for a render message has been increased by a factor of 100. This means you can draw a lot of lines at once without getting errors. - Boost amount for cars will now round up to the nearest integer, so 0.3% boost will now appear as 1 instead of 0. - Fixed a crash that would commonly happen after a match ends. As a side effect, you can no longer see up-to-date player data during instant replays. Time for the big 1.0 release! We actually left "beta" a long time ago so this isn't as big a milestone as the number implies, but we DO have two great new features! 1. Setting game state. You can manipulate the position, velocity, etc of the ball and the cars! This can be a great help during bot development, and you can also get creative with it. Visit the wiki for details and documentation - https://github.com/RLBot/RLBot/wiki/Manipulating-Game-State Code written by hallo_doei, ccman32, and tarehart 2. Ball prediction. We now provide a list of future ball positions based on chip's excellent physics modeling. Take advantage of this to do next-level wall reads, catches, and dribbles! You can read about the math involved here: https://samuelpmish.github.io/notes/RocketLeague/ball_bouncing/ Note: currently the wall bounces are only accurate on the standard arena, not hoops or dropshot. Documentation and examples can be found here: https://github.com/RLBot/RLBot/wiki/Ball-Path-Prediction Code written by chip and tarehart Bonus: - You can now play on Salty Shores thanks to hallo_doei - Bug fix for people with spaces in their file path by Zaptive - Subprocess agent for future Rust support by whatisaphone More comprehensive fix for Rocket League patch 1.50. Compared to previous version: - Dropshot tile data is fixed - Boost pad data is fixed - Loadout configuration is fixed Thanks to ccman32 and dtracers for delivering this fix quickly! Rapid response to Rocket League patch 1.50 with the following known issues: - Dropshot tile data is missing - Boost pad data is missing - Loadout configuration is broken Thanks to ccman32 and dtracers for delivering this short-term fix quickly. We will follow this up with a proper fix as soon as possible. You may also choose to stay on Rocket League 1.49 and RLBot 0.0.30, ask for instructions on discord. - New core dll that is less likely to break when Rocket League is patched - ccman32 and hallo-doei - Fixed bug resulting in incorrect quickchat - dtracers - Added more built-in colors to the python rendering manager - Eastvillage - Fix for items with a ':' not showing up in the GUI - hallo-doei - Fix for GUI not saving correct path - hallo-doei - Fix for GUI crash when saving preset then canceling - hallo-doei - Adding file checking before injection (Resolves #167) - Redox - Fixed typo in rlbot.cfg - Redox - Fancy release notes - tarehart and Skyborg ______ _ ______ _ 10100 | ___ \ | | ___ \ | | 00101 110011 | |_/ / | | |_/ / ___ | |_ 110011 00110110 | /| | | ___ \/ _ \| __| 01101100 010010 | |\ \| |____| |_/ / (_) | |_ 010010 10010 \_| \_\_____/\____/ \___/ \__| 01001
2.211007
2
classy_vision/heads/fully_connected_head.py
dlegor/ClassyVision
1
54
<gh_stars>1-10 #!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Any, Dict import torch.nn as nn from classy_vision.generic.util import is_pos_int from classy_vision.heads import ClassyHead, register_head @register_head("fully_connected") class FullyConnectedHead(ClassyHead): """This head defines a 2d average pooling layer (:class:`torch.nn.AdaptiveAvgPool2d`) followed by a fully connected layer (:class:`torch.nn.Linear`). """ def __init__( self, unique_id: str, num_classes: int, in_plane: int, zero_init_bias: bool = False, ): """Constructor for FullyConnectedHead Args: unique_id: A unique identifier for the head. Multiple instances of the same head might be attached to a model, and unique_id is used to refer to them. num_classes: Number of classes for the head. If None, then the fully connected layer is not applied. in_plane: Input size for the fully connected layer. """ super().__init__(unique_id, num_classes) assert num_classes is None or is_pos_int(num_classes) assert is_pos_int(in_plane) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.fc = None if num_classes is None else nn.Linear(in_plane, num_classes) if zero_init_bias: self.fc.bias.data.zero_() @classmethod def from_config(cls, config: Dict[str, Any]) -> "FullyConnectedHead": """Instantiates a FullyConnectedHead from a configuration. Args: config: A configuration for a FullyConnectedHead. See :func:`__init__` for parameters expected in the config. Returns: A FullyConnectedHead instance. """ num_classes = config.get("num_classes", None) in_plane = config["in_plane"] return cls( config["unique_id"], num_classes, in_plane, zero_init_bias=config.get("zero_init_bias", False), ) def forward(self, x): # perform average pooling: out = self.avgpool(x) # final classifier: out = out.reshape(out.size(0), -1) if self.fc is not None: out = self.fc(out) return out
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Any, Dict import torch.nn as nn from classy_vision.generic.util import is_pos_int from classy_vision.heads import ClassyHead, register_head @register_head("fully_connected") class FullyConnectedHead(ClassyHead): """This head defines a 2d average pooling layer (:class:`torch.nn.AdaptiveAvgPool2d`) followed by a fully connected layer (:class:`torch.nn.Linear`). """ def __init__( self, unique_id: str, num_classes: int, in_plane: int, zero_init_bias: bool = False, ): """Constructor for FullyConnectedHead Args: unique_id: A unique identifier for the head. Multiple instances of the same head might be attached to a model, and unique_id is used to refer to them. num_classes: Number of classes for the head. If None, then the fully connected layer is not applied. in_plane: Input size for the fully connected layer. """ super().__init__(unique_id, num_classes) assert num_classes is None or is_pos_int(num_classes) assert is_pos_int(in_plane) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.fc = None if num_classes is None else nn.Linear(in_plane, num_classes) if zero_init_bias: self.fc.bias.data.zero_() @classmethod def from_config(cls, config: Dict[str, Any]) -> "FullyConnectedHead": """Instantiates a FullyConnectedHead from a configuration. Args: config: A configuration for a FullyConnectedHead. See :func:`__init__` for parameters expected in the config. Returns: A FullyConnectedHead instance. """ num_classes = config.get("num_classes", None) in_plane = config["in_plane"] return cls( config["unique_id"], num_classes, in_plane, zero_init_bias=config.get("zero_init_bias", False), ) def forward(self, x): # perform average pooling: out = self.avgpool(x) # final classifier: out = out.reshape(out.size(0), -1) if self.fc is not None: out = self.fc(out) return out
en
0.776931
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. This head defines a 2d average pooling layer (:class:`torch.nn.AdaptiveAvgPool2d`) followed by a fully connected layer (:class:`torch.nn.Linear`). Constructor for FullyConnectedHead Args: unique_id: A unique identifier for the head. Multiple instances of the same head might be attached to a model, and unique_id is used to refer to them. num_classes: Number of classes for the head. If None, then the fully connected layer is not applied. in_plane: Input size for the fully connected layer. Instantiates a FullyConnectedHead from a configuration. Args: config: A configuration for a FullyConnectedHead. See :func:`__init__` for parameters expected in the config. Returns: A FullyConnectedHead instance. # perform average pooling: # final classifier:
2.365666
2
Task2C.py
StanleyHou117/group66_LentTermProject
0
55
from floodsystem.stationdata import build_station_list from floodsystem.flood import stations_highest_rel_level def run(): stations = build_station_list() warning_stations = stations_highest_rel_level(stations,10) for entry in warning_stations: print(entry[0].name,entry[1]) if __name__ == "__main__": print("*** Task 2C: CUED Part IA Flood Warning System ***") run()
from floodsystem.stationdata import build_station_list from floodsystem.flood import stations_highest_rel_level def run(): stations = build_station_list() warning_stations = stations_highest_rel_level(stations,10) for entry in warning_stations: print(entry[0].name,entry[1]) if __name__ == "__main__": print("*** Task 2C: CUED Part IA Flood Warning System ***") run()
none
1
2.767442
3
src/biotite/copyable.py
danijoo/biotite
208
56
<filename>src/biotite/copyable.py # This source code is part of the Biotite package and is distributed # under the 3-Clause BSD License. Please see 'LICENSE.rst' for further # information. __name__ = "biotite" __author__ = "<NAME>" __all__ = ["Copyable"] import abc class Copyable(metaclass=abc.ABCMeta): """ Base class for all objects, that should be copyable. The public method `copy()` first creates a fresh instance of the class of the instance, that is copied via the `__copy_create__()` method. All variables, that could not be set via the constructor, are then copied via `__copy_fill__()`, starting with the method in the uppermost base class and ending with the class of the instance to be copied. This approach solves the problem of encapsulated variables in superclasses. """ def copy(self): """ Create a deep copy of this object. Returns ------- copy A copy of this object. """ clone = self.__copy_create__() self.__copy_fill__(clone) return clone def __copy_create__(self): """ Instantiate a new object of this class. Only the constructor should be called in this method. All further attributes, that need to be copied are handled in `__copy_fill__()` Do not call the `super()` method here. This method must be overridden, if the constructor takes parameters. Returns ------- copy A freshly instantiated copy of *self*. """ return type(self)() def __copy_fill__(self, clone): """ Copy all necessary attributes to the new object. Always call the `super()` method as first statement. Parameters ---------- clone The freshly instantiated copy of *self*. """ pass
<filename>src/biotite/copyable.py # This source code is part of the Biotite package and is distributed # under the 3-Clause BSD License. Please see 'LICENSE.rst' for further # information. __name__ = "biotite" __author__ = "<NAME>" __all__ = ["Copyable"] import abc class Copyable(metaclass=abc.ABCMeta): """ Base class for all objects, that should be copyable. The public method `copy()` first creates a fresh instance of the class of the instance, that is copied via the `__copy_create__()` method. All variables, that could not be set via the constructor, are then copied via `__copy_fill__()`, starting with the method in the uppermost base class and ending with the class of the instance to be copied. This approach solves the problem of encapsulated variables in superclasses. """ def copy(self): """ Create a deep copy of this object. Returns ------- copy A copy of this object. """ clone = self.__copy_create__() self.__copy_fill__(clone) return clone def __copy_create__(self): """ Instantiate a new object of this class. Only the constructor should be called in this method. All further attributes, that need to be copied are handled in `__copy_fill__()` Do not call the `super()` method here. This method must be overridden, if the constructor takes parameters. Returns ------- copy A freshly instantiated copy of *self*. """ return type(self)() def __copy_fill__(self, clone): """ Copy all necessary attributes to the new object. Always call the `super()` method as first statement. Parameters ---------- clone The freshly instantiated copy of *self*. """ pass
en
0.836455
# This source code is part of the Biotite package and is distributed # under the 3-Clause BSD License. Please see 'LICENSE.rst' for further # information. Base class for all objects, that should be copyable. The public method `copy()` first creates a fresh instance of the class of the instance, that is copied via the `__copy_create__()` method. All variables, that could not be set via the constructor, are then copied via `__copy_fill__()`, starting with the method in the uppermost base class and ending with the class of the instance to be copied. This approach solves the problem of encapsulated variables in superclasses. Create a deep copy of this object. Returns ------- copy A copy of this object. Instantiate a new object of this class. Only the constructor should be called in this method. All further attributes, that need to be copied are handled in `__copy_fill__()` Do not call the `super()` method here. This method must be overridden, if the constructor takes parameters. Returns ------- copy A freshly instantiated copy of *self*. Copy all necessary attributes to the new object. Always call the `super()` method as first statement. Parameters ---------- clone The freshly instantiated copy of *self*.
3.507864
4
custom_components/wyzeapi/binary_sensor.py
np-hacs/ha-wyzeapi
0
57
import logging import time from datetime import timedelta from typing import List from homeassistant.components.binary_sensor import ( BinarySensorEntity, DEVICE_CLASS_MOTION ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ATTR_ATTRIBUTION from homeassistant.core import HomeAssistant from wyzeapy.base_client import Device, AccessTokenError from wyzeapy.client import Client from wyzeapy.types import PropertyIDs from .const import DOMAIN _LOGGER = logging.getLogger(__name__) ATTRIBUTION = "Data provided by Wyze" SCAN_INTERVAL = timedelta(seconds=10) async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities): _LOGGER.debug("""Creating new WyzeApi binary sensor component""") client: Client = hass.data[DOMAIN][config_entry.entry_id] def get_cameras() -> List[Device]: try: return client.get_cameras() except AccessTokenError as e: _LOGGER.warning(e) client.reauthenticate() return client.get_cameras() cameras = [WyzeCameraMotion(client, camera) for camera in await hass.async_add_executor_job(get_cameras)] async_add_entities(cameras, True) class WyzeCameraMotion(BinarySensorEntity): _on: bool _available: bool def __init__(self, wyzeapi_client: Client, device: Device): self._client = wyzeapi_client self._device = device self._last_event = int(str(int(time.time())) + "000") @property def device_info(self): return { "identifiers": { (DOMAIN, self._device.mac) }, "name": self.name, "manufacturer": "WyzeLabs", "model": self._device.product_model } @property def available(self) -> bool: return self._available @property def name(self): """Return the display name of this switch.""" return self._device.nickname @property def is_on(self): """Return true if switch is on.""" return self._on @property def unique_id(self): return "{}-motion".format(self._device.mac) @property def device_state_attributes(self): """Return device attributes of the entity.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, "state": self.is_on, "available": self.available, "device model": self._device.product_model, "mac": self.unique_id } @property def device_class(self): return DEVICE_CLASS_MOTION def update(self): try: device_info = self._client.get_info(self._device) except AccessTokenError: self._client.reauthenticate() device_info = self._client.get_info(self._device) for property_id, value in device_info: if property_id == PropertyIDs.AVAILABLE: self._available = True if value == "1" else False latest_event = self._client.get_latest_event(self._device) if latest_event is not None: if latest_event.event_ts > self._last_event: self._on = True self._last_event = latest_event.event_ts else: self._on = False self._last_event = latest_event.event_ts else: self._on = False
import logging import time from datetime import timedelta from typing import List from homeassistant.components.binary_sensor import ( BinarySensorEntity, DEVICE_CLASS_MOTION ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ATTR_ATTRIBUTION from homeassistant.core import HomeAssistant from wyzeapy.base_client import Device, AccessTokenError from wyzeapy.client import Client from wyzeapy.types import PropertyIDs from .const import DOMAIN _LOGGER = logging.getLogger(__name__) ATTRIBUTION = "Data provided by Wyze" SCAN_INTERVAL = timedelta(seconds=10) async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities): _LOGGER.debug("""Creating new WyzeApi binary sensor component""") client: Client = hass.data[DOMAIN][config_entry.entry_id] def get_cameras() -> List[Device]: try: return client.get_cameras() except AccessTokenError as e: _LOGGER.warning(e) client.reauthenticate() return client.get_cameras() cameras = [WyzeCameraMotion(client, camera) for camera in await hass.async_add_executor_job(get_cameras)] async_add_entities(cameras, True) class WyzeCameraMotion(BinarySensorEntity): _on: bool _available: bool def __init__(self, wyzeapi_client: Client, device: Device): self._client = wyzeapi_client self._device = device self._last_event = int(str(int(time.time())) + "000") @property def device_info(self): return { "identifiers": { (DOMAIN, self._device.mac) }, "name": self.name, "manufacturer": "WyzeLabs", "model": self._device.product_model } @property def available(self) -> bool: return self._available @property def name(self): """Return the display name of this switch.""" return self._device.nickname @property def is_on(self): """Return true if switch is on.""" return self._on @property def unique_id(self): return "{}-motion".format(self._device.mac) @property def device_state_attributes(self): """Return device attributes of the entity.""" return { ATTR_ATTRIBUTION: ATTRIBUTION, "state": self.is_on, "available": self.available, "device model": self._device.product_model, "mac": self.unique_id } @property def device_class(self): return DEVICE_CLASS_MOTION def update(self): try: device_info = self._client.get_info(self._device) except AccessTokenError: self._client.reauthenticate() device_info = self._client.get_info(self._device) for property_id, value in device_info: if property_id == PropertyIDs.AVAILABLE: self._available = True if value == "1" else False latest_event = self._client.get_latest_event(self._device) if latest_event is not None: if latest_event.event_ts > self._last_event: self._on = True self._last_event = latest_event.event_ts else: self._on = False self._last_event = latest_event.event_ts else: self._on = False
en
0.681523
Creating new WyzeApi binary sensor component Return the display name of this switch. Return true if switch is on. Return device attributes of the entity.
2.108677
2
src/Components/missions/GEMS/mcd43c.py
GEOS-ESM/AeroApps
2
58
<filename>src/Components/missions/GEMS/mcd43c.py """ Reads climate modeling grid 0.05 degree MCD43 BRDF files. """ import os import sys from numpy import loadtxt, array, tile, where, concatenate, flipud from numpy import ones from datetime import date, datetime, timedelta from glob import glob from pyhdf.SD import SD, HDF4Error MISSING = 32.767 SDS = dict ( LAND = ('BRDF_Albedo_Parameter1_Band1','BRDF_Albedo_Parameter1_Band2', 'BRDF_Albedo_Parameter1_Band3','BRDF_Albedo_Parameter1_Band4', 'BRDF_Albedo_Parameter1_Band5','BRDF_Albedo_Parameter1_Band6', 'BRDF_Albedo_Parameter1_Band7', 'BRDF_Albedo_Parameter2_Band1','BRDF_Albedo_Parameter2_Band2', 'BRDF_Albedo_Parameter2_Band3','BRDF_Albedo_Parameter2_Band4', 'BRDF_Albedo_Parameter2_Band5','BRDF_Albedo_Parameter2_Band6', 'BRDF_Albedo_Parameter2_Band7', 'BRDF_Albedo_Parameter3_Band1','BRDF_Albedo_Parameter3_Band2', 'BRDF_Albedo_Parameter3_Band3','BRDF_Albedo_Parameter3_Band4', 'BRDF_Albedo_Parameter3_Band5','BRDF_Albedo_Parameter3_Band6', 'BRDF_Albedo_Parameter3_Band7'), QUAL = ('BRDF_Albedo_Quality', 'Snow_BRDF_Albedo', 'BRDF_Albedo_Ancillary', ) ) ALIAS = dict ( BRDF_Albedo_Parameter1_Band1 = 'KISO_b1_645', BRDF_Albedo_Parameter1_Band2 = 'KISO_b2_856', BRDF_Albedo_Parameter1_Band3 = 'KISO_b3_465', BRDF_Albedo_Parameter1_Band4 = 'KISO_b4_553', BRDF_Albedo_Parameter1_Band5 = 'KISO_b5_1241', BRDF_Albedo_Parameter1_Band6 = 'KISO_b6_1629', BRDF_Albedo_Parameter1_Band7 = 'KISO_b7_2114', BRDF_Albedo_Parameter2_Band1 = 'KVOL_b1_645', BRDF_Albedo_Parameter2_Band2 = 'KVOL_b2_856', BRDF_Albedo_Parameter2_Band3 = 'KVOL_b3_465', BRDF_Albedo_Parameter2_Band4 = 'KVOL_b4_553', BRDF_Albedo_Parameter2_Band5 = 'KVOL_b5_1241', BRDF_Albedo_Parameter2_Band6 = 'KVOL_b6_1629', BRDF_Albedo_Parameter2_Band7 = 'KVOL_b7_2114', BRDF_Albedo_Parameter3_Band1 = 'KGEO_b1_645', BRDF_Albedo_Parameter3_Band2 = 'KGEO_b2_856', BRDF_Albedo_Parameter3_Band3 = 'KGEO_b3_465', BRDF_Albedo_Parameter3_Band4 = 'KGEO_b4_553', BRDF_Albedo_Parameter3_Band5 = 'KGEO_b5_1241', BRDF_Albedo_Parameter3_Band6 = 'KGEO_b6_1629', BRDF_Albedo_Parameter3_Band7 = 'KGEO_b7_2114', ) #........................................................................... class McD43C(object): """ This class implements the MODIS LAND BRDF 16-day Level 3 products, MCD43C1 (0.05 degree horz res), """ def __init__ (self,Path,lon,lat,Verb=1): """ Reads files for one day of Level 3 MCD43C1 present on a given *Path* and returns an object with all 3 kernels coeff. On input, Required parameters: Path -- for now a single file. Eventually implement a single directory, or a list of files and directories. """ if type(lon) is list: lon = array(lon) lat = array(lat) # List of HDF files for a given date #----------------------------------- self.verb = Verb self.SDS = SDS['LAND'] #self.Tfiles = glob(Path + '*.hdf') if type(Path) is str: self.Files = [Path] else: self.Files = Path # From a list of lat and lon, return the # dx, dy on the grid # ------------------------------------- self.nobs = len(lon) self._findNearest(Path,lon,lat) # Read BRDF kernel in a MODIS tile # --------------------------------- self.read_BRDF() # Result #--- def _findNearest(self,path,lon,lat): """Given a list of lat, lon, return numbers to find the position of the nearest neighbor on the grid (dx,dy) """ dLon = 0.05 dLat = 0.05 Lon0 = -180 - dLon Lat0 = -90 + dLat self.dx = (0.5+(lon-Lon0)/dLon).astype(int) self.dy = (0.5+(lat-Lat0)/dLat).astype(int) if self.verb: print 'dx','dy', self.dx,self.dy #--- def read_BRDF(self): """Reads MCD43C1 file with Level 3 BRDF kernels for each MODIS band.""" # Create empty lists for SDS to be read from file # ----------------------------------------------- for name in self.SDS: self.__dict__[name] = [] BRDF = MISSING * ones((len(self.SDS),self.nobs)) for fn in self.Files: try: if self.verb: print "[] Working on "+fn hfile = SD(fn) except HDF4Error: if self.verb > 2: print "- %s: not recognized as an HDF file"%filename return # Read select variables (reshape to allow concatenation later) # ------------------------------------------------------------ for sds in self.SDS: if self.verb: print 'sds',self.SDS.index(sds) v = hfile.select(sds).get() a = hfile.select(sds).attributes() if a['scale_factor']!=1.0 or a['add_offset']!=0.0: v = a['scale_factor'] * v + a['add_offset'] if self.verb: print array(self.dx), BRDF.shape, BRDF[self.SDS.index(sds),:], v.shape v = flipud(v) BRDF[self.SDS.index(sds),:] = v[array(self.dy), array(self.dx)] for sds in self.SDS: self.__dict__[sds] = BRDF[self.SDS.index(sds),:] if sds in ALIAS.keys(): self.__dict__[ALIAS[sds]] = self.__dict__[sds] #--- #............................................................................ if __name__ == "__main__": path = '/nobackup/3/pcastell/MODIS/MCD43C1/MCD43C1.A2005361.005.2008094071946.hdf' lon = [-2.,-120.,15.2,17.2,170.1] lat = [88.,40.,-20.,-20.,-55.5] lon = np.arange(-180,180,1) lat = np.arange(-90,90,1) lon,lat = np.meshgrid(lon,lat) ex = McD43C(path,lon.flatten(),lat.flatte())
<filename>src/Components/missions/GEMS/mcd43c.py """ Reads climate modeling grid 0.05 degree MCD43 BRDF files. """ import os import sys from numpy import loadtxt, array, tile, where, concatenate, flipud from numpy import ones from datetime import date, datetime, timedelta from glob import glob from pyhdf.SD import SD, HDF4Error MISSING = 32.767 SDS = dict ( LAND = ('BRDF_Albedo_Parameter1_Band1','BRDF_Albedo_Parameter1_Band2', 'BRDF_Albedo_Parameter1_Band3','BRDF_Albedo_Parameter1_Band4', 'BRDF_Albedo_Parameter1_Band5','BRDF_Albedo_Parameter1_Band6', 'BRDF_Albedo_Parameter1_Band7', 'BRDF_Albedo_Parameter2_Band1','BRDF_Albedo_Parameter2_Band2', 'BRDF_Albedo_Parameter2_Band3','BRDF_Albedo_Parameter2_Band4', 'BRDF_Albedo_Parameter2_Band5','BRDF_Albedo_Parameter2_Band6', 'BRDF_Albedo_Parameter2_Band7', 'BRDF_Albedo_Parameter3_Band1','BRDF_Albedo_Parameter3_Band2', 'BRDF_Albedo_Parameter3_Band3','BRDF_Albedo_Parameter3_Band4', 'BRDF_Albedo_Parameter3_Band5','BRDF_Albedo_Parameter3_Band6', 'BRDF_Albedo_Parameter3_Band7'), QUAL = ('BRDF_Albedo_Quality', 'Snow_BRDF_Albedo', 'BRDF_Albedo_Ancillary', ) ) ALIAS = dict ( BRDF_Albedo_Parameter1_Band1 = 'KISO_b1_645', BRDF_Albedo_Parameter1_Band2 = 'KISO_b2_856', BRDF_Albedo_Parameter1_Band3 = 'KISO_b3_465', BRDF_Albedo_Parameter1_Band4 = 'KISO_b4_553', BRDF_Albedo_Parameter1_Band5 = 'KISO_b5_1241', BRDF_Albedo_Parameter1_Band6 = 'KISO_b6_1629', BRDF_Albedo_Parameter1_Band7 = 'KISO_b7_2114', BRDF_Albedo_Parameter2_Band1 = 'KVOL_b1_645', BRDF_Albedo_Parameter2_Band2 = 'KVOL_b2_856', BRDF_Albedo_Parameter2_Band3 = 'KVOL_b3_465', BRDF_Albedo_Parameter2_Band4 = 'KVOL_b4_553', BRDF_Albedo_Parameter2_Band5 = 'KVOL_b5_1241', BRDF_Albedo_Parameter2_Band6 = 'KVOL_b6_1629', BRDF_Albedo_Parameter2_Band7 = 'KVOL_b7_2114', BRDF_Albedo_Parameter3_Band1 = 'KGEO_b1_645', BRDF_Albedo_Parameter3_Band2 = 'KGEO_b2_856', BRDF_Albedo_Parameter3_Band3 = 'KGEO_b3_465', BRDF_Albedo_Parameter3_Band4 = 'KGEO_b4_553', BRDF_Albedo_Parameter3_Band5 = 'KGEO_b5_1241', BRDF_Albedo_Parameter3_Band6 = 'KGEO_b6_1629', BRDF_Albedo_Parameter3_Band7 = 'KGEO_b7_2114', ) #........................................................................... class McD43C(object): """ This class implements the MODIS LAND BRDF 16-day Level 3 products, MCD43C1 (0.05 degree horz res), """ def __init__ (self,Path,lon,lat,Verb=1): """ Reads files for one day of Level 3 MCD43C1 present on a given *Path* and returns an object with all 3 kernels coeff. On input, Required parameters: Path -- for now a single file. Eventually implement a single directory, or a list of files and directories. """ if type(lon) is list: lon = array(lon) lat = array(lat) # List of HDF files for a given date #----------------------------------- self.verb = Verb self.SDS = SDS['LAND'] #self.Tfiles = glob(Path + '*.hdf') if type(Path) is str: self.Files = [Path] else: self.Files = Path # From a list of lat and lon, return the # dx, dy on the grid # ------------------------------------- self.nobs = len(lon) self._findNearest(Path,lon,lat) # Read BRDF kernel in a MODIS tile # --------------------------------- self.read_BRDF() # Result #--- def _findNearest(self,path,lon,lat): """Given a list of lat, lon, return numbers to find the position of the nearest neighbor on the grid (dx,dy) """ dLon = 0.05 dLat = 0.05 Lon0 = -180 - dLon Lat0 = -90 + dLat self.dx = (0.5+(lon-Lon0)/dLon).astype(int) self.dy = (0.5+(lat-Lat0)/dLat).astype(int) if self.verb: print 'dx','dy', self.dx,self.dy #--- def read_BRDF(self): """Reads MCD43C1 file with Level 3 BRDF kernels for each MODIS band.""" # Create empty lists for SDS to be read from file # ----------------------------------------------- for name in self.SDS: self.__dict__[name] = [] BRDF = MISSING * ones((len(self.SDS),self.nobs)) for fn in self.Files: try: if self.verb: print "[] Working on "+fn hfile = SD(fn) except HDF4Error: if self.verb > 2: print "- %s: not recognized as an HDF file"%filename return # Read select variables (reshape to allow concatenation later) # ------------------------------------------------------------ for sds in self.SDS: if self.verb: print 'sds',self.SDS.index(sds) v = hfile.select(sds).get() a = hfile.select(sds).attributes() if a['scale_factor']!=1.0 or a['add_offset']!=0.0: v = a['scale_factor'] * v + a['add_offset'] if self.verb: print array(self.dx), BRDF.shape, BRDF[self.SDS.index(sds),:], v.shape v = flipud(v) BRDF[self.SDS.index(sds),:] = v[array(self.dy), array(self.dx)] for sds in self.SDS: self.__dict__[sds] = BRDF[self.SDS.index(sds),:] if sds in ALIAS.keys(): self.__dict__[ALIAS[sds]] = self.__dict__[sds] #--- #............................................................................ if __name__ == "__main__": path = '/nobackup/3/pcastell/MODIS/MCD43C1/MCD43C1.A2005361.005.2008094071946.hdf' lon = [-2.,-120.,15.2,17.2,170.1] lat = [88.,40.,-20.,-20.,-55.5] lon = np.arange(-180,180,1) lat = np.arange(-90,90,1) lon,lat = np.meshgrid(lon,lat) ex = McD43C(path,lon.flatten(),lat.flatte())
en
0.539024
Reads climate modeling grid 0.05 degree MCD43 BRDF files. #........................................................................... This class implements the MODIS LAND BRDF 16-day Level 3 products, MCD43C1 (0.05 degree horz res), Reads files for one day of Level 3 MCD43C1 present on a given *Path* and returns an object with all 3 kernels coeff. On input, Required parameters: Path -- for now a single file. Eventually implement a single directory, or a list of files and directories. # List of HDF files for a given date #----------------------------------- #self.Tfiles = glob(Path + '*.hdf') # From a list of lat and lon, return the # dx, dy on the grid # ------------------------------------- # Read BRDF kernel in a MODIS tile # --------------------------------- # Result #--- Given a list of lat, lon, return numbers to find the position of the nearest neighbor on the grid (dx,dy) #--- Reads MCD43C1 file with Level 3 BRDF kernels for each MODIS band. # Create empty lists for SDS to be read from file # ----------------------------------------------- # Read select variables (reshape to allow concatenation later) # ------------------------------------------------------------ #--- #............................................................................
2.124294
2
tests/keras/layers/wrappers_test.py
kalyc/keras-apache-mxnet
300
59
<filename>tests/keras/layers/wrappers_test.py<gh_stars>100-1000 import pytest import numpy as np import copy from numpy.testing import assert_allclose from keras.utils import CustomObjectScope from keras.layers import wrappers, Input, Layer from keras.layers import RNN from keras import layers from keras.models import Sequential, Model, model_from_json from keras import backend as K from keras.utils.generic_utils import object_list_uid, to_list @pytest.mark.skipif(K.backend() == 'mxnet', reason='MXNet backend does not support TimeDistributed and RNN yet') def test_TimeDistributed(): # first, test with Dense layer model = Sequential() model.add(wrappers.TimeDistributed(layers.Dense(2), input_shape=(3, 4))) model.add(layers.Activation('relu')) model.compile(optimizer='rmsprop', loss='mse') model.fit(np.random.random((10, 3, 4)), np.random.random((10, 3, 2)), epochs=1, batch_size=10) # test config model.get_config() # test when specifying a batch_input_shape test_input = np.random.random((1, 3, 4)) test_output = model.predict(test_input) weights = model.layers[0].get_weights() reference = Sequential() reference.add(wrappers.TimeDistributed(layers.Dense(2), batch_input_shape=(1, 3, 4))) reference.add(layers.Activation('relu')) reference.compile(optimizer='rmsprop', loss='mse') reference.layers[0].set_weights(weights) reference_output = reference.predict(test_input) assert_allclose(test_output, reference_output, atol=1e-05) # test with Embedding model = Sequential() model.add(wrappers.TimeDistributed(layers.Embedding(5, 6), batch_input_shape=(10, 3, 4), dtype='int32')) model.compile(optimizer='rmsprop', loss='mse') model.fit(np.random.randint(5, size=(10, 3, 4), dtype='int32'), np.random.random((10, 3, 4, 6)), epochs=1, batch_size=10) # compare to not using batch_input_shape test_input = np.random.randint(5, size=(10, 3, 4), dtype='int32') test_output = model.predict(test_input) weights = model.layers[0].get_weights() reference = Sequential() reference.add(wrappers.TimeDistributed(layers.Embedding(5, 6), input_shape=(3, 4), dtype='int32')) reference.compile(optimizer='rmsprop', loss='mse') reference.layers[0].set_weights(weights) reference_output = reference.predict(test_input) assert_allclose(test_output, reference_output, atol=1e-05) # test with Conv2D model = Sequential() model.add(wrappers.TimeDistributed(layers.Conv2D(5, (2, 2), padding='same'), input_shape=(2, 4, 4, 3))) model.add(layers.Activation('relu')) model.compile(optimizer='rmsprop', loss='mse') model.train_on_batch(np.random.random((1, 2, 4, 4, 3)), np.random.random((1, 2, 4, 4, 5))) model = model_from_json(model.to_json()) model.summary() # test stacked layers model = Sequential() model.add(wrappers.TimeDistributed(layers.Dense(2), input_shape=(3, 4))) model.add(wrappers.TimeDistributed(layers.Dense(3))) model.add(layers.Activation('relu')) model.compile(optimizer='rmsprop', loss='mse') model.fit(np.random.random((10, 3, 4)), np.random.random((10, 3, 3)), epochs=1, batch_size=10) # test wrapping Sequential model model = Sequential() model.add(layers.Dense(3, input_dim=2)) outer_model = Sequential() outer_model.add(wrappers.TimeDistributed(model, input_shape=(3, 2))) outer_model.compile(optimizer='rmsprop', loss='mse') outer_model.fit(np.random.random((10, 3, 2)), np.random.random((10, 3, 3)), epochs=1, batch_size=10) # test with functional API x = Input(shape=(3, 2)) y = wrappers.TimeDistributed(model)(x) outer_model = Model(x, y) outer_model.compile(optimizer='rmsprop', loss='mse') outer_model.fit(np.random.random((10, 3, 2)), np.random.random((10, 3, 3)), epochs=1, batch_size=10) # test with BatchNormalization model = Sequential() model.add(wrappers.TimeDistributed( layers.BatchNormalization(center=True, scale=True), name='bn', input_shape=(10, 2))) model.compile(optimizer='rmsprop', loss='mse') # Assert that mean and variance are 0 and 1. td = model.layers[0] assert np.array_equal(td.get_weights()[2], np.array([0, 0])) assert np.array_equal(td.get_weights()[3], np.array([1, 1])) # Train model.train_on_batch(np.random.normal(loc=2, scale=2, size=(1, 10, 2)), np.broadcast_to(np.array([0, 1]), (1, 10, 2))) # Assert that mean and variance changed. assert not np.array_equal(td.get_weights()[2], np.array([0, 0])) assert not np.array_equal(td.get_weights()[3], np.array([1, 1])) # Verify input_map has one mapping from inputs to reshaped inputs. uid = object_list_uid(model.inputs) assert len(td._input_map.keys()) == 1 assert uid in td._input_map assert K.int_shape(td._input_map[uid]) == (None, 2) @pytest.mark.skipif(K.backend() == 'mxnet', reason='MXNet backend does not support TimeDistributed and RNN yet') @pytest.mark.skipif((K.backend() == 'cntk'), reason='Flaky with CNTK backend') def test_TimeDistributed_learning_phase(): # test layers that need learning_phase to be set np.random.seed(1234) x = Input(shape=(3, 2)) y = wrappers.TimeDistributed(layers.Dropout(.999))(x, training=True) model = Model(x, y) y = model.predict(np.random.random((10, 3, 2))) assert_allclose(np.mean(y), 0., atol=1e-1, rtol=1e-1) @pytest.mark.skipif(K.backend() == 'mxnet', reason='MXNet backend does not support TimeDistributed and RNN yet') def test_TimeDistributed_trainable(): # test layers that need learning_phase to be set x = Input(shape=(3, 2)) layer = wrappers.TimeDistributed(layers.BatchNormalization()) _ = layer(x) assert len(layer.updates) == 2 assert len(layer.trainable_weights) == 2 layer.trainable = False assert len(layer.updates) == 0 assert len(layer.trainable_weights) == 0 layer.trainable = True assert len(layer.updates) == 2 assert len(layer.trainable_weights) == 2 @pytest.mark.skipif((K.backend() == 'cntk' or K.backend() == 'mxnet'), reason='Unknown timestamps for RNN not supported in CNTK and MXNet.') def test_TimeDistributed_with_masked_embedding_and_unspecified_shape(): # test with unspecified shape and Embeddings with mask_zero model = Sequential() model.add(wrappers.TimeDistributed(layers.Embedding(5, 6, mask_zero=True), input_shape=(None, None))) # the shape so far: (N, t_1, t_2, 6) model.add(wrappers.TimeDistributed(layers.SimpleRNN(7, return_sequences=True))) model.add(wrappers.TimeDistributed(layers.SimpleRNN(8, return_sequences=False))) model.add(layers.SimpleRNN(1, return_sequences=False)) model.compile(optimizer='rmsprop', loss='mse') model_input = np.random.randint(low=1, high=5, size=(10, 3, 4), dtype='int32') for i in range(4): model_input[i, i:, i:] = 0 model.fit(model_input, np.random.random((10, 1)), epochs=1, batch_size=10) mask_outputs = [model.layers[0].compute_mask(model.input)] for layer in model.layers[1:]: mask_outputs.append(layer.compute_mask(layer.input, mask_outputs[-1])) func = K.function([model.input], mask_outputs[:-1]) mask_outputs_val = func([model_input]) ref_mask_val_0 = model_input > 0 # embedding layer ref_mask_val_1 = ref_mask_val_0 # first RNN layer ref_mask_val_2 = np.any(ref_mask_val_1, axis=-1) # second RNN layer ref_mask_val = [ref_mask_val_0, ref_mask_val_1, ref_mask_val_2] for i in range(3): assert np.array_equal(mask_outputs_val[i], ref_mask_val[i]) assert mask_outputs[-1] is None # final layer @pytest.mark.skipif(K.backend() == 'mxnet', reason='MXNet backend does not support TimeDistributed and RNN yet') def test_TimeDistributed_with_masking_layer(): # test with Masking layer model = Sequential() model.add(wrappers.TimeDistributed(layers.Masking(mask_value=0.,), input_shape=(None, 4))) model.add(wrappers.TimeDistributed(layers.Dense(5))) model.compile(optimizer='rmsprop', loss='mse') model_input = np.random.randint(low=1, high=5, size=(10, 3, 4)) for i in range(4): model_input[i, i:, :] = 0. model.compile(optimizer='rmsprop', loss='mse') model.fit(model_input, np.random.random((10, 3, 5)), epochs=1, batch_size=6) mask_outputs = [model.layers[0].compute_mask(model.input)] mask_outputs += [model.layers[1].compute_mask(model.layers[1].input, mask_outputs[-1])] func = K.function([model.input], mask_outputs) mask_outputs_val = func([model_input]) assert np.array_equal(mask_outputs_val[0], np.any(model_input, axis=-1)) assert np.array_equal(mask_outputs_val[1], np.any(model_input, axis=-1)) def test_regularizers(): model = Sequential() model.add(wrappers.TimeDistributed( layers.Dense(2, kernel_regularizer='l1'), input_shape=(3, 4))) model.add(layers.Activation('relu')) model.compile(optimizer='rmsprop', loss='mse') assert len(model.layers[0].layer.losses) == 1 assert len(model.layers[0].losses) == 1 assert len(model.layers[0].get_losses_for(None)) == 1 assert len(model.losses) == 1 model = Sequential() model.add(wrappers.TimeDistributed( layers.Dense(2, activity_regularizer='l1'), input_shape=(3, 4))) model.add(layers.Activation('relu')) model.compile(optimizer='rmsprop', loss='mse') assert len(model.losses) == 1 def test_Bidirectional(): rnn = layers.SimpleRNN samples = 2 dim = 2 timesteps = 2 output_dim = 2 dropout_rate = 0.2 for mode in ['sum', 'concat']: x = np.random.random((samples, timesteps, dim)) target_dim = 2 * output_dim if mode == 'concat' else output_dim y = np.random.random((samples, target_dim)) # test with Sequential model model = Sequential() model.add(wrappers.Bidirectional(rnn(output_dim, dropout=dropout_rate, recurrent_dropout=dropout_rate), merge_mode=mode, input_shape=(timesteps, dim))) model.compile(loss='mse', optimizer='sgd') model.fit(x, y, epochs=1, batch_size=1) # test config model.get_config() model = model_from_json(model.to_json()) model.summary() # test stacked bidirectional layers model = Sequential() model.add(wrappers.Bidirectional(rnn(output_dim, return_sequences=True), merge_mode=mode, input_shape=(timesteps, dim))) model.add(wrappers.Bidirectional(rnn(output_dim), merge_mode=mode)) model.compile(loss='mse', optimizer='sgd') model.fit(x, y, epochs=1, batch_size=1) # test with functional API inputs = Input((timesteps, dim)) outputs = wrappers.Bidirectional(rnn(output_dim, dropout=dropout_rate, recurrent_dropout=dropout_rate), merge_mode=mode)(inputs) model = Model(inputs, outputs) model.compile(loss='mse', optimizer='sgd') model.fit(x, y, epochs=1, batch_size=1) # Bidirectional and stateful inputs = Input(batch_shape=(1, timesteps, dim)) outputs = wrappers.Bidirectional(rnn(output_dim, stateful=True), merge_mode=mode)(inputs) model = Model(inputs, outputs) model.compile(loss='mse', optimizer='sgd') model.fit(x, y, epochs=1, batch_size=1) @pytest.mark.skipif((K.backend() == 'cntk'), reason='Unknown timestamps not supported in CNTK.') def test_Bidirectional_dynamic_timesteps(): # test with functional API with dynamic length rnn = layers.SimpleRNN samples = 2 dim = 2 timesteps = 2 output_dim = 2 dropout_rate = 0.2 for mode in ['sum', 'concat']: x = np.random.random((samples, timesteps, dim)) target_dim = 2 * output_dim if mode == 'concat' else output_dim y = np.random.random((samples, target_dim)) inputs = Input((None, dim)) outputs = wrappers.Bidirectional(rnn(output_dim, dropout=dropout_rate, recurrent_dropout=dropout_rate), merge_mode=mode)(inputs) model = Model(inputs, outputs) model.compile(loss='mse', optimizer='sgd') model.fit(x, y, epochs=1, batch_size=1) @pytest.mark.parametrize('merge_mode', ['sum', 'mul', 'ave', 'concat', None]) def test_Bidirectional_merged_value(merge_mode): rnn = layers.LSTM samples = 2 dim = 5 timesteps = 3 units = 3 X = [np.random.rand(samples, timesteps, dim)] if merge_mode == 'sum': merge_func = lambda y, y_rev: y + y_rev elif merge_mode == 'mul': merge_func = lambda y, y_rev: y * y_rev elif merge_mode == 'ave': merge_func = lambda y, y_rev: (y + y_rev) / 2 elif merge_mode == 'concat': merge_func = lambda y, y_rev: np.concatenate((y, y_rev), axis=-1) else: merge_func = lambda y, y_rev: [y, y_rev] # basic case inputs = Input((timesteps, dim)) layer = wrappers.Bidirectional(rnn(units, return_sequences=True), merge_mode=merge_mode) f_merged = K.function([inputs], to_list(layer(inputs))) f_forward = K.function([inputs], [layer.forward_layer.call(inputs)]) f_backward = K.function([inputs], [K.reverse(layer.backward_layer.call(inputs), 1)]) y_merged = f_merged(X) y_expected = to_list(merge_func(f_forward(X)[0], f_backward(X)[0])) assert len(y_merged) == len(y_expected) for x1, x2 in zip(y_merged, y_expected): assert_allclose(x1, x2, atol=1e-5) # test return_state inputs = Input((timesteps, dim)) layer = wrappers.Bidirectional(rnn(units, return_state=True), merge_mode=merge_mode) f_merged = K.function([inputs], layer(inputs)) f_forward = K.function([inputs], layer.forward_layer.call(inputs)) f_backward = K.function([inputs], layer.backward_layer.call(inputs)) n_states = len(layer.layer.states) y_merged = f_merged(X) y_forward = f_forward(X) y_backward = f_backward(X) y_expected = to_list(merge_func(y_forward[0], y_backward[0])) assert len(y_merged) == len(y_expected) + n_states * 2 for x1, x2 in zip(y_merged, y_expected): assert_allclose(x1, x2, atol=1e-5) # test if the state of a BiRNN is the concatenation of the underlying RNNs y_merged = y_merged[-n_states * 2:] y_forward = y_forward[-n_states:] y_backward = y_backward[-n_states:] for state_birnn, state_inner in zip(y_merged, y_forward + y_backward): assert_allclose(state_birnn, state_inner, atol=1e-5) @pytest.mark.skipif(K.backend() == 'theano' or K.backend() == 'mxnet', reason='Not supported.') @pytest.mark.parametrize('merge_mode', ['sum', 'concat', None]) def test_Bidirectional_dropout(merge_mode): rnn = layers.LSTM samples = 2 dim = 5 timesteps = 3 units = 3 X = [np.random.rand(samples, timesteps, dim)] inputs = Input((timesteps, dim)) wrapped = wrappers.Bidirectional(rnn(units, dropout=0.2, recurrent_dropout=0.2), merge_mode=merge_mode) outputs = to_list(wrapped(inputs, training=True)) assert all(not getattr(x, '_uses_learning_phase') for x in outputs) inputs = Input((timesteps, dim)) wrapped = wrappers.Bidirectional(rnn(units, dropout=0.2, return_state=True), merge_mode=merge_mode) outputs = to_list(wrapped(inputs)) assert all(x._uses_learning_phase for x in outputs) model = Model(inputs, outputs) assert model.uses_learning_phase y1 = to_list(model.predict(X)) y2 = to_list(model.predict(X)) for x1, x2 in zip(y1, y2): assert_allclose(x1, x2, atol=1e-5) def test_Bidirectional_state_reuse(): rnn = layers.LSTM samples = 2 dim = 5 timesteps = 3 units = 3 input1 = Input((timesteps, dim)) layer = wrappers.Bidirectional(rnn(units, return_state=True, return_sequences=True)) state = layer(input1)[1:] # test passing invalid initial_state: passing a tensor input2 = Input((timesteps, dim)) with pytest.raises(ValueError): output = wrappers.Bidirectional(rnn(units))(input2, initial_state=state[0]) # test valid usage: passing a list output = wrappers.Bidirectional(rnn(units))(input2, initial_state=state) model = Model([input1, input2], output) assert len(model.layers) == 4 assert isinstance(model.layers[-1].input, list) inputs = [np.random.rand(samples, timesteps, dim), np.random.rand(samples, timesteps, dim)] outputs = model.predict(inputs) @pytest.mark.skipif(K.backend() == 'mxnet', reason='MXNet backend does not support custom RNN cell yet') def test_Bidirectional_with_constants(): class RNNCellWithConstants(Layer): def __init__(self, units, **kwargs): self.units = units self.state_size = units super(RNNCellWithConstants, self).__init__(**kwargs) def build(self, input_shape): if not isinstance(input_shape, list): raise TypeError('expects constants shape') [input_shape, constant_shape] = input_shape # will (and should) raise if more than one constant passed self.input_kernel = self.add_weight( shape=(input_shape[-1], self.units), initializer='uniform', name='kernel') self.recurrent_kernel = self.add_weight( shape=(self.units, self.units), initializer='uniform', name='recurrent_kernel') self.constant_kernel = self.add_weight( shape=(constant_shape[-1], self.units), initializer='uniform', name='constant_kernel') self.built = True def call(self, inputs, states, constants): [prev_output] = states [constant] = constants h_input = K.dot(inputs, self.input_kernel) h_state = K.dot(prev_output, self.recurrent_kernel) h_const = K.dot(constant, self.constant_kernel) output = h_input + h_state + h_const return output, [output] def get_config(self): config = {'units': self.units} base_config = super(RNNCellWithConstants, self).get_config() return dict(list(base_config.items()) + list(config.items())) # Test basic case. x = Input((5, 5)) c = Input((3,)) cell = RNNCellWithConstants(32) custom_objects = {'RNNCellWithConstants': RNNCellWithConstants} with CustomObjectScope(custom_objects): layer = wrappers.Bidirectional(RNN(cell)) y = layer(x, constants=c) model = Model([x, c], y) model.compile(optimizer='rmsprop', loss='mse') model.train_on_batch( [np.zeros((6, 5, 5)), np.zeros((6, 3))], np.zeros((6, 64)) ) # Test basic case serialization. x_np = np.random.random((6, 5, 5)) c_np = np.random.random((6, 3)) y_np = model.predict([x_np, c_np]) weights = model.get_weights() config = layer.get_config() with CustomObjectScope(custom_objects): layer = wrappers.Bidirectional.from_config(copy.deepcopy(config)) y = layer(x, constants=c) model = Model([x, c], y) model.set_weights(weights) y_np_2 = model.predict([x_np, c_np]) assert_allclose(y_np, y_np_2, atol=1e-4) # test flat list inputs with CustomObjectScope(custom_objects): layer = wrappers.Bidirectional.from_config(copy.deepcopy(config)) y = layer([x, c]) model = Model([x, c], y) model.set_weights(weights) y_np_3 = model.predict([x_np, c_np]) assert_allclose(y_np, y_np_3, atol=1e-4) @pytest.mark.skipif(K.backend() == 'mxnet', reason='MXNet backend does not support custom RNN cell yet') def test_Bidirectional_with_constants_layer_passing_initial_state(): class RNNCellWithConstants(Layer): def __init__(self, units, **kwargs): self.units = units self.state_size = units super(RNNCellWithConstants, self).__init__(**kwargs) def build(self, input_shape): if not isinstance(input_shape, list): raise TypeError('expects constants shape') [input_shape, constant_shape] = input_shape # will (and should) raise if more than one constant passed self.input_kernel = self.add_weight( shape=(input_shape[-1], self.units), initializer='uniform', name='kernel') self.recurrent_kernel = self.add_weight( shape=(self.units, self.units), initializer='uniform', name='recurrent_kernel') self.constant_kernel = self.add_weight( shape=(constant_shape[-1], self.units), initializer='uniform', name='constant_kernel') self.built = True def call(self, inputs, states, constants): [prev_output] = states [constant] = constants h_input = K.dot(inputs, self.input_kernel) h_state = K.dot(prev_output, self.recurrent_kernel) h_const = K.dot(constant, self.constant_kernel) output = h_input + h_state + h_const return output, [output] def get_config(self): config = {'units': self.units} base_config = super(RNNCellWithConstants, self).get_config() return dict(list(base_config.items()) + list(config.items())) # Test basic case. x = Input((5, 5)) c = Input((3,)) s_for = Input((32,)) s_bac = Input((32,)) cell = RNNCellWithConstants(32) custom_objects = {'RNNCellWithConstants': RNNCellWithConstants} with CustomObjectScope(custom_objects): layer = wrappers.Bidirectional(RNN(cell)) y = layer(x, initial_state=[s_for, s_bac], constants=c) model = Model([x, s_for, s_bac, c], y) model.compile(optimizer='rmsprop', loss='mse') model.train_on_batch( [np.zeros((6, 5, 5)), np.zeros((6, 32)), np.zeros((6, 32)), np.zeros((6, 3))], np.zeros((6, 64)) ) # Test basic case serialization. x_np = np.random.random((6, 5, 5)) s_fw_np = np.random.random((6, 32)) s_bk_np = np.random.random((6, 32)) c_np = np.random.random((6, 3)) y_np = model.predict([x_np, s_fw_np, s_bk_np, c_np]) weights = model.get_weights() config = layer.get_config() with CustomObjectScope(custom_objects): layer = wrappers.Bidirectional.from_config(copy.deepcopy(config)) y = layer(x, initial_state=[s_for, s_bac], constants=c) model = Model([x, s_for, s_bac, c], y) model.set_weights(weights) y_np_2 = model.predict([x_np, s_fw_np, s_bk_np, c_np]) assert_allclose(y_np, y_np_2, atol=1e-4) # verify that state is used y_np_2_different_s = model.predict([x_np, s_fw_np + 10., s_bk_np + 10., c_np]) with pytest.raises(AssertionError): assert_allclose(y_np, y_np_2_different_s, atol=1e-4) # test flat list inputs with CustomObjectScope(custom_objects): layer = wrappers.Bidirectional.from_config(copy.deepcopy(config)) y = layer([x, s_for, s_bac, c]) model = Model([x, s_for, s_bac, c], y) model.set_weights(weights) y_np_3 = model.predict([x_np, s_fw_np, s_bk_np, c_np]) assert_allclose(y_np, y_np_3, atol=1e-4) def test_Bidirectional_trainable(): # test layers that need learning_phase to be set x = Input(shape=(3, 2)) layer = wrappers.Bidirectional(layers.SimpleRNN(3)) _ = layer(x) assert len(layer.trainable_weights) == 6 layer.trainable = False assert len(layer.trainable_weights) == 0 layer.trainable = True assert len(layer.trainable_weights) == 6 def test_Bidirectional_updates(): x = Input(shape=(3, 2)) layer = wrappers.Bidirectional(layers.SimpleRNN(3)) assert len(layer.updates) == 0 assert len(layer.get_updates_for(None)) == 0 assert len(layer.get_updates_for(x)) == 0 layer.forward_layer.add_update(0, inputs=x) layer.forward_layer.add_update(1, inputs=None) layer.backward_layer.add_update(0, inputs=x) layer.backward_layer.add_update(1, inputs=None) assert len(layer.updates) == 4 assert len(layer.get_updates_for(None)) == 2 assert len(layer.get_updates_for(x)) == 2 def test_Bidirectional_losses(): x = Input(shape=(3, 2)) layer = wrappers.Bidirectional( layers.SimpleRNN(3, kernel_regularizer='l1', bias_regularizer='l1')) _ = layer(x) assert len(layer.losses) == 4 assert len(layer.get_losses_for(None)) == 4 assert len(layer.get_losses_for(x)) == 0 layer.forward_layer.add_loss(0, inputs=x) layer.forward_layer.add_loss(1, inputs=None) layer.backward_layer.add_loss(0, inputs=x) layer.backward_layer.add_loss(1, inputs=None) assert len(layer.losses) == 8 assert len(layer.get_losses_for(None)) == 6 assert len(layer.get_losses_for(x)) == 2 if __name__ == '__main__': pytest.main([__file__])
<filename>tests/keras/layers/wrappers_test.py<gh_stars>100-1000 import pytest import numpy as np import copy from numpy.testing import assert_allclose from keras.utils import CustomObjectScope from keras.layers import wrappers, Input, Layer from keras.layers import RNN from keras import layers from keras.models import Sequential, Model, model_from_json from keras import backend as K from keras.utils.generic_utils import object_list_uid, to_list @pytest.mark.skipif(K.backend() == 'mxnet', reason='MXNet backend does not support TimeDistributed and RNN yet') def test_TimeDistributed(): # first, test with Dense layer model = Sequential() model.add(wrappers.TimeDistributed(layers.Dense(2), input_shape=(3, 4))) model.add(layers.Activation('relu')) model.compile(optimizer='rmsprop', loss='mse') model.fit(np.random.random((10, 3, 4)), np.random.random((10, 3, 2)), epochs=1, batch_size=10) # test config model.get_config() # test when specifying a batch_input_shape test_input = np.random.random((1, 3, 4)) test_output = model.predict(test_input) weights = model.layers[0].get_weights() reference = Sequential() reference.add(wrappers.TimeDistributed(layers.Dense(2), batch_input_shape=(1, 3, 4))) reference.add(layers.Activation('relu')) reference.compile(optimizer='rmsprop', loss='mse') reference.layers[0].set_weights(weights) reference_output = reference.predict(test_input) assert_allclose(test_output, reference_output, atol=1e-05) # test with Embedding model = Sequential() model.add(wrappers.TimeDistributed(layers.Embedding(5, 6), batch_input_shape=(10, 3, 4), dtype='int32')) model.compile(optimizer='rmsprop', loss='mse') model.fit(np.random.randint(5, size=(10, 3, 4), dtype='int32'), np.random.random((10, 3, 4, 6)), epochs=1, batch_size=10) # compare to not using batch_input_shape test_input = np.random.randint(5, size=(10, 3, 4), dtype='int32') test_output = model.predict(test_input) weights = model.layers[0].get_weights() reference = Sequential() reference.add(wrappers.TimeDistributed(layers.Embedding(5, 6), input_shape=(3, 4), dtype='int32')) reference.compile(optimizer='rmsprop', loss='mse') reference.layers[0].set_weights(weights) reference_output = reference.predict(test_input) assert_allclose(test_output, reference_output, atol=1e-05) # test with Conv2D model = Sequential() model.add(wrappers.TimeDistributed(layers.Conv2D(5, (2, 2), padding='same'), input_shape=(2, 4, 4, 3))) model.add(layers.Activation('relu')) model.compile(optimizer='rmsprop', loss='mse') model.train_on_batch(np.random.random((1, 2, 4, 4, 3)), np.random.random((1, 2, 4, 4, 5))) model = model_from_json(model.to_json()) model.summary() # test stacked layers model = Sequential() model.add(wrappers.TimeDistributed(layers.Dense(2), input_shape=(3, 4))) model.add(wrappers.TimeDistributed(layers.Dense(3))) model.add(layers.Activation('relu')) model.compile(optimizer='rmsprop', loss='mse') model.fit(np.random.random((10, 3, 4)), np.random.random((10, 3, 3)), epochs=1, batch_size=10) # test wrapping Sequential model model = Sequential() model.add(layers.Dense(3, input_dim=2)) outer_model = Sequential() outer_model.add(wrappers.TimeDistributed(model, input_shape=(3, 2))) outer_model.compile(optimizer='rmsprop', loss='mse') outer_model.fit(np.random.random((10, 3, 2)), np.random.random((10, 3, 3)), epochs=1, batch_size=10) # test with functional API x = Input(shape=(3, 2)) y = wrappers.TimeDistributed(model)(x) outer_model = Model(x, y) outer_model.compile(optimizer='rmsprop', loss='mse') outer_model.fit(np.random.random((10, 3, 2)), np.random.random((10, 3, 3)), epochs=1, batch_size=10) # test with BatchNormalization model = Sequential() model.add(wrappers.TimeDistributed( layers.BatchNormalization(center=True, scale=True), name='bn', input_shape=(10, 2))) model.compile(optimizer='rmsprop', loss='mse') # Assert that mean and variance are 0 and 1. td = model.layers[0] assert np.array_equal(td.get_weights()[2], np.array([0, 0])) assert np.array_equal(td.get_weights()[3], np.array([1, 1])) # Train model.train_on_batch(np.random.normal(loc=2, scale=2, size=(1, 10, 2)), np.broadcast_to(np.array([0, 1]), (1, 10, 2))) # Assert that mean and variance changed. assert not np.array_equal(td.get_weights()[2], np.array([0, 0])) assert not np.array_equal(td.get_weights()[3], np.array([1, 1])) # Verify input_map has one mapping from inputs to reshaped inputs. uid = object_list_uid(model.inputs) assert len(td._input_map.keys()) == 1 assert uid in td._input_map assert K.int_shape(td._input_map[uid]) == (None, 2) @pytest.mark.skipif(K.backend() == 'mxnet', reason='MXNet backend does not support TimeDistributed and RNN yet') @pytest.mark.skipif((K.backend() == 'cntk'), reason='Flaky with CNTK backend') def test_TimeDistributed_learning_phase(): # test layers that need learning_phase to be set np.random.seed(1234) x = Input(shape=(3, 2)) y = wrappers.TimeDistributed(layers.Dropout(.999))(x, training=True) model = Model(x, y) y = model.predict(np.random.random((10, 3, 2))) assert_allclose(np.mean(y), 0., atol=1e-1, rtol=1e-1) @pytest.mark.skipif(K.backend() == 'mxnet', reason='MXNet backend does not support TimeDistributed and RNN yet') def test_TimeDistributed_trainable(): # test layers that need learning_phase to be set x = Input(shape=(3, 2)) layer = wrappers.TimeDistributed(layers.BatchNormalization()) _ = layer(x) assert len(layer.updates) == 2 assert len(layer.trainable_weights) == 2 layer.trainable = False assert len(layer.updates) == 0 assert len(layer.trainable_weights) == 0 layer.trainable = True assert len(layer.updates) == 2 assert len(layer.trainable_weights) == 2 @pytest.mark.skipif((K.backend() == 'cntk' or K.backend() == 'mxnet'), reason='Unknown timestamps for RNN not supported in CNTK and MXNet.') def test_TimeDistributed_with_masked_embedding_and_unspecified_shape(): # test with unspecified shape and Embeddings with mask_zero model = Sequential() model.add(wrappers.TimeDistributed(layers.Embedding(5, 6, mask_zero=True), input_shape=(None, None))) # the shape so far: (N, t_1, t_2, 6) model.add(wrappers.TimeDistributed(layers.SimpleRNN(7, return_sequences=True))) model.add(wrappers.TimeDistributed(layers.SimpleRNN(8, return_sequences=False))) model.add(layers.SimpleRNN(1, return_sequences=False)) model.compile(optimizer='rmsprop', loss='mse') model_input = np.random.randint(low=1, high=5, size=(10, 3, 4), dtype='int32') for i in range(4): model_input[i, i:, i:] = 0 model.fit(model_input, np.random.random((10, 1)), epochs=1, batch_size=10) mask_outputs = [model.layers[0].compute_mask(model.input)] for layer in model.layers[1:]: mask_outputs.append(layer.compute_mask(layer.input, mask_outputs[-1])) func = K.function([model.input], mask_outputs[:-1]) mask_outputs_val = func([model_input]) ref_mask_val_0 = model_input > 0 # embedding layer ref_mask_val_1 = ref_mask_val_0 # first RNN layer ref_mask_val_2 = np.any(ref_mask_val_1, axis=-1) # second RNN layer ref_mask_val = [ref_mask_val_0, ref_mask_val_1, ref_mask_val_2] for i in range(3): assert np.array_equal(mask_outputs_val[i], ref_mask_val[i]) assert mask_outputs[-1] is None # final layer @pytest.mark.skipif(K.backend() == 'mxnet', reason='MXNet backend does not support TimeDistributed and RNN yet') def test_TimeDistributed_with_masking_layer(): # test with Masking layer model = Sequential() model.add(wrappers.TimeDistributed(layers.Masking(mask_value=0.,), input_shape=(None, 4))) model.add(wrappers.TimeDistributed(layers.Dense(5))) model.compile(optimizer='rmsprop', loss='mse') model_input = np.random.randint(low=1, high=5, size=(10, 3, 4)) for i in range(4): model_input[i, i:, :] = 0. model.compile(optimizer='rmsprop', loss='mse') model.fit(model_input, np.random.random((10, 3, 5)), epochs=1, batch_size=6) mask_outputs = [model.layers[0].compute_mask(model.input)] mask_outputs += [model.layers[1].compute_mask(model.layers[1].input, mask_outputs[-1])] func = K.function([model.input], mask_outputs) mask_outputs_val = func([model_input]) assert np.array_equal(mask_outputs_val[0], np.any(model_input, axis=-1)) assert np.array_equal(mask_outputs_val[1], np.any(model_input, axis=-1)) def test_regularizers(): model = Sequential() model.add(wrappers.TimeDistributed( layers.Dense(2, kernel_regularizer='l1'), input_shape=(3, 4))) model.add(layers.Activation('relu')) model.compile(optimizer='rmsprop', loss='mse') assert len(model.layers[0].layer.losses) == 1 assert len(model.layers[0].losses) == 1 assert len(model.layers[0].get_losses_for(None)) == 1 assert len(model.losses) == 1 model = Sequential() model.add(wrappers.TimeDistributed( layers.Dense(2, activity_regularizer='l1'), input_shape=(3, 4))) model.add(layers.Activation('relu')) model.compile(optimizer='rmsprop', loss='mse') assert len(model.losses) == 1 def test_Bidirectional(): rnn = layers.SimpleRNN samples = 2 dim = 2 timesteps = 2 output_dim = 2 dropout_rate = 0.2 for mode in ['sum', 'concat']: x = np.random.random((samples, timesteps, dim)) target_dim = 2 * output_dim if mode == 'concat' else output_dim y = np.random.random((samples, target_dim)) # test with Sequential model model = Sequential() model.add(wrappers.Bidirectional(rnn(output_dim, dropout=dropout_rate, recurrent_dropout=dropout_rate), merge_mode=mode, input_shape=(timesteps, dim))) model.compile(loss='mse', optimizer='sgd') model.fit(x, y, epochs=1, batch_size=1) # test config model.get_config() model = model_from_json(model.to_json()) model.summary() # test stacked bidirectional layers model = Sequential() model.add(wrappers.Bidirectional(rnn(output_dim, return_sequences=True), merge_mode=mode, input_shape=(timesteps, dim))) model.add(wrappers.Bidirectional(rnn(output_dim), merge_mode=mode)) model.compile(loss='mse', optimizer='sgd') model.fit(x, y, epochs=1, batch_size=1) # test with functional API inputs = Input((timesteps, dim)) outputs = wrappers.Bidirectional(rnn(output_dim, dropout=dropout_rate, recurrent_dropout=dropout_rate), merge_mode=mode)(inputs) model = Model(inputs, outputs) model.compile(loss='mse', optimizer='sgd') model.fit(x, y, epochs=1, batch_size=1) # Bidirectional and stateful inputs = Input(batch_shape=(1, timesteps, dim)) outputs = wrappers.Bidirectional(rnn(output_dim, stateful=True), merge_mode=mode)(inputs) model = Model(inputs, outputs) model.compile(loss='mse', optimizer='sgd') model.fit(x, y, epochs=1, batch_size=1) @pytest.mark.skipif((K.backend() == 'cntk'), reason='Unknown timestamps not supported in CNTK.') def test_Bidirectional_dynamic_timesteps(): # test with functional API with dynamic length rnn = layers.SimpleRNN samples = 2 dim = 2 timesteps = 2 output_dim = 2 dropout_rate = 0.2 for mode in ['sum', 'concat']: x = np.random.random((samples, timesteps, dim)) target_dim = 2 * output_dim if mode == 'concat' else output_dim y = np.random.random((samples, target_dim)) inputs = Input((None, dim)) outputs = wrappers.Bidirectional(rnn(output_dim, dropout=dropout_rate, recurrent_dropout=dropout_rate), merge_mode=mode)(inputs) model = Model(inputs, outputs) model.compile(loss='mse', optimizer='sgd') model.fit(x, y, epochs=1, batch_size=1) @pytest.mark.parametrize('merge_mode', ['sum', 'mul', 'ave', 'concat', None]) def test_Bidirectional_merged_value(merge_mode): rnn = layers.LSTM samples = 2 dim = 5 timesteps = 3 units = 3 X = [np.random.rand(samples, timesteps, dim)] if merge_mode == 'sum': merge_func = lambda y, y_rev: y + y_rev elif merge_mode == 'mul': merge_func = lambda y, y_rev: y * y_rev elif merge_mode == 'ave': merge_func = lambda y, y_rev: (y + y_rev) / 2 elif merge_mode == 'concat': merge_func = lambda y, y_rev: np.concatenate((y, y_rev), axis=-1) else: merge_func = lambda y, y_rev: [y, y_rev] # basic case inputs = Input((timesteps, dim)) layer = wrappers.Bidirectional(rnn(units, return_sequences=True), merge_mode=merge_mode) f_merged = K.function([inputs], to_list(layer(inputs))) f_forward = K.function([inputs], [layer.forward_layer.call(inputs)]) f_backward = K.function([inputs], [K.reverse(layer.backward_layer.call(inputs), 1)]) y_merged = f_merged(X) y_expected = to_list(merge_func(f_forward(X)[0], f_backward(X)[0])) assert len(y_merged) == len(y_expected) for x1, x2 in zip(y_merged, y_expected): assert_allclose(x1, x2, atol=1e-5) # test return_state inputs = Input((timesteps, dim)) layer = wrappers.Bidirectional(rnn(units, return_state=True), merge_mode=merge_mode) f_merged = K.function([inputs], layer(inputs)) f_forward = K.function([inputs], layer.forward_layer.call(inputs)) f_backward = K.function([inputs], layer.backward_layer.call(inputs)) n_states = len(layer.layer.states) y_merged = f_merged(X) y_forward = f_forward(X) y_backward = f_backward(X) y_expected = to_list(merge_func(y_forward[0], y_backward[0])) assert len(y_merged) == len(y_expected) + n_states * 2 for x1, x2 in zip(y_merged, y_expected): assert_allclose(x1, x2, atol=1e-5) # test if the state of a BiRNN is the concatenation of the underlying RNNs y_merged = y_merged[-n_states * 2:] y_forward = y_forward[-n_states:] y_backward = y_backward[-n_states:] for state_birnn, state_inner in zip(y_merged, y_forward + y_backward): assert_allclose(state_birnn, state_inner, atol=1e-5) @pytest.mark.skipif(K.backend() == 'theano' or K.backend() == 'mxnet', reason='Not supported.') @pytest.mark.parametrize('merge_mode', ['sum', 'concat', None]) def test_Bidirectional_dropout(merge_mode): rnn = layers.LSTM samples = 2 dim = 5 timesteps = 3 units = 3 X = [np.random.rand(samples, timesteps, dim)] inputs = Input((timesteps, dim)) wrapped = wrappers.Bidirectional(rnn(units, dropout=0.2, recurrent_dropout=0.2), merge_mode=merge_mode) outputs = to_list(wrapped(inputs, training=True)) assert all(not getattr(x, '_uses_learning_phase') for x in outputs) inputs = Input((timesteps, dim)) wrapped = wrappers.Bidirectional(rnn(units, dropout=0.2, return_state=True), merge_mode=merge_mode) outputs = to_list(wrapped(inputs)) assert all(x._uses_learning_phase for x in outputs) model = Model(inputs, outputs) assert model.uses_learning_phase y1 = to_list(model.predict(X)) y2 = to_list(model.predict(X)) for x1, x2 in zip(y1, y2): assert_allclose(x1, x2, atol=1e-5) def test_Bidirectional_state_reuse(): rnn = layers.LSTM samples = 2 dim = 5 timesteps = 3 units = 3 input1 = Input((timesteps, dim)) layer = wrappers.Bidirectional(rnn(units, return_state=True, return_sequences=True)) state = layer(input1)[1:] # test passing invalid initial_state: passing a tensor input2 = Input((timesteps, dim)) with pytest.raises(ValueError): output = wrappers.Bidirectional(rnn(units))(input2, initial_state=state[0]) # test valid usage: passing a list output = wrappers.Bidirectional(rnn(units))(input2, initial_state=state) model = Model([input1, input2], output) assert len(model.layers) == 4 assert isinstance(model.layers[-1].input, list) inputs = [np.random.rand(samples, timesteps, dim), np.random.rand(samples, timesteps, dim)] outputs = model.predict(inputs) @pytest.mark.skipif(K.backend() == 'mxnet', reason='MXNet backend does not support custom RNN cell yet') def test_Bidirectional_with_constants(): class RNNCellWithConstants(Layer): def __init__(self, units, **kwargs): self.units = units self.state_size = units super(RNNCellWithConstants, self).__init__(**kwargs) def build(self, input_shape): if not isinstance(input_shape, list): raise TypeError('expects constants shape') [input_shape, constant_shape] = input_shape # will (and should) raise if more than one constant passed self.input_kernel = self.add_weight( shape=(input_shape[-1], self.units), initializer='uniform', name='kernel') self.recurrent_kernel = self.add_weight( shape=(self.units, self.units), initializer='uniform', name='recurrent_kernel') self.constant_kernel = self.add_weight( shape=(constant_shape[-1], self.units), initializer='uniform', name='constant_kernel') self.built = True def call(self, inputs, states, constants): [prev_output] = states [constant] = constants h_input = K.dot(inputs, self.input_kernel) h_state = K.dot(prev_output, self.recurrent_kernel) h_const = K.dot(constant, self.constant_kernel) output = h_input + h_state + h_const return output, [output] def get_config(self): config = {'units': self.units} base_config = super(RNNCellWithConstants, self).get_config() return dict(list(base_config.items()) + list(config.items())) # Test basic case. x = Input((5, 5)) c = Input((3,)) cell = RNNCellWithConstants(32) custom_objects = {'RNNCellWithConstants': RNNCellWithConstants} with CustomObjectScope(custom_objects): layer = wrappers.Bidirectional(RNN(cell)) y = layer(x, constants=c) model = Model([x, c], y) model.compile(optimizer='rmsprop', loss='mse') model.train_on_batch( [np.zeros((6, 5, 5)), np.zeros((6, 3))], np.zeros((6, 64)) ) # Test basic case serialization. x_np = np.random.random((6, 5, 5)) c_np = np.random.random((6, 3)) y_np = model.predict([x_np, c_np]) weights = model.get_weights() config = layer.get_config() with CustomObjectScope(custom_objects): layer = wrappers.Bidirectional.from_config(copy.deepcopy(config)) y = layer(x, constants=c) model = Model([x, c], y) model.set_weights(weights) y_np_2 = model.predict([x_np, c_np]) assert_allclose(y_np, y_np_2, atol=1e-4) # test flat list inputs with CustomObjectScope(custom_objects): layer = wrappers.Bidirectional.from_config(copy.deepcopy(config)) y = layer([x, c]) model = Model([x, c], y) model.set_weights(weights) y_np_3 = model.predict([x_np, c_np]) assert_allclose(y_np, y_np_3, atol=1e-4) @pytest.mark.skipif(K.backend() == 'mxnet', reason='MXNet backend does not support custom RNN cell yet') def test_Bidirectional_with_constants_layer_passing_initial_state(): class RNNCellWithConstants(Layer): def __init__(self, units, **kwargs): self.units = units self.state_size = units super(RNNCellWithConstants, self).__init__(**kwargs) def build(self, input_shape): if not isinstance(input_shape, list): raise TypeError('expects constants shape') [input_shape, constant_shape] = input_shape # will (and should) raise if more than one constant passed self.input_kernel = self.add_weight( shape=(input_shape[-1], self.units), initializer='uniform', name='kernel') self.recurrent_kernel = self.add_weight( shape=(self.units, self.units), initializer='uniform', name='recurrent_kernel') self.constant_kernel = self.add_weight( shape=(constant_shape[-1], self.units), initializer='uniform', name='constant_kernel') self.built = True def call(self, inputs, states, constants): [prev_output] = states [constant] = constants h_input = K.dot(inputs, self.input_kernel) h_state = K.dot(prev_output, self.recurrent_kernel) h_const = K.dot(constant, self.constant_kernel) output = h_input + h_state + h_const return output, [output] def get_config(self): config = {'units': self.units} base_config = super(RNNCellWithConstants, self).get_config() return dict(list(base_config.items()) + list(config.items())) # Test basic case. x = Input((5, 5)) c = Input((3,)) s_for = Input((32,)) s_bac = Input((32,)) cell = RNNCellWithConstants(32) custom_objects = {'RNNCellWithConstants': RNNCellWithConstants} with CustomObjectScope(custom_objects): layer = wrappers.Bidirectional(RNN(cell)) y = layer(x, initial_state=[s_for, s_bac], constants=c) model = Model([x, s_for, s_bac, c], y) model.compile(optimizer='rmsprop', loss='mse') model.train_on_batch( [np.zeros((6, 5, 5)), np.zeros((6, 32)), np.zeros((6, 32)), np.zeros((6, 3))], np.zeros((6, 64)) ) # Test basic case serialization. x_np = np.random.random((6, 5, 5)) s_fw_np = np.random.random((6, 32)) s_bk_np = np.random.random((6, 32)) c_np = np.random.random((6, 3)) y_np = model.predict([x_np, s_fw_np, s_bk_np, c_np]) weights = model.get_weights() config = layer.get_config() with CustomObjectScope(custom_objects): layer = wrappers.Bidirectional.from_config(copy.deepcopy(config)) y = layer(x, initial_state=[s_for, s_bac], constants=c) model = Model([x, s_for, s_bac, c], y) model.set_weights(weights) y_np_2 = model.predict([x_np, s_fw_np, s_bk_np, c_np]) assert_allclose(y_np, y_np_2, atol=1e-4) # verify that state is used y_np_2_different_s = model.predict([x_np, s_fw_np + 10., s_bk_np + 10., c_np]) with pytest.raises(AssertionError): assert_allclose(y_np, y_np_2_different_s, atol=1e-4) # test flat list inputs with CustomObjectScope(custom_objects): layer = wrappers.Bidirectional.from_config(copy.deepcopy(config)) y = layer([x, s_for, s_bac, c]) model = Model([x, s_for, s_bac, c], y) model.set_weights(weights) y_np_3 = model.predict([x_np, s_fw_np, s_bk_np, c_np]) assert_allclose(y_np, y_np_3, atol=1e-4) def test_Bidirectional_trainable(): # test layers that need learning_phase to be set x = Input(shape=(3, 2)) layer = wrappers.Bidirectional(layers.SimpleRNN(3)) _ = layer(x) assert len(layer.trainable_weights) == 6 layer.trainable = False assert len(layer.trainable_weights) == 0 layer.trainable = True assert len(layer.trainable_weights) == 6 def test_Bidirectional_updates(): x = Input(shape=(3, 2)) layer = wrappers.Bidirectional(layers.SimpleRNN(3)) assert len(layer.updates) == 0 assert len(layer.get_updates_for(None)) == 0 assert len(layer.get_updates_for(x)) == 0 layer.forward_layer.add_update(0, inputs=x) layer.forward_layer.add_update(1, inputs=None) layer.backward_layer.add_update(0, inputs=x) layer.backward_layer.add_update(1, inputs=None) assert len(layer.updates) == 4 assert len(layer.get_updates_for(None)) == 2 assert len(layer.get_updates_for(x)) == 2 def test_Bidirectional_losses(): x = Input(shape=(3, 2)) layer = wrappers.Bidirectional( layers.SimpleRNN(3, kernel_regularizer='l1', bias_regularizer='l1')) _ = layer(x) assert len(layer.losses) == 4 assert len(layer.get_losses_for(None)) == 4 assert len(layer.get_losses_for(x)) == 0 layer.forward_layer.add_loss(0, inputs=x) layer.forward_layer.add_loss(1, inputs=None) layer.backward_layer.add_loss(0, inputs=x) layer.backward_layer.add_loss(1, inputs=None) assert len(layer.losses) == 8 assert len(layer.get_losses_for(None)) == 6 assert len(layer.get_losses_for(x)) == 2 if __name__ == '__main__': pytest.main([__file__])
en
0.772666
# first, test with Dense layer # test config # test when specifying a batch_input_shape # test with Embedding # compare to not using batch_input_shape # test with Conv2D # test stacked layers # test wrapping Sequential model # test with functional API # test with BatchNormalization # Assert that mean and variance are 0 and 1. # Train # Assert that mean and variance changed. # Verify input_map has one mapping from inputs to reshaped inputs. # test layers that need learning_phase to be set # test layers that need learning_phase to be set # test with unspecified shape and Embeddings with mask_zero # the shape so far: (N, t_1, t_2, 6) # embedding layer # first RNN layer # second RNN layer # final layer # test with Masking layer # test with Sequential model # test config # test stacked bidirectional layers # test with functional API # Bidirectional and stateful # test with functional API with dynamic length # basic case # test return_state # test if the state of a BiRNN is the concatenation of the underlying RNNs # test passing invalid initial_state: passing a tensor # test valid usage: passing a list # will (and should) raise if more than one constant passed # Test basic case. # Test basic case serialization. # test flat list inputs # will (and should) raise if more than one constant passed # Test basic case. # Test basic case serialization. # verify that state is used # test flat list inputs # test layers that need learning_phase to be set
2.096959
2
src/tornado-3.2.2/tornado/platform/common.py
code-annotator/tornado-annotated
645
60
<gh_stars>100-1000 """Lowest-common-denominator implementations of platform functionality.""" from __future__ import absolute_import, division, print_function, with_statement import errno import socket from tornado.platform import interface class Waker(interface.Waker): """Create an OS independent asynchronous pipe. For use on platforms that don't have os.pipe() (or where pipes cannot be passed to select()), but do have sockets. This includes Windows and Jython. """ def __init__(self): # Based on Zope async.py: http://svn.zope.org/zc.ngi/trunk/src/zc/ngi/async.py self.writer = socket.socket() # Disable buffering -- pulling the trigger sends 1 byte, # and we want that sent immediately, to wake up ASAP. self.writer.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) count = 0 while 1: count += 1 # Bind to a local port; for efficiency, let the OS pick # a free port for us. # Unfortunately, stress tests showed that we may not # be able to connect to that port ("Address already in # use") despite that the OS picked it. This appears # to be a race bug in the Windows socket implementation. # So we loop until a connect() succeeds (almost always # on the first try). See the long thread at # http://mail.zope.org/pipermail/zope/2005-July/160433.html # for hideous details. a = socket.socket() a.bind(("127.0.0.1", 0)) a.listen(1) connect_address = a.getsockname() # assigned (host, port) pair try: self.writer.connect(connect_address) break # success except socket.error as detail: if (not hasattr(errno, 'WSAEADDRINUSE') or detail[0] != errno.WSAEADDRINUSE): # "Address already in use" is the only error # I've seen on two WinXP Pro SP2 boxes, under # Pythons 2.3.5 and 2.4.1. raise # (10048, 'Address already in use') # assert count <= 2 # never triggered in Tim's tests if count >= 10: # I've never seen it go above 2 a.close() self.writer.close() raise socket.error("Cannot bind trigger!") # Close `a` and try again. Note: I originally put a short # sleep() here, but it didn't appear to help or hurt. a.close() self.reader, addr = a.accept() self.reader.setblocking(0) self.writer.setblocking(0) a.close() self.reader_fd = self.reader.fileno() def fileno(self): return self.reader.fileno() def write_fileno(self): return self.writer.fileno() def wake(self): try: self.writer.send(b"x") except (IOError, socket.error): pass def consume(self): try: while True: result = self.reader.recv(1024) if not result: break except (IOError, socket.error): pass def close(self): self.reader.close() self.writer.close()
"""Lowest-common-denominator implementations of platform functionality.""" from __future__ import absolute_import, division, print_function, with_statement import errno import socket from tornado.platform import interface class Waker(interface.Waker): """Create an OS independent asynchronous pipe. For use on platforms that don't have os.pipe() (or where pipes cannot be passed to select()), but do have sockets. This includes Windows and Jython. """ def __init__(self): # Based on Zope async.py: http://svn.zope.org/zc.ngi/trunk/src/zc/ngi/async.py self.writer = socket.socket() # Disable buffering -- pulling the trigger sends 1 byte, # and we want that sent immediately, to wake up ASAP. self.writer.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) count = 0 while 1: count += 1 # Bind to a local port; for efficiency, let the OS pick # a free port for us. # Unfortunately, stress tests showed that we may not # be able to connect to that port ("Address already in # use") despite that the OS picked it. This appears # to be a race bug in the Windows socket implementation. # So we loop until a connect() succeeds (almost always # on the first try). See the long thread at # http://mail.zope.org/pipermail/zope/2005-July/160433.html # for hideous details. a = socket.socket() a.bind(("127.0.0.1", 0)) a.listen(1) connect_address = a.getsockname() # assigned (host, port) pair try: self.writer.connect(connect_address) break # success except socket.error as detail: if (not hasattr(errno, 'WSAEADDRINUSE') or detail[0] != errno.WSAEADDRINUSE): # "Address already in use" is the only error # I've seen on two WinXP Pro SP2 boxes, under # Pythons 2.3.5 and 2.4.1. raise # (10048, 'Address already in use') # assert count <= 2 # never triggered in Tim's tests if count >= 10: # I've never seen it go above 2 a.close() self.writer.close() raise socket.error("Cannot bind trigger!") # Close `a` and try again. Note: I originally put a short # sleep() here, but it didn't appear to help or hurt. a.close() self.reader, addr = a.accept() self.reader.setblocking(0) self.writer.setblocking(0) a.close() self.reader_fd = self.reader.fileno() def fileno(self): return self.reader.fileno() def write_fileno(self): return self.writer.fileno() def wake(self): try: self.writer.send(b"x") except (IOError, socket.error): pass def consume(self): try: while True: result = self.reader.recv(1024) if not result: break except (IOError, socket.error): pass def close(self): self.reader.close() self.writer.close()
en
0.893389
Lowest-common-denominator implementations of platform functionality. Create an OS independent asynchronous pipe. For use on platforms that don't have os.pipe() (or where pipes cannot be passed to select()), but do have sockets. This includes Windows and Jython. # Based on Zope async.py: http://svn.zope.org/zc.ngi/trunk/src/zc/ngi/async.py # Disable buffering -- pulling the trigger sends 1 byte, # and we want that sent immediately, to wake up ASAP. # Bind to a local port; for efficiency, let the OS pick # a free port for us. # Unfortunately, stress tests showed that we may not # be able to connect to that port ("Address already in # use") despite that the OS picked it. This appears # to be a race bug in the Windows socket implementation. # So we loop until a connect() succeeds (almost always # on the first try). See the long thread at # http://mail.zope.org/pipermail/zope/2005-July/160433.html # for hideous details. # assigned (host, port) pair # success # "Address already in use" is the only error # I've seen on two WinXP Pro SP2 boxes, under # Pythons 2.3.5 and 2.4.1. # (10048, 'Address already in use') # assert count <= 2 # never triggered in Tim's tests # I've never seen it go above 2 # Close `a` and try again. Note: I originally put a short # sleep() here, but it didn't appear to help or hurt.
2.524958
3
bathymetry_blink/bathymetry_blink.py
poster515/BlinkyTape_Python
26
61
""" This script will modulate the blinky lights using the following algorithm: 1) uses user-provided location to obtain row of pixel data from bathy image 2) samples a 'number of LEDs' number of pixels from that row 3) shifts the sampled row data to center it at the location specified by user 4) displays resulting pixels on Blinky Tape 5) shifts next row by a given latitude, also specified by user 6) sleeps for user-specified period of time Uses the following arguments: -l/--location: tuple Location of the user in tuple(lat, lon). This represents the center of the LED strip. Defaults to (0, 0) -u/--update-interval: int Update interval of the script, in minutes. Defaults to 10. -p/--port: str Serial port of the BlinkyLight (e.g., 'ttyAMA0', 'COM3'). Defaults to 'COM5'. -d/--delta_latitude: int Vertical change in latitude every update rate. May be 0, but this will result in a never-changing LEDs. -i/--image: str Name of the PNG image that contains the color coded pathymetric data. The file current named mapserv.png was obtained using the following API: https://www.gebco.net/data_and_products/gebco_web_services/web_map_service/mapserv?request=getmap&service=wms&BBOX=-90,-180,90,180&format=image/png&height=600&width=1200&crs=EPSG:4326&layers=GEBCO_LATEST_SUB_ICE_TOPO&version=1.3.0 In lieu of providing command line arguments, you may alternatively edit the defaults in bath_config.json. NOTE: runs via: runfile('/BlinkyTape_Python/bathymetry_blink/bathymetry_blink.py', wdir='/BlinkyTape_Python/') (C) 2021 <NAME> (https://joeycodes.dev) MIT Licensed """ import optparse import json from blinkytape import BlinkyTape from time import sleep from PIL import Image import numpy as np import sys MAX_ERRORS = 3 num_errors = 0 # Obtain default parameters with open("./bathymetry_blink/bathy_config.json") as f: config = json.load(f) # Default Blinky Tape port on Raspberry Pi is /dev/ttyACM0 parser = optparse.OptionParser() parser.add_option("-p", "--port", dest="portname", help="serial port (ex: /dev/ttyACM0)", default=config["port"]) parser.add_option("-l", "--location", dest="location", help="Location of the center of the LED strip (ex: 70,-110)", default=config["location"]) parser.add_option("-u", "--update-rate", dest="update_rate", help="How often to update elevation profile (mins) (ex: 5)", default=config["update_rate"]) parser.add_option("-d", "--delta-latitude", dest="delta_latitude", help="Change in latitude during update (ex: 5)", default=config["delta_latitude"]) parser.add_option("-n", "--num-leds", dest="num_leds", help="Number of LEDs in strip (ex: 60)", default=config["num_leds"]) parser.add_option("-i", "--image", dest="image_name", help="Name of the map/bathymetry image (ex: ./mapserv.png)", default=config["image"]) (options, args) = parser.parse_args() if args: print("Unknown parameters: " + args) # grab the values provided by user (or defaults) port = options.portname loc = options.location rate = options.update_rate delta = options.delta_latitude n_leds = options.num_leds i_name = options.image_name # Some visual indication that it works, for headless setups (green tape) bt = BlinkyTape(port, n_leds) bt.displayColor(0, 100, 0) bt.show() sleep(2) while True: try: # first, load image im = Image.open(i_name) # Can be many different formats. cols, rows = im.size a = np.asarray(im) # of shape (rows, cols, channels) # map loc latitude to 0-based index latitude_index = min(rows - 1, max(0, (int)(((loc[0] - -90) / (90 - -90)) * (rows - 0) + 0))) longitude_index = min(cols - 1, max(0, (int)(((loc[1] - -180) / (180 - -180)) * (cols - 0) + 0))) # update the location of the next row of elevation data to take loc[0] += delta loc[0] = ((loc[0] + 90) % 180) - 90 # wraps to next pole if overflow print("Lat index: " + str(latitude_index)) print("Lon index: " + str(longitude_index)) print("Next latitude: " + str(loc[0])) # grab the applicable pixel indices indices = [(int)(x*(cols/n_leds)) for x in range(n_leds)] # sample that row of pixel data output_pixels = np.take(a[latitude_index], indices, axis=0) # rotate the row to center around the specified longitude output_pixels = np.roll(output_pixels, longitude_index, axis=0) # send all pixel data to bt for pixel in output_pixels: print("Sending r: {}, g: {}, b: {}".format(*pixel)) bt.sendPixel(*pixel) # finally, show the image bt.show() # delete variables for memory management del a del im # Tape resets to stored pattern after a few seconds of inactivity sleep(rate * 60) # Wait specified number of minutes # sleep(10) # Wait specified number of minutes except KeyboardInterrupt: print("Keyboard interrupt, ending program.") sys.exit() except RuntimeError as e: print("Encountered runtime error: " + e.args[0]) # flush any incomplete data bt.show() num_errors += 1 if num_errors > MAX_ERRORS: sys.exit("Error count exceeds that allowed.")
""" This script will modulate the blinky lights using the following algorithm: 1) uses user-provided location to obtain row of pixel data from bathy image 2) samples a 'number of LEDs' number of pixels from that row 3) shifts the sampled row data to center it at the location specified by user 4) displays resulting pixels on Blinky Tape 5) shifts next row by a given latitude, also specified by user 6) sleeps for user-specified period of time Uses the following arguments: -l/--location: tuple Location of the user in tuple(lat, lon). This represents the center of the LED strip. Defaults to (0, 0) -u/--update-interval: int Update interval of the script, in minutes. Defaults to 10. -p/--port: str Serial port of the BlinkyLight (e.g., 'ttyAMA0', 'COM3'). Defaults to 'COM5'. -d/--delta_latitude: int Vertical change in latitude every update rate. May be 0, but this will result in a never-changing LEDs. -i/--image: str Name of the PNG image that contains the color coded pathymetric data. The file current named mapserv.png was obtained using the following API: https://www.gebco.net/data_and_products/gebco_web_services/web_map_service/mapserv?request=getmap&service=wms&BBOX=-90,-180,90,180&format=image/png&height=600&width=1200&crs=EPSG:4326&layers=GEBCO_LATEST_SUB_ICE_TOPO&version=1.3.0 In lieu of providing command line arguments, you may alternatively edit the defaults in bath_config.json. NOTE: runs via: runfile('/BlinkyTape_Python/bathymetry_blink/bathymetry_blink.py', wdir='/BlinkyTape_Python/') (C) 2021 <NAME> (https://joeycodes.dev) MIT Licensed """ import optparse import json from blinkytape import BlinkyTape from time import sleep from PIL import Image import numpy as np import sys MAX_ERRORS = 3 num_errors = 0 # Obtain default parameters with open("./bathymetry_blink/bathy_config.json") as f: config = json.load(f) # Default Blinky Tape port on Raspberry Pi is /dev/ttyACM0 parser = optparse.OptionParser() parser.add_option("-p", "--port", dest="portname", help="serial port (ex: /dev/ttyACM0)", default=config["port"]) parser.add_option("-l", "--location", dest="location", help="Location of the center of the LED strip (ex: 70,-110)", default=config["location"]) parser.add_option("-u", "--update-rate", dest="update_rate", help="How often to update elevation profile (mins) (ex: 5)", default=config["update_rate"]) parser.add_option("-d", "--delta-latitude", dest="delta_latitude", help="Change in latitude during update (ex: 5)", default=config["delta_latitude"]) parser.add_option("-n", "--num-leds", dest="num_leds", help="Number of LEDs in strip (ex: 60)", default=config["num_leds"]) parser.add_option("-i", "--image", dest="image_name", help="Name of the map/bathymetry image (ex: ./mapserv.png)", default=config["image"]) (options, args) = parser.parse_args() if args: print("Unknown parameters: " + args) # grab the values provided by user (or defaults) port = options.portname loc = options.location rate = options.update_rate delta = options.delta_latitude n_leds = options.num_leds i_name = options.image_name # Some visual indication that it works, for headless setups (green tape) bt = BlinkyTape(port, n_leds) bt.displayColor(0, 100, 0) bt.show() sleep(2) while True: try: # first, load image im = Image.open(i_name) # Can be many different formats. cols, rows = im.size a = np.asarray(im) # of shape (rows, cols, channels) # map loc latitude to 0-based index latitude_index = min(rows - 1, max(0, (int)(((loc[0] - -90) / (90 - -90)) * (rows - 0) + 0))) longitude_index = min(cols - 1, max(0, (int)(((loc[1] - -180) / (180 - -180)) * (cols - 0) + 0))) # update the location of the next row of elevation data to take loc[0] += delta loc[0] = ((loc[0] + 90) % 180) - 90 # wraps to next pole if overflow print("Lat index: " + str(latitude_index)) print("Lon index: " + str(longitude_index)) print("Next latitude: " + str(loc[0])) # grab the applicable pixel indices indices = [(int)(x*(cols/n_leds)) for x in range(n_leds)] # sample that row of pixel data output_pixels = np.take(a[latitude_index], indices, axis=0) # rotate the row to center around the specified longitude output_pixels = np.roll(output_pixels, longitude_index, axis=0) # send all pixel data to bt for pixel in output_pixels: print("Sending r: {}, g: {}, b: {}".format(*pixel)) bt.sendPixel(*pixel) # finally, show the image bt.show() # delete variables for memory management del a del im # Tape resets to stored pattern after a few seconds of inactivity sleep(rate * 60) # Wait specified number of minutes # sleep(10) # Wait specified number of minutes except KeyboardInterrupt: print("Keyboard interrupt, ending program.") sys.exit() except RuntimeError as e: print("Encountered runtime error: " + e.args[0]) # flush any incomplete data bt.show() num_errors += 1 if num_errors > MAX_ERRORS: sys.exit("Error count exceeds that allowed.")
en
0.649859
This script will modulate the blinky lights using the following algorithm: 1) uses user-provided location to obtain row of pixel data from bathy image 2) samples a 'number of LEDs' number of pixels from that row 3) shifts the sampled row data to center it at the location specified by user 4) displays resulting pixels on Blinky Tape 5) shifts next row by a given latitude, also specified by user 6) sleeps for user-specified period of time Uses the following arguments: -l/--location: tuple Location of the user in tuple(lat, lon). This represents the center of the LED strip. Defaults to (0, 0) -u/--update-interval: int Update interval of the script, in minutes. Defaults to 10. -p/--port: str Serial port of the BlinkyLight (e.g., 'ttyAMA0', 'COM3'). Defaults to 'COM5'. -d/--delta_latitude: int Vertical change in latitude every update rate. May be 0, but this will result in a never-changing LEDs. -i/--image: str Name of the PNG image that contains the color coded pathymetric data. The file current named mapserv.png was obtained using the following API: https://www.gebco.net/data_and_products/gebco_web_services/web_map_service/mapserv?request=getmap&service=wms&BBOX=-90,-180,90,180&format=image/png&height=600&width=1200&crs=EPSG:4326&layers=GEBCO_LATEST_SUB_ICE_TOPO&version=1.3.0 In lieu of providing command line arguments, you may alternatively edit the defaults in bath_config.json. NOTE: runs via: runfile('/BlinkyTape_Python/bathymetry_blink/bathymetry_blink.py', wdir='/BlinkyTape_Python/') (C) 2021 <NAME> (https://joeycodes.dev) MIT Licensed # Obtain default parameters # Default Blinky Tape port on Raspberry Pi is /dev/ttyACM0 # grab the values provided by user (or defaults) # Some visual indication that it works, for headless setups (green tape) # first, load image # Can be many different formats. # of shape (rows, cols, channels) # map loc latitude to 0-based index # update the location of the next row of elevation data to take # wraps to next pole if overflow # grab the applicable pixel indices # sample that row of pixel data # rotate the row to center around the specified longitude # send all pixel data to bt # finally, show the image # delete variables for memory management # Tape resets to stored pattern after a few seconds of inactivity # Wait specified number of minutes # sleep(10) # Wait specified number of minutes # flush any incomplete data
3.177374
3
service/transforms/export_submissions.py
SFDigitalServices/pts-dispatcher-microservice-py
0
62
<filename>service/transforms/export_submissions.py """ Export Submissions Transform module """ #pylint: disable=too-few-public-methods import pandas as pd from .transform import TransformBase from ..resources.field_configs import FieldConfigs from ..resources.field_maps import FieldMaps class ExportSubmissionsTransform(TransformBase): """ Transform for Export Submissions """ def transform(self, data, sep): """ transform submissions from export """ output = list(map(self.get_data, data)) output = list(map(self.pretty_format, output)) output = [i for i in output if i is not None] output = self.normalize(output) output = self.to_csv(output, sep) return output # pylint: disable=R0201 def get_data(self, submission): """ Get data from submission object """ # skip permit type = existingPermitApplication submissions #pylint: disable=too-many-nested-blocks if submission['data']['permitType'] and submission['data']['permitType'] != 'existingPermitApplication': output = {} data = submission['data'] output['id'] = submission['_id'] output['created'] = submission['created'] #pylint: disable=too-many-nested-blocks for key in data: # flatten list values if isinstance(data[key], list): if len(data[key]) > 0: if isinstance(data[key][0], (int, str)): output[key] = ', '.join(map(str, data[key])) else: file_names = [] for index, val in enumerate(data[key]): # if storage, concat filename if 'storage' in val and 'originalName' in val: file_names.append(val['originalName']) else: output[key+str(index+1)] = val if len(file_names) > 0: output[key] = ', '.join(file_names) # flatten multi select values elif isinstance(data[key], dict): # building use code needs manual process if FieldConfigs.is_building_use(key): output[key] = self.convert_building_use(key, data[key], data) # flatten nested address fields elif FieldConfigs.is_nested_address_field(key): output = self.convert_address_fields(key, data[key], output) else: multi_selects = [] for multi_key, multi_value in data[key].items(): if multi_value: multi_selects.append(multi_key) output[key] = ', '.join(multi_selects) else: output[key] = data[key] return output def normalize(self, data): """ Normalize data into a flat structure into DataFrame """ dataframe = pd.json_normalize(data) # update column names dataframe.rename(columns=self.pretty_string, inplace=True) return dataframe def to_csv(self, dataframe, sep=','): """ Return CSV from DataFrame """ return dataframe.to_csv(index=False, sep=sep, line_terminator='\r\n') def pretty_format(self, data): """ Pretty format data fields """ output = {} if data: data = self.set_pts_fields(data) for key in data: if self.datetime_valid(data[key]): output[key] = self.pretty_time(data[key]) else: field_key = FieldConfigs.get_field_key(key, 'map') phone_appnum_key = FieldConfigs.get_field_key(key, 'pretty') if field_key is not None: output[key] = FieldMaps.map_key_value(field_key, data[key]) # manually add Fire Rating and proposed Fire Rating if field_key == 'construction_type' and data[key] != '': output = self.add_fire_rating(key, data[key], output) # format phone numbers and building application number elif phone_appnum_key is not None: if phone_appnum_key == 'phone_fields': output[key] = self.pretty_phonenumber(data[key]) # cleanse characters that break the csv elif isinstance(data[key], (str, bytes)): output[key] = data[key].replace('\n', '\t').replace('|', '') # relabel field, if necessary relabel_field = FieldConfigs.get_relabel_fields(key) if relabel_field: output[relabel_field] = output.pop(key) output = self.reorder_fields(output) return output
<filename>service/transforms/export_submissions.py """ Export Submissions Transform module """ #pylint: disable=too-few-public-methods import pandas as pd from .transform import TransformBase from ..resources.field_configs import FieldConfigs from ..resources.field_maps import FieldMaps class ExportSubmissionsTransform(TransformBase): """ Transform for Export Submissions """ def transform(self, data, sep): """ transform submissions from export """ output = list(map(self.get_data, data)) output = list(map(self.pretty_format, output)) output = [i for i in output if i is not None] output = self.normalize(output) output = self.to_csv(output, sep) return output # pylint: disable=R0201 def get_data(self, submission): """ Get data from submission object """ # skip permit type = existingPermitApplication submissions #pylint: disable=too-many-nested-blocks if submission['data']['permitType'] and submission['data']['permitType'] != 'existingPermitApplication': output = {} data = submission['data'] output['id'] = submission['_id'] output['created'] = submission['created'] #pylint: disable=too-many-nested-blocks for key in data: # flatten list values if isinstance(data[key], list): if len(data[key]) > 0: if isinstance(data[key][0], (int, str)): output[key] = ', '.join(map(str, data[key])) else: file_names = [] for index, val in enumerate(data[key]): # if storage, concat filename if 'storage' in val and 'originalName' in val: file_names.append(val['originalName']) else: output[key+str(index+1)] = val if len(file_names) > 0: output[key] = ', '.join(file_names) # flatten multi select values elif isinstance(data[key], dict): # building use code needs manual process if FieldConfigs.is_building_use(key): output[key] = self.convert_building_use(key, data[key], data) # flatten nested address fields elif FieldConfigs.is_nested_address_field(key): output = self.convert_address_fields(key, data[key], output) else: multi_selects = [] for multi_key, multi_value in data[key].items(): if multi_value: multi_selects.append(multi_key) output[key] = ', '.join(multi_selects) else: output[key] = data[key] return output def normalize(self, data): """ Normalize data into a flat structure into DataFrame """ dataframe = pd.json_normalize(data) # update column names dataframe.rename(columns=self.pretty_string, inplace=True) return dataframe def to_csv(self, dataframe, sep=','): """ Return CSV from DataFrame """ return dataframe.to_csv(index=False, sep=sep, line_terminator='\r\n') def pretty_format(self, data): """ Pretty format data fields """ output = {} if data: data = self.set_pts_fields(data) for key in data: if self.datetime_valid(data[key]): output[key] = self.pretty_time(data[key]) else: field_key = FieldConfigs.get_field_key(key, 'map') phone_appnum_key = FieldConfigs.get_field_key(key, 'pretty') if field_key is not None: output[key] = FieldMaps.map_key_value(field_key, data[key]) # manually add Fire Rating and proposed Fire Rating if field_key == 'construction_type' and data[key] != '': output = self.add_fire_rating(key, data[key], output) # format phone numbers and building application number elif phone_appnum_key is not None: if phone_appnum_key == 'phone_fields': output[key] = self.pretty_phonenumber(data[key]) # cleanse characters that break the csv elif isinstance(data[key], (str, bytes)): output[key] = data[key].replace('\n', '\t').replace('|', '') # relabel field, if necessary relabel_field = FieldConfigs.get_relabel_fields(key) if relabel_field: output[relabel_field] = output.pop(key) output = self.reorder_fields(output) return output
en
0.666707
Export Submissions Transform module #pylint: disable=too-few-public-methods Transform for Export Submissions transform submissions from export # pylint: disable=R0201 Get data from submission object # skip permit type = existingPermitApplication submissions #pylint: disable=too-many-nested-blocks #pylint: disable=too-many-nested-blocks # flatten list values # if storage, concat filename # flatten multi select values # building use code needs manual process # flatten nested address fields Normalize data into a flat structure into DataFrame # update column names Return CSV from DataFrame Pretty format data fields # manually add Fire Rating and proposed Fire Rating # format phone numbers and building application number # cleanse characters that break the csv # relabel field, if necessary
2.487029
2
python/ray/ml/tests/test_torch_trainer.py
mgelbart/ray
22
63
<reponame>mgelbart/ray<gh_stars>10-100 import pytest import torch import ray from ray.ml.predictors.integrations.torch import TorchPredictor from ray.ml.train.integrations.torch import TorchTrainer from ray import train from ray.ml.examples.pytorch.torch_linear_example import train_func as linear_train_func @pytest.fixture def ray_start_4_cpus(): address_info = ray.init(num_cpus=4) yield address_info # The code after the yield will run as teardown code. ray.shutdown() @pytest.mark.parametrize("num_workers", [1, 2]) def test_torch_linear(ray_start_4_cpus, num_workers): def train_func(config): result = linear_train_func(config) assert len(result) == epochs assert result[-1]["loss"] < result[0]["loss"] num_workers = num_workers epochs = 3 scaling_config = {"num_workers": num_workers} config = {"lr": 1e-2, "hidden_size": 1, "batch_size": 4, "epochs": epochs} trainer = TorchTrainer( train_loop_per_worker=train_func, train_loop_config=config, scaling_config=scaling_config, ) trainer.fit() def test_torch_e2e(ray_start_4_cpus): def train_func(): model = torch.nn.Linear(1, 1) train.save_checkpoint(model=model) scaling_config = {"num_workers": 2} trainer = TorchTrainer( train_loop_per_worker=train_func, scaling_config=scaling_config ) result = trainer.fit() predict_dataset = ray.data.range(3) class TorchScorer: def __init__(self): self.pred = TorchPredictor.from_checkpoint(result.checkpoint) def __call__(self, x): return self.pred.predict(x, dtype=torch.float) predictions = predict_dataset.map_batches( TorchScorer, batch_format="pandas", compute="actors" ) assert predictions.count() == 3 def test_torch_e2e_state_dict(ray_start_4_cpus): def train_func(): model = torch.nn.Linear(1, 1).state_dict() train.save_checkpoint(model=model) scaling_config = {"num_workers": 2} trainer = TorchTrainer( train_loop_per_worker=train_func, scaling_config=scaling_config ) result = trainer.fit() # If loading from a state dict, a model definition must be passed in. with pytest.raises(ValueError): TorchPredictor.from_checkpoint(result.checkpoint) class TorchScorer: def __init__(self): self.pred = TorchPredictor.from_checkpoint( result.checkpoint, model=torch.nn.Linear(1, 1) ) def __call__(self, x): return self.pred.predict(x, dtype=torch.float) predict_dataset = ray.data.range(3) predictions = predict_dataset.map_batches( TorchScorer, batch_format="pandas", compute="actors" ) assert predictions.count() == 3 if __name__ == "__main__": import pytest import sys sys.exit(pytest.main(["-v", "-x", __file__]))
import pytest import torch import ray from ray.ml.predictors.integrations.torch import TorchPredictor from ray.ml.train.integrations.torch import TorchTrainer from ray import train from ray.ml.examples.pytorch.torch_linear_example import train_func as linear_train_func @pytest.fixture def ray_start_4_cpus(): address_info = ray.init(num_cpus=4) yield address_info # The code after the yield will run as teardown code. ray.shutdown() @pytest.mark.parametrize("num_workers", [1, 2]) def test_torch_linear(ray_start_4_cpus, num_workers): def train_func(config): result = linear_train_func(config) assert len(result) == epochs assert result[-1]["loss"] < result[0]["loss"] num_workers = num_workers epochs = 3 scaling_config = {"num_workers": num_workers} config = {"lr": 1e-2, "hidden_size": 1, "batch_size": 4, "epochs": epochs} trainer = TorchTrainer( train_loop_per_worker=train_func, train_loop_config=config, scaling_config=scaling_config, ) trainer.fit() def test_torch_e2e(ray_start_4_cpus): def train_func(): model = torch.nn.Linear(1, 1) train.save_checkpoint(model=model) scaling_config = {"num_workers": 2} trainer = TorchTrainer( train_loop_per_worker=train_func, scaling_config=scaling_config ) result = trainer.fit() predict_dataset = ray.data.range(3) class TorchScorer: def __init__(self): self.pred = TorchPredictor.from_checkpoint(result.checkpoint) def __call__(self, x): return self.pred.predict(x, dtype=torch.float) predictions = predict_dataset.map_batches( TorchScorer, batch_format="pandas", compute="actors" ) assert predictions.count() == 3 def test_torch_e2e_state_dict(ray_start_4_cpus): def train_func(): model = torch.nn.Linear(1, 1).state_dict() train.save_checkpoint(model=model) scaling_config = {"num_workers": 2} trainer = TorchTrainer( train_loop_per_worker=train_func, scaling_config=scaling_config ) result = trainer.fit() # If loading from a state dict, a model definition must be passed in. with pytest.raises(ValueError): TorchPredictor.from_checkpoint(result.checkpoint) class TorchScorer: def __init__(self): self.pred = TorchPredictor.from_checkpoint( result.checkpoint, model=torch.nn.Linear(1, 1) ) def __call__(self, x): return self.pred.predict(x, dtype=torch.float) predict_dataset = ray.data.range(3) predictions = predict_dataset.map_batches( TorchScorer, batch_format="pandas", compute="actors" ) assert predictions.count() == 3 if __name__ == "__main__": import pytest import sys sys.exit(pytest.main(["-v", "-x", __file__]))
en
0.908035
# The code after the yield will run as teardown code. # If loading from a state dict, a model definition must be passed in.
2.319725
2
uhd_restpy/testplatform/sessions/ixnetwork/quicktest/learnframes_58e01d83db5d99bcabff902f5cf6ec51.py
OpenIxia/ixnetwork_restpy
20
64
<filename>uhd_restpy/testplatform/sessions/ixnetwork/quicktest/learnframes_58e01d83db5d99bcabff902f5cf6ec51.py # MIT LICENSE # # Copyright 1997 - 2020 by IXIA Keysight # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from uhd_restpy.base import Base from uhd_restpy.files import Files from typing import List, Any, Union class LearnFrames(Base): """The learning frames that IxNetwork sends during the test. The LearnFrames class encapsulates a required learnFrames resource which will be retrieved from the server every time the property is accessed. """ __slots__ = () _SDM_NAME = 'learnFrames' _SDM_ATT_MAP = { 'FastPathEnable': 'fastPathEnable', 'FastPathLearnFrameSize': 'fastPathLearnFrameSize', 'FastPathNumFrames': 'fastPathNumFrames', 'FastPathRate': 'fastPathRate', 'LearnFrameSize': 'learnFrameSize', 'LearnFrequency': 'learnFrequency', 'LearnNumFrames': 'learnNumFrames', 'LearnRate': 'learnRate', 'LearnSendMacOnly': 'learnSendMacOnly', 'LearnSendRouterSolicitation': 'learnSendRouterSolicitation', 'LearnWaitTime': 'learnWaitTime', 'LearnWaitTimeBeforeTransmit': 'learnWaitTimeBeforeTransmit', } _SDM_ENUM_MAP = { 'learnFrequency': ['never', 'onBinaryIteration', 'oncePerFramesize', 'oncePerTest', 'onTrial'], } def __init__(self, parent, list_op=False): super(LearnFrames, self).__init__(parent, list_op) @property def FastPathEnable(self): # type: () -> bool """ Returns ------- - bool: If true, enables fast path transmit. """ return self._get_attribute(self._SDM_ATT_MAP['FastPathEnable']) @FastPathEnable.setter def FastPathEnable(self, value): # type: (bool) -> None self._set_attribute(self._SDM_ATT_MAP['FastPathEnable'], value) @property def FastPathLearnFrameSize(self): # type: () -> int """ Returns ------- - number: Specifies the size of the learning frames in the fast path. """ return self._get_attribute(self._SDM_ATT_MAP['FastPathLearnFrameSize']) @FastPathLearnFrameSize.setter def FastPathLearnFrameSize(self, value): # type: (int) -> None self._set_attribute(self._SDM_ATT_MAP['FastPathLearnFrameSize'], value) @property def FastPathNumFrames(self): # type: () -> int """ Returns ------- - number: Specifies the number of learn frames that IxNetwork sends through fast path. """ return self._get_attribute(self._SDM_ATT_MAP['FastPathNumFrames']) @FastPathNumFrames.setter def FastPathNumFrames(self, value): # type: (int) -> None self._set_attribute(self._SDM_ATT_MAP['FastPathNumFrames'], value) @property def FastPathRate(self): # type: () -> int """ Returns ------- - number: Specifies the rate at which IxNetwork sends learn frames through fast path. """ return self._get_attribute(self._SDM_ATT_MAP['FastPathRate']) @FastPathRate.setter def FastPathRate(self, value): # type: (int) -> None self._set_attribute(self._SDM_ATT_MAP['FastPathRate'], value) @property def LearnFrameSize(self): # type: () -> int """ Returns ------- - number: Specifies the size of the learning frames. """ return self._get_attribute(self._SDM_ATT_MAP['LearnFrameSize']) @LearnFrameSize.setter def LearnFrameSize(self, value): # type: (int) -> None self._set_attribute(self._SDM_ATT_MAP['LearnFrameSize'], value) @property def LearnFrequency(self): # type: () -> str """ Returns ------- - str(never | onBinaryIteration | oncePerFramesize | oncePerTest | onTrial): Allows to choose how frequently IxNetwork sends learning frames during the test. """ return self._get_attribute(self._SDM_ATT_MAP['LearnFrequency']) @LearnFrequency.setter def LearnFrequency(self, value): # type: (str) -> None self._set_attribute(self._SDM_ATT_MAP['LearnFrequency'], value) @property def LearnNumFrames(self): # type: () -> int """ Returns ------- - number: Specifies the number of learning frames that IxNetwork sends for each address. """ return self._get_attribute(self._SDM_ATT_MAP['LearnNumFrames']) @LearnNumFrames.setter def LearnNumFrames(self, value): # type: (int) -> None self._set_attribute(self._SDM_ATT_MAP['LearnNumFrames'], value) @property def LearnRate(self): # type: () -> int """ Returns ------- - number: Specifies the rate at which IxNetwork sends learn frames to the DUT. """ return self._get_attribute(self._SDM_ATT_MAP['LearnRate']) @LearnRate.setter def LearnRate(self, value): # type: (int) -> None self._set_attribute(self._SDM_ATT_MAP['LearnRate'], value) @property def LearnSendMacOnly(self): # type: () -> bool """ Returns ------- - bool: Sends learning frames to MAC address only. """ return self._get_attribute(self._SDM_ATT_MAP['LearnSendMacOnly']) @LearnSendMacOnly.setter def LearnSendMacOnly(self, value): # type: (bool) -> None self._set_attribute(self._SDM_ATT_MAP['LearnSendMacOnly'], value) @property def LearnSendRouterSolicitation(self): # type: () -> bool """ Returns ------- - bool: Sends router solicitation messages. """ return self._get_attribute(self._SDM_ATT_MAP['LearnSendRouterSolicitation']) @LearnSendRouterSolicitation.setter def LearnSendRouterSolicitation(self, value): # type: (bool) -> None self._set_attribute(self._SDM_ATT_MAP['LearnSendRouterSolicitation'], value) @property def LearnWaitTime(self): # type: () -> int """ Returns ------- - number: Specifies the length of time in ms that IxNetwork pauses before sending all the learning frames from all the ports. """ return self._get_attribute(self._SDM_ATT_MAP['LearnWaitTime']) @LearnWaitTime.setter def LearnWaitTime(self, value): # type: (int) -> None self._set_attribute(self._SDM_ATT_MAP['LearnWaitTime'], value) @property def LearnWaitTimeBeforeTransmit(self): # type: () -> int """ Returns ------- - number: Specifies the length of time in ms that IxNetwork pauses before sending all the """ return self._get_attribute(self._SDM_ATT_MAP['LearnWaitTimeBeforeTransmit']) @LearnWaitTimeBeforeTransmit.setter def LearnWaitTimeBeforeTransmit(self, value): # type: (int) -> None self._set_attribute(self._SDM_ATT_MAP['LearnWaitTimeBeforeTransmit'], value) def update(self, FastPathEnable=None, FastPathLearnFrameSize=None, FastPathNumFrames=None, FastPathRate=None, LearnFrameSize=None, LearnFrequency=None, LearnNumFrames=None, LearnRate=None, LearnSendMacOnly=None, LearnSendRouterSolicitation=None, LearnWaitTime=None, LearnWaitTimeBeforeTransmit=None): # type: (bool, int, int, int, int, str, int, int, bool, bool, int, int) -> LearnFrames """Updates learnFrames resource on the server. Args ---- - FastPathEnable (bool): If true, enables fast path transmit. - FastPathLearnFrameSize (number): Specifies the size of the learning frames in the fast path. - FastPathNumFrames (number): Specifies the number of learn frames that IxNetwork sends through fast path. - FastPathRate (number): Specifies the rate at which IxNetwork sends learn frames through fast path. - LearnFrameSize (number): Specifies the size of the learning frames. - LearnFrequency (str(never | onBinaryIteration | oncePerFramesize | oncePerTest | onTrial)): Allows to choose how frequently IxNetwork sends learning frames during the test. - LearnNumFrames (number): Specifies the number of learning frames that IxNetwork sends for each address. - LearnRate (number): Specifies the rate at which IxNetwork sends learn frames to the DUT. - LearnSendMacOnly (bool): Sends learning frames to MAC address only. - LearnSendRouterSolicitation (bool): Sends router solicitation messages. - LearnWaitTime (number): Specifies the length of time in ms that IxNetwork pauses before sending all the learning frames from all the ports. - LearnWaitTimeBeforeTransmit (number): Specifies the length of time in ms that IxNetwork pauses before sending all the Raises ------ - ServerError: The server has encountered an uncategorized error condition """ return self._update(self._map_locals(self._SDM_ATT_MAP, locals())) def Apply(self, *args, **kwargs): # type: (*Any, **Any) -> None """Executes the apply operation on the server. Applies the specified Quick Test. apply(async_operation=bool) --------------------------- - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('apply', payload=payload, response_object=None) def ApplyAsync(self, *args, **kwargs): # type: (*Any, **Any) -> None """Executes the applyAsync operation on the server. applyAsync(async_operation=bool) -------------------------------- - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('applyAsync', payload=payload, response_object=None) def ApplyAsyncResult(self, *args, **kwargs): # type: (*Any, **Any) -> Union[bool, None] """Executes the applyAsyncResult operation on the server. applyAsyncResult(async_operation=bool)bool ------------------------------------------ - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. - Returns bool: Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('applyAsyncResult', payload=payload, response_object=None) def ApplyITWizardConfiguration(self, *args, **kwargs): # type: (*Any, **Any) -> None """Executes the applyITWizardConfiguration operation on the server. Applies the specified Quick Test. applyITWizardConfiguration(async_operation=bool) ------------------------------------------------ - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('applyITWizardConfiguration', payload=payload, response_object=None) def GenerateReport(self, *args, **kwargs): # type: (*Any, **Any) -> Union[str, None] """Executes the generateReport operation on the server. Generate a PDF report for the last succesfull test run. generateReport(async_operation=bool)string ------------------------------------------ - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. - Returns str: This method is asynchronous and has no return value. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('generateReport', payload=payload, response_object=None) def Run(self, *args, **kwargs): # type: (*Any, **Any) -> Union[List[str], None] """Executes the run operation on the server. Starts the specified Quick Test and waits for its execution to finish. The IxNetwork model allows for multiple method Signatures with the same name while python does not. run(async_operation=bool)list ----------------------------- - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. - Returns list(str): This method is synchronous and returns the result of the test. run(InputParameters=string, async_operation=bool)list ----------------------------------------------------- - InputParameters (str): The input arguments of the test. - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. - Returns list(str): This method is synchronous and returns the result of the test. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('run', payload=payload, response_object=None) def Start(self, *args, **kwargs): # type: (*Any, **Any) -> None """Executes the start operation on the server. Starts the specified Quick Test. The IxNetwork model allows for multiple method Signatures with the same name while python does not. start(async_operation=bool) --------------------------- - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. start(InputParameters=string, async_operation=bool) --------------------------------------------------- - InputParameters (str): The input arguments of the test. - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('start', payload=payload, response_object=None) def Stop(self, *args, **kwargs): # type: (*Any, **Any) -> None """Executes the stop operation on the server. Stops the currently running Quick Test. stop(async_operation=bool) -------------------------- - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('stop', payload=payload, response_object=None) def WaitForTest(self, *args, **kwargs): # type: (*Any, **Any) -> Union[List[str], None] """Executes the waitForTest operation on the server. Waits for the execution of the specified Quick Test to be completed. waitForTest(async_operation=bool)list ------------------------------------- - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. - Returns list(str): This method is synchronous and returns the result of the test. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('waitForTest', payload=payload, response_object=None)
<filename>uhd_restpy/testplatform/sessions/ixnetwork/quicktest/learnframes_58e01d83db5d99bcabff902f5cf6ec51.py # MIT LICENSE # # Copyright 1997 - 2020 by IXIA Keysight # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. from uhd_restpy.base import Base from uhd_restpy.files import Files from typing import List, Any, Union class LearnFrames(Base): """The learning frames that IxNetwork sends during the test. The LearnFrames class encapsulates a required learnFrames resource which will be retrieved from the server every time the property is accessed. """ __slots__ = () _SDM_NAME = 'learnFrames' _SDM_ATT_MAP = { 'FastPathEnable': 'fastPathEnable', 'FastPathLearnFrameSize': 'fastPathLearnFrameSize', 'FastPathNumFrames': 'fastPathNumFrames', 'FastPathRate': 'fastPathRate', 'LearnFrameSize': 'learnFrameSize', 'LearnFrequency': 'learnFrequency', 'LearnNumFrames': 'learnNumFrames', 'LearnRate': 'learnRate', 'LearnSendMacOnly': 'learnSendMacOnly', 'LearnSendRouterSolicitation': 'learnSendRouterSolicitation', 'LearnWaitTime': 'learnWaitTime', 'LearnWaitTimeBeforeTransmit': 'learnWaitTimeBeforeTransmit', } _SDM_ENUM_MAP = { 'learnFrequency': ['never', 'onBinaryIteration', 'oncePerFramesize', 'oncePerTest', 'onTrial'], } def __init__(self, parent, list_op=False): super(LearnFrames, self).__init__(parent, list_op) @property def FastPathEnable(self): # type: () -> bool """ Returns ------- - bool: If true, enables fast path transmit. """ return self._get_attribute(self._SDM_ATT_MAP['FastPathEnable']) @FastPathEnable.setter def FastPathEnable(self, value): # type: (bool) -> None self._set_attribute(self._SDM_ATT_MAP['FastPathEnable'], value) @property def FastPathLearnFrameSize(self): # type: () -> int """ Returns ------- - number: Specifies the size of the learning frames in the fast path. """ return self._get_attribute(self._SDM_ATT_MAP['FastPathLearnFrameSize']) @FastPathLearnFrameSize.setter def FastPathLearnFrameSize(self, value): # type: (int) -> None self._set_attribute(self._SDM_ATT_MAP['FastPathLearnFrameSize'], value) @property def FastPathNumFrames(self): # type: () -> int """ Returns ------- - number: Specifies the number of learn frames that IxNetwork sends through fast path. """ return self._get_attribute(self._SDM_ATT_MAP['FastPathNumFrames']) @FastPathNumFrames.setter def FastPathNumFrames(self, value): # type: (int) -> None self._set_attribute(self._SDM_ATT_MAP['FastPathNumFrames'], value) @property def FastPathRate(self): # type: () -> int """ Returns ------- - number: Specifies the rate at which IxNetwork sends learn frames through fast path. """ return self._get_attribute(self._SDM_ATT_MAP['FastPathRate']) @FastPathRate.setter def FastPathRate(self, value): # type: (int) -> None self._set_attribute(self._SDM_ATT_MAP['FastPathRate'], value) @property def LearnFrameSize(self): # type: () -> int """ Returns ------- - number: Specifies the size of the learning frames. """ return self._get_attribute(self._SDM_ATT_MAP['LearnFrameSize']) @LearnFrameSize.setter def LearnFrameSize(self, value): # type: (int) -> None self._set_attribute(self._SDM_ATT_MAP['LearnFrameSize'], value) @property def LearnFrequency(self): # type: () -> str """ Returns ------- - str(never | onBinaryIteration | oncePerFramesize | oncePerTest | onTrial): Allows to choose how frequently IxNetwork sends learning frames during the test. """ return self._get_attribute(self._SDM_ATT_MAP['LearnFrequency']) @LearnFrequency.setter def LearnFrequency(self, value): # type: (str) -> None self._set_attribute(self._SDM_ATT_MAP['LearnFrequency'], value) @property def LearnNumFrames(self): # type: () -> int """ Returns ------- - number: Specifies the number of learning frames that IxNetwork sends for each address. """ return self._get_attribute(self._SDM_ATT_MAP['LearnNumFrames']) @LearnNumFrames.setter def LearnNumFrames(self, value): # type: (int) -> None self._set_attribute(self._SDM_ATT_MAP['LearnNumFrames'], value) @property def LearnRate(self): # type: () -> int """ Returns ------- - number: Specifies the rate at which IxNetwork sends learn frames to the DUT. """ return self._get_attribute(self._SDM_ATT_MAP['LearnRate']) @LearnRate.setter def LearnRate(self, value): # type: (int) -> None self._set_attribute(self._SDM_ATT_MAP['LearnRate'], value) @property def LearnSendMacOnly(self): # type: () -> bool """ Returns ------- - bool: Sends learning frames to MAC address only. """ return self._get_attribute(self._SDM_ATT_MAP['LearnSendMacOnly']) @LearnSendMacOnly.setter def LearnSendMacOnly(self, value): # type: (bool) -> None self._set_attribute(self._SDM_ATT_MAP['LearnSendMacOnly'], value) @property def LearnSendRouterSolicitation(self): # type: () -> bool """ Returns ------- - bool: Sends router solicitation messages. """ return self._get_attribute(self._SDM_ATT_MAP['LearnSendRouterSolicitation']) @LearnSendRouterSolicitation.setter def LearnSendRouterSolicitation(self, value): # type: (bool) -> None self._set_attribute(self._SDM_ATT_MAP['LearnSendRouterSolicitation'], value) @property def LearnWaitTime(self): # type: () -> int """ Returns ------- - number: Specifies the length of time in ms that IxNetwork pauses before sending all the learning frames from all the ports. """ return self._get_attribute(self._SDM_ATT_MAP['LearnWaitTime']) @LearnWaitTime.setter def LearnWaitTime(self, value): # type: (int) -> None self._set_attribute(self._SDM_ATT_MAP['LearnWaitTime'], value) @property def LearnWaitTimeBeforeTransmit(self): # type: () -> int """ Returns ------- - number: Specifies the length of time in ms that IxNetwork pauses before sending all the """ return self._get_attribute(self._SDM_ATT_MAP['LearnWaitTimeBeforeTransmit']) @LearnWaitTimeBeforeTransmit.setter def LearnWaitTimeBeforeTransmit(self, value): # type: (int) -> None self._set_attribute(self._SDM_ATT_MAP['LearnWaitTimeBeforeTransmit'], value) def update(self, FastPathEnable=None, FastPathLearnFrameSize=None, FastPathNumFrames=None, FastPathRate=None, LearnFrameSize=None, LearnFrequency=None, LearnNumFrames=None, LearnRate=None, LearnSendMacOnly=None, LearnSendRouterSolicitation=None, LearnWaitTime=None, LearnWaitTimeBeforeTransmit=None): # type: (bool, int, int, int, int, str, int, int, bool, bool, int, int) -> LearnFrames """Updates learnFrames resource on the server. Args ---- - FastPathEnable (bool): If true, enables fast path transmit. - FastPathLearnFrameSize (number): Specifies the size of the learning frames in the fast path. - FastPathNumFrames (number): Specifies the number of learn frames that IxNetwork sends through fast path. - FastPathRate (number): Specifies the rate at which IxNetwork sends learn frames through fast path. - LearnFrameSize (number): Specifies the size of the learning frames. - LearnFrequency (str(never | onBinaryIteration | oncePerFramesize | oncePerTest | onTrial)): Allows to choose how frequently IxNetwork sends learning frames during the test. - LearnNumFrames (number): Specifies the number of learning frames that IxNetwork sends for each address. - LearnRate (number): Specifies the rate at which IxNetwork sends learn frames to the DUT. - LearnSendMacOnly (bool): Sends learning frames to MAC address only. - LearnSendRouterSolicitation (bool): Sends router solicitation messages. - LearnWaitTime (number): Specifies the length of time in ms that IxNetwork pauses before sending all the learning frames from all the ports. - LearnWaitTimeBeforeTransmit (number): Specifies the length of time in ms that IxNetwork pauses before sending all the Raises ------ - ServerError: The server has encountered an uncategorized error condition """ return self._update(self._map_locals(self._SDM_ATT_MAP, locals())) def Apply(self, *args, **kwargs): # type: (*Any, **Any) -> None """Executes the apply operation on the server. Applies the specified Quick Test. apply(async_operation=bool) --------------------------- - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('apply', payload=payload, response_object=None) def ApplyAsync(self, *args, **kwargs): # type: (*Any, **Any) -> None """Executes the applyAsync operation on the server. applyAsync(async_operation=bool) -------------------------------- - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('applyAsync', payload=payload, response_object=None) def ApplyAsyncResult(self, *args, **kwargs): # type: (*Any, **Any) -> Union[bool, None] """Executes the applyAsyncResult operation on the server. applyAsyncResult(async_operation=bool)bool ------------------------------------------ - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. - Returns bool: Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('applyAsyncResult', payload=payload, response_object=None) def ApplyITWizardConfiguration(self, *args, **kwargs): # type: (*Any, **Any) -> None """Executes the applyITWizardConfiguration operation on the server. Applies the specified Quick Test. applyITWizardConfiguration(async_operation=bool) ------------------------------------------------ - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('applyITWizardConfiguration', payload=payload, response_object=None) def GenerateReport(self, *args, **kwargs): # type: (*Any, **Any) -> Union[str, None] """Executes the generateReport operation on the server. Generate a PDF report for the last succesfull test run. generateReport(async_operation=bool)string ------------------------------------------ - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. - Returns str: This method is asynchronous and has no return value. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('generateReport', payload=payload, response_object=None) def Run(self, *args, **kwargs): # type: (*Any, **Any) -> Union[List[str], None] """Executes the run operation on the server. Starts the specified Quick Test and waits for its execution to finish. The IxNetwork model allows for multiple method Signatures with the same name while python does not. run(async_operation=bool)list ----------------------------- - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. - Returns list(str): This method is synchronous and returns the result of the test. run(InputParameters=string, async_operation=bool)list ----------------------------------------------------- - InputParameters (str): The input arguments of the test. - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. - Returns list(str): This method is synchronous and returns the result of the test. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('run', payload=payload, response_object=None) def Start(self, *args, **kwargs): # type: (*Any, **Any) -> None """Executes the start operation on the server. Starts the specified Quick Test. The IxNetwork model allows for multiple method Signatures with the same name while python does not. start(async_operation=bool) --------------------------- - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. start(InputParameters=string, async_operation=bool) --------------------------------------------------- - InputParameters (str): The input arguments of the test. - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('start', payload=payload, response_object=None) def Stop(self, *args, **kwargs): # type: (*Any, **Any) -> None """Executes the stop operation on the server. Stops the currently running Quick Test. stop(async_operation=bool) -------------------------- - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('stop', payload=payload, response_object=None) def WaitForTest(self, *args, **kwargs): # type: (*Any, **Any) -> Union[List[str], None] """Executes the waitForTest operation on the server. Waits for the execution of the specified Quick Test to be completed. waitForTest(async_operation=bool)list ------------------------------------- - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. - Returns list(str): This method is synchronous and returns the result of the test. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition """ payload = { "Arg1": self.href } for i in range(len(args)): payload['Arg%s' % (i + 2)] = args[i] for item in kwargs.items(): payload[item[0]] = item[1] return self._execute('waitForTest', payload=payload, response_object=None)
en
0.765421
# MIT LICENSE # # Copyright 1997 - 2020 by IXIA Keysight # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. The learning frames that IxNetwork sends during the test. The LearnFrames class encapsulates a required learnFrames resource which will be retrieved from the server every time the property is accessed. # type: () -> bool Returns ------- - bool: If true, enables fast path transmit. # type: (bool) -> None # type: () -> int Returns ------- - number: Specifies the size of the learning frames in the fast path. # type: (int) -> None # type: () -> int Returns ------- - number: Specifies the number of learn frames that IxNetwork sends through fast path. # type: (int) -> None # type: () -> int Returns ------- - number: Specifies the rate at which IxNetwork sends learn frames through fast path. # type: (int) -> None # type: () -> int Returns ------- - number: Specifies the size of the learning frames. # type: (int) -> None # type: () -> str Returns ------- - str(never | onBinaryIteration | oncePerFramesize | oncePerTest | onTrial): Allows to choose how frequently IxNetwork sends learning frames during the test. # type: (str) -> None # type: () -> int Returns ------- - number: Specifies the number of learning frames that IxNetwork sends for each address. # type: (int) -> None # type: () -> int Returns ------- - number: Specifies the rate at which IxNetwork sends learn frames to the DUT. # type: (int) -> None # type: () -> bool Returns ------- - bool: Sends learning frames to MAC address only. # type: (bool) -> None # type: () -> bool Returns ------- - bool: Sends router solicitation messages. # type: (bool) -> None # type: () -> int Returns ------- - number: Specifies the length of time in ms that IxNetwork pauses before sending all the learning frames from all the ports. # type: (int) -> None # type: () -> int Returns ------- - number: Specifies the length of time in ms that IxNetwork pauses before sending all the # type: (int) -> None # type: (bool, int, int, int, int, str, int, int, bool, bool, int, int) -> LearnFrames Updates learnFrames resource on the server. Args ---- - FastPathEnable (bool): If true, enables fast path transmit. - FastPathLearnFrameSize (number): Specifies the size of the learning frames in the fast path. - FastPathNumFrames (number): Specifies the number of learn frames that IxNetwork sends through fast path. - FastPathRate (number): Specifies the rate at which IxNetwork sends learn frames through fast path. - LearnFrameSize (number): Specifies the size of the learning frames. - LearnFrequency (str(never | onBinaryIteration | oncePerFramesize | oncePerTest | onTrial)): Allows to choose how frequently IxNetwork sends learning frames during the test. - LearnNumFrames (number): Specifies the number of learning frames that IxNetwork sends for each address. - LearnRate (number): Specifies the rate at which IxNetwork sends learn frames to the DUT. - LearnSendMacOnly (bool): Sends learning frames to MAC address only. - LearnSendRouterSolicitation (bool): Sends router solicitation messages. - LearnWaitTime (number): Specifies the length of time in ms that IxNetwork pauses before sending all the learning frames from all the ports. - LearnWaitTimeBeforeTransmit (number): Specifies the length of time in ms that IxNetwork pauses before sending all the Raises ------ - ServerError: The server has encountered an uncategorized error condition # type: (*Any, **Any) -> None Executes the apply operation on the server. Applies the specified Quick Test. apply(async_operation=bool) --------------------------- - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition # type: (*Any, **Any) -> None Executes the applyAsync operation on the server. applyAsync(async_operation=bool) -------------------------------- - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition # type: (*Any, **Any) -> Union[bool, None] Executes the applyAsyncResult operation on the server. applyAsyncResult(async_operation=bool)bool ------------------------------------------ - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. - Returns bool: Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition # type: (*Any, **Any) -> None Executes the applyITWizardConfiguration operation on the server. Applies the specified Quick Test. applyITWizardConfiguration(async_operation=bool) ------------------------------------------------ - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition # type: (*Any, **Any) -> Union[str, None] Executes the generateReport operation on the server. Generate a PDF report for the last succesfull test run. generateReport(async_operation=bool)string ------------------------------------------ - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. - Returns str: This method is asynchronous and has no return value. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition # type: (*Any, **Any) -> Union[List[str], None] Executes the run operation on the server. Starts the specified Quick Test and waits for its execution to finish. The IxNetwork model allows for multiple method Signatures with the same name while python does not. run(async_operation=bool)list ----------------------------- - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. - Returns list(str): This method is synchronous and returns the result of the test. run(InputParameters=string, async_operation=bool)list ----------------------------------------------------- - InputParameters (str): The input arguments of the test. - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. - Returns list(str): This method is synchronous and returns the result of the test. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition # type: (*Any, **Any) -> None Executes the start operation on the server. Starts the specified Quick Test. The IxNetwork model allows for multiple method Signatures with the same name while python does not. start(async_operation=bool) --------------------------- - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. start(InputParameters=string, async_operation=bool) --------------------------------------------------- - InputParameters (str): The input arguments of the test. - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition # type: (*Any, **Any) -> None Executes the stop operation on the server. Stops the currently running Quick Test. stop(async_operation=bool) -------------------------- - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition # type: (*Any, **Any) -> Union[List[str], None] Executes the waitForTest operation on the server. Waits for the execution of the specified Quick Test to be completed. waitForTest(async_operation=bool)list ------------------------------------- - async_operation (bool=False): True to execute the operation asynchronously. Any subsequent rest api calls made through the Connection class will block until the operation is complete. - Returns list(str): This method is synchronous and returns the result of the test. Raises ------ - NotFoundError: The requested resource does not exist on the server - ServerError: The server has encountered an uncategorized error condition
1.622468
2
core/serializers.py
telminov/sonm-cdn-cms
1
65
from rest_framework import serializers from core import models class AssetSerializer(serializers.ModelSerializer): class Meta: model = models.Asset fields = '__all__'
from rest_framework import serializers from core import models class AssetSerializer(serializers.ModelSerializer): class Meta: model = models.Asset fields = '__all__'
none
1
1.713569
2
tests/wasp1/AllAnswerSets/aggregates_count_boundvariables_1.test.py
bernardocuteri/wasp
19
66
<filename>tests/wasp1/AllAnswerSets/aggregates_count_boundvariables_1.test.py input = """ c(2). p(1). a(2). d(2,2,1). okay(X):- c(X), #count{V:a(V),d(V,X,1)} = 1. ouch(X):- p(X), #count{V:a(V),d(V,X,1)} = 1. """ output = """ {a(2), c(2), d(2,2,1), okay(2), p(1)} """
<filename>tests/wasp1/AllAnswerSets/aggregates_count_boundvariables_1.test.py input = """ c(2). p(1). a(2). d(2,2,1). okay(X):- c(X), #count{V:a(V),d(V,X,1)} = 1. ouch(X):- p(X), #count{V:a(V),d(V,X,1)} = 1. """ output = """ {a(2), c(2), d(2,2,1), okay(2), p(1)} """
en
0.289431
c(2). p(1). a(2). d(2,2,1). okay(X):- c(X), #count{V:a(V),d(V,X,1)} = 1. ouch(X):- p(X), #count{V:a(V),d(V,X,1)} = 1. {a(2), c(2), d(2,2,1), okay(2), p(1)}
2.033683
2
Pzzzzz/plugins/wm.py
Pzzzzz5142/animal-forest-QQ-group-bot
5
67
<filename>Pzzzzz/plugins/wm.py from nonebot import CommandSession, on_command from langdetect import detect, detect_langs from aiohttp import ClientSession from nonebot import get_bot from nonebot.argparse import ArgumentParser import time import hmac import random, sys import hashlib import binascii import urllib bot = get_bot() # 百度通用翻译API,不包含词典、tts语音合成等资源,如有相关需求请联系<EMAIL> # coding=utf-8 import hashlib import urllib import random @on_command("wm", aliases={"翻译", "translate"}, only_to_me=False) async def wm(session: CommandSession): session.get("token", prompt="请输入你想翻译的句子!") myurl = "/api/trans/vip/translate" q = session.state["token"] fromLang = session.state["fr"] # 原文语种 toLang = session.state["to"] # 译文语种 salt = random.randint(32768, 65536) sign = bot.config.BAIDUAPI + q + str(salt) + bot.config.BAIDUKey sign = hashlib.md5(sign.encode()).hexdigest() myurl = ( myurl + "?appid=" + bot.config.BAIDUAPI + "&q=" + urllib.parse.quote(q) + "&from=" + fromLang + "&to=" + toLang + "&salt=" + str(salt) + "&sign=" + sign ) async with ClientSession() as sess: async with sess.get("https://fanyi-api.baidu.com" + myurl) as resp: if resp.status != 200: pass ShitAns = await resp.json() try: ans = [i["dst"] for i in ShitAns["trans_result"]] ans = "\n".join(ans) except: session.finish("翻译错误,原因是:" + ShitAns["error_code"]) session.finish("翻译结果为:\n" + ans) @wm.args_parser async def _(session: CommandSession): arg = session.current_arg_text.strip() if session.is_first_run: parser = ArgumentParser(session=session) parser.add_argument("--fr", "-f", type=str, default="no") parser.add_argument("--to", "-t", type=str, default="no") parser.add_argument("token", type=str, default="", nargs="+") argv = parser.parse_args(session.current_arg.split(" ")) arg = " ".join(argv.token) if arg == "": session.pause("输入不能为空哦!") session.state["fr"] = detect(arg) if argv.fr == "no" else argv.fr if session.state["fr"][:2] == "zh": session.state["fr"] = "zh" if argv.to == "no": if session.state["fr"] == "zh": session.state["to"] = "en" else: session.state["to"] = "zh" else: session.state["to"] = argv.to if argv.fr == "no": session.state["fr"] = "auto" session.state["token"] = arg
<filename>Pzzzzz/plugins/wm.py from nonebot import CommandSession, on_command from langdetect import detect, detect_langs from aiohttp import ClientSession from nonebot import get_bot from nonebot.argparse import ArgumentParser import time import hmac import random, sys import hashlib import binascii import urllib bot = get_bot() # 百度通用翻译API,不包含词典、tts语音合成等资源,如有相关需求请联系<EMAIL> # coding=utf-8 import hashlib import urllib import random @on_command("wm", aliases={"翻译", "translate"}, only_to_me=False) async def wm(session: CommandSession): session.get("token", prompt="请输入你想翻译的句子!") myurl = "/api/trans/vip/translate" q = session.state["token"] fromLang = session.state["fr"] # 原文语种 toLang = session.state["to"] # 译文语种 salt = random.randint(32768, 65536) sign = bot.config.BAIDUAPI + q + str(salt) + bot.config.BAIDUKey sign = hashlib.md5(sign.encode()).hexdigest() myurl = ( myurl + "?appid=" + bot.config.BAIDUAPI + "&q=" + urllib.parse.quote(q) + "&from=" + fromLang + "&to=" + toLang + "&salt=" + str(salt) + "&sign=" + sign ) async with ClientSession() as sess: async with sess.get("https://fanyi-api.baidu.com" + myurl) as resp: if resp.status != 200: pass ShitAns = await resp.json() try: ans = [i["dst"] for i in ShitAns["trans_result"]] ans = "\n".join(ans) except: session.finish("翻译错误,原因是:" + ShitAns["error_code"]) session.finish("翻译结果为:\n" + ans) @wm.args_parser async def _(session: CommandSession): arg = session.current_arg_text.strip() if session.is_first_run: parser = ArgumentParser(session=session) parser.add_argument("--fr", "-f", type=str, default="no") parser.add_argument("--to", "-t", type=str, default="no") parser.add_argument("token", type=str, default="", nargs="+") argv = parser.parse_args(session.current_arg.split(" ")) arg = " ".join(argv.token) if arg == "": session.pause("输入不能为空哦!") session.state["fr"] = detect(arg) if argv.fr == "no" else argv.fr if session.state["fr"][:2] == "zh": session.state["fr"] = "zh" if argv.to == "no": if session.state["fr"] == "zh": session.state["to"] = "en" else: session.state["to"] = "zh" else: session.state["to"] = argv.to if argv.fr == "no": session.state["fr"] = "auto" session.state["token"] = arg
zh
0.835842
# 百度通用翻译API,不包含词典、tts语音合成等资源,如有相关需求请联系<EMAIL> # coding=utf-8 # 原文语种 # 译文语种
2.207566
2
home/scripts/memory/lpsolve.py
ParksProjets/Mips-Applications
1
68
<filename>home/scripts/memory/lpsolve.py """ LpSolve wrapper. Copyright (C) 2018, <NAME> License MIT """ from ctypes import * import sys import os.path as path import platform # Import the DLL ver = ("x86", "x64")[sys.maxsize > 2**32] here = path.dirname(__file__) if sys.platform == "win32": lib = windll.LoadLibrary(path.abspath(path.join(here, "dll/lpsolve55-%s.dll" % ver))) elif sys.platform == "linux": lib = cdll.LoadLibrary(path.abspath(path.join(here, "dll/lpsolve55-%s.so" % ver))) else: raise ValueError("Can't load LpSolve library on this platform.") # Make the bindings c_double_p = POINTER(c_double) c_int_p = POINTER(c_int) lib.make_lp.argtypes = [c_int, c_int] lib.make_lp.restype = c_void_p lib.delete_lp.argtypes = [c_void_p] lib.set_binary.argtypes = [c_void_p, c_int, c_ubyte] lib.set_binary.restype = c_ubyte lib.set_int.argtypes = [c_void_p, c_int, c_ubyte] lib.set_int.restype = c_ubyte lib.add_constraintex.argtypes = [c_void_p, c_int, c_double_p, c_int_p, c_int, c_double] lib.add_constraintex.restype = c_ubyte lib.set_obj_fnex.argtypes = [c_void_p, c_int, c_double_p, c_int_p] lib.set_obj_fnex.restype = c_ubyte lib.set_add_rowmode.argtypes = [c_void_p, c_ubyte] lib.set_add_rowmode.restype = c_ubyte lib.set_maxim.argtypes = [c_void_p] lib.write_lp.argtypes = [c_void_p, c_char_p] lib.write_lp.restype = c_ubyte lib.set_verbose.argtypes = [c_void_p, c_int] lib.solve.argtypes = [c_void_p] lib.solve.restype = c_int lib.get_variables.argtypes = [c_void_p, c_double_p] lib.get_variables.restype = c_ubyte class LpEngine(object): "The Linear Programming Engine." def __init__(self, maxvars, debug=False): self.debug = debug self.maxvars = maxvars self.vars = [] self.lp = lib.make_lp(0, maxvars) assert self.lp != 0, "Can't construct a new LpSolve model" self.colbuff = (c_int * maxvars)() self.rowbuff = (c_double * maxvars)() lib.set_add_rowmode(self.lp, 1) def __del__(self): lib.delete_lp(self.lp) def constraint(self, const): "Add a new constraint into the model." assert const.optype is not None, "You must provide the RHS of constraint" const.fill_buffers(self.colbuff, self.rowbuff) ret = lib.add_constraintex(self.lp, len(const.vars), cast(self.rowbuff, c_double_p), cast(self.colbuff, c_int_p), const.optype, const.rhs) assert ret == 1, "Can't add constraint into model" def objective(self, const): "Set the objective function." lib.set_add_rowmode(self.lp, 0) const.fill_buffers(self.colbuff, self.rowbuff) ret = lib.set_obj_fnex(self.lp, len(const.vars), cast(self.rowbuff, c_double_p), cast(self.colbuff, c_int_p)) assert ret == 1, "Can't set objective function of model" def update_variables(self): "Update the variable values." ret = lib.get_variables(self.lp, cast(self.rowbuff, c_double_p)) assert ret == 1, "Can't get variable values" for i, var in enumerate(self.vars): var.value = self.rowbuff[i] def solve(self): "Solve the model." lib.set_maxim(self.lp) if self.debug: lib.write_lp(self.lp, b"debug-model.lp") else: lib.set_verbose(self.lp, 3) ret = lib.solve(self.lp) if ret == 0 or ret == 1: self.update_variables() return ret class LpVariable(object): "A LpSolve variable." def __init__(self, lp, vtype="real"): assert len(lp.vars) < lp.maxvars, "Can't add a variable: " self.index = len(lp.vars) + 1 self.value = None self.lp = lp lp.vars.append(self) self.type = "real" self.retype(vtype) def retype(self, vtype): "Change the type of the variable" if "bin" in (self.type, vtype): lib.set_binary(self.lp.lp, self.index, (vtype == "bin")) elif "int" in (self.type, vtype): lib.set_binary(self.lp.lp, self.index, (vtype == "int")) def __rmul__(self, num): return LpConstraint([num], [self]) def __add__(self, other): if isinstance(other, LpConstraint): return other.__add__(self) return LpConstraint([1, 1], [self, other]) class LpConstraint(object): "A LpSolve constraint." def __init__(self, numbers, vars): self.numbers = numbers self.vars = vars self.optype = None self.rhs = None def fill_buffers(self, colno, row): "Fill colno and row buffers for calling LpSolve." for i, (num, var) in enumerate(zip(self.numbers, self.vars)): colno[i] = var.index row[i] = num def __add__(self, other): if isinstance(other, LpVariable): return LpConstraint(self.numbers + [1], self.vars + [other]) else: c = LpConstraint(self.numbers + other.numbers, self.vars + other.vars) assert len(c.vars) == len(set(c.vars)), "Some variables appear several times" return c def __le__(self, val): self.optype, self.rhs = (1, val) return self def __eq__(self, val): self.optype, self.rhs = (3, val) return self def __ge__(self, val): self.optype, self.rhs = (2, val) return self
<filename>home/scripts/memory/lpsolve.py """ LpSolve wrapper. Copyright (C) 2018, <NAME> License MIT """ from ctypes import * import sys import os.path as path import platform # Import the DLL ver = ("x86", "x64")[sys.maxsize > 2**32] here = path.dirname(__file__) if sys.platform == "win32": lib = windll.LoadLibrary(path.abspath(path.join(here, "dll/lpsolve55-%s.dll" % ver))) elif sys.platform == "linux": lib = cdll.LoadLibrary(path.abspath(path.join(here, "dll/lpsolve55-%s.so" % ver))) else: raise ValueError("Can't load LpSolve library on this platform.") # Make the bindings c_double_p = POINTER(c_double) c_int_p = POINTER(c_int) lib.make_lp.argtypes = [c_int, c_int] lib.make_lp.restype = c_void_p lib.delete_lp.argtypes = [c_void_p] lib.set_binary.argtypes = [c_void_p, c_int, c_ubyte] lib.set_binary.restype = c_ubyte lib.set_int.argtypes = [c_void_p, c_int, c_ubyte] lib.set_int.restype = c_ubyte lib.add_constraintex.argtypes = [c_void_p, c_int, c_double_p, c_int_p, c_int, c_double] lib.add_constraintex.restype = c_ubyte lib.set_obj_fnex.argtypes = [c_void_p, c_int, c_double_p, c_int_p] lib.set_obj_fnex.restype = c_ubyte lib.set_add_rowmode.argtypes = [c_void_p, c_ubyte] lib.set_add_rowmode.restype = c_ubyte lib.set_maxim.argtypes = [c_void_p] lib.write_lp.argtypes = [c_void_p, c_char_p] lib.write_lp.restype = c_ubyte lib.set_verbose.argtypes = [c_void_p, c_int] lib.solve.argtypes = [c_void_p] lib.solve.restype = c_int lib.get_variables.argtypes = [c_void_p, c_double_p] lib.get_variables.restype = c_ubyte class LpEngine(object): "The Linear Programming Engine." def __init__(self, maxvars, debug=False): self.debug = debug self.maxvars = maxvars self.vars = [] self.lp = lib.make_lp(0, maxvars) assert self.lp != 0, "Can't construct a new LpSolve model" self.colbuff = (c_int * maxvars)() self.rowbuff = (c_double * maxvars)() lib.set_add_rowmode(self.lp, 1) def __del__(self): lib.delete_lp(self.lp) def constraint(self, const): "Add a new constraint into the model." assert const.optype is not None, "You must provide the RHS of constraint" const.fill_buffers(self.colbuff, self.rowbuff) ret = lib.add_constraintex(self.lp, len(const.vars), cast(self.rowbuff, c_double_p), cast(self.colbuff, c_int_p), const.optype, const.rhs) assert ret == 1, "Can't add constraint into model" def objective(self, const): "Set the objective function." lib.set_add_rowmode(self.lp, 0) const.fill_buffers(self.colbuff, self.rowbuff) ret = lib.set_obj_fnex(self.lp, len(const.vars), cast(self.rowbuff, c_double_p), cast(self.colbuff, c_int_p)) assert ret == 1, "Can't set objective function of model" def update_variables(self): "Update the variable values." ret = lib.get_variables(self.lp, cast(self.rowbuff, c_double_p)) assert ret == 1, "Can't get variable values" for i, var in enumerate(self.vars): var.value = self.rowbuff[i] def solve(self): "Solve the model." lib.set_maxim(self.lp) if self.debug: lib.write_lp(self.lp, b"debug-model.lp") else: lib.set_verbose(self.lp, 3) ret = lib.solve(self.lp) if ret == 0 or ret == 1: self.update_variables() return ret class LpVariable(object): "A LpSolve variable." def __init__(self, lp, vtype="real"): assert len(lp.vars) < lp.maxvars, "Can't add a variable: " self.index = len(lp.vars) + 1 self.value = None self.lp = lp lp.vars.append(self) self.type = "real" self.retype(vtype) def retype(self, vtype): "Change the type of the variable" if "bin" in (self.type, vtype): lib.set_binary(self.lp.lp, self.index, (vtype == "bin")) elif "int" in (self.type, vtype): lib.set_binary(self.lp.lp, self.index, (vtype == "int")) def __rmul__(self, num): return LpConstraint([num], [self]) def __add__(self, other): if isinstance(other, LpConstraint): return other.__add__(self) return LpConstraint([1, 1], [self, other]) class LpConstraint(object): "A LpSolve constraint." def __init__(self, numbers, vars): self.numbers = numbers self.vars = vars self.optype = None self.rhs = None def fill_buffers(self, colno, row): "Fill colno and row buffers for calling LpSolve." for i, (num, var) in enumerate(zip(self.numbers, self.vars)): colno[i] = var.index row[i] = num def __add__(self, other): if isinstance(other, LpVariable): return LpConstraint(self.numbers + [1], self.vars + [other]) else: c = LpConstraint(self.numbers + other.numbers, self.vars + other.vars) assert len(c.vars) == len(set(c.vars)), "Some variables appear several times" return c def __le__(self, val): self.optype, self.rhs = (1, val) return self def __eq__(self, val): self.optype, self.rhs = (3, val) return self def __ge__(self, val): self.optype, self.rhs = (2, val) return self
en
0.475577
LpSolve wrapper. Copyright (C) 2018, <NAME> License MIT # Import the DLL # Make the bindings
2.34145
2
octavia/tests/unit/controller/worker/v2/tasks/test_database_tasks.py
mauroseb/octavia
0
69
<gh_stars>0 # Copyright 2015 Hewlett-Packard Development Company, L.P. # # 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 random from cryptography import fernet import mock from oslo_db import exception as odb_exceptions from oslo_utils import uuidutils from sqlalchemy.orm import exc from taskflow.types import failure from octavia.common import constants from octavia.common import data_models from octavia.common import utils from octavia.controller.worker.v2.tasks import database_tasks from octavia.db import repositories as repo import octavia.tests.unit.base as base AMP_ID = uuidutils.generate_uuid() COMPUTE_ID = uuidutils.generate_uuid() LB_ID = uuidutils.generate_uuid() SERVER_GROUP_ID = uuidutils.generate_uuid() LB_NET_IP = '192.0.2.2' LISTENER_ID = uuidutils.generate_uuid() POOL_ID = uuidutils.generate_uuid() HM_ID = uuidutils.generate_uuid() MEMBER_ID = uuidutils.generate_uuid() PORT_ID = uuidutils.generate_uuid() SUBNET_ID = uuidutils.generate_uuid() VRRP_PORT_ID = uuidutils.generate_uuid() HA_PORT_ID = uuidutils.generate_uuid() L7POLICY_ID = uuidutils.generate_uuid() L7RULE_ID = uuidutils.generate_uuid() VIP_IP = '192.168.127.12' VRRP_IP = '172.16.31.10' HA_IP = '192.168.3.11' AMP_ROLE = 'FAKE_ROLE' VRRP_ID = random.randrange(255) VRRP_PRIORITY = random.randrange(100) CACHED_ZONE = 'zone1' IMAGE_ID = uuidutils.generate_uuid() COMPUTE_FLAVOR = uuidutils.generate_uuid() _amphora_mock = mock.MagicMock() _amphora_mock.id = AMP_ID _amphora_mock.compute_id = COMPUTE_ID _amphora_mock.lb_network_ip = LB_NET_IP _amphora_mock.vrrp_ip = VRRP_IP _amphora_mock.ha_ip = HA_IP _amphora_mock.ha_port_id = HA_PORT_ID _amphora_mock.vrrp_port_id = VRRP_PORT_ID _amphora_mock.role = AMP_ROLE _amphora_mock.vrrp_id = VRRP_ID _amphora_mock.vrrp_priority = VRRP_PRIORITY _amphorae = [_amphora_mock] _loadbalancer_mock = mock.MagicMock() _loadbalancer_mock.id = LB_ID _loadbalancer_mock.amphorae = [_amphora_mock] _l7policy_mock = mock.MagicMock() _l7policy_mock.id = L7POLICY_ID _l7rule_mock = mock.MagicMock() _l7rule_mock.id = L7RULE_ID _listener_mock = mock.MagicMock() _listener_to_dict_mock = mock.MagicMock( return_value={'id': LISTENER_ID}) _listener_mock.id = LISTENER_ID _listener_mock.to_dict = _listener_to_dict_mock _tf_failure_mock = mock.Mock(spec=failure.Failure) _vip_mock = mock.MagicMock() _vip_mock.port_id = PORT_ID _vip_mock.subnet_id = SUBNET_ID _vip_mock.ip_address = VIP_IP _vrrp_group_mock = mock.MagicMock() _cert_mock = mock.MagicMock() _compute_mock = mock.MagicMock() _compute_mock.lb_network_ip = LB_NET_IP _compute_mock.cached_zone = CACHED_ZONE _compute_mock.image_id = IMAGE_ID _compute_mock.compute_flavor = COMPUTE_FLAVOR @mock.patch('octavia.db.repositories.AmphoraRepository.delete') @mock.patch('octavia.db.repositories.AmphoraRepository.update') @mock.patch('octavia.db.repositories.ListenerRepository.update') @mock.patch('octavia.db.repositories.LoadBalancerRepository.update') @mock.patch('octavia.db.api.get_session', return_value='TEST') @mock.patch('octavia.controller.worker.v2.tasks.database_tasks.LOG') @mock.patch('oslo_utils.uuidutils.generate_uuid', return_value=AMP_ID) class TestDatabaseTasks(base.TestCase): def setUp(self): self.health_mon_mock = mock.MagicMock() self.health_mon_mock.id = HM_ID self.health_mon_mock.pool_id = POOL_ID self.listener_mock = mock.MagicMock() self.listener_mock.id = LISTENER_ID self.loadbalancer_mock = mock.MagicMock() self.loadbalancer_mock.id = LB_ID self.member_mock = mock.MagicMock() self.member_mock.id = MEMBER_ID self.db_pool_mock = mock.MagicMock() self.db_pool_mock.id = POOL_ID self.db_pool_mock.health_monitor = self.health_mon_mock self.member_mock = { constants.MEMBER_ID: MEMBER_ID, constants.POOL_ID: POOL_ID, } self.l7policy_mock = mock.MagicMock() self.l7policy_mock.id = L7POLICY_ID self.l7rule_mock = mock.MagicMock() self.l7rule_mock.id = L7RULE_ID self.l7rule_mock.l7policy = self.l7policy_mock super(TestDatabaseTasks, self).setUp() @mock.patch('octavia.db.repositories.AmphoraRepository.create', return_value=_amphora_mock) def test_create_amphora_in_db(self, mock_create, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): create_amp_in_db = database_tasks.CreateAmphoraInDB() amp_id = create_amp_in_db.execute() repo.AmphoraRepository.create.assert_called_once_with( 'TEST', id=AMP_ID, status=constants.PENDING_CREATE, cert_busy=False) self.assertEqual(_amphora_mock.id, amp_id) # Test the revert create_amp_in_db.revert(_tf_failure_mock) self.assertFalse(mock_amphora_repo_delete.called) mock_amphora_repo_delete.reset_mock() create_amp_in_db.revert(result='AMP') self.assertTrue(mock_amphora_repo_delete.called) mock_amphora_repo_delete.assert_called_once_with( 'TEST', id='AMP') # Test revert with exception mock_amphora_repo_delete.reset_mock() mock_amphora_repo_delete.side_effect = Exception('fail') create_amp_in_db.revert(result='AMP') self.assertTrue(mock_amphora_repo_delete.called) mock_amphora_repo_delete.assert_called_once_with( 'TEST', id='AMP') @mock.patch('octavia.db.repositories.ListenerRepository.delete') def test_delete_listener_in_db(self, mock_listener_repo_delete, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): delete_listener = database_tasks.DeleteListenerInDB() delete_listener.execute({constants.LISTENER_ID: LISTENER_ID}) repo.ListenerRepository.delete.assert_called_once_with( 'TEST', id=LISTENER_ID) # Test the revert repo.ListenerRepository.delete.reset_mock() delete_listener.revert({constants.LISTENER_ID: LISTENER_ID}) repo.ListenerRepository.delete.assert_not_called() @mock.patch('octavia.db.repositories.HealthMonitorRepository.update') @mock.patch('octavia.db.repositories.HealthMonitorRepository.delete') def test_delete_health_monitor_in_db(self, mock_health_mon_repo_delete, mock_health_mon_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): delete_health_mon = database_tasks.DeleteHealthMonitorInDB() delete_health_mon.execute(self.health_mon_mock) repo.HealthMonitorRepository.delete.assert_called_once_with( 'TEST', id=HM_ID) # Test the revert mock_health_mon_repo_delete.reset_mock() delete_health_mon.revert(self.health_mon_mock) repo.HealthMonitorRepository.update.assert_called_once_with( 'TEST', id=HM_ID, provisioning_status=constants.ERROR) # Test Not Found Exception mock_health_mon_repo_delete.reset_mock() mock_health_mon_repo_delete.side_effect = [exc.NoResultFound()] delete_health_mon.execute(self.health_mon_mock) repo.HealthMonitorRepository.delete.assert_called_once_with( 'TEST', id=HM_ID) @mock.patch('octavia.db.repositories.HealthMonitorRepository.update') @mock.patch('octavia.db.repositories.HealthMonitorRepository.delete') def test_delete_health_monitor_in_db_by_pool(self, mock_health_mon_repo_delete, mock_health_mon_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): delete_health_mon = database_tasks.DeleteHealthMonitorInDBByPool() delete_health_mon.execute(self.db_pool_mock) repo.HealthMonitorRepository.delete.assert_called_once_with( 'TEST', id=HM_ID) # Test the revert mock_health_mon_repo_delete.reset_mock() delete_health_mon.revert(self.db_pool_mock) repo.HealthMonitorRepository.update.assert_called_once_with( 'TEST', id=HM_ID, provisioning_status=constants.ERROR) # TODO(johnsom) fix once provisioning status added # repo.HealthMonitorRepository.update.assert_called_once_with( # 'TEST', # POOL_ID, # provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.MemberRepository.delete') def test_delete_member_in_db(self, mock_member_repo_delete, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): delete_member = database_tasks.DeleteMemberInDB() delete_member.execute(self.member_mock) repo.MemberRepository.delete.assert_called_once_with( 'TEST', id=MEMBER_ID) # Test the revert mock_member_repo_delete.reset_mock() delete_member.revert(self.member_mock) # TODO(johnsom) Fix # repo.MemberRepository.delete.assert_called_once_with( # 'TEST', # MEMBER_ID) @mock.patch('octavia.db.repositories.PoolRepository.delete') def test_delete_pool_in_db(self, mock_pool_repo_delete, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): delete_pool = database_tasks.DeletePoolInDB() delete_pool.execute(POOL_ID) repo.PoolRepository.delete.assert_called_once_with( 'TEST', id=POOL_ID) # Test the revert mock_pool_repo_delete.reset_mock() delete_pool.revert(POOL_ID) # TODO(johnsom) Fix # repo.PoolRepository.update.assert_called_once_with( # 'TEST', # POOL_ID, # operating_status=constants.ERROR) @mock.patch('octavia.db.repositories.L7PolicyRepository.delete') def test_delete_l7policy_in_db(self, mock_l7policy_repo_delete, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): delete_l7policy = database_tasks.DeleteL7PolicyInDB() delete_l7policy.execute(_l7policy_mock) repo.L7PolicyRepository.delete.assert_called_once_with( 'TEST', id=L7POLICY_ID) # Test the revert mock_l7policy_repo_delete.reset_mock() delete_l7policy.revert(_l7policy_mock) # TODO(sbalukoff) Fix # repo.ListenerRepository.update.assert_called_once_with( # 'TEST', # LISTENER_ID, # operating_status=constants.ERROR) @mock.patch('octavia.db.repositories.L7RuleRepository.delete') def test_delete_l7rule_in_db(self, mock_l7rule_repo_delete, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): delete_l7rule = database_tasks.DeleteL7RuleInDB() delete_l7rule.execute(_l7rule_mock) repo.L7RuleRepository.delete.assert_called_once_with( 'TEST', id=L7RULE_ID) # Test the revert mock_l7rule_repo_delete.reset_mock() delete_l7rule.revert(_l7rule_mock) # TODO(sbalukoff) Fix # repo.ListenerRepository.update.assert_called_once_with( # 'TEST', # LISTENER_ID, # operating_status=constants.ERROR) @mock.patch('octavia.db.repositories.AmphoraRepository.get', return_value=_amphora_mock) def test_reload_amphora(self, mock_amp_get, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): reload_amp = database_tasks.ReloadAmphora() amp = reload_amp.execute(AMP_ID) repo.AmphoraRepository.get.assert_called_once_with( 'TEST', id=AMP_ID) self.assertEqual(_amphora_mock, amp) @mock.patch('octavia.db.repositories.LoadBalancerRepository.get', return_value=_loadbalancer_mock) def test_reload_load_balancer(self, mock_lb_get, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): reload_lb = database_tasks.ReloadLoadBalancer() lb = reload_lb.execute(LB_ID) repo.LoadBalancerRepository.get.assert_called_once_with( 'TEST', id=LB_ID) self.assertEqual(_loadbalancer_mock, lb) @mock.patch('octavia.db.repositories.LoadBalancerRepository.get', return_value=_loadbalancer_mock) @mock.patch('octavia.db.repositories.VipRepository.update') def test_update_vip_after_allocation(self, mock_vip_update, mock_loadbalancer_get, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): update_vip = database_tasks.UpdateVIPAfterAllocation() loadbalancer = update_vip.execute(LB_ID, _vip_mock) self.assertEqual(_loadbalancer_mock, loadbalancer) mock_vip_update.assert_called_once_with('TEST', LB_ID, port_id=PORT_ID, subnet_id=SUBNET_ID, ip_address=VIP_IP) mock_loadbalancer_get.assert_called_once_with('TEST', id=LB_ID) def test_update_amphora_vip_data(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): update_amp_vip_data = database_tasks.UpdateAmphoraeVIPData() update_amp_vip_data.execute(_amphorae) mock_amphora_repo_update.assert_called_once_with( 'TEST', AMP_ID, vrrp_ip=VRRP_IP, ha_ip=HA_IP, vrrp_port_id=VRRP_PORT_ID, ha_port_id=HA_PORT_ID, vrrp_id=1) def test_update_amphora_vip_data2(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): update_amp_vip_data2 = database_tasks.UpdateAmphoraVIPData() update_amp_vip_data2.execute(_amphorae[0]) mock_amphora_repo_update.assert_called_once_with( 'TEST', AMP_ID, vrrp_ip=VRRP_IP, ha_ip=HA_IP, vrrp_port_id=VRRP_PORT_ID, ha_port_id=HA_PORT_ID, vrrp_id=1) def test_update_amp_failover_details(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): update_amp_fo_details = database_tasks.UpdateAmpFailoverDetails() update_amp_fo_details.execute(_amphora_mock, _amphora_mock) mock_amphora_repo_update.assert_called_once_with( 'TEST', AMP_ID, vrrp_ip=VRRP_IP, ha_ip=HA_IP, vrrp_port_id=VRRP_PORT_ID, ha_port_id=HA_PORT_ID, vrrp_id=VRRP_ID) @mock.patch('octavia.db.repositories.AmphoraRepository.associate') def test_associate_failover_amphora_with_lb_id( self, mock_associate, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): assoc_fo_amp_lb_id = database_tasks.AssociateFailoverAmphoraWithLBID() assoc_fo_amp_lb_id.execute(AMP_ID, LB_ID) mock_associate.assert_called_once_with('TEST', load_balancer_id=LB_ID, amphora_id=AMP_ID) # Test revert assoc_fo_amp_lb_id.revert(AMP_ID) mock_amphora_repo_update.assert_called_once_with('TEST', AMP_ID, loadbalancer_id=None) # Test revert with exception mock_amphora_repo_update.reset_mock() mock_amphora_repo_update.side_effect = Exception('fail') assoc_fo_amp_lb_id.revert(AMP_ID) mock_amphora_repo_update.assert_called_once_with('TEST', AMP_ID, loadbalancer_id=None) @mock.patch('octavia.db.repositories.AmphoraRepository.' 'allocate_and_associate', side_effect=[_amphora_mock, None]) def test_map_loadbalancer_to_amphora(self, mock_allocate_and_associate, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): map_lb_to_amp = database_tasks.MapLoadbalancerToAmphora() amp_id = map_lb_to_amp.execute(self.loadbalancer_mock.id) repo.AmphoraRepository.allocate_and_associate.assert_called_once_with( 'TEST', LB_ID, None) self.assertEqual(_amphora_mock.id, amp_id) amp_id = map_lb_to_amp.execute(self.loadbalancer_mock.id) self.assertIsNone(amp_id) # Test revert map_lb_to_amp.revert(None, self.loadbalancer_mock.id) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) # Test revert with exception repo.LoadBalancerRepository.update.reset_mock() mock_loadbalancer_repo_update.side_effect = Exception('fail') map_lb_to_amp.revert(None, self.loadbalancer_mock.id) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.AmphoraRepository.' 'allocate_and_associate', side_effect=[_amphora_mock, None]) def test_map_loadbalancer_to_amphora_with_az(self, mock_allocate_and_associate, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): map_lb_to_amp = database_tasks.MapLoadbalancerToAmphora() amp_id = map_lb_to_amp.execute( self.loadbalancer_mock.id, availability_zone={ constants.COMPUTE_ZONE: 'fakeaz'}) repo.AmphoraRepository.allocate_and_associate.assert_called_once_with( 'TEST', LB_ID, 'fakeaz') self.assertEqual(_amphora_mock.id, amp_id) amp_id = map_lb_to_amp.execute(self.loadbalancer_mock.id) self.assertIsNone(amp_id) # Test revert map_lb_to_amp.revert(None, self.loadbalancer_mock.id) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) # Test revert with exception repo.LoadBalancerRepository.update.reset_mock() mock_loadbalancer_repo_update.side_effect = Exception('fail') map_lb_to_amp.revert(None, self.loadbalancer_mock.id) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.AmphoraRepository.get', return_value=_amphora_mock) @mock.patch('octavia.db.repositories.LoadBalancerRepository.get', return_value=_loadbalancer_mock) def test_mark_lb_amphorae_deleted_in_db(self, mock_loadbalancer_repo_get, mock_amphora_repo_get, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_amp_deleted_in_db = (database_tasks. MarkLBAmphoraeDeletedInDB()) mark_amp_deleted_in_db.execute(_loadbalancer_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', id=AMP_ID, status=constants.DELETED) @mock.patch('octavia.db.repositories.AmphoraRepository.get', return_value=_amphora_mock) @mock.patch('octavia.db.repositories.LoadBalancerRepository.get', return_value=_loadbalancer_mock) def test_mark_amphora_allocated_in_db(self, mock_loadbalancer_repo_get, mock_amphora_repo_get, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_amp_allocated_in_db = (database_tasks. MarkAmphoraAllocatedInDB()) mark_amp_allocated_in_db.execute(_amphora_mock, self.loadbalancer_mock.id) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, status=constants.AMPHORA_ALLOCATED, compute_id=COMPUTE_ID, lb_network_ip=LB_NET_IP, load_balancer_id=LB_ID) # Test the revert mock_amphora_repo_update.reset_mock() mark_amp_allocated_in_db.revert(None, _amphora_mock, self.loadbalancer_mock.id) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', id=AMP_ID, status=constants.ERROR) # Test the revert with exception mock_amphora_repo_update.reset_mock() mock_amphora_repo_update.side_effect = Exception('fail') mark_amp_allocated_in_db.revert(None, _amphora_mock, self.loadbalancer_mock.id) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', id=AMP_ID, status=constants.ERROR) def test_mark_amphora_booting_in_db(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_amp_booting_in_db = database_tasks.MarkAmphoraBootingInDB() mark_amp_booting_in_db.execute(_amphora_mock.id, _amphora_mock.compute_id) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, status=constants.AMPHORA_BOOTING, compute_id=COMPUTE_ID) # Test the revert mock_amphora_repo_update.reset_mock() mark_amp_booting_in_db.revert(None, _amphora_mock.id, _amphora_mock.compute_id) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, status=constants.ERROR, compute_id=COMPUTE_ID) # Test the revert with exception mock_amphora_repo_update.reset_mock() mock_amphora_repo_update.side_effect = Exception('fail') mark_amp_booting_in_db.revert(None, _amphora_mock.id, _amphora_mock.compute_id) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, status=constants.ERROR, compute_id=COMPUTE_ID) def test_mark_amphora_deleted_in_db(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_amp_deleted_in_db = database_tasks.MarkAmphoraDeletedInDB() mark_amp_deleted_in_db.execute(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, status=constants.DELETED) # Test the revert mock_amphora_repo_update.reset_mock() mark_amp_deleted_in_db.revert(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', id=AMP_ID, status=constants.ERROR) # Test the revert with exception mock_amphora_repo_update.reset_mock() mock_amphora_repo_update.side_effect = Exception('fail') mark_amp_deleted_in_db.revert(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', id=AMP_ID, status=constants.ERROR) def test_mark_amphora_pending_delete_in_db(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_amp_pending_delete_in_db = (database_tasks. MarkAmphoraPendingDeleteInDB()) mark_amp_pending_delete_in_db.execute(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, status=constants.PENDING_DELETE) # Test the revert mock_amphora_repo_update.reset_mock() mark_amp_pending_delete_in_db.revert(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', id=AMP_ID, status=constants.ERROR) # Test the revert with exception mock_amphora_repo_update.reset_mock() mock_amphora_repo_update.side_effect = Exception('fail') mark_amp_pending_delete_in_db.revert(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', id=AMP_ID, status=constants.ERROR) def test_mark_amphora_pending_update_in_db(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_amp_pending_update_in_db = (database_tasks. MarkAmphoraPendingUpdateInDB()) mark_amp_pending_update_in_db.execute(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, status=constants.PENDING_UPDATE) # Test the revert mock_amphora_repo_update.reset_mock() mark_amp_pending_update_in_db.revert(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', id=AMP_ID, status=constants.ERROR) # Test the revert with exception mock_amphora_repo_update.reset_mock() mock_amphora_repo_update.side_effect = Exception('fail') mark_amp_pending_update_in_db.revert(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', id=AMP_ID, status=constants.ERROR) def test_mark_amphora_ready_in_db(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): _amphora_mock.lb_network_ip = LB_NET_IP mark_amp_ready_in_db = database_tasks.MarkAmphoraReadyInDB() mark_amp_ready_in_db.execute(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, status=constants.AMPHORA_READY, compute_id=COMPUTE_ID, lb_network_ip=LB_NET_IP) # Test the revert mock_amphora_repo_update.reset_mock() mark_amp_ready_in_db.revert(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, status=constants.ERROR, compute_id=COMPUTE_ID, lb_network_ip=LB_NET_IP) # Test the revert with exception mock_amphora_repo_update.reset_mock() mock_amphora_repo_update.side_effect = Exception('fail') mark_amp_ready_in_db.revert(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, status=constants.ERROR, compute_id=COMPUTE_ID, lb_network_ip=LB_NET_IP) @mock.patch('octavia.db.repositories.AmphoraRepository.get') def test_update_amphora_info(self, mock_amphora_repo_get, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): update_amphora_info = database_tasks.UpdateAmphoraInfo() update_amphora_info.execute(AMP_ID, _compute_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, lb_network_ip=LB_NET_IP, cached_zone=CACHED_ZONE, image_id=IMAGE_ID, compute_flavor=COMPUTE_FLAVOR) repo.AmphoraRepository.get.assert_called_once_with( 'TEST', id=AMP_ID) def test_mark_listener_deleted_in_db(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_listener_deleted = database_tasks.MarkListenerDeletedInDB() mark_listener_deleted.execute(self.listener_mock) repo.ListenerRepository.update.assert_called_once_with( 'TEST', LISTENER_ID, provisioning_status=constants.DELETED) # Test the revert mock_listener_repo_update.reset_mock() mark_listener_deleted.revert(self.listener_mock) repo.ListenerRepository.update.assert_called_once_with( 'TEST', id=LISTENER_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_listener_repo_update.reset_mock() mock_listener_repo_update.side_effect = Exception('fail') mark_listener_deleted.revert(self.listener_mock) repo.ListenerRepository.update.assert_called_once_with( 'TEST', id=LISTENER_ID, provisioning_status=constants.ERROR) def test_mark_listener_pending_deleted_in_db(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_listener_pending_delete = (database_tasks. MarkListenerPendingDeleteInDB()) mark_listener_pending_delete.execute(self.listener_mock) repo.ListenerRepository.update.assert_called_once_with( 'TEST', LISTENER_ID, provisioning_status=constants.PENDING_DELETE) # Test the revert mock_listener_repo_update.reset_mock() mark_listener_pending_delete.revert(self.listener_mock) repo.ListenerRepository.update.assert_called_once_with( 'TEST', id=LISTENER_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_listener_repo_update.reset_mock() mock_listener_repo_update.side_effect = Exception('fail') mark_listener_pending_delete.revert(self.listener_mock) repo.ListenerRepository.update.assert_called_once_with( 'TEST', id=LISTENER_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.ListenerRepository.' 'prov_status_active_if_not_error') def test_mark_lb_and_listeners_active_in_db(self, mock_list_not_error, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): listener_dict = {constants.LISTENER_ID: LISTENER_ID, constants.LOADBALANCER_ID: LB_ID} mark_lb_and_listeners_active = (database_tasks. MarkLBAndListenersActiveInDB()) mark_lb_and_listeners_active.execute(LB_ID, [listener_dict]) mock_list_not_error.assert_called_once_with('TEST', LISTENER_ID) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', LB_ID, provisioning_status=constants.ACTIVE) # Test with LB_ID from listeners mock_loadbalancer_repo_update.reset_mock() mock_list_not_error.reset_mock() listener_dict = {constants.LISTENER_ID: LISTENER_ID, constants.LOADBALANCER_ID: LB_ID} mark_lb_and_listeners_active = (database_tasks. MarkLBAndListenersActiveInDB()) mark_lb_and_listeners_active.execute(None, [listener_dict]) mock_list_not_error.assert_called_once_with('TEST', LISTENER_ID) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', LB_ID, provisioning_status=constants.ACTIVE) # Test with no LB_ID mock_loadbalancer_repo_update.reset_mock() mark_lb_and_listeners_active.execute(None, []) mock_loadbalancer_repo_update.assert_not_called() # Test the revert mock_loadbalancer_repo_update.reset_mock() mock_listener_repo_update.reset_mock() mark_lb_and_listeners_active.revert(LB_ID, [listener_dict]) repo.ListenerRepository.update.assert_called_once_with( 'TEST', id=LISTENER_ID, provisioning_status=constants.ERROR) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) # Test the revert LB_ID from listeners mock_loadbalancer_repo_update.reset_mock() mock_listener_repo_update.reset_mock() mark_lb_and_listeners_active.revert(None, [listener_dict]) repo.ListenerRepository.update.assert_called_once_with( 'TEST', id=LISTENER_ID, provisioning_status=constants.ERROR) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) # Test the revert no LB_ID mock_loadbalancer_repo_update.reset_mock() mock_listener_repo_update.reset_mock() mark_lb_and_listeners_active.revert(None, []) mock_loadbalancer_repo_update.assert_not_called() mock_listener_repo_update.assert_not_called() # Test the revert with exceptions mock_loadbalancer_repo_update.reset_mock() mock_loadbalancer_repo_update.side_effect = Exception('fail') mock_listener_repo_update.reset_mock() mock_listener_repo_update.side_effect = Exception('fail') mark_lb_and_listeners_active.revert(LB_ID, [listener_dict]) repo.ListenerRepository.update.assert_called_once_with( 'TEST', id=LISTENER_ID, provisioning_status=constants.ERROR) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.common.tls_utils.cert_parser.get_cert_expiration', return_value=_cert_mock) def test_update_amphora_db_cert_exp(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete, mock_get_cert_exp): update_amp_cert = database_tasks.UpdateAmphoraDBCertExpiration() key = utils.get_six_compatible_server_certs_key_passphrase() fer = fernet.Fernet(key) _pem_mock = fer.encrypt( utils.get_six_compatible_value('test_cert') ) update_amp_cert.execute(_amphora_mock.id, _pem_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, cert_expiration=_cert_mock) def test_update_amphora_cert_busy_to_false(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): amp_cert_busy_to_F = database_tasks.UpdateAmphoraCertBusyToFalse() amp_cert_busy_to_F.execute(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, cert_busy=False) def test_mark_LB_active_in_db(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_loadbalancer_active = database_tasks.MarkLBActiveInDB() mark_loadbalancer_active.execute(self.loadbalancer_mock) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', LB_ID, provisioning_status=constants.ACTIVE) self.assertEqual(0, repo.ListenerRepository.update.call_count) # Test the revert mock_loadbalancer_repo_update.reset_mock() mark_loadbalancer_active.revert(self.loadbalancer_mock) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) self.assertEqual(0, repo.ListenerRepository.update.call_count) # Test the revert with exception mock_loadbalancer_repo_update.reset_mock() mock_loadbalancer_repo_update.side_effect = Exception('fail') mark_loadbalancer_active.revert(self.loadbalancer_mock) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) self.assertEqual(0, repo.ListenerRepository.update.call_count) def test_mark_LB_active_in_db_by_listener(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): listener_dict = {'loadbalancer_id': LB_ID} mark_loadbalancer_active = database_tasks.MarkLBActiveInDBByListener() mark_loadbalancer_active.execute(listener_dict) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', LB_ID, provisioning_status=constants.ACTIVE) self.assertEqual(0, repo.ListenerRepository.update.call_count) # Test the revert mock_loadbalancer_repo_update.reset_mock() mark_loadbalancer_active.revert(listener_dict) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) self.assertEqual(0, repo.ListenerRepository.update.call_count) # Test the revert with exception mock_loadbalancer_repo_update.reset_mock() mock_loadbalancer_repo_update.side_effect = Exception('fail') mark_loadbalancer_active.revert(listener_dict) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) self.assertEqual(0, repo.ListenerRepository.update.call_count) def test_mark_LB_active_in_db_and_listeners(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): listeners = [data_models.Listener(id='listener1'), data_models.Listener(id='listener2')] lb = data_models.LoadBalancer(id=LB_ID, listeners=listeners) mark_lb_active = database_tasks.MarkLBActiveInDB(mark_subobjects=True) mark_lb_active.execute(lb) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', lb.id, provisioning_status=constants.ACTIVE) self.assertEqual(2, repo.ListenerRepository.update.call_count) repo.ListenerRepository.update.has_calls( [mock.call('TEST', listeners[0].id, provisioning_status=constants.ACTIVE), mock.call('TEST', listeners[1].id, provisioning_status=constants.ACTIVE)]) mock_loadbalancer_repo_update.reset_mock() mock_listener_repo_update.reset_mock() mark_lb_active.revert(lb) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=lb.id, provisioning_status=constants.ERROR) self.assertEqual(2, repo.ListenerRepository.update.call_count) repo.ListenerRepository.update.has_calls( [mock.call('TEST', listeners[0].id, provisioning_status=constants.ERROR), mock.call('TEST', listeners[1].id, provisioning_status=constants.ERROR)]) @mock.patch('octavia.db.repositories.PoolRepository.update') @mock.patch('octavia.db.repositories.MemberRepository.update') @mock.patch('octavia.db.repositories.HealthMonitorRepository.update') @mock.patch('octavia.db.repositories.L7PolicyRepository.update') @mock.patch('octavia.db.repositories.L7RuleRepository.update') def test_mark_LB_active_in_db_full_graph(self, mock_l7r_repo_update, mock_l7p_repo_update, mock_hm_repo_update, mock_member_repo_update, mock_pool_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): unused_pool = data_models.Pool(id='unused_pool') members1 = [{constants.MEMBER_ID: 'member1'}, {constants.MEMBER_ID: 'member2'}] health_monitor = data_models.HealthMonitor(id='hm1') default_pool = data_models.Pool(id='default_pool', members=members1, health_monitor=health_monitor) listener1 = data_models.Listener(id='listener1', default_pool=default_pool) members2 = [{constants.MEMBER_ID: 'member3'}, {constants.MEMBER_ID: 'member4'}] redirect_pool = data_models.Pool(id='redirect_pool', members=members2) l7rules = [data_models.L7Rule(id='rule1')] redirect_policy = data_models.L7Policy(id='redirect_policy', redirect_pool=redirect_pool, l7rules=l7rules) l7policies = [redirect_policy] listener2 = data_models.Listener(id='listener2', l7policies=l7policies) listener2.l7policies = l7policies listeners = [listener1, listener2] pools = [default_pool, redirect_pool, unused_pool] lb = data_models.LoadBalancer(id=LB_ID, listeners=listeners, pools=pools) mark_lb_active = database_tasks.MarkLBActiveInDB(mark_subobjects=True) mark_lb_active.execute(lb) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', lb.id, provisioning_status=constants.ACTIVE) self.assertEqual(2, repo.ListenerRepository.update.call_count) repo.ListenerRepository.update.has_calls( [mock.call('TEST', listeners[0].id, provisioning_status=constants.ACTIVE), mock.call('TEST', listeners[1].id, provisioning_status=constants.ACTIVE)]) self.assertEqual(2, repo.PoolRepository.update.call_count) repo.PoolRepository.update.has_calls( [mock.call('TEST', default_pool.id, provisioning_status=constants.ACTIVE), mock.call('TEST', redirect_pool.id, provisioning_status=constants.ACTIVE)]) self.assertEqual(1, repo.HealthMonitorRepository.update.call_count) repo.HealthMonitorRepository.update.has_calls( [mock.call('TEST', health_monitor.id, provisioning_status=constants.ACTIVE)]) self.assertEqual(1, repo.L7PolicyRepository.update.call_count) repo.L7PolicyRepository.update.has_calls( [mock.call('TEST', l7policies[0].id, provisioning_status=constants.ACTIVE)]) self.assertEqual(1, repo.L7RuleRepository.update.call_count) repo.L7RuleRepository.update.has_calls( [mock.call('TEST', l7rules[0].id, provisioning_status=constants.ACTIVE)]) mock_loadbalancer_repo_update.reset_mock() mock_listener_repo_update.reset_mock() mock_pool_repo_update.reset_mock() mock_member_repo_update.reset_mock() mock_hm_repo_update.reset_mock() mock_l7p_repo_update.reset_mock() mock_l7r_repo_update.reset_mock() mark_lb_active.revert(lb) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=lb.id, provisioning_status=constants.ERROR) self.assertEqual(2, repo.ListenerRepository.update.call_count) repo.ListenerRepository.update.has_calls( [mock.call('TEST', listeners[0].id, provisioning_status=constants.ERROR), mock.call('TEST', listeners[1].id, provisioning_status=constants.ERROR)]) self.assertEqual(2, repo.PoolRepository.update.call_count) repo.PoolRepository.update.has_calls( [mock.call('TEST', default_pool.id, provisioning_status=constants.ERROR), mock.call('TEST', redirect_pool.id, provisioning_status=constants.ERROR)]) self.assertEqual(1, repo.HealthMonitorRepository.update.call_count) repo.HealthMonitorRepository.update.has_calls( [mock.call('TEST', health_monitor.id, provisioning_status=constants.ERROR)]) self.assertEqual(1, repo.L7PolicyRepository.update.call_count) repo.L7PolicyRepository.update.has_calls( [mock.call('TEST', l7policies[0].id, provisioning_status=constants.ERROR)]) self.assertEqual(1, repo.L7RuleRepository.update.call_count) repo.L7RuleRepository.update.has_calls( [mock.call('TEST', l7rules[0].id, provisioning_status=constants.ERROR)]) def test_mark_LB_deleted_in_db(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_loadbalancer_deleted = database_tasks.MarkLBDeletedInDB() mark_loadbalancer_deleted.execute(self.loadbalancer_mock) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', LB_ID, provisioning_status=constants.DELETED) # Test the revert mock_loadbalancer_repo_update.reset_mock() mark_loadbalancer_deleted.revert(self.loadbalancer_mock) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_loadbalancer_repo_update.reset_mock() mock_loadbalancer_repo_update.side_effect = Exception('fail') mark_loadbalancer_deleted.revert(self.loadbalancer_mock) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) def test_mark_LB_pending_deleted_in_db(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_loadbalancer_pending_delete = (database_tasks. MarkLBPendingDeleteInDB()) mark_loadbalancer_pending_delete.execute(self.loadbalancer_mock) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', LB_ID, provisioning_status=constants.PENDING_DELETE) # Test the revert mock_loadbalancer_repo_update.reset_mock() mark_loadbalancer_pending_delete.revert(self.loadbalancer_mock) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_loadbalancer_repo_update.reset_mock() mock_loadbalancer_repo_update.side_effect = Exception('fail') mark_loadbalancer_pending_delete.revert(self.loadbalancer_mock) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.HealthMonitorRepository.update') def test_update_health_monitor_in_db(self, mock_health_mon_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): update_health_mon = database_tasks.UpdateHealthMonInDB() update_health_mon.execute(self.health_mon_mock, {'delay': 1, 'timeout': 2}) repo.HealthMonitorRepository.update.assert_called_once_with( 'TEST', HM_ID, delay=1, timeout=2) # Test the revert mock_health_mon_repo_update.reset_mock() update_health_mon.revert(self.health_mon_mock) repo.HealthMonitorRepository.update.assert_called_once_with( 'TEST', HM_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_health_mon_repo_update.reset_mock() mock_health_mon_repo_update.side_effect = Exception('fail') update_health_mon.revert(self.health_mon_mock) repo.HealthMonitorRepository.update.assert_called_once_with( 'TEST', HM_ID, provisioning_status=constants.ERROR) def test_update_load_balancer_in_db(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): update_load_balancer = database_tasks.UpdateLoadbalancerInDB() update_load_balancer.execute(self.loadbalancer_mock, {'name': 'test', 'description': 'test2'}) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', LB_ID, name='test', description='test2') # Test the revert mock_loadbalancer_repo_update.reset_mock() update_load_balancer.revert(self.loadbalancer_mock) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_loadbalancer_repo_update.reset_mock() mock_loadbalancer_repo_update.side_effect = Exception('fail') update_load_balancer.revert(self.loadbalancer_mock) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.VipRepository.update') def test_update_vip_in_db_during_update_loadbalancer(self, mock_vip_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_lb_update, mock_listener_update, mock_amphora_update, mock_amphora_delete): self.loadbalancer_mock.vip.load_balancer_id = LB_ID update_load_balancer = database_tasks.UpdateLoadbalancerInDB() update_load_balancer.execute(self.loadbalancer_mock, {'name': 'test', 'description': 'test2', 'vip': {'qos_policy_id': 'fool'}}) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', LB_ID, name='test', description='test2') repo.VipRepository.update.assert_called_once_with('TEST', LB_ID, qos_policy_id='fool') def test_update_listener_in_db(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): update_listener = database_tasks.UpdateListenerInDB() listener_dict = {constants.LISTENER_ID: LISTENER_ID} update_listener.execute(listener_dict, {'name': 'test', 'description': 'test2'}) repo.ListenerRepository.update.assert_called_once_with( 'TEST', LISTENER_ID, name='test', description='test2') # Test the revert mock_listener_repo_update.reset_mock() update_listener.revert(listener_dict) repo.ListenerRepository.update.assert_called_once_with( 'TEST', id=LISTENER_ID, provisioning_status=constants.ERROR) # Test the revert mock_listener_repo_update.reset_mock() mock_listener_repo_update.side_effect = Exception('fail') update_listener.revert(listener_dict) repo.ListenerRepository.update.assert_called_once_with( 'TEST', id=LISTENER_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.MemberRepository.update') def test_update_member_in_db(self, mock_member_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): update_member = database_tasks.UpdateMemberInDB() update_member.execute(self.member_mock, {'weight': 1, 'ip_address': '10.1.0.0'}) repo.MemberRepository.update.assert_called_once_with( 'TEST', MEMBER_ID, weight=1, ip_address='10.1.0.0') # Test the revert mock_member_repo_update.reset_mock() update_member.revert(self.member_mock) repo.MemberRepository.update.assert_called_once_with( 'TEST', MEMBER_ID, provisioning_status=constants.ERROR) # Test the revert mock_member_repo_update.reset_mock() mock_member_repo_update.side_effect = Exception('fail') update_member.revert(self.member_mock) repo.MemberRepository.update.assert_called_once_with( 'TEST', MEMBER_ID, provisioning_status=constants.ERROR) @mock.patch( 'octavia.db.repositories.Repositories.update_pool_and_sp') def test_update_pool_in_db(self, mock_repos_pool_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): sp_dict = {'type': 'SOURCE_IP', 'cookie_name': None} update_dict = {'name': 'test', 'description': 'test2', 'session_persistence': sp_dict} update_pool = database_tasks.UpdatePoolInDB() update_pool.execute(POOL_ID, update_dict) repo.Repositories.update_pool_and_sp.assert_called_once_with( 'TEST', POOL_ID, update_dict) # Test the revert mock_repos_pool_update.reset_mock() update_pool.revert(POOL_ID) repo.Repositories.update_pool_and_sp.assert_called_once_with( 'TEST', POOL_ID, {'provisioning_status': constants.ERROR}) # Test the revert with exception mock_repos_pool_update.reset_mock() mock_repos_pool_update.side_effect = Exception('fail') update_pool.revert(POOL_ID) repo.Repositories.update_pool_and_sp.assert_called_once_with( 'TEST', POOL_ID, {'provisioning_status': constants.ERROR}) @mock.patch('octavia.db.repositories.L7PolicyRepository.update') def test_update_l7policy_in_db(self, mock_l7policy_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): update_l7policy = database_tasks.UpdateL7PolicyInDB() update_l7policy.execute(self.l7policy_mock, {'action': constants.L7POLICY_ACTION_REJECT}) repo.L7PolicyRepository.update.assert_called_once_with( 'TEST', L7POLICY_ID, action=constants.L7POLICY_ACTION_REJECT) # Test the revert mock_l7policy_repo_update.reset_mock() update_l7policy.revert(self.l7policy_mock) repo.L7PolicyRepository.update.assert_called_once_with( 'TEST', L7POLICY_ID, provisioning_status=constants.ERROR) # Test the revert mock_l7policy_repo_update.reset_mock() mock_l7policy_repo_update.side_effect = Exception('fail') update_l7policy.revert(self.l7policy_mock) repo.L7PolicyRepository.update.assert_called_once_with( 'TEST', L7POLICY_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.L7RuleRepository.update') @mock.patch('octavia.db.repositories.L7PolicyRepository.update') def test_update_l7rule_in_db(self, mock_l7rule_repo_update, mock_l7policy_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): update_l7rule = database_tasks.UpdateL7RuleInDB() update_l7rule.execute( self.l7rule_mock, {'type': constants.L7RULE_TYPE_PATH, 'compare_type': constants.L7RULE_COMPARE_TYPE_STARTS_WITH, 'value': '/api'}) repo.L7RuleRepository.update.assert_called_once_with( 'TEST', L7RULE_ID, type=constants.L7RULE_TYPE_PATH, compare_type=constants.L7RULE_COMPARE_TYPE_STARTS_WITH, value='/api') # Test the revert mock_l7rule_repo_update.reset_mock() update_l7rule.revert(self.l7rule_mock) repo.L7PolicyRepository.update.assert_called_once_with( 'TEST', L7POLICY_ID, provisioning_status=constants.ERROR) # Test the revert mock_l7rule_repo_update.reset_mock() mock_l7rule_repo_update.side_effect = Exception('fail') update_l7rule.revert(self.l7rule_mock) repo.L7PolicyRepository.update.assert_called_once_with( 'TEST', L7POLICY_ID, provisioning_status=constants.ERROR) def test_get_amphora_details(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): get_amp_details = database_tasks.GetAmphoraDetails() new_amp = get_amp_details.execute(_amphora_mock) self.assertEqual(AMP_ID, new_amp.id) self.assertEqual(VRRP_IP, new_amp.vrrp_ip) self.assertEqual(HA_IP, new_amp.ha_ip) self.assertEqual(VRRP_PORT_ID, new_amp.vrrp_port_id) self.assertEqual(AMP_ROLE, new_amp.role) self.assertEqual(VRRP_ID, new_amp.vrrp_id) self.assertEqual(VRRP_PRIORITY, new_amp.vrrp_priority) def test_mark_amphora_role_indb(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_amp_master_indb = database_tasks.MarkAmphoraMasterInDB() mark_amp_master_indb.execute(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, role='MASTER', vrrp_priority=constants.ROLE_MASTER_PRIORITY) mock_amphora_repo_update.reset_mock() mark_amp_master_indb.revert("BADRESULT", _amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, role=None, vrrp_priority=None) mock_amphora_repo_update.reset_mock() failure_obj = failure.Failure.from_exception(Exception("TESTEXCEPT")) mark_amp_master_indb.revert(failure_obj, _amphora_mock) self.assertFalse(repo.AmphoraRepository.update.called) mock_amphora_repo_update.reset_mock() mark_amp_backup_indb = database_tasks.MarkAmphoraBackupInDB() mark_amp_backup_indb.execute(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, role='BACKUP', vrrp_priority=constants.ROLE_BACKUP_PRIORITY) mock_amphora_repo_update.reset_mock() mark_amp_backup_indb.revert("BADRESULT", _amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, role=None, vrrp_priority=None) mock_amphora_repo_update.reset_mock() mark_amp_standalone_indb = database_tasks.MarkAmphoraStandAloneInDB() mark_amp_standalone_indb.execute(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, role='STANDALONE', vrrp_priority=None) mock_amphora_repo_update.reset_mock() mark_amp_standalone_indb.revert("BADRESULT", _amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, role=None, vrrp_priority=None) # Test revert with exception mock_amphora_repo_update.reset_mock() mock_amphora_repo_update.side_effect = Exception('fail') mark_amp_standalone_indb.revert("BADRESULT", _amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, role=None, vrrp_priority=None) @mock.patch('octavia.db.repositories.AmphoraRepository.get') def test_get_amphorae_from_loadbalancer(self, mock_amphora_get, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): amp1 = mock.MagicMock() amp1.id = uuidutils.generate_uuid() amp2 = mock.MagicMock() amp2.id = uuidutils.generate_uuid() lb = mock.MagicMock() lb.amphorae = [amp1, amp2] mock_amphora_get.side_effect = [_amphora_mock, None] get_amps_from_lb_obj = database_tasks.GetAmphoraeFromLoadbalancer() result = get_amps_from_lb_obj.execute(lb) self.assertEqual([_amphora_mock], result) @mock.patch('octavia.db.repositories.ListenerRepository.get') def test_get_listeners_from_loadbalancer(self, mock_listener_get, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mock_listener_get.return_value = _listener_mock _loadbalancer_mock.listeners = [_listener_mock] get_list_from_lb_obj = database_tasks.GetListenersFromLoadbalancer() result = get_list_from_lb_obj.execute(_loadbalancer_mock) mock_listener_get.assert_called_once_with('TEST', id=_listener_mock.id) self.assertEqual([{constants.LISTENER_ID: LISTENER_ID}], result) def test_get_vip_from_loadbalancer(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): _loadbalancer_mock.vip = _vip_mock get_vip_from_lb_obj = database_tasks.GetVipFromLoadbalancer() result = get_vip_from_lb_obj.execute(_loadbalancer_mock) self.assertEqual(_vip_mock, result) @mock.patch('octavia.db.repositories.VRRPGroupRepository.create') def test_create_vrrp_group_for_lb(self, mock_vrrp_group_create, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mock_get_session.side_effect = ['TEST', odb_exceptions.DBDuplicateEntry] create_vrrp_group = database_tasks.CreateVRRPGroupForLB() create_vrrp_group.execute(_loadbalancer_mock) mock_vrrp_group_create.assert_called_once_with( 'TEST', load_balancer_id=LB_ID, vrrp_group_name=LB_ID.replace('-', ''), vrrp_auth_type=constants.VRRP_AUTH_DEFAULT, vrrp_auth_pass=mock_generate_uuid.return_value.replace('-', '')[0:7], advert_int=1) create_vrrp_group.execute(_loadbalancer_mock) @mock.patch('octavia.db.repositories.AmphoraHealthRepository.delete') def test_disable_amphora_health_monitoring(self, mock_amp_health_repo_delete, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): disable_amp_health = database_tasks.DisableAmphoraHealthMonitoring() disable_amp_health.execute(_amphora_mock) mock_amp_health_repo_delete.assert_called_once_with( 'TEST', amphora_id=AMP_ID) @mock.patch('octavia.db.repositories.AmphoraHealthRepository.delete') def test_disable_lb_amphorae_health_monitoring( self, mock_amp_health_repo_delete, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): disable_amp_health = ( database_tasks.DisableLBAmphoraeHealthMonitoring()) disable_amp_health.execute(_loadbalancer_mock) mock_amp_health_repo_delete.assert_called_once_with( 'TEST', amphora_id=AMP_ID) @mock.patch('octavia.db.repositories.AmphoraHealthRepository.update') def test_mark_amphora_health_monitoring_busy(self, mock_amp_health_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_busy = database_tasks.MarkAmphoraHealthBusy() mark_busy.execute(_amphora_mock) mock_amp_health_repo_update.assert_called_once_with( 'TEST', amphora_id=AMP_ID, busy=True) @mock.patch('octavia.db.repositories.AmphoraHealthRepository.update') def test_mark_lb_amphorae_health_monitoring_busy( self, mock_amp_health_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_busy = ( database_tasks.MarkLBAmphoraeHealthBusy()) mark_busy.execute(_loadbalancer_mock) mock_amp_health_repo_update.assert_called_once_with( 'TEST', amphora_id=AMP_ID, busy=True) def test_update_lb_server_group_in_db(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): update_server_group_info = database_tasks.UpdateLBServerGroupInDB() update_server_group_info.execute(LB_ID, SERVER_GROUP_ID) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, server_group_id=SERVER_GROUP_ID) # Test the revert mock_listener_repo_update.reset_mock() update_server_group_info.revert(LB_ID, SERVER_GROUP_ID) # Test the revert with exception mock_listener_repo_update.reset_mock() mock_loadbalancer_repo_update.side_effect = Exception('fail') update_server_group_info.revert(LB_ID, SERVER_GROUP_ID) @mock.patch('octavia.db.repositories.HealthMonitorRepository.update') def test_mark_health_mon_active_in_db(self, mock_health_mon_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_health_mon_active = (database_tasks.MarkHealthMonitorActiveInDB()) mark_health_mon_active.execute(self.health_mon_mock) mock_health_mon_repo_update.assert_called_once_with( 'TEST', HM_ID, operating_status=constants.ONLINE, provisioning_status=constants.ACTIVE) # Test the revert mock_health_mon_repo_update.reset_mock() mark_health_mon_active.revert(self.health_mon_mock) mock_health_mon_repo_update.assert_called_once_with( 'TEST', id=HM_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_health_mon_repo_update.reset_mock() mock_health_mon_repo_update.side_effect = Exception('fail') mark_health_mon_active.revert(self.health_mon_mock) mock_health_mon_repo_update.assert_called_once_with( 'TEST', id=HM_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.HealthMonitorRepository.update') def test_mark_health_mon_pending_create_in_db( self, mock_health_mon_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_health_mon_pending_create = (database_tasks. MarkHealthMonitorPendingCreateInDB()) mark_health_mon_pending_create.execute(self.health_mon_mock) mock_health_mon_repo_update.assert_called_once_with( 'TEST', HM_ID, provisioning_status=constants.PENDING_CREATE) # Test the revert mock_health_mon_repo_update.reset_mock() mark_health_mon_pending_create.revert(self.health_mon_mock) mock_health_mon_repo_update.assert_called_once_with( 'TEST', id=HM_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_health_mon_repo_update.reset_mock() mock_health_mon_repo_update.side_effect = Exception('fail') mark_health_mon_pending_create.revert(self.health_mon_mock) mock_health_mon_repo_update.assert_called_once_with( 'TEST', id=HM_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.HealthMonitorRepository.update') def test_mark_health_mon_pending_delete_in_db( self, mock_health_mon_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_health_mon_pending_delete = (database_tasks. MarkHealthMonitorPendingDeleteInDB()) mark_health_mon_pending_delete.execute(self.health_mon_mock) mock_health_mon_repo_update.assert_called_once_with( 'TEST', HM_ID, provisioning_status=constants.PENDING_DELETE) # Test the revert mock_health_mon_repo_update.reset_mock() mark_health_mon_pending_delete.revert(self.health_mon_mock) mock_health_mon_repo_update.assert_called_once_with( 'TEST', id=HM_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_health_mon_repo_update.reset_mock() mock_health_mon_repo_update.side_effect = Exception('fail') mark_health_mon_pending_delete.revert(self.health_mon_mock) mock_health_mon_repo_update.assert_called_once_with( 'TEST', id=HM_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.HealthMonitorRepository.update') def test_mark_health_mon_pending_update_in_db( self, mock_health_mon_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_health_mon_pending_update = (database_tasks. MarkHealthMonitorPendingUpdateInDB()) mark_health_mon_pending_update.execute(self.health_mon_mock) mock_health_mon_repo_update.assert_called_once_with( 'TEST', HM_ID, provisioning_status=constants.PENDING_UPDATE) # Test the revert mock_health_mon_repo_update.reset_mock() mark_health_mon_pending_update.revert(self.health_mon_mock) mock_health_mon_repo_update.assert_called_once_with( 'TEST', id=HM_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_health_mon_repo_update.reset_mock() mock_health_mon_repo_update.side_effect = Exception('fail') mark_health_mon_pending_update.revert(self.health_mon_mock) mock_health_mon_repo_update.assert_called_once_with( 'TEST', id=HM_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.L7PolicyRepository.update') def test_mark_l7policy_active_in_db(self, mock_l7policy_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_l7policy_active = (database_tasks.MarkL7PolicyActiveInDB()) mark_l7policy_active.execute(self.l7policy_mock) mock_l7policy_repo_update.assert_called_once_with( 'TEST', L7POLICY_ID, provisioning_status=constants.ACTIVE, operating_status=constants.ONLINE) # Test the revert mock_l7policy_repo_update.reset_mock() mark_l7policy_active.revert(self.l7policy_mock) mock_l7policy_repo_update.assert_called_once_with( 'TEST', id=L7POLICY_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_l7policy_repo_update.reset_mock() mock_l7policy_repo_update.side_effect = Exception('fail') mark_l7policy_active.revert(self.l7policy_mock) mock_l7policy_repo_update.assert_called_once_with( 'TEST', id=L7POLICY_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.L7PolicyRepository.update') def test_mark_l7policy_pending_create_in_db(self, mock_l7policy_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_l7policy_pending_create = (database_tasks. MarkL7PolicyPendingCreateInDB()) mark_l7policy_pending_create.execute(self.l7policy_mock) mock_l7policy_repo_update.assert_called_once_with( 'TEST', L7POLICY_ID, provisioning_status=constants.PENDING_CREATE) # Test the revert mock_l7policy_repo_update.reset_mock() mark_l7policy_pending_create.revert(self.l7policy_mock) mock_l7policy_repo_update.assert_called_once_with( 'TEST', id=L7POLICY_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_l7policy_repo_update.reset_mock() mock_l7policy_repo_update.side_effect = Exception('fail') mark_l7policy_pending_create.revert(self.l7policy_mock) mock_l7policy_repo_update.assert_called_once_with( 'TEST', id=L7POLICY_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.L7PolicyRepository.update') def test_mark_l7policy_pending_delete_in_db(self, mock_l7policy_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_l7policy_pending_delete = (database_tasks. MarkL7PolicyPendingDeleteInDB()) mark_l7policy_pending_delete.execute(self.l7policy_mock) mock_l7policy_repo_update.assert_called_once_with( 'TEST', L7POLICY_ID, provisioning_status=constants.PENDING_DELETE) # Test the revert mock_l7policy_repo_update.reset_mock() mark_l7policy_pending_delete.revert(self.l7policy_mock) mock_l7policy_repo_update.assert_called_once_with( 'TEST', id=L7POLICY_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_l7policy_repo_update.reset_mock() mock_l7policy_repo_update.side_effect = Exception('fail') mark_l7policy_pending_delete.revert(self.l7policy_mock) mock_l7policy_repo_update.assert_called_once_with( 'TEST', id=L7POLICY_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.L7PolicyRepository.update') def test_mark_l7policy_pending_update_in_db(self, mock_l7policy_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_l7policy_pending_update = (database_tasks. MarkL7PolicyPendingUpdateInDB()) mark_l7policy_pending_update.execute(self.l7policy_mock) mock_l7policy_repo_update.assert_called_once_with( 'TEST', L7POLICY_ID, provisioning_status=constants.PENDING_UPDATE) # Test the revert mock_l7policy_repo_update.reset_mock() mark_l7policy_pending_update.revert(self.l7policy_mock) mock_l7policy_repo_update.assert_called_once_with( 'TEST', id=L7POLICY_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_l7policy_repo_update.reset_mock() mock_l7policy_repo_update.side_effect = Exception('fail') mark_l7policy_pending_update.revert(self.l7policy_mock) mock_l7policy_repo_update.assert_called_once_with( 'TEST', id=L7POLICY_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.L7RuleRepository.update') def test_mark_l7rule_active_in_db(self, mock_l7rule_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_l7rule_active = (database_tasks.MarkL7RuleActiveInDB()) mark_l7rule_active.execute(self.l7rule_mock) mock_l7rule_repo_update.assert_called_once_with( 'TEST', L7RULE_ID, provisioning_status=constants.ACTIVE, operating_status=constants.ONLINE) # Test the revert mock_l7rule_repo_update.reset_mock() mark_l7rule_active.revert(self.l7rule_mock) mock_l7rule_repo_update.assert_called_once_with( 'TEST', id=L7RULE_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_l7rule_repo_update.reset_mock() mock_l7rule_repo_update.side_effect = Exception('fail') mark_l7rule_active.revert(self.l7rule_mock) mock_l7rule_repo_update.assert_called_once_with( 'TEST', id=L7RULE_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.L7RuleRepository.update') def test_mark_l7rule_pending_create_in_db(self, mock_l7rule_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_l7rule_pending_create = (database_tasks. MarkL7RulePendingCreateInDB()) mark_l7rule_pending_create.execute(self.l7rule_mock) mock_l7rule_repo_update.assert_called_once_with( 'TEST', L7RULE_ID, provisioning_status=constants.PENDING_CREATE) # Test the revert mock_l7rule_repo_update.reset_mock() mark_l7rule_pending_create.revert(self.l7rule_mock) mock_l7rule_repo_update.assert_called_once_with( 'TEST', id=L7RULE_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_l7rule_repo_update.reset_mock() mock_l7rule_repo_update.side_effect = Exception('fail') mark_l7rule_pending_create.revert(self.l7rule_mock) mock_l7rule_repo_update.assert_called_once_with( 'TEST', id=L7RULE_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.L7RuleRepository.update') def test_mark_l7rule_pending_delete_in_db(self, mock_l7rule_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_l7rule_pending_delete = (database_tasks. MarkL7RulePendingDeleteInDB()) mark_l7rule_pending_delete.execute(self.l7rule_mock) mock_l7rule_repo_update.assert_called_once_with( 'TEST', L7RULE_ID, provisioning_status=constants.PENDING_DELETE) # Test the revert mock_l7rule_repo_update.reset_mock() mark_l7rule_pending_delete.revert(self.l7rule_mock) mock_l7rule_repo_update.assert_called_once_with( 'TEST', id=L7RULE_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_l7rule_repo_update.reset_mock() mock_l7rule_repo_update.side_effect = Exception('fail') mark_l7rule_pending_delete.revert(self.l7rule_mock) mock_l7rule_repo_update.assert_called_once_with( 'TEST', id=L7RULE_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.L7RuleRepository.update') def test_mark_l7rule_pending_update_in_db(self, mock_l7rule_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_l7rule_pending_update = (database_tasks. MarkL7RulePendingUpdateInDB()) mark_l7rule_pending_update.execute(self.l7rule_mock) mock_l7rule_repo_update.assert_called_once_with( 'TEST', L7RULE_ID, provisioning_status=constants.PENDING_UPDATE) # Test the revert mock_l7rule_repo_update.reset_mock() mark_l7rule_pending_update.revert(self.l7rule_mock) mock_l7rule_repo_update.assert_called_once_with( 'TEST', id=L7RULE_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_l7rule_repo_update.reset_mock() mock_l7rule_repo_update.side_effect = Exception('fail') mark_l7rule_pending_update.revert(self.l7rule_mock) mock_l7rule_repo_update.assert_called_once_with( 'TEST', id=L7RULE_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.MemberRepository.update') def test_mark_member_active_in_db(self, mock_member_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_member_active = (database_tasks.MarkMemberActiveInDB()) mark_member_active.execute(self.member_mock) mock_member_repo_update.assert_called_once_with( 'TEST', MEMBER_ID, provisioning_status=constants.ACTIVE) # Test the revert mock_member_repo_update.reset_mock() mark_member_active.revert(self.member_mock) mock_member_repo_update.assert_called_once_with( 'TEST', id=MEMBER_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_member_repo_update.reset_mock() mock_member_repo_update.side_effect = Exception('fail') mark_member_active.revert(self.member_mock) mock_member_repo_update.assert_called_once_with( 'TEST', id=MEMBER_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.MemberRepository.update') def test_mark_member_pending_create_in_db(self, mock_member_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_member_pending_create = (database_tasks. MarkMemberPendingCreateInDB()) mark_member_pending_create.execute(self.member_mock) mock_member_repo_update.assert_called_once_with( 'TEST', MEMBER_ID, provisioning_status=constants.PENDING_CREATE) # Test the revert mock_member_repo_update.reset_mock() mark_member_pending_create.revert(self.member_mock) mock_member_repo_update.assert_called_once_with( 'TEST', id=MEMBER_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_member_repo_update.reset_mock() mock_member_repo_update.side_effect = Exception('fail') mark_member_pending_create.revert(self.member_mock) mock_member_repo_update.assert_called_once_with( 'TEST', id=MEMBER_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.MemberRepository.update') def test_mark_member_pending_delete_in_db(self, mock_member_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_member_pending_delete = (database_tasks. MarkMemberPendingDeleteInDB()) mark_member_pending_delete.execute(self.member_mock) mock_member_repo_update.assert_called_once_with( 'TEST', MEMBER_ID, provisioning_status=constants.PENDING_DELETE) # Test the revert mock_member_repo_update.reset_mock() mark_member_pending_delete.revert(self.member_mock) mock_member_repo_update.assert_called_once_with( 'TEST', id=MEMBER_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_member_repo_update.reset_mock() mock_member_repo_update.side_effect = Exception('fail') mark_member_pending_delete.revert(self.member_mock) mock_member_repo_update.assert_called_once_with( 'TEST', id=MEMBER_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.MemberRepository.update') def test_mark_member_pending_update_in_db(self, mock_member_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_member_pending_update = (database_tasks. MarkMemberPendingUpdateInDB()) mark_member_pending_update.execute(self.member_mock) mock_member_repo_update.assert_called_once_with( 'TEST', MEMBER_ID, provisioning_status=constants.PENDING_UPDATE) # Test the revert mock_member_repo_update.reset_mock() mark_member_pending_update.revert(self.member_mock) mock_member_repo_update.assert_called_once_with( 'TEST', id=MEMBER_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_member_repo_update.reset_mock() mock_member_repo_update.side_effect = Exception('fail') mark_member_pending_update.revert(self.member_mock) mock_member_repo_update.assert_called_once_with( 'TEST', id=MEMBER_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.PoolRepository.update') def test_mark_pool_active_in_db(self, mock_pool_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_pool_active = (database_tasks.MarkPoolActiveInDB()) mark_pool_active.execute(POOL_ID) mock_pool_repo_update.assert_called_once_with( 'TEST', POOL_ID, provisioning_status=constants.ACTIVE) # Test the revert mock_pool_repo_update.reset_mock() mark_pool_active.revert(POOL_ID) mock_pool_repo_update.assert_called_once_with( 'TEST', id=POOL_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_pool_repo_update.reset_mock() mock_pool_repo_update.side_effect = Exception('fail') mark_pool_active.revert(POOL_ID) mock_pool_repo_update.assert_called_once_with( 'TEST', id=POOL_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.PoolRepository.update') def test_mark_pool_pending_create_in_db(self, mock_pool_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_pool_pending_create = (database_tasks.MarkPoolPendingCreateInDB()) mark_pool_pending_create.execute(POOL_ID) mock_pool_repo_update.assert_called_once_with( 'TEST', POOL_ID, provisioning_status=constants.PENDING_CREATE) # Test the revert mock_pool_repo_update.reset_mock() mark_pool_pending_create.revert(POOL_ID) mock_pool_repo_update.assert_called_once_with( 'TEST', id=POOL_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_pool_repo_update.reset_mock() mock_pool_repo_update.side_effect = Exception('fail') mark_pool_pending_create.revert(POOL_ID) mock_pool_repo_update.assert_called_once_with( 'TEST', id=POOL_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.PoolRepository.update') def test_mark_pool_pending_delete_in_db(self, mock_pool_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_pool_pending_delete = (database_tasks.MarkPoolPendingDeleteInDB()) mark_pool_pending_delete.execute(POOL_ID) mock_pool_repo_update.assert_called_once_with( 'TEST', POOL_ID, provisioning_status=constants.PENDING_DELETE) # Test the revert mock_pool_repo_update.reset_mock() mark_pool_pending_delete.revert(POOL_ID) mock_pool_repo_update.assert_called_once_with( 'TEST', id=POOL_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_pool_repo_update.reset_mock() mock_pool_repo_update.side_effect = Exception('fail') mark_pool_pending_delete.revert(POOL_ID) mock_pool_repo_update.assert_called_once_with( 'TEST', id=POOL_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.PoolRepository.update') def test_mark_pool_pending_update_in_db(self, mock_pool_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_pool_pending_update = (database_tasks. MarkPoolPendingUpdateInDB()) mark_pool_pending_update.execute(POOL_ID) mock_pool_repo_update.assert_called_once_with( 'TEST', POOL_ID, provisioning_status=constants.PENDING_UPDATE) # Test the revert mock_pool_repo_update.reset_mock() mark_pool_pending_update.revert(POOL_ID) mock_pool_repo_update.assert_called_once_with( 'TEST', id=POOL_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_pool_repo_update.reset_mock() mock_pool_repo_update.side_effect = Exception('fail') mark_pool_pending_update.revert(POOL_ID) mock_pool_repo_update.assert_called_once_with( 'TEST', id=POOL_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.MemberRepository.update_pool_members') def test_update_pool_members_operating_status_in_db( self, mock_member_repo_update_pool_members, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): update_members = database_tasks.UpdatePoolMembersOperatingStatusInDB() update_members.execute(POOL_ID, constants.ONLINE) mock_member_repo_update_pool_members.assert_called_once_with( 'TEST', POOL_ID, operating_status=constants.ONLINE)
# Copyright 2015 Hewlett-Packard Development Company, L.P. # # 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 random from cryptography import fernet import mock from oslo_db import exception as odb_exceptions from oslo_utils import uuidutils from sqlalchemy.orm import exc from taskflow.types import failure from octavia.common import constants from octavia.common import data_models from octavia.common import utils from octavia.controller.worker.v2.tasks import database_tasks from octavia.db import repositories as repo import octavia.tests.unit.base as base AMP_ID = uuidutils.generate_uuid() COMPUTE_ID = uuidutils.generate_uuid() LB_ID = uuidutils.generate_uuid() SERVER_GROUP_ID = uuidutils.generate_uuid() LB_NET_IP = '192.0.2.2' LISTENER_ID = uuidutils.generate_uuid() POOL_ID = uuidutils.generate_uuid() HM_ID = uuidutils.generate_uuid() MEMBER_ID = uuidutils.generate_uuid() PORT_ID = uuidutils.generate_uuid() SUBNET_ID = uuidutils.generate_uuid() VRRP_PORT_ID = uuidutils.generate_uuid() HA_PORT_ID = uuidutils.generate_uuid() L7POLICY_ID = uuidutils.generate_uuid() L7RULE_ID = uuidutils.generate_uuid() VIP_IP = '192.168.127.12' VRRP_IP = '172.16.31.10' HA_IP = '192.168.3.11' AMP_ROLE = 'FAKE_ROLE' VRRP_ID = random.randrange(255) VRRP_PRIORITY = random.randrange(100) CACHED_ZONE = 'zone1' IMAGE_ID = uuidutils.generate_uuid() COMPUTE_FLAVOR = uuidutils.generate_uuid() _amphora_mock = mock.MagicMock() _amphora_mock.id = AMP_ID _amphora_mock.compute_id = COMPUTE_ID _amphora_mock.lb_network_ip = LB_NET_IP _amphora_mock.vrrp_ip = VRRP_IP _amphora_mock.ha_ip = HA_IP _amphora_mock.ha_port_id = HA_PORT_ID _amphora_mock.vrrp_port_id = VRRP_PORT_ID _amphora_mock.role = AMP_ROLE _amphora_mock.vrrp_id = VRRP_ID _amphora_mock.vrrp_priority = VRRP_PRIORITY _amphorae = [_amphora_mock] _loadbalancer_mock = mock.MagicMock() _loadbalancer_mock.id = LB_ID _loadbalancer_mock.amphorae = [_amphora_mock] _l7policy_mock = mock.MagicMock() _l7policy_mock.id = L7POLICY_ID _l7rule_mock = mock.MagicMock() _l7rule_mock.id = L7RULE_ID _listener_mock = mock.MagicMock() _listener_to_dict_mock = mock.MagicMock( return_value={'id': LISTENER_ID}) _listener_mock.id = LISTENER_ID _listener_mock.to_dict = _listener_to_dict_mock _tf_failure_mock = mock.Mock(spec=failure.Failure) _vip_mock = mock.MagicMock() _vip_mock.port_id = PORT_ID _vip_mock.subnet_id = SUBNET_ID _vip_mock.ip_address = VIP_IP _vrrp_group_mock = mock.MagicMock() _cert_mock = mock.MagicMock() _compute_mock = mock.MagicMock() _compute_mock.lb_network_ip = LB_NET_IP _compute_mock.cached_zone = CACHED_ZONE _compute_mock.image_id = IMAGE_ID _compute_mock.compute_flavor = COMPUTE_FLAVOR @mock.patch('octavia.db.repositories.AmphoraRepository.delete') @mock.patch('octavia.db.repositories.AmphoraRepository.update') @mock.patch('octavia.db.repositories.ListenerRepository.update') @mock.patch('octavia.db.repositories.LoadBalancerRepository.update') @mock.patch('octavia.db.api.get_session', return_value='TEST') @mock.patch('octavia.controller.worker.v2.tasks.database_tasks.LOG') @mock.patch('oslo_utils.uuidutils.generate_uuid', return_value=AMP_ID) class TestDatabaseTasks(base.TestCase): def setUp(self): self.health_mon_mock = mock.MagicMock() self.health_mon_mock.id = HM_ID self.health_mon_mock.pool_id = POOL_ID self.listener_mock = mock.MagicMock() self.listener_mock.id = LISTENER_ID self.loadbalancer_mock = mock.MagicMock() self.loadbalancer_mock.id = LB_ID self.member_mock = mock.MagicMock() self.member_mock.id = MEMBER_ID self.db_pool_mock = mock.MagicMock() self.db_pool_mock.id = POOL_ID self.db_pool_mock.health_monitor = self.health_mon_mock self.member_mock = { constants.MEMBER_ID: MEMBER_ID, constants.POOL_ID: POOL_ID, } self.l7policy_mock = mock.MagicMock() self.l7policy_mock.id = L7POLICY_ID self.l7rule_mock = mock.MagicMock() self.l7rule_mock.id = L7RULE_ID self.l7rule_mock.l7policy = self.l7policy_mock super(TestDatabaseTasks, self).setUp() @mock.patch('octavia.db.repositories.AmphoraRepository.create', return_value=_amphora_mock) def test_create_amphora_in_db(self, mock_create, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): create_amp_in_db = database_tasks.CreateAmphoraInDB() amp_id = create_amp_in_db.execute() repo.AmphoraRepository.create.assert_called_once_with( 'TEST', id=AMP_ID, status=constants.PENDING_CREATE, cert_busy=False) self.assertEqual(_amphora_mock.id, amp_id) # Test the revert create_amp_in_db.revert(_tf_failure_mock) self.assertFalse(mock_amphora_repo_delete.called) mock_amphora_repo_delete.reset_mock() create_amp_in_db.revert(result='AMP') self.assertTrue(mock_amphora_repo_delete.called) mock_amphora_repo_delete.assert_called_once_with( 'TEST', id='AMP') # Test revert with exception mock_amphora_repo_delete.reset_mock() mock_amphora_repo_delete.side_effect = Exception('fail') create_amp_in_db.revert(result='AMP') self.assertTrue(mock_amphora_repo_delete.called) mock_amphora_repo_delete.assert_called_once_with( 'TEST', id='AMP') @mock.patch('octavia.db.repositories.ListenerRepository.delete') def test_delete_listener_in_db(self, mock_listener_repo_delete, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): delete_listener = database_tasks.DeleteListenerInDB() delete_listener.execute({constants.LISTENER_ID: LISTENER_ID}) repo.ListenerRepository.delete.assert_called_once_with( 'TEST', id=LISTENER_ID) # Test the revert repo.ListenerRepository.delete.reset_mock() delete_listener.revert({constants.LISTENER_ID: LISTENER_ID}) repo.ListenerRepository.delete.assert_not_called() @mock.patch('octavia.db.repositories.HealthMonitorRepository.update') @mock.patch('octavia.db.repositories.HealthMonitorRepository.delete') def test_delete_health_monitor_in_db(self, mock_health_mon_repo_delete, mock_health_mon_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): delete_health_mon = database_tasks.DeleteHealthMonitorInDB() delete_health_mon.execute(self.health_mon_mock) repo.HealthMonitorRepository.delete.assert_called_once_with( 'TEST', id=HM_ID) # Test the revert mock_health_mon_repo_delete.reset_mock() delete_health_mon.revert(self.health_mon_mock) repo.HealthMonitorRepository.update.assert_called_once_with( 'TEST', id=HM_ID, provisioning_status=constants.ERROR) # Test Not Found Exception mock_health_mon_repo_delete.reset_mock() mock_health_mon_repo_delete.side_effect = [exc.NoResultFound()] delete_health_mon.execute(self.health_mon_mock) repo.HealthMonitorRepository.delete.assert_called_once_with( 'TEST', id=HM_ID) @mock.patch('octavia.db.repositories.HealthMonitorRepository.update') @mock.patch('octavia.db.repositories.HealthMonitorRepository.delete') def test_delete_health_monitor_in_db_by_pool(self, mock_health_mon_repo_delete, mock_health_mon_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): delete_health_mon = database_tasks.DeleteHealthMonitorInDBByPool() delete_health_mon.execute(self.db_pool_mock) repo.HealthMonitorRepository.delete.assert_called_once_with( 'TEST', id=HM_ID) # Test the revert mock_health_mon_repo_delete.reset_mock() delete_health_mon.revert(self.db_pool_mock) repo.HealthMonitorRepository.update.assert_called_once_with( 'TEST', id=HM_ID, provisioning_status=constants.ERROR) # TODO(johnsom) fix once provisioning status added # repo.HealthMonitorRepository.update.assert_called_once_with( # 'TEST', # POOL_ID, # provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.MemberRepository.delete') def test_delete_member_in_db(self, mock_member_repo_delete, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): delete_member = database_tasks.DeleteMemberInDB() delete_member.execute(self.member_mock) repo.MemberRepository.delete.assert_called_once_with( 'TEST', id=MEMBER_ID) # Test the revert mock_member_repo_delete.reset_mock() delete_member.revert(self.member_mock) # TODO(johnsom) Fix # repo.MemberRepository.delete.assert_called_once_with( # 'TEST', # MEMBER_ID) @mock.patch('octavia.db.repositories.PoolRepository.delete') def test_delete_pool_in_db(self, mock_pool_repo_delete, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): delete_pool = database_tasks.DeletePoolInDB() delete_pool.execute(POOL_ID) repo.PoolRepository.delete.assert_called_once_with( 'TEST', id=POOL_ID) # Test the revert mock_pool_repo_delete.reset_mock() delete_pool.revert(POOL_ID) # TODO(johnsom) Fix # repo.PoolRepository.update.assert_called_once_with( # 'TEST', # POOL_ID, # operating_status=constants.ERROR) @mock.patch('octavia.db.repositories.L7PolicyRepository.delete') def test_delete_l7policy_in_db(self, mock_l7policy_repo_delete, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): delete_l7policy = database_tasks.DeleteL7PolicyInDB() delete_l7policy.execute(_l7policy_mock) repo.L7PolicyRepository.delete.assert_called_once_with( 'TEST', id=L7POLICY_ID) # Test the revert mock_l7policy_repo_delete.reset_mock() delete_l7policy.revert(_l7policy_mock) # TODO(sbalukoff) Fix # repo.ListenerRepository.update.assert_called_once_with( # 'TEST', # LISTENER_ID, # operating_status=constants.ERROR) @mock.patch('octavia.db.repositories.L7RuleRepository.delete') def test_delete_l7rule_in_db(self, mock_l7rule_repo_delete, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): delete_l7rule = database_tasks.DeleteL7RuleInDB() delete_l7rule.execute(_l7rule_mock) repo.L7RuleRepository.delete.assert_called_once_with( 'TEST', id=L7RULE_ID) # Test the revert mock_l7rule_repo_delete.reset_mock() delete_l7rule.revert(_l7rule_mock) # TODO(sbalukoff) Fix # repo.ListenerRepository.update.assert_called_once_with( # 'TEST', # LISTENER_ID, # operating_status=constants.ERROR) @mock.patch('octavia.db.repositories.AmphoraRepository.get', return_value=_amphora_mock) def test_reload_amphora(self, mock_amp_get, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): reload_amp = database_tasks.ReloadAmphora() amp = reload_amp.execute(AMP_ID) repo.AmphoraRepository.get.assert_called_once_with( 'TEST', id=AMP_ID) self.assertEqual(_amphora_mock, amp) @mock.patch('octavia.db.repositories.LoadBalancerRepository.get', return_value=_loadbalancer_mock) def test_reload_load_balancer(self, mock_lb_get, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): reload_lb = database_tasks.ReloadLoadBalancer() lb = reload_lb.execute(LB_ID) repo.LoadBalancerRepository.get.assert_called_once_with( 'TEST', id=LB_ID) self.assertEqual(_loadbalancer_mock, lb) @mock.patch('octavia.db.repositories.LoadBalancerRepository.get', return_value=_loadbalancer_mock) @mock.patch('octavia.db.repositories.VipRepository.update') def test_update_vip_after_allocation(self, mock_vip_update, mock_loadbalancer_get, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): update_vip = database_tasks.UpdateVIPAfterAllocation() loadbalancer = update_vip.execute(LB_ID, _vip_mock) self.assertEqual(_loadbalancer_mock, loadbalancer) mock_vip_update.assert_called_once_with('TEST', LB_ID, port_id=PORT_ID, subnet_id=SUBNET_ID, ip_address=VIP_IP) mock_loadbalancer_get.assert_called_once_with('TEST', id=LB_ID) def test_update_amphora_vip_data(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): update_amp_vip_data = database_tasks.UpdateAmphoraeVIPData() update_amp_vip_data.execute(_amphorae) mock_amphora_repo_update.assert_called_once_with( 'TEST', AMP_ID, vrrp_ip=VRRP_IP, ha_ip=HA_IP, vrrp_port_id=VRRP_PORT_ID, ha_port_id=HA_PORT_ID, vrrp_id=1) def test_update_amphora_vip_data2(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): update_amp_vip_data2 = database_tasks.UpdateAmphoraVIPData() update_amp_vip_data2.execute(_amphorae[0]) mock_amphora_repo_update.assert_called_once_with( 'TEST', AMP_ID, vrrp_ip=VRRP_IP, ha_ip=HA_IP, vrrp_port_id=VRRP_PORT_ID, ha_port_id=HA_PORT_ID, vrrp_id=1) def test_update_amp_failover_details(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): update_amp_fo_details = database_tasks.UpdateAmpFailoverDetails() update_amp_fo_details.execute(_amphora_mock, _amphora_mock) mock_amphora_repo_update.assert_called_once_with( 'TEST', AMP_ID, vrrp_ip=VRRP_IP, ha_ip=HA_IP, vrrp_port_id=VRRP_PORT_ID, ha_port_id=HA_PORT_ID, vrrp_id=VRRP_ID) @mock.patch('octavia.db.repositories.AmphoraRepository.associate') def test_associate_failover_amphora_with_lb_id( self, mock_associate, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): assoc_fo_amp_lb_id = database_tasks.AssociateFailoverAmphoraWithLBID() assoc_fo_amp_lb_id.execute(AMP_ID, LB_ID) mock_associate.assert_called_once_with('TEST', load_balancer_id=LB_ID, amphora_id=AMP_ID) # Test revert assoc_fo_amp_lb_id.revert(AMP_ID) mock_amphora_repo_update.assert_called_once_with('TEST', AMP_ID, loadbalancer_id=None) # Test revert with exception mock_amphora_repo_update.reset_mock() mock_amphora_repo_update.side_effect = Exception('fail') assoc_fo_amp_lb_id.revert(AMP_ID) mock_amphora_repo_update.assert_called_once_with('TEST', AMP_ID, loadbalancer_id=None) @mock.patch('octavia.db.repositories.AmphoraRepository.' 'allocate_and_associate', side_effect=[_amphora_mock, None]) def test_map_loadbalancer_to_amphora(self, mock_allocate_and_associate, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): map_lb_to_amp = database_tasks.MapLoadbalancerToAmphora() amp_id = map_lb_to_amp.execute(self.loadbalancer_mock.id) repo.AmphoraRepository.allocate_and_associate.assert_called_once_with( 'TEST', LB_ID, None) self.assertEqual(_amphora_mock.id, amp_id) amp_id = map_lb_to_amp.execute(self.loadbalancer_mock.id) self.assertIsNone(amp_id) # Test revert map_lb_to_amp.revert(None, self.loadbalancer_mock.id) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) # Test revert with exception repo.LoadBalancerRepository.update.reset_mock() mock_loadbalancer_repo_update.side_effect = Exception('fail') map_lb_to_amp.revert(None, self.loadbalancer_mock.id) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.AmphoraRepository.' 'allocate_and_associate', side_effect=[_amphora_mock, None]) def test_map_loadbalancer_to_amphora_with_az(self, mock_allocate_and_associate, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): map_lb_to_amp = database_tasks.MapLoadbalancerToAmphora() amp_id = map_lb_to_amp.execute( self.loadbalancer_mock.id, availability_zone={ constants.COMPUTE_ZONE: 'fakeaz'}) repo.AmphoraRepository.allocate_and_associate.assert_called_once_with( 'TEST', LB_ID, 'fakeaz') self.assertEqual(_amphora_mock.id, amp_id) amp_id = map_lb_to_amp.execute(self.loadbalancer_mock.id) self.assertIsNone(amp_id) # Test revert map_lb_to_amp.revert(None, self.loadbalancer_mock.id) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) # Test revert with exception repo.LoadBalancerRepository.update.reset_mock() mock_loadbalancer_repo_update.side_effect = Exception('fail') map_lb_to_amp.revert(None, self.loadbalancer_mock.id) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.AmphoraRepository.get', return_value=_amphora_mock) @mock.patch('octavia.db.repositories.LoadBalancerRepository.get', return_value=_loadbalancer_mock) def test_mark_lb_amphorae_deleted_in_db(self, mock_loadbalancer_repo_get, mock_amphora_repo_get, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_amp_deleted_in_db = (database_tasks. MarkLBAmphoraeDeletedInDB()) mark_amp_deleted_in_db.execute(_loadbalancer_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', id=AMP_ID, status=constants.DELETED) @mock.patch('octavia.db.repositories.AmphoraRepository.get', return_value=_amphora_mock) @mock.patch('octavia.db.repositories.LoadBalancerRepository.get', return_value=_loadbalancer_mock) def test_mark_amphora_allocated_in_db(self, mock_loadbalancer_repo_get, mock_amphora_repo_get, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_amp_allocated_in_db = (database_tasks. MarkAmphoraAllocatedInDB()) mark_amp_allocated_in_db.execute(_amphora_mock, self.loadbalancer_mock.id) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, status=constants.AMPHORA_ALLOCATED, compute_id=COMPUTE_ID, lb_network_ip=LB_NET_IP, load_balancer_id=LB_ID) # Test the revert mock_amphora_repo_update.reset_mock() mark_amp_allocated_in_db.revert(None, _amphora_mock, self.loadbalancer_mock.id) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', id=AMP_ID, status=constants.ERROR) # Test the revert with exception mock_amphora_repo_update.reset_mock() mock_amphora_repo_update.side_effect = Exception('fail') mark_amp_allocated_in_db.revert(None, _amphora_mock, self.loadbalancer_mock.id) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', id=AMP_ID, status=constants.ERROR) def test_mark_amphora_booting_in_db(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_amp_booting_in_db = database_tasks.MarkAmphoraBootingInDB() mark_amp_booting_in_db.execute(_amphora_mock.id, _amphora_mock.compute_id) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, status=constants.AMPHORA_BOOTING, compute_id=COMPUTE_ID) # Test the revert mock_amphora_repo_update.reset_mock() mark_amp_booting_in_db.revert(None, _amphora_mock.id, _amphora_mock.compute_id) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, status=constants.ERROR, compute_id=COMPUTE_ID) # Test the revert with exception mock_amphora_repo_update.reset_mock() mock_amphora_repo_update.side_effect = Exception('fail') mark_amp_booting_in_db.revert(None, _amphora_mock.id, _amphora_mock.compute_id) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, status=constants.ERROR, compute_id=COMPUTE_ID) def test_mark_amphora_deleted_in_db(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_amp_deleted_in_db = database_tasks.MarkAmphoraDeletedInDB() mark_amp_deleted_in_db.execute(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, status=constants.DELETED) # Test the revert mock_amphora_repo_update.reset_mock() mark_amp_deleted_in_db.revert(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', id=AMP_ID, status=constants.ERROR) # Test the revert with exception mock_amphora_repo_update.reset_mock() mock_amphora_repo_update.side_effect = Exception('fail') mark_amp_deleted_in_db.revert(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', id=AMP_ID, status=constants.ERROR) def test_mark_amphora_pending_delete_in_db(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_amp_pending_delete_in_db = (database_tasks. MarkAmphoraPendingDeleteInDB()) mark_amp_pending_delete_in_db.execute(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, status=constants.PENDING_DELETE) # Test the revert mock_amphora_repo_update.reset_mock() mark_amp_pending_delete_in_db.revert(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', id=AMP_ID, status=constants.ERROR) # Test the revert with exception mock_amphora_repo_update.reset_mock() mock_amphora_repo_update.side_effect = Exception('fail') mark_amp_pending_delete_in_db.revert(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', id=AMP_ID, status=constants.ERROR) def test_mark_amphora_pending_update_in_db(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_amp_pending_update_in_db = (database_tasks. MarkAmphoraPendingUpdateInDB()) mark_amp_pending_update_in_db.execute(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, status=constants.PENDING_UPDATE) # Test the revert mock_amphora_repo_update.reset_mock() mark_amp_pending_update_in_db.revert(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', id=AMP_ID, status=constants.ERROR) # Test the revert with exception mock_amphora_repo_update.reset_mock() mock_amphora_repo_update.side_effect = Exception('fail') mark_amp_pending_update_in_db.revert(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', id=AMP_ID, status=constants.ERROR) def test_mark_amphora_ready_in_db(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): _amphora_mock.lb_network_ip = LB_NET_IP mark_amp_ready_in_db = database_tasks.MarkAmphoraReadyInDB() mark_amp_ready_in_db.execute(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, status=constants.AMPHORA_READY, compute_id=COMPUTE_ID, lb_network_ip=LB_NET_IP) # Test the revert mock_amphora_repo_update.reset_mock() mark_amp_ready_in_db.revert(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, status=constants.ERROR, compute_id=COMPUTE_ID, lb_network_ip=LB_NET_IP) # Test the revert with exception mock_amphora_repo_update.reset_mock() mock_amphora_repo_update.side_effect = Exception('fail') mark_amp_ready_in_db.revert(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, status=constants.ERROR, compute_id=COMPUTE_ID, lb_network_ip=LB_NET_IP) @mock.patch('octavia.db.repositories.AmphoraRepository.get') def test_update_amphora_info(self, mock_amphora_repo_get, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): update_amphora_info = database_tasks.UpdateAmphoraInfo() update_amphora_info.execute(AMP_ID, _compute_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, lb_network_ip=LB_NET_IP, cached_zone=CACHED_ZONE, image_id=IMAGE_ID, compute_flavor=COMPUTE_FLAVOR) repo.AmphoraRepository.get.assert_called_once_with( 'TEST', id=AMP_ID) def test_mark_listener_deleted_in_db(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_listener_deleted = database_tasks.MarkListenerDeletedInDB() mark_listener_deleted.execute(self.listener_mock) repo.ListenerRepository.update.assert_called_once_with( 'TEST', LISTENER_ID, provisioning_status=constants.DELETED) # Test the revert mock_listener_repo_update.reset_mock() mark_listener_deleted.revert(self.listener_mock) repo.ListenerRepository.update.assert_called_once_with( 'TEST', id=LISTENER_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_listener_repo_update.reset_mock() mock_listener_repo_update.side_effect = Exception('fail') mark_listener_deleted.revert(self.listener_mock) repo.ListenerRepository.update.assert_called_once_with( 'TEST', id=LISTENER_ID, provisioning_status=constants.ERROR) def test_mark_listener_pending_deleted_in_db(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_listener_pending_delete = (database_tasks. MarkListenerPendingDeleteInDB()) mark_listener_pending_delete.execute(self.listener_mock) repo.ListenerRepository.update.assert_called_once_with( 'TEST', LISTENER_ID, provisioning_status=constants.PENDING_DELETE) # Test the revert mock_listener_repo_update.reset_mock() mark_listener_pending_delete.revert(self.listener_mock) repo.ListenerRepository.update.assert_called_once_with( 'TEST', id=LISTENER_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_listener_repo_update.reset_mock() mock_listener_repo_update.side_effect = Exception('fail') mark_listener_pending_delete.revert(self.listener_mock) repo.ListenerRepository.update.assert_called_once_with( 'TEST', id=LISTENER_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.ListenerRepository.' 'prov_status_active_if_not_error') def test_mark_lb_and_listeners_active_in_db(self, mock_list_not_error, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): listener_dict = {constants.LISTENER_ID: LISTENER_ID, constants.LOADBALANCER_ID: LB_ID} mark_lb_and_listeners_active = (database_tasks. MarkLBAndListenersActiveInDB()) mark_lb_and_listeners_active.execute(LB_ID, [listener_dict]) mock_list_not_error.assert_called_once_with('TEST', LISTENER_ID) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', LB_ID, provisioning_status=constants.ACTIVE) # Test with LB_ID from listeners mock_loadbalancer_repo_update.reset_mock() mock_list_not_error.reset_mock() listener_dict = {constants.LISTENER_ID: LISTENER_ID, constants.LOADBALANCER_ID: LB_ID} mark_lb_and_listeners_active = (database_tasks. MarkLBAndListenersActiveInDB()) mark_lb_and_listeners_active.execute(None, [listener_dict]) mock_list_not_error.assert_called_once_with('TEST', LISTENER_ID) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', LB_ID, provisioning_status=constants.ACTIVE) # Test with no LB_ID mock_loadbalancer_repo_update.reset_mock() mark_lb_and_listeners_active.execute(None, []) mock_loadbalancer_repo_update.assert_not_called() # Test the revert mock_loadbalancer_repo_update.reset_mock() mock_listener_repo_update.reset_mock() mark_lb_and_listeners_active.revert(LB_ID, [listener_dict]) repo.ListenerRepository.update.assert_called_once_with( 'TEST', id=LISTENER_ID, provisioning_status=constants.ERROR) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) # Test the revert LB_ID from listeners mock_loadbalancer_repo_update.reset_mock() mock_listener_repo_update.reset_mock() mark_lb_and_listeners_active.revert(None, [listener_dict]) repo.ListenerRepository.update.assert_called_once_with( 'TEST', id=LISTENER_ID, provisioning_status=constants.ERROR) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) # Test the revert no LB_ID mock_loadbalancer_repo_update.reset_mock() mock_listener_repo_update.reset_mock() mark_lb_and_listeners_active.revert(None, []) mock_loadbalancer_repo_update.assert_not_called() mock_listener_repo_update.assert_not_called() # Test the revert with exceptions mock_loadbalancer_repo_update.reset_mock() mock_loadbalancer_repo_update.side_effect = Exception('fail') mock_listener_repo_update.reset_mock() mock_listener_repo_update.side_effect = Exception('fail') mark_lb_and_listeners_active.revert(LB_ID, [listener_dict]) repo.ListenerRepository.update.assert_called_once_with( 'TEST', id=LISTENER_ID, provisioning_status=constants.ERROR) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.common.tls_utils.cert_parser.get_cert_expiration', return_value=_cert_mock) def test_update_amphora_db_cert_exp(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete, mock_get_cert_exp): update_amp_cert = database_tasks.UpdateAmphoraDBCertExpiration() key = utils.get_six_compatible_server_certs_key_passphrase() fer = fernet.Fernet(key) _pem_mock = fer.encrypt( utils.get_six_compatible_value('test_cert') ) update_amp_cert.execute(_amphora_mock.id, _pem_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, cert_expiration=_cert_mock) def test_update_amphora_cert_busy_to_false(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): amp_cert_busy_to_F = database_tasks.UpdateAmphoraCertBusyToFalse() amp_cert_busy_to_F.execute(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, cert_busy=False) def test_mark_LB_active_in_db(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_loadbalancer_active = database_tasks.MarkLBActiveInDB() mark_loadbalancer_active.execute(self.loadbalancer_mock) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', LB_ID, provisioning_status=constants.ACTIVE) self.assertEqual(0, repo.ListenerRepository.update.call_count) # Test the revert mock_loadbalancer_repo_update.reset_mock() mark_loadbalancer_active.revert(self.loadbalancer_mock) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) self.assertEqual(0, repo.ListenerRepository.update.call_count) # Test the revert with exception mock_loadbalancer_repo_update.reset_mock() mock_loadbalancer_repo_update.side_effect = Exception('fail') mark_loadbalancer_active.revert(self.loadbalancer_mock) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) self.assertEqual(0, repo.ListenerRepository.update.call_count) def test_mark_LB_active_in_db_by_listener(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): listener_dict = {'loadbalancer_id': LB_ID} mark_loadbalancer_active = database_tasks.MarkLBActiveInDBByListener() mark_loadbalancer_active.execute(listener_dict) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', LB_ID, provisioning_status=constants.ACTIVE) self.assertEqual(0, repo.ListenerRepository.update.call_count) # Test the revert mock_loadbalancer_repo_update.reset_mock() mark_loadbalancer_active.revert(listener_dict) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) self.assertEqual(0, repo.ListenerRepository.update.call_count) # Test the revert with exception mock_loadbalancer_repo_update.reset_mock() mock_loadbalancer_repo_update.side_effect = Exception('fail') mark_loadbalancer_active.revert(listener_dict) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) self.assertEqual(0, repo.ListenerRepository.update.call_count) def test_mark_LB_active_in_db_and_listeners(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): listeners = [data_models.Listener(id='listener1'), data_models.Listener(id='listener2')] lb = data_models.LoadBalancer(id=LB_ID, listeners=listeners) mark_lb_active = database_tasks.MarkLBActiveInDB(mark_subobjects=True) mark_lb_active.execute(lb) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', lb.id, provisioning_status=constants.ACTIVE) self.assertEqual(2, repo.ListenerRepository.update.call_count) repo.ListenerRepository.update.has_calls( [mock.call('TEST', listeners[0].id, provisioning_status=constants.ACTIVE), mock.call('TEST', listeners[1].id, provisioning_status=constants.ACTIVE)]) mock_loadbalancer_repo_update.reset_mock() mock_listener_repo_update.reset_mock() mark_lb_active.revert(lb) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=lb.id, provisioning_status=constants.ERROR) self.assertEqual(2, repo.ListenerRepository.update.call_count) repo.ListenerRepository.update.has_calls( [mock.call('TEST', listeners[0].id, provisioning_status=constants.ERROR), mock.call('TEST', listeners[1].id, provisioning_status=constants.ERROR)]) @mock.patch('octavia.db.repositories.PoolRepository.update') @mock.patch('octavia.db.repositories.MemberRepository.update') @mock.patch('octavia.db.repositories.HealthMonitorRepository.update') @mock.patch('octavia.db.repositories.L7PolicyRepository.update') @mock.patch('octavia.db.repositories.L7RuleRepository.update') def test_mark_LB_active_in_db_full_graph(self, mock_l7r_repo_update, mock_l7p_repo_update, mock_hm_repo_update, mock_member_repo_update, mock_pool_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): unused_pool = data_models.Pool(id='unused_pool') members1 = [{constants.MEMBER_ID: 'member1'}, {constants.MEMBER_ID: 'member2'}] health_monitor = data_models.HealthMonitor(id='hm1') default_pool = data_models.Pool(id='default_pool', members=members1, health_monitor=health_monitor) listener1 = data_models.Listener(id='listener1', default_pool=default_pool) members2 = [{constants.MEMBER_ID: 'member3'}, {constants.MEMBER_ID: 'member4'}] redirect_pool = data_models.Pool(id='redirect_pool', members=members2) l7rules = [data_models.L7Rule(id='rule1')] redirect_policy = data_models.L7Policy(id='redirect_policy', redirect_pool=redirect_pool, l7rules=l7rules) l7policies = [redirect_policy] listener2 = data_models.Listener(id='listener2', l7policies=l7policies) listener2.l7policies = l7policies listeners = [listener1, listener2] pools = [default_pool, redirect_pool, unused_pool] lb = data_models.LoadBalancer(id=LB_ID, listeners=listeners, pools=pools) mark_lb_active = database_tasks.MarkLBActiveInDB(mark_subobjects=True) mark_lb_active.execute(lb) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', lb.id, provisioning_status=constants.ACTIVE) self.assertEqual(2, repo.ListenerRepository.update.call_count) repo.ListenerRepository.update.has_calls( [mock.call('TEST', listeners[0].id, provisioning_status=constants.ACTIVE), mock.call('TEST', listeners[1].id, provisioning_status=constants.ACTIVE)]) self.assertEqual(2, repo.PoolRepository.update.call_count) repo.PoolRepository.update.has_calls( [mock.call('TEST', default_pool.id, provisioning_status=constants.ACTIVE), mock.call('TEST', redirect_pool.id, provisioning_status=constants.ACTIVE)]) self.assertEqual(1, repo.HealthMonitorRepository.update.call_count) repo.HealthMonitorRepository.update.has_calls( [mock.call('TEST', health_monitor.id, provisioning_status=constants.ACTIVE)]) self.assertEqual(1, repo.L7PolicyRepository.update.call_count) repo.L7PolicyRepository.update.has_calls( [mock.call('TEST', l7policies[0].id, provisioning_status=constants.ACTIVE)]) self.assertEqual(1, repo.L7RuleRepository.update.call_count) repo.L7RuleRepository.update.has_calls( [mock.call('TEST', l7rules[0].id, provisioning_status=constants.ACTIVE)]) mock_loadbalancer_repo_update.reset_mock() mock_listener_repo_update.reset_mock() mock_pool_repo_update.reset_mock() mock_member_repo_update.reset_mock() mock_hm_repo_update.reset_mock() mock_l7p_repo_update.reset_mock() mock_l7r_repo_update.reset_mock() mark_lb_active.revert(lb) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=lb.id, provisioning_status=constants.ERROR) self.assertEqual(2, repo.ListenerRepository.update.call_count) repo.ListenerRepository.update.has_calls( [mock.call('TEST', listeners[0].id, provisioning_status=constants.ERROR), mock.call('TEST', listeners[1].id, provisioning_status=constants.ERROR)]) self.assertEqual(2, repo.PoolRepository.update.call_count) repo.PoolRepository.update.has_calls( [mock.call('TEST', default_pool.id, provisioning_status=constants.ERROR), mock.call('TEST', redirect_pool.id, provisioning_status=constants.ERROR)]) self.assertEqual(1, repo.HealthMonitorRepository.update.call_count) repo.HealthMonitorRepository.update.has_calls( [mock.call('TEST', health_monitor.id, provisioning_status=constants.ERROR)]) self.assertEqual(1, repo.L7PolicyRepository.update.call_count) repo.L7PolicyRepository.update.has_calls( [mock.call('TEST', l7policies[0].id, provisioning_status=constants.ERROR)]) self.assertEqual(1, repo.L7RuleRepository.update.call_count) repo.L7RuleRepository.update.has_calls( [mock.call('TEST', l7rules[0].id, provisioning_status=constants.ERROR)]) def test_mark_LB_deleted_in_db(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_loadbalancer_deleted = database_tasks.MarkLBDeletedInDB() mark_loadbalancer_deleted.execute(self.loadbalancer_mock) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', LB_ID, provisioning_status=constants.DELETED) # Test the revert mock_loadbalancer_repo_update.reset_mock() mark_loadbalancer_deleted.revert(self.loadbalancer_mock) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_loadbalancer_repo_update.reset_mock() mock_loadbalancer_repo_update.side_effect = Exception('fail') mark_loadbalancer_deleted.revert(self.loadbalancer_mock) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) def test_mark_LB_pending_deleted_in_db(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_loadbalancer_pending_delete = (database_tasks. MarkLBPendingDeleteInDB()) mark_loadbalancer_pending_delete.execute(self.loadbalancer_mock) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', LB_ID, provisioning_status=constants.PENDING_DELETE) # Test the revert mock_loadbalancer_repo_update.reset_mock() mark_loadbalancer_pending_delete.revert(self.loadbalancer_mock) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_loadbalancer_repo_update.reset_mock() mock_loadbalancer_repo_update.side_effect = Exception('fail') mark_loadbalancer_pending_delete.revert(self.loadbalancer_mock) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.HealthMonitorRepository.update') def test_update_health_monitor_in_db(self, mock_health_mon_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): update_health_mon = database_tasks.UpdateHealthMonInDB() update_health_mon.execute(self.health_mon_mock, {'delay': 1, 'timeout': 2}) repo.HealthMonitorRepository.update.assert_called_once_with( 'TEST', HM_ID, delay=1, timeout=2) # Test the revert mock_health_mon_repo_update.reset_mock() update_health_mon.revert(self.health_mon_mock) repo.HealthMonitorRepository.update.assert_called_once_with( 'TEST', HM_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_health_mon_repo_update.reset_mock() mock_health_mon_repo_update.side_effect = Exception('fail') update_health_mon.revert(self.health_mon_mock) repo.HealthMonitorRepository.update.assert_called_once_with( 'TEST', HM_ID, provisioning_status=constants.ERROR) def test_update_load_balancer_in_db(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): update_load_balancer = database_tasks.UpdateLoadbalancerInDB() update_load_balancer.execute(self.loadbalancer_mock, {'name': 'test', 'description': 'test2'}) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', LB_ID, name='test', description='test2') # Test the revert mock_loadbalancer_repo_update.reset_mock() update_load_balancer.revert(self.loadbalancer_mock) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_loadbalancer_repo_update.reset_mock() mock_loadbalancer_repo_update.side_effect = Exception('fail') update_load_balancer.revert(self.loadbalancer_mock) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.VipRepository.update') def test_update_vip_in_db_during_update_loadbalancer(self, mock_vip_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_lb_update, mock_listener_update, mock_amphora_update, mock_amphora_delete): self.loadbalancer_mock.vip.load_balancer_id = LB_ID update_load_balancer = database_tasks.UpdateLoadbalancerInDB() update_load_balancer.execute(self.loadbalancer_mock, {'name': 'test', 'description': 'test2', 'vip': {'qos_policy_id': 'fool'}}) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', LB_ID, name='test', description='test2') repo.VipRepository.update.assert_called_once_with('TEST', LB_ID, qos_policy_id='fool') def test_update_listener_in_db(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): update_listener = database_tasks.UpdateListenerInDB() listener_dict = {constants.LISTENER_ID: LISTENER_ID} update_listener.execute(listener_dict, {'name': 'test', 'description': 'test2'}) repo.ListenerRepository.update.assert_called_once_with( 'TEST', LISTENER_ID, name='test', description='test2') # Test the revert mock_listener_repo_update.reset_mock() update_listener.revert(listener_dict) repo.ListenerRepository.update.assert_called_once_with( 'TEST', id=LISTENER_ID, provisioning_status=constants.ERROR) # Test the revert mock_listener_repo_update.reset_mock() mock_listener_repo_update.side_effect = Exception('fail') update_listener.revert(listener_dict) repo.ListenerRepository.update.assert_called_once_with( 'TEST', id=LISTENER_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.MemberRepository.update') def test_update_member_in_db(self, mock_member_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): update_member = database_tasks.UpdateMemberInDB() update_member.execute(self.member_mock, {'weight': 1, 'ip_address': '10.1.0.0'}) repo.MemberRepository.update.assert_called_once_with( 'TEST', MEMBER_ID, weight=1, ip_address='10.1.0.0') # Test the revert mock_member_repo_update.reset_mock() update_member.revert(self.member_mock) repo.MemberRepository.update.assert_called_once_with( 'TEST', MEMBER_ID, provisioning_status=constants.ERROR) # Test the revert mock_member_repo_update.reset_mock() mock_member_repo_update.side_effect = Exception('fail') update_member.revert(self.member_mock) repo.MemberRepository.update.assert_called_once_with( 'TEST', MEMBER_ID, provisioning_status=constants.ERROR) @mock.patch( 'octavia.db.repositories.Repositories.update_pool_and_sp') def test_update_pool_in_db(self, mock_repos_pool_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): sp_dict = {'type': 'SOURCE_IP', 'cookie_name': None} update_dict = {'name': 'test', 'description': 'test2', 'session_persistence': sp_dict} update_pool = database_tasks.UpdatePoolInDB() update_pool.execute(POOL_ID, update_dict) repo.Repositories.update_pool_and_sp.assert_called_once_with( 'TEST', POOL_ID, update_dict) # Test the revert mock_repos_pool_update.reset_mock() update_pool.revert(POOL_ID) repo.Repositories.update_pool_and_sp.assert_called_once_with( 'TEST', POOL_ID, {'provisioning_status': constants.ERROR}) # Test the revert with exception mock_repos_pool_update.reset_mock() mock_repos_pool_update.side_effect = Exception('fail') update_pool.revert(POOL_ID) repo.Repositories.update_pool_and_sp.assert_called_once_with( 'TEST', POOL_ID, {'provisioning_status': constants.ERROR}) @mock.patch('octavia.db.repositories.L7PolicyRepository.update') def test_update_l7policy_in_db(self, mock_l7policy_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): update_l7policy = database_tasks.UpdateL7PolicyInDB() update_l7policy.execute(self.l7policy_mock, {'action': constants.L7POLICY_ACTION_REJECT}) repo.L7PolicyRepository.update.assert_called_once_with( 'TEST', L7POLICY_ID, action=constants.L7POLICY_ACTION_REJECT) # Test the revert mock_l7policy_repo_update.reset_mock() update_l7policy.revert(self.l7policy_mock) repo.L7PolicyRepository.update.assert_called_once_with( 'TEST', L7POLICY_ID, provisioning_status=constants.ERROR) # Test the revert mock_l7policy_repo_update.reset_mock() mock_l7policy_repo_update.side_effect = Exception('fail') update_l7policy.revert(self.l7policy_mock) repo.L7PolicyRepository.update.assert_called_once_with( 'TEST', L7POLICY_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.L7RuleRepository.update') @mock.patch('octavia.db.repositories.L7PolicyRepository.update') def test_update_l7rule_in_db(self, mock_l7rule_repo_update, mock_l7policy_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): update_l7rule = database_tasks.UpdateL7RuleInDB() update_l7rule.execute( self.l7rule_mock, {'type': constants.L7RULE_TYPE_PATH, 'compare_type': constants.L7RULE_COMPARE_TYPE_STARTS_WITH, 'value': '/api'}) repo.L7RuleRepository.update.assert_called_once_with( 'TEST', L7RULE_ID, type=constants.L7RULE_TYPE_PATH, compare_type=constants.L7RULE_COMPARE_TYPE_STARTS_WITH, value='/api') # Test the revert mock_l7rule_repo_update.reset_mock() update_l7rule.revert(self.l7rule_mock) repo.L7PolicyRepository.update.assert_called_once_with( 'TEST', L7POLICY_ID, provisioning_status=constants.ERROR) # Test the revert mock_l7rule_repo_update.reset_mock() mock_l7rule_repo_update.side_effect = Exception('fail') update_l7rule.revert(self.l7rule_mock) repo.L7PolicyRepository.update.assert_called_once_with( 'TEST', L7POLICY_ID, provisioning_status=constants.ERROR) def test_get_amphora_details(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): get_amp_details = database_tasks.GetAmphoraDetails() new_amp = get_amp_details.execute(_amphora_mock) self.assertEqual(AMP_ID, new_amp.id) self.assertEqual(VRRP_IP, new_amp.vrrp_ip) self.assertEqual(HA_IP, new_amp.ha_ip) self.assertEqual(VRRP_PORT_ID, new_amp.vrrp_port_id) self.assertEqual(AMP_ROLE, new_amp.role) self.assertEqual(VRRP_ID, new_amp.vrrp_id) self.assertEqual(VRRP_PRIORITY, new_amp.vrrp_priority) def test_mark_amphora_role_indb(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_amp_master_indb = database_tasks.MarkAmphoraMasterInDB() mark_amp_master_indb.execute(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, role='MASTER', vrrp_priority=constants.ROLE_MASTER_PRIORITY) mock_amphora_repo_update.reset_mock() mark_amp_master_indb.revert("BADRESULT", _amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, role=None, vrrp_priority=None) mock_amphora_repo_update.reset_mock() failure_obj = failure.Failure.from_exception(Exception("TESTEXCEPT")) mark_amp_master_indb.revert(failure_obj, _amphora_mock) self.assertFalse(repo.AmphoraRepository.update.called) mock_amphora_repo_update.reset_mock() mark_amp_backup_indb = database_tasks.MarkAmphoraBackupInDB() mark_amp_backup_indb.execute(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, role='BACKUP', vrrp_priority=constants.ROLE_BACKUP_PRIORITY) mock_amphora_repo_update.reset_mock() mark_amp_backup_indb.revert("BADRESULT", _amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, role=None, vrrp_priority=None) mock_amphora_repo_update.reset_mock() mark_amp_standalone_indb = database_tasks.MarkAmphoraStandAloneInDB() mark_amp_standalone_indb.execute(_amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, role='STANDALONE', vrrp_priority=None) mock_amphora_repo_update.reset_mock() mark_amp_standalone_indb.revert("BADRESULT", _amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, role=None, vrrp_priority=None) # Test revert with exception mock_amphora_repo_update.reset_mock() mock_amphora_repo_update.side_effect = Exception('fail') mark_amp_standalone_indb.revert("BADRESULT", _amphora_mock) repo.AmphoraRepository.update.assert_called_once_with( 'TEST', AMP_ID, role=None, vrrp_priority=None) @mock.patch('octavia.db.repositories.AmphoraRepository.get') def test_get_amphorae_from_loadbalancer(self, mock_amphora_get, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): amp1 = mock.MagicMock() amp1.id = uuidutils.generate_uuid() amp2 = mock.MagicMock() amp2.id = uuidutils.generate_uuid() lb = mock.MagicMock() lb.amphorae = [amp1, amp2] mock_amphora_get.side_effect = [_amphora_mock, None] get_amps_from_lb_obj = database_tasks.GetAmphoraeFromLoadbalancer() result = get_amps_from_lb_obj.execute(lb) self.assertEqual([_amphora_mock], result) @mock.patch('octavia.db.repositories.ListenerRepository.get') def test_get_listeners_from_loadbalancer(self, mock_listener_get, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mock_listener_get.return_value = _listener_mock _loadbalancer_mock.listeners = [_listener_mock] get_list_from_lb_obj = database_tasks.GetListenersFromLoadbalancer() result = get_list_from_lb_obj.execute(_loadbalancer_mock) mock_listener_get.assert_called_once_with('TEST', id=_listener_mock.id) self.assertEqual([{constants.LISTENER_ID: LISTENER_ID}], result) def test_get_vip_from_loadbalancer(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): _loadbalancer_mock.vip = _vip_mock get_vip_from_lb_obj = database_tasks.GetVipFromLoadbalancer() result = get_vip_from_lb_obj.execute(_loadbalancer_mock) self.assertEqual(_vip_mock, result) @mock.patch('octavia.db.repositories.VRRPGroupRepository.create') def test_create_vrrp_group_for_lb(self, mock_vrrp_group_create, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mock_get_session.side_effect = ['TEST', odb_exceptions.DBDuplicateEntry] create_vrrp_group = database_tasks.CreateVRRPGroupForLB() create_vrrp_group.execute(_loadbalancer_mock) mock_vrrp_group_create.assert_called_once_with( 'TEST', load_balancer_id=LB_ID, vrrp_group_name=LB_ID.replace('-', ''), vrrp_auth_type=constants.VRRP_AUTH_DEFAULT, vrrp_auth_pass=mock_generate_uuid.return_value.replace('-', '')[0:7], advert_int=1) create_vrrp_group.execute(_loadbalancer_mock) @mock.patch('octavia.db.repositories.AmphoraHealthRepository.delete') def test_disable_amphora_health_monitoring(self, mock_amp_health_repo_delete, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): disable_amp_health = database_tasks.DisableAmphoraHealthMonitoring() disable_amp_health.execute(_amphora_mock) mock_amp_health_repo_delete.assert_called_once_with( 'TEST', amphora_id=AMP_ID) @mock.patch('octavia.db.repositories.AmphoraHealthRepository.delete') def test_disable_lb_amphorae_health_monitoring( self, mock_amp_health_repo_delete, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): disable_amp_health = ( database_tasks.DisableLBAmphoraeHealthMonitoring()) disable_amp_health.execute(_loadbalancer_mock) mock_amp_health_repo_delete.assert_called_once_with( 'TEST', amphora_id=AMP_ID) @mock.patch('octavia.db.repositories.AmphoraHealthRepository.update') def test_mark_amphora_health_monitoring_busy(self, mock_amp_health_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_busy = database_tasks.MarkAmphoraHealthBusy() mark_busy.execute(_amphora_mock) mock_amp_health_repo_update.assert_called_once_with( 'TEST', amphora_id=AMP_ID, busy=True) @mock.patch('octavia.db.repositories.AmphoraHealthRepository.update') def test_mark_lb_amphorae_health_monitoring_busy( self, mock_amp_health_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_busy = ( database_tasks.MarkLBAmphoraeHealthBusy()) mark_busy.execute(_loadbalancer_mock) mock_amp_health_repo_update.assert_called_once_with( 'TEST', amphora_id=AMP_ID, busy=True) def test_update_lb_server_group_in_db(self, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): update_server_group_info = database_tasks.UpdateLBServerGroupInDB() update_server_group_info.execute(LB_ID, SERVER_GROUP_ID) repo.LoadBalancerRepository.update.assert_called_once_with( 'TEST', id=LB_ID, server_group_id=SERVER_GROUP_ID) # Test the revert mock_listener_repo_update.reset_mock() update_server_group_info.revert(LB_ID, SERVER_GROUP_ID) # Test the revert with exception mock_listener_repo_update.reset_mock() mock_loadbalancer_repo_update.side_effect = Exception('fail') update_server_group_info.revert(LB_ID, SERVER_GROUP_ID) @mock.patch('octavia.db.repositories.HealthMonitorRepository.update') def test_mark_health_mon_active_in_db(self, mock_health_mon_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_health_mon_active = (database_tasks.MarkHealthMonitorActiveInDB()) mark_health_mon_active.execute(self.health_mon_mock) mock_health_mon_repo_update.assert_called_once_with( 'TEST', HM_ID, operating_status=constants.ONLINE, provisioning_status=constants.ACTIVE) # Test the revert mock_health_mon_repo_update.reset_mock() mark_health_mon_active.revert(self.health_mon_mock) mock_health_mon_repo_update.assert_called_once_with( 'TEST', id=HM_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_health_mon_repo_update.reset_mock() mock_health_mon_repo_update.side_effect = Exception('fail') mark_health_mon_active.revert(self.health_mon_mock) mock_health_mon_repo_update.assert_called_once_with( 'TEST', id=HM_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.HealthMonitorRepository.update') def test_mark_health_mon_pending_create_in_db( self, mock_health_mon_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_health_mon_pending_create = (database_tasks. MarkHealthMonitorPendingCreateInDB()) mark_health_mon_pending_create.execute(self.health_mon_mock) mock_health_mon_repo_update.assert_called_once_with( 'TEST', HM_ID, provisioning_status=constants.PENDING_CREATE) # Test the revert mock_health_mon_repo_update.reset_mock() mark_health_mon_pending_create.revert(self.health_mon_mock) mock_health_mon_repo_update.assert_called_once_with( 'TEST', id=HM_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_health_mon_repo_update.reset_mock() mock_health_mon_repo_update.side_effect = Exception('fail') mark_health_mon_pending_create.revert(self.health_mon_mock) mock_health_mon_repo_update.assert_called_once_with( 'TEST', id=HM_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.HealthMonitorRepository.update') def test_mark_health_mon_pending_delete_in_db( self, mock_health_mon_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_health_mon_pending_delete = (database_tasks. MarkHealthMonitorPendingDeleteInDB()) mark_health_mon_pending_delete.execute(self.health_mon_mock) mock_health_mon_repo_update.assert_called_once_with( 'TEST', HM_ID, provisioning_status=constants.PENDING_DELETE) # Test the revert mock_health_mon_repo_update.reset_mock() mark_health_mon_pending_delete.revert(self.health_mon_mock) mock_health_mon_repo_update.assert_called_once_with( 'TEST', id=HM_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_health_mon_repo_update.reset_mock() mock_health_mon_repo_update.side_effect = Exception('fail') mark_health_mon_pending_delete.revert(self.health_mon_mock) mock_health_mon_repo_update.assert_called_once_with( 'TEST', id=HM_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.HealthMonitorRepository.update') def test_mark_health_mon_pending_update_in_db( self, mock_health_mon_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_health_mon_pending_update = (database_tasks. MarkHealthMonitorPendingUpdateInDB()) mark_health_mon_pending_update.execute(self.health_mon_mock) mock_health_mon_repo_update.assert_called_once_with( 'TEST', HM_ID, provisioning_status=constants.PENDING_UPDATE) # Test the revert mock_health_mon_repo_update.reset_mock() mark_health_mon_pending_update.revert(self.health_mon_mock) mock_health_mon_repo_update.assert_called_once_with( 'TEST', id=HM_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_health_mon_repo_update.reset_mock() mock_health_mon_repo_update.side_effect = Exception('fail') mark_health_mon_pending_update.revert(self.health_mon_mock) mock_health_mon_repo_update.assert_called_once_with( 'TEST', id=HM_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.L7PolicyRepository.update') def test_mark_l7policy_active_in_db(self, mock_l7policy_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_l7policy_active = (database_tasks.MarkL7PolicyActiveInDB()) mark_l7policy_active.execute(self.l7policy_mock) mock_l7policy_repo_update.assert_called_once_with( 'TEST', L7POLICY_ID, provisioning_status=constants.ACTIVE, operating_status=constants.ONLINE) # Test the revert mock_l7policy_repo_update.reset_mock() mark_l7policy_active.revert(self.l7policy_mock) mock_l7policy_repo_update.assert_called_once_with( 'TEST', id=L7POLICY_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_l7policy_repo_update.reset_mock() mock_l7policy_repo_update.side_effect = Exception('fail') mark_l7policy_active.revert(self.l7policy_mock) mock_l7policy_repo_update.assert_called_once_with( 'TEST', id=L7POLICY_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.L7PolicyRepository.update') def test_mark_l7policy_pending_create_in_db(self, mock_l7policy_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_l7policy_pending_create = (database_tasks. MarkL7PolicyPendingCreateInDB()) mark_l7policy_pending_create.execute(self.l7policy_mock) mock_l7policy_repo_update.assert_called_once_with( 'TEST', L7POLICY_ID, provisioning_status=constants.PENDING_CREATE) # Test the revert mock_l7policy_repo_update.reset_mock() mark_l7policy_pending_create.revert(self.l7policy_mock) mock_l7policy_repo_update.assert_called_once_with( 'TEST', id=L7POLICY_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_l7policy_repo_update.reset_mock() mock_l7policy_repo_update.side_effect = Exception('fail') mark_l7policy_pending_create.revert(self.l7policy_mock) mock_l7policy_repo_update.assert_called_once_with( 'TEST', id=L7POLICY_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.L7PolicyRepository.update') def test_mark_l7policy_pending_delete_in_db(self, mock_l7policy_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_l7policy_pending_delete = (database_tasks. MarkL7PolicyPendingDeleteInDB()) mark_l7policy_pending_delete.execute(self.l7policy_mock) mock_l7policy_repo_update.assert_called_once_with( 'TEST', L7POLICY_ID, provisioning_status=constants.PENDING_DELETE) # Test the revert mock_l7policy_repo_update.reset_mock() mark_l7policy_pending_delete.revert(self.l7policy_mock) mock_l7policy_repo_update.assert_called_once_with( 'TEST', id=L7POLICY_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_l7policy_repo_update.reset_mock() mock_l7policy_repo_update.side_effect = Exception('fail') mark_l7policy_pending_delete.revert(self.l7policy_mock) mock_l7policy_repo_update.assert_called_once_with( 'TEST', id=L7POLICY_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.L7PolicyRepository.update') def test_mark_l7policy_pending_update_in_db(self, mock_l7policy_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_l7policy_pending_update = (database_tasks. MarkL7PolicyPendingUpdateInDB()) mark_l7policy_pending_update.execute(self.l7policy_mock) mock_l7policy_repo_update.assert_called_once_with( 'TEST', L7POLICY_ID, provisioning_status=constants.PENDING_UPDATE) # Test the revert mock_l7policy_repo_update.reset_mock() mark_l7policy_pending_update.revert(self.l7policy_mock) mock_l7policy_repo_update.assert_called_once_with( 'TEST', id=L7POLICY_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_l7policy_repo_update.reset_mock() mock_l7policy_repo_update.side_effect = Exception('fail') mark_l7policy_pending_update.revert(self.l7policy_mock) mock_l7policy_repo_update.assert_called_once_with( 'TEST', id=L7POLICY_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.L7RuleRepository.update') def test_mark_l7rule_active_in_db(self, mock_l7rule_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_l7rule_active = (database_tasks.MarkL7RuleActiveInDB()) mark_l7rule_active.execute(self.l7rule_mock) mock_l7rule_repo_update.assert_called_once_with( 'TEST', L7RULE_ID, provisioning_status=constants.ACTIVE, operating_status=constants.ONLINE) # Test the revert mock_l7rule_repo_update.reset_mock() mark_l7rule_active.revert(self.l7rule_mock) mock_l7rule_repo_update.assert_called_once_with( 'TEST', id=L7RULE_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_l7rule_repo_update.reset_mock() mock_l7rule_repo_update.side_effect = Exception('fail') mark_l7rule_active.revert(self.l7rule_mock) mock_l7rule_repo_update.assert_called_once_with( 'TEST', id=L7RULE_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.L7RuleRepository.update') def test_mark_l7rule_pending_create_in_db(self, mock_l7rule_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_l7rule_pending_create = (database_tasks. MarkL7RulePendingCreateInDB()) mark_l7rule_pending_create.execute(self.l7rule_mock) mock_l7rule_repo_update.assert_called_once_with( 'TEST', L7RULE_ID, provisioning_status=constants.PENDING_CREATE) # Test the revert mock_l7rule_repo_update.reset_mock() mark_l7rule_pending_create.revert(self.l7rule_mock) mock_l7rule_repo_update.assert_called_once_with( 'TEST', id=L7RULE_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_l7rule_repo_update.reset_mock() mock_l7rule_repo_update.side_effect = Exception('fail') mark_l7rule_pending_create.revert(self.l7rule_mock) mock_l7rule_repo_update.assert_called_once_with( 'TEST', id=L7RULE_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.L7RuleRepository.update') def test_mark_l7rule_pending_delete_in_db(self, mock_l7rule_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_l7rule_pending_delete = (database_tasks. MarkL7RulePendingDeleteInDB()) mark_l7rule_pending_delete.execute(self.l7rule_mock) mock_l7rule_repo_update.assert_called_once_with( 'TEST', L7RULE_ID, provisioning_status=constants.PENDING_DELETE) # Test the revert mock_l7rule_repo_update.reset_mock() mark_l7rule_pending_delete.revert(self.l7rule_mock) mock_l7rule_repo_update.assert_called_once_with( 'TEST', id=L7RULE_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_l7rule_repo_update.reset_mock() mock_l7rule_repo_update.side_effect = Exception('fail') mark_l7rule_pending_delete.revert(self.l7rule_mock) mock_l7rule_repo_update.assert_called_once_with( 'TEST', id=L7RULE_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.L7RuleRepository.update') def test_mark_l7rule_pending_update_in_db(self, mock_l7rule_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_l7rule_pending_update = (database_tasks. MarkL7RulePendingUpdateInDB()) mark_l7rule_pending_update.execute(self.l7rule_mock) mock_l7rule_repo_update.assert_called_once_with( 'TEST', L7RULE_ID, provisioning_status=constants.PENDING_UPDATE) # Test the revert mock_l7rule_repo_update.reset_mock() mark_l7rule_pending_update.revert(self.l7rule_mock) mock_l7rule_repo_update.assert_called_once_with( 'TEST', id=L7RULE_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_l7rule_repo_update.reset_mock() mock_l7rule_repo_update.side_effect = Exception('fail') mark_l7rule_pending_update.revert(self.l7rule_mock) mock_l7rule_repo_update.assert_called_once_with( 'TEST', id=L7RULE_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.MemberRepository.update') def test_mark_member_active_in_db(self, mock_member_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_member_active = (database_tasks.MarkMemberActiveInDB()) mark_member_active.execute(self.member_mock) mock_member_repo_update.assert_called_once_with( 'TEST', MEMBER_ID, provisioning_status=constants.ACTIVE) # Test the revert mock_member_repo_update.reset_mock() mark_member_active.revert(self.member_mock) mock_member_repo_update.assert_called_once_with( 'TEST', id=MEMBER_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_member_repo_update.reset_mock() mock_member_repo_update.side_effect = Exception('fail') mark_member_active.revert(self.member_mock) mock_member_repo_update.assert_called_once_with( 'TEST', id=MEMBER_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.MemberRepository.update') def test_mark_member_pending_create_in_db(self, mock_member_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_member_pending_create = (database_tasks. MarkMemberPendingCreateInDB()) mark_member_pending_create.execute(self.member_mock) mock_member_repo_update.assert_called_once_with( 'TEST', MEMBER_ID, provisioning_status=constants.PENDING_CREATE) # Test the revert mock_member_repo_update.reset_mock() mark_member_pending_create.revert(self.member_mock) mock_member_repo_update.assert_called_once_with( 'TEST', id=MEMBER_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_member_repo_update.reset_mock() mock_member_repo_update.side_effect = Exception('fail') mark_member_pending_create.revert(self.member_mock) mock_member_repo_update.assert_called_once_with( 'TEST', id=MEMBER_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.MemberRepository.update') def test_mark_member_pending_delete_in_db(self, mock_member_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_member_pending_delete = (database_tasks. MarkMemberPendingDeleteInDB()) mark_member_pending_delete.execute(self.member_mock) mock_member_repo_update.assert_called_once_with( 'TEST', MEMBER_ID, provisioning_status=constants.PENDING_DELETE) # Test the revert mock_member_repo_update.reset_mock() mark_member_pending_delete.revert(self.member_mock) mock_member_repo_update.assert_called_once_with( 'TEST', id=MEMBER_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_member_repo_update.reset_mock() mock_member_repo_update.side_effect = Exception('fail') mark_member_pending_delete.revert(self.member_mock) mock_member_repo_update.assert_called_once_with( 'TEST', id=MEMBER_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.MemberRepository.update') def test_mark_member_pending_update_in_db(self, mock_member_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_member_pending_update = (database_tasks. MarkMemberPendingUpdateInDB()) mark_member_pending_update.execute(self.member_mock) mock_member_repo_update.assert_called_once_with( 'TEST', MEMBER_ID, provisioning_status=constants.PENDING_UPDATE) # Test the revert mock_member_repo_update.reset_mock() mark_member_pending_update.revert(self.member_mock) mock_member_repo_update.assert_called_once_with( 'TEST', id=MEMBER_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_member_repo_update.reset_mock() mock_member_repo_update.side_effect = Exception('fail') mark_member_pending_update.revert(self.member_mock) mock_member_repo_update.assert_called_once_with( 'TEST', id=MEMBER_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.PoolRepository.update') def test_mark_pool_active_in_db(self, mock_pool_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_pool_active = (database_tasks.MarkPoolActiveInDB()) mark_pool_active.execute(POOL_ID) mock_pool_repo_update.assert_called_once_with( 'TEST', POOL_ID, provisioning_status=constants.ACTIVE) # Test the revert mock_pool_repo_update.reset_mock() mark_pool_active.revert(POOL_ID) mock_pool_repo_update.assert_called_once_with( 'TEST', id=POOL_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_pool_repo_update.reset_mock() mock_pool_repo_update.side_effect = Exception('fail') mark_pool_active.revert(POOL_ID) mock_pool_repo_update.assert_called_once_with( 'TEST', id=POOL_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.PoolRepository.update') def test_mark_pool_pending_create_in_db(self, mock_pool_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_pool_pending_create = (database_tasks.MarkPoolPendingCreateInDB()) mark_pool_pending_create.execute(POOL_ID) mock_pool_repo_update.assert_called_once_with( 'TEST', POOL_ID, provisioning_status=constants.PENDING_CREATE) # Test the revert mock_pool_repo_update.reset_mock() mark_pool_pending_create.revert(POOL_ID) mock_pool_repo_update.assert_called_once_with( 'TEST', id=POOL_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_pool_repo_update.reset_mock() mock_pool_repo_update.side_effect = Exception('fail') mark_pool_pending_create.revert(POOL_ID) mock_pool_repo_update.assert_called_once_with( 'TEST', id=POOL_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.PoolRepository.update') def test_mark_pool_pending_delete_in_db(self, mock_pool_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_pool_pending_delete = (database_tasks.MarkPoolPendingDeleteInDB()) mark_pool_pending_delete.execute(POOL_ID) mock_pool_repo_update.assert_called_once_with( 'TEST', POOL_ID, provisioning_status=constants.PENDING_DELETE) # Test the revert mock_pool_repo_update.reset_mock() mark_pool_pending_delete.revert(POOL_ID) mock_pool_repo_update.assert_called_once_with( 'TEST', id=POOL_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_pool_repo_update.reset_mock() mock_pool_repo_update.side_effect = Exception('fail') mark_pool_pending_delete.revert(POOL_ID) mock_pool_repo_update.assert_called_once_with( 'TEST', id=POOL_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.PoolRepository.update') def test_mark_pool_pending_update_in_db(self, mock_pool_repo_update, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): mark_pool_pending_update = (database_tasks. MarkPoolPendingUpdateInDB()) mark_pool_pending_update.execute(POOL_ID) mock_pool_repo_update.assert_called_once_with( 'TEST', POOL_ID, provisioning_status=constants.PENDING_UPDATE) # Test the revert mock_pool_repo_update.reset_mock() mark_pool_pending_update.revert(POOL_ID) mock_pool_repo_update.assert_called_once_with( 'TEST', id=POOL_ID, provisioning_status=constants.ERROR) # Test the revert with exception mock_pool_repo_update.reset_mock() mock_pool_repo_update.side_effect = Exception('fail') mark_pool_pending_update.revert(POOL_ID) mock_pool_repo_update.assert_called_once_with( 'TEST', id=POOL_ID, provisioning_status=constants.ERROR) @mock.patch('octavia.db.repositories.MemberRepository.update_pool_members') def test_update_pool_members_operating_status_in_db( self, mock_member_repo_update_pool_members, mock_generate_uuid, mock_LOG, mock_get_session, mock_loadbalancer_repo_update, mock_listener_repo_update, mock_amphora_repo_update, mock_amphora_repo_delete): update_members = database_tasks.UpdatePoolMembersOperatingStatusInDB() update_members.execute(POOL_ID, constants.ONLINE) mock_member_repo_update_pool_members.assert_called_once_with( 'TEST', POOL_ID, operating_status=constants.ONLINE)
en
0.825035
# Copyright 2015 Hewlett-Packard Development Company, L.P. # # 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. # # Test the revert # Test revert with exception # Test the revert # Test the revert # Test Not Found Exception # Test the revert # TODO(johnsom) fix once provisioning status added # repo.HealthMonitorRepository.update.assert_called_once_with( # 'TEST', # POOL_ID, # provisioning_status=constants.ERROR) # Test the revert # TODO(johnsom) Fix # repo.MemberRepository.delete.assert_called_once_with( # 'TEST', # MEMBER_ID) # Test the revert # TODO(johnsom) Fix # repo.PoolRepository.update.assert_called_once_with( # 'TEST', # POOL_ID, # operating_status=constants.ERROR) # Test the revert # TODO(sbalukoff) Fix # repo.ListenerRepository.update.assert_called_once_with( # 'TEST', # LISTENER_ID, # operating_status=constants.ERROR) # Test the revert # TODO(sbalukoff) Fix # repo.ListenerRepository.update.assert_called_once_with( # 'TEST', # LISTENER_ID, # operating_status=constants.ERROR) # Test revert # Test revert with exception # Test revert # Test revert with exception # Test revert # Test revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception # Test with LB_ID from listeners # Test with no LB_ID # Test the revert # Test the revert LB_ID from listeners # Test the revert no LB_ID # Test the revert with exceptions # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert # Test the revert # Test the revert # Test the revert # Test the revert with exception # Test the revert # Test the revert # Test the revert # Test the revert # Test revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception # Test the revert # Test the revert with exception
1.60762
2
Yellow_Pages_Lithuania/unit_tests.py
Jay4C/Web-Scraping
1
70
<gh_stars>1-10 import time from bs4 import BeautifulSoup import requests import pymysql.cursors import unittest class UnitTestsDataMinerYellowPagesLithuania(unittest.TestCase): def test_extract_one_email(self): url = "https://www.visalietuva.lt/en/company/astorija-hotel-uab" # Request the content of a page from the url html = requests.get(url) # Parse the content of html_doc soup = BeautifulSoup(html.content, 'html.parser') if soup.find('a', {'itemprop': 'email'}) is not None: email = "info@" + soup.find('a', {'itemprop': 'email'}).text.split("@")[1] print('email : ' + email) else: print('no email business') def test_extract_emails_from_all_page_of_results_for_one_activity_and_capital(self): activity = "hotel" city = "vilniuje" url_search = "https://www.visalietuva.lt/en/search/" + activity + "/" + city html_search = requests.get(url_search) soup_search = BeautifulSoup(html_search.content, 'html.parser') number_of_pages = 0 if soup_search.find('div', {'class': 'search_count f_left'}) is not None: number_of_pages_with_coma = int(soup_search .find('div', {'class': 'search_count f_left'}) .find('span').text )/20 if int(str(number_of_pages_with_coma).split(".")[1][:1]) < 5: number_of_pages += round(number_of_pages_with_coma) + 1 print('number_of_pages : ' + str(number_of_pages)) elif int(str(number_of_pages_with_coma).split(".")[1][:1]) >= 5: number_of_pages += round(number_of_pages_with_coma) print('number_of_pages : ' + str(number_of_pages)) i_1 = 0 if soup_search.find('div', {'class': 'company_list'}) is not None: print(url_search) for result_item in soup_search \ .find('div', {'class': 'company_list'}) \ .find_all('div', {'class': 'item'}): i_1 += 1 url_result = result_item.find('a', {'class': 'company-item-title'}).get('href') time.sleep(2) # Request the content of a page from the url html_result = requests.get(url_result) # Parse the content of html_doc soup_result = BeautifulSoup(html_result.content, 'html.parser') if soup_result.find('a', {'itemprop': 'email'}) is not None: email = "info@" + soup_result.find('a', {'itemprop': 'email'}).text.split("@")[1] print(str(i_1) + ' email : ' + email) else: print(str(i_1) + ' no email business') else: print('sorry there is nothing') if number_of_pages > 1: for i in range(2, number_of_pages+1): url_of_one_page_of_results = url_search + "/" + str(i) print(url_of_one_page_of_results) time.sleep(2) html_of_one_page_of_results = requests.get(url_of_one_page_of_results) soup_of_one_page_of_results = BeautifulSoup(html_of_one_page_of_results.content, 'html.parser') if soup_of_one_page_of_results.find('div', {'class': 'company_list'}) is not None: for result_item in soup_of_one_page_of_results\ .find('div', {'class': 'company_list'})\ .find_all('div', {'class': 'item'}): i_1 += 1 url_result = result_item.find('a', {'class': 'company-item-title'}).get('href') # Request the content of a page from the url html_result = requests.get(url_result) # Parse the content of html_doc soup_result = BeautifulSoup(html_result.content, 'html.parser') if soup_result.find('a', {'itemprop': 'email'}) is not None: email = "info@" + soup_result.find('a', {'itemprop': 'email'}).text.split("@")[1] print(str(i_1) + ' email : ' + email) else: print(str(i_1) + ' no email business') else: print('sorry there is nothing') def test_extract_emails_from_all_page_of_results_for_all_activities_and_capitals(self): activites = [ # {'id': '1', 'url': 'labour'} #{'id': '2', 'url': 'real+estate'}, #{'id': '3', 'url': 'recruitment'}, #{'id': '4', 'url': 'software'}, #{'id': '5', 'url': 'hotel'}, #{'id': '6', 'url': 'landlord'}, #{'id': '7', 'url': 'cleaning'}, #{'id': '8', 'url': 'association'}, #{'id': '9', 'url': 'financial'}, #{'id': '10', 'url': 'restaurant'}, #{'id': '11', 'url': 'building'}, #{'id': '12', 'url': 'hairdresser'}, #{'id': '13', 'url': 'florist'}, #{'id': '14', 'url': 'locksmith'}, #{'id': '15', 'url': 'bakery'}, #{'id': '16', 'url': 'insurance'}, #{'id': '17', 'url': 'pharmacy'}, #{'id': '18', 'url': 'moving'}, #{'id': '19', 'url': 'electricity'}, #{'id': '20', 'url': 'plumbing'}, #{'id': '21', 'url': 'security'}, #{'id': '22', 'url': 'lawyer'}, #{'id': '23', 'url': 'bank'}, #{'id': '24', 'url': 'garage'}, #{'id': '25', 'url': 'dentist'}, #{'id': '26', 'url': 'doctor'}, #{'id': '27', 'url': 'accounting'}, #{'id': '28', 'url': 'store'}, #{'id': '29', 'url': 'notary'}, #{'id': '30', 'url': 'jeweller'}, #{'id': '31', 'url': 'tailor'}, #{'id': '32', 'url': 'meat'}, #{'id': '33', 'url': 'library'}, #{'id': '34', 'url': 'architect'} ] capitales_du_monde = [ {'id': '183', 'nom': 'akmeneje'},#Akmenė {'id': '184', 'nom': 'alytuje'},#Alytus {'id': '185', 'nom': 'anyksciuose'},#Anykščiai {'id': '186', 'nom': 'birstone'},#Birštonas {'id': '187', 'nom': 'birzuose'},#Biržai {'id': '188', 'nom': 'druskininkuose'},#Druskininkai {'id': '189', 'nom': 'elektrenuose'},#Elektrėnai {'id': '190', 'nom': 'ignalinoje'},#Ignalina {'id': '191', 'nom': 'jonavoje'},#Jonava {'id': '192', 'nom': 'joniskyje'},#Joniškis {'id': '193', 'nom': 'jurbarke'},#Jurbarkas {'id': '194', 'nom': 'kaisiadoryse'},#Kaišiadorys {'id': '195', 'nom': 'kalvarijoje'},#Kalvarija {'id': '196', 'nom': 'kaune'},#Kaunas {'id': '197', 'nom': 'kazlu-rudoje'},#Kazlų Rūda {'id': '198', 'nom': 'kedainiuose'},#Kėdainiai {'id': '199', 'nom': 'kelmeje'},#Kelmė {'id': '200', 'nom': 'klaipedoje'},#Klaipėda {'id': '201', 'nom': 'kretingoje'},#Kretinga {'id': '202', 'nom': 'kupiskyje'},#Kupiškis {'id': '203', 'nom': 'lazdijuose'},#Lazdijai {'id': '204', 'nom': 'marijampoleje'},#Marijampolė {'id': '205', 'nom': 'mazeikiuose'},#Mažeikiai {'id': '206', 'nom': 'moletuose'},#Molėtai {'id': '207', 'nom': 'neringoje'},#Neringa {'id': '208', 'nom': 'pagegiuose'},#Pagėgiai {'id': '209', 'nom': 'pakruojyje'},#Pakruojis {'id': '210', 'nom': 'palangoje'},#Palanga {'id': '211', 'nom': 'panevezyje'},#Panevėžys {'id': '212', 'nom': 'pasvalyje'},#Pasvalys {'id': '213', 'nom': 'plungeje'},#Plungė {'id': '214', 'nom': 'prienuose'},#Prienai {'id': '215', 'nom': 'radviliskyje'},#Radviliškis {'id': '216', 'nom': 'raseiniuose'},#Raseiniai {'id': '217', 'nom': 'rietave'},#Rietavas {'id': '218', 'nom': 'rokiskyje'},#Rokiškis {'id': '219', 'nom': 'sakiuose'},#Šakiai {'id': '220', 'nom': 'salcininkuose'},#Šalčininkai {'id': '221', 'nom': 'siauliuose'},#Šiauliai {'id': '222', 'nom': 'silaleje'},#Šilalė {'id': '223', 'nom': 'siluteje'},#Šilutė {'id': '224', 'nom': 'sirvintose'},#Širvintos {'id': '225', 'nom': 'skuode'},#Skuodas {'id': '226', 'nom': 'svencionyse'},#Švenčionys {'id': '227', 'nom': 'taurageje'},#Tauragė {'id': '228', 'nom': 'telsiuose'},#Telšiai {'id': '229', 'nom': 'trakuose'},#Trakai {'id': '230', 'nom': 'ukmergeje'},#Ukmergė {'id': '231', 'nom': 'utenoje'},#Utena {'id': '232', 'nom': 'varenoje'},#Varėna {'id': '233', 'nom': 'vilkaviskyje'},#Vilkaviškis {'id': '234', 'nom': 'vilniuje'},#Vilnius {'id': '235', 'nom': 'visagine'},#Visaginas {'id': '236', 'nom': 'zarasuose'}#Zarasai ] try: for capitale in capitales_du_monde: for activite in activites: try: activity = activite.get("url") city = capitale.get("nom") url_search = "https://www.visalietuva.lt/en/search/" + activity + "/" + city html_search = requests.get(url_search) soup_search = BeautifulSoup(html_search.content, 'html.parser') number_of_pages = 0 if soup_search.find('div', {'class': 'search_count f_left'}) is not None: number_of_pages_with_coma = int(soup_search .find('div', {'class': 'search_count f_left'}) .find('span').text ) / 20 if int(str(number_of_pages_with_coma).split(".")[1][:1]) < 5: number_of_pages += round(number_of_pages_with_coma) + 1 print('number_of_pages : ' + str(number_of_pages)) elif int(str(number_of_pages_with_coma).split(".")[1][:1]) >= 5: number_of_pages += round(number_of_pages_with_coma) print('number_of_pages : ' + str(number_of_pages)) i_1 = 0 if soup_search.find('div', {'class': 'company_list'}) is not None: print(url_search) for result_item in soup_search \ .find('div', {'class': 'company_list'}) \ .find_all('div', {'class': 'item'}): i_1 += 1 url_result = result_item.find('a', {'class': 'company-item-title'}).get('href') time.sleep(2) # Request the content of a page from the url html_result = requests.get(url_result) # Parse the content of html_doc soup_result = BeautifulSoup(html_result.content, 'html.parser') if soup_result.find('a', {'itemprop': 'email'}) is not None: email = "info@" + soup_result.find('a', {'itemprop': 'email'}).text.split("@")[1] try: connection = pymysql.connect( host='localhost', port=3306, user='', password='', db='contacts_professionnels', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor ) with connection.cursor() as cursor: try: sql = "INSERT INTO `emails` (" \ "`id_activite`, " \ "`id_capitale_du_monde`, " \ "`email`) VALUE (%s, %s, %s)" cursor.execute(sql, ( activite.get('id'), capitale.get('id'), email)) connection.commit() print(str(i_1) + " The record is stored : " + email) connection.close() except: print(str(i_1) + " The record already exists : " + email) connection.close() except Exception as e: print(str(i_1) + " An error with the email : " + email + " " + str(e)) else: print(str(i_1) + ' no email business') else: print('sorry there is nothing') if number_of_pages > 1: for i in range(2, number_of_pages + 1): url_of_one_page_of_results = url_search + "/" + str(i) print(url_of_one_page_of_results) time.sleep(2) html_of_one_page_of_results = requests.get(url_of_one_page_of_results) soup_of_one_page_of_results = BeautifulSoup(html_of_one_page_of_results.content, 'html.parser') if soup_of_one_page_of_results.find('div', {'class': 'company_list'}) is not None: for result_item in soup_of_one_page_of_results \ .find('div', {'class': 'company_list'}) \ .find_all('div', {'class': 'item'}): i_1 += 1 url_result = result_item.find('a', {'class': 'company-item-title'}).get('href') # Request the content of a page from the url html_result = requests.get(url_result) # Parse the content of html_doc soup_result = BeautifulSoup(html_result.content, 'html.parser') if soup_result.find('a', {'itemprop': 'email'}) is not None: email = "info@" + \ soup_result.find('a', {'itemprop': 'email'}).text.split("@")[1] try: connection = pymysql.connect( host='localhost', port=3306, user='', password='', db='contacts_professionnels', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor ) with connection.cursor() as cursor: try: sql = "INSERT INTO `emails` (" \ "`id_activite`, " \ "`id_capitale_du_monde`, " \ "`email`) VALUE (%s, %s, %s)" cursor.execute(sql, ( activite.get('id'), capitale.get('id'), email)) connection.commit() print(str(i_1) + " The record is stored : " + email) connection.close() except: print(str(i_1) + " The record already exists : " + email) connection.close() except Exception as e: print(str(i_1) + " An error with the email : " + email + " " + str(e)) else: print(str(i_1) + ' no email business') else: print('sorry there is nothing') except Exception as e: print("There is an error connection at url : " + str(e)) finally: print('done') if __name__ == '__main__': unittest.main()
import time from bs4 import BeautifulSoup import requests import pymysql.cursors import unittest class UnitTestsDataMinerYellowPagesLithuania(unittest.TestCase): def test_extract_one_email(self): url = "https://www.visalietuva.lt/en/company/astorija-hotel-uab" # Request the content of a page from the url html = requests.get(url) # Parse the content of html_doc soup = BeautifulSoup(html.content, 'html.parser') if soup.find('a', {'itemprop': 'email'}) is not None: email = "info@" + soup.find('a', {'itemprop': 'email'}).text.split("@")[1] print('email : ' + email) else: print('no email business') def test_extract_emails_from_all_page_of_results_for_one_activity_and_capital(self): activity = "hotel" city = "vilniuje" url_search = "https://www.visalietuva.lt/en/search/" + activity + "/" + city html_search = requests.get(url_search) soup_search = BeautifulSoup(html_search.content, 'html.parser') number_of_pages = 0 if soup_search.find('div', {'class': 'search_count f_left'}) is not None: number_of_pages_with_coma = int(soup_search .find('div', {'class': 'search_count f_left'}) .find('span').text )/20 if int(str(number_of_pages_with_coma).split(".")[1][:1]) < 5: number_of_pages += round(number_of_pages_with_coma) + 1 print('number_of_pages : ' + str(number_of_pages)) elif int(str(number_of_pages_with_coma).split(".")[1][:1]) >= 5: number_of_pages += round(number_of_pages_with_coma) print('number_of_pages : ' + str(number_of_pages)) i_1 = 0 if soup_search.find('div', {'class': 'company_list'}) is not None: print(url_search) for result_item in soup_search \ .find('div', {'class': 'company_list'}) \ .find_all('div', {'class': 'item'}): i_1 += 1 url_result = result_item.find('a', {'class': 'company-item-title'}).get('href') time.sleep(2) # Request the content of a page from the url html_result = requests.get(url_result) # Parse the content of html_doc soup_result = BeautifulSoup(html_result.content, 'html.parser') if soup_result.find('a', {'itemprop': 'email'}) is not None: email = "info@" + soup_result.find('a', {'itemprop': 'email'}).text.split("@")[1] print(str(i_1) + ' email : ' + email) else: print(str(i_1) + ' no email business') else: print('sorry there is nothing') if number_of_pages > 1: for i in range(2, number_of_pages+1): url_of_one_page_of_results = url_search + "/" + str(i) print(url_of_one_page_of_results) time.sleep(2) html_of_one_page_of_results = requests.get(url_of_one_page_of_results) soup_of_one_page_of_results = BeautifulSoup(html_of_one_page_of_results.content, 'html.parser') if soup_of_one_page_of_results.find('div', {'class': 'company_list'}) is not None: for result_item in soup_of_one_page_of_results\ .find('div', {'class': 'company_list'})\ .find_all('div', {'class': 'item'}): i_1 += 1 url_result = result_item.find('a', {'class': 'company-item-title'}).get('href') # Request the content of a page from the url html_result = requests.get(url_result) # Parse the content of html_doc soup_result = BeautifulSoup(html_result.content, 'html.parser') if soup_result.find('a', {'itemprop': 'email'}) is not None: email = "info@" + soup_result.find('a', {'itemprop': 'email'}).text.split("@")[1] print(str(i_1) + ' email : ' + email) else: print(str(i_1) + ' no email business') else: print('sorry there is nothing') def test_extract_emails_from_all_page_of_results_for_all_activities_and_capitals(self): activites = [ # {'id': '1', 'url': 'labour'} #{'id': '2', 'url': 'real+estate'}, #{'id': '3', 'url': 'recruitment'}, #{'id': '4', 'url': 'software'}, #{'id': '5', 'url': 'hotel'}, #{'id': '6', 'url': 'landlord'}, #{'id': '7', 'url': 'cleaning'}, #{'id': '8', 'url': 'association'}, #{'id': '9', 'url': 'financial'}, #{'id': '10', 'url': 'restaurant'}, #{'id': '11', 'url': 'building'}, #{'id': '12', 'url': 'hairdresser'}, #{'id': '13', 'url': 'florist'}, #{'id': '14', 'url': 'locksmith'}, #{'id': '15', 'url': 'bakery'}, #{'id': '16', 'url': 'insurance'}, #{'id': '17', 'url': 'pharmacy'}, #{'id': '18', 'url': 'moving'}, #{'id': '19', 'url': 'electricity'}, #{'id': '20', 'url': 'plumbing'}, #{'id': '21', 'url': 'security'}, #{'id': '22', 'url': 'lawyer'}, #{'id': '23', 'url': 'bank'}, #{'id': '24', 'url': 'garage'}, #{'id': '25', 'url': 'dentist'}, #{'id': '26', 'url': 'doctor'}, #{'id': '27', 'url': 'accounting'}, #{'id': '28', 'url': 'store'}, #{'id': '29', 'url': 'notary'}, #{'id': '30', 'url': 'jeweller'}, #{'id': '31', 'url': 'tailor'}, #{'id': '32', 'url': 'meat'}, #{'id': '33', 'url': 'library'}, #{'id': '34', 'url': 'architect'} ] capitales_du_monde = [ {'id': '183', 'nom': 'akmeneje'},#Akmenė {'id': '184', 'nom': 'alytuje'},#Alytus {'id': '185', 'nom': 'anyksciuose'},#Anykščiai {'id': '186', 'nom': 'birstone'},#Birštonas {'id': '187', 'nom': 'birzuose'},#Biržai {'id': '188', 'nom': 'druskininkuose'},#Druskininkai {'id': '189', 'nom': 'elektrenuose'},#Elektrėnai {'id': '190', 'nom': 'ignalinoje'},#Ignalina {'id': '191', 'nom': 'jonavoje'},#Jonava {'id': '192', 'nom': 'joniskyje'},#Joniškis {'id': '193', 'nom': 'jurbarke'},#Jurbarkas {'id': '194', 'nom': 'kaisiadoryse'},#Kaišiadorys {'id': '195', 'nom': 'kalvarijoje'},#Kalvarija {'id': '196', 'nom': 'kaune'},#Kaunas {'id': '197', 'nom': 'kazlu-rudoje'},#Kazlų Rūda {'id': '198', 'nom': 'kedainiuose'},#Kėdainiai {'id': '199', 'nom': 'kelmeje'},#Kelmė {'id': '200', 'nom': 'klaipedoje'},#Klaipėda {'id': '201', 'nom': 'kretingoje'},#Kretinga {'id': '202', 'nom': 'kupiskyje'},#Kupiškis {'id': '203', 'nom': 'lazdijuose'},#Lazdijai {'id': '204', 'nom': 'marijampoleje'},#Marijampolė {'id': '205', 'nom': 'mazeikiuose'},#Mažeikiai {'id': '206', 'nom': 'moletuose'},#Molėtai {'id': '207', 'nom': 'neringoje'},#Neringa {'id': '208', 'nom': 'pagegiuose'},#Pagėgiai {'id': '209', 'nom': 'pakruojyje'},#Pakruojis {'id': '210', 'nom': 'palangoje'},#Palanga {'id': '211', 'nom': 'panevezyje'},#Panevėžys {'id': '212', 'nom': 'pasvalyje'},#Pasvalys {'id': '213', 'nom': 'plungeje'},#Plungė {'id': '214', 'nom': 'prienuose'},#Prienai {'id': '215', 'nom': 'radviliskyje'},#Radviliškis {'id': '216', 'nom': 'raseiniuose'},#Raseiniai {'id': '217', 'nom': 'rietave'},#Rietavas {'id': '218', 'nom': 'rokiskyje'},#Rokiškis {'id': '219', 'nom': 'sakiuose'},#Šakiai {'id': '220', 'nom': 'salcininkuose'},#Šalčininkai {'id': '221', 'nom': 'siauliuose'},#Šiauliai {'id': '222', 'nom': 'silaleje'},#Šilalė {'id': '223', 'nom': 'siluteje'},#Šilutė {'id': '224', 'nom': 'sirvintose'},#Širvintos {'id': '225', 'nom': 'skuode'},#Skuodas {'id': '226', 'nom': 'svencionyse'},#Švenčionys {'id': '227', 'nom': 'taurageje'},#Tauragė {'id': '228', 'nom': 'telsiuose'},#Telšiai {'id': '229', 'nom': 'trakuose'},#Trakai {'id': '230', 'nom': 'ukmergeje'},#Ukmergė {'id': '231', 'nom': 'utenoje'},#Utena {'id': '232', 'nom': 'varenoje'},#Varėna {'id': '233', 'nom': 'vilkaviskyje'},#Vilkaviškis {'id': '234', 'nom': 'vilniuje'},#Vilnius {'id': '235', 'nom': 'visagine'},#Visaginas {'id': '236', 'nom': 'zarasuose'}#Zarasai ] try: for capitale in capitales_du_monde: for activite in activites: try: activity = activite.get("url") city = capitale.get("nom") url_search = "https://www.visalietuva.lt/en/search/" + activity + "/" + city html_search = requests.get(url_search) soup_search = BeautifulSoup(html_search.content, 'html.parser') number_of_pages = 0 if soup_search.find('div', {'class': 'search_count f_left'}) is not None: number_of_pages_with_coma = int(soup_search .find('div', {'class': 'search_count f_left'}) .find('span').text ) / 20 if int(str(number_of_pages_with_coma).split(".")[1][:1]) < 5: number_of_pages += round(number_of_pages_with_coma) + 1 print('number_of_pages : ' + str(number_of_pages)) elif int(str(number_of_pages_with_coma).split(".")[1][:1]) >= 5: number_of_pages += round(number_of_pages_with_coma) print('number_of_pages : ' + str(number_of_pages)) i_1 = 0 if soup_search.find('div', {'class': 'company_list'}) is not None: print(url_search) for result_item in soup_search \ .find('div', {'class': 'company_list'}) \ .find_all('div', {'class': 'item'}): i_1 += 1 url_result = result_item.find('a', {'class': 'company-item-title'}).get('href') time.sleep(2) # Request the content of a page from the url html_result = requests.get(url_result) # Parse the content of html_doc soup_result = BeautifulSoup(html_result.content, 'html.parser') if soup_result.find('a', {'itemprop': 'email'}) is not None: email = "info@" + soup_result.find('a', {'itemprop': 'email'}).text.split("@")[1] try: connection = pymysql.connect( host='localhost', port=3306, user='', password='', db='contacts_professionnels', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor ) with connection.cursor() as cursor: try: sql = "INSERT INTO `emails` (" \ "`id_activite`, " \ "`id_capitale_du_monde`, " \ "`email`) VALUE (%s, %s, %s)" cursor.execute(sql, ( activite.get('id'), capitale.get('id'), email)) connection.commit() print(str(i_1) + " The record is stored : " + email) connection.close() except: print(str(i_1) + " The record already exists : " + email) connection.close() except Exception as e: print(str(i_1) + " An error with the email : " + email + " " + str(e)) else: print(str(i_1) + ' no email business') else: print('sorry there is nothing') if number_of_pages > 1: for i in range(2, number_of_pages + 1): url_of_one_page_of_results = url_search + "/" + str(i) print(url_of_one_page_of_results) time.sleep(2) html_of_one_page_of_results = requests.get(url_of_one_page_of_results) soup_of_one_page_of_results = BeautifulSoup(html_of_one_page_of_results.content, 'html.parser') if soup_of_one_page_of_results.find('div', {'class': 'company_list'}) is not None: for result_item in soup_of_one_page_of_results \ .find('div', {'class': 'company_list'}) \ .find_all('div', {'class': 'item'}): i_1 += 1 url_result = result_item.find('a', {'class': 'company-item-title'}).get('href') # Request the content of a page from the url html_result = requests.get(url_result) # Parse the content of html_doc soup_result = BeautifulSoup(html_result.content, 'html.parser') if soup_result.find('a', {'itemprop': 'email'}) is not None: email = "info@" + \ soup_result.find('a', {'itemprop': 'email'}).text.split("@")[1] try: connection = pymysql.connect( host='localhost', port=3306, user='', password='', db='contacts_professionnels', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor ) with connection.cursor() as cursor: try: sql = "INSERT INTO `emails` (" \ "`id_activite`, " \ "`id_capitale_du_monde`, " \ "`email`) VALUE (%s, %s, %s)" cursor.execute(sql, ( activite.get('id'), capitale.get('id'), email)) connection.commit() print(str(i_1) + " The record is stored : " + email) connection.close() except: print(str(i_1) + " The record already exists : " + email) connection.close() except Exception as e: print(str(i_1) + " An error with the email : " + email + " " + str(e)) else: print(str(i_1) + ' no email business') else: print('sorry there is nothing') except Exception as e: print("There is an error connection at url : " + str(e)) finally: print('done') if __name__ == '__main__': unittest.main()
en
0.101764
# Request the content of a page from the url # Parse the content of html_doc # Request the content of a page from the url # Parse the content of html_doc # Request the content of a page from the url # Parse the content of html_doc # {'id': '1', 'url': 'labour'} #{'id': '2', 'url': 'real+estate'}, #{'id': '3', 'url': 'recruitment'}, #{'id': '4', 'url': 'software'}, #{'id': '5', 'url': 'hotel'}, #{'id': '6', 'url': 'landlord'}, #{'id': '7', 'url': 'cleaning'}, #{'id': '8', 'url': 'association'}, #{'id': '9', 'url': 'financial'}, #{'id': '10', 'url': 'restaurant'}, #{'id': '11', 'url': 'building'}, #{'id': '12', 'url': 'hairdresser'}, #{'id': '13', 'url': 'florist'}, #{'id': '14', 'url': 'locksmith'}, #{'id': '15', 'url': 'bakery'}, #{'id': '16', 'url': 'insurance'}, #{'id': '17', 'url': 'pharmacy'}, #{'id': '18', 'url': 'moving'}, #{'id': '19', 'url': 'electricity'}, #{'id': '20', 'url': 'plumbing'}, #{'id': '21', 'url': 'security'}, #{'id': '22', 'url': 'lawyer'}, #{'id': '23', 'url': 'bank'}, #{'id': '24', 'url': 'garage'}, #{'id': '25', 'url': 'dentist'}, #{'id': '26', 'url': 'doctor'}, #{'id': '27', 'url': 'accounting'}, #{'id': '28', 'url': 'store'}, #{'id': '29', 'url': 'notary'}, #{'id': '30', 'url': 'jeweller'}, #{'id': '31', 'url': 'tailor'}, #{'id': '32', 'url': 'meat'}, #{'id': '33', 'url': 'library'}, #{'id': '34', 'url': 'architect'} #Akmenė #Alytus #Anykščiai #Birštonas #Biržai #Druskininkai #Elektrėnai #Ignalina #Jonava #Joniškis #Jurbarkas #Kaišiadorys #Kalvarija #Kaunas #Kazlų Rūda #Kėdainiai #Kelmė #Klaipėda #Kretinga #Kupiškis #Lazdijai #Marijampolė #Mažeikiai #Molėtai #Neringa #Pagėgiai #Pakruojis #Palanga #Panevėžys #Pasvalys #Plungė #Prienai #Radviliškis #Raseiniai #Rietavas #Rokiškis #Šakiai #Šalčininkai #Šiauliai #Šilalė #Šilutė #Širvintos #Skuodas #Švenčionys #Tauragė #Telšiai #Trakai #Ukmergė #Utena #Varėna #Vilkaviškis #Vilnius #Visaginas #Zarasai # Request the content of a page from the url # Parse the content of html_doc # Request the content of a page from the url # Parse the content of html_doc
2.78679
3
python_modules/dagster/dagster_tests/compat_tests/test_back_compat.py
vatervonacht/dagster
3
71
# pylint: disable=protected-access import os import re import pytest from dagster import file_relative_path from dagster.core.errors import DagsterInstanceMigrationRequired from dagster.core.instance import DagsterInstance, InstanceRef from dagster.utils.test import restore_directory # test that we can load runs and events from an old instance def test_0_6_4(): test_dir = file_relative_path(__file__, 'snapshot_0_6_4') with restore_directory(test_dir): instance = DagsterInstance.from_ref(InstanceRef.from_dir(test_dir)) runs = instance.get_runs() with pytest.raises( DagsterInstanceMigrationRequired, match=re.escape( 'Instance is out of date and must be migrated (SqliteEventLogStorage for run ' 'c7a6c4d7-6c88-46d0-8baa-d4937c3cefe5). Database is at revision None, head is ' '567bc23fd1ac. Please run `dagster instance migrate`.' ), ): for run in runs: instance.all_logs(run.run_id) def test_0_6_6_sqlite_exc(): test_dir = file_relative_path(__file__, 'snapshot_0_6_6/sqlite') with restore_directory(test_dir): instance = DagsterInstance.from_ref(InstanceRef.from_dir(test_dir)) runs = instance.get_runs() # Note that this is a deliberate choice -- old runs are simply invisible, and their # presence won't raise DagsterInstanceMigrationRequired. This is a reasonable choice since # the runs.db has moved and otherwise we would have to do a check for the existence of an # old runs.db every time we accessed the runs. Instead, we'll do this only in the upgrade # method. assert len(runs) == 0 run_ids = instance._event_storage.get_all_run_ids() assert run_ids == ['89296095-892d-4a15-aa0d-9018d1580945'] with pytest.raises( DagsterInstanceMigrationRequired, match=re.escape( 'Instance is out of date and must be migrated (SqliteEventLogStorage for run ' '89296095-892d-4a15-aa0d-9018d1580945). Database is at revision None, head is ' '567bc23fd1ac. Please run `dagster instance migrate`.' ), ): instance._event_storage.get_logs_for_run('89296095-892d-4a15-aa0d-9018d1580945') def test_0_6_6_sqlite_migrate(): test_dir = file_relative_path(__file__, 'snapshot_0_6_6/sqlite') assert os.path.exists(file_relative_path(__file__, 'snapshot_0_6_6/sqlite/runs.db')) assert not os.path.exists(file_relative_path(__file__, 'snapshot_0_6_6/sqlite/history/runs.db')) with restore_directory(test_dir): instance = DagsterInstance.from_ref(InstanceRef.from_dir(test_dir)) instance.upgrade() runs = instance.get_runs() assert len(runs) == 1 run_ids = instance._event_storage.get_all_run_ids() assert run_ids == ['89296095-892d-4a15-aa0d-9018d1580945'] instance._event_storage.get_logs_for_run('89296095-892d-4a15-aa0d-9018d1580945') assert not os.path.exists(file_relative_path(__file__, 'snapshot_0_6_6/sqlite/runs.db')) assert os.path.exists(file_relative_path(__file__, 'snapshot_0_6_6/sqlite/history/runs.db'))
# pylint: disable=protected-access import os import re import pytest from dagster import file_relative_path from dagster.core.errors import DagsterInstanceMigrationRequired from dagster.core.instance import DagsterInstance, InstanceRef from dagster.utils.test import restore_directory # test that we can load runs and events from an old instance def test_0_6_4(): test_dir = file_relative_path(__file__, 'snapshot_0_6_4') with restore_directory(test_dir): instance = DagsterInstance.from_ref(InstanceRef.from_dir(test_dir)) runs = instance.get_runs() with pytest.raises( DagsterInstanceMigrationRequired, match=re.escape( 'Instance is out of date and must be migrated (SqliteEventLogStorage for run ' 'c7a6c4d7-6c88-46d0-8baa-d4937c3cefe5). Database is at revision None, head is ' '567bc23fd1ac. Please run `dagster instance migrate`.' ), ): for run in runs: instance.all_logs(run.run_id) def test_0_6_6_sqlite_exc(): test_dir = file_relative_path(__file__, 'snapshot_0_6_6/sqlite') with restore_directory(test_dir): instance = DagsterInstance.from_ref(InstanceRef.from_dir(test_dir)) runs = instance.get_runs() # Note that this is a deliberate choice -- old runs are simply invisible, and their # presence won't raise DagsterInstanceMigrationRequired. This is a reasonable choice since # the runs.db has moved and otherwise we would have to do a check for the existence of an # old runs.db every time we accessed the runs. Instead, we'll do this only in the upgrade # method. assert len(runs) == 0 run_ids = instance._event_storage.get_all_run_ids() assert run_ids == ['89296095-892d-4a15-aa0d-9018d1580945'] with pytest.raises( DagsterInstanceMigrationRequired, match=re.escape( 'Instance is out of date and must be migrated (SqliteEventLogStorage for run ' '89296095-892d-4a15-aa0d-9018d1580945). Database is at revision None, head is ' '567bc23fd1ac. Please run `dagster instance migrate`.' ), ): instance._event_storage.get_logs_for_run('89296095-892d-4a15-aa0d-9018d1580945') def test_0_6_6_sqlite_migrate(): test_dir = file_relative_path(__file__, 'snapshot_0_6_6/sqlite') assert os.path.exists(file_relative_path(__file__, 'snapshot_0_6_6/sqlite/runs.db')) assert not os.path.exists(file_relative_path(__file__, 'snapshot_0_6_6/sqlite/history/runs.db')) with restore_directory(test_dir): instance = DagsterInstance.from_ref(InstanceRef.from_dir(test_dir)) instance.upgrade() runs = instance.get_runs() assert len(runs) == 1 run_ids = instance._event_storage.get_all_run_ids() assert run_ids == ['89296095-892d-4a15-aa0d-9018d1580945'] instance._event_storage.get_logs_for_run('89296095-892d-4a15-aa0d-9018d1580945') assert not os.path.exists(file_relative_path(__file__, 'snapshot_0_6_6/sqlite/runs.db')) assert os.path.exists(file_relative_path(__file__, 'snapshot_0_6_6/sqlite/history/runs.db'))
en
0.940548
# pylint: disable=protected-access # test that we can load runs and events from an old instance # Note that this is a deliberate choice -- old runs are simply invisible, and their # presence won't raise DagsterInstanceMigrationRequired. This is a reasonable choice since # the runs.db has moved and otherwise we would have to do a check for the existence of an # old runs.db every time we accessed the runs. Instead, we'll do this only in the upgrade # method.
2.009902
2
scripts/charts.py
yshrdbrn/bigdata
0
72
import matplotlib.pyplot as plt import pandas as pd def group_by_category(df): grouped = df.groupby(['CATEGORY']).size().to_frame('Crimes') labels = ['Trespassing', 'Vehicle theft', 'General Theft', 'Damage to Property', 'Robbery', 'Homicide'] p = grouped.plot.pie(y='Crimes', labels=labels, autopct='%1.1f%%') p.set_title('Crimes Percentage Grouped By Category') p.get_legend().remove() plt.savefig('../charts/category.png') def group_by_time_of_day(df): grouped = df.groupby(['TIME_OF_DAY']).size().to_frame('Crimes') p = grouped.plot.pie(y='Crimes', labels=['Day', 'Evening', 'Night'], autopct='%1.1f%%') p.set_title('Crimes Percentage Grouped By Time of Day') p.get_legend().remove() plt.savefig('../charts/time_of_day.png') def group_by_day_of_the_week(df): grouped = df.groupby(['DAY_OF_THE_WEEK']).size().to_frame('Crimes') labels = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] p = grouped.plot.pie(y='Crimes', labels=labels, autopct='%1.1f%%') p.set_title('Crimes Percentage Grouped By Day of The Week') p.get_legend().remove() plt.savefig('../charts/day_of_the_week.png') def group_by_month(df): grouped = df.groupby(['MONTH']).size().to_frame('Size') grouped['Percentage'] = 100 * grouped['Size'] / len(df) grouped = grouped.drop(columns='Size') p = grouped.plot.bar() p.set_title('Crimes Percentage Grouped By Month') p.set_ylabel('Percentage of Crimes') p.set_xlabel('Month') p.get_legend().remove() plt.savefig('../charts/month.png') def group_by_year(df): grouped = df.groupby(['YEAR']).size().to_frame('Crimes') p = grouped.plot.pie(y='Crimes', autopct='%1.1f%%') p.set_title('Crimes Percentage Grouped By Year') p.get_legend().remove() plt.savefig('../charts/year.png') def group_by_territory(df): grouped = df.groupby(['PDQ']).size().to_frame('Size') grouped['Percentage'] = 100 * grouped['Size'] / len(df) grouped = grouped.drop(columns='Size') grouped.index = grouped.index.astype(int) p = grouped.plot.bar() p.set_title('Crimes Percentage Grouped By Territory') p.set_ylabel('Percentage of Crimes') p.set_xlabel('Territory Number') p.get_legend().remove() plt.savefig('../charts/territory.png') if __name__ == '__main__': df = pd.read_csv('../data/crimes_dataset_processed_incomplete.csv') group_by_territory(df) group_by_year(df) group_by_month(df) group_by_time_of_day(df) group_by_day_of_the_week(df) group_by_category(df)
import matplotlib.pyplot as plt import pandas as pd def group_by_category(df): grouped = df.groupby(['CATEGORY']).size().to_frame('Crimes') labels = ['Trespassing', 'Vehicle theft', 'General Theft', 'Damage to Property', 'Robbery', 'Homicide'] p = grouped.plot.pie(y='Crimes', labels=labels, autopct='%1.1f%%') p.set_title('Crimes Percentage Grouped By Category') p.get_legend().remove() plt.savefig('../charts/category.png') def group_by_time_of_day(df): grouped = df.groupby(['TIME_OF_DAY']).size().to_frame('Crimes') p = grouped.plot.pie(y='Crimes', labels=['Day', 'Evening', 'Night'], autopct='%1.1f%%') p.set_title('Crimes Percentage Grouped By Time of Day') p.get_legend().remove() plt.savefig('../charts/time_of_day.png') def group_by_day_of_the_week(df): grouped = df.groupby(['DAY_OF_THE_WEEK']).size().to_frame('Crimes') labels = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] p = grouped.plot.pie(y='Crimes', labels=labels, autopct='%1.1f%%') p.set_title('Crimes Percentage Grouped By Day of The Week') p.get_legend().remove() plt.savefig('../charts/day_of_the_week.png') def group_by_month(df): grouped = df.groupby(['MONTH']).size().to_frame('Size') grouped['Percentage'] = 100 * grouped['Size'] / len(df) grouped = grouped.drop(columns='Size') p = grouped.plot.bar() p.set_title('Crimes Percentage Grouped By Month') p.set_ylabel('Percentage of Crimes') p.set_xlabel('Month') p.get_legend().remove() plt.savefig('../charts/month.png') def group_by_year(df): grouped = df.groupby(['YEAR']).size().to_frame('Crimes') p = grouped.plot.pie(y='Crimes', autopct='%1.1f%%') p.set_title('Crimes Percentage Grouped By Year') p.get_legend().remove() plt.savefig('../charts/year.png') def group_by_territory(df): grouped = df.groupby(['PDQ']).size().to_frame('Size') grouped['Percentage'] = 100 * grouped['Size'] / len(df) grouped = grouped.drop(columns='Size') grouped.index = grouped.index.astype(int) p = grouped.plot.bar() p.set_title('Crimes Percentage Grouped By Territory') p.set_ylabel('Percentage of Crimes') p.set_xlabel('Territory Number') p.get_legend().remove() plt.savefig('../charts/territory.png') if __name__ == '__main__': df = pd.read_csv('../data/crimes_dataset_processed_incomplete.csv') group_by_territory(df) group_by_year(df) group_by_month(df) group_by_time_of_day(df) group_by_day_of_the_week(df) group_by_category(df)
none
1
2.965389
3
unittests.py
benjaminkrenn/abcvoting
0
73
# Unit tests import unittest def run_test_instance(unittestinstance, profile, committeesize, tests): import rules_approval # all rules used? for rule in rules_approval.MWRULES: unittestinstance.assertTrue(rule in tests.keys()) for rule in tests.keys(): output = rules_approval.compute_rule(rule, profile, committeesize, resolute=False) unittestinstance.assertEqual( output, tests[rule], msg=rules_approval.MWRULES[rule] + " failed") output = rules_approval.compute_rule( rule, profile, committeesize, resolute=True) unittestinstance.assertEqual( len(output), 1, msg=rules_approval.MWRULES[rule] + " failed with resolute=True") unittestinstance.assertTrue( output[0] in tests[rule], msg=rules_approval.MWRULES[rule] + " failed with resolute=True") class TestApprovalMultiwinner(unittest.TestCase): def test_createprofiles(self): from preferences import Profile from preferences import DichotomousPreferences num_cand = 7 prof = Profile(num_cand) self.assertEqual(prof.add_preferences( DichotomousPreferences([0, 4, 5])), None) with self.assertRaises(Exception): prof.add_preferences(DichotomousPreferences([num_cand])) with self.assertRaises(Exception): prof.add_preferences(DichotomousPreferences([-1])) self.assertEqual(prof.add_preferences([0, 4, 5]), None) with self.assertRaises(Exception): prof.add_preferences([0, 4, 5, "1"]) with self.assertRaises(Exception): prof.add_preferences(["1", 0, 4, 5]) p1 = DichotomousPreferences([0, 4, 5]) p2 = DichotomousPreferences([1, 2]) self.assertEqual(prof.add_preferences([p1, p2]), None) self.assertTrue(prof.has_unit_weights()) prof.add_preferences(DichotomousPreferences([0, 4, 5], 2.4)) self.assertFalse(prof.has_unit_weights()) self.assertEqual(prof.totalweight(), 6.4) def test_mwrules__toofewcandidates(self): from preferences import Profile import rules_approval profile = Profile(5) committeesize = 4 preflist = [[0, 1, 2], [1], [1, 2], [0]] profile.add_preferences(preflist) for rule in rules_approval.MWRULES.keys(): with self.assertRaises(Exception): rules_approval.compute_rule(rule, profile, committeesize) with self.assertRaises(Exception): rules_approval.compute_rule(rule, profile, committeesize, resolute=True) def test_mwrules_weightsconsidered(self): from preferences import Profile from preferences import DichotomousPreferences import rules_approval self.longMessage = True profile = Profile(3) profile.add_preferences(DichotomousPreferences([0])) profile.add_preferences(DichotomousPreferences([0])) profile.add_preferences(DichotomousPreferences([1], 5)) profile.add_preferences(DichotomousPreferences([0])) committeesize = 1 for rule in rules_approval.MWRULES.keys(): if "monroe" in rule or "rule-x" in rule: # Monroe and rule x only work with unit weights: continue result = rules_approval.compute_rule(rule, profile, committeesize) self.assertTrue([1] in result, msg=rule + " failed"+str(result)) def test_mwrules_correct_simple(self): from preferences import Profile import rules_approval self.longMessage = True profile = Profile(4) profile.add_preferences([[0], [1], [2], [3]]) committeesize = 2 for rule in rules_approval.MWRULES.keys(): if rule == "greedy-monroe": # always returns one committee continue self.assertEqual(len(rules_approval.compute_rule(rule, profile, committeesize)), 6, msg=rule + " failed") for rule in rules_approval.MWRULES.keys(): self.assertEqual(len(rules_approval.compute_rule(rule, profile, committeesize, resolute=True)), 1, msg=rule + " failed with resolute=True") def test_monroe_indivisible(self): from preferences import Profile import rules_approval self.longMessage = True profile = Profile(4) profile.add_preferences([[0], [0], [0], [1, 2], [1, 2], [1], [3]]) committeesize = 3 for ilp in [True, False]: # max Monroe score is 6 (even for committee [0, 1, 3]) self.assertEqual( rules_approval.compute_monroe(profile, committeesize, ilp=ilp, resolute=False), [[0, 1, 2], [0, 1, 3], [0, 2, 3]]) # this test shows that tiebreaking is not (yet) # implemented for opt-Phragmen def test_optphrag_notiebreaking(self): from preferences import Profile from rules_approval import compute_rule self.longMessage = True profile = Profile(6) profile.add_preferences([[0], [0], [1, 3], [1, 3], [1, 4], [2, 4], [2, 5], [2, 5]]) committeesize = 3 self.assertEqual( len(compute_rule("optphrag", profile, committeesize, resolute=False)), 12) def test_mwrules_correct_advanced_1(self): from preferences import Profile self.longMessage = True committeesize = 4 profile = Profile(6) preflist = [[0, 4, 5], [0], [1, 4, 5], [1], [2, 4, 5], [2], [3, 4, 5], [3]] profile.add_preferences(preflist) tests1 = { "seqpav": [[0, 1, 4, 5], [0, 2, 4, 5], [0, 3, 4, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]], "av": [[0, 1, 4, 5], [0, 2, 4, 5], [0, 3, 4, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]], "sav": [[0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 2, 5], [0, 1, 3, 4], [0, 1, 3, 5], [0, 1, 4, 5], [0, 2, 3, 4], [0, 2, 3, 5], [0, 2, 4, 5], [0, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]], "pav-ilp": [[0, 1, 4, 5], [0, 2, 4, 5], [0, 3, 4, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]], "pav-noilp": [[0, 1, 4, 5], [0, 2, 4, 5], [0, 3, 4, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]], "revseqpav": [[0, 1, 4, 5], [0, 2, 4, 5], [0, 3, 4, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]], "minimaxav-noilp": [[0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 2, 5], [0, 1, 3, 4], [0, 1, 3, 5], [0, 1, 4, 5], [0, 2, 3, 4], [0, 2, 3, 5], [0, 2, 4, 5], [0, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]], "minimaxav-ilp": [[0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 2, 5], [0, 1, 3, 4], [0, 1, 3, 5], [0, 1, 4, 5], [0, 2, 3, 4], [0, 2, 3, 5], [0, 2, 4, 5], [0, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]], "phrag": [[0, 1, 4, 5], [0, 2, 4, 5], [0, 3, 4, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]], "optphrag": [[0, 1, 2, 3]], "cc-ilp": [[0, 1, 2, 3]], "cc-noilp": [[0, 1, 2, 3]], "seqcc": [[0, 1, 2, 4], [0, 1, 2, 5], [0, 1, 3, 4], [0, 1, 3, 5], [0, 2, 3, 4], [0, 2, 3, 5], [1, 2, 3, 4], [1, 2, 3, 5]], "revseqcc": [[0, 1, 2, 3]], "monroe-ilp": [[0, 1, 2, 3]], "monroe-noilp": [[0, 1, 2, 3]], "greedy-monroe": [[0, 2, 3, 4]], "slav-ilp": [[0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 2, 5], [0, 1, 3, 4], [0, 1, 3, 5], [0, 2, 3, 4], [0, 2, 3, 5], [1, 2, 3, 4], [1, 2, 3, 5]], "slav-noilp": [[0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 2, 5], [0, 1, 3, 4], [0, 1, 3, 5], [0, 2, 3, 4], [0, 2, 3, 5], [1, 2, 3, 4], [1, 2, 3, 5]], "seqslav": [[0, 1, 2, 4], [0, 1, 2, 5], [0, 1, 3, 4], [0, 1, 3, 5], [0, 2, 3, 4], [0, 2, 3, 5], [1, 2, 3, 4], [1, 2, 3, 5]], "rule-x": [[0, 1, 4, 5], [0, 2, 4, 5], [0, 3, 4, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]], "phragmen-enestroem": [[0, 1, 4, 5], [0, 2, 4, 5], [0, 3, 4, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]], } run_test_instance(self, profile, committeesize, tests1) # and now with reversed preflist preflist.reverse() for p in preflist: p.reverse() profile = Profile(6) profile.add_preferences(preflist) run_test_instance(self, profile, committeesize, tests1) def test_mwrules_correct_advanced_2(self): from preferences import Profile self.longMessage = True # and another profile profile = Profile(5) committeesize = 3 preflist = [[0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1], [3, 4], [3, 4], [3]] profile.add_preferences(preflist) tests2 = { "seqpav": [[0, 1, 3]], "av": [[0, 1, 2]], "sav": [[0, 1, 3]], "pav-ilp": [[0, 1, 3]], "pav-noilp": [[0, 1, 3]], "revseqpav": [[0, 1, 3]], "minimaxav-noilp": [[0, 1, 3], [0, 2, 3], [1, 2, 3]], "minimaxav-ilp": [[0, 1, 3], [0, 2, 3], [1, 2, 3]], "phrag": [[0, 1, 3]], "optphrag": [[0, 1, 3], [0, 2, 3], [1, 2, 3]], "cc-ilp": [[0, 1, 3], [0, 2, 3], [0, 3, 4], [1, 2, 3], [1, 3, 4]], "cc-noilp": [[0, 1, 3], [0, 2, 3], [0, 3, 4], [1, 2, 3], [1, 3, 4]], "seqcc": [[0, 1, 3], [0, 2, 3], [0, 3, 4], [1, 2, 3], [1, 3, 4]], "revseqcc": [[0, 1, 3], [0, 2, 3], [0, 3, 4], [1, 2, 3], [1, 3, 4]], "monroe-ilp": [[0, 1, 3], [0, 2, 3], [1, 2, 3]], "monroe-noilp": [[0, 1, 3], [0, 2, 3], [1, 2, 3]], "greedy-monroe": [[0, 1, 3]], "seqslav": [[0, 1, 3]], "slav-ilp": [[0, 1, 3]], "slav-noilp": [[0, 1, 3]], "rule-x": [[0, 1, 3]], "phragmen-enestroem": [[0, 1, 3]], } run_test_instance(self, profile, committeesize, tests2) def test_mwrules_correct_advanced_3(self): from preferences import Profile self.longMessage = True # and a third profile profile = Profile(6) committeesize = 4 preflist = [[0, 3, 4, 5], [1, 2], [0, 2, 5], [2], [0, 1, 2, 3, 4], [0, 3, 4], [0, 2, 4], [0, 1]] profile.add_preferences(preflist) tests3 = { "seqpav": [[0, 1, 2, 4]], "av": [[0, 1, 2, 4], [0, 2, 3, 4]], "sav": [[0, 1, 2, 4]], "pav-ilp": [[0, 1, 2, 4]], "pav-noilp": [[0, 1, 2, 4]], "revseqpav": [[0, 1, 2, 4]], "minimaxav-noilp": [[0, 1, 2, 3], [0, 1, 2, 4], [0, 2, 3, 4], [0, 2, 3, 5], [0, 2, 4, 5]], "minimaxav-ilp": [[0, 1, 2, 3], [0, 1, 2, 4], [0, 2, 3, 4], [0, 2, 3, 5], [0, 2, 4, 5]], "phrag": [[0, 1, 2, 4]], "optphrag": [[0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 2, 5], [0, 2, 3, 4], [0, 2, 3, 5], [0, 2, 4, 5], [1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5]], "cc-ilp": [[0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 2, 5], [0, 2, 3, 4], [0, 2, 3, 5], [0, 2, 4, 5], [1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5]], "cc-noilp": [[0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 2, 5], [0, 2, 3, 4], [0, 2, 3, 5], [0, 2, 4, 5], [1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5]], "seqcc": [[0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 2, 5], [0, 2, 3, 4], [0, 2, 3, 5], [0, 2, 4, 5]], "revseqcc": [[0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 2, 5], [0, 2, 3, 4], [0, 2, 3, 5], [0, 2, 4, 5], [1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5]], "monroe-ilp": [[0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 2, 5], [0, 2, 3, 4], [0, 2, 3, 5], [0, 2, 4, 5], [1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5]], "monroe-noilp": [[0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 2, 5], [0, 2, 3, 4], [0, 2, 3, 5], [0, 2, 4, 5], [1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5]], "greedy-monroe": [[0, 1, 2, 3]], "seqslav": [[0, 1, 2, 4]], "slav-ilp": [[0, 1, 2, 4]], "slav-noilp": [[0, 1, 2, 4]], "rule-x": [[0, 1, 2, 4]], "phragmen-enestroem": [[0, 1, 2, 4]], } run_test_instance(self, profile, committeesize, tests3) def test_monroescore(self): from preferences import Profile from score_functions import monroescore_flowbased, monroescore_matching self.longMessage = True # and a third profile profile = Profile(6) preflist = [[0, 1], [1], [1, 3], [4], [2], [1, 5, 3]] profile.add_preferences(preflist) self.assertEqual(monroescore_flowbased(profile, [1, 3, 2]), 5) self.assertEqual(monroescore_matching(profile, [1, 3, 2]), 5) self.assertEqual(monroescore_flowbased(profile, [2, 1, 5]), 4) self.assertEqual(monroescore_matching(profile, [2, 1, 5]), 4) self.assertEqual(monroescore_flowbased(profile, [2, 4, 5]), 3) self.assertEqual(monroescore_matching(profile, [2, 5, 4]), 3) if __name__ == '__main__': unittest.main()
# Unit tests import unittest def run_test_instance(unittestinstance, profile, committeesize, tests): import rules_approval # all rules used? for rule in rules_approval.MWRULES: unittestinstance.assertTrue(rule in tests.keys()) for rule in tests.keys(): output = rules_approval.compute_rule(rule, profile, committeesize, resolute=False) unittestinstance.assertEqual( output, tests[rule], msg=rules_approval.MWRULES[rule] + " failed") output = rules_approval.compute_rule( rule, profile, committeesize, resolute=True) unittestinstance.assertEqual( len(output), 1, msg=rules_approval.MWRULES[rule] + " failed with resolute=True") unittestinstance.assertTrue( output[0] in tests[rule], msg=rules_approval.MWRULES[rule] + " failed with resolute=True") class TestApprovalMultiwinner(unittest.TestCase): def test_createprofiles(self): from preferences import Profile from preferences import DichotomousPreferences num_cand = 7 prof = Profile(num_cand) self.assertEqual(prof.add_preferences( DichotomousPreferences([0, 4, 5])), None) with self.assertRaises(Exception): prof.add_preferences(DichotomousPreferences([num_cand])) with self.assertRaises(Exception): prof.add_preferences(DichotomousPreferences([-1])) self.assertEqual(prof.add_preferences([0, 4, 5]), None) with self.assertRaises(Exception): prof.add_preferences([0, 4, 5, "1"]) with self.assertRaises(Exception): prof.add_preferences(["1", 0, 4, 5]) p1 = DichotomousPreferences([0, 4, 5]) p2 = DichotomousPreferences([1, 2]) self.assertEqual(prof.add_preferences([p1, p2]), None) self.assertTrue(prof.has_unit_weights()) prof.add_preferences(DichotomousPreferences([0, 4, 5], 2.4)) self.assertFalse(prof.has_unit_weights()) self.assertEqual(prof.totalweight(), 6.4) def test_mwrules__toofewcandidates(self): from preferences import Profile import rules_approval profile = Profile(5) committeesize = 4 preflist = [[0, 1, 2], [1], [1, 2], [0]] profile.add_preferences(preflist) for rule in rules_approval.MWRULES.keys(): with self.assertRaises(Exception): rules_approval.compute_rule(rule, profile, committeesize) with self.assertRaises(Exception): rules_approval.compute_rule(rule, profile, committeesize, resolute=True) def test_mwrules_weightsconsidered(self): from preferences import Profile from preferences import DichotomousPreferences import rules_approval self.longMessage = True profile = Profile(3) profile.add_preferences(DichotomousPreferences([0])) profile.add_preferences(DichotomousPreferences([0])) profile.add_preferences(DichotomousPreferences([1], 5)) profile.add_preferences(DichotomousPreferences([0])) committeesize = 1 for rule in rules_approval.MWRULES.keys(): if "monroe" in rule or "rule-x" in rule: # Monroe and rule x only work with unit weights: continue result = rules_approval.compute_rule(rule, profile, committeesize) self.assertTrue([1] in result, msg=rule + " failed"+str(result)) def test_mwrules_correct_simple(self): from preferences import Profile import rules_approval self.longMessage = True profile = Profile(4) profile.add_preferences([[0], [1], [2], [3]]) committeesize = 2 for rule in rules_approval.MWRULES.keys(): if rule == "greedy-monroe": # always returns one committee continue self.assertEqual(len(rules_approval.compute_rule(rule, profile, committeesize)), 6, msg=rule + " failed") for rule in rules_approval.MWRULES.keys(): self.assertEqual(len(rules_approval.compute_rule(rule, profile, committeesize, resolute=True)), 1, msg=rule + " failed with resolute=True") def test_monroe_indivisible(self): from preferences import Profile import rules_approval self.longMessage = True profile = Profile(4) profile.add_preferences([[0], [0], [0], [1, 2], [1, 2], [1], [3]]) committeesize = 3 for ilp in [True, False]: # max Monroe score is 6 (even for committee [0, 1, 3]) self.assertEqual( rules_approval.compute_monroe(profile, committeesize, ilp=ilp, resolute=False), [[0, 1, 2], [0, 1, 3], [0, 2, 3]]) # this test shows that tiebreaking is not (yet) # implemented for opt-Phragmen def test_optphrag_notiebreaking(self): from preferences import Profile from rules_approval import compute_rule self.longMessage = True profile = Profile(6) profile.add_preferences([[0], [0], [1, 3], [1, 3], [1, 4], [2, 4], [2, 5], [2, 5]]) committeesize = 3 self.assertEqual( len(compute_rule("optphrag", profile, committeesize, resolute=False)), 12) def test_mwrules_correct_advanced_1(self): from preferences import Profile self.longMessage = True committeesize = 4 profile = Profile(6) preflist = [[0, 4, 5], [0], [1, 4, 5], [1], [2, 4, 5], [2], [3, 4, 5], [3]] profile.add_preferences(preflist) tests1 = { "seqpav": [[0, 1, 4, 5], [0, 2, 4, 5], [0, 3, 4, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]], "av": [[0, 1, 4, 5], [0, 2, 4, 5], [0, 3, 4, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]], "sav": [[0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 2, 5], [0, 1, 3, 4], [0, 1, 3, 5], [0, 1, 4, 5], [0, 2, 3, 4], [0, 2, 3, 5], [0, 2, 4, 5], [0, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]], "pav-ilp": [[0, 1, 4, 5], [0, 2, 4, 5], [0, 3, 4, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]], "pav-noilp": [[0, 1, 4, 5], [0, 2, 4, 5], [0, 3, 4, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]], "revseqpav": [[0, 1, 4, 5], [0, 2, 4, 5], [0, 3, 4, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]], "minimaxav-noilp": [[0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 2, 5], [0, 1, 3, 4], [0, 1, 3, 5], [0, 1, 4, 5], [0, 2, 3, 4], [0, 2, 3, 5], [0, 2, 4, 5], [0, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]], "minimaxav-ilp": [[0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 2, 5], [0, 1, 3, 4], [0, 1, 3, 5], [0, 1, 4, 5], [0, 2, 3, 4], [0, 2, 3, 5], [0, 2, 4, 5], [0, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]], "phrag": [[0, 1, 4, 5], [0, 2, 4, 5], [0, 3, 4, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]], "optphrag": [[0, 1, 2, 3]], "cc-ilp": [[0, 1, 2, 3]], "cc-noilp": [[0, 1, 2, 3]], "seqcc": [[0, 1, 2, 4], [0, 1, 2, 5], [0, 1, 3, 4], [0, 1, 3, 5], [0, 2, 3, 4], [0, 2, 3, 5], [1, 2, 3, 4], [1, 2, 3, 5]], "revseqcc": [[0, 1, 2, 3]], "monroe-ilp": [[0, 1, 2, 3]], "monroe-noilp": [[0, 1, 2, 3]], "greedy-monroe": [[0, 2, 3, 4]], "slav-ilp": [[0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 2, 5], [0, 1, 3, 4], [0, 1, 3, 5], [0, 2, 3, 4], [0, 2, 3, 5], [1, 2, 3, 4], [1, 2, 3, 5]], "slav-noilp": [[0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 2, 5], [0, 1, 3, 4], [0, 1, 3, 5], [0, 2, 3, 4], [0, 2, 3, 5], [1, 2, 3, 4], [1, 2, 3, 5]], "seqslav": [[0, 1, 2, 4], [0, 1, 2, 5], [0, 1, 3, 4], [0, 1, 3, 5], [0, 2, 3, 4], [0, 2, 3, 5], [1, 2, 3, 4], [1, 2, 3, 5]], "rule-x": [[0, 1, 4, 5], [0, 2, 4, 5], [0, 3, 4, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]], "phragmen-enestroem": [[0, 1, 4, 5], [0, 2, 4, 5], [0, 3, 4, 5], [1, 2, 4, 5], [1, 3, 4, 5], [2, 3, 4, 5]], } run_test_instance(self, profile, committeesize, tests1) # and now with reversed preflist preflist.reverse() for p in preflist: p.reverse() profile = Profile(6) profile.add_preferences(preflist) run_test_instance(self, profile, committeesize, tests1) def test_mwrules_correct_advanced_2(self): from preferences import Profile self.longMessage = True # and another profile profile = Profile(5) committeesize = 3 preflist = [[0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1], [3, 4], [3, 4], [3]] profile.add_preferences(preflist) tests2 = { "seqpav": [[0, 1, 3]], "av": [[0, 1, 2]], "sav": [[0, 1, 3]], "pav-ilp": [[0, 1, 3]], "pav-noilp": [[0, 1, 3]], "revseqpav": [[0, 1, 3]], "minimaxav-noilp": [[0, 1, 3], [0, 2, 3], [1, 2, 3]], "minimaxav-ilp": [[0, 1, 3], [0, 2, 3], [1, 2, 3]], "phrag": [[0, 1, 3]], "optphrag": [[0, 1, 3], [0, 2, 3], [1, 2, 3]], "cc-ilp": [[0, 1, 3], [0, 2, 3], [0, 3, 4], [1, 2, 3], [1, 3, 4]], "cc-noilp": [[0, 1, 3], [0, 2, 3], [0, 3, 4], [1, 2, 3], [1, 3, 4]], "seqcc": [[0, 1, 3], [0, 2, 3], [0, 3, 4], [1, 2, 3], [1, 3, 4]], "revseqcc": [[0, 1, 3], [0, 2, 3], [0, 3, 4], [1, 2, 3], [1, 3, 4]], "monroe-ilp": [[0, 1, 3], [0, 2, 3], [1, 2, 3]], "monroe-noilp": [[0, 1, 3], [0, 2, 3], [1, 2, 3]], "greedy-monroe": [[0, 1, 3]], "seqslav": [[0, 1, 3]], "slav-ilp": [[0, 1, 3]], "slav-noilp": [[0, 1, 3]], "rule-x": [[0, 1, 3]], "phragmen-enestroem": [[0, 1, 3]], } run_test_instance(self, profile, committeesize, tests2) def test_mwrules_correct_advanced_3(self): from preferences import Profile self.longMessage = True # and a third profile profile = Profile(6) committeesize = 4 preflist = [[0, 3, 4, 5], [1, 2], [0, 2, 5], [2], [0, 1, 2, 3, 4], [0, 3, 4], [0, 2, 4], [0, 1]] profile.add_preferences(preflist) tests3 = { "seqpav": [[0, 1, 2, 4]], "av": [[0, 1, 2, 4], [0, 2, 3, 4]], "sav": [[0, 1, 2, 4]], "pav-ilp": [[0, 1, 2, 4]], "pav-noilp": [[0, 1, 2, 4]], "revseqpav": [[0, 1, 2, 4]], "minimaxav-noilp": [[0, 1, 2, 3], [0, 1, 2, 4], [0, 2, 3, 4], [0, 2, 3, 5], [0, 2, 4, 5]], "minimaxav-ilp": [[0, 1, 2, 3], [0, 1, 2, 4], [0, 2, 3, 4], [0, 2, 3, 5], [0, 2, 4, 5]], "phrag": [[0, 1, 2, 4]], "optphrag": [[0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 2, 5], [0, 2, 3, 4], [0, 2, 3, 5], [0, 2, 4, 5], [1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5]], "cc-ilp": [[0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 2, 5], [0, 2, 3, 4], [0, 2, 3, 5], [0, 2, 4, 5], [1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5]], "cc-noilp": [[0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 2, 5], [0, 2, 3, 4], [0, 2, 3, 5], [0, 2, 4, 5], [1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5]], "seqcc": [[0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 2, 5], [0, 2, 3, 4], [0, 2, 3, 5], [0, 2, 4, 5]], "revseqcc": [[0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 2, 5], [0, 2, 3, 4], [0, 2, 3, 5], [0, 2, 4, 5], [1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5]], "monroe-ilp": [[0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 2, 5], [0, 2, 3, 4], [0, 2, 3, 5], [0, 2, 4, 5], [1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5]], "monroe-noilp": [[0, 1, 2, 3], [0, 1, 2, 4], [0, 1, 2, 5], [0, 2, 3, 4], [0, 2, 3, 5], [0, 2, 4, 5], [1, 2, 3, 4], [1, 2, 3, 5], [1, 2, 4, 5]], "greedy-monroe": [[0, 1, 2, 3]], "seqslav": [[0, 1, 2, 4]], "slav-ilp": [[0, 1, 2, 4]], "slav-noilp": [[0, 1, 2, 4]], "rule-x": [[0, 1, 2, 4]], "phragmen-enestroem": [[0, 1, 2, 4]], } run_test_instance(self, profile, committeesize, tests3) def test_monroescore(self): from preferences import Profile from score_functions import monroescore_flowbased, monroescore_matching self.longMessage = True # and a third profile profile = Profile(6) preflist = [[0, 1], [1], [1, 3], [4], [2], [1, 5, 3]] profile.add_preferences(preflist) self.assertEqual(monroescore_flowbased(profile, [1, 3, 2]), 5) self.assertEqual(monroescore_matching(profile, [1, 3, 2]), 5) self.assertEqual(monroescore_flowbased(profile, [2, 1, 5]), 4) self.assertEqual(monroescore_matching(profile, [2, 1, 5]), 4) self.assertEqual(monroescore_flowbased(profile, [2, 4, 5]), 3) self.assertEqual(monroescore_matching(profile, [2, 5, 4]), 3) if __name__ == '__main__': unittest.main()
en
0.893149
# Unit tests # all rules used? # Monroe and rule x only work with unit weights: # always returns one committee # max Monroe score is 6 (even for committee [0, 1, 3]) # this test shows that tiebreaking is not (yet) # implemented for opt-Phragmen # and now with reversed preflist # and another profile # and a third profile # and a third profile
2.754515
3
Robustness Check/Calculating Risk Factors/calculate_momentum_factor.py
behnoud-bazrafshan/ThesisPortfolio
0
74
<reponame>behnoud-bazrafshan/ThesisPortfolio import pandas as pd import numpy as np import jdatetime pd.options.mode.chained_assignment = None # Read Bourseview data for market cap # Concat all 75 tickers' data me_list = [] for file_number in range(1, 76): print(file_number) me_path = f'E:/Thesis/New Sampling/Daily Data - Bourseview/'\ f'{file_number}.xlsx' me_df = pd.read_excel( me_path, skiprows=7, usecols=[2, 3, 11], names=['date', 'open', 'market_cap'], na_values='-' ) # Change order from old to new dates me_df = me_df[::-1].reset_index(drop=True) me_df['date'] = me_df['date'].str.replace('-', '') # Delete non-traded days me_df.dropna(subset=['open'], inplace=True) me_df.drop(columns='open', inplace=True) # Create monthly dataframe me_df = me_df.groupby(me_df['date'].str[:6]).last() me_df = me_df.drop(columns=['date']).reset_index() me_df.insert(1, 'ticker_num', file_number) me_list.append(me_df) me_df = pd.concat(me_list, ignore_index=True) me_df = me_df.loc[(me_df['date'] >= '139212') & (me_df['date'] <= '139900')] me_df.reset_index(drop=True, inplace=True) # Read rahavard 365 data for calculating returns close_list = [] for file_number in range(1, 76): rahavard_path = f'E:/Thesis/New Sampling/Daily Data - Rahavard 365/'\ f'{file_number}.txt' df = pd.read_csv( rahavard_path, usecols=[2, 7], names=['date', 'close'], header=0, dtype={'date': str}, parse_dates=[0] ) # Solve index reading problem, pandas add 2 index to the df df.reset_index(drop=True, inplace=True) # Convert to shamsi dates df['date'] = df['date'].apply( lambda x: jdatetime.date.fromgregorian(date=x).strftime('%Y%m%d') ) # Create monthly dataframe df = df.groupby(df['date'].str[:6]).last() df = df.drop(columns=['date']).reset_index() df.insert(1, 'ticker_num', file_number) df['monthly_return'] = df['close'].pct_change() close_list.append(df) df = pd.concat(close_list, ignore_index=True) df = df.loc[(df['date'] >= '139212') & (df['date'] <= '139900')] # Read index df for indicating open market days index_path = r'E:\Thesis\New Sampling\TEDPIX\شاخص كل6.xls' index_df = pd.read_excel( index_path, usecols=[1], names=['date'], dtype={'date': str} ) index_df.dropna(inplace=True) # The list of all months months = index_df['date'].str[:6].unique().tolist() # The list of months that we need for calculating market cap me_months = [ '139312', '139401', '139402', '139403', '139404', '139405', '139406', '139407', '139408', '139409', '139410', '139411', '139412', '139501', '139502', '139503', '139504', '139505', '139506', '139507', '139508', '139509', '139510', '139511', '139512', '139601', '139602', '139603', '139604', '139605', '139606', '139607', '139608', '139609', '139610', '139611', '139612', '139701', '139702', '139703', '139704', '139705', '139706', '139707', '139708', '139709', '139710', '139711', '139712', '139801', '139802', '139803', '139804', '139805', '139806', '139807', '139808', '139809', '139810', '139811', '139812' ] # The list of months that we need for camculating MOM mom_months = me_months[1:] # Merge market cap and price dfs merged_df = pd.merge(df, me_df, on=['ticker_num', 'date']) # First, create a NaN column, and then add t-13 prices merged_df.insert(5, 't-13 price', np.nan) for month in mom_months: # Find t-13 prices for ticker in range(1, 76): t_13 = months[months.index(month) - 13] t_13_condtion = (merged_df['date'] == t_13) ticker_condition = (merged_df['ticker_num'] == ticker) try: t_13_price = merged_df.loc[ t_13_condtion & ticker_condition ]['close'].values[0] previous_month = me_months[me_months.index(month) - 1] t_1_condtion = (merged_df['date'] == previous_month) merged_df.loc[ (t_1_condtion & ticker_condition), 't-13 price' ] = t_13_price except: pass # Calculate last 12 months return for month t (t-1, t-12) merged_df['past_year_return'] = ( (merged_df['close'] / merged_df['t-13 price']) - 1 ) mom_list = [] for month in mom_months: # Check t-13 price condition and t-1 market cap condition previous_month = months[months.index(month) - 1] me_condition = (merged_df['date'] == previous_month) mom_condition = (merged_df['past_year_return'].notna()) portfo_const_df = merged_df.loc[me_condition & mom_condition] # Split each month ME into two groups conditions = [ ( portfo_const_df['market_cap'] > portfo_const_df['market_cap'].median() ), ( portfo_const_df['market_cap'] <= portfo_const_df['market_cap'].median() ) ] portfolio_size = np.select(conditions, ['B', 'S']).tolist() portfo_const_df.insert(6, 'size', portfolio_size) # Split each me portfolio into 3 MOM group q = [0, .3, .7, 1] labels = ['L', 'M', 'H'] x_b = portfo_const_df.loc[ portfo_const_df['size'] == 'B' ]['past_year_return'] b_mom = pd.qcut(x=x_b, q=q, labels=labels).to_dict() x_s = portfo_const_df.loc[ portfo_const_df['size'] == 'S' ]['past_year_return'] s_mom = pd.qcut(x=x_s, q=q, labels=labels).to_dict() portfo_const_df['mom'] = pd.Series(b_mom) portfo_const_df['mom'].update(pd.Series(s_mom)) # Extrect portfolio ticker numbers portfo_const_df['portfolio'] = ( portfo_const_df['size'] + portfo_const_df['mom'] ) bh = portfo_const_df.loc[ portfo_const_df['portfolio'] == 'BH' ]['ticker_num'].tolist() bl = portfo_const_df.loc[ portfo_const_df['portfolio'] == 'BL' ]['ticker_num'].tolist() sh = portfo_const_df.loc[ portfo_const_df['portfolio'] == 'SH' ]['ticker_num'].tolist() sl = portfo_const_df.loc[ portfo_const_df['portfolio'] == 'SL' ]['ticker_num'].tolist() # Calculating value-weighted return for each portfolio in month t # Set conditions month_condition = (merged_df['date'] == month) bh_condition = merged_df['ticker_num'].isin(bh) bl_condition = merged_df['ticker_num'].isin(bl) sh_condition = merged_df['ticker_num'].isin(sh) sl_condition = merged_df['ticker_num'].isin(sl) # Construct portfolios bh_portfolio = merged_df.loc[month_condition & bh_condition] bl_portfolio = merged_df.loc[month_condition & bl_condition] sh_portfolio = merged_df.loc[month_condition & sh_condition] sl_portfolio = merged_df.loc[month_condition & sl_condition] # Calculate value-weighted returns bh_return = np.average( bh_portfolio.monthly_return, weights=bh_portfolio.market_cap ) bl_return = np.average( bl_portfolio.monthly_return, weights=bl_portfolio.market_cap ) sh_return = np.average( sh_portfolio.monthly_return, weights=sh_portfolio.market_cap ) sl_return = np.average( sl_portfolio.monthly_return, weights=sl_portfolio.market_cap ) # Calculate MOM, and add it to a list mom = ( ((sh_return + bh_return) / 2) - ((sl_return + bl_return) / 2) ) mom_list.append(mom) mom_df = pd.Series(mom_list).to_excel('mom.xlsx')
import pandas as pd import numpy as np import jdatetime pd.options.mode.chained_assignment = None # Read Bourseview data for market cap # Concat all 75 tickers' data me_list = [] for file_number in range(1, 76): print(file_number) me_path = f'E:/Thesis/New Sampling/Daily Data - Bourseview/'\ f'{file_number}.xlsx' me_df = pd.read_excel( me_path, skiprows=7, usecols=[2, 3, 11], names=['date', 'open', 'market_cap'], na_values='-' ) # Change order from old to new dates me_df = me_df[::-1].reset_index(drop=True) me_df['date'] = me_df['date'].str.replace('-', '') # Delete non-traded days me_df.dropna(subset=['open'], inplace=True) me_df.drop(columns='open', inplace=True) # Create monthly dataframe me_df = me_df.groupby(me_df['date'].str[:6]).last() me_df = me_df.drop(columns=['date']).reset_index() me_df.insert(1, 'ticker_num', file_number) me_list.append(me_df) me_df = pd.concat(me_list, ignore_index=True) me_df = me_df.loc[(me_df['date'] >= '139212') & (me_df['date'] <= '139900')] me_df.reset_index(drop=True, inplace=True) # Read rahavard 365 data for calculating returns close_list = [] for file_number in range(1, 76): rahavard_path = f'E:/Thesis/New Sampling/Daily Data - Rahavard 365/'\ f'{file_number}.txt' df = pd.read_csv( rahavard_path, usecols=[2, 7], names=['date', 'close'], header=0, dtype={'date': str}, parse_dates=[0] ) # Solve index reading problem, pandas add 2 index to the df df.reset_index(drop=True, inplace=True) # Convert to shamsi dates df['date'] = df['date'].apply( lambda x: jdatetime.date.fromgregorian(date=x).strftime('%Y%m%d') ) # Create monthly dataframe df = df.groupby(df['date'].str[:6]).last() df = df.drop(columns=['date']).reset_index() df.insert(1, 'ticker_num', file_number) df['monthly_return'] = df['close'].pct_change() close_list.append(df) df = pd.concat(close_list, ignore_index=True) df = df.loc[(df['date'] >= '139212') & (df['date'] <= '139900')] # Read index df for indicating open market days index_path = r'E:\Thesis\New Sampling\TEDPIX\شاخص كل6.xls' index_df = pd.read_excel( index_path, usecols=[1], names=['date'], dtype={'date': str} ) index_df.dropna(inplace=True) # The list of all months months = index_df['date'].str[:6].unique().tolist() # The list of months that we need for calculating market cap me_months = [ '139312', '139401', '139402', '139403', '139404', '139405', '139406', '139407', '139408', '139409', '139410', '139411', '139412', '139501', '139502', '139503', '139504', '139505', '139506', '139507', '139508', '139509', '139510', '139511', '139512', '139601', '139602', '139603', '139604', '139605', '139606', '139607', '139608', '139609', '139610', '139611', '139612', '139701', '139702', '139703', '139704', '139705', '139706', '139707', '139708', '139709', '139710', '139711', '139712', '139801', '139802', '139803', '139804', '139805', '139806', '139807', '139808', '139809', '139810', '139811', '139812' ] # The list of months that we need for camculating MOM mom_months = me_months[1:] # Merge market cap and price dfs merged_df = pd.merge(df, me_df, on=['ticker_num', 'date']) # First, create a NaN column, and then add t-13 prices merged_df.insert(5, 't-13 price', np.nan) for month in mom_months: # Find t-13 prices for ticker in range(1, 76): t_13 = months[months.index(month) - 13] t_13_condtion = (merged_df['date'] == t_13) ticker_condition = (merged_df['ticker_num'] == ticker) try: t_13_price = merged_df.loc[ t_13_condtion & ticker_condition ]['close'].values[0] previous_month = me_months[me_months.index(month) - 1] t_1_condtion = (merged_df['date'] == previous_month) merged_df.loc[ (t_1_condtion & ticker_condition), 't-13 price' ] = t_13_price except: pass # Calculate last 12 months return for month t (t-1, t-12) merged_df['past_year_return'] = ( (merged_df['close'] / merged_df['t-13 price']) - 1 ) mom_list = [] for month in mom_months: # Check t-13 price condition and t-1 market cap condition previous_month = months[months.index(month) - 1] me_condition = (merged_df['date'] == previous_month) mom_condition = (merged_df['past_year_return'].notna()) portfo_const_df = merged_df.loc[me_condition & mom_condition] # Split each month ME into two groups conditions = [ ( portfo_const_df['market_cap'] > portfo_const_df['market_cap'].median() ), ( portfo_const_df['market_cap'] <= portfo_const_df['market_cap'].median() ) ] portfolio_size = np.select(conditions, ['B', 'S']).tolist() portfo_const_df.insert(6, 'size', portfolio_size) # Split each me portfolio into 3 MOM group q = [0, .3, .7, 1] labels = ['L', 'M', 'H'] x_b = portfo_const_df.loc[ portfo_const_df['size'] == 'B' ]['past_year_return'] b_mom = pd.qcut(x=x_b, q=q, labels=labels).to_dict() x_s = portfo_const_df.loc[ portfo_const_df['size'] == 'S' ]['past_year_return'] s_mom = pd.qcut(x=x_s, q=q, labels=labels).to_dict() portfo_const_df['mom'] = pd.Series(b_mom) portfo_const_df['mom'].update(pd.Series(s_mom)) # Extrect portfolio ticker numbers portfo_const_df['portfolio'] = ( portfo_const_df['size'] + portfo_const_df['mom'] ) bh = portfo_const_df.loc[ portfo_const_df['portfolio'] == 'BH' ]['ticker_num'].tolist() bl = portfo_const_df.loc[ portfo_const_df['portfolio'] == 'BL' ]['ticker_num'].tolist() sh = portfo_const_df.loc[ portfo_const_df['portfolio'] == 'SH' ]['ticker_num'].tolist() sl = portfo_const_df.loc[ portfo_const_df['portfolio'] == 'SL' ]['ticker_num'].tolist() # Calculating value-weighted return for each portfolio in month t # Set conditions month_condition = (merged_df['date'] == month) bh_condition = merged_df['ticker_num'].isin(bh) bl_condition = merged_df['ticker_num'].isin(bl) sh_condition = merged_df['ticker_num'].isin(sh) sl_condition = merged_df['ticker_num'].isin(sl) # Construct portfolios bh_portfolio = merged_df.loc[month_condition & bh_condition] bl_portfolio = merged_df.loc[month_condition & bl_condition] sh_portfolio = merged_df.loc[month_condition & sh_condition] sl_portfolio = merged_df.loc[month_condition & sl_condition] # Calculate value-weighted returns bh_return = np.average( bh_portfolio.monthly_return, weights=bh_portfolio.market_cap ) bl_return = np.average( bl_portfolio.monthly_return, weights=bl_portfolio.market_cap ) sh_return = np.average( sh_portfolio.monthly_return, weights=sh_portfolio.market_cap ) sl_return = np.average( sl_portfolio.monthly_return, weights=sl_portfolio.market_cap ) # Calculate MOM, and add it to a list mom = ( ((sh_return + bh_return) / 2) - ((sl_return + bl_return) / 2) ) mom_list.append(mom) mom_df = pd.Series(mom_list).to_excel('mom.xlsx')
en
0.728143
# Read Bourseview data for market cap # Concat all 75 tickers' data # Change order from old to new dates # Delete non-traded days # Create monthly dataframe # Read rahavard 365 data for calculating returns # Solve index reading problem, pandas add 2 index to the df # Convert to shamsi dates # Create monthly dataframe # Read index df for indicating open market days # The list of all months # The list of months that we need for calculating market cap # The list of months that we need for camculating MOM # Merge market cap and price dfs # First, create a NaN column, and then add t-13 prices # Find t-13 prices # Calculate last 12 months return for month t (t-1, t-12) # Check t-13 price condition and t-1 market cap condition # Split each month ME into two groups # Split each me portfolio into 3 MOM group # Extrect portfolio ticker numbers # Calculating value-weighted return for each portfolio in month t # Set conditions # Construct portfolios # Calculate value-weighted returns # Calculate MOM, and add it to a list
2.453526
2
source/lambda/geoip_downloader/index.py
aws-samples/siem-on-amazon-opensearch-service
92
75
<reponame>aws-samples/siem-on-amazon-opensearch-service<filename>source/lambda/geoip_downloader/index.py # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 __copyright__ = ('Copyright Amazon.com, Inc. or its affiliates. ' 'All Rights Reserved.') __version__ = '2.7.1' __license__ = 'MIT-0' __author__ = '<NAME>' __url__ = 'https://github.com/aws-samples/siem-on-amazon-opensearch-service' import hashlib import json import os import tarfile import urllib.error import urllib.parse import urllib.request import boto3 # get var from lambda environment try: s3bucket_name = os.environ['s3bucket_name'] license_key = os.environ['license_key'] except KeyError: raise Exception('ERROR: impossible to get lambda environment') s3key_prefix = os.environ.get('s3key_prefix', 'GeoLite2/') s3 = boto3.resource('s3') bucket = s3.Bucket(s3bucket_name) url = 'https://download.maxmind.com/app/geoip_download?' put_files = ['GeoLite2-City', 'GeoLite2-ASN', 'GeoLite2-Country'] def download_file(filename): for suffix in ['tar.gz', 'tar.gz.sha256']: values = {'edition_id': filename, 'license_key': license_key, 'suffix': suffix} data = urllib.parse.urlencode(values) try: urllib.request.urlretrieve( url + data, filename='/tmp/' + filename + '.' + suffix) except urllib.error.HTTPError as err: if err.status == 401: return err.status print(err) raise Exception('ERROR: http error') except Exception as err: print(err) raise Exception('ERROR: ' + err) print('INFO: ' + filename + ' was downloaded') return 200 def put_to_s3(filename): with open('/tmp/' + filename + '.tar.gz.sha256') as f: checksum = f.read().split()[0] print('INFO: Checksum: ' + checksum) with open('/tmp/' + filename + '.tar.gz', 'rb') as f: calcurated_checksum = hashlib.sha256(f.read()).hexdigest() if checksum not in calcurated_checksum: print('ERROR: checksum is different. download is failed') return False with tarfile.open('/tmp/' + filename + '.tar.gz', 'r:gz') as tf: directory = tf.getmembers()[0].name tf.extractall(path='/tmp/') mmdb = directory + '/' + filename + '.mmdb' s3obj = s3key_prefix + filename + '.mmdb' bucket.upload_file('/tmp/' + mmdb, s3obj) print('INFO: uploaded {0} to s3://{1}/{2}'.format( mmdb, s3bucket_name, s3obj)) def send(event, context, responseStatus, responseData, physicalResourceId=None, noEcho=False): # https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/cfn-lambda-function-code-cfnresponsemodule.html responseUrl = event['ResponseURL'] print(responseUrl) response_body = {} response_body['Status'] = responseStatus response_body['Reason'] = ('See the details in CloudWatch Log Stream: ' '' + context.log_stream_name) response_body['PhysicalResourceId'] = ( physicalResourceId or context.log_stream_name) response_body['StackId'] = event['StackId'] response_body['RequestId'] = event['RequestId'] response_body['LogicalResourceId'] = event['LogicalResourceId'] response_body['NoEcho'] = noEcho response_body['Data'] = responseData json_response_body = json.dumps(response_body) print('Response body:\n' + json_response_body) headers = {'content-type': 'application/json', } req = urllib.request.Request( event['ResponseURL'], json_response_body.encode(), headers=headers, method='PUT') try: res = urllib.request.urlopen(req) print('Status code: ' + str(res.status)) except Exception as e: print('send(..) failed executing requests.put(..): ' + str(e)) def lambda_handler(event, context): physicalResourceId = 'geoipdb' status = 'None' if event: print(json.dumps(event)) try: for filename in put_files: status = download_file(filename) if status == 401: break put_to_s3(filename) except Exception as e: print(e) if event and 'RequestType' in event: response = {'failed_reason': e} send(event, context, 'FAILED', response, physicalResourceId) if event and 'RequestType' in event: if status == 401: response = {'status': 'invalide_license_key'} else: response = {'status': 'downloaded'} send(event, context, 'SUCCESS', response, physicalResourceId) return(json.dumps(response))
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 __copyright__ = ('Copyright Amazon.com, Inc. or its affiliates. ' 'All Rights Reserved.') __version__ = '2.7.1' __license__ = 'MIT-0' __author__ = '<NAME>' __url__ = 'https://github.com/aws-samples/siem-on-amazon-opensearch-service' import hashlib import json import os import tarfile import urllib.error import urllib.parse import urllib.request import boto3 # get var from lambda environment try: s3bucket_name = os.environ['s3bucket_name'] license_key = os.environ['license_key'] except KeyError: raise Exception('ERROR: impossible to get lambda environment') s3key_prefix = os.environ.get('s3key_prefix', 'GeoLite2/') s3 = boto3.resource('s3') bucket = s3.Bucket(s3bucket_name) url = 'https://download.maxmind.com/app/geoip_download?' put_files = ['GeoLite2-City', 'GeoLite2-ASN', 'GeoLite2-Country'] def download_file(filename): for suffix in ['tar.gz', 'tar.gz.sha256']: values = {'edition_id': filename, 'license_key': license_key, 'suffix': suffix} data = urllib.parse.urlencode(values) try: urllib.request.urlretrieve( url + data, filename='/tmp/' + filename + '.' + suffix) except urllib.error.HTTPError as err: if err.status == 401: return err.status print(err) raise Exception('ERROR: http error') except Exception as err: print(err) raise Exception('ERROR: ' + err) print('INFO: ' + filename + ' was downloaded') return 200 def put_to_s3(filename): with open('/tmp/' + filename + '.tar.gz.sha256') as f: checksum = f.read().split()[0] print('INFO: Checksum: ' + checksum) with open('/tmp/' + filename + '.tar.gz', 'rb') as f: calcurated_checksum = hashlib.sha256(f.read()).hexdigest() if checksum not in calcurated_checksum: print('ERROR: checksum is different. download is failed') return False with tarfile.open('/tmp/' + filename + '.tar.gz', 'r:gz') as tf: directory = tf.getmembers()[0].name tf.extractall(path='/tmp/') mmdb = directory + '/' + filename + '.mmdb' s3obj = s3key_prefix + filename + '.mmdb' bucket.upload_file('/tmp/' + mmdb, s3obj) print('INFO: uploaded {0} to s3://{1}/{2}'.format( mmdb, s3bucket_name, s3obj)) def send(event, context, responseStatus, responseData, physicalResourceId=None, noEcho=False): # https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/cfn-lambda-function-code-cfnresponsemodule.html responseUrl = event['ResponseURL'] print(responseUrl) response_body = {} response_body['Status'] = responseStatus response_body['Reason'] = ('See the details in CloudWatch Log Stream: ' '' + context.log_stream_name) response_body['PhysicalResourceId'] = ( physicalResourceId or context.log_stream_name) response_body['StackId'] = event['StackId'] response_body['RequestId'] = event['RequestId'] response_body['LogicalResourceId'] = event['LogicalResourceId'] response_body['NoEcho'] = noEcho response_body['Data'] = responseData json_response_body = json.dumps(response_body) print('Response body:\n' + json_response_body) headers = {'content-type': 'application/json', } req = urllib.request.Request( event['ResponseURL'], json_response_body.encode(), headers=headers, method='PUT') try: res = urllib.request.urlopen(req) print('Status code: ' + str(res.status)) except Exception as e: print('send(..) failed executing requests.put(..): ' + str(e)) def lambda_handler(event, context): physicalResourceId = 'geoipdb' status = 'None' if event: print(json.dumps(event)) try: for filename in put_files: status = download_file(filename) if status == 401: break put_to_s3(filename) except Exception as e: print(e) if event and 'RequestType' in event: response = {'failed_reason': e} send(event, context, 'FAILED', response, physicalResourceId) if event and 'RequestType' in event: if status == 401: response = {'status': 'invalide_license_key'} else: response = {'status': 'downloaded'} send(event, context, 'SUCCESS', response, physicalResourceId) return(json.dumps(response))
en
0.726815
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 # get var from lambda environment # https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/cfn-lambda-function-code-cfnresponsemodule.html
2.236546
2
components/mroipac/baseline/Baseline.py
earthobservatory/isce2
1
76
<gh_stars>1-10 #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Copyright 2010 California Institute of Technology. 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. # # United States Government Sponsorship acknowledged. This software is subject to # U.S. export control laws and regulations and has been classified as 'EAR99 NLR' # (No [Export] License Required except when exporting to an embargoed country, # end user, or in support of a prohibited end use). By downloading this software, # the user agrees to comply with all applicable U.S. export laws and regulations. # The user has the responsibility to obtain export licenses, or other export # authority as may be required before exporting this software to any 'EAR99' # embargoed foreign country or citizen of those countries. # # Author: <NAME> #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ import math import datetime import logging from iscesys.Component.Component import Component, Port from isceobj.Util.mathModule import MathModule as MM from isceobj.Orbit.Orbit import StateVector # A class to hold three-dimensional basis vectors class Basis(object): def __init__(self): self.x1 = [] self.x2 = [] self.x3 = [] # A class to hold three-dimensional basis vectors for spacecraft baselines class BaselineBasis(Basis): def __init__(self): Basis.__init__(self) def setPositionVector(self,x): self.x1 = x def getPositionVector(self): return self.x1 def setVelocityVector(self,v): self.x2 = v def getVelocityVector(self): return self.x2 def setCrossTrackVector(self,c): self.x3 = c def getCrossTrackVector(self): return self.x3 BASELINE_LOCATION = Component.Parameter('baselineLocation', public_name = 'BASELINE_LOCATION', default = 'all', type=str, mandatory=False, doc = ('Location at which to compute baselines - "all" implies '+ 'top, middle, bottom of master image, '+ '"top" implies near start of master image, '+ '"bottom" implies at bottom of master image, '+ '"middle" implies near middle of master image. '+ 'To be used in case there is a large shift between images.') ) class Baseline(Component): family = 'baseline' logging_name = 'isce.mroipac.baseline' parameter_list = (BASELINE_LOCATION,) # Calculate the Look Angle of the master frame def calculateLookAngle(self): lookVector = self.calculateLookVector() return math.degrees(math.atan2(lookVector[1],lookVector[0])) # Calculate the look vector of the master frame def calculateLookVector(self): try: z = self.masterFrame.terrainHeight except: z = 0.0 cosl = ((self.height-z)*(2*self.radius + self.height + z) + self.startingRange1*self.startingRange1)/( 2*self.startingRange1*(self.radius + self.height) ) # print('Height: ', self.height) # print('Radius: ', self.radius) # print('Range: ', self.startingRange1) # print('COSL: ', cosl) sinl = math.sqrt(1 - cosl*cosl) return [cosl,sinl] # Calculate the scalar spacecraft velocity def calculateScalarVelocity(self,orbit,time): sv = orbit.interpolateOrbit(time, method='hermite') v = sv.getVelocity() normV = MM.norm(v) return normV # Given an orbit and a time, calculate an orthogonal basis for cross-track and velocity directions # based on the spacecraft position def calculateBasis(self,orbit,time): sv = orbit.interpolateOrbit(time, method='hermite') x1 = sv.getPosition() v = sv.getVelocity() r = MM.normalizeVector(x1) # Turn the position vector into a unit vector v = MM.normalizeVector(v) # Turn the velocity vector into a unit vector c = MM.crossProduct(r,v) # Calculate the vector perpendicular to the platform position and velocity, this is the c, or cross-track vector c = MM.normalizeVector(c) v = MM.crossProduct(c,r) # Calculate a the "velocity" component that is perpendicular to the cross-track direction and position basis = BaselineBasis() basis.setPositionVector(r) basis.setVelocityVector(v) basis.setCrossTrackVector(c) return basis # Given two position vectors and a basis, calculate the offset between the two positions in this basis def calculateBasisOffset(self,x1,x2,basis): dx = [(x2[j] - x1[j]) for j in range(len(x1))] # Calculate the difference between the master and slave position vectors z_offset = MM.dotProduct(dx,basis.getVelocityVector()) # Calculate the length of the projection of the difference in position and the "velocity" component v_offset = MM.dotProduct(dx,basis.getPositionVector()) c_offset = MM.dotProduct(dx,basis.getCrossTrackVector()) return z_offset,v_offset,c_offset # Calculate the baseline components between two frames def baseline(self): #TODO This could be further refactored into a method that calculates the baseline between #TODO frames when given a master time and a slave time and a method that calls this method #TODO multiple times to calculate the rate of baseline change over time. for port in self.inputPorts: port() lookVector = self.calculateLookVector() az_offset = [] vb = [] hb = [] csb = [] asb = [] s = [0.,0.,0.] if self.baselineLocation.lower() == 'all': print('Using entire span of image for estimating baselines') masterTime = [self.masterFrame.getSensingStart(),self.masterFrame.getSensingMid(),self.masterFrame.getSensingStop()] elif self.baselineLocation.lower() == 'middle': print('Estimating baselines around center of master image') masterTime = [self.masterFrame.getSensingMid() - datetime.timedelta(seconds=1.0), self.masterFrame.getSensingMid(), self.masterFrame.getSensingMid() + datetime.timedelta(seconds=1.0)] elif self.baselineLocation.lower() == 'top': print('Estimating baselines at top of master image') masterTime = [self.masterFrame.getSensingStart(), self.masterFrame.getSensingStart() + datetime.timedelta(seconds=1.0), self.masterFrame.getSensingStart() + datetime.timedelta(seconds=2.0)] elif self.baselineLocation.lower() == 'bottom': print('Estimating baselines at bottom of master image') masterTime = [self.masterFrame.getSensingStop() - datetime.timedelta(seconds=2.0), self.masterFrame.getSensingStop() - datetime.timedelta(seconds=1.0), self.masterFrame.getSensingStop()] else: raise Exception('Unknown baseline location: {0}'.format(self.baselineLocation)) slaveTime = [self.slaveFrame.getSensingMid() - datetime.timedelta(seconds=1.0), self.slaveFrame.getSensingMid(), self.slaveFrame.getSensingMid() + datetime.timedelta(seconds=1.0)] # slaveTime = [self.slaveFrame.getSensingStart(),self.slaveFrame.getSensingMid(),self.slaveFrame.getSensingStop()] for i in range(3): # Calculate the Baseline at the start of the scene, mid-scene, and the end of the scene # First, get the position and velocity at the start of the scene self.logger.info("Sampling time %s" % i) masterBasis = self.calculateBasis(self.masterOrbit,masterTime[i]) normV = self.calculateScalarVelocity(self.masterOrbit,masterTime[i]) # Calculate the distance moved since the last baseline point if (i > 0): deltaT = self._timeDeltaToSeconds(masterTime[i] - masterTime[0]) s[i] = s[i-1] + deltaT*normV masterSV = self.masterOrbit.interpolateOrbit(masterTime[i], method='hermite') slaveSV = self.slaveOrbit.interpolateOrbit(slaveTime[i], method='hermite') x1 = masterSV.getPosition() x2 = slaveSV.getPosition() (z_offset,v_offset,c_offset) = self.calculateBasisOffset(x1,x2,masterBasis) az_offset.append(z_offset) # Save the position offset # Calculate a new start time relativeSlaveTime = slaveTime[i] - datetime.timedelta(seconds=(z_offset/normV)) slaveSV = self.slaveOrbit.interpolateOrbit(relativeSlaveTime, method='hermite') # Recalculate the offsets x2 = slaveSV.getPosition() (z_offset,v_offset,c_offset) = self.calculateBasisOffset(x1,x2,masterBasis) vb.append(v_offset) hb.append(c_offset) csb.append(-hb[i]*lookVector[0] + vb[i]*lookVector[1]) # Multiply the horizontal and vertical baseline components by the look angle vector asb.append(-hb[i]*lookVector[1] - vb[i]*lookVector[0]) #Calculating baseline crossTrackBaselinePolynomialCoefficients = self.polynomialFit(s,hb) verticalBaselinePolynomialCoefficients = self.polynomialFit(s,vb) h_rate = crossTrackBaselinePolynomialCoefficients[1] # Calculate the gross azimuth and range offsets azb_avg = (az_offset[0] + az_offset[-1])/2.0 asb_avg = (asb[0] + asb[-1])/2.0 az_offset = (-azb_avg - h_rate*self.startingRange1*lookVector[1])/(self.azimuthPixelSize) r_offset = (self.startingRange1 - self.startingRange2 - asb_avg)/(self.rangePixelSize) # Populate class attributes self.hBaselineTop = crossTrackBaselinePolynomialCoefficients[0] self.hBaselineRate = crossTrackBaselinePolynomialCoefficients[1] self.hBaselineAcc = crossTrackBaselinePolynomialCoefficients[2] self.vBaselineTop = verticalBaselinePolynomialCoefficients[0] self.vBaselineRate = verticalBaselinePolynomialCoefficients[1] self.vBaselineAcc = verticalBaselinePolynomialCoefficients[2] self.pBaselineTop = csb[0] self.pBaselineBottom = csb[-1] self.orbSlcAzimuthOffset = az_offset self.orbSlcRangeOffset = r_offset self.rangeOffset = self.startingRange1 - self.startingRange2 # Calculate a quadratic fit to the baseline polynomial def polynomialFit(self,xRef,yRef): size = len(xRef) if not (len(xRef) == len(yRef)): print("Error. Expecting input vectors of same length.") raise Exception if not (size == 3): print("Error. Expecting input vectors of length 3.") raise Exception Y = [0]*size A = [0]*size M = [[0 for i in range(size) ] for j in range(size)] for j in range(size): for i in range(size): M[j][i] = math.pow(xRef[j],i) Y[j] = yRef[j] MInv = MM.invertMatrix(M) for i in range(size): for j in range(size): A[i] += MInv[i][j]*Y[j] return A def setRangePixelSize(self,pixelSize): self.rangePixelSize = pixelSize return def setAzimuthPixelSize(self,pixelSize): self.azimuthPixelSize = pixelSize return def setHeight(self,var): self.height = float(var) return def setRadius(self,radius): self.radius = radius return def setMasterStartingRange(self,range): self.startingRange1 = range return def setSlaveStartingRange(self,range): self.startingRange2 = range return def getHBaselineTop(self): return self.hBaselineTop def getHBaselineRate(self): return self.hBaselineRate def getHBaselineAcc(self): return self.hBaselineAcc def getVBaselineTop(self): return self.vBaselineTop def getVBaselineRate(self): return self.vBaselineRate def getVBaselineAcc(self): return self.vBaselineAcc def getPBaselineTop(self): return self.pBaselineTop def getPBaselineBottom(self): return self.pBaselineBottom def getOrbSlcAzimuthOffset(self): return self.orbSlcAzimuthOffset def getOrbSlcRangeOffset(self): return self.orbSlcRangeOffset def getRangeOffset(self): return self.rangeOffset def getPhaseConst(self): return self.phaseConst def getLookAngle(self): return self.lookAngle def _timeDeltaToSeconds(self,td): return (td.microseconds + (td.seconds + td.days * 24.0 * 3600) * 10**6) / 10**6 def addMasterFrame(self): frame = self._inputPorts.getPort(name='masterFrame').getObject() self.masterFrame = frame self.startingRange1 = frame.getStartingRange() prf = frame.getInstrument().getPulseRepetitionFrequency() self.rangePixelSize = frame.getInstrument().getRangePixelSize() self.masterOrbit = frame.getOrbit() midSV = self.masterOrbit.interpolateOrbit(frame.getSensingMid(), method='hermite') self.azimuthPixelSize = midSV.getScalarVelocity()/prf try: ellipsoid = frame._ellipsoid #UAVSAR frame creates ellipsoid with peg self.radius = ellipsoid.pegRadCur self.height = frame.platformHeight except: ellipsoid = frame.getInstrument().getPlatform().getPlanet().get_elp() self.radius = ellipsoid.get_a() self.height = midSV.calculateHeight(ellipsoid) def addSlaveFrame(self): frame = self._inputPorts.getPort(name='slaveFrame').getObject() self.slaveFrame = frame self.startingRange2 = frame.getStartingRange() self.slaveOrbit = frame.getOrbit() def __init__(self, name=''): self.masterOrbit = None self.slaveOrbit = None self.masterFrame = None self.slaveFrame = None self.lookAngle = None self.rangePixelSize = None self.azimuthPixelSize = None self.height = None self.radius = None self.startingRange1 = None self.startingRange2 = None self.hBaselineTop = None self.hBaselineRate = None self.hBaselineAcc = None self.vBaselineTop = None self.vBaselineRate = None self.vBaselineAcc = None self.pBaselineTop = None self.pBaselineBottom = None self.orbSlcAzimuthOffset = None self.orbSlcRangeOffset = None self.rangeOffset = None self.phaseConst = -99999 super(Baseline, self).__init__(family=self.__class__.family, name=name) self.logger = logging.getLogger('isce.mroipac.baseline') self.createPorts() # Satisfy the old Component self.dictionaryOfOutputVariables = {} self.dictionaryOfVariables = {} self.descriptionOfVariables = {} self.mandatoryVariables = [] self.optionalVariables = [] return None def createPorts(self): # Set input ports # It looks like we really need two orbits, a time, range and azimuth pixel sizes # the two starting ranges, a planet, and the two prfs # These provide the orbits # These provide the range and azimuth pixel sizes, starting ranges, # satellite heights and times for the first lines masterFramePort = Port(name='masterFrame',method=self.addMasterFrame) slaveFramePort = Port(name='slaveFrame',method=self.addSlaveFrame) self._inputPorts.add(masterFramePort) self._inputPorts.add(slaveFramePort) return None def __str__(self): retstr = "Initial Baseline estimates \n" retstr += "Cross-track Baseline: %s\n" retlst = (self.hBaselineTop,) retstr += "Vertical Baseline: %s\n" retlst += (self.vBaselineTop,) retstr += "Perpendicular Baseline: %s\n" retlst += (self.pBaselineTop,) retstr += "Bulk Azimuth Offset: %s\n" retlst += (self.orbSlcAzimuthOffset,) retstr += "Bulk Range Offset: %s\n" retlst += (self.orbSlcRangeOffset,) return retstr % retlst
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Copyright 2010 California Institute of Technology. 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. # # United States Government Sponsorship acknowledged. This software is subject to # U.S. export control laws and regulations and has been classified as 'EAR99 NLR' # (No [Export] License Required except when exporting to an embargoed country, # end user, or in support of a prohibited end use). By downloading this software, # the user agrees to comply with all applicable U.S. export laws and regulations. # The user has the responsibility to obtain export licenses, or other export # authority as may be required before exporting this software to any 'EAR99' # embargoed foreign country or citizen of those countries. # # Author: <NAME> #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ import math import datetime import logging from iscesys.Component.Component import Component, Port from isceobj.Util.mathModule import MathModule as MM from isceobj.Orbit.Orbit import StateVector # A class to hold three-dimensional basis vectors class Basis(object): def __init__(self): self.x1 = [] self.x2 = [] self.x3 = [] # A class to hold three-dimensional basis vectors for spacecraft baselines class BaselineBasis(Basis): def __init__(self): Basis.__init__(self) def setPositionVector(self,x): self.x1 = x def getPositionVector(self): return self.x1 def setVelocityVector(self,v): self.x2 = v def getVelocityVector(self): return self.x2 def setCrossTrackVector(self,c): self.x3 = c def getCrossTrackVector(self): return self.x3 BASELINE_LOCATION = Component.Parameter('baselineLocation', public_name = 'BASELINE_LOCATION', default = 'all', type=str, mandatory=False, doc = ('Location at which to compute baselines - "all" implies '+ 'top, middle, bottom of master image, '+ '"top" implies near start of master image, '+ '"bottom" implies at bottom of master image, '+ '"middle" implies near middle of master image. '+ 'To be used in case there is a large shift between images.') ) class Baseline(Component): family = 'baseline' logging_name = 'isce.mroipac.baseline' parameter_list = (BASELINE_LOCATION,) # Calculate the Look Angle of the master frame def calculateLookAngle(self): lookVector = self.calculateLookVector() return math.degrees(math.atan2(lookVector[1],lookVector[0])) # Calculate the look vector of the master frame def calculateLookVector(self): try: z = self.masterFrame.terrainHeight except: z = 0.0 cosl = ((self.height-z)*(2*self.radius + self.height + z) + self.startingRange1*self.startingRange1)/( 2*self.startingRange1*(self.radius + self.height) ) # print('Height: ', self.height) # print('Radius: ', self.radius) # print('Range: ', self.startingRange1) # print('COSL: ', cosl) sinl = math.sqrt(1 - cosl*cosl) return [cosl,sinl] # Calculate the scalar spacecraft velocity def calculateScalarVelocity(self,orbit,time): sv = orbit.interpolateOrbit(time, method='hermite') v = sv.getVelocity() normV = MM.norm(v) return normV # Given an orbit and a time, calculate an orthogonal basis for cross-track and velocity directions # based on the spacecraft position def calculateBasis(self,orbit,time): sv = orbit.interpolateOrbit(time, method='hermite') x1 = sv.getPosition() v = sv.getVelocity() r = MM.normalizeVector(x1) # Turn the position vector into a unit vector v = MM.normalizeVector(v) # Turn the velocity vector into a unit vector c = MM.crossProduct(r,v) # Calculate the vector perpendicular to the platform position and velocity, this is the c, or cross-track vector c = MM.normalizeVector(c) v = MM.crossProduct(c,r) # Calculate a the "velocity" component that is perpendicular to the cross-track direction and position basis = BaselineBasis() basis.setPositionVector(r) basis.setVelocityVector(v) basis.setCrossTrackVector(c) return basis # Given two position vectors and a basis, calculate the offset between the two positions in this basis def calculateBasisOffset(self,x1,x2,basis): dx = [(x2[j] - x1[j]) for j in range(len(x1))] # Calculate the difference between the master and slave position vectors z_offset = MM.dotProduct(dx,basis.getVelocityVector()) # Calculate the length of the projection of the difference in position and the "velocity" component v_offset = MM.dotProduct(dx,basis.getPositionVector()) c_offset = MM.dotProduct(dx,basis.getCrossTrackVector()) return z_offset,v_offset,c_offset # Calculate the baseline components between two frames def baseline(self): #TODO This could be further refactored into a method that calculates the baseline between #TODO frames when given a master time and a slave time and a method that calls this method #TODO multiple times to calculate the rate of baseline change over time. for port in self.inputPorts: port() lookVector = self.calculateLookVector() az_offset = [] vb = [] hb = [] csb = [] asb = [] s = [0.,0.,0.] if self.baselineLocation.lower() == 'all': print('Using entire span of image for estimating baselines') masterTime = [self.masterFrame.getSensingStart(),self.masterFrame.getSensingMid(),self.masterFrame.getSensingStop()] elif self.baselineLocation.lower() == 'middle': print('Estimating baselines around center of master image') masterTime = [self.masterFrame.getSensingMid() - datetime.timedelta(seconds=1.0), self.masterFrame.getSensingMid(), self.masterFrame.getSensingMid() + datetime.timedelta(seconds=1.0)] elif self.baselineLocation.lower() == 'top': print('Estimating baselines at top of master image') masterTime = [self.masterFrame.getSensingStart(), self.masterFrame.getSensingStart() + datetime.timedelta(seconds=1.0), self.masterFrame.getSensingStart() + datetime.timedelta(seconds=2.0)] elif self.baselineLocation.lower() == 'bottom': print('Estimating baselines at bottom of master image') masterTime = [self.masterFrame.getSensingStop() - datetime.timedelta(seconds=2.0), self.masterFrame.getSensingStop() - datetime.timedelta(seconds=1.0), self.masterFrame.getSensingStop()] else: raise Exception('Unknown baseline location: {0}'.format(self.baselineLocation)) slaveTime = [self.slaveFrame.getSensingMid() - datetime.timedelta(seconds=1.0), self.slaveFrame.getSensingMid(), self.slaveFrame.getSensingMid() + datetime.timedelta(seconds=1.0)] # slaveTime = [self.slaveFrame.getSensingStart(),self.slaveFrame.getSensingMid(),self.slaveFrame.getSensingStop()] for i in range(3): # Calculate the Baseline at the start of the scene, mid-scene, and the end of the scene # First, get the position and velocity at the start of the scene self.logger.info("Sampling time %s" % i) masterBasis = self.calculateBasis(self.masterOrbit,masterTime[i]) normV = self.calculateScalarVelocity(self.masterOrbit,masterTime[i]) # Calculate the distance moved since the last baseline point if (i > 0): deltaT = self._timeDeltaToSeconds(masterTime[i] - masterTime[0]) s[i] = s[i-1] + deltaT*normV masterSV = self.masterOrbit.interpolateOrbit(masterTime[i], method='hermite') slaveSV = self.slaveOrbit.interpolateOrbit(slaveTime[i], method='hermite') x1 = masterSV.getPosition() x2 = slaveSV.getPosition() (z_offset,v_offset,c_offset) = self.calculateBasisOffset(x1,x2,masterBasis) az_offset.append(z_offset) # Save the position offset # Calculate a new start time relativeSlaveTime = slaveTime[i] - datetime.timedelta(seconds=(z_offset/normV)) slaveSV = self.slaveOrbit.interpolateOrbit(relativeSlaveTime, method='hermite') # Recalculate the offsets x2 = slaveSV.getPosition() (z_offset,v_offset,c_offset) = self.calculateBasisOffset(x1,x2,masterBasis) vb.append(v_offset) hb.append(c_offset) csb.append(-hb[i]*lookVector[0] + vb[i]*lookVector[1]) # Multiply the horizontal and vertical baseline components by the look angle vector asb.append(-hb[i]*lookVector[1] - vb[i]*lookVector[0]) #Calculating baseline crossTrackBaselinePolynomialCoefficients = self.polynomialFit(s,hb) verticalBaselinePolynomialCoefficients = self.polynomialFit(s,vb) h_rate = crossTrackBaselinePolynomialCoefficients[1] # Calculate the gross azimuth and range offsets azb_avg = (az_offset[0] + az_offset[-1])/2.0 asb_avg = (asb[0] + asb[-1])/2.0 az_offset = (-azb_avg - h_rate*self.startingRange1*lookVector[1])/(self.azimuthPixelSize) r_offset = (self.startingRange1 - self.startingRange2 - asb_avg)/(self.rangePixelSize) # Populate class attributes self.hBaselineTop = crossTrackBaselinePolynomialCoefficients[0] self.hBaselineRate = crossTrackBaselinePolynomialCoefficients[1] self.hBaselineAcc = crossTrackBaselinePolynomialCoefficients[2] self.vBaselineTop = verticalBaselinePolynomialCoefficients[0] self.vBaselineRate = verticalBaselinePolynomialCoefficients[1] self.vBaselineAcc = verticalBaselinePolynomialCoefficients[2] self.pBaselineTop = csb[0] self.pBaselineBottom = csb[-1] self.orbSlcAzimuthOffset = az_offset self.orbSlcRangeOffset = r_offset self.rangeOffset = self.startingRange1 - self.startingRange2 # Calculate a quadratic fit to the baseline polynomial def polynomialFit(self,xRef,yRef): size = len(xRef) if not (len(xRef) == len(yRef)): print("Error. Expecting input vectors of same length.") raise Exception if not (size == 3): print("Error. Expecting input vectors of length 3.") raise Exception Y = [0]*size A = [0]*size M = [[0 for i in range(size) ] for j in range(size)] for j in range(size): for i in range(size): M[j][i] = math.pow(xRef[j],i) Y[j] = yRef[j] MInv = MM.invertMatrix(M) for i in range(size): for j in range(size): A[i] += MInv[i][j]*Y[j] return A def setRangePixelSize(self,pixelSize): self.rangePixelSize = pixelSize return def setAzimuthPixelSize(self,pixelSize): self.azimuthPixelSize = pixelSize return def setHeight(self,var): self.height = float(var) return def setRadius(self,radius): self.radius = radius return def setMasterStartingRange(self,range): self.startingRange1 = range return def setSlaveStartingRange(self,range): self.startingRange2 = range return def getHBaselineTop(self): return self.hBaselineTop def getHBaselineRate(self): return self.hBaselineRate def getHBaselineAcc(self): return self.hBaselineAcc def getVBaselineTop(self): return self.vBaselineTop def getVBaselineRate(self): return self.vBaselineRate def getVBaselineAcc(self): return self.vBaselineAcc def getPBaselineTop(self): return self.pBaselineTop def getPBaselineBottom(self): return self.pBaselineBottom def getOrbSlcAzimuthOffset(self): return self.orbSlcAzimuthOffset def getOrbSlcRangeOffset(self): return self.orbSlcRangeOffset def getRangeOffset(self): return self.rangeOffset def getPhaseConst(self): return self.phaseConst def getLookAngle(self): return self.lookAngle def _timeDeltaToSeconds(self,td): return (td.microseconds + (td.seconds + td.days * 24.0 * 3600) * 10**6) / 10**6 def addMasterFrame(self): frame = self._inputPorts.getPort(name='masterFrame').getObject() self.masterFrame = frame self.startingRange1 = frame.getStartingRange() prf = frame.getInstrument().getPulseRepetitionFrequency() self.rangePixelSize = frame.getInstrument().getRangePixelSize() self.masterOrbit = frame.getOrbit() midSV = self.masterOrbit.interpolateOrbit(frame.getSensingMid(), method='hermite') self.azimuthPixelSize = midSV.getScalarVelocity()/prf try: ellipsoid = frame._ellipsoid #UAVSAR frame creates ellipsoid with peg self.radius = ellipsoid.pegRadCur self.height = frame.platformHeight except: ellipsoid = frame.getInstrument().getPlatform().getPlanet().get_elp() self.radius = ellipsoid.get_a() self.height = midSV.calculateHeight(ellipsoid) def addSlaveFrame(self): frame = self._inputPorts.getPort(name='slaveFrame').getObject() self.slaveFrame = frame self.startingRange2 = frame.getStartingRange() self.slaveOrbit = frame.getOrbit() def __init__(self, name=''): self.masterOrbit = None self.slaveOrbit = None self.masterFrame = None self.slaveFrame = None self.lookAngle = None self.rangePixelSize = None self.azimuthPixelSize = None self.height = None self.radius = None self.startingRange1 = None self.startingRange2 = None self.hBaselineTop = None self.hBaselineRate = None self.hBaselineAcc = None self.vBaselineTop = None self.vBaselineRate = None self.vBaselineAcc = None self.pBaselineTop = None self.pBaselineBottom = None self.orbSlcAzimuthOffset = None self.orbSlcRangeOffset = None self.rangeOffset = None self.phaseConst = -99999 super(Baseline, self).__init__(family=self.__class__.family, name=name) self.logger = logging.getLogger('isce.mroipac.baseline') self.createPorts() # Satisfy the old Component self.dictionaryOfOutputVariables = {} self.dictionaryOfVariables = {} self.descriptionOfVariables = {} self.mandatoryVariables = [] self.optionalVariables = [] return None def createPorts(self): # Set input ports # It looks like we really need two orbits, a time, range and azimuth pixel sizes # the two starting ranges, a planet, and the two prfs # These provide the orbits # These provide the range and azimuth pixel sizes, starting ranges, # satellite heights and times for the first lines masterFramePort = Port(name='masterFrame',method=self.addMasterFrame) slaveFramePort = Port(name='slaveFrame',method=self.addSlaveFrame) self._inputPorts.add(masterFramePort) self._inputPorts.add(slaveFramePort) return None def __str__(self): retstr = "Initial Baseline estimates \n" retstr += "Cross-track Baseline: %s\n" retlst = (self.hBaselineTop,) retstr += "Vertical Baseline: %s\n" retlst += (self.vBaselineTop,) retstr += "Perpendicular Baseline: %s\n" retlst += (self.pBaselineTop,) retstr += "Bulk Azimuth Offset: %s\n" retlst += (self.orbSlcAzimuthOffset,) retstr += "Bulk Range Offset: %s\n" retlst += (self.orbSlcRangeOffset,) return retstr % retlst
en
0.818031
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Copyright 2010 California Institute of Technology. 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. # # United States Government Sponsorship acknowledged. This software is subject to # U.S. export control laws and regulations and has been classified as 'EAR99 NLR' # (No [Export] License Required except when exporting to an embargoed country, # end user, or in support of a prohibited end use). By downloading this software, # the user agrees to comply with all applicable U.S. export laws and regulations. # The user has the responsibility to obtain export licenses, or other export # authority as may be required before exporting this software to any 'EAR99' # embargoed foreign country or citizen of those countries. # # Author: <NAME> #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # A class to hold three-dimensional basis vectors # A class to hold three-dimensional basis vectors for spacecraft baselines # Calculate the Look Angle of the master frame # Calculate the look vector of the master frame # print('Height: ', self.height) # print('Radius: ', self.radius) # print('Range: ', self.startingRange1) # print('COSL: ', cosl) # Calculate the scalar spacecraft velocity # Given an orbit and a time, calculate an orthogonal basis for cross-track and velocity directions # based on the spacecraft position # Turn the position vector into a unit vector # Turn the velocity vector into a unit vector # Calculate the vector perpendicular to the platform position and velocity, this is the c, or cross-track vector # Calculate a the "velocity" component that is perpendicular to the cross-track direction and position # Given two position vectors and a basis, calculate the offset between the two positions in this basis # Calculate the difference between the master and slave position vectors # Calculate the length of the projection of the difference in position and the "velocity" component # Calculate the baseline components between two frames #TODO This could be further refactored into a method that calculates the baseline between #TODO frames when given a master time and a slave time and a method that calls this method #TODO multiple times to calculate the rate of baseline change over time. # slaveTime = [self.slaveFrame.getSensingStart(),self.slaveFrame.getSensingMid(),self.slaveFrame.getSensingStop()] # Calculate the Baseline at the start of the scene, mid-scene, and the end of the scene # First, get the position and velocity at the start of the scene # Calculate the distance moved since the last baseline point # Save the position offset # Calculate a new start time # Recalculate the offsets # Multiply the horizontal and vertical baseline components by the look angle vector #Calculating baseline # Calculate the gross azimuth and range offsets # Populate class attributes # Calculate a quadratic fit to the baseline polynomial #UAVSAR frame creates ellipsoid with peg # Satisfy the old Component # Set input ports # It looks like we really need two orbits, a time, range and azimuth pixel sizes # the two starting ranges, a planet, and the two prfs # These provide the orbits # These provide the range and azimuth pixel sizes, starting ranges, # satellite heights and times for the first lines
1.472274
1
src/modules/deuces/deck.py
Bot-Box/FiveCardStud
0
77
<filename>src/modules/deuces/deck.py from random import shuffle as rshuffle from .card import Card class Deck: """ Class representing a deck. The first time we create, we seed the static deck with the list of unique card integers. Each object instantiated simply makes a copy of this object and shuffles it. """ _FULL_DECK = [] def __init__(self): self.shuffle() def shuffle(self): # and then shuffle self.cards = Deck.GetFullDeck() rshuffle(self.cards) def draw(self, n=1): if n == 1: return self.cards.pop(0) cards = [] for i in range(n): cards.append(self.draw()) return cards def __str__(self): return Card.print_pretty_cards(self.cards) @staticmethod def GetFullDeck(): if Deck._FULL_DECK: return list(Deck._FULL_DECK) # create the standard 52 card deck for rank in Card.STR_RANKS: for suit, val in Card.CHAR_SUIT_TO_INT_SUIT.items(): Deck._FULL_DECK.append(Card.new(rank + suit)) return list(Deck._FULL_DECK)
<filename>src/modules/deuces/deck.py from random import shuffle as rshuffle from .card import Card class Deck: """ Class representing a deck. The first time we create, we seed the static deck with the list of unique card integers. Each object instantiated simply makes a copy of this object and shuffles it. """ _FULL_DECK = [] def __init__(self): self.shuffle() def shuffle(self): # and then shuffle self.cards = Deck.GetFullDeck() rshuffle(self.cards) def draw(self, n=1): if n == 1: return self.cards.pop(0) cards = [] for i in range(n): cards.append(self.draw()) return cards def __str__(self): return Card.print_pretty_cards(self.cards) @staticmethod def GetFullDeck(): if Deck._FULL_DECK: return list(Deck._FULL_DECK) # create the standard 52 card deck for rank in Card.STR_RANKS: for suit, val in Card.CHAR_SUIT_TO_INT_SUIT.items(): Deck._FULL_DECK.append(Card.new(rank + suit)) return list(Deck._FULL_DECK)
en
0.883157
Class representing a deck. The first time we create, we seed the static deck with the list of unique card integers. Each object instantiated simply makes a copy of this object and shuffles it. # and then shuffle # create the standard 52 card deck
3.95507
4
openidc_client/__init__.py
puiterwijk/python-openidc-client
6
78
# -*- coding: utf-8 -*- # # Copyright (C) 2016, 2017 Red Hat, Inc. # Red Hat Author: <NAME> <<EMAIL>> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. """Client for applications relying on OpenID Connect for authentication.""" from __future__ import print_function from copy import copy import json import logging from threading import Lock import time try: from StringIO import StringIO except ImportError: from io import StringIO import socket import os try: from urllib import urlencode except ImportError: from urllib.parse import urlencode from uuid import uuid4 as uuidgen import webbrowser from wsgiref import simple_server import requests import sys from openidc_client import release # The ports that we will try to use for our webserver WEB_PORTS = [12345, 23456] class OpenIDCClient(object): # Internal implementation of tokens: # Every app id has its own token cache # The token cache is a json serialized dict # This dict contains uuid: token pairs # Every "token" object is a json dict with the following keys: # idp: The URL of the idp that issued the token # sub: The subject that owns the token # access_token: Token value # token_type: Token type. Currently supported: "Bearer" # expires_at: Token expiration UTC time. NOTE: Even if the expires_at # indicates the token should still be valid, it may have been revoked by # the user! Also, even if it has expired, we might still be able to # refresh the token. # refresh_token: The token we can use to refresh the access token # scopes: A list of scopes that we had requested with the token def __init__(self, app_identifier, id_provider, id_provider_mapping, client_id, client_secret=None, use_post=False, useragent=None, cachedir=None, printfd=sys.stdout): """Client for interacting with web services relying on OpenID Connect. :param app_identifier: Identifier for storage of retrieved tokens :param id_provider: URL of the identity provider to get tokens from :param id_provider_mapping: Mapping with URLs to use for specific endpoints on the IdP. :kwarg use_post: Whether to use POST submission of client secrets rather than Authorization header :kwarg client_id: The Client Identifier used to request credentials :kwarg client_secret: The client "secret" that goes with the client_id. May be None if your IdP does not require you to use a secret. :kwarg useragent: Useragent string to use. If not provided, defaults to "python-openidc-client/VERSION" :kwarg cachedir: The directory in which to store the token caches. Will be put through expanduer. Default is ~/.openidc. If this does not exist and we are unable to create it, the OSError will be thrown. :kwargs printfd: The File object to print token instructions to. """ self.logger = logging.getLogger(__name__) self.debug = self.logger.debug self.app_id = app_identifier self.use_post = use_post self.idp = id_provider self.idp_mapping = id_provider_mapping self.client_id = client_id self.client_secret = client_secret self.useragent = useragent or 'python-openid-client/%s' % \ release.VERSION self.cachedir = os.path.expanduser(cachedir or '~/.openidc') self.last_returned_uuid = None self.problem_reported = False self.token_to_try = None self._retrieved_code = None # TODO: Make cache_lock a filesystem lock so we also lock across # multiple invocations self._cache_lock = Lock() with self._cache_lock: self.__refresh_cache() self._valid_cache = [] self._printfd = printfd def get_token(self, scopes, new_token=True): """Function to retrieve tokens with specific scopes. This function will block until a token is retrieved if requested. It is always safe to call this though, since if we already have a token with the current app_identifier that has the required scopes, we will return it. This function will return a bearer token or None. Note that the bearer token might have been revoked by the user or expired. In that case, you will want to call report_token_issue() to try to renew the token or delete the token. :kwarg scopes: A list of scopes required for the current client. :kwarg new_token: If True, we will actively request the user to get a new token with the current scopeset if we do not already have on. :rtype: string or None :returns: String bearer token if possible or None """ if not isinstance(scopes, list): raise ValueError('Scopes must be a list') token = self._get_token_with_scopes(scopes) if token: # If we had a valid token, use that self.last_returned_uuid = token[0] self.problem_reported = False return token[1]['access_token'] elif not new_token: return None # We did not have a valid token, now comes the hard part... uuid = self._get_new_token(scopes) if uuid: self.last_returned_uuid = uuid self.problem_reported = False return self._cache[uuid]['access_token'] def report_token_issue(self): """Report an error with the last token that was returned. This will attempt to renew the token that was last returned. If that worked, we will return the new access token. If it did not work, we will return None and remove this token from the cache. If you get an indication from your application that the token you sent was invalid, you should call it. You should explicitly NOT call this function if the token was valid but your request failed due to a server error or because the account or token was lacking specific permissions. """ if not self.last_returned_uuid: raise Exception('Cannot report issue before requesting token') if self.problem_reported: # We were reported an issue before. Let's just remove this token. self._delete_token(self.last_returned_uuid) return None refresh_result = self._refresh_token(self.last_returned_uuid) if not refresh_result: self._delete_token(self.last_returned_uuid) return None else: self.problem_reported = True return self._cache[self.last_returned_uuid]['access_token'] def send_request(self, *args, **kwargs): """Make an python-requests POST request. Allarguments and keyword arguments are like the arguments to requests, except for `scopes`, `new_token` and `auto_refresh` keyword arguments. `scopes` is required. :kwarg scopes: Scopes required for this call. If a token is not present with this token, a new one will be requested unless nonblocking is True. :kwarg new_token: If True, we will actively request the user to get a new token with the current scopeset if we do not already have on. :kwarg auto_refresh: If False, will not try to automatically report token issues on 401. This helps with broken apps that may send a 401 return code in incorrect cases. :kwargs http_method: The HTTP method to use, defaults to POST.. """ ckwargs = copy(kwargs) scopes = ckwargs.pop('scopes') new_token = ckwargs.pop('new_token', True) auto_refresh = ckwargs.pop('auto_refresh', True) method = ckwargs.pop('http_method', 'POST') is_retry = False if self.token_to_try: is_retry = True token = self.token_to_try self.token_to_try = None else: token = self.get_token(scopes, new_token=new_token) if not token: return None if self.use_post: if 'json' in ckwargs: raise ValueError('Cannot provide json in a post call') if method not in ['POST']: raise ValueError('Cannot use POST tokens in %s method' % method) if 'data' not in ckwargs: ckwargs['data'] = {} ckwargs['data']['access_token'] = token else: if 'headers' not in ckwargs: ckwargs['headers'] = {} ckwargs['headers']['Authorization'] = 'Bearer %s' % token resp = requests.request(method, *args, **ckwargs) if resp.status_code == 401 and not is_retry: if not auto_refresh: return resp self.token_to_try = self.report_token_issue() if not self.token_to_try: return resp return self.send_request(*args, **kwargs) elif resp.status_code == 401: # We got a 401 and this is a retry. Report error self.report_token_issue() return resp else: return resp @property def _cachefile(self): """Property to get the cache file name for the current client. This assures that whenever this file is touched, the cache lock is held """ assert self._cache_lock.locked() return os.path.join(self.cachedir, 'oidc_%s.json' % self.app_id) def __refresh_cache(self): """Refreshes the self._cache from the cache on disk. Requires cache_lock to be held by caller.""" assert self._cache_lock.locked() self.debug('Refreshing cache') if not os.path.isdir(self.cachedir): self.debug('Creating directory') os.makedirs(self.cachedir) if not os.path.exists(self._cachefile): self.debug('Creating file') with open(self._cachefile, 'w') as f: f.write(json.dumps({})) with open(self._cachefile, 'r') as f: self._cache = json.loads(f.read()) self.debug('Loaded %i tokens', len(self._cache)) def _refresh_cache(self): """Refreshes the self._cache from the cache on disk. cache_lock may not be held by anyone.""" with self._cache_lock: self.__refresh_cache() def __write_cache(self): """Wirtes self._cache to cache on disk. Requires cache_lock to be held by caller.""" assert self._cache_lock.locked() self.debug('Writing cache with %i tokens', len(self._cache)) with open(self._cachefile, 'w') as f: f.write(json.dumps(self._cache)) def _add_token(self, token): """Adds a token to the cache and writes cache to disk. cache_lock may not be held by anyone. :param token: Dict of the token to be added to the cache """ uuid = uuidgen().hex self.debug('Adding token %s to cache', uuid) with self._cache_lock: self.__refresh_cache() self._cache[uuid] = token self.__write_cache() return uuid def _update_token(self, uuid, toupdate): """Updates a token in the cache. cache_lock may not be held by anyone. :param token: UUID of the token to be updated :param toupdate: Dict indicating which fields need to be updated """ self.debug('Updating token %s in cache, fields %s', uuid, toupdate.keys()) with self._cache_lock: self.__refresh_cache() if uuid not in self._cache: return None self._cache[uuid].update(toupdate) self.__write_cache() return uuid def _delete_token(self, uuid): """Removes a token from the cache and writes cache to disk. cache_lock may not be held by anyone. :param uuid: UUID of the token to be removed from cache """ self.debug('Removing token %s from cache', uuid) with self._cache_lock: self.__refresh_cache() if uuid in self._cache: self.debug('Removing token') del self._cache[uuid] self.__write_cache() else: self.debug('Token was already gone') def _get_token_with_scopes(self, scopes): """Searches the cache for any tokens that have the requested scopes. It will prefer to return tokens whose expires_at is still before the current time, but if no such tokens exist it will return the possibly expired token: it might be refreshable. :param scopes: List of scopes that need to be in the returned token :rtype: (string, dict) or None :returns: Token UUID and contents or None if no applicable tokens were found """ possible_token = None self.debug('Trying to get token with scopes %s', scopes) for uuid in self._cache: self.debug('Checking %s', uuid) token = self._cache[uuid] if token['idp'] != self.idp: self.debug('Incorrect idp') continue if not set(scopes).issubset(set(token['scopes'])): self.debug('Missing scope: %s not subset of %s', set(scopes), set(token['scopes'])) continue if token['expires_at'] < time.time(): # This is a token that's supposed to still be valid, prefer it # over any others we have self.debug('Not yet expired, returning') return uuid, token # This is a token that may or may not still be valid self.debug('Possible') possible_token = (uuid, token) if possible_token: self.debug('Returning possible token') return possible_token def _idp_url(self, method): """Returns the IdP URL for the requested method. :param method: The method name in the IdP mapping dict. :rtype: string :returns: The IdP URL """ if method in self.idp_mapping: return self.idp + self.idp_mapping[method] else: return ValueError('Idp Mapping did not include path for %s' % method) def _refresh_token(self, uuid): """Tries to refresh a token and put the refreshed token in self._cache The caller is responsible for either removing the token if it could not be refreshed or saving the cache if renewal was succesful. :param uuid: The UUID of the cached token to attempt to refresh. :rtype: bool :returns: True if the token was succesfully refreshed, False otherwise """ oldtoken = self._cache[uuid] self.debug('Refreshing token %s', uuid) data = {'client_id': self.client_id, 'grant_type': 'refresh_token', 'refresh_token': oldtoken['refresh_token']} if self.client_secret: data['client_secret'] = self.client_secret resp = requests.request( 'POST', self._idp_url('Token'), data=data) resp.raise_for_status() resp = resp.json() if 'error' in resp: self.debug('Unable to refresh, error: %s', resp['error']) return False self._update_token( uuid, {'access_token': resp['access_token'], 'token_type': resp['token_type'], 'refresh_token': resp['refresh_token'], 'expires_at': time.time() + resp['expires_in']}) self.debug('Refreshed until %s', self._cache[uuid]['expires_at']) return True def _get_server(self, app): """This function returns a SimpleServer with an available WEB_PORT.""" for port in WEB_PORTS: try: server = simple_server.make_server('0.0.0.0', port, app) return server except socket.error: # This port did not work. Switch to next one continue def _get_new_token(self, scopes): """This function kicks off some magic. We will start a new webserver on one of the WEB_PORTS, and then either show the user a URL, or if possible, kick off their browser. This URL will be the Authorization endpoint of the IdP with a request for our client_id to get a new token with the specified scopes. The webserver will then need to catch the return with either an Authorization Code (that we will exchange for an access token) or the cancellation message. This function will store the new token in the local cache, add it to the valid cache, and then return the UUID. If the user cancelled (or we got another error), we will return None. """ def _token_app(environ, start_response): query = environ['QUERY_STRING'] split = query.split('&') kv = dict([v.split('=', 1) for v in split]) if 'error' in kv: self.debug('Error code returned: %s (%s)', kv['error'], kv.get('error_description')) self._retrieved_code = False else: self._retrieved_code = kv['code'] # Just return a message start_response('200 OK', [('Content-Type', 'text/plain')]) return [u'You can close this window and return to the CLI'.encode('ascii')] self._retrieved_code = None server = self._get_server(_token_app) if not server: raise Exception('We were unable to instantiate a webserver') return_uri = 'http://localhost:%i/' % server.socket.getsockname()[1] rquery = {} rquery['scope'] = ' '.join(scopes) rquery['response_type'] = 'code' rquery['client_id'] = self.client_id rquery['redirect_uri'] = return_uri rquery['response_mode'] = 'query' query = urlencode(rquery) authz_url = '%s?%s' % (self._idp_url('Authorization'), query) print('Please visit %s to grant authorization' % authz_url, file=self._printfd) webbrowser.open(authz_url) server.handle_request() server.server_close() assert self._retrieved_code is not None if self._retrieved_code is False: # The user cancelled the request self._retrieved_code = None self.debug('User cancelled') return None self.debug('We got an authorization code!') data = {'client_id': self.client_id, 'grant_type': 'authorization_code', 'redirect_uri': return_uri, 'code': self._retrieved_code} if self.client_secret: data['client_secret'] = self.client_secret resp = requests.request( 'POST', self._idp_url('Token'), data=data) resp.raise_for_status() self._retrieved_code = None resp = resp.json() if 'error' in resp: self.debug('Error exchanging authorization code: %s', resp['error']) return None token = {'access_token': resp['access_token'], 'refresh_token': resp['refresh_token'], 'expires_at': time.time() + int(resp['expires_in']), 'idp': self.idp, 'token_type': resp['token_type'], 'scopes': scopes} # AND WE ARE DONE! \o/ return self._add_token(token)
# -*- coding: utf-8 -*- # # Copyright (C) 2016, 2017 Red Hat, Inc. # Red Hat Author: <NAME> <<EMAIL>> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. """Client for applications relying on OpenID Connect for authentication.""" from __future__ import print_function from copy import copy import json import logging from threading import Lock import time try: from StringIO import StringIO except ImportError: from io import StringIO import socket import os try: from urllib import urlencode except ImportError: from urllib.parse import urlencode from uuid import uuid4 as uuidgen import webbrowser from wsgiref import simple_server import requests import sys from openidc_client import release # The ports that we will try to use for our webserver WEB_PORTS = [12345, 23456] class OpenIDCClient(object): # Internal implementation of tokens: # Every app id has its own token cache # The token cache is a json serialized dict # This dict contains uuid: token pairs # Every "token" object is a json dict with the following keys: # idp: The URL of the idp that issued the token # sub: The subject that owns the token # access_token: Token value # token_type: Token type. Currently supported: "Bearer" # expires_at: Token expiration UTC time. NOTE: Even if the expires_at # indicates the token should still be valid, it may have been revoked by # the user! Also, even if it has expired, we might still be able to # refresh the token. # refresh_token: The token we can use to refresh the access token # scopes: A list of scopes that we had requested with the token def __init__(self, app_identifier, id_provider, id_provider_mapping, client_id, client_secret=None, use_post=False, useragent=None, cachedir=None, printfd=sys.stdout): """Client for interacting with web services relying on OpenID Connect. :param app_identifier: Identifier for storage of retrieved tokens :param id_provider: URL of the identity provider to get tokens from :param id_provider_mapping: Mapping with URLs to use for specific endpoints on the IdP. :kwarg use_post: Whether to use POST submission of client secrets rather than Authorization header :kwarg client_id: The Client Identifier used to request credentials :kwarg client_secret: The client "secret" that goes with the client_id. May be None if your IdP does not require you to use a secret. :kwarg useragent: Useragent string to use. If not provided, defaults to "python-openidc-client/VERSION" :kwarg cachedir: The directory in which to store the token caches. Will be put through expanduer. Default is ~/.openidc. If this does not exist and we are unable to create it, the OSError will be thrown. :kwargs printfd: The File object to print token instructions to. """ self.logger = logging.getLogger(__name__) self.debug = self.logger.debug self.app_id = app_identifier self.use_post = use_post self.idp = id_provider self.idp_mapping = id_provider_mapping self.client_id = client_id self.client_secret = client_secret self.useragent = useragent or 'python-openid-client/%s' % \ release.VERSION self.cachedir = os.path.expanduser(cachedir or '~/.openidc') self.last_returned_uuid = None self.problem_reported = False self.token_to_try = None self._retrieved_code = None # TODO: Make cache_lock a filesystem lock so we also lock across # multiple invocations self._cache_lock = Lock() with self._cache_lock: self.__refresh_cache() self._valid_cache = [] self._printfd = printfd def get_token(self, scopes, new_token=True): """Function to retrieve tokens with specific scopes. This function will block until a token is retrieved if requested. It is always safe to call this though, since if we already have a token with the current app_identifier that has the required scopes, we will return it. This function will return a bearer token or None. Note that the bearer token might have been revoked by the user or expired. In that case, you will want to call report_token_issue() to try to renew the token or delete the token. :kwarg scopes: A list of scopes required for the current client. :kwarg new_token: If True, we will actively request the user to get a new token with the current scopeset if we do not already have on. :rtype: string or None :returns: String bearer token if possible or None """ if not isinstance(scopes, list): raise ValueError('Scopes must be a list') token = self._get_token_with_scopes(scopes) if token: # If we had a valid token, use that self.last_returned_uuid = token[0] self.problem_reported = False return token[1]['access_token'] elif not new_token: return None # We did not have a valid token, now comes the hard part... uuid = self._get_new_token(scopes) if uuid: self.last_returned_uuid = uuid self.problem_reported = False return self._cache[uuid]['access_token'] def report_token_issue(self): """Report an error with the last token that was returned. This will attempt to renew the token that was last returned. If that worked, we will return the new access token. If it did not work, we will return None and remove this token from the cache. If you get an indication from your application that the token you sent was invalid, you should call it. You should explicitly NOT call this function if the token was valid but your request failed due to a server error or because the account or token was lacking specific permissions. """ if not self.last_returned_uuid: raise Exception('Cannot report issue before requesting token') if self.problem_reported: # We were reported an issue before. Let's just remove this token. self._delete_token(self.last_returned_uuid) return None refresh_result = self._refresh_token(self.last_returned_uuid) if not refresh_result: self._delete_token(self.last_returned_uuid) return None else: self.problem_reported = True return self._cache[self.last_returned_uuid]['access_token'] def send_request(self, *args, **kwargs): """Make an python-requests POST request. Allarguments and keyword arguments are like the arguments to requests, except for `scopes`, `new_token` and `auto_refresh` keyword arguments. `scopes` is required. :kwarg scopes: Scopes required for this call. If a token is not present with this token, a new one will be requested unless nonblocking is True. :kwarg new_token: If True, we will actively request the user to get a new token with the current scopeset if we do not already have on. :kwarg auto_refresh: If False, will not try to automatically report token issues on 401. This helps with broken apps that may send a 401 return code in incorrect cases. :kwargs http_method: The HTTP method to use, defaults to POST.. """ ckwargs = copy(kwargs) scopes = ckwargs.pop('scopes') new_token = ckwargs.pop('new_token', True) auto_refresh = ckwargs.pop('auto_refresh', True) method = ckwargs.pop('http_method', 'POST') is_retry = False if self.token_to_try: is_retry = True token = self.token_to_try self.token_to_try = None else: token = self.get_token(scopes, new_token=new_token) if not token: return None if self.use_post: if 'json' in ckwargs: raise ValueError('Cannot provide json in a post call') if method not in ['POST']: raise ValueError('Cannot use POST tokens in %s method' % method) if 'data' not in ckwargs: ckwargs['data'] = {} ckwargs['data']['access_token'] = token else: if 'headers' not in ckwargs: ckwargs['headers'] = {} ckwargs['headers']['Authorization'] = 'Bearer %s' % token resp = requests.request(method, *args, **ckwargs) if resp.status_code == 401 and not is_retry: if not auto_refresh: return resp self.token_to_try = self.report_token_issue() if not self.token_to_try: return resp return self.send_request(*args, **kwargs) elif resp.status_code == 401: # We got a 401 and this is a retry. Report error self.report_token_issue() return resp else: return resp @property def _cachefile(self): """Property to get the cache file name for the current client. This assures that whenever this file is touched, the cache lock is held """ assert self._cache_lock.locked() return os.path.join(self.cachedir, 'oidc_%s.json' % self.app_id) def __refresh_cache(self): """Refreshes the self._cache from the cache on disk. Requires cache_lock to be held by caller.""" assert self._cache_lock.locked() self.debug('Refreshing cache') if not os.path.isdir(self.cachedir): self.debug('Creating directory') os.makedirs(self.cachedir) if not os.path.exists(self._cachefile): self.debug('Creating file') with open(self._cachefile, 'w') as f: f.write(json.dumps({})) with open(self._cachefile, 'r') as f: self._cache = json.loads(f.read()) self.debug('Loaded %i tokens', len(self._cache)) def _refresh_cache(self): """Refreshes the self._cache from the cache on disk. cache_lock may not be held by anyone.""" with self._cache_lock: self.__refresh_cache() def __write_cache(self): """Wirtes self._cache to cache on disk. Requires cache_lock to be held by caller.""" assert self._cache_lock.locked() self.debug('Writing cache with %i tokens', len(self._cache)) with open(self._cachefile, 'w') as f: f.write(json.dumps(self._cache)) def _add_token(self, token): """Adds a token to the cache and writes cache to disk. cache_lock may not be held by anyone. :param token: Dict of the token to be added to the cache """ uuid = uuidgen().hex self.debug('Adding token %s to cache', uuid) with self._cache_lock: self.__refresh_cache() self._cache[uuid] = token self.__write_cache() return uuid def _update_token(self, uuid, toupdate): """Updates a token in the cache. cache_lock may not be held by anyone. :param token: UUID of the token to be updated :param toupdate: Dict indicating which fields need to be updated """ self.debug('Updating token %s in cache, fields %s', uuid, toupdate.keys()) with self._cache_lock: self.__refresh_cache() if uuid not in self._cache: return None self._cache[uuid].update(toupdate) self.__write_cache() return uuid def _delete_token(self, uuid): """Removes a token from the cache and writes cache to disk. cache_lock may not be held by anyone. :param uuid: UUID of the token to be removed from cache """ self.debug('Removing token %s from cache', uuid) with self._cache_lock: self.__refresh_cache() if uuid in self._cache: self.debug('Removing token') del self._cache[uuid] self.__write_cache() else: self.debug('Token was already gone') def _get_token_with_scopes(self, scopes): """Searches the cache for any tokens that have the requested scopes. It will prefer to return tokens whose expires_at is still before the current time, but if no such tokens exist it will return the possibly expired token: it might be refreshable. :param scopes: List of scopes that need to be in the returned token :rtype: (string, dict) or None :returns: Token UUID and contents or None if no applicable tokens were found """ possible_token = None self.debug('Trying to get token with scopes %s', scopes) for uuid in self._cache: self.debug('Checking %s', uuid) token = self._cache[uuid] if token['idp'] != self.idp: self.debug('Incorrect idp') continue if not set(scopes).issubset(set(token['scopes'])): self.debug('Missing scope: %s not subset of %s', set(scopes), set(token['scopes'])) continue if token['expires_at'] < time.time(): # This is a token that's supposed to still be valid, prefer it # over any others we have self.debug('Not yet expired, returning') return uuid, token # This is a token that may or may not still be valid self.debug('Possible') possible_token = (uuid, token) if possible_token: self.debug('Returning possible token') return possible_token def _idp_url(self, method): """Returns the IdP URL for the requested method. :param method: The method name in the IdP mapping dict. :rtype: string :returns: The IdP URL """ if method in self.idp_mapping: return self.idp + self.idp_mapping[method] else: return ValueError('Idp Mapping did not include path for %s' % method) def _refresh_token(self, uuid): """Tries to refresh a token and put the refreshed token in self._cache The caller is responsible for either removing the token if it could not be refreshed or saving the cache if renewal was succesful. :param uuid: The UUID of the cached token to attempt to refresh. :rtype: bool :returns: True if the token was succesfully refreshed, False otherwise """ oldtoken = self._cache[uuid] self.debug('Refreshing token %s', uuid) data = {'client_id': self.client_id, 'grant_type': 'refresh_token', 'refresh_token': oldtoken['refresh_token']} if self.client_secret: data['client_secret'] = self.client_secret resp = requests.request( 'POST', self._idp_url('Token'), data=data) resp.raise_for_status() resp = resp.json() if 'error' in resp: self.debug('Unable to refresh, error: %s', resp['error']) return False self._update_token( uuid, {'access_token': resp['access_token'], 'token_type': resp['token_type'], 'refresh_token': resp['refresh_token'], 'expires_at': time.time() + resp['expires_in']}) self.debug('Refreshed until %s', self._cache[uuid]['expires_at']) return True def _get_server(self, app): """This function returns a SimpleServer with an available WEB_PORT.""" for port in WEB_PORTS: try: server = simple_server.make_server('0.0.0.0', port, app) return server except socket.error: # This port did not work. Switch to next one continue def _get_new_token(self, scopes): """This function kicks off some magic. We will start a new webserver on one of the WEB_PORTS, and then either show the user a URL, or if possible, kick off their browser. This URL will be the Authorization endpoint of the IdP with a request for our client_id to get a new token with the specified scopes. The webserver will then need to catch the return with either an Authorization Code (that we will exchange for an access token) or the cancellation message. This function will store the new token in the local cache, add it to the valid cache, and then return the UUID. If the user cancelled (or we got another error), we will return None. """ def _token_app(environ, start_response): query = environ['QUERY_STRING'] split = query.split('&') kv = dict([v.split('=', 1) for v in split]) if 'error' in kv: self.debug('Error code returned: %s (%s)', kv['error'], kv.get('error_description')) self._retrieved_code = False else: self._retrieved_code = kv['code'] # Just return a message start_response('200 OK', [('Content-Type', 'text/plain')]) return [u'You can close this window and return to the CLI'.encode('ascii')] self._retrieved_code = None server = self._get_server(_token_app) if not server: raise Exception('We were unable to instantiate a webserver') return_uri = 'http://localhost:%i/' % server.socket.getsockname()[1] rquery = {} rquery['scope'] = ' '.join(scopes) rquery['response_type'] = 'code' rquery['client_id'] = self.client_id rquery['redirect_uri'] = return_uri rquery['response_mode'] = 'query' query = urlencode(rquery) authz_url = '%s?%s' % (self._idp_url('Authorization'), query) print('Please visit %s to grant authorization' % authz_url, file=self._printfd) webbrowser.open(authz_url) server.handle_request() server.server_close() assert self._retrieved_code is not None if self._retrieved_code is False: # The user cancelled the request self._retrieved_code = None self.debug('User cancelled') return None self.debug('We got an authorization code!') data = {'client_id': self.client_id, 'grant_type': 'authorization_code', 'redirect_uri': return_uri, 'code': self._retrieved_code} if self.client_secret: data['client_secret'] = self.client_secret resp = requests.request( 'POST', self._idp_url('Token'), data=data) resp.raise_for_status() self._retrieved_code = None resp = resp.json() if 'error' in resp: self.debug('Error exchanging authorization code: %s', resp['error']) return None token = {'access_token': resp['access_token'], 'refresh_token': resp['refresh_token'], 'expires_at': time.time() + int(resp['expires_in']), 'idp': self.idp, 'token_type': resp['token_type'], 'scopes': scopes} # AND WE ARE DONE! \o/ return self._add_token(token)
en
0.842488
# -*- coding: utf-8 -*- # # Copyright (C) 2016, 2017 Red Hat, Inc. # Red Hat Author: <NAME> <<EMAIL>> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. Client for applications relying on OpenID Connect for authentication. # The ports that we will try to use for our webserver # Internal implementation of tokens: # Every app id has its own token cache # The token cache is a json serialized dict # This dict contains uuid: token pairs # Every "token" object is a json dict with the following keys: # idp: The URL of the idp that issued the token # sub: The subject that owns the token # access_token: Token value # token_type: Token type. Currently supported: "Bearer" # expires_at: Token expiration UTC time. NOTE: Even if the expires_at # indicates the token should still be valid, it may have been revoked by # the user! Also, even if it has expired, we might still be able to # refresh the token. # refresh_token: The token we can use to refresh the access token # scopes: A list of scopes that we had requested with the token Client for interacting with web services relying on OpenID Connect. :param app_identifier: Identifier for storage of retrieved tokens :param id_provider: URL of the identity provider to get tokens from :param id_provider_mapping: Mapping with URLs to use for specific endpoints on the IdP. :kwarg use_post: Whether to use POST submission of client secrets rather than Authorization header :kwarg client_id: The Client Identifier used to request credentials :kwarg client_secret: The client "secret" that goes with the client_id. May be None if your IdP does not require you to use a secret. :kwarg useragent: Useragent string to use. If not provided, defaults to "python-openidc-client/VERSION" :kwarg cachedir: The directory in which to store the token caches. Will be put through expanduer. Default is ~/.openidc. If this does not exist and we are unable to create it, the OSError will be thrown. :kwargs printfd: The File object to print token instructions to. # TODO: Make cache_lock a filesystem lock so we also lock across # multiple invocations Function to retrieve tokens with specific scopes. This function will block until a token is retrieved if requested. It is always safe to call this though, since if we already have a token with the current app_identifier that has the required scopes, we will return it. This function will return a bearer token or None. Note that the bearer token might have been revoked by the user or expired. In that case, you will want to call report_token_issue() to try to renew the token or delete the token. :kwarg scopes: A list of scopes required for the current client. :kwarg new_token: If True, we will actively request the user to get a new token with the current scopeset if we do not already have on. :rtype: string or None :returns: String bearer token if possible or None # If we had a valid token, use that # We did not have a valid token, now comes the hard part... Report an error with the last token that was returned. This will attempt to renew the token that was last returned. If that worked, we will return the new access token. If it did not work, we will return None and remove this token from the cache. If you get an indication from your application that the token you sent was invalid, you should call it. You should explicitly NOT call this function if the token was valid but your request failed due to a server error or because the account or token was lacking specific permissions. # We were reported an issue before. Let's just remove this token. Make an python-requests POST request. Allarguments and keyword arguments are like the arguments to requests, except for `scopes`, `new_token` and `auto_refresh` keyword arguments. `scopes` is required. :kwarg scopes: Scopes required for this call. If a token is not present with this token, a new one will be requested unless nonblocking is True. :kwarg new_token: If True, we will actively request the user to get a new token with the current scopeset if we do not already have on. :kwarg auto_refresh: If False, will not try to automatically report token issues on 401. This helps with broken apps that may send a 401 return code in incorrect cases. :kwargs http_method: The HTTP method to use, defaults to POST.. # We got a 401 and this is a retry. Report error Property to get the cache file name for the current client. This assures that whenever this file is touched, the cache lock is held Refreshes the self._cache from the cache on disk. Requires cache_lock to be held by caller. Refreshes the self._cache from the cache on disk. cache_lock may not be held by anyone. Wirtes self._cache to cache on disk. Requires cache_lock to be held by caller. Adds a token to the cache and writes cache to disk. cache_lock may not be held by anyone. :param token: Dict of the token to be added to the cache Updates a token in the cache. cache_lock may not be held by anyone. :param token: UUID of the token to be updated :param toupdate: Dict indicating which fields need to be updated Removes a token from the cache and writes cache to disk. cache_lock may not be held by anyone. :param uuid: UUID of the token to be removed from cache Searches the cache for any tokens that have the requested scopes. It will prefer to return tokens whose expires_at is still before the current time, but if no such tokens exist it will return the possibly expired token: it might be refreshable. :param scopes: List of scopes that need to be in the returned token :rtype: (string, dict) or None :returns: Token UUID and contents or None if no applicable tokens were found # This is a token that's supposed to still be valid, prefer it # over any others we have # This is a token that may or may not still be valid Returns the IdP URL for the requested method. :param method: The method name in the IdP mapping dict. :rtype: string :returns: The IdP URL Tries to refresh a token and put the refreshed token in self._cache The caller is responsible for either removing the token if it could not be refreshed or saving the cache if renewal was succesful. :param uuid: The UUID of the cached token to attempt to refresh. :rtype: bool :returns: True if the token was succesfully refreshed, False otherwise This function returns a SimpleServer with an available WEB_PORT. # This port did not work. Switch to next one This function kicks off some magic. We will start a new webserver on one of the WEB_PORTS, and then either show the user a URL, or if possible, kick off their browser. This URL will be the Authorization endpoint of the IdP with a request for our client_id to get a new token with the specified scopes. The webserver will then need to catch the return with either an Authorization Code (that we will exchange for an access token) or the cancellation message. This function will store the new token in the local cache, add it to the valid cache, and then return the UUID. If the user cancelled (or we got another error), we will return None. # Just return a message # The user cancelled the request # AND WE ARE DONE! \o/
1.399626
1
eoxserver/services/ows/wps/v10/encoders/parameters.py
constantinius/eoxserver_combined
1
79
<reponame>constantinius/eoxserver_combined<filename>eoxserver/services/ows/wps/v10/encoders/parameters.py #------------------------------------------------------------------------------- # # WPS 1.0 parameters' XML encoders # # Project: EOxServer <http://eoxserver.org> # Authors: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # #------------------------------------------------------------------------------- # Copyright (C) 2013 EOX IT Services GmbH # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies of this Software or works derived from this Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. #------------------------------------------------------------------------------- from eoxserver.services.ows.wps.parameters import ( LiteralData, ComplexData, BoundingBoxData, AllowedAny, AllowedEnum, AllowedRange, AllowedRangeCollection, AllowedByReference, ) from eoxserver.services.ows.wps.v10.util import ( OWS, WPS, NIL, ns_ows, ) #------------------------------------------------------------------------------- def encode_input_descr(prm): """ Encode process description input.""" elem = NIL("Input", *_encode_param_common(prm)) elem.attrib["minOccurs"] = ("1", "0")[bool(prm.is_optional)] elem.attrib["maxOccurs"] = "1" if isinstance(prm, LiteralData): elem.append(_encode_literal(prm, True)) elif isinstance(prm, ComplexData): elem.append(_encode_complex(prm, True)) elif isinstance(prm, BoundingBoxData): elem.append(_encode_bbox(prm, True)) return elem def encode_output_descr(prm): """ Encode process description output.""" elem = NIL("Output", *_encode_param_common(prm)) if isinstance(prm, LiteralData): elem.append(_encode_literal(prm, False)) elif isinstance(prm, ComplexData): elem.append(_encode_complex(prm, False)) elif isinstance(prm, BoundingBoxData): elem.append(_encode_bbox(prm, False)) return elem def encode_input_exec(prm): """ Encode common part of the execure response data input.""" return WPS("Input", *_encode_param_common(prm, False)) def encode_output_exec(prm): """ Encode common part of the execure response data output.""" return WPS("Output", *_encode_param_common(prm)) def encode_output_def(outdef): """ Encode the execure response output definition.""" attrib = {} if outdef.uom is not None: attrib['uom'] = outdef.uom if outdef.crs is not None: attrib['crs'] = outdef.crs if outdef.mime_type is not None: attrib['mimeType'] = outdef.mime_type if outdef.encoding is not None: attrib['encoding'] = outdef.encoding if outdef.schema is not None: attrib['schema'] = outdef.schema if outdef.as_reference is not None: attrib['asReference'] = 'true' if outdef.as_reference else 'false' return WPS("Output", *_encode_param_common(outdef, False), **attrib) def _encode_param_common(prm, title_required=True): """ Encode common sub-elements of all XML parameters.""" elist = [OWS("Identifier", prm.identifier)] if prm.title or title_required: elist.append(OWS("Title", prm.title or prm.identifier)) if prm.abstract: elist.append(OWS("Abstract", prm.abstract)) return elist #------------------------------------------------------------------------------- def _encode_literal(prm, is_input): dtype = prm.dtype elem = NIL("LiteralData" if is_input else "LiteralOutput") elem.append(OWS("DataType", dtype.name, **{ ns_ows("reference"): "http://www.w3.org/TR/xmlschema-2/#%s"%dtype.name, })) if prm.uoms: elem.append(NIL("UOMs", NIL("Default", OWS("UOM", prm.uoms[0])), NIL("Supported", *[OWS("UOM", u) for u in prm.uoms]) )) if is_input: elem.append(_encode_allowed_value(prm.allowed_values)) if prm.default is not None: elem.append(NIL("DefaultValue", str(prm.default))) return elem def _encode_allowed_value(avobj): enum, ranges, elist = None, [], [] if isinstance(avobj, AllowedAny): return OWS("AnyValue") elif isinstance(avobj, AllowedByReference): return WPS("ValuesReference", **{ ns_ows("reference"): avobj.url, "valuesForm": avobj.url, }) elif isinstance(avobj, AllowedEnum): enum = avobj elif isinstance(avobj, AllowedRange): ranges = [avobj] elif isinstance(avobj, AllowedRangeCollection): enum, ranges = avobj.enum, avobj.ranges else: raise TypeError("Invalid allowed value object! OBJ=%r"%avobj) dtype = avobj.dtype ddtype = dtype.get_diff_dtype() if enum is not None: elist.extend(OWS("Value", dtype.encode(v)) for v in enum.values) for range_ in ranges: attr, elms = {}, [] if range_.closure != 'closed': attr = {ns_ows("rangeClosure"): range_.closure} if range_.minval is not None: elms.append(OWS("MinimumValue", dtype.encode(range_.minval))) if range_.maxval is not None: elms.append(OWS("MaximumValue", dtype.encode(range_.maxval))) if range_.spacing is not None: elms.append(OWS("Spacing", ddtype.encode(range_.spacing))) elist.append(OWS("Range", *elms, **attr)) return OWS("AllowedValues", *elist) #------------------------------------------------------------------------------- def _encode_complex(prm, is_input): return NIL("ComplexData" if is_input else "ComplexOutput", NIL("Default", _encode_format(prm.default_format)), NIL("Supported", *[_encode_format(f) for f in prm.formats.itervalues()]) ) def _encode_format(frmt): elem = NIL("Format", NIL("MimeType", frmt.mime_type)) if frmt.encoding is not None: elem.append(NIL("Encoding", frmt.encoding)) if frmt.schema is not None: elem.append(NIL("Schema", frmt.schema)) return elem #------------------------------------------------------------------------------- def _encode_bbox(prm, is_input): return NIL("BoundingBoxData" if is_input else "BoundingBoxOutput", NIL("Default", NIL("CRS", prm.encode_crs(prm.default_crs))), NIL("Supported", *[NIL("CRS", prm.encode_crs(crs)) for crs in prm.crss]) )
#------------------------------------------------------------------------------- # # WPS 1.0 parameters' XML encoders # # Project: EOxServer <http://eoxserver.org> # Authors: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # #------------------------------------------------------------------------------- # Copyright (C) 2013 EOX IT Services GmbH # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies of this Software or works derived from this Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. #------------------------------------------------------------------------------- from eoxserver.services.ows.wps.parameters import ( LiteralData, ComplexData, BoundingBoxData, AllowedAny, AllowedEnum, AllowedRange, AllowedRangeCollection, AllowedByReference, ) from eoxserver.services.ows.wps.v10.util import ( OWS, WPS, NIL, ns_ows, ) #------------------------------------------------------------------------------- def encode_input_descr(prm): """ Encode process description input.""" elem = NIL("Input", *_encode_param_common(prm)) elem.attrib["minOccurs"] = ("1", "0")[bool(prm.is_optional)] elem.attrib["maxOccurs"] = "1" if isinstance(prm, LiteralData): elem.append(_encode_literal(prm, True)) elif isinstance(prm, ComplexData): elem.append(_encode_complex(prm, True)) elif isinstance(prm, BoundingBoxData): elem.append(_encode_bbox(prm, True)) return elem def encode_output_descr(prm): """ Encode process description output.""" elem = NIL("Output", *_encode_param_common(prm)) if isinstance(prm, LiteralData): elem.append(_encode_literal(prm, False)) elif isinstance(prm, ComplexData): elem.append(_encode_complex(prm, False)) elif isinstance(prm, BoundingBoxData): elem.append(_encode_bbox(prm, False)) return elem def encode_input_exec(prm): """ Encode common part of the execure response data input.""" return WPS("Input", *_encode_param_common(prm, False)) def encode_output_exec(prm): """ Encode common part of the execure response data output.""" return WPS("Output", *_encode_param_common(prm)) def encode_output_def(outdef): """ Encode the execure response output definition.""" attrib = {} if outdef.uom is not None: attrib['uom'] = outdef.uom if outdef.crs is not None: attrib['crs'] = outdef.crs if outdef.mime_type is not None: attrib['mimeType'] = outdef.mime_type if outdef.encoding is not None: attrib['encoding'] = outdef.encoding if outdef.schema is not None: attrib['schema'] = outdef.schema if outdef.as_reference is not None: attrib['asReference'] = 'true' if outdef.as_reference else 'false' return WPS("Output", *_encode_param_common(outdef, False), **attrib) def _encode_param_common(prm, title_required=True): """ Encode common sub-elements of all XML parameters.""" elist = [OWS("Identifier", prm.identifier)] if prm.title or title_required: elist.append(OWS("Title", prm.title or prm.identifier)) if prm.abstract: elist.append(OWS("Abstract", prm.abstract)) return elist #------------------------------------------------------------------------------- def _encode_literal(prm, is_input): dtype = prm.dtype elem = NIL("LiteralData" if is_input else "LiteralOutput") elem.append(OWS("DataType", dtype.name, **{ ns_ows("reference"): "http://www.w3.org/TR/xmlschema-2/#%s"%dtype.name, })) if prm.uoms: elem.append(NIL("UOMs", NIL("Default", OWS("UOM", prm.uoms[0])), NIL("Supported", *[OWS("UOM", u) for u in prm.uoms]) )) if is_input: elem.append(_encode_allowed_value(prm.allowed_values)) if prm.default is not None: elem.append(NIL("DefaultValue", str(prm.default))) return elem def _encode_allowed_value(avobj): enum, ranges, elist = None, [], [] if isinstance(avobj, AllowedAny): return OWS("AnyValue") elif isinstance(avobj, AllowedByReference): return WPS("ValuesReference", **{ ns_ows("reference"): avobj.url, "valuesForm": avobj.url, }) elif isinstance(avobj, AllowedEnum): enum = avobj elif isinstance(avobj, AllowedRange): ranges = [avobj] elif isinstance(avobj, AllowedRangeCollection): enum, ranges = avobj.enum, avobj.ranges else: raise TypeError("Invalid allowed value object! OBJ=%r"%avobj) dtype = avobj.dtype ddtype = dtype.get_diff_dtype() if enum is not None: elist.extend(OWS("Value", dtype.encode(v)) for v in enum.values) for range_ in ranges: attr, elms = {}, [] if range_.closure != 'closed': attr = {ns_ows("rangeClosure"): range_.closure} if range_.minval is not None: elms.append(OWS("MinimumValue", dtype.encode(range_.minval))) if range_.maxval is not None: elms.append(OWS("MaximumValue", dtype.encode(range_.maxval))) if range_.spacing is not None: elms.append(OWS("Spacing", ddtype.encode(range_.spacing))) elist.append(OWS("Range", *elms, **attr)) return OWS("AllowedValues", *elist) #------------------------------------------------------------------------------- def _encode_complex(prm, is_input): return NIL("ComplexData" if is_input else "ComplexOutput", NIL("Default", _encode_format(prm.default_format)), NIL("Supported", *[_encode_format(f) for f in prm.formats.itervalues()]) ) def _encode_format(frmt): elem = NIL("Format", NIL("MimeType", frmt.mime_type)) if frmt.encoding is not None: elem.append(NIL("Encoding", frmt.encoding)) if frmt.schema is not None: elem.append(NIL("Schema", frmt.schema)) return elem #------------------------------------------------------------------------------- def _encode_bbox(prm, is_input): return NIL("BoundingBoxData" if is_input else "BoundingBoxOutput", NIL("Default", NIL("CRS", prm.encode_crs(prm.default_crs))), NIL("Supported", *[NIL("CRS", prm.encode_crs(crs)) for crs in prm.crss]) )
en
0.52179
#------------------------------------------------------------------------------- # # WPS 1.0 parameters' XML encoders # # Project: EOxServer <http://eoxserver.org> # Authors: <NAME> <<EMAIL>> # <NAME> <<EMAIL>> # #------------------------------------------------------------------------------- # Copyright (C) 2013 EOX IT Services GmbH # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies of this Software or works derived from this Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- Encode process description input. Encode process description output. Encode common part of the execure response data input. Encode common part of the execure response data output. Encode the execure response output definition. Encode common sub-elements of all XML parameters. #------------------------------------------------------------------------------- #%s"%dtype.name, #------------------------------------------------------------------------------- #-------------------------------------------------------------------------------
1.311243
1
gci-vci-serverless/src/helpers/vp_saves_helpers.py
ClinGen/gene-and-variant-curation-tools
1
80
import datetime import uuid import simplejson as json from src.db.s3_client import Client as S3Client from decimal import Decimal def get_from_archive(archive_key): ''' Download a VP Save from S3. :param str archive_key: The vp_save data's location (S3 bucket and file path). This value is required. ''' if archive_key is None or '/' not in archive_key: raise ValueError() bucket, key = archive_key.split('/', 1) s3_client = S3Client() try: archive_object = json.loads(s3_client.get_object(bucket, key)['Body'].read(),parse_float=Decimal) except Exception as e: print('ERROR: Error downloading ' + key + ' from ' + bucket + ' bucket. ERROR\n%s' %e) raise return archive_object def build(vp_save={}): ''' Builds and returns a valid vp_save object. Builds a new vp_save object by creating default values for required fields and combines any of the given attributes. ''' vp_save['PK'] = str(uuid.uuid4()) # Set timestamps (for new data) now = datetime.datetime.now().isoformat() vp_save['date_created'] = now vp_save['last_modified'] = now vp_save['item_type'] = 'vp_save' return vp_save def archive(bucket, vp_save_pk, save_data): ''' Archives a vp save data to S3. Uploads the save data object as a JSON file to S3. The location of the archive depends on the bucket and the primary key of the save data. If the upload fails, an exception is raised. If successful, returns the archive location. :param str bucket: The name of the S3 bucket for the archive. This value is required. :param str vp_save_pk: The vp_save PK to use as the name of the JSON file. This value is required. :param obj save_data: The save data object to archive. This value is required. ''' if bucket is None or len(bucket) <= 0: raise ValueError() if vp_save_pk is None or len(vp_save_pk) <= 0: raise ValueError() if not save_data: raise ValueError() archive_file = __archive_key(save_data) + '/' + vp_save_pk + '.json' # Upload curation data to S3 archive bucket. s3_client = S3Client() try: s3_client.put_object( bytes(json.dumps(save_data).encode('UTF-8')), bucket, archive_file ) except Exception as e: print('ERROR: Error uploading ' + archive_file + ' to ' + bucket + ' bucket. ERROR\n%s' %e) raise archive_key_comps = [bucket, archive_file] return '/'.join(archive_key_comps) def __archive_key(save_data): return save_data['PK']
import datetime import uuid import simplejson as json from src.db.s3_client import Client as S3Client from decimal import Decimal def get_from_archive(archive_key): ''' Download a VP Save from S3. :param str archive_key: The vp_save data's location (S3 bucket and file path). This value is required. ''' if archive_key is None or '/' not in archive_key: raise ValueError() bucket, key = archive_key.split('/', 1) s3_client = S3Client() try: archive_object = json.loads(s3_client.get_object(bucket, key)['Body'].read(),parse_float=Decimal) except Exception as e: print('ERROR: Error downloading ' + key + ' from ' + bucket + ' bucket. ERROR\n%s' %e) raise return archive_object def build(vp_save={}): ''' Builds and returns a valid vp_save object. Builds a new vp_save object by creating default values for required fields and combines any of the given attributes. ''' vp_save['PK'] = str(uuid.uuid4()) # Set timestamps (for new data) now = datetime.datetime.now().isoformat() vp_save['date_created'] = now vp_save['last_modified'] = now vp_save['item_type'] = 'vp_save' return vp_save def archive(bucket, vp_save_pk, save_data): ''' Archives a vp save data to S3. Uploads the save data object as a JSON file to S3. The location of the archive depends on the bucket and the primary key of the save data. If the upload fails, an exception is raised. If successful, returns the archive location. :param str bucket: The name of the S3 bucket for the archive. This value is required. :param str vp_save_pk: The vp_save PK to use as the name of the JSON file. This value is required. :param obj save_data: The save data object to archive. This value is required. ''' if bucket is None or len(bucket) <= 0: raise ValueError() if vp_save_pk is None or len(vp_save_pk) <= 0: raise ValueError() if not save_data: raise ValueError() archive_file = __archive_key(save_data) + '/' + vp_save_pk + '.json' # Upload curation data to S3 archive bucket. s3_client = S3Client() try: s3_client.put_object( bytes(json.dumps(save_data).encode('UTF-8')), bucket, archive_file ) except Exception as e: print('ERROR: Error uploading ' + archive_file + ' to ' + bucket + ' bucket. ERROR\n%s' %e) raise archive_key_comps = [bucket, archive_file] return '/'.join(archive_key_comps) def __archive_key(save_data): return save_data['PK']
en
0.760003
Download a VP Save from S3. :param str archive_key: The vp_save data's location (S3 bucket and file path). This value is required. Builds and returns a valid vp_save object. Builds a new vp_save object by creating default values for required fields and combines any of the given attributes. # Set timestamps (for new data) Archives a vp save data to S3. Uploads the save data object as a JSON file to S3. The location of the archive depends on the bucket and the primary key of the save data. If the upload fails, an exception is raised. If successful, returns the archive location. :param str bucket: The name of the S3 bucket for the archive. This value is required. :param str vp_save_pk: The vp_save PK to use as the name of the JSON file. This value is required. :param obj save_data: The save data object to archive. This value is required. # Upload curation data to S3 archive bucket.
2.807394
3
docs/source/auto_examples/plot_usage.py
ruhugu/brokenaxes
362
81
""" Basic usage =========== This example presents the basic usage of brokenaxes """ import matplotlib.pyplot as plt from brokenaxes import brokenaxes import numpy as np fig = plt.figure(figsize=(5,2)) bax = brokenaxes(xlims=((0, .1), (.4, .7)), ylims=((-1, .7), (.79, 1)), hspace=.05) x = np.linspace(0, 1, 100) bax.plot(x, np.sin(10 * x), label='sin') bax.plot(x, np.cos(10 * x), label='cos') bax.legend(loc=3) bax.set_xlabel('time') bax.set_ylabel('value')
""" Basic usage =========== This example presents the basic usage of brokenaxes """ import matplotlib.pyplot as plt from brokenaxes import brokenaxes import numpy as np fig = plt.figure(figsize=(5,2)) bax = brokenaxes(xlims=((0, .1), (.4, .7)), ylims=((-1, .7), (.79, 1)), hspace=.05) x = np.linspace(0, 1, 100) bax.plot(x, np.sin(10 * x), label='sin') bax.plot(x, np.cos(10 * x), label='cos') bax.legend(loc=3) bax.set_xlabel('time') bax.set_ylabel('value')
en
0.605778
Basic usage =========== This example presents the basic usage of brokenaxes
3.567628
4
src/entity/002_createRdf.py
toyo-bunko/paper_app
1
82
import shutil import os import json import glob import yaml import sys import urllib import ssl import csv import time import requests import json import csv from rdflib import URIRef, BNode, Literal, Graph from rdflib.namespace import RDF, RDFS, FOAF, XSD from rdflib import Namespace all = Graph() with open("data/dict.json") as f: ln_map = json.load(f) st_path = "../data/index.json" with open(st_path) as f: result = json.load(f) uris = [] for obj in result: fields = ["spatial", "agential"] for field in fields: values = obj[field] for value in values: uri = "chname:"+value if field == "spatial": uri = "place:"+value if uri not in uris: uris.append(uri) for uri in uris: print(uri) tmp = uri.split(":") prefix = tmp[0] suffix = tmp[1] ln = suffix ln_org = "" if ln in ln_map: ln_org = ln ln = ln_map[ln] if len(ln) > 20: continue # ln = obj["uri"].split(":")[1] ''' wiki_path = "data/wikidata/"+ln+".json" wiki = {} if os.path.exists(wiki_path): with open(wiki_path) as f: wiki = json.load(f) # sameAs stmt = (subject, URIRef("http://www.w3.org/2002/07/owl#sameAs"), URIRef(wiki_url)) all.add(stmt) obj = wiki["entities"][wiki_url.split("/")[-1]] # description if "descriptions" in obj and "ja" in obj["descriptions"]: stmt = (subject, URIRef("http://schema.org/description"), Literal(obj["descriptions"]["ja"]["value"], lang="ja")) all.add(stmt) # label if "labels" in obj and "ja" in obj["labels"]: stmt = (subject, RDFS.label, Literal(obj["labels"]["ja"]["value"])) all.add(stmt) ln = wiki_url.split("/")[-1] ''' db_path = "data/dbpedia_ja/"+ln+".json" wiki_path = "data/wikidata/"+ln+".json" db = {} wiki = {} if os.path.exists(db_path): with open(db_path) as f: db = json.load(f) if os.path.exists(wiki_path): with open(wiki_path) as f: wiki = json.load(f) db_uri = "http://ja.dbpedia.org/resource/"+ln if db_uri not in db: print("not" , db_uri) continue # ###### subject = URIRef("https://shibusawa-dlab.github.io/lab1/api/"+prefix+"/"+ln) if prefix == "chname": stmt = (subject, RDF.type, URIRef("https://jpsearch.go.jp/term/type/Agent")) all.add(stmt) elif prefix == "time": stmt = (subject, RDF.type, URIRef("https://jpsearch.go.jp/term/type/Time")) all.add(stmt) elif prefix == "place": stmt = (subject, RDF.type, URIRef("https://jpsearch.go.jp/term/type/Place")) all.add(stmt) elif prefix == "event": stmt = (subject, RDF.type, URIRef("https://jpsearch.go.jp/term/type/Event")) all.add(stmt) elif prefix == "org": stmt = (subject, RDF.type, URIRef("https://jpsearch.go.jp/term/type/Organization")) all.add(stmt) elif prefix == "keyword": stmt = (subject, RDF.type, URIRef("https://jpsearch.go.jp/term/type/Keyword")) all.add(stmt) elif prefix == "type": stmt = (subject, RDF.type, URIRef("https://jpsearch.go.jp/term/type/Type")) all.add(stmt) # ###### obj = db[db_uri] stmt = (subject, URIRef("http://www.w3.org/2002/07/owl#sameAs"), URIRef(db_uri)) all.add(stmt) if "http://dbpedia.org/ontology/thumbnail" in obj: stmt = (subject, URIRef("http://schema.org/image"), URIRef(obj["http://dbpedia.org/ontology/thumbnail"][0]["value"])) all.add(stmt) if "http://www.w3.org/2000/01/rdf-schema#label" in obj: labels = obj["http://www.w3.org/2000/01/rdf-schema#label"] for label in labels: if label["lang"] == "ja": stmt = (subject, RDFS.label, Literal(label["value"])) all.add(stmt) if "http://www.w3.org/2000/01/rdf-schema#comment" in obj: labels = obj["http://www.w3.org/2000/01/rdf-schema#comment"] for label in labels: stmt = (subject, URIRef("http://schema.org/description"), Literal(label["value"], lang=label["lang"])) all.add(stmt) if "http://www.w3.org/2002/07/owl#sameAs" in obj: labels = obj["http://www.w3.org/2002/07/owl#sameAs"] for label in labels: value = label["value"] if "http://dbpedia.org" in value or "http://ja.dbpedia.org" in value or "www.wikidata.org" in value: stmt = (subject, URIRef("http://www.w3.org/2002/07/owl#sameAs"), URIRef(value)) all.add(stmt) # 位置情報 ''' if "point" in obj and prefix == "place": value = obj["point"]["value"].split(" ") # addGeo関数 geoUri = addGeo({ "lat" : float(value[0]), "long": float(value[1]) }) stmt = (subject, URIRef("http://schema.org/geo"), geoUri) if suffix not in places: places[suffix] = { "lat" : float(value[0]), "long": float(value[1]) } all.add(stmt) ''' # 正規化前 if ln_org != "" and ln != ln_org: stmt = (subject, URIRef("http://schema.org/name"), Literal(ln_org)) all.add(stmt) path = "data/all.json" all.serialize(destination=path, format='json-ld') all.serialize(destination=path.replace(".json", ".rdf"), format='pretty-xml')
import shutil import os import json import glob import yaml import sys import urllib import ssl import csv import time import requests import json import csv from rdflib import URIRef, BNode, Literal, Graph from rdflib.namespace import RDF, RDFS, FOAF, XSD from rdflib import Namespace all = Graph() with open("data/dict.json") as f: ln_map = json.load(f) st_path = "../data/index.json" with open(st_path) as f: result = json.load(f) uris = [] for obj in result: fields = ["spatial", "agential"] for field in fields: values = obj[field] for value in values: uri = "chname:"+value if field == "spatial": uri = "place:"+value if uri not in uris: uris.append(uri) for uri in uris: print(uri) tmp = uri.split(":") prefix = tmp[0] suffix = tmp[1] ln = suffix ln_org = "" if ln in ln_map: ln_org = ln ln = ln_map[ln] if len(ln) > 20: continue # ln = obj["uri"].split(":")[1] ''' wiki_path = "data/wikidata/"+ln+".json" wiki = {} if os.path.exists(wiki_path): with open(wiki_path) as f: wiki = json.load(f) # sameAs stmt = (subject, URIRef("http://www.w3.org/2002/07/owl#sameAs"), URIRef(wiki_url)) all.add(stmt) obj = wiki["entities"][wiki_url.split("/")[-1]] # description if "descriptions" in obj and "ja" in obj["descriptions"]: stmt = (subject, URIRef("http://schema.org/description"), Literal(obj["descriptions"]["ja"]["value"], lang="ja")) all.add(stmt) # label if "labels" in obj and "ja" in obj["labels"]: stmt = (subject, RDFS.label, Literal(obj["labels"]["ja"]["value"])) all.add(stmt) ln = wiki_url.split("/")[-1] ''' db_path = "data/dbpedia_ja/"+ln+".json" wiki_path = "data/wikidata/"+ln+".json" db = {} wiki = {} if os.path.exists(db_path): with open(db_path) as f: db = json.load(f) if os.path.exists(wiki_path): with open(wiki_path) as f: wiki = json.load(f) db_uri = "http://ja.dbpedia.org/resource/"+ln if db_uri not in db: print("not" , db_uri) continue # ###### subject = URIRef("https://shibusawa-dlab.github.io/lab1/api/"+prefix+"/"+ln) if prefix == "chname": stmt = (subject, RDF.type, URIRef("https://jpsearch.go.jp/term/type/Agent")) all.add(stmt) elif prefix == "time": stmt = (subject, RDF.type, URIRef("https://jpsearch.go.jp/term/type/Time")) all.add(stmt) elif prefix == "place": stmt = (subject, RDF.type, URIRef("https://jpsearch.go.jp/term/type/Place")) all.add(stmt) elif prefix == "event": stmt = (subject, RDF.type, URIRef("https://jpsearch.go.jp/term/type/Event")) all.add(stmt) elif prefix == "org": stmt = (subject, RDF.type, URIRef("https://jpsearch.go.jp/term/type/Organization")) all.add(stmt) elif prefix == "keyword": stmt = (subject, RDF.type, URIRef("https://jpsearch.go.jp/term/type/Keyword")) all.add(stmt) elif prefix == "type": stmt = (subject, RDF.type, URIRef("https://jpsearch.go.jp/term/type/Type")) all.add(stmt) # ###### obj = db[db_uri] stmt = (subject, URIRef("http://www.w3.org/2002/07/owl#sameAs"), URIRef(db_uri)) all.add(stmt) if "http://dbpedia.org/ontology/thumbnail" in obj: stmt = (subject, URIRef("http://schema.org/image"), URIRef(obj["http://dbpedia.org/ontology/thumbnail"][0]["value"])) all.add(stmt) if "http://www.w3.org/2000/01/rdf-schema#label" in obj: labels = obj["http://www.w3.org/2000/01/rdf-schema#label"] for label in labels: if label["lang"] == "ja": stmt = (subject, RDFS.label, Literal(label["value"])) all.add(stmt) if "http://www.w3.org/2000/01/rdf-schema#comment" in obj: labels = obj["http://www.w3.org/2000/01/rdf-schema#comment"] for label in labels: stmt = (subject, URIRef("http://schema.org/description"), Literal(label["value"], lang=label["lang"])) all.add(stmt) if "http://www.w3.org/2002/07/owl#sameAs" in obj: labels = obj["http://www.w3.org/2002/07/owl#sameAs"] for label in labels: value = label["value"] if "http://dbpedia.org" in value or "http://ja.dbpedia.org" in value or "www.wikidata.org" in value: stmt = (subject, URIRef("http://www.w3.org/2002/07/owl#sameAs"), URIRef(value)) all.add(stmt) # 位置情報 ''' if "point" in obj and prefix == "place": value = obj["point"]["value"].split(" ") # addGeo関数 geoUri = addGeo({ "lat" : float(value[0]), "long": float(value[1]) }) stmt = (subject, URIRef("http://schema.org/geo"), geoUri) if suffix not in places: places[suffix] = { "lat" : float(value[0]), "long": float(value[1]) } all.add(stmt) ''' # 正規化前 if ln_org != "" and ln != ln_org: stmt = (subject, URIRef("http://schema.org/name"), Literal(ln_org)) all.add(stmt) path = "data/all.json" all.serialize(destination=path, format='json-ld') all.serialize(destination=path.replace(".json", ".rdf"), format='pretty-xml')
en
0.248541
# ln = obj["uri"].split(":")[1] wiki_path = "data/wikidata/"+ln+".json" wiki = {} if os.path.exists(wiki_path): with open(wiki_path) as f: wiki = json.load(f) # sameAs stmt = (subject, URIRef("http://www.w3.org/2002/07/owl#sameAs"), URIRef(wiki_url)) all.add(stmt) obj = wiki["entities"][wiki_url.split("/")[-1]] # description if "descriptions" in obj and "ja" in obj["descriptions"]: stmt = (subject, URIRef("http://schema.org/description"), Literal(obj["descriptions"]["ja"]["value"], lang="ja")) all.add(stmt) # label if "labels" in obj and "ja" in obj["labels"]: stmt = (subject, RDFS.label, Literal(obj["labels"]["ja"]["value"])) all.add(stmt) ln = wiki_url.split("/")[-1] # ###### # ###### #sameAs"), URIRef(db_uri)) #label" in obj: #label"] #comment" in obj: #comment"] #sameAs" in obj: #sameAs"] #sameAs"), URIRef(value)) # 位置情報 if "point" in obj and prefix == "place": value = obj["point"]["value"].split(" ") # addGeo関数 geoUri = addGeo({ "lat" : float(value[0]), "long": float(value[1]) }) stmt = (subject, URIRef("http://schema.org/geo"), geoUri) if suffix not in places: places[suffix] = { "lat" : float(value[0]), "long": float(value[1]) } all.add(stmt) # 正規化前
2.632599
3
client/tests/test_config_read_tool.py
nuft/can-bootloader
0
83
import unittest try: from unittest.mock import * except ImportError: from mock import * from msgpack import * import bootloader_read_config from commands import * import sys import json class ReadConfigToolTestCase(unittest.TestCase): @patch('utils.write_command_retry') @patch('utils.write_command') @patch('utils.open_connection') @patch('builtins.print') def test_integration(self, print_mock, open_conn, write_command, write_command_retry): sys.argv = "test.py -p /dev/ttyUSB0 0 1 2".split() configs = [{'id': i} for i in range(3)] write_command_retry.return_value = { i: packb(configs[i]) for i in range(3) } open_conn.return_value = object() bootloader_read_config.main() write_command_retry.assert_any_call(open_conn.return_value, encode_read_config(), [0, 1, 2]) all_configs = {i: configs[i] for i in range(3)} print_mock.assert_any_call(json.dumps(all_configs, indent=4, sort_keys=True)) @patch('utils.open_connection') @patch('utils.write_command_retry') @patch('utils.write_command') @patch('utils.read_can_datagrams') @patch('builtins.print') def test_network_discovery(self, print_mock, read_can_datagram, write_command, write_command_retry, open_conn): """ Checks if we can perform a whole network discovery. """ sys.argv = "test.py -p /dev/ttyUSB0 --all".split() # The first two board answers the ping board_answers = [(b'', [0], i) for i in range(1, 3)] + [None] read_can_datagram.return_value = iter(board_answers) write_command_retry.return_value = { i: packb({'id': i}) for i in range(1, 3) } bootloader_read_config.main() write_command.assert_any_call(open_conn.return_value, encode_ping(), list(range(1, 128)))
import unittest try: from unittest.mock import * except ImportError: from mock import * from msgpack import * import bootloader_read_config from commands import * import sys import json class ReadConfigToolTestCase(unittest.TestCase): @patch('utils.write_command_retry') @patch('utils.write_command') @patch('utils.open_connection') @patch('builtins.print') def test_integration(self, print_mock, open_conn, write_command, write_command_retry): sys.argv = "test.py -p /dev/ttyUSB0 0 1 2".split() configs = [{'id': i} for i in range(3)] write_command_retry.return_value = { i: packb(configs[i]) for i in range(3) } open_conn.return_value = object() bootloader_read_config.main() write_command_retry.assert_any_call(open_conn.return_value, encode_read_config(), [0, 1, 2]) all_configs = {i: configs[i] for i in range(3)} print_mock.assert_any_call(json.dumps(all_configs, indent=4, sort_keys=True)) @patch('utils.open_connection') @patch('utils.write_command_retry') @patch('utils.write_command') @patch('utils.read_can_datagrams') @patch('builtins.print') def test_network_discovery(self, print_mock, read_can_datagram, write_command, write_command_retry, open_conn): """ Checks if we can perform a whole network discovery. """ sys.argv = "test.py -p /dev/ttyUSB0 --all".split() # The first two board answers the ping board_answers = [(b'', [0], i) for i in range(1, 3)] + [None] read_can_datagram.return_value = iter(board_answers) write_command_retry.return_value = { i: packb({'id': i}) for i in range(1, 3) } bootloader_read_config.main() write_command.assert_any_call(open_conn.return_value, encode_ping(), list(range(1, 128)))
en
0.905069
Checks if we can perform a whole network discovery. # The first two board answers the ping
2.600654
3
bot.py
Pyrrolidine/letterboxd-bot
1
84
import logging from asyncio import sleep import discord from discord.ext import commands from config import SETTINGS from crew import crew_embed from diary import diary_embed from film import film_embed from helpers import LetterboxdError from list_ import list_embed from review import review_embed from user import user_embed logging.basicConfig( level=logging.INFO, format='%(asctime)s | %(message)s', datefmt='%m/%d %H:%M:%S') bot = commands.Bot(command_prefix='!', case_insensitive=True) bot.remove_command('help') @bot.event async def on_ready(): logging.info( 'Logged in %d servers as %s' % (len(bot.guilds), bot.user.name)) bot.loop.create_task(update_stats()) @bot.event async def on_message(message): if message.content.startswith('!'): message.content = message.content.replace('’', '').replace('‘', '') await bot.process_commands(message) async def update_stats(): while True: await bot.change_presence( activity=discord.Game('!helplb - {} servers'.format( len(bot.guilds)))) await sleep(900) @bot.event async def on_command_error(ctx, error): if isinstance(error, commands.MissingRequiredArgument): await ctx.send('This command requires a parameter.') elif isinstance(error, commands.BotMissingPermissions): await ctx.send('This command requires the {} permission.'.format( ', '.join(err for err in error.missing_perms))) elif isinstance(error, (commands.CommandNotFound, commands.CheckFailure)): return elif isinstance(error, commands.CommandInvokeError): if isinstance(error.original, discord.HTTPException): return else: await ctx.send('Sorry, the command crashed. :/') logging.error(ctx.message.content) raise error async def send_msg(ctx, msg): if isinstance(msg, discord.Embed): await ctx.send(embed=msg) else: await ctx.send(msg) # Commands @bot.command() async def helplb(ctx): help_embed = discord.Embed(colour=discord.Color.from_rgb(54, 57, 62)) help_embed.set_thumbnail(url='https://i.imgur.com/Kr1diFu.png') help_embed.set_author( name='Letterboxd Bot', icon_url='https://i.imgur.com/5VALKVy.jpg') help_embed.set_footer( text='Created by Porkepik#2664', icon_url='https://i.imgur.com/li4cLpd.png') for key, value in SETTINGS['help'].items(): help_embed.add_field(name=key, value=value, inline=False) help_embed.description = 'Invite Bot | '\ + '[GitHub](https://github.com/Porkepik/Letterboxd-Bot)' await ctx.send(embed=help_embed) @bot.command() async def user(ctx, username): try: msg = await user_embed(username) except LetterboxdError as err: msg = err await send_msg(ctx, msg) @bot.command() async def diary(ctx, username): try: msg = await diary_embed(username) except LetterboxdError as err: msg = err await send_msg(ctx, msg) @bot.command(aliases=['actor', 'actress', 'director']) async def crew(ctx, *, arg): try: msg = await crew_embed(arg, ctx.invoked_with) except LetterboxdError as err: msg = err await send_msg(ctx, msg) @bot.command(aliases=['movie']) async def film(ctx, *, arg): try: # eiga.me ratings for specific servers if ctx.guild and ctx.guild.id in SETTINGS['mkdb_servers']: msg = await film_embed(arg, True) else: msg = await film_embed(arg) except LetterboxdError as err: msg = err await send_msg(ctx, msg) async def check_if_two_args(ctx): msg = ctx.message.content.split() if len(msg) < 3: await ctx.send('This command requires 2 parameters.') return len(msg) > 2 @bot.command(name='list') @commands.check(check_if_two_args) async def list_(ctx, username, *args): try: msg = await list_embed(username, ' '.join(str(i) for i in args)) except LetterboxdError as err: msg = err await send_msg(ctx, msg) @bot.command(aliases=['entry']) @commands.check(check_if_two_args) async def review(ctx, username, *args): try: msg = await review_embed(username, ' '.join(str(i) for i in args)) except LetterboxdError as err: msg = err await send_msg(ctx, msg) @bot.command(name='del') @commands.bot_has_permissions(manage_messages=True) async def delete(ctx): await ctx.message.delete() found_bot_msg = False found_usr_cmd = False cmd_list = list() for command in bot.commands: cmd_list.append('!' + command.name) for alias in command.aliases: cmd_list.append('!' + alias) async for log_message in ctx.channel.history(limit=30): if log_message.author.id == bot.user.id and not found_bot_msg: bot_message = log_message found_bot_msg = True elif found_bot_msg: if log_message.content: first_word = log_message.content.split()[0] else: continue if first_word in cmd_list: found_usr_cmd = True cmd_message = log_message break if found_usr_cmd: if not ctx.author.permissions_in(ctx.channel).manage_messages: if not cmd_message.author.id == ctx.author.id: return await cmd_message.delete() await bot_message.delete() bot.run(SETTINGS['discord'])
import logging from asyncio import sleep import discord from discord.ext import commands from config import SETTINGS from crew import crew_embed from diary import diary_embed from film import film_embed from helpers import LetterboxdError from list_ import list_embed from review import review_embed from user import user_embed logging.basicConfig( level=logging.INFO, format='%(asctime)s | %(message)s', datefmt='%m/%d %H:%M:%S') bot = commands.Bot(command_prefix='!', case_insensitive=True) bot.remove_command('help') @bot.event async def on_ready(): logging.info( 'Logged in %d servers as %s' % (len(bot.guilds), bot.user.name)) bot.loop.create_task(update_stats()) @bot.event async def on_message(message): if message.content.startswith('!'): message.content = message.content.replace('’', '').replace('‘', '') await bot.process_commands(message) async def update_stats(): while True: await bot.change_presence( activity=discord.Game('!helplb - {} servers'.format( len(bot.guilds)))) await sleep(900) @bot.event async def on_command_error(ctx, error): if isinstance(error, commands.MissingRequiredArgument): await ctx.send('This command requires a parameter.') elif isinstance(error, commands.BotMissingPermissions): await ctx.send('This command requires the {} permission.'.format( ', '.join(err for err in error.missing_perms))) elif isinstance(error, (commands.CommandNotFound, commands.CheckFailure)): return elif isinstance(error, commands.CommandInvokeError): if isinstance(error.original, discord.HTTPException): return else: await ctx.send('Sorry, the command crashed. :/') logging.error(ctx.message.content) raise error async def send_msg(ctx, msg): if isinstance(msg, discord.Embed): await ctx.send(embed=msg) else: await ctx.send(msg) # Commands @bot.command() async def helplb(ctx): help_embed = discord.Embed(colour=discord.Color.from_rgb(54, 57, 62)) help_embed.set_thumbnail(url='https://i.imgur.com/Kr1diFu.png') help_embed.set_author( name='Letterboxd Bot', icon_url='https://i.imgur.com/5VALKVy.jpg') help_embed.set_footer( text='Created by Porkepik#2664', icon_url='https://i.imgur.com/li4cLpd.png') for key, value in SETTINGS['help'].items(): help_embed.add_field(name=key, value=value, inline=False) help_embed.description = 'Invite Bot | '\ + '[GitHub](https://github.com/Porkepik/Letterboxd-Bot)' await ctx.send(embed=help_embed) @bot.command() async def user(ctx, username): try: msg = await user_embed(username) except LetterboxdError as err: msg = err await send_msg(ctx, msg) @bot.command() async def diary(ctx, username): try: msg = await diary_embed(username) except LetterboxdError as err: msg = err await send_msg(ctx, msg) @bot.command(aliases=['actor', 'actress', 'director']) async def crew(ctx, *, arg): try: msg = await crew_embed(arg, ctx.invoked_with) except LetterboxdError as err: msg = err await send_msg(ctx, msg) @bot.command(aliases=['movie']) async def film(ctx, *, arg): try: # eiga.me ratings for specific servers if ctx.guild and ctx.guild.id in SETTINGS['mkdb_servers']: msg = await film_embed(arg, True) else: msg = await film_embed(arg) except LetterboxdError as err: msg = err await send_msg(ctx, msg) async def check_if_two_args(ctx): msg = ctx.message.content.split() if len(msg) < 3: await ctx.send('This command requires 2 parameters.') return len(msg) > 2 @bot.command(name='list') @commands.check(check_if_two_args) async def list_(ctx, username, *args): try: msg = await list_embed(username, ' '.join(str(i) for i in args)) except LetterboxdError as err: msg = err await send_msg(ctx, msg) @bot.command(aliases=['entry']) @commands.check(check_if_two_args) async def review(ctx, username, *args): try: msg = await review_embed(username, ' '.join(str(i) for i in args)) except LetterboxdError as err: msg = err await send_msg(ctx, msg) @bot.command(name='del') @commands.bot_has_permissions(manage_messages=True) async def delete(ctx): await ctx.message.delete() found_bot_msg = False found_usr_cmd = False cmd_list = list() for command in bot.commands: cmd_list.append('!' + command.name) for alias in command.aliases: cmd_list.append('!' + alias) async for log_message in ctx.channel.history(limit=30): if log_message.author.id == bot.user.id and not found_bot_msg: bot_message = log_message found_bot_msg = True elif found_bot_msg: if log_message.content: first_word = log_message.content.split()[0] else: continue if first_word in cmd_list: found_usr_cmd = True cmd_message = log_message break if found_usr_cmd: if not ctx.author.permissions_in(ctx.channel).manage_messages: if not cmd_message.author.id == ctx.author.id: return await cmd_message.delete() await bot_message.delete() bot.run(SETTINGS['discord'])
en
0.742594
# Commands #2664', # eiga.me ratings for specific servers
2.212044
2
python/ray/experimental/workflow/execution.py
wgifford/ray
0
85
<gh_stars>0 import asyncio import logging import time from typing import Set, List, Tuple, Optional, TYPE_CHECKING import uuid import ray from ray.experimental.workflow import workflow_context from ray.experimental.workflow import workflow_storage from ray.experimental.workflow.common import (Workflow, WorkflowStatus, WorkflowMetaData, StepType) from ray.experimental.workflow.step_executor import commit_step from ray.experimental.workflow.storage import get_global_storage from ray.experimental.workflow.workflow_access import ( flatten_workflow_output, get_or_create_management_actor, get_management_actor) if TYPE_CHECKING: from ray.experimental.workflow.step_executor import WorkflowExecutionResult logger = logging.getLogger(__name__) def run(entry_workflow: Workflow, workflow_id: Optional[str] = None, overwrite: bool = True) -> ray.ObjectRef: """Run a workflow asynchronously. # TODO(suquark): The current "run" always overwrite existing workflow. # We need to fix this later. """ store = get_global_storage() assert ray.is_initialized() if workflow_id is None: # Workflow ID format: {Entry workflow UUID}.{Unix time to nanoseconds} workflow_id = f"{str(uuid.uuid4())}.{time.time():.9f}" logger.info(f"Workflow job created. [id=\"{workflow_id}\", storage_url=" f"\"{store.storage_url}\"].") with workflow_context.workflow_step_context(workflow_id, store.storage_url): # checkpoint the workflow ws = workflow_storage.get_workflow_storage(workflow_id) commit_step(ws, "", entry_workflow) workflow_manager = get_or_create_management_actor() ignore_existing = (entry_workflow.data.step_type != StepType.FUNCTION) # NOTE: It is important to 'ray.get' the returned output. This # ensures caller of 'run()' holds the reference to the workflow # result. Otherwise if the actor removes the reference of the # workflow output, the caller may fail to resolve the result. result: "WorkflowExecutionResult" = ray.get( workflow_manager.run_or_resume.remote(workflow_id, ignore_existing)) if entry_workflow.data.step_type == StepType.FUNCTION: return flatten_workflow_output(workflow_id, result.persisted_output) else: return flatten_workflow_output(workflow_id, result.volatile_output) # TODO(suquark): support recovery with ObjectRef inputs. def resume(workflow_id: str) -> ray.ObjectRef: """Resume a workflow asynchronously. See "api.resume()" for details. """ storage = get_global_storage() logger.info(f"Resuming workflow [id=\"{workflow_id}\", storage_url=" f"\"{storage.storage_url}\"].") workflow_manager = get_or_create_management_actor() # NOTE: It is important to 'ray.get' the returned output. This # ensures caller of 'run()' holds the reference to the workflow # result. Otherwise if the actor removes the reference of the # workflow output, the caller may fail to resolve the result. result: "WorkflowExecutionResult" = ray.get( workflow_manager.run_or_resume.remote( workflow_id, ignore_existing=False)) logger.info(f"Workflow job {workflow_id} resumed.") return flatten_workflow_output(workflow_id, result.persisted_output) def get_output(workflow_id: str, name: Optional[str]) -> ray.ObjectRef: """Get the output of a running workflow. See "api.get_output()" for details. """ assert ray.is_initialized() try: workflow_manager = get_management_actor() except ValueError as e: raise ValueError( "Failed to connect to the workflow management " "actor. The workflow could have already failed. You can use " "workflow.resume() to resume the workflow.") from e output = ray.get(workflow_manager.get_output.remote(workflow_id, name)) return flatten_workflow_output(workflow_id, output) def cancel(workflow_id: str) -> None: try: workflow_manager = get_management_actor() ray.get(workflow_manager.cancel_workflow.remote(workflow_id)) except ValueError: wf_store = workflow_storage.get_workflow_storage(workflow_id) wf_store.save_workflow_meta(WorkflowMetaData(WorkflowStatus.CANCELED)) def get_status(workflow_id: str) -> Optional[WorkflowStatus]: try: workflow_manager = get_management_actor() running = ray.get( workflow_manager.is_workflow_running.remote(workflow_id)) except Exception: running = False if running: return WorkflowStatus.RUNNING store = workflow_storage.get_workflow_storage(workflow_id) meta = store.load_workflow_meta() if meta is None: raise ValueError(f"No such workflow_id {workflow_id}") return meta.status def list_all(status_filter: Set[WorkflowStatus] ) -> List[Tuple[str, WorkflowStatus]]: try: workflow_manager = get_management_actor() except ValueError: workflow_manager = None if workflow_manager is None: runnings = [] else: runnings = ray.get(workflow_manager.list_running_workflow.remote()) if WorkflowStatus.RUNNING in status_filter and len(status_filter) == 1: return [(r, WorkflowStatus.RUNNING) for r in runnings] runnings = set(runnings) # Here we don't have workflow id, so use empty one instead store = workflow_storage.get_workflow_storage("") ret = [] for (k, s) in store.list_workflow(): if s == WorkflowStatus.RUNNING and k not in runnings: s = WorkflowStatus.RESUMABLE if s in status_filter: ret.append((k, s)) return ret def resume_all(with_failed: bool) -> List[Tuple[str, ray.ObjectRef]]: filter_set = {WorkflowStatus.RESUMABLE} if with_failed: filter_set.add(WorkflowStatus.FAILED) all_failed = list_all(filter_set) try: workflow_manager = get_management_actor() except Exception as e: raise RuntimeError("Failed to get management actor") from e async def _resume_one(wid: str) -> Tuple[str, Optional[ray.ObjectRef]]: try: result: "WorkflowExecutionResult" = ( await workflow_manager.run_or_resume.remote(wid)) obj = flatten_workflow_output(wid, result.persisted_output) return wid, obj except Exception: logger.error(f"Failed to resume workflow {wid}") return (wid, None) ret = workflow_storage.asyncio_run( asyncio.gather(*[_resume_one(wid) for (wid, _) in all_failed])) return [(wid, obj) for (wid, obj) in ret if obj is not None]
import asyncio import logging import time from typing import Set, List, Tuple, Optional, TYPE_CHECKING import uuid import ray from ray.experimental.workflow import workflow_context from ray.experimental.workflow import workflow_storage from ray.experimental.workflow.common import (Workflow, WorkflowStatus, WorkflowMetaData, StepType) from ray.experimental.workflow.step_executor import commit_step from ray.experimental.workflow.storage import get_global_storage from ray.experimental.workflow.workflow_access import ( flatten_workflow_output, get_or_create_management_actor, get_management_actor) if TYPE_CHECKING: from ray.experimental.workflow.step_executor import WorkflowExecutionResult logger = logging.getLogger(__name__) def run(entry_workflow: Workflow, workflow_id: Optional[str] = None, overwrite: bool = True) -> ray.ObjectRef: """Run a workflow asynchronously. # TODO(suquark): The current "run" always overwrite existing workflow. # We need to fix this later. """ store = get_global_storage() assert ray.is_initialized() if workflow_id is None: # Workflow ID format: {Entry workflow UUID}.{Unix time to nanoseconds} workflow_id = f"{str(uuid.uuid4())}.{time.time():.9f}" logger.info(f"Workflow job created. [id=\"{workflow_id}\", storage_url=" f"\"{store.storage_url}\"].") with workflow_context.workflow_step_context(workflow_id, store.storage_url): # checkpoint the workflow ws = workflow_storage.get_workflow_storage(workflow_id) commit_step(ws, "", entry_workflow) workflow_manager = get_or_create_management_actor() ignore_existing = (entry_workflow.data.step_type != StepType.FUNCTION) # NOTE: It is important to 'ray.get' the returned output. This # ensures caller of 'run()' holds the reference to the workflow # result. Otherwise if the actor removes the reference of the # workflow output, the caller may fail to resolve the result. result: "WorkflowExecutionResult" = ray.get( workflow_manager.run_or_resume.remote(workflow_id, ignore_existing)) if entry_workflow.data.step_type == StepType.FUNCTION: return flatten_workflow_output(workflow_id, result.persisted_output) else: return flatten_workflow_output(workflow_id, result.volatile_output) # TODO(suquark): support recovery with ObjectRef inputs. def resume(workflow_id: str) -> ray.ObjectRef: """Resume a workflow asynchronously. See "api.resume()" for details. """ storage = get_global_storage() logger.info(f"Resuming workflow [id=\"{workflow_id}\", storage_url=" f"\"{storage.storage_url}\"].") workflow_manager = get_or_create_management_actor() # NOTE: It is important to 'ray.get' the returned output. This # ensures caller of 'run()' holds the reference to the workflow # result. Otherwise if the actor removes the reference of the # workflow output, the caller may fail to resolve the result. result: "WorkflowExecutionResult" = ray.get( workflow_manager.run_or_resume.remote( workflow_id, ignore_existing=False)) logger.info(f"Workflow job {workflow_id} resumed.") return flatten_workflow_output(workflow_id, result.persisted_output) def get_output(workflow_id: str, name: Optional[str]) -> ray.ObjectRef: """Get the output of a running workflow. See "api.get_output()" for details. """ assert ray.is_initialized() try: workflow_manager = get_management_actor() except ValueError as e: raise ValueError( "Failed to connect to the workflow management " "actor. The workflow could have already failed. You can use " "workflow.resume() to resume the workflow.") from e output = ray.get(workflow_manager.get_output.remote(workflow_id, name)) return flatten_workflow_output(workflow_id, output) def cancel(workflow_id: str) -> None: try: workflow_manager = get_management_actor() ray.get(workflow_manager.cancel_workflow.remote(workflow_id)) except ValueError: wf_store = workflow_storage.get_workflow_storage(workflow_id) wf_store.save_workflow_meta(WorkflowMetaData(WorkflowStatus.CANCELED)) def get_status(workflow_id: str) -> Optional[WorkflowStatus]: try: workflow_manager = get_management_actor() running = ray.get( workflow_manager.is_workflow_running.remote(workflow_id)) except Exception: running = False if running: return WorkflowStatus.RUNNING store = workflow_storage.get_workflow_storage(workflow_id) meta = store.load_workflow_meta() if meta is None: raise ValueError(f"No such workflow_id {workflow_id}") return meta.status def list_all(status_filter: Set[WorkflowStatus] ) -> List[Tuple[str, WorkflowStatus]]: try: workflow_manager = get_management_actor() except ValueError: workflow_manager = None if workflow_manager is None: runnings = [] else: runnings = ray.get(workflow_manager.list_running_workflow.remote()) if WorkflowStatus.RUNNING in status_filter and len(status_filter) == 1: return [(r, WorkflowStatus.RUNNING) for r in runnings] runnings = set(runnings) # Here we don't have workflow id, so use empty one instead store = workflow_storage.get_workflow_storage("") ret = [] for (k, s) in store.list_workflow(): if s == WorkflowStatus.RUNNING and k not in runnings: s = WorkflowStatus.RESUMABLE if s in status_filter: ret.append((k, s)) return ret def resume_all(with_failed: bool) -> List[Tuple[str, ray.ObjectRef]]: filter_set = {WorkflowStatus.RESUMABLE} if with_failed: filter_set.add(WorkflowStatus.FAILED) all_failed = list_all(filter_set) try: workflow_manager = get_management_actor() except Exception as e: raise RuntimeError("Failed to get management actor") from e async def _resume_one(wid: str) -> Tuple[str, Optional[ray.ObjectRef]]: try: result: "WorkflowExecutionResult" = ( await workflow_manager.run_or_resume.remote(wid)) obj = flatten_workflow_output(wid, result.persisted_output) return wid, obj except Exception: logger.error(f"Failed to resume workflow {wid}") return (wid, None) ret = workflow_storage.asyncio_run( asyncio.gather(*[_resume_one(wid) for (wid, _) in all_failed])) return [(wid, obj) for (wid, obj) in ret if obj is not None]
en
0.776901
Run a workflow asynchronously. # TODO(suquark): The current "run" always overwrite existing workflow. # We need to fix this later. # Workflow ID format: {Entry workflow UUID}.{Unix time to nanoseconds} # checkpoint the workflow # NOTE: It is important to 'ray.get' the returned output. This # ensures caller of 'run()' holds the reference to the workflow # result. Otherwise if the actor removes the reference of the # workflow output, the caller may fail to resolve the result. # TODO(suquark): support recovery with ObjectRef inputs. Resume a workflow asynchronously. See "api.resume()" for details. # NOTE: It is important to 'ray.get' the returned output. This # ensures caller of 'run()' holds the reference to the workflow # result. Otherwise if the actor removes the reference of the # workflow output, the caller may fail to resolve the result. Get the output of a running workflow. See "api.get_output()" for details. # Here we don't have workflow id, so use empty one instead
2.099409
2
src/zeep/wsse/__init__.py
bertonha/python-zeep
0
86
<reponame>bertonha/python-zeep from .compose import Compose # noqa from .signature import BinarySignature, Signature, MemorySignature # noqa from .username import UsernameToken # noqa
from .compose import Compose # noqa from .signature import BinarySignature, Signature, MemorySignature # noqa from .username import UsernameToken # noqa
uz
0.446344
# noqa # noqa # noqa
1.009677
1
Complab assignment.py
peteboi/Python-Scripts
0
87
<reponame>peteboi/Python-Scripts<gh_stars>0 # -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt def orbit(u): x,y,v_x,v_y = u r=np.hypot(x,y) #r= 1.521e+06 #M,G=1.989e+30,6.7e-11 M,G=20,110 f=G*M/r**3 return np.array([v_x,v_y,-f*x,-f*y]) def RK4(f,u,dt): k1=f(u)*dt k2=f(u+0.5*k1)*dt k3=f(u+0.5*k2)*dt k4=f(u+k3)*dt return u+(k1+2*k2+2*k3+k4)/6 def RK4_int(f,y0,tspan): y=np.zeros([len(tspan),len(y0)]) y[0,:] =y0 for k in range (1,len(tspan)): y[k,:] = RK4(f,y[k-1],tspan[k]-tspan[k-1]) return y dt=0.1 t = np.arange(0,10,dt) y0=np.array([10, 0.0, 10, 10]) sol_rk4=RK4_int(orbit,y0,t) x,y,v_x,v_y = sol_rk4.T plt.grid() plt.plot(x,y) plt.show()
# -*- coding: utf-8 -*- import numpy as np import matplotlib.pyplot as plt def orbit(u): x,y,v_x,v_y = u r=np.hypot(x,y) #r= 1.521e+06 #M,G=1.989e+30,6.7e-11 M,G=20,110 f=G*M/r**3 return np.array([v_x,v_y,-f*x,-f*y]) def RK4(f,u,dt): k1=f(u)*dt k2=f(u+0.5*k1)*dt k3=f(u+0.5*k2)*dt k4=f(u+k3)*dt return u+(k1+2*k2+2*k3+k4)/6 def RK4_int(f,y0,tspan): y=np.zeros([len(tspan),len(y0)]) y[0,:] =y0 for k in range (1,len(tspan)): y[k,:] = RK4(f,y[k-1],tspan[k]-tspan[k-1]) return y dt=0.1 t = np.arange(0,10,dt) y0=np.array([10, 0.0, 10, 10]) sol_rk4=RK4_int(orbit,y0,t) x,y,v_x,v_y = sol_rk4.T plt.grid() plt.plot(x,y) plt.show()
en
0.724715
# -*- coding: utf-8 -*- #r= 1.521e+06 #M,G=1.989e+30,6.7e-11
3.044791
3
factory_generator/management/commands/generate_factories.py
gamabounty/django-factory-generator
10
88
<reponame>gamabounty/django-factory-generator import os from django.apps import apps from django.core.management.base import BaseCommand from factory_generator.generator import FactoryAppGenerator class Command(BaseCommand): help = 'Create model factories for all installed apps' def handle(self, *args, **options): created_files = [] for app in apps.get_app_configs(): factory_app_generator = FactoryAppGenerator(app) created_files += factory_app_generator.create_files() self.stdout.write(self.style.SUCCESS('Successfully created factories:')) for created_file in created_files: self.stdout.write(self.style.SUCCESS('- ' + created_file))
import os from django.apps import apps from django.core.management.base import BaseCommand from factory_generator.generator import FactoryAppGenerator class Command(BaseCommand): help = 'Create model factories for all installed apps' def handle(self, *args, **options): created_files = [] for app in apps.get_app_configs(): factory_app_generator = FactoryAppGenerator(app) created_files += factory_app_generator.create_files() self.stdout.write(self.style.SUCCESS('Successfully created factories:')) for created_file in created_files: self.stdout.write(self.style.SUCCESS('- ' + created_file))
none
1
2.165767
2
mro/stages/analyzer/run_differential_expression/__init__.py
qiangli/cellranger
1
89
<reponame>qiangli/cellranger<filename>mro/stages/analyzer/run_differential_expression/__init__.py #!/usr/bin/env python # # Copyright (c) 2017 10X Genomics, Inc. All rights reserved. # import cellranger.analysis.diffexp as cr_diffexp import cellranger.analysis.io as analysis_io from cellranger.analysis.singlegenome import SingleGenomeAnalysis import cellranger.h5_constants as h5_constants import cellranger.analysis.constants as analysis_constants import cellranger.matrix as cr_matrix import cellranger.io as cr_io import cellranger.library_constants as lib_constants NUM_THREADS_MIN = 4 #TODO Not clear why this stage takes > 1 thread. Martian thinks it does and kills it on long jobs __MRO__ = """ stage RUN_DIFFERENTIAL_EXPRESSION( in h5 matrix_h5, in h5 clustering_h5, in bool skip, in int random_seed, in int max_clusters, out h5 diffexp_h5, out path diffexp_csv, src py "stages/analyzer/run_differential_expression", ) split using ( in string clustering_key, ) """ def split(args): if args.skip: return {'chunks': [{'__mem_gb': h5_constants.MIN_MEM_GB}]} chunks = [] # FIXME: Add one for reasons unknown matrix_mem_gb = 1.8 * cr_matrix.CountMatrix.get_mem_gb_from_matrix_h5(args.matrix_h5) chunk_mem_gb = int(max(matrix_mem_gb, h5_constants.MIN_MEM_GB)) # HACK - give big jobs more threads in order to avoid overloading a node threads = min(cr_io.get_thread_request_from_mem_gb(chunk_mem_gb), NUM_THREADS_MIN) threads = 4 for key in SingleGenomeAnalysis.load_clustering_keys_from_h5(args.clustering_h5): chunks.append({ 'clustering_key': key, '__mem_gb': chunk_mem_gb, '__threads': threads, }) return {'chunks': chunks, 'join': {'__mem_gb' : 1}} def main(args, outs): if args.skip: return matrix = cr_matrix.CountMatrix.load_h5_file(args.matrix_h5) # For now, only compute for gene expression features matrix = matrix.select_features_by_type(lib_constants.GENE_EXPRESSION_LIBRARY_TYPE) clustering = SingleGenomeAnalysis.load_clustering_from_h5(args.clustering_h5, args.clustering_key) diffexp = cr_diffexp.run_differential_expression(matrix, clustering.clusters) with analysis_io.open_h5_for_writing(outs.diffexp_h5) as f: cr_diffexp.save_differential_expression_h5(f, args.clustering_key, diffexp) cr_diffexp.save_differential_expression_csv(args.clustering_key, diffexp, matrix, outs.diffexp_csv) def join(args, outs, chunk_defs, chunk_outs): if args.skip: return chunk_h5s = [chunk_out.diffexp_h5 for chunk_out in chunk_outs] chunk_csv_dirs = [chunk_out.diffexp_csv for chunk_out in chunk_outs] analysis_io.combine_h5_files(chunk_h5s, outs.diffexp_h5, [analysis_constants.ANALYSIS_H5_DIFFERENTIAL_EXPRESSION_GROUP, analysis_constants.ANALYSIS_H5_KMEANS_DIFFERENTIAL_EXPRESSION_GROUP]) for csv_dir in chunk_csv_dirs: cr_io.copytree(csv_dir, outs.diffexp_csv, allow_existing=True)
#!/usr/bin/env python # # Copyright (c) 2017 10X Genomics, Inc. All rights reserved. # import cellranger.analysis.diffexp as cr_diffexp import cellranger.analysis.io as analysis_io from cellranger.analysis.singlegenome import SingleGenomeAnalysis import cellranger.h5_constants as h5_constants import cellranger.analysis.constants as analysis_constants import cellranger.matrix as cr_matrix import cellranger.io as cr_io import cellranger.library_constants as lib_constants NUM_THREADS_MIN = 4 #TODO Not clear why this stage takes > 1 thread. Martian thinks it does and kills it on long jobs __MRO__ = """ stage RUN_DIFFERENTIAL_EXPRESSION( in h5 matrix_h5, in h5 clustering_h5, in bool skip, in int random_seed, in int max_clusters, out h5 diffexp_h5, out path diffexp_csv, src py "stages/analyzer/run_differential_expression", ) split using ( in string clustering_key, ) """ def split(args): if args.skip: return {'chunks': [{'__mem_gb': h5_constants.MIN_MEM_GB}]} chunks = [] # FIXME: Add one for reasons unknown matrix_mem_gb = 1.8 * cr_matrix.CountMatrix.get_mem_gb_from_matrix_h5(args.matrix_h5) chunk_mem_gb = int(max(matrix_mem_gb, h5_constants.MIN_MEM_GB)) # HACK - give big jobs more threads in order to avoid overloading a node threads = min(cr_io.get_thread_request_from_mem_gb(chunk_mem_gb), NUM_THREADS_MIN) threads = 4 for key in SingleGenomeAnalysis.load_clustering_keys_from_h5(args.clustering_h5): chunks.append({ 'clustering_key': key, '__mem_gb': chunk_mem_gb, '__threads': threads, }) return {'chunks': chunks, 'join': {'__mem_gb' : 1}} def main(args, outs): if args.skip: return matrix = cr_matrix.CountMatrix.load_h5_file(args.matrix_h5) # For now, only compute for gene expression features matrix = matrix.select_features_by_type(lib_constants.GENE_EXPRESSION_LIBRARY_TYPE) clustering = SingleGenomeAnalysis.load_clustering_from_h5(args.clustering_h5, args.clustering_key) diffexp = cr_diffexp.run_differential_expression(matrix, clustering.clusters) with analysis_io.open_h5_for_writing(outs.diffexp_h5) as f: cr_diffexp.save_differential_expression_h5(f, args.clustering_key, diffexp) cr_diffexp.save_differential_expression_csv(args.clustering_key, diffexp, matrix, outs.diffexp_csv) def join(args, outs, chunk_defs, chunk_outs): if args.skip: return chunk_h5s = [chunk_out.diffexp_h5 for chunk_out in chunk_outs] chunk_csv_dirs = [chunk_out.diffexp_csv for chunk_out in chunk_outs] analysis_io.combine_h5_files(chunk_h5s, outs.diffexp_h5, [analysis_constants.ANALYSIS_H5_DIFFERENTIAL_EXPRESSION_GROUP, analysis_constants.ANALYSIS_H5_KMEANS_DIFFERENTIAL_EXPRESSION_GROUP]) for csv_dir in chunk_csv_dirs: cr_io.copytree(csv_dir, outs.diffexp_csv, allow_existing=True)
en
0.780541
#!/usr/bin/env python # # Copyright (c) 2017 10X Genomics, Inc. All rights reserved. # #TODO Not clear why this stage takes > 1 thread. Martian thinks it does and kills it on long jobs stage RUN_DIFFERENTIAL_EXPRESSION( in h5 matrix_h5, in h5 clustering_h5, in bool skip, in int random_seed, in int max_clusters, out h5 diffexp_h5, out path diffexp_csv, src py "stages/analyzer/run_differential_expression", ) split using ( in string clustering_key, ) # FIXME: Add one for reasons unknown # HACK - give big jobs more threads in order to avoid overloading a node # For now, only compute for gene expression features
1.792563
2
sympy/combinatorics/testutil.py
ethankward/sympy
2
90
<reponame>ethankward/sympy<filename>sympy/combinatorics/testutil.py from sympy.combinatorics import Permutation from sympy.combinatorics.util import _distribute_gens_by_base rmul = Permutation.rmul def _cmp_perm_lists(first, second): """ Compare two lists of permutations as sets. This is used for testing purposes. Since the array form of a permutation is currently a list, Permutation is not hashable and cannot be put into a set. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.combinatorics.testutil import _cmp_perm_lists >>> a = Permutation([0, 2, 3, 4, 1]) >>> b = Permutation([1, 2, 0, 4, 3]) >>> c = Permutation([3, 4, 0, 1, 2]) >>> ls1 = [a, b, c] >>> ls2 = [b, c, a] >>> _cmp_perm_lists(ls1, ls2) True """ return {tuple(a) for a in first} == \ {tuple(a) for a in second} def _naive_list_centralizer(self, other, af=False): from sympy.combinatorics.perm_groups import PermutationGroup """ Return a list of elements for the centralizer of a subgroup/set/element. This is a brute force implementation that goes over all elements of the group and checks for membership in the centralizer. It is used to test ``.centralizer()`` from ``sympy.combinatorics.perm_groups``. Examples ======== >>> from sympy.combinatorics.testutil import _naive_list_centralizer >>> from sympy.combinatorics.named_groups import DihedralGroup >>> D = DihedralGroup(4) >>> _naive_list_centralizer(D, D) [Permutation([0, 1, 2, 3]), Permutation([2, 3, 0, 1])] See Also ======== sympy.combinatorics.perm_groups.centralizer """ from sympy.combinatorics.permutations import _af_commutes_with if hasattr(other, 'generators'): elements = list(self.generate_dimino(af=True)) gens = [x._array_form for x in other.generators] commutes_with_gens = lambda x: all(_af_commutes_with(x, gen) for gen in gens) centralizer_list = [] if not af: for element in elements: if commutes_with_gens(element): centralizer_list.append(Permutation._af_new(element)) else: for element in elements: if commutes_with_gens(element): centralizer_list.append(element) return centralizer_list elif hasattr(other, 'getitem'): return _naive_list_centralizer(self, PermutationGroup(other), af) elif hasattr(other, 'array_form'): return _naive_list_centralizer(self, PermutationGroup([other]), af) def _verify_bsgs(group, base, gens): """ Verify the correctness of a base and strong generating set. This is a naive implementation using the definition of a base and a strong generating set relative to it. There are other procedures for verifying a base and strong generating set, but this one will serve for more robust testing. Examples ======== >>> from sympy.combinatorics.named_groups import AlternatingGroup >>> from sympy.combinatorics.testutil import _verify_bsgs >>> A = AlternatingGroup(4) >>> A.schreier_sims() >>> _verify_bsgs(A, A.base, A.strong_gens) True See Also ======== sympy.combinatorics.perm_groups.PermutationGroup.schreier_sims """ from sympy.combinatorics.perm_groups import PermutationGroup strong_gens_distr = _distribute_gens_by_base(base, gens) current_stabilizer = group for i in range(len(base)): candidate = PermutationGroup(strong_gens_distr[i]) if current_stabilizer.order() != candidate.order(): return False current_stabilizer = current_stabilizer.stabilizer(base[i]) if current_stabilizer.order() != 1: return False return True def _verify_centralizer(group, arg, centr=None): """ Verify the centralizer of a group/set/element inside another group. This is used for testing ``.centralizer()`` from ``sympy.combinatorics.perm_groups`` Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... AlternatingGroup) >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.combinatorics.testutil import _verify_centralizer >>> S = SymmetricGroup(5) >>> A = AlternatingGroup(5) >>> centr = PermutationGroup([Permutation([0, 1, 2, 3, 4])]) >>> _verify_centralizer(S, A, centr) True See Also ======== _naive_list_centralizer, sympy.combinatorics.perm_groups.PermutationGroup.centralizer, _cmp_perm_lists """ if centr is None: centr = group.centralizer(arg) centr_list = list(centr.generate_dimino(af=True)) centr_list_naive = _naive_list_centralizer(group, arg, af=True) return _cmp_perm_lists(centr_list, centr_list_naive) def _verify_normal_closure(group, arg, closure=None): from sympy.combinatorics.perm_groups import PermutationGroup """ Verify the normal closure of a subgroup/subset/element in a group. This is used to test sympy.combinatorics.perm_groups.PermutationGroup.normal_closure Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... AlternatingGroup) >>> from sympy.combinatorics.testutil import _verify_normal_closure >>> S = SymmetricGroup(3) >>> A = AlternatingGroup(3) >>> _verify_normal_closure(S, A, closure=A) True See Also ======== sympy.combinatorics.perm_groups.PermutationGroup.normal_closure """ if closure is None: closure = group.normal_closure(arg) conjugates = set() if hasattr(arg, 'generators'): subgr_gens = arg.generators elif hasattr(arg, '__getitem__'): subgr_gens = arg elif hasattr(arg, 'array_form'): subgr_gens = [arg] for el in group.generate_dimino(): for gen in subgr_gens: conjugates.add(gen ^ el) naive_closure = PermutationGroup(list(conjugates)) return closure.is_subgroup(naive_closure) def canonicalize_naive(g, dummies, sym, *v): """ Canonicalize tensor formed by tensors of the different types g permutation representing the tensor dummies list of dummy indices msym symmetry of the metric v is a list of (base_i, gens_i, n_i, sym_i) for tensors of type `i` base_i, gens_i BSGS for tensors of this type n_i number ot tensors of type `i` sym_i symmetry under exchange of two component tensors of type `i` None no symmetry 0 commuting 1 anticommuting Return 0 if the tensor is zero, else return the array form of the permutation representing the canonical form of the tensor. Examples ======== >>> from sympy.combinatorics.testutil import canonicalize_naive >>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs >>> from sympy.combinatorics import Permutation, PermutationGroup >>> g = Permutation([1, 3, 2, 0, 4, 5]) >>> base2, gens2 = get_symmetric_group_sgs(2) >>> canonicalize_naive(g, [2, 3], 0, (base2, gens2, 2, 0)) [0, 2, 1, 3, 4, 5] """ from sympy.combinatorics.perm_groups import PermutationGroup from sympy.combinatorics.tensor_can import gens_products, dummy_sgs from sympy.combinatorics.permutations import Permutation, _af_rmul v1 = [] for i in range(len(v)): base_i, gens_i, n_i, sym_i = v[i] v1.append((base_i, gens_i, [[]]*n_i, sym_i)) size, sbase, sgens = gens_products(*v1) dgens = dummy_sgs(dummies, sym, size-2) if isinstance(sym, int): num_types = 1 dummies = [dummies] sym = [sym] else: num_types = len(sym) dgens = [] for i in range(num_types): dgens.extend(dummy_sgs(dummies[i], sym[i], size - 2)) S = PermutationGroup(sgens) D = PermutationGroup([Permutation(x) for x in dgens]) dlist = list(D.generate(af=True)) g = g.array_form st = set() for s in S.generate(af=True): h = _af_rmul(g, s) for d in dlist: q = tuple(_af_rmul(d, h)) st.add(q) a = list(st) a.sort() prev = (0,)*size for h in a: if h[:-2] == prev[:-2]: if h[-1] != prev[-1]: return 0 prev = h return list(a[0]) def graph_certificate(gr): """ Return a certificate for the graph gr adjacency list The graph is assumed to be unoriented and without external lines. Associate to each vertex of the graph a symmetric tensor with number of indices equal to the degree of the vertex; indices are contracted when they correspond to the same line of the graph. The canonical form of the tensor gives a certificate for the graph. This is not an efficient algorithm to get the certificate of a graph. Examples ======== >>> from sympy.combinatorics.testutil import graph_certificate >>> gr1 = {0:[1, 2, 3, 5], 1:[0, 2, 4], 2:[0, 1, 3, 4], 3:[0, 2, 4], 4:[1, 2, 3, 5], 5:[0, 4]} >>> gr2 = {0:[1, 5], 1:[0, 2, 3, 4], 2:[1, 3, 5], 3:[1, 2, 4, 5], 4:[1, 3, 5], 5:[0, 2, 3, 4]} >>> c1 = graph_certificate(gr1) >>> c2 = graph_certificate(gr2) >>> c1 [0, 2, 4, 6, 1, 8, 10, 12, 3, 14, 16, 18, 5, 9, 15, 7, 11, 17, 13, 19, 20, 21] >>> c1 == c2 True """ from sympy.combinatorics.permutations import _af_invert from sympy.combinatorics.tensor_can import get_symmetric_group_sgs, canonicalize items = list(gr.items()) items.sort(key=lambda x: len(x[1]), reverse=True) pvert = [x[0] for x in items] pvert = _af_invert(pvert) # the indices of the tensor are twice the number of lines of the graph num_indices = 0 for v, neigh in items: num_indices += len(neigh) # associate to each vertex its indices; for each line # between two vertices assign the # even index to the vertex which comes first in items, # the odd index to the other vertex vertices = [[] for i in items] i = 0 for v, neigh in items: for v2 in neigh: if pvert[v] < pvert[v2]: vertices[pvert[v]].append(i) vertices[pvert[v2]].append(i+1) i += 2 g = [] for v in vertices: g.extend(v) assert len(g) == num_indices g += [num_indices, num_indices + 1] size = num_indices + 2 assert sorted(g) == list(range(size)) g = Permutation(g) vlen = [0]*(len(vertices[0])+1) for neigh in vertices: vlen[len(neigh)] += 1 v = [] for i in range(len(vlen)): n = vlen[i] if n: base, gens = get_symmetric_group_sgs(i) v.append((base, gens, n, 0)) v.reverse() dummies = list(range(num_indices)) can = canonicalize(g, dummies, 0, *v) return can
from sympy.combinatorics import Permutation from sympy.combinatorics.util import _distribute_gens_by_base rmul = Permutation.rmul def _cmp_perm_lists(first, second): """ Compare two lists of permutations as sets. This is used for testing purposes. Since the array form of a permutation is currently a list, Permutation is not hashable and cannot be put into a set. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.combinatorics.testutil import _cmp_perm_lists >>> a = Permutation([0, 2, 3, 4, 1]) >>> b = Permutation([1, 2, 0, 4, 3]) >>> c = Permutation([3, 4, 0, 1, 2]) >>> ls1 = [a, b, c] >>> ls2 = [b, c, a] >>> _cmp_perm_lists(ls1, ls2) True """ return {tuple(a) for a in first} == \ {tuple(a) for a in second} def _naive_list_centralizer(self, other, af=False): from sympy.combinatorics.perm_groups import PermutationGroup """ Return a list of elements for the centralizer of a subgroup/set/element. This is a brute force implementation that goes over all elements of the group and checks for membership in the centralizer. It is used to test ``.centralizer()`` from ``sympy.combinatorics.perm_groups``. Examples ======== >>> from sympy.combinatorics.testutil import _naive_list_centralizer >>> from sympy.combinatorics.named_groups import DihedralGroup >>> D = DihedralGroup(4) >>> _naive_list_centralizer(D, D) [Permutation([0, 1, 2, 3]), Permutation([2, 3, 0, 1])] See Also ======== sympy.combinatorics.perm_groups.centralizer """ from sympy.combinatorics.permutations import _af_commutes_with if hasattr(other, 'generators'): elements = list(self.generate_dimino(af=True)) gens = [x._array_form for x in other.generators] commutes_with_gens = lambda x: all(_af_commutes_with(x, gen) for gen in gens) centralizer_list = [] if not af: for element in elements: if commutes_with_gens(element): centralizer_list.append(Permutation._af_new(element)) else: for element in elements: if commutes_with_gens(element): centralizer_list.append(element) return centralizer_list elif hasattr(other, 'getitem'): return _naive_list_centralizer(self, PermutationGroup(other), af) elif hasattr(other, 'array_form'): return _naive_list_centralizer(self, PermutationGroup([other]), af) def _verify_bsgs(group, base, gens): """ Verify the correctness of a base and strong generating set. This is a naive implementation using the definition of a base and a strong generating set relative to it. There are other procedures for verifying a base and strong generating set, but this one will serve for more robust testing. Examples ======== >>> from sympy.combinatorics.named_groups import AlternatingGroup >>> from sympy.combinatorics.testutil import _verify_bsgs >>> A = AlternatingGroup(4) >>> A.schreier_sims() >>> _verify_bsgs(A, A.base, A.strong_gens) True See Also ======== sympy.combinatorics.perm_groups.PermutationGroup.schreier_sims """ from sympy.combinatorics.perm_groups import PermutationGroup strong_gens_distr = _distribute_gens_by_base(base, gens) current_stabilizer = group for i in range(len(base)): candidate = PermutationGroup(strong_gens_distr[i]) if current_stabilizer.order() != candidate.order(): return False current_stabilizer = current_stabilizer.stabilizer(base[i]) if current_stabilizer.order() != 1: return False return True def _verify_centralizer(group, arg, centr=None): """ Verify the centralizer of a group/set/element inside another group. This is used for testing ``.centralizer()`` from ``sympy.combinatorics.perm_groups`` Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... AlternatingGroup) >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.combinatorics.testutil import _verify_centralizer >>> S = SymmetricGroup(5) >>> A = AlternatingGroup(5) >>> centr = PermutationGroup([Permutation([0, 1, 2, 3, 4])]) >>> _verify_centralizer(S, A, centr) True See Also ======== _naive_list_centralizer, sympy.combinatorics.perm_groups.PermutationGroup.centralizer, _cmp_perm_lists """ if centr is None: centr = group.centralizer(arg) centr_list = list(centr.generate_dimino(af=True)) centr_list_naive = _naive_list_centralizer(group, arg, af=True) return _cmp_perm_lists(centr_list, centr_list_naive) def _verify_normal_closure(group, arg, closure=None): from sympy.combinatorics.perm_groups import PermutationGroup """ Verify the normal closure of a subgroup/subset/element in a group. This is used to test sympy.combinatorics.perm_groups.PermutationGroup.normal_closure Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... AlternatingGroup) >>> from sympy.combinatorics.testutil import _verify_normal_closure >>> S = SymmetricGroup(3) >>> A = AlternatingGroup(3) >>> _verify_normal_closure(S, A, closure=A) True See Also ======== sympy.combinatorics.perm_groups.PermutationGroup.normal_closure """ if closure is None: closure = group.normal_closure(arg) conjugates = set() if hasattr(arg, 'generators'): subgr_gens = arg.generators elif hasattr(arg, '__getitem__'): subgr_gens = arg elif hasattr(arg, 'array_form'): subgr_gens = [arg] for el in group.generate_dimino(): for gen in subgr_gens: conjugates.add(gen ^ el) naive_closure = PermutationGroup(list(conjugates)) return closure.is_subgroup(naive_closure) def canonicalize_naive(g, dummies, sym, *v): """ Canonicalize tensor formed by tensors of the different types g permutation representing the tensor dummies list of dummy indices msym symmetry of the metric v is a list of (base_i, gens_i, n_i, sym_i) for tensors of type `i` base_i, gens_i BSGS for tensors of this type n_i number ot tensors of type `i` sym_i symmetry under exchange of two component tensors of type `i` None no symmetry 0 commuting 1 anticommuting Return 0 if the tensor is zero, else return the array form of the permutation representing the canonical form of the tensor. Examples ======== >>> from sympy.combinatorics.testutil import canonicalize_naive >>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs >>> from sympy.combinatorics import Permutation, PermutationGroup >>> g = Permutation([1, 3, 2, 0, 4, 5]) >>> base2, gens2 = get_symmetric_group_sgs(2) >>> canonicalize_naive(g, [2, 3], 0, (base2, gens2, 2, 0)) [0, 2, 1, 3, 4, 5] """ from sympy.combinatorics.perm_groups import PermutationGroup from sympy.combinatorics.tensor_can import gens_products, dummy_sgs from sympy.combinatorics.permutations import Permutation, _af_rmul v1 = [] for i in range(len(v)): base_i, gens_i, n_i, sym_i = v[i] v1.append((base_i, gens_i, [[]]*n_i, sym_i)) size, sbase, sgens = gens_products(*v1) dgens = dummy_sgs(dummies, sym, size-2) if isinstance(sym, int): num_types = 1 dummies = [dummies] sym = [sym] else: num_types = len(sym) dgens = [] for i in range(num_types): dgens.extend(dummy_sgs(dummies[i], sym[i], size - 2)) S = PermutationGroup(sgens) D = PermutationGroup([Permutation(x) for x in dgens]) dlist = list(D.generate(af=True)) g = g.array_form st = set() for s in S.generate(af=True): h = _af_rmul(g, s) for d in dlist: q = tuple(_af_rmul(d, h)) st.add(q) a = list(st) a.sort() prev = (0,)*size for h in a: if h[:-2] == prev[:-2]: if h[-1] != prev[-1]: return 0 prev = h return list(a[0]) def graph_certificate(gr): """ Return a certificate for the graph gr adjacency list The graph is assumed to be unoriented and without external lines. Associate to each vertex of the graph a symmetric tensor with number of indices equal to the degree of the vertex; indices are contracted when they correspond to the same line of the graph. The canonical form of the tensor gives a certificate for the graph. This is not an efficient algorithm to get the certificate of a graph. Examples ======== >>> from sympy.combinatorics.testutil import graph_certificate >>> gr1 = {0:[1, 2, 3, 5], 1:[0, 2, 4], 2:[0, 1, 3, 4], 3:[0, 2, 4], 4:[1, 2, 3, 5], 5:[0, 4]} >>> gr2 = {0:[1, 5], 1:[0, 2, 3, 4], 2:[1, 3, 5], 3:[1, 2, 4, 5], 4:[1, 3, 5], 5:[0, 2, 3, 4]} >>> c1 = graph_certificate(gr1) >>> c2 = graph_certificate(gr2) >>> c1 [0, 2, 4, 6, 1, 8, 10, 12, 3, 14, 16, 18, 5, 9, 15, 7, 11, 17, 13, 19, 20, 21] >>> c1 == c2 True """ from sympy.combinatorics.permutations import _af_invert from sympy.combinatorics.tensor_can import get_symmetric_group_sgs, canonicalize items = list(gr.items()) items.sort(key=lambda x: len(x[1]), reverse=True) pvert = [x[0] for x in items] pvert = _af_invert(pvert) # the indices of the tensor are twice the number of lines of the graph num_indices = 0 for v, neigh in items: num_indices += len(neigh) # associate to each vertex its indices; for each line # between two vertices assign the # even index to the vertex which comes first in items, # the odd index to the other vertex vertices = [[] for i in items] i = 0 for v, neigh in items: for v2 in neigh: if pvert[v] < pvert[v2]: vertices[pvert[v]].append(i) vertices[pvert[v2]].append(i+1) i += 2 g = [] for v in vertices: g.extend(v) assert len(g) == num_indices g += [num_indices, num_indices + 1] size = num_indices + 2 assert sorted(g) == list(range(size)) g = Permutation(g) vlen = [0]*(len(vertices[0])+1) for neigh in vertices: vlen[len(neigh)] += 1 v = [] for i in range(len(vlen)): n = vlen[i] if n: base, gens = get_symmetric_group_sgs(i) v.append((base, gens, n, 0)) v.reverse() dummies = list(range(num_indices)) can = canonicalize(g, dummies, 0, *v) return can
en
0.693706
Compare two lists of permutations as sets. This is used for testing purposes. Since the array form of a permutation is currently a list, Permutation is not hashable and cannot be put into a set. Examples ======== >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.combinatorics.testutil import _cmp_perm_lists >>> a = Permutation([0, 2, 3, 4, 1]) >>> b = Permutation([1, 2, 0, 4, 3]) >>> c = Permutation([3, 4, 0, 1, 2]) >>> ls1 = [a, b, c] >>> ls2 = [b, c, a] >>> _cmp_perm_lists(ls1, ls2) True Return a list of elements for the centralizer of a subgroup/set/element. This is a brute force implementation that goes over all elements of the group and checks for membership in the centralizer. It is used to test ``.centralizer()`` from ``sympy.combinatorics.perm_groups``. Examples ======== >>> from sympy.combinatorics.testutil import _naive_list_centralizer >>> from sympy.combinatorics.named_groups import DihedralGroup >>> D = DihedralGroup(4) >>> _naive_list_centralizer(D, D) [Permutation([0, 1, 2, 3]), Permutation([2, 3, 0, 1])] See Also ======== sympy.combinatorics.perm_groups.centralizer Verify the correctness of a base and strong generating set. This is a naive implementation using the definition of a base and a strong generating set relative to it. There are other procedures for verifying a base and strong generating set, but this one will serve for more robust testing. Examples ======== >>> from sympy.combinatorics.named_groups import AlternatingGroup >>> from sympy.combinatorics.testutil import _verify_bsgs >>> A = AlternatingGroup(4) >>> A.schreier_sims() >>> _verify_bsgs(A, A.base, A.strong_gens) True See Also ======== sympy.combinatorics.perm_groups.PermutationGroup.schreier_sims Verify the centralizer of a group/set/element inside another group. This is used for testing ``.centralizer()`` from ``sympy.combinatorics.perm_groups`` Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... AlternatingGroup) >>> from sympy.combinatorics.perm_groups import PermutationGroup >>> from sympy.combinatorics.permutations import Permutation >>> from sympy.combinatorics.testutil import _verify_centralizer >>> S = SymmetricGroup(5) >>> A = AlternatingGroup(5) >>> centr = PermutationGroup([Permutation([0, 1, 2, 3, 4])]) >>> _verify_centralizer(S, A, centr) True See Also ======== _naive_list_centralizer, sympy.combinatorics.perm_groups.PermutationGroup.centralizer, _cmp_perm_lists Verify the normal closure of a subgroup/subset/element in a group. This is used to test sympy.combinatorics.perm_groups.PermutationGroup.normal_closure Examples ======== >>> from sympy.combinatorics.named_groups import (SymmetricGroup, ... AlternatingGroup) >>> from sympy.combinatorics.testutil import _verify_normal_closure >>> S = SymmetricGroup(3) >>> A = AlternatingGroup(3) >>> _verify_normal_closure(S, A, closure=A) True See Also ======== sympy.combinatorics.perm_groups.PermutationGroup.normal_closure Canonicalize tensor formed by tensors of the different types g permutation representing the tensor dummies list of dummy indices msym symmetry of the metric v is a list of (base_i, gens_i, n_i, sym_i) for tensors of type `i` base_i, gens_i BSGS for tensors of this type n_i number ot tensors of type `i` sym_i symmetry under exchange of two component tensors of type `i` None no symmetry 0 commuting 1 anticommuting Return 0 if the tensor is zero, else return the array form of the permutation representing the canonical form of the tensor. Examples ======== >>> from sympy.combinatorics.testutil import canonicalize_naive >>> from sympy.combinatorics.tensor_can import get_symmetric_group_sgs >>> from sympy.combinatorics import Permutation, PermutationGroup >>> g = Permutation([1, 3, 2, 0, 4, 5]) >>> base2, gens2 = get_symmetric_group_sgs(2) >>> canonicalize_naive(g, [2, 3], 0, (base2, gens2, 2, 0)) [0, 2, 1, 3, 4, 5] Return a certificate for the graph gr adjacency list The graph is assumed to be unoriented and without external lines. Associate to each vertex of the graph a symmetric tensor with number of indices equal to the degree of the vertex; indices are contracted when they correspond to the same line of the graph. The canonical form of the tensor gives a certificate for the graph. This is not an efficient algorithm to get the certificate of a graph. Examples ======== >>> from sympy.combinatorics.testutil import graph_certificate >>> gr1 = {0:[1, 2, 3, 5], 1:[0, 2, 4], 2:[0, 1, 3, 4], 3:[0, 2, 4], 4:[1, 2, 3, 5], 5:[0, 4]} >>> gr2 = {0:[1, 5], 1:[0, 2, 3, 4], 2:[1, 3, 5], 3:[1, 2, 4, 5], 4:[1, 3, 5], 5:[0, 2, 3, 4]} >>> c1 = graph_certificate(gr1) >>> c2 = graph_certificate(gr2) >>> c1 [0, 2, 4, 6, 1, 8, 10, 12, 3, 14, 16, 18, 5, 9, 15, 7, 11, 17, 13, 19, 20, 21] >>> c1 == c2 True # the indices of the tensor are twice the number of lines of the graph # associate to each vertex its indices; for each line # between two vertices assign the # even index to the vertex which comes first in items, # the odd index to the other vertex
3.853454
4
src/vatic_checker/config.py
jonkeane/vatic-checker
0
91
localhost = "http://localhost/" # your local host database = "mysql://root@localhost/vaticChecker" # server://user:pass@localhost/dbname min_training = 2 # the minimum number of training videos to be considered recaptcha_secret = "" # recaptcha secret for verification duplicate_annotations = False # Should the server allow for duplicate annotations? import os.path import sys sys.path.append(os.path.dirname(os.path.abspath(__file__))) # TODO: remove on server import os os.environ['PYTHON_EGG_CACHE'] = '/tmp/apache'
localhost = "http://localhost/" # your local host database = "mysql://root@localhost/vaticChecker" # server://user:pass@localhost/dbname min_training = 2 # the minimum number of training videos to be considered recaptcha_secret = "" # recaptcha secret for verification duplicate_annotations = False # Should the server allow for duplicate annotations? import os.path import sys sys.path.append(os.path.dirname(os.path.abspath(__file__))) # TODO: remove on server import os os.environ['PYTHON_EGG_CACHE'] = '/tmp/apache'
en
0.734703
# your local host # server://user:pass@localhost/dbname # the minimum number of training videos to be considered # recaptcha secret for verification # Should the server allow for duplicate annotations? # TODO: remove on server
1.890271
2
django/utils/timezone.py
graingert/django
1
92
"""Timezone helper functions. This module uses pytz when it's available and fallbacks when it isn't. """ from datetime import datetime, timedelta, tzinfo from threading import local import time as _time try: import pytz except ImportError: pytz = None from django.conf import settings __all__ = [ 'utc', 'get_default_timezone', 'get_current_timezone', 'activate', 'deactivate', 'override', 'is_naive', 'is_aware', 'make_aware', 'make_naive', ] # UTC and local time zones ZERO = timedelta(0) class UTC(tzinfo): """ UTC implementation taken from Python's docs. Used only when pytz isn't available. """ def __repr__(self): return "<UTC>" def utcoffset(self, dt): return ZERO def tzname(self, dt): return "UTC" def dst(self, dt): return ZERO class LocalTimezone(tzinfo): """ Local time implementation taken from Python's docs. Used only when pytz isn't available, and most likely inaccurate. If you're having trouble with this class, don't waste your time, just install pytz. """ def __init__(self): # This code is moved in __init__ to execute it as late as possible # See get_default_timezone(). self.STDOFFSET = timedelta(seconds=-_time.timezone) if _time.daylight: self.DSTOFFSET = timedelta(seconds=-_time.altzone) else: self.DSTOFFSET = self.STDOFFSET self.DSTDIFF = self.DSTOFFSET - self.STDOFFSET tzinfo.__init__(self) def __repr__(self): return "<LocalTimezone>" def utcoffset(self, dt): if self._isdst(dt): return self.DSTOFFSET else: return self.STDOFFSET def dst(self, dt): if self._isdst(dt): return self.DSTDIFF else: return ZERO def tzname(self, dt): return _time.tzname[self._isdst(dt)] def _isdst(self, dt): tt = (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.weekday(), 0, 0) stamp = _time.mktime(tt) tt = _time.localtime(stamp) return tt.tm_isdst > 0 utc = pytz.utc if pytz else UTC() """UTC time zone as a tzinfo instance.""" # In order to avoid accessing the settings at compile time, # wrap the expression in a function and cache the result. _localtime = None def get_default_timezone(): """ Returns the default time zone as a tzinfo instance. This is the time zone defined by settings.TIME_ZONE. See also :func:`get_current_timezone`. """ global _localtime if _localtime is None: if isinstance(settings.TIME_ZONE, basestring) and pytz is not None: _localtime = pytz.timezone(settings.TIME_ZONE) else: _localtime = LocalTimezone() return _localtime # This function exists for consistency with get_current_timezone_name def get_default_timezone_name(): """ Returns the name of the default time zone. """ return _get_timezone_name(get_default_timezone()) _active = local() def get_current_timezone(): """ Returns the currently active time zone as a tzinfo instance. """ return getattr(_active, "value", get_default_timezone()) def get_current_timezone_name(): """ Returns the name of the currently active time zone. """ return _get_timezone_name(get_current_timezone()) def _get_timezone_name(timezone): """ Returns the name of ``timezone``. """ try: # for pytz timezones return timezone.zone except AttributeError: # for regular tzinfo objects local_now = datetime.now(timezone) return timezone.tzname(local_now) # Timezone selection functions. # These functions don't change os.environ['TZ'] and call time.tzset() # because it isn't thread safe. def activate(timezone): """ Sets the time zone for the current thread. The ``timezone`` argument must be an instance of a tzinfo subclass or a time zone name. If it is a time zone name, pytz is required. """ if isinstance(timezone, tzinfo): _active.value = timezone elif isinstance(timezone, basestring) and pytz is not None: _active.value = pytz.timezone(timezone) else: raise ValueError("Invalid timezone: %r" % timezone) def deactivate(): """ Unsets the time zone for the current thread. Django will then use the time zone defined by settings.TIME_ZONE. """ if hasattr(_active, "value"): del _active.value class override(object): """ Temporarily set the time zone for the current thread. This is a context manager that uses ``~django.utils.timezone.activate()`` to set the timezone on entry, and restores the previously active timezone on exit. The ``timezone`` argument must be an instance of a ``tzinfo`` subclass, a time zone name, or ``None``. If is it a time zone name, pytz is required. If it is ``None``, Django enables the default time zone. """ def __init__(self, timezone): self.timezone = timezone self.old_timezone = getattr(_active, 'value', None) def __enter__(self): if self.timezone is None: deactivate() else: activate(self.timezone) def __exit__(self, exc_type, exc_value, traceback): if self.old_timezone is not None: _active.value = self.old_timezone else: del _active.value # Templates def template_localtime(value, use_tz=None): """ Checks if value is a datetime and converts it to local time if necessary. If use_tz is provided and is not None, that will force the value to be converted (or not), overriding the value of settings.USE_TZ. This function is designed for use by the template engine. """ should_convert = (isinstance(value, datetime) and (settings.USE_TZ if use_tz is None else use_tz) and not is_naive(value) and getattr(value, 'convert_to_local_time', True)) return localtime(value) if should_convert else value # Utilities def localtime(value, timezone=None): """ Converts an aware datetime.datetime to local time. Local time is defined by the current time zone, unless another time zone is specified. """ if timezone is None: timezone = get_current_timezone() value = value.astimezone(timezone) if hasattr(timezone, 'normalize'): # available for pytz time zones value = timezone.normalize(value) return value def now(): """ Returns an aware or naive datetime.datetime, depending on settings.USE_TZ. """ if settings.USE_TZ: # timeit shows that datetime.now(tz=utc) is 24% slower return datetime.utcnow().replace(tzinfo=utc) else: return datetime.now() # By design, these four functions don't perform any checks on their arguments. # The caller should ensure that they don't receive an invalid value like None. def is_aware(value): """ Determines if a given datetime.datetime is aware. The logic is described in Python's docs: http://docs.python.org/library/datetime.html#datetime.tzinfo """ return value.tzinfo is not None and value.tzinfo.utcoffset(value) is not None def is_naive(value): """ Determines if a given datetime.datetime is naive. The logic is described in Python's docs: http://docs.python.org/library/datetime.html#datetime.tzinfo """ return value.tzinfo is None or value.tzinfo.utcoffset(value) is None def make_aware(value, timezone): """ Makes a naive datetime.datetime in a given time zone aware. """ if hasattr(timezone, 'localize'): # available for pytz time zones return timezone.localize(value, is_dst=None) else: # may be wrong around DST changes return value.replace(tzinfo=timezone) def make_naive(value, timezone): """ Makes an aware datetime.datetime naive in a given time zone. """ value = value.astimezone(timezone) if hasattr(timezone, 'normalize'): # available for pytz time zones value = timezone.normalize(value) return value.replace(tzinfo=None)
"""Timezone helper functions. This module uses pytz when it's available and fallbacks when it isn't. """ from datetime import datetime, timedelta, tzinfo from threading import local import time as _time try: import pytz except ImportError: pytz = None from django.conf import settings __all__ = [ 'utc', 'get_default_timezone', 'get_current_timezone', 'activate', 'deactivate', 'override', 'is_naive', 'is_aware', 'make_aware', 'make_naive', ] # UTC and local time zones ZERO = timedelta(0) class UTC(tzinfo): """ UTC implementation taken from Python's docs. Used only when pytz isn't available. """ def __repr__(self): return "<UTC>" def utcoffset(self, dt): return ZERO def tzname(self, dt): return "UTC" def dst(self, dt): return ZERO class LocalTimezone(tzinfo): """ Local time implementation taken from Python's docs. Used only when pytz isn't available, and most likely inaccurate. If you're having trouble with this class, don't waste your time, just install pytz. """ def __init__(self): # This code is moved in __init__ to execute it as late as possible # See get_default_timezone(). self.STDOFFSET = timedelta(seconds=-_time.timezone) if _time.daylight: self.DSTOFFSET = timedelta(seconds=-_time.altzone) else: self.DSTOFFSET = self.STDOFFSET self.DSTDIFF = self.DSTOFFSET - self.STDOFFSET tzinfo.__init__(self) def __repr__(self): return "<LocalTimezone>" def utcoffset(self, dt): if self._isdst(dt): return self.DSTOFFSET else: return self.STDOFFSET def dst(self, dt): if self._isdst(dt): return self.DSTDIFF else: return ZERO def tzname(self, dt): return _time.tzname[self._isdst(dt)] def _isdst(self, dt): tt = (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.weekday(), 0, 0) stamp = _time.mktime(tt) tt = _time.localtime(stamp) return tt.tm_isdst > 0 utc = pytz.utc if pytz else UTC() """UTC time zone as a tzinfo instance.""" # In order to avoid accessing the settings at compile time, # wrap the expression in a function and cache the result. _localtime = None def get_default_timezone(): """ Returns the default time zone as a tzinfo instance. This is the time zone defined by settings.TIME_ZONE. See also :func:`get_current_timezone`. """ global _localtime if _localtime is None: if isinstance(settings.TIME_ZONE, basestring) and pytz is not None: _localtime = pytz.timezone(settings.TIME_ZONE) else: _localtime = LocalTimezone() return _localtime # This function exists for consistency with get_current_timezone_name def get_default_timezone_name(): """ Returns the name of the default time zone. """ return _get_timezone_name(get_default_timezone()) _active = local() def get_current_timezone(): """ Returns the currently active time zone as a tzinfo instance. """ return getattr(_active, "value", get_default_timezone()) def get_current_timezone_name(): """ Returns the name of the currently active time zone. """ return _get_timezone_name(get_current_timezone()) def _get_timezone_name(timezone): """ Returns the name of ``timezone``. """ try: # for pytz timezones return timezone.zone except AttributeError: # for regular tzinfo objects local_now = datetime.now(timezone) return timezone.tzname(local_now) # Timezone selection functions. # These functions don't change os.environ['TZ'] and call time.tzset() # because it isn't thread safe. def activate(timezone): """ Sets the time zone for the current thread. The ``timezone`` argument must be an instance of a tzinfo subclass or a time zone name. If it is a time zone name, pytz is required. """ if isinstance(timezone, tzinfo): _active.value = timezone elif isinstance(timezone, basestring) and pytz is not None: _active.value = pytz.timezone(timezone) else: raise ValueError("Invalid timezone: %r" % timezone) def deactivate(): """ Unsets the time zone for the current thread. Django will then use the time zone defined by settings.TIME_ZONE. """ if hasattr(_active, "value"): del _active.value class override(object): """ Temporarily set the time zone for the current thread. This is a context manager that uses ``~django.utils.timezone.activate()`` to set the timezone on entry, and restores the previously active timezone on exit. The ``timezone`` argument must be an instance of a ``tzinfo`` subclass, a time zone name, or ``None``. If is it a time zone name, pytz is required. If it is ``None``, Django enables the default time zone. """ def __init__(self, timezone): self.timezone = timezone self.old_timezone = getattr(_active, 'value', None) def __enter__(self): if self.timezone is None: deactivate() else: activate(self.timezone) def __exit__(self, exc_type, exc_value, traceback): if self.old_timezone is not None: _active.value = self.old_timezone else: del _active.value # Templates def template_localtime(value, use_tz=None): """ Checks if value is a datetime and converts it to local time if necessary. If use_tz is provided and is not None, that will force the value to be converted (or not), overriding the value of settings.USE_TZ. This function is designed for use by the template engine. """ should_convert = (isinstance(value, datetime) and (settings.USE_TZ if use_tz is None else use_tz) and not is_naive(value) and getattr(value, 'convert_to_local_time', True)) return localtime(value) if should_convert else value # Utilities def localtime(value, timezone=None): """ Converts an aware datetime.datetime to local time. Local time is defined by the current time zone, unless another time zone is specified. """ if timezone is None: timezone = get_current_timezone() value = value.astimezone(timezone) if hasattr(timezone, 'normalize'): # available for pytz time zones value = timezone.normalize(value) return value def now(): """ Returns an aware or naive datetime.datetime, depending on settings.USE_TZ. """ if settings.USE_TZ: # timeit shows that datetime.now(tz=utc) is 24% slower return datetime.utcnow().replace(tzinfo=utc) else: return datetime.now() # By design, these four functions don't perform any checks on their arguments. # The caller should ensure that they don't receive an invalid value like None. def is_aware(value): """ Determines if a given datetime.datetime is aware. The logic is described in Python's docs: http://docs.python.org/library/datetime.html#datetime.tzinfo """ return value.tzinfo is not None and value.tzinfo.utcoffset(value) is not None def is_naive(value): """ Determines if a given datetime.datetime is naive. The logic is described in Python's docs: http://docs.python.org/library/datetime.html#datetime.tzinfo """ return value.tzinfo is None or value.tzinfo.utcoffset(value) is None def make_aware(value, timezone): """ Makes a naive datetime.datetime in a given time zone aware. """ if hasattr(timezone, 'localize'): # available for pytz time zones return timezone.localize(value, is_dst=None) else: # may be wrong around DST changes return value.replace(tzinfo=timezone) def make_naive(value, timezone): """ Makes an aware datetime.datetime naive in a given time zone. """ value = value.astimezone(timezone) if hasattr(timezone, 'normalize'): # available for pytz time zones value = timezone.normalize(value) return value.replace(tzinfo=None)
en
0.800747
Timezone helper functions. This module uses pytz when it's available and fallbacks when it isn't. # UTC and local time zones UTC implementation taken from Python's docs. Used only when pytz isn't available. Local time implementation taken from Python's docs. Used only when pytz isn't available, and most likely inaccurate. If you're having trouble with this class, don't waste your time, just install pytz. # This code is moved in __init__ to execute it as late as possible # See get_default_timezone(). UTC time zone as a tzinfo instance. # In order to avoid accessing the settings at compile time, # wrap the expression in a function and cache the result. Returns the default time zone as a tzinfo instance. This is the time zone defined by settings.TIME_ZONE. See also :func:`get_current_timezone`. # This function exists for consistency with get_current_timezone_name Returns the name of the default time zone. Returns the currently active time zone as a tzinfo instance. Returns the name of the currently active time zone. Returns the name of ``timezone``. # for pytz timezones # for regular tzinfo objects # Timezone selection functions. # These functions don't change os.environ['TZ'] and call time.tzset() # because it isn't thread safe. Sets the time zone for the current thread. The ``timezone`` argument must be an instance of a tzinfo subclass or a time zone name. If it is a time zone name, pytz is required. Unsets the time zone for the current thread. Django will then use the time zone defined by settings.TIME_ZONE. Temporarily set the time zone for the current thread. This is a context manager that uses ``~django.utils.timezone.activate()`` to set the timezone on entry, and restores the previously active timezone on exit. The ``timezone`` argument must be an instance of a ``tzinfo`` subclass, a time zone name, or ``None``. If is it a time zone name, pytz is required. If it is ``None``, Django enables the default time zone. # Templates Checks if value is a datetime and converts it to local time if necessary. If use_tz is provided and is not None, that will force the value to be converted (or not), overriding the value of settings.USE_TZ. This function is designed for use by the template engine. # Utilities Converts an aware datetime.datetime to local time. Local time is defined by the current time zone, unless another time zone is specified. # available for pytz time zones Returns an aware or naive datetime.datetime, depending on settings.USE_TZ. # timeit shows that datetime.now(tz=utc) is 24% slower # By design, these four functions don't perform any checks on their arguments. # The caller should ensure that they don't receive an invalid value like None. Determines if a given datetime.datetime is aware. The logic is described in Python's docs: http://docs.python.org/library/datetime.html#datetime.tzinfo Determines if a given datetime.datetime is naive. The logic is described in Python's docs: http://docs.python.org/library/datetime.html#datetime.tzinfo Makes a naive datetime.datetime in a given time zone aware. # available for pytz time zones # may be wrong around DST changes Makes an aware datetime.datetime naive in a given time zone. # available for pytz time zones
3.061816
3
malleefowl/tests/test_wps_caps.py
Ouranosinc/malleefowl
0
93
<gh_stars>0 import pytest from pywps import Service from pywps.tests import assert_response_success from .common import client_for from malleefowl.processes import processes def test_wps_caps(): client = client_for(Service(processes=processes)) resp = client.get(service='wps', request='getcapabilities', version='1.0.0') names = resp.xpath_text('/wps:Capabilities' '/wps:ProcessOfferings' '/wps:Process' '/ows:Identifier') assert sorted(names.split()) == [ 'download', 'esgsearch', 'thredds_download', 'workflow' ]
import pytest from pywps import Service from pywps.tests import assert_response_success from .common import client_for from malleefowl.processes import processes def test_wps_caps(): client = client_for(Service(processes=processes)) resp = client.get(service='wps', request='getcapabilities', version='1.0.0') names = resp.xpath_text('/wps:Capabilities' '/wps:ProcessOfferings' '/wps:Process' '/ows:Identifier') assert sorted(names.split()) == [ 'download', 'esgsearch', 'thredds_download', 'workflow' ]
none
1
2.28341
2
setup.py
CallumJHays/pyngrok
0
94
<filename>setup.py from setuptools import setup __author__ = "<NAME>" __copyright__ = "Copyright 2019, <NAME>" __version__ = "1.4.0" with open("README.md", "r") as f: long_description = f.read() setup( name="pyngrok", version=__version__, packages=["pyngrok"], python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*", install_requires=[ "future", "pyyaml" ], entry_points=""" [console_scripts] ngrok=pyngrok.ngrok:run """, description="A Python wrapper for Ngrok.", long_description=long_description, long_description_content_type="text/markdown", author="<NAME>", author_email="<EMAIL>", url="https://github.com/alexdlaird/pyngrok", download_url="https://github.com/alexdlaird/pyngrok/archive/{}.tar.gz".format(__version__), keywords=["ngrok", "tunnel", "tunneling", "webhook", "localhost"], license="MIT", classifiers=[ "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Software Development :: Libraries :: Python Modules", "Environment :: Console", "Environment :: Web Environment", "Intended Audience :: Developers", "Intended Audience :: Education", "Development Status :: 5 - Production/Stable", "License :: OSI Approved :: MIT License", "Operating System :: MacOS", "Operating System :: Microsoft :: Windows", "Operating System :: POSIX", "Operating System :: Unix" ] )
<filename>setup.py from setuptools import setup __author__ = "<NAME>" __copyright__ = "Copyright 2019, <NAME>" __version__ = "1.4.0" with open("README.md", "r") as f: long_description = f.read() setup( name="pyngrok", version=__version__, packages=["pyngrok"], python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*", install_requires=[ "future", "pyyaml" ], entry_points=""" [console_scripts] ngrok=pyngrok.ngrok:run """, description="A Python wrapper for Ngrok.", long_description=long_description, long_description_content_type="text/markdown", author="<NAME>", author_email="<EMAIL>", url="https://github.com/alexdlaird/pyngrok", download_url="https://github.com/alexdlaird/pyngrok/archive/{}.tar.gz".format(__version__), keywords=["ngrok", "tunnel", "tunneling", "webhook", "localhost"], license="MIT", classifiers=[ "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Software Development :: Libraries :: Python Modules", "Environment :: Console", "Environment :: Web Environment", "Intended Audience :: Developers", "Intended Audience :: Education", "Development Status :: 5 - Production/Stable", "License :: OSI Approved :: MIT License", "Operating System :: MacOS", "Operating System :: Microsoft :: Windows", "Operating System :: POSIX", "Operating System :: Unix" ] )
pl
0.253002
[console_scripts] ngrok=pyngrok.ngrok:run
1.575727
2
pipelines/trackml.py
texasmichelle/kubeflow-cern
4
95
#!/usr/bin/env python3 import kfp.dsl as dsl import kfp.gcp as gcp # Pipeline input variables. KUBECTL_IMAGE = "gcr.io/mcas-195423/trackml_master_kfp_kubectl" KUBECTL_IMAGE_VERSION = "1" TRACKML_IMAGE = "gcr.io/mcas-195423/trackml_master_trackml" TRACKML_IMAGE_VERSION = "1" def train_op(): return dsl.ContainerOp( name='train', image="{}:{}".format(TRACKML_IMAGE, TRACKML_IMAGE_VERSION), command=["python"], arguments=["train.py"], ).apply(gcp.use_gcp_secret() )#.set_gpu_limit(1) def serve_op(): return dsl.ContainerOp( name='serve', image="{}:{}".format(KUBECTL_IMAGE, KUBECTL_IMAGE_VERSION), arguments=[ "/src/set_kubectl.sh", "--namespace", "kubeflow", "--command", "apply -f /src/k8s/serve.yaml", ] ).apply(gcp.use_gcp_secret()) def resultsgen_op(): return dsl.ContainerOp( name='resultsgen', image="{}:{}".format(TRACKML_IMAGE, TRACKML_IMAGE_VERSION), command=["python"], arguments=["resultsgen.py"], ).apply(gcp.use_gcp_secret()) @dsl.pipeline( name='trackml', description='A pipeline that predicts particle tracks' ) def trackml(): train = train_op() serve = serve_op() serve.after(train) resultsgen = resultsgen_op() resultsgen.after(serve) if __name__ == '__main__': import kfp.compiler as compiler compiler.Compiler().compile(trackml, __file__ + '.tar.gz')
#!/usr/bin/env python3 import kfp.dsl as dsl import kfp.gcp as gcp # Pipeline input variables. KUBECTL_IMAGE = "gcr.io/mcas-195423/trackml_master_kfp_kubectl" KUBECTL_IMAGE_VERSION = "1" TRACKML_IMAGE = "gcr.io/mcas-195423/trackml_master_trackml" TRACKML_IMAGE_VERSION = "1" def train_op(): return dsl.ContainerOp( name='train', image="{}:{}".format(TRACKML_IMAGE, TRACKML_IMAGE_VERSION), command=["python"], arguments=["train.py"], ).apply(gcp.use_gcp_secret() )#.set_gpu_limit(1) def serve_op(): return dsl.ContainerOp( name='serve', image="{}:{}".format(KUBECTL_IMAGE, KUBECTL_IMAGE_VERSION), arguments=[ "/src/set_kubectl.sh", "--namespace", "kubeflow", "--command", "apply -f /src/k8s/serve.yaml", ] ).apply(gcp.use_gcp_secret()) def resultsgen_op(): return dsl.ContainerOp( name='resultsgen', image="{}:{}".format(TRACKML_IMAGE, TRACKML_IMAGE_VERSION), command=["python"], arguments=["resultsgen.py"], ).apply(gcp.use_gcp_secret()) @dsl.pipeline( name='trackml', description='A pipeline that predicts particle tracks' ) def trackml(): train = train_op() serve = serve_op() serve.after(train) resultsgen = resultsgen_op() resultsgen.after(serve) if __name__ == '__main__': import kfp.compiler as compiler compiler.Compiler().compile(trackml, __file__ + '.tar.gz')
en
0.078969
#!/usr/bin/env python3 # Pipeline input variables. #.set_gpu_limit(1)
2.342043
2
bin/ticker.py
aleasoluciones/infrabbitmq
0
96
<reponame>aleasoluciones/infrabbitmq<filename>bin/ticker.py # -*- coding: utf-8 -*- import time import puka import argparse import logging from infcommon import utils from infrabbitmq import factory as infrabbitmq_factory from infrabbitmq.rabbitmq import RabbitMQError from infrabbitmq.events_names import ( TICK_1_SECOND, TICK_1_MINUTE, TICK_2_MINUTES, TICK_5_MINUTES, TICK_60_MINUTES, ) def publish_event(publisher, event, network, secs, mins): logging.info("publish event {} {}".format(event, secs)) publisher.publish(event, network, data={'tick': secs, 'mins': mins}) def main(network): publisher = infrabbitmq_factory.event_publisher_json_serializer() secs = 0 mins = 0 rabbitmq_exceptions = (RabbitMQError, puka.AMQPError, KeyError,) while True: time.sleep(1) secs += 1 utils.do_stuff_with_exponential_backoff(rabbitmq_exceptions, publish_event, publisher, TICK_1_SECOND, network, secs, mins) if secs % 60 == 0: mins += 1 secs = 0 utils.do_stuff_with_exponential_backoff(rabbitmq_exceptions, publish_event, publisher, TICK_1_MINUTE, network, secs, mins) if mins % 2 == 0: utils.do_stuff_with_exponential_backoff(rabbitmq_exceptions, publish_event, publisher, TICK_2_MINUTES, network, secs, mins) if mins % 5 == 0: utils.do_stuff_with_exponential_backoff(rabbitmq_exceptions, publish_event, publisher, TICK_5_MINUTES, network, secs, mins) if mins % 60 == 0: utils.do_stuff_with_exponential_backoff(rabbitmq_exceptions, publish_event, publisher, TICK_60_MINUTES, network, secs, mins) if __name__ == '__main__': try: parser = argparse.ArgumentParser() parser.add_argument('-n', '--network', action='store', required=True, help='Network name (ilo, c2k, ...)') args = parser.parse_args() network = args.network.split('-')[0] main(network) except Exception as exc: logging.critical("Ticker Fails: {}".format(exc))
# -*- coding: utf-8 -*- import time import puka import argparse import logging from infcommon import utils from infrabbitmq import factory as infrabbitmq_factory from infrabbitmq.rabbitmq import RabbitMQError from infrabbitmq.events_names import ( TICK_1_SECOND, TICK_1_MINUTE, TICK_2_MINUTES, TICK_5_MINUTES, TICK_60_MINUTES, ) def publish_event(publisher, event, network, secs, mins): logging.info("publish event {} {}".format(event, secs)) publisher.publish(event, network, data={'tick': secs, 'mins': mins}) def main(network): publisher = infrabbitmq_factory.event_publisher_json_serializer() secs = 0 mins = 0 rabbitmq_exceptions = (RabbitMQError, puka.AMQPError, KeyError,) while True: time.sleep(1) secs += 1 utils.do_stuff_with_exponential_backoff(rabbitmq_exceptions, publish_event, publisher, TICK_1_SECOND, network, secs, mins) if secs % 60 == 0: mins += 1 secs = 0 utils.do_stuff_with_exponential_backoff(rabbitmq_exceptions, publish_event, publisher, TICK_1_MINUTE, network, secs, mins) if mins % 2 == 0: utils.do_stuff_with_exponential_backoff(rabbitmq_exceptions, publish_event, publisher, TICK_2_MINUTES, network, secs, mins) if mins % 5 == 0: utils.do_stuff_with_exponential_backoff(rabbitmq_exceptions, publish_event, publisher, TICK_5_MINUTES, network, secs, mins) if mins % 60 == 0: utils.do_stuff_with_exponential_backoff(rabbitmq_exceptions, publish_event, publisher, TICK_60_MINUTES, network, secs, mins) if __name__ == '__main__': try: parser = argparse.ArgumentParser() parser.add_argument('-n', '--network', action='store', required=True, help='Network name (ilo, c2k, ...)') args = parser.parse_args() network = args.network.split('-')[0] main(network) except Exception as exc: logging.critical("Ticker Fails: {}".format(exc))
en
0.769321
# -*- coding: utf-8 -*-
2.164284
2
transformers/modeling_encoder_decoder.py
Tarpelite/UniNLP
0
97
# coding=utf-8 # Copyright 2018 The HuggingFace Inc. team. # # 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. """ Classes to support Encoder-Decoder architectures """ from __future__ import absolute_import, division, print_function, unicode_literals import logging import os import torch from torch import nn from .modeling_auto import AutoModel, AutoModelWithLMHead logger = logging.getLogger(__name__) class PreTrainedEncoderDecoder(nn.Module): r""" :class:`~transformers.PreTrainedEncoderDecoder` is a generic model class that will be instantiated as a transformer architecture with one of the base model classes of the library as encoder and (optionally) another one as decoder when created with the `AutoModel.from_pretrained(pretrained_model_name_or_path)` class method. """ def __init__(self, encoder, decoder): super(PreTrainedEncoderDecoder, self).__init__() self.encoder = encoder self.decoder = decoder @classmethod def from_pretrained( cls, encoder_pretrained_model_name_or_path=None, decoder_pretrained_model_name_or_path=None, *model_args, **kwargs ): r""" Instantiates an encoder and a decoder from one or two base classes of the library from pre-trained model checkpoints. The model is set in evaluation mode by default using `model.eval()` (Dropout modules are deactivated) To train the model, you need to first set it back in training mode with `model.train()` Params: encoder_pretrained_model_name_or_path: information necessary to initiate the encoder. Either: - a string with the `shortcut name` of a pre-trained model to load from cache or download, e.g.: ``bert-base-uncased``. - a path to a `directory` containing model weights saved using :func:`~transformers.PreTrainedModel.save_pretrained`, e.g.: ``./my_model_directory/encoder``. - a path or url to a `tensorflow index checkpoint file` (e.g. `./tf_model/model.ckpt.index`). In this case, ``from_tf`` should be set to True and a configuration object should be provided as ``config`` argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards. decoder_pretrained_model_name_or_path: information necessary to initiate the decoder. Either: - a string with the `shortcut name` of a pre-trained model to load from cache or download, e.g.: ``bert-base-uncased``. - a path to a `directory` containing model weights saved using :func:`~transformers.PreTrainedModel.save_pretrained`, e.g.: ``./my_model_directory/decoder``. - a path or url to a `tensorflow index checkpoint file` (e.g. `./tf_model/model.ckpt.index`). In this case, ``from_tf`` should be set to True and a configuration object should be provided as ``config`` argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards. model_args: (`optional`) Sequence of positional arguments: All remaning positional arguments will be passed to the underlying model's ``__init__`` method config: (`optional`) instance of a class derived from :class:`~transformers.PretrainedConfig`: Configuration for the model to use instead of an automatically loaded configuation. Configuration can be automatically loaded when: - the model is a model provided by the library (loaded with the ``shortcut-name`` string of a pretrained model), or - the model was saved using :func:`~transformers.PreTrainedModel.save_pretrained` and is reloaded by suppling the save directory. - the model is loaded by suppling a local directory as ``pretrained_model_name_or_path`` and a configuration JSON file named `config.json` is found in the directory. state_dict: (`optional`) dict: an optional state dictionnary for the model to use instead of a state dictionary loaded from saved weights file. This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using :func:`~transformers.PreTrainedModel.save_pretrained` and :func:`~transformers.PreTrainedModel.from_pretrained` is not a simpler option. cache_dir: (`optional`) string: Path to a directory in which a downloaded pre-trained model configuration should be cached if the standard cache should not be used. force_download: (`optional`) boolean, default False: Force to (re-)download the model weights and configuration files and override the cached versions if they exists. proxies: (`optional`) dict, default None: A dictionary of proxy servers to use by protocol or endpoint, e.g.: {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}. The proxies are used on each request. output_loading_info: (`optional`) boolean: Set to ``True`` to also return a dictionnary containing missing keys, unexpected keys and error messages. kwargs: (`optional`) Remaining dictionary of keyword arguments. Can be used to update the configuration object (after it being loaded) and initiate the model. (e.g. ``output_attention=True``). Behave differently depending on whether a `config` is provided or automatically loaded: - If a configuration is provided with ``config``, ``**kwargs`` will be directly passed to the underlying model's ``__init__`` method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided, ``kwargs`` will be first passed to the configuration class initialization function (:func:`~transformers.PretrainedConfig.from_pretrained`). Each key of ``kwargs`` that corresponds to a configuration attribute will be used to override said attribute with the supplied ``kwargs`` value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model's ``__init__`` function. You can specify kwargs sepcific for the encoder and decoder by prefixing the key with `encoder_` and `decoder_` respectively. (e.g. ``decoder_output_attention=True``). The remaining kwargs will be passed to both encoders and decoders. Examples:: model = PreTrainedEncoderDecoder.from_pretained('bert-base-uncased', 'bert-base-uncased') # initialize Bert2Bert """ # keyword arguments come in 3 flavors: encoder-specific (prefixed by # `encoder_`), decoder-specific (prefixed by `decoder_`) and those # that apply to the model as a whole. # We let the specific kwargs override the common ones in case of conflict. kwargs_common = { argument: value for argument, value in kwargs.items() if not argument.startswith("encoder_") and not argument.startswith("decoder_") } kwargs_decoder = kwargs_common.copy() kwargs_encoder = kwargs_common.copy() kwargs_encoder.update( { argument[len("encoder_") :]: value for argument, value in kwargs.items() if argument.startswith("encoder_") } ) kwargs_decoder.update( { argument[len("decoder_") :]: value for argument, value in kwargs.items() if argument.startswith("decoder_") } ) # Load and initialize the encoder and decoder # The distinction between encoder and decoder at the model level is made # by the value of the flag `is_decoder` that we need to set correctly. encoder = kwargs_encoder.pop("model", None) if encoder is None: encoder = AutoModel.from_pretrained( encoder_pretrained_model_name_or_path, *model_args, **kwargs_encoder ) encoder.config.is_decoder = False decoder = kwargs_decoder.pop("model", None) if decoder is None: decoder = AutoModelWithLMHead.from_pretrained( decoder_pretrained_model_name_or_path, **kwargs_decoder ) decoder.config.is_decoder = True model = cls(encoder, decoder) return model def save_pretrained(self, save_directory): """ Save a Seq2Seq model and its configuration file in a format such that it can be loaded using `:func:`~transformers.PreTrainedEncoderDecoder.from_pretrained` We save the encoder' and decoder's parameters in two separate directories. """ self.encoder.save_pretrained(os.path.join(save_directory, "encoder")) self.decoder.save_pretrained(os.path.join(save_directory, "decoder")) def forward(self, encoder_input_ids, decoder_input_ids, **kwargs): """ The forward pass on a seq2eq depends what we are performing: - During training we perform one forward pass through both the encoder and decoder; - During prediction, we perform one forward pass through the encoder, and then perform several forward passes with the encoder's hidden state through the decoder to decode a full sequence. Therefore, we skip the forward pass on the encoder if an argument named `encoder_hidden_state` is passed to this function. Params: encoder_input_ids: ``torch.LongTensor`` of shape ``(batch_size, sequence_length)`` Indices of encoder input sequence tokens in the vocabulary. decoder_input_ids: ``torch.LongTensor`` of shape ``(batch_size, sequence_length)`` Indices of decoder input sequence tokens in the vocabulary. kwargs: (`optional`) Remaining dictionary of keyword arguments. """ # keyword arguments come in 3 flavors: encoder-specific (prefixed by # `encoder_`), decoder-specific (prefixed by `decoder_`) and those # that apply to the model as whole. # We let the specific kwargs override the common ones in case of conflict. kwargs_common = { argument: value for argument, value in kwargs.items() if not argument.startswith("encoder_") and not argument.startswith("decoder_") } kwargs_decoder = kwargs_common.copy() kwargs_encoder = kwargs_common.copy() kwargs_encoder.update( { argument[len("encoder_") :]: value for argument, value in kwargs.items() if argument.startswith("encoder_") } ) kwargs_decoder.update( { argument[len("decoder_") :]: value for argument, value in kwargs.items() if argument.startswith("decoder_") } ) # Encode if needed (training, first prediction pass) encoder_hidden_states = kwargs_encoder.pop("hidden_states", None) if encoder_hidden_states is None: encoder_outputs = self.encoder(encoder_input_ids, **kwargs_encoder) encoder_hidden_states = encoder_outputs[ 0 ] # output the last layer hidden state else: encoder_outputs = () # Decode kwargs_decoder["encoder_hidden_states"] = encoder_hidden_states kwargs_decoder["encoder_attention_mask"] = kwargs_encoder.get( "attention_mask", None ) decoder_outputs = self.decoder(decoder_input_ids, **kwargs_decoder) return decoder_outputs + encoder_outputs class Model2Model(PreTrainedEncoderDecoder): r""" :class:`~transformers.Model2Model` instantiates a Seq2Seq2 model where both of the encoder and decoder are of the same family. If the name of or that path to a pretrained model is specified the encoder and the decoder will be initialized with the pretrained weight (the cross-attention will be intialized randomly if its weights are not present). It is possible to override this behavior and initialize, say, the decoder randomly by creating it beforehand as follows config = BertConfig.from_pretrained() decoder = BertForMaskedLM(config) model = Model2Model.from_pretrained('bert-base-uncased', decoder_model=decoder) """ def __init__(self, *args, **kwargs): super(Model2Model, self).__init__(*args, **kwargs) self.tie_weights() def tie_weights(self): """ Tying the encoder and decoders' embeddings together. We need for each to get down to the embedding weights. However the different model classes are inconsistent to that respect: - BertModel: embeddings.word_embeddings - RoBERTa: embeddings.word_embeddings - XLMModel: embeddings - GPT2: wte - BertForMaskedLM: bert.embeddings.word_embeddings - RobertaForMaskedLM: roberta.embeddings.word_embeddings argument of the XEmbedding layer for each model, but it is "blocked" by a model-specific keyword (bert, )... """ # self._tie_or_clone_weights(self.encoder, self.decoder) pass @classmethod def from_pretrained(cls, pretrained_model_name_or_path, *args, **kwargs): if ( "bert" not in pretrained_model_name_or_path or "roberta" in pretrained_model_name_or_path or "distilbert" in pretrained_model_name_or_path ): raise ValueError("Only the Bert model is currently supported.") model = super(Model2Model, cls).from_pretrained( encoder_pretrained_model_name_or_path=pretrained_model_name_or_path, decoder_pretrained_model_name_or_path=pretrained_model_name_or_path, *args, **kwargs ) return model class Model2LSTM(PreTrainedEncoderDecoder): @classmethod def from_pretrained(cls, *args, **kwargs): if kwargs.get("decoder_model", None) is None: # We will create a randomly initilized LSTM model as decoder if "decoder_config" not in kwargs: raise ValueError( "To load an LSTM in Encoder-Decoder model, please supply either: " " - a torch.nn.LSTM model as `decoder_model` parameter (`decoder_model=lstm_model`), or" " - a dictionary of configuration parameters that will be used to initialize a" " torch.nn.LSTM model as `decoder_config` keyword argument. " " E.g. `decoder_config={'input_size': 768, 'hidden_size': 768, 'num_layers': 2}`" ) kwargs["decoder_model"] = torch.nn.LSTM(kwargs.pop("decoder_config")) model = super(Model2LSTM, cls).from_pretrained(*args, **kwargs) return model
# coding=utf-8 # Copyright 2018 The HuggingFace Inc. team. # # 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. """ Classes to support Encoder-Decoder architectures """ from __future__ import absolute_import, division, print_function, unicode_literals import logging import os import torch from torch import nn from .modeling_auto import AutoModel, AutoModelWithLMHead logger = logging.getLogger(__name__) class PreTrainedEncoderDecoder(nn.Module): r""" :class:`~transformers.PreTrainedEncoderDecoder` is a generic model class that will be instantiated as a transformer architecture with one of the base model classes of the library as encoder and (optionally) another one as decoder when created with the `AutoModel.from_pretrained(pretrained_model_name_or_path)` class method. """ def __init__(self, encoder, decoder): super(PreTrainedEncoderDecoder, self).__init__() self.encoder = encoder self.decoder = decoder @classmethod def from_pretrained( cls, encoder_pretrained_model_name_or_path=None, decoder_pretrained_model_name_or_path=None, *model_args, **kwargs ): r""" Instantiates an encoder and a decoder from one or two base classes of the library from pre-trained model checkpoints. The model is set in evaluation mode by default using `model.eval()` (Dropout modules are deactivated) To train the model, you need to first set it back in training mode with `model.train()` Params: encoder_pretrained_model_name_or_path: information necessary to initiate the encoder. Either: - a string with the `shortcut name` of a pre-trained model to load from cache or download, e.g.: ``bert-base-uncased``. - a path to a `directory` containing model weights saved using :func:`~transformers.PreTrainedModel.save_pretrained`, e.g.: ``./my_model_directory/encoder``. - a path or url to a `tensorflow index checkpoint file` (e.g. `./tf_model/model.ckpt.index`). In this case, ``from_tf`` should be set to True and a configuration object should be provided as ``config`` argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards. decoder_pretrained_model_name_or_path: information necessary to initiate the decoder. Either: - a string with the `shortcut name` of a pre-trained model to load from cache or download, e.g.: ``bert-base-uncased``. - a path to a `directory` containing model weights saved using :func:`~transformers.PreTrainedModel.save_pretrained`, e.g.: ``./my_model_directory/decoder``. - a path or url to a `tensorflow index checkpoint file` (e.g. `./tf_model/model.ckpt.index`). In this case, ``from_tf`` should be set to True and a configuration object should be provided as ``config`` argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards. model_args: (`optional`) Sequence of positional arguments: All remaning positional arguments will be passed to the underlying model's ``__init__`` method config: (`optional`) instance of a class derived from :class:`~transformers.PretrainedConfig`: Configuration for the model to use instead of an automatically loaded configuation. Configuration can be automatically loaded when: - the model is a model provided by the library (loaded with the ``shortcut-name`` string of a pretrained model), or - the model was saved using :func:`~transformers.PreTrainedModel.save_pretrained` and is reloaded by suppling the save directory. - the model is loaded by suppling a local directory as ``pretrained_model_name_or_path`` and a configuration JSON file named `config.json` is found in the directory. state_dict: (`optional`) dict: an optional state dictionnary for the model to use instead of a state dictionary loaded from saved weights file. This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using :func:`~transformers.PreTrainedModel.save_pretrained` and :func:`~transformers.PreTrainedModel.from_pretrained` is not a simpler option. cache_dir: (`optional`) string: Path to a directory in which a downloaded pre-trained model configuration should be cached if the standard cache should not be used. force_download: (`optional`) boolean, default False: Force to (re-)download the model weights and configuration files and override the cached versions if they exists. proxies: (`optional`) dict, default None: A dictionary of proxy servers to use by protocol or endpoint, e.g.: {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}. The proxies are used on each request. output_loading_info: (`optional`) boolean: Set to ``True`` to also return a dictionnary containing missing keys, unexpected keys and error messages. kwargs: (`optional`) Remaining dictionary of keyword arguments. Can be used to update the configuration object (after it being loaded) and initiate the model. (e.g. ``output_attention=True``). Behave differently depending on whether a `config` is provided or automatically loaded: - If a configuration is provided with ``config``, ``**kwargs`` will be directly passed to the underlying model's ``__init__`` method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided, ``kwargs`` will be first passed to the configuration class initialization function (:func:`~transformers.PretrainedConfig.from_pretrained`). Each key of ``kwargs`` that corresponds to a configuration attribute will be used to override said attribute with the supplied ``kwargs`` value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model's ``__init__`` function. You can specify kwargs sepcific for the encoder and decoder by prefixing the key with `encoder_` and `decoder_` respectively. (e.g. ``decoder_output_attention=True``). The remaining kwargs will be passed to both encoders and decoders. Examples:: model = PreTrainedEncoderDecoder.from_pretained('bert-base-uncased', 'bert-base-uncased') # initialize Bert2Bert """ # keyword arguments come in 3 flavors: encoder-specific (prefixed by # `encoder_`), decoder-specific (prefixed by `decoder_`) and those # that apply to the model as a whole. # We let the specific kwargs override the common ones in case of conflict. kwargs_common = { argument: value for argument, value in kwargs.items() if not argument.startswith("encoder_") and not argument.startswith("decoder_") } kwargs_decoder = kwargs_common.copy() kwargs_encoder = kwargs_common.copy() kwargs_encoder.update( { argument[len("encoder_") :]: value for argument, value in kwargs.items() if argument.startswith("encoder_") } ) kwargs_decoder.update( { argument[len("decoder_") :]: value for argument, value in kwargs.items() if argument.startswith("decoder_") } ) # Load and initialize the encoder and decoder # The distinction between encoder and decoder at the model level is made # by the value of the flag `is_decoder` that we need to set correctly. encoder = kwargs_encoder.pop("model", None) if encoder is None: encoder = AutoModel.from_pretrained( encoder_pretrained_model_name_or_path, *model_args, **kwargs_encoder ) encoder.config.is_decoder = False decoder = kwargs_decoder.pop("model", None) if decoder is None: decoder = AutoModelWithLMHead.from_pretrained( decoder_pretrained_model_name_or_path, **kwargs_decoder ) decoder.config.is_decoder = True model = cls(encoder, decoder) return model def save_pretrained(self, save_directory): """ Save a Seq2Seq model and its configuration file in a format such that it can be loaded using `:func:`~transformers.PreTrainedEncoderDecoder.from_pretrained` We save the encoder' and decoder's parameters in two separate directories. """ self.encoder.save_pretrained(os.path.join(save_directory, "encoder")) self.decoder.save_pretrained(os.path.join(save_directory, "decoder")) def forward(self, encoder_input_ids, decoder_input_ids, **kwargs): """ The forward pass on a seq2eq depends what we are performing: - During training we perform one forward pass through both the encoder and decoder; - During prediction, we perform one forward pass through the encoder, and then perform several forward passes with the encoder's hidden state through the decoder to decode a full sequence. Therefore, we skip the forward pass on the encoder if an argument named `encoder_hidden_state` is passed to this function. Params: encoder_input_ids: ``torch.LongTensor`` of shape ``(batch_size, sequence_length)`` Indices of encoder input sequence tokens in the vocabulary. decoder_input_ids: ``torch.LongTensor`` of shape ``(batch_size, sequence_length)`` Indices of decoder input sequence tokens in the vocabulary. kwargs: (`optional`) Remaining dictionary of keyword arguments. """ # keyword arguments come in 3 flavors: encoder-specific (prefixed by # `encoder_`), decoder-specific (prefixed by `decoder_`) and those # that apply to the model as whole. # We let the specific kwargs override the common ones in case of conflict. kwargs_common = { argument: value for argument, value in kwargs.items() if not argument.startswith("encoder_") and not argument.startswith("decoder_") } kwargs_decoder = kwargs_common.copy() kwargs_encoder = kwargs_common.copy() kwargs_encoder.update( { argument[len("encoder_") :]: value for argument, value in kwargs.items() if argument.startswith("encoder_") } ) kwargs_decoder.update( { argument[len("decoder_") :]: value for argument, value in kwargs.items() if argument.startswith("decoder_") } ) # Encode if needed (training, first prediction pass) encoder_hidden_states = kwargs_encoder.pop("hidden_states", None) if encoder_hidden_states is None: encoder_outputs = self.encoder(encoder_input_ids, **kwargs_encoder) encoder_hidden_states = encoder_outputs[ 0 ] # output the last layer hidden state else: encoder_outputs = () # Decode kwargs_decoder["encoder_hidden_states"] = encoder_hidden_states kwargs_decoder["encoder_attention_mask"] = kwargs_encoder.get( "attention_mask", None ) decoder_outputs = self.decoder(decoder_input_ids, **kwargs_decoder) return decoder_outputs + encoder_outputs class Model2Model(PreTrainedEncoderDecoder): r""" :class:`~transformers.Model2Model` instantiates a Seq2Seq2 model where both of the encoder and decoder are of the same family. If the name of or that path to a pretrained model is specified the encoder and the decoder will be initialized with the pretrained weight (the cross-attention will be intialized randomly if its weights are not present). It is possible to override this behavior and initialize, say, the decoder randomly by creating it beforehand as follows config = BertConfig.from_pretrained() decoder = BertForMaskedLM(config) model = Model2Model.from_pretrained('bert-base-uncased', decoder_model=decoder) """ def __init__(self, *args, **kwargs): super(Model2Model, self).__init__(*args, **kwargs) self.tie_weights() def tie_weights(self): """ Tying the encoder and decoders' embeddings together. We need for each to get down to the embedding weights. However the different model classes are inconsistent to that respect: - BertModel: embeddings.word_embeddings - RoBERTa: embeddings.word_embeddings - XLMModel: embeddings - GPT2: wte - BertForMaskedLM: bert.embeddings.word_embeddings - RobertaForMaskedLM: roberta.embeddings.word_embeddings argument of the XEmbedding layer for each model, but it is "blocked" by a model-specific keyword (bert, )... """ # self._tie_or_clone_weights(self.encoder, self.decoder) pass @classmethod def from_pretrained(cls, pretrained_model_name_or_path, *args, **kwargs): if ( "bert" not in pretrained_model_name_or_path or "roberta" in pretrained_model_name_or_path or "distilbert" in pretrained_model_name_or_path ): raise ValueError("Only the Bert model is currently supported.") model = super(Model2Model, cls).from_pretrained( encoder_pretrained_model_name_or_path=pretrained_model_name_or_path, decoder_pretrained_model_name_or_path=pretrained_model_name_or_path, *args, **kwargs ) return model class Model2LSTM(PreTrainedEncoderDecoder): @classmethod def from_pretrained(cls, *args, **kwargs): if kwargs.get("decoder_model", None) is None: # We will create a randomly initilized LSTM model as decoder if "decoder_config" not in kwargs: raise ValueError( "To load an LSTM in Encoder-Decoder model, please supply either: " " - a torch.nn.LSTM model as `decoder_model` parameter (`decoder_model=lstm_model`), or" " - a dictionary of configuration parameters that will be used to initialize a" " torch.nn.LSTM model as `decoder_config` keyword argument. " " E.g. `decoder_config={'input_size': 768, 'hidden_size': 768, 'num_layers': 2}`" ) kwargs["decoder_model"] = torch.nn.LSTM(kwargs.pop("decoder_config")) model = super(Model2LSTM, cls).from_pretrained(*args, **kwargs) return model
en
0.774968
# coding=utf-8 # Copyright 2018 The HuggingFace Inc. team. # # 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. Classes to support Encoder-Decoder architectures :class:`~transformers.PreTrainedEncoderDecoder` is a generic model class that will be instantiated as a transformer architecture with one of the base model classes of the library as encoder and (optionally) another one as decoder when created with the `AutoModel.from_pretrained(pretrained_model_name_or_path)` class method. Instantiates an encoder and a decoder from one or two base classes of the library from pre-trained model checkpoints. The model is set in evaluation mode by default using `model.eval()` (Dropout modules are deactivated) To train the model, you need to first set it back in training mode with `model.train()` Params: encoder_pretrained_model_name_or_path: information necessary to initiate the encoder. Either: - a string with the `shortcut name` of a pre-trained model to load from cache or download, e.g.: ``bert-base-uncased``. - a path to a `directory` containing model weights saved using :func:`~transformers.PreTrainedModel.save_pretrained`, e.g.: ``./my_model_directory/encoder``. - a path or url to a `tensorflow index checkpoint file` (e.g. `./tf_model/model.ckpt.index`). In this case, ``from_tf`` should be set to True and a configuration object should be provided as ``config`` argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards. decoder_pretrained_model_name_or_path: information necessary to initiate the decoder. Either: - a string with the `shortcut name` of a pre-trained model to load from cache or download, e.g.: ``bert-base-uncased``. - a path to a `directory` containing model weights saved using :func:`~transformers.PreTrainedModel.save_pretrained`, e.g.: ``./my_model_directory/decoder``. - a path or url to a `tensorflow index checkpoint file` (e.g. `./tf_model/model.ckpt.index`). In this case, ``from_tf`` should be set to True and a configuration object should be provided as ``config`` argument. This loading path is slower than converting the TensorFlow checkpoint in a PyTorch model using the provided conversion scripts and loading the PyTorch model afterwards. model_args: (`optional`) Sequence of positional arguments: All remaning positional arguments will be passed to the underlying model's ``__init__`` method config: (`optional`) instance of a class derived from :class:`~transformers.PretrainedConfig`: Configuration for the model to use instead of an automatically loaded configuation. Configuration can be automatically loaded when: - the model is a model provided by the library (loaded with the ``shortcut-name`` string of a pretrained model), or - the model was saved using :func:`~transformers.PreTrainedModel.save_pretrained` and is reloaded by suppling the save directory. - the model is loaded by suppling a local directory as ``pretrained_model_name_or_path`` and a configuration JSON file named `config.json` is found in the directory. state_dict: (`optional`) dict: an optional state dictionnary for the model to use instead of a state dictionary loaded from saved weights file. This option can be used if you want to create a model from a pretrained configuration but load your own weights. In this case though, you should check if using :func:`~transformers.PreTrainedModel.save_pretrained` and :func:`~transformers.PreTrainedModel.from_pretrained` is not a simpler option. cache_dir: (`optional`) string: Path to a directory in which a downloaded pre-trained model configuration should be cached if the standard cache should not be used. force_download: (`optional`) boolean, default False: Force to (re-)download the model weights and configuration files and override the cached versions if they exists. proxies: (`optional`) dict, default None: A dictionary of proxy servers to use by protocol or endpoint, e.g.: {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}. The proxies are used on each request. output_loading_info: (`optional`) boolean: Set to ``True`` to also return a dictionnary containing missing keys, unexpected keys and error messages. kwargs: (`optional`) Remaining dictionary of keyword arguments. Can be used to update the configuration object (after it being loaded) and initiate the model. (e.g. ``output_attention=True``). Behave differently depending on whether a `config` is provided or automatically loaded: - If a configuration is provided with ``config``, ``**kwargs`` will be directly passed to the underlying model's ``__init__`` method (we assume all relevant updates to the configuration have already been done) - If a configuration is not provided, ``kwargs`` will be first passed to the configuration class initialization function (:func:`~transformers.PretrainedConfig.from_pretrained`). Each key of ``kwargs`` that corresponds to a configuration attribute will be used to override said attribute with the supplied ``kwargs`` value. Remaining keys that do not correspond to any configuration attribute will be passed to the underlying model's ``__init__`` function. You can specify kwargs sepcific for the encoder and decoder by prefixing the key with `encoder_` and `decoder_` respectively. (e.g. ``decoder_output_attention=True``). The remaining kwargs will be passed to both encoders and decoders. Examples:: model = PreTrainedEncoderDecoder.from_pretained('bert-base-uncased', 'bert-base-uncased') # initialize Bert2Bert # keyword arguments come in 3 flavors: encoder-specific (prefixed by # `encoder_`), decoder-specific (prefixed by `decoder_`) and those # that apply to the model as a whole. # We let the specific kwargs override the common ones in case of conflict. # Load and initialize the encoder and decoder # The distinction between encoder and decoder at the model level is made # by the value of the flag `is_decoder` that we need to set correctly. Save a Seq2Seq model and its configuration file in a format such that it can be loaded using `:func:`~transformers.PreTrainedEncoderDecoder.from_pretrained` We save the encoder' and decoder's parameters in two separate directories. The forward pass on a seq2eq depends what we are performing: - During training we perform one forward pass through both the encoder and decoder; - During prediction, we perform one forward pass through the encoder, and then perform several forward passes with the encoder's hidden state through the decoder to decode a full sequence. Therefore, we skip the forward pass on the encoder if an argument named `encoder_hidden_state` is passed to this function. Params: encoder_input_ids: ``torch.LongTensor`` of shape ``(batch_size, sequence_length)`` Indices of encoder input sequence tokens in the vocabulary. decoder_input_ids: ``torch.LongTensor`` of shape ``(batch_size, sequence_length)`` Indices of decoder input sequence tokens in the vocabulary. kwargs: (`optional`) Remaining dictionary of keyword arguments. # keyword arguments come in 3 flavors: encoder-specific (prefixed by # `encoder_`), decoder-specific (prefixed by `decoder_`) and those # that apply to the model as whole. # We let the specific kwargs override the common ones in case of conflict. # Encode if needed (training, first prediction pass) # output the last layer hidden state # Decode :class:`~transformers.Model2Model` instantiates a Seq2Seq2 model where both of the encoder and decoder are of the same family. If the name of or that path to a pretrained model is specified the encoder and the decoder will be initialized with the pretrained weight (the cross-attention will be intialized randomly if its weights are not present). It is possible to override this behavior and initialize, say, the decoder randomly by creating it beforehand as follows config = BertConfig.from_pretrained() decoder = BertForMaskedLM(config) model = Model2Model.from_pretrained('bert-base-uncased', decoder_model=decoder) Tying the encoder and decoders' embeddings together. We need for each to get down to the embedding weights. However the different model classes are inconsistent to that respect: - BertModel: embeddings.word_embeddings - RoBERTa: embeddings.word_embeddings - XLMModel: embeddings - GPT2: wte - BertForMaskedLM: bert.embeddings.word_embeddings - RobertaForMaskedLM: roberta.embeddings.word_embeddings argument of the XEmbedding layer for each model, but it is "blocked" by a model-specific keyword (bert, )... # self._tie_or_clone_weights(self.encoder, self.decoder) # We will create a randomly initilized LSTM model as decoder
2.401325
2
dags/treinos_igti/treino03.py
rafaelols/airflow
0
98
from airflow import DAG from airflow.operators.bash_operator import BashOperator from airflow.operators.python_operator import PythonOperator, BranchPythonOperator from datetime import datetime, timedelta import pandas as pd import random # Default args definition default_args = { 'owner': 'Rafael', 'depends_on_past': False, 'start_date': datetime(2020, 11, 29, 18, 20), 'email': ['<EMAIL>', '<EMAIL>'], 'email_on_failure': False, 'email_on_retry': False, 'retries': 1, 'Retry_delay': timedelta(minutes=1) } # Dag definition dag = DAG( 'treino-03', description="Extrai dados do Titanic e calcula idade media para homens ou mulheres", default_args = default_args, schedule_interval='*/20 * * * *' ) get_data = BashOperator( task_id='get-data', bash_command='curl https://raw.githubusercontent.com/A3Data/hermione/master/hermione/file_text/train.csv -o /usr/local/airflow/data/train.csv', dag=dag ) def sorteia_h_m(): return random.choice(['male', 'female']) escolhe_h_m = PythonOperator( task_id='escolhe-h-m', python_callable=sorteia_h_m, dag=dag ) def MouF(**context): value=context['task_instance'].xcom_pull(task_ids='escolhe-h-m') if value == 'male': return 'branch_homem' else: return 'branch_mulher' male_female = BranchPythonOperator( task_id='condicional', python_callable=MouF, provide_context=True, dag=dag ) def mean_homem(): df = pd.read_csv('/usr/local/airflow/data/train.csv') med = df.loc[df.Sex == 'male'].Age.mean() print(f'Media de idade dos homens no Titanic: {med}') branch_homem = PythonOperator( task_id='branch_homem', python_callable=mean_homem, dag=dag ) def mean_mulher(): df = pd.read_csv('/usr/local/airflow/data/train.csv') med = df.loc[df.Sex == 'female'].Age.mean() print(f'Media de idade das mulheres no Titanic: {med}') branch_mulher = PythonOperator( task_id='branch_mulher', python_callable=mean_mulher, dag=dag ) get_data >> escolhe_h_m >> male_female >> [branch_homem, branch_mulher]
from airflow import DAG from airflow.operators.bash_operator import BashOperator from airflow.operators.python_operator import PythonOperator, BranchPythonOperator from datetime import datetime, timedelta import pandas as pd import random # Default args definition default_args = { 'owner': 'Rafael', 'depends_on_past': False, 'start_date': datetime(2020, 11, 29, 18, 20), 'email': ['<EMAIL>', '<EMAIL>'], 'email_on_failure': False, 'email_on_retry': False, 'retries': 1, 'Retry_delay': timedelta(minutes=1) } # Dag definition dag = DAG( 'treino-03', description="Extrai dados do Titanic e calcula idade media para homens ou mulheres", default_args = default_args, schedule_interval='*/20 * * * *' ) get_data = BashOperator( task_id='get-data', bash_command='curl https://raw.githubusercontent.com/A3Data/hermione/master/hermione/file_text/train.csv -o /usr/local/airflow/data/train.csv', dag=dag ) def sorteia_h_m(): return random.choice(['male', 'female']) escolhe_h_m = PythonOperator( task_id='escolhe-h-m', python_callable=sorteia_h_m, dag=dag ) def MouF(**context): value=context['task_instance'].xcom_pull(task_ids='escolhe-h-m') if value == 'male': return 'branch_homem' else: return 'branch_mulher' male_female = BranchPythonOperator( task_id='condicional', python_callable=MouF, provide_context=True, dag=dag ) def mean_homem(): df = pd.read_csv('/usr/local/airflow/data/train.csv') med = df.loc[df.Sex == 'male'].Age.mean() print(f'Media de idade dos homens no Titanic: {med}') branch_homem = PythonOperator( task_id='branch_homem', python_callable=mean_homem, dag=dag ) def mean_mulher(): df = pd.read_csv('/usr/local/airflow/data/train.csv') med = df.loc[df.Sex == 'female'].Age.mean() print(f'Media de idade das mulheres no Titanic: {med}') branch_mulher = PythonOperator( task_id='branch_mulher', python_callable=mean_mulher, dag=dag ) get_data >> escolhe_h_m >> male_female >> [branch_homem, branch_mulher]
en
0.243487
# Default args definition # Dag definition
2.335279
2
tclCommands/TclCommandListSys.py
DannyPol/flatcam
1
99
<filename>tclCommands/TclCommandListSys.py # ########################################################## # FlatCAM: 2D Post-processing for Manufacturing # # File Author: <NAME> (c) # # Date: 8/17/2019 # # MIT Licence # # ########################################################## from tclCommands.TclCommand import * class TclCommandListSys(TclCommand): """ Tcl shell command to get the list of system variables example: list_sys """ # List of all command aliases, to be able use old names for backward compatibility (add_poly, add_polygon) aliases = ['list_sys', 'listsys'] description = '%s %s' % ("--", "Outputs in Tcl Shell the list with the names of system variables.") # Dictionary of types from Tcl command, needs to be ordered arg_names = collections.OrderedDict([ ('selection', str), ]) # Dictionary of types from Tcl command, needs to be ordered , this is for options like -optionname value option_types = collections.OrderedDict([ ]) # array of mandatory options for current Tcl command: required = {'name','outname'} required = [] # structured help for current command, args needs to be ordered help = { 'main': "Returns the list of the names of system variables.\n" "Without an argument it will list all the system parameters. " "As an argument use first letter or first letters from the name " "of the system variable.\n" "In that case it will list only the system variables that starts with that string.\n" "Main categories start with: gerber or excellon or geometry or cncjob or global.\n" "Note: Use 'get_sys system variable' to get the value and 'set_sys system variable value' to set it.\n", 'args': collections.OrderedDict([ ]), 'examples': ['list_sys', 'list_sys ser', 'list_sys gerber', 'list_sys cncj'] } def execute(self, args, unnamed_args): """ :param args: :param unnamed_args: :return: """ if 'selection' in args: argument = args['selection'] return str([k for k in self.app.defaults.keys() if str(k).startswith(str(argument))]) else: ret_val = list(self.app.defaults.keys()) return str(ret_val) # return str([*self.app.defaults])
<filename>tclCommands/TclCommandListSys.py # ########################################################## # FlatCAM: 2D Post-processing for Manufacturing # # File Author: <NAME> (c) # # Date: 8/17/2019 # # MIT Licence # # ########################################################## from tclCommands.TclCommand import * class TclCommandListSys(TclCommand): """ Tcl shell command to get the list of system variables example: list_sys """ # List of all command aliases, to be able use old names for backward compatibility (add_poly, add_polygon) aliases = ['list_sys', 'listsys'] description = '%s %s' % ("--", "Outputs in Tcl Shell the list with the names of system variables.") # Dictionary of types from Tcl command, needs to be ordered arg_names = collections.OrderedDict([ ('selection', str), ]) # Dictionary of types from Tcl command, needs to be ordered , this is for options like -optionname value option_types = collections.OrderedDict([ ]) # array of mandatory options for current Tcl command: required = {'name','outname'} required = [] # structured help for current command, args needs to be ordered help = { 'main': "Returns the list of the names of system variables.\n" "Without an argument it will list all the system parameters. " "As an argument use first letter or first letters from the name " "of the system variable.\n" "In that case it will list only the system variables that starts with that string.\n" "Main categories start with: gerber or excellon or geometry or cncjob or global.\n" "Note: Use 'get_sys system variable' to get the value and 'set_sys system variable value' to set it.\n", 'args': collections.OrderedDict([ ]), 'examples': ['list_sys', 'list_sys ser', 'list_sys gerber', 'list_sys cncj'] } def execute(self, args, unnamed_args): """ :param args: :param unnamed_args: :return: """ if 'selection' in args: argument = args['selection'] return str([k for k in self.app.defaults.keys() if str(k).startswith(str(argument))]) else: ret_val = list(self.app.defaults.keys()) return str(ret_val) # return str([*self.app.defaults])
en
0.50521
# ########################################################## # FlatCAM: 2D Post-processing for Manufacturing # # File Author: <NAME> (c) # # Date: 8/17/2019 # # MIT Licence # # ########################################################## Tcl shell command to get the list of system variables example: list_sys # List of all command aliases, to be able use old names for backward compatibility (add_poly, add_polygon) # Dictionary of types from Tcl command, needs to be ordered # Dictionary of types from Tcl command, needs to be ordered , this is for options like -optionname value # array of mandatory options for current Tcl command: required = {'name','outname'} # structured help for current command, args needs to be ordered :param args: :param unnamed_args: :return: # return str([*self.app.defaults])
2.338145
2