repo_name
stringlengths
7
94
repo_path
stringlengths
4
237
repo_head_hexsha
stringlengths
40
40
content
stringlengths
10
680k
apis
stringlengths
2
840k
MTES-MCT/sparte
public_data/serializers.py
3b8ae6d21da81ca761d64ae9dfe2c8f54487211c
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
[((28, 17, 28, 42), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ({}, {}), '()', True, 'from rest_framework import serializers as s\n'), ((29, 17, 29, 42), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ({}, {}), '()', True, 'from rest_framework import serializers as s\n'), ((30, 22, 30, 47), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ({}, {}), '()', True, 'from rest_framework import serializers as s\n'), ((31, 22, 31, 47), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ({}, {}), '()', True, 'from rest_framework import serializers as s\n'), ((59, 17, 59, 42), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ({}, {}), '()', True, 'from rest_framework import serializers as s\n'), ((90, 17, 90, 42), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ({}, {}), '()', True, 'from rest_framework import serializers as s\n'), ((106, 17, 106, 42), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ({}, {}), '()', True, 'from rest_framework import serializers as s\n'), ((107, 12, 107, 37), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ({}, {}), '()', True, 'from rest_framework import serializers as s\n'), ((129, 17, 129, 42), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ({}, {}), '()', True, 'from rest_framework import serializers as s\n'), ((130, 17, 130, 42), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ({}, {}), '()', True, 'from rest_framework import serializers as s\n'), ((131, 22, 131, 47), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ({}, {}), '()', True, 'from rest_framework import serializers as s\n'), ((132, 22, 132, 47), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ({}, {}), '()', True, 'from rest_framework import serializers as s\n'), ((170, 17, 170, 42), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ({}, {}), '()', True, 'from rest_framework import serializers as s\n'), ((171, 12, 171, 37), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ({}, {}), '()', True, 'from rest_framework import serializers as s\n'), ((191, 17, 191, 42), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ({}, {}), '()', True, 'from rest_framework import serializers as s\n'), ((192, 12, 192, 37), 'rest_framework.serializers.SerializerMethodField', 's.SerializerMethodField', ({}, {}), '()', True, 'from rest_framework import serializers as s\n')]
naman1901/django-quick-search
quick_search/admin.py
7b93554ed9fa4721e52372f9fd1a395d94cc04a7
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)
[((8, 0, 8, 52), 'django.contrib.admin.site.register', 'admin.site.register', ({(8, 20, 8, 32): 'SearchResult', (8, 34, 8, 51): 'SearchResultAdmin'}, {}), '(SearchResult, SearchResultAdmin)', False, 'from django.contrib import admin\n')]
Amirali-Shirkh/rasa-for-botfront
rasa/train.py
36aa24ad31241c5d1a180bbe34e1c8c50da40ff7
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
[((116, 4, 119, 5), 'rasa.cli.utils.print_warning', 'print_warning', ({(117, 8, 118, 110): '"""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."""'}, {}), '(\n "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."\n )', False, 'from rasa.cli.utils import print_success, print_warning, print_error, bcolors, print_color\n'), ((169, 16, 169, 51), 'rasa.model.get_latest_model', 'model.get_latest_model', ({(169, 39, 169, 50): 'output_path'}, {}), '(output_path)', False, 'from rasa import model\n'), ((170, 29, 170, 87), 'rasa.model.FingerprintComparisonResult', 'FingerprintComparisonResult', (), '', False, 'from rasa.model import FingerprintComparisonResult\n'), ((275, 11, 275, 35), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ({}, {}), '()', False, 'import asyncio\n'), ((317, 20, 319, 5), 'rasa.importers.importer.TrainingDataImporter.load_core_importer_from_config', 'TrainingDataImporter.load_core_importer_from_config', ({(318, 8, 318, 14): 'config', (318, 16, 318, 22): 'domain', (318, 24, 318, 33): '[stories]'}, {}), '(config, domain, [stories])', False, 'from rasa.importers.importer import TrainingDataImporter\n'), ((418, 11, 418, 35), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ({}, {}), '()', False, 'import asyncio\n'), ((447, 20, 449, 5), 'rasa.importers.importer.TrainingDataImporter.load_nlu_importer_from_config', 'TrainingDataImporter.load_nlu_importer_from_config', (), '', False, 'from rasa.importers.importer import TrainingDataImporter\n'), ((86, 9, 86, 20), 'contextlib.ExitStack', 'ExitStack', ({}, {}), '()', False, 'from contextlib import ExitStack\n'), ((91, 24, 91, 76), 'rasa_addons.importers.BotfrontFileImporter', 'BotfrontFileImporter', ({(91, 45, 91, 51): 'config', (91, 53, 91, 59): 'domain', (91, 61, 91, 75): 'training_files'}, {}), '(config, domain, training_files)', False, 'from rasa_addons.importers import BotfrontFileImporter\n'), ((168, 28, 168, 66), 'rasa.model.model_fingerprint', 'model.model_fingerprint', ({(168, 52, 168, 65): 'file_importer'}, {}), '(file_importer)', False, 'from rasa import model\n'), ((172, 33, 174, 9), 'rasa.model.should_retrain', 'model.should_retrain', ({(173, 12, 173, 27): 'new_fingerprint', (173, 29, 173, 38): 'old_model', (173, 40, 173, 50): 'train_path'}, {}), '(new_fingerprint, old_model, train_path)', False, 'from rasa import model\n'), ((186, 8, 186, 102), 'rasa.cli.utils.print_color', 'print_color', (), '', False, 'from rasa.cli.utils import print_success, print_warning, print_error, bcolors, print_color\n'), ((202, 15, 207, 9), 'rasa.model.package_model', 'model.package_model', (), '', False, 'from rasa import model\n'), ((226, 40, 226, 69), 'rasa.model.FingerprintComparisonResult', 'FingerprintComparisonResult', ({}, {}), '()', False, 'from rasa.model import FingerprintComparisonResult\n'), ((260, 8, 263, 9), 'rasa.cli.utils.print_color', 'print_color', (), '', False, 'from rasa.cli.utils import print_success, print_warning, print_error, bcolors, print_color\n'), ((322, 8, 325, 9), 'rasa.cli.utils.print_error', 'print_error', ({(323, 12, 324, 114): '"""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."""'}, {}), '(\n "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."\n )', False, 'from rasa.cli.utils import print_success, print_warning, print_error, bcolors, print_color\n'), ((329, 8, 332, 9), 'rasa.cli.utils.print_error', 'print_error', ({(330, 12, 331, 69): '"""No stories given. Please provide stories in order to train a Rasa Core model using the \'--stories\' argument."""'}, {}), '(\n "No stories given. Please provide stories in order to train a Rasa Core model using the \'--stories\' argument."\n )', False, 'from rasa.cli.utils import print_success, print_warning, print_error, bcolors, print_color\n'), ((355, 9, 355, 20), 'contextlib.ExitStack', 'ExitStack', ({}, {}), '()', False, 'from contextlib import ExitStack\n'), ((364, 8, 364, 67), 'rasa.cli.utils.print_color', 'print_color', (), '', False, 'from rasa.cli.utils import print_success, print_warning, print_error, bcolors, print_color\n'), ((375, 8, 375, 75), 'rasa.cli.utils.print_color', 'print_color', (), '', False, 'from rasa.cli.utils import print_success, print_warning, print_error, bcolors, print_color\n'), ((440, 8, 443, 9), 'rasa.cli.utils.print_error', 'print_error', ({(441, 12, 442, 58): '"""No NLU data given. Please provide NLU data in order to train a Rasa NLU model using the \'--nlu\' argument."""'}, {}), '(\n "No NLU data given. Please provide NLU data in order to train a Rasa NLU model using the \'--nlu\' argument."\n )', False, 'from rasa.cli.utils import print_success, print_warning, print_error, bcolors, print_color\n'), ((453, 8, 457, 9), 'rasa.cli.utils.print_error', 'print_error', ({(454, 12, 456, 57): '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."""'}, {}), '(\n 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."\n )', False, 'from rasa.cli.utils import print_success, print_warning, print_error, bcolors, print_color\n'), ((481, 9, 481, 20), 'contextlib.ExitStack', 'ExitStack', ({}, {}), '()', False, 'from contextlib import ExitStack\n'), ((506, 8, 506, 74), 'rasa.cli.utils.print_color', 'print_color', (), '', False, 'from rasa.cli.utils import print_success, print_warning, print_error, bcolors, print_color\n'), ((36, 19, 36, 43), 'asyncio.get_event_loop', 'asyncio.get_event_loop', ({}, {}), '()', False, 'import asyncio\n'), ((211, 18, 211, 44), 'os.path.abspath', 'os.path.abspath', ({(211, 34, 211, 43): 'old_model'}, {}), '(old_model)', False, 'import os\n'), ((237, 8, 242, 9), 'rasa.cli.utils.print_color', 'print_color', (), '', False, 'from rasa.cli.utils import print_success, print_warning, print_error, bcolors, print_color\n'), ((245, 8, 248, 9), 'rasa.cli.utils.print_color', 'print_color', (), '', False, 'from rasa.cli.utils import print_success, print_warning, print_error, bcolors, print_color\n'), ((380, 19, 386, 13), 'rasa.model.package_model', 'model.package_model', (), '', False, 'from rasa import model\n'), ((512, 19, 518, 13), 'rasa.model.package_model', 'model.package_model', (), '', False, 'from rasa import model\n'), ((38, 19, 38, 43), 'asyncio.new_event_loop', 'asyncio.new_event_loop', ({}, {}), '()', False, 'import asyncio\n'), ((39, 12, 39, 40), 'asyncio.set_event_loop', 'asyncio.set_event_loop', ({(39, 35, 39, 39): 'loop'}, {}), '(loop)', False, 'import asyncio\n'), ((87, 59, 87, 77), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ({}, {}), '()', False, 'import tempfile\n'), ((243, 14, 243, 75), 'rasa.model.update_model_with_new_domain', 'model.update_model_with_new_domain', ({(243, 49, 243, 62): 'file_importer', (243, 64, 243, 74): 'train_path'}, {}), '(file_importer, train_path)', False, 'from rasa import model\n'), ((379, 36, 379, 74), 'rasa.model.model_fingerprint', 'model.model_fingerprint', ({(379, 60, 379, 73): 'file_importer'}, {}), '(file_importer)', False, 'from rasa import model\n'), ((510, 36, 510, 74), 'rasa.model.model_fingerprint', 'model.model_fingerprint', ({(510, 60, 510, 73): 'file_importer'}, {}), '(file_importer)', False, 'from rasa import model\n'), ((361, 64, 361, 82), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ({}, {}), '()', False, 'import tempfile\n'), ((371, 24, 371, 81), 'os.path.join', 'os.path.join', ({(371, 37, 371, 48): '_train_path', (371, 50, 371, 80): 'DEFAULT_CORE_SUBDIRECTORY_NAME'}, {}), '(_train_path, DEFAULT_CORE_SUBDIRECTORY_NAME)', False, 'import os\n'), ((490, 64, 490, 82), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ({}, {}), '()', False, 'import tempfile\n')]
Jahidul007/Python-Bootcamp
coding_intereview/1475. Final Prices With a Special Discount in a Shop.py
3c870587465ff66c2c1871c8d3c4eea72463abda
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
[]
timgates42/denite.nvim
rplugin/python3/denite/ui/default.py
12a9b5456f5a4600afeb0ba284ce1098bd35e501
# ============================================================================ # FILE: default.py # AUTHOR: Shougo Matsushita <Shougo.Matsu at gmail.com> # 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'], })
[((177, 11, 177, 73), 're.search', 're.search', ({(177, 21, 177, 41): '"""\\\\[Command Line\\\\]$"""', (177, 43, 177, 72): 'self._vim.current.buffer.name'}, {}), "('\\\\[Command Line\\\\]$', self._vim.current.buffer.name)", False, 'import re\n'), ((814, 8, 814, 29), 'denite.util.clearmatch', 'clearmatch', ({(814, 19, 814, 28): 'self._vim'}, {}), '(self._vim)', False, 'from denite.util import echo, error, clearmatch, regex_convert_py_vim\n'), ((64, 27, 64, 48), 'denite.parent.SyncParent', 'SyncParent', ({(64, 38, 64, 47): 'self._vim'}, {}), '(self._vim)', False, 'from denite.parent import SyncParent\n'), ((227, 43, 227, 73), 'denite.ui.map.do_map', 'do_map', ({(227, 50, 227, 54): 'self', (227, 56, 227, 68): '"""quick_move"""', (227, 70, 227, 72): '[]'}, {}), "(self, 'quick_move', [])", False, 'from denite.ui.map import do_map\n'), ((231, 12, 231, 50), 'denite.ui.map.do_map', 'do_map', ({(231, 19, 231, 23): 'self', (231, 25, 231, 45): '"""open_filter_buffer"""', (231, 47, 231, 49): '[]'}, {}), "(self, 'open_filter_buffer', [])", False, 'from denite.ui.map import do_map\n'), ((715, 13, 715, 60), 're.match', 're.match', ({(715, 22, 715, 30): '"""\\\\+\\\\d+"""', (715, 32, 715, 59): "self._context['cursor_pos']"}, {}), "('\\\\+\\\\d+', self._context['cursor_pos'])", False, 'import re\n'), ((209, 16, 209, 49), 'denite.util.error', 'error', ({(209, 22, 209, 31): 'self._vim', (209, 33, 209, 48): '"""Empty sources"""'}, {}), "(self._vim, 'Empty sources')", False, 'from denite.util import echo, error, clearmatch, regex_convert_py_vim\n'), ((610, 29, 610, 58), 're.search', 're.search', ({(610, 39, 610, 51): '"""[^a-zA-Z]"""', (610, 53, 610, 57): 'name'}, {}), "('[^a-zA-Z]', name)", False, 'import re\n'), ((609, 26, 609, 69), 're.sub', 're.sub', ({(609, 33, 609, 55): '"""([a-zA-Z])[a-zA-Z]+"""', (609, 57, 609, 62): '"""\\\\1"""', (609, 64, 609, 68): 'name'}, {}), "('([a-zA-Z])[a-zA-Z]+', '\\\\1', name)", False, 'import re\n'), ((718, 13, 718, 59), 're.match', 're.match', ({(718, 22, 718, 29): '"""-\\\\d+"""', (718, 31, 718, 58): "self._context['cursor_pos']"}, {}), "('-\\\\d+', self._context['cursor_pos'])", False, 'import re\n'), ((517, 28, 517, 71), 'denite.util.regex_convert_py_vim', 'regex_convert_py_vim', ({(517, 49, 517, 70): 'self._matched_pattern'}, {}), '(self._matched_pattern)', False, 'from denite.util import echo, error, clearmatch, regex_convert_py_vim\n')]
yuanz271/PyDSTool
PyDSTool/core/context_managers.py
886c143cdd192aea204285f3a1cb4968c763c646
# -*- 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 Marc Abramowitz, 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, "")
[((43, 17, 43, 70), 'functools.partial', 'functools.partial', ({(43, 35, 43, 57): '_stdchannel_redirected', (43, 59, 43, 69): 'sys.stdout'}, {}), '(_stdchannel_redirected, sys.stdout)', False, 'import functools\n'), ((44, 17, 44, 70), 'functools.partial', 'functools.partial', ({(44, 35, 44, 57): '_stdchannel_redirected', (44, 59, 44, 69): 'sys.stderr'}, {}), '(_stdchannel_redirected, sys.stderr)', False, 'import functools\n'), ((45, 15, 45, 66), 'functools.partial', 'functools.partial', ({(45, 33, 45, 55): '_stdchannel_redirected', (45, 57, 45, 61): 'None', (45, 63, 45, 65): '""""""'}, {}), "(_stdchannel_redirected, None, '')", False, 'import functools\n')]
Muzzy73/pos_kiosk
pos_kiosk/hooks.py
1ed42cfaeb15f009293b76d05dd85bd322b42f03
# -*- 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 protected]" 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 # }
[]
gcouti/pypagAI
pypagai/models/model_lstm.py
d08fac95361dcc036d890a88cb86ce090322a612
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'])
[((14, 17, 14, 44), 'pypagai.models.base.KerasModel.default_config', 'KerasModel.default_config', ({}, {}), '()', False, 'from pypagai.models.base import KerasModel\n'), ((25, 16, 25, 59), 'keras.Input', 'Input', (), '', False, 'from keras import Model, Input\n'), ((26, 19, 26, 65), 'keras.Input', 'Input', (), '', False, 'from keras import Model, Input\n'), ((28, 15, 28, 46), 'keras.layers.concatenate', 'concatenate', ({(28, 27, 28, 44): '[story, question]'}, {}), '([story, question])', False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((35, 22, 35, 71), 'keras.Model', 'Model', (), '', False, 'from keras import Model, Input\n'), ((46, 17, 46, 44), 'pypagai.models.base.KerasModel.default_config', 'KerasModel.default_config', ({}, {}), '()', False, 'from pypagai.models.base import KerasModel\n'), ((58, 16, 58, 59), 'keras.Input', 'Input', (), '', False, 'from keras import Model, Input\n'), ((59, 19, 59, 65), 'keras.Input', 'Input', (), '', False, 'from keras import Model, Input\n'), ((67, 15, 67, 59), 'keras.layers.concatenate', 'concatenate', (), '', False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((72, 22, 72, 71), 'keras.Model', 'Model', (), '', False, 'from keras import Model, Input\n'), ((83, 17, 83, 44), 'pypagai.models.base.KerasModel.default_config', 'KerasModel.default_config', ({}, {}), '()', False, 'from pypagai.models.base import KerasModel\n'), ((95, 16, 95, 59), 'keras.Input', 'Input', (), '', False, 'from keras import Model, Input\n'), ((96, 19, 96, 65), 'keras.Input', 'Input', (), '', False, 'from keras import Model, Input\n'), ((110, 15, 110, 59), 'keras.layers.concatenate', 'concatenate', (), '', False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((115, 22, 115, 71), 'keras.Model', 'Model', (), '', False, 'from keras import Model, Input\n'), ((30, 15, 30, 30), 'keras.layers.Permute', 'Permute', ({(30, 23, 30, 29): '(2, 1)'}, {}), '((2, 1))', False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((32, 19, 32, 67), 'keras.layers.LSTM', 'LSTM', (), '', False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((33, 19, 33, 64), 'keras.layers.Dense', 'Dense', (), '', False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((61, 19, 61, 50), 'keras.layers.Embedding', 'Embedding', ({(61, 29, 61, 45): 'self._vocab_size', (61, 47, 61, 49): '64'}, {}), '(self._vocab_size, 64)', False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((62, 19, 62, 31), 'keras.layers.Dropout', 'Dropout', ({(62, 27, 62, 30): '0.3'}, {}), '(0.3)', False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((64, 22, 64, 53), 'keras.layers.Embedding', 'Embedding', ({(64, 32, 64, 48): 'self._vocab_size', (64, 50, 64, 52): '64'}, {}), '(self._vocab_size, 64)', False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((65, 22, 65, 34), 'keras.layers.Dropout', 'Dropout', ({(65, 30, 65, 33): '0.3'}, {}), '(0.3)', False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((69, 19, 69, 67), 'keras.layers.LSTM', 'LSTM', (), '', False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((70, 19, 70, 64), 'keras.layers.Dense', 'Dense', (), '', False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((98, 19, 98, 50), 'keras.layers.Embedding', 'Embedding', ({(98, 29, 98, 45): 'self._vocab_size', (98, 47, 98, 49): '64'}, {}), '(self._vocab_size, 64)', False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((99, 19, 99, 55), 'keras.layers.Convolution1D', 'Convolution1D', (), '', False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((100, 19, 100, 55), 'keras.layers.Convolution1D', 'Convolution1D', (), '', False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((101, 19, 101, 55), 'keras.layers.Convolution1D', 'Convolution1D', (), '', False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((104, 22, 104, 53), 'keras.layers.Embedding', 'Embedding', ({(104, 32, 104, 48): 'self._vocab_size', (104, 50, 104, 52): '64'}, {}), '(self._vocab_size, 64)', False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((105, 22, 105, 58), 'keras.layers.Convolution1D', 'Convolution1D', (), '', False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((106, 22, 106, 58), 'keras.layers.Convolution1D', 'Convolution1D', (), '', False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((107, 22, 107, 58), 'keras.layers.Convolution1D', 'Convolution1D', (), '', False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((112, 19, 112, 67), 'keras.layers.LSTM', 'LSTM', (), '', False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((113, 19, 113, 64), 'keras.layers.Dense', 'Dense', (), '', False, 'from keras.layers import Dense, concatenate, LSTM, Reshape, Permute, Embedding, Dropout, Convolution1D, Flatten\n'), ((36, 38, 36, 51), 'keras.optimizers.Adam', 'Adam', (), '', False, 'from keras.optimizers import Adam\n'), ((73, 38, 73, 51), 'keras.optimizers.Adam', 'Adam', (), '', False, 'from keras.optimizers import Adam\n'), ((116, 38, 116, 51), 'keras.optimizers.Adam', 'Adam', (), '', False, 'from keras.optimizers import Adam\n')]
joelouismarino/variational_rl
lib/variables/latent_variables/__init__.py
11dc14bfb56f3ebbfccd5de206b78712a8039a9a
from .fully_connected import FullyConnectedLatentVariable from .convolutional import ConvolutionalLatentVariable
[]
lpj0822/image_point_cloud_det
easyai/model/backbone/cls/pnasnet.py
7b20e2f42f3f2ff4881485da58ad188a1f0d0e0f
#!/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
[((39, 17, 46, 75), 'easyai.model.base_block.utility.utility_block.ConvBNActivationBlock', 'ConvBNActivationBlock', (), '', False, 'from easyai.model.base_block.utility.utility_block import ConvBNActivationBlock\n')]
cugxy/map_download
map_download/cmd/TerrainDownloader.py
02142b33edb2bc163f7ae971f443efe84c13e029
# -*- 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
[((52, 11, 52, 36), 'os.path.exists', 'os.path.exists', ({(52, 26, 52, 35): 'file_path'}, {}), '(file_path)', False, 'import os\n'), ((97, 23, 97, 73), 'map_download.cmd.BaseDownloader.latlng2tile_terrain', 'latlng2tile_terrain', ({(97, 43, 97, 55): 'bbox.min_lat', (97, 57, 97, 69): 'bbox.min_lng', (97, 71, 97, 72): 'z'}, {}), '(bbox.min_lat, bbox.min_lng, z)', False, 'from map_download.cmd.BaseDownloader import DownloadEngine, BaseDownloaderThread, latlng2tile_terrain, BoundBox\n'), ((98, 23, 98, 73), 'map_download.cmd.BaseDownloader.latlng2tile_terrain', 'latlng2tile_terrain', ({(98, 43, 98, 55): 'bbox.max_lat', (98, 57, 98, 69): 'bbox.max_lng', (98, 71, 98, 72): 'z'}, {}), '(bbox.max_lat, bbox.max_lng, z)', False, 'from map_download.cmd.BaseDownloader import DownloadEngine, BaseDownloaderThread, latlng2tile_terrain, BoundBox\n'), ((289, 17, 289, 42), 'logging.getLogger', 'logging.getLogger', ({(289, 35, 289, 41): '"""down"""'}, {}), "('down')", False, 'import logging\n'), ((23, 19, 23, 61), 'requests.get', 'requests.get', (), '', False, 'import requests\n'), ((55, 20, 55, 46), 'os.path.dirname', 'os.path.dirname', ({(55, 36, 55, 45): 'file_path'}, {}), '(file_path)', False, 'import os\n'), ((99, 15, 99, 32), 'math.floor', 'math.floor', ({(99, 26, 99, 31): 'min_x'}, {}), '(min_x)', False, 'import math\n'), ((99, 34, 99, 51), 'math.floor', 'math.floor', ({(99, 45, 99, 50): 'min_y'}, {}), '(min_y)', False, 'import math\n'), ((242, 19, 242, 57), 'os.path.join', 'os.path.join', ({(242, 32, 242, 45): 'self.root_dir', (242, 47, 242, 56): '"""Terrain"""'}, {}), "(self.root_dir, 'Terrain')", False, 'import os\n'), ((243, 12, 243, 44), 'os.makedirs', 'os.makedirs', (), '', False, 'import os\n'), ((244, 29, 244, 61), 'os.path.join', 'os.path.join', ({(244, 42, 244, 46): '_dir', (244, 48, 244, 60): '"""layer.json"""'}, {}), "(_dir, 'layer.json')", False, 'import os\n'), ((292, 24, 292, 70), 'logging.Formatter', 'logging.Formatter', ({(292, 42, 292, 69): '"""%(levelname)s-%(message)s"""'}, {}), "('%(levelname)s-%(message)s')", False, 'import logging\n'), ((293, 19, 293, 42), 'logging.StreamHandler', 'logging.StreamHandler', ({}, {}), '()', False, 'import logging\n'), ((294, 23, 294, 53), 'os.path.join', 'os.path.join', ({(294, 36, 294, 40): 'root', (294, 42, 294, 52): '"""down.log"""'}, {}), "(root, 'down.log')", False, 'import os\n'), ((295, 24, 295, 53), 'logging.FileHandler', 'logging.FileHandler', ({(295, 44, 295, 52): 'log_file'}, {}), '(log_file)', False, 'import logging\n'), ((306, 19, 306, 85), 'map_download.cmd.BaseDownloader.BoundBox', 'BoundBox', ({(306, 28, 306, 35): 'max_lat', (306, 37, 306, 44): 'max_lng', (306, 46, 306, 53): 'min_lat', (306, 55, 306, 62): 'min_lng', (306, 64, 306, 74): 'start_zoom', (306, 76, 306, 84): 'end_zoom'}, {}), '(max_lat, max_lng, min_lat, min_lng, start_zoom, end_zoom)', False, 'from map_download.cmd.BaseDownloader import DownloadEngine, BaseDownloaderThread, latlng2tile_terrain, BoundBox\n'), ((309, 12, 309, 29), 'time.sleep', 'time.sleep', ({(309, 23, 309, 28): '(10000)'}, {}), '(10000)', False, 'import time\n'), ((29, 12, 29, 25), 'time.sleep', 'time.sleep', ({(29, 23, 29, 24): '(3)'}, {}), '(3)', False, 'import time\n'), ((67, 23, 67, 79), 'requests.get', 'requests.get', (), '', False, 'import requests\n'), ((99, 53, 99, 69), 'math.ceil', 'math.ceil', ({(99, 63, 99, 68): 'max_x'}, {}), '(max_x)', False, 'import math\n'), ((99, 75, 99, 91), 'math.ceil', 'math.ceil', ({(99, 85, 99, 90): 'max_y'}, {}), '(max_y)', False, 'import math\n'), ((246, 16, 246, 39), 'json.dump', 'json.dump', ({(246, 26, 246, 35): 'metadatas', (246, 37, 246, 38): 'f'}, {}), '(metadatas, f)', False, 'import json\n'), ((71, 16, 71, 29), 'time.sleep', 'time.sleep', ({(71, 27, 71, 28): '(3)'}, {}), '(3)', False, 'import time\n'), ((263, 24, 263, 40), 'time.sleep', 'time.sleep', ({(263, 35, 263, 39): '(0.01)'}, {}), '(0.01)', False, 'import time\n')]

Dataset Card for "the-stack-python_api-10k"

More Information needed

Downloads last month
32
Edit dataset card