code
stringlengths
2
1.05M
repo_name
stringlengths
5
104
path
stringlengths
4
251
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
from django import forms from django.core.exceptions import ValidationError from django.core.validators import validate_slug from django.db import models from django.utils import simplejson as json from django.utils.text import capfirst from django.utils.translation import ugettext_lazy as _ from philo.forms.fields import JSONFormField from philo.utils.registry import RegistryIterator from philo.validators import TemplateValidator, json_validator #from philo.models.fields.entities import * class TemplateField(models.TextField): """A :class:`TextField` which is validated with a :class:`.TemplateValidator`. ``allow``, ``disallow``, and ``secure`` will be passed into the validator's construction.""" def __init__(self, allow=None, disallow=None, secure=True, *args, **kwargs): super(TemplateField, self).__init__(*args, **kwargs) self.validators.append(TemplateValidator(allow, disallow, secure)) class JSONDescriptor(object): def __init__(self, field): self.field = field def __get__(self, instance, owner): if instance is None: raise AttributeError # ? if self.field.name not in instance.__dict__: json_string = getattr(instance, self.field.attname) instance.__dict__[self.field.name] = json.loads(json_string) return instance.__dict__[self.field.name] def __set__(self, instance, value): instance.__dict__[self.field.name] = value setattr(instance, self.field.attname, json.dumps(value)) def __delete__(self, instance): del(instance.__dict__[self.field.name]) setattr(instance, self.field.attname, json.dumps(None)) class JSONField(models.TextField): """A :class:`TextField` which stores its value on the model instance as a python object and stores its value in the database as JSON. Validated with :func:`.json_validator`.""" default_validators = [json_validator] def get_attname(self): return "%s_json" % self.name def contribute_to_class(self, cls, name): super(JSONField, self).contribute_to_class(cls, name) setattr(cls, name, JSONDescriptor(self)) models.signals.pre_init.connect(self.fix_init_kwarg, sender=cls) def fix_init_kwarg(self, sender, args, kwargs, **signal_kwargs): # Anything passed in as self.name is assumed to come from a serializer and # will be treated as a json string. if self.name in kwargs: value = kwargs.pop(self.name) # Hack to handle the xml serializer's handling of "null" if value is None: value = 'null' kwargs[self.attname] = value def formfield(self, *args, **kwargs): kwargs["form_class"] = JSONFormField return super(JSONField, self).formfield(*args, **kwargs) class SlugMultipleChoiceField(models.Field): """Stores a selection of multiple items with unique slugs in the form of a comma-separated list. Also knows how to correctly handle :class:`RegistryIterator`\ s passed in as choices.""" __metaclass__ = models.SubfieldBase description = _("Comma-separated slug field") def get_internal_type(self): return "TextField" def to_python(self, value): if not value: return [] if isinstance(value, list): return value return value.split(',') def get_prep_value(self, value): return ','.join(value) def formfield(self, **kwargs): # This is necessary because django hard-codes TypedChoiceField for things with choices. defaults = { 'widget': forms.CheckboxSelectMultiple, 'choices': self.get_choices(include_blank=False), 'label': capfirst(self.verbose_name), 'required': not self.blank, 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() for k in kwargs.keys(): if k not in ('coerce', 'empty_value', 'choices', 'required', 'widget', 'label', 'initial', 'help_text', 'error_messages', 'show_hidden_initial'): del kwargs[k] defaults.update(kwargs) form_class = forms.TypedMultipleChoiceField return form_class(**defaults) def validate(self, value, model_instance): invalid_values = [] for val in value: try: validate_slug(val) except ValidationError: invalid_values.append(val) if invalid_values: # should really make a custom message. raise ValidationError(self.error_messages['invalid_choice'] % invalid_values) def _get_choices(self): if isinstance(self._choices, RegistryIterator): return self._choices.copy() elif hasattr(self._choices, 'next'): choices, self._choices = itertools.tee(self._choices) return choices else: return self._choices choices = property(_get_choices) try: from south.modelsinspector import add_introspection_rules except ImportError: pass else: add_introspection_rules([], ["^philo\.models\.fields\.SlugMultipleChoiceField"]) add_introspection_rules([], ["^philo\.models\.fields\.TemplateField"]) add_introspection_rules([], ["^philo\.models\.fields\.JSONField"])
ithinksw/philo
philo/models/fields/__init__.py
Python
isc
4,971
import hashlib import json import logging import os import subprocess import sys import time from collections import defaultdict from shutil import copy from shutil import copyfile from shutil import copystat from shutil import copytree from tempfile import mkdtemp import boto3 import botocore import yaml import sys from .helpers import archive from .helpers import get_environment_variable_value from .helpers import LambdaContext from .helpers import mkdir from .helpers import read from .helpers import timestamp ARN_PREFIXES = { "cn-north-1": "aws-cn", "cn-northwest-1": "aws-cn", "us-gov-west-1": "aws-us-gov", } log = logging.getLogger(__name__) def load_source(module_name, module_path): """Loads a python module from the path of the corresponding file.""" if sys.version_info[0] == 3 and sys.version_info[1] >= 5: import importlib.util spec = importlib.util.spec_from_file_location(module_name, module_path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) elif sys.version_info[0] == 3 and sys.version_info[1] < 5: import importlib.machinery loader = importlib.machinery.SourceFileLoader(module_name, module_path) module = loader.load_module() return module def cleanup_old_versions( src, keep_last_versions, config_file="config.yaml", profile_name=None, ): """Deletes old deployed versions of the function in AWS Lambda. Won't delete $Latest and any aliased version :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param int keep_last_versions: The number of recent versions to keep and not delete """ if keep_last_versions <= 0: print("Won't delete all versions. Please do this manually") else: path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) profile_name = cfg.get("profile") aws_access_key_id = cfg.get("aws_access_key_id") aws_secret_access_key = cfg.get("aws_secret_access_key") client = get_client( "lambda", profile_name, aws_access_key_id, aws_secret_access_key, cfg.get("region"), ) response = client.list_versions_by_function( FunctionName=cfg.get("function_name"), ) versions = response.get("Versions") if len(response.get("Versions")) < keep_last_versions: print("Nothing to delete. (Too few versions published)") else: version_numbers = [ elem.get("Version") for elem in versions[1:-keep_last_versions] ] for version_number in version_numbers: try: client.delete_function( FunctionName=cfg.get("function_name"), Qualifier=version_number, ) except botocore.exceptions.ClientError as e: print(f"Skipping Version {version_number}: {e}") def deploy( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, preserve_vpc=False, ): """Deploys a new function to AWS Lambda. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Copy all the pip dependencies required to run your code into a temporary # folder then add the handler file in the root of this directory. # Zip the contents of this folder into a single file and output to the dist # directory. path_to_zip_file = build( src, config_file=config_file, requirements=requirements, local_package=local_package, ) existing_config = get_function_config(cfg) if existing_config: update_function( cfg, path_to_zip_file, existing_config, preserve_vpc=preserve_vpc ) else: create_function(cfg, path_to_zip_file) def deploy_s3( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, preserve_vpc=False, ): """Deploys a new function via AWS S3. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Copy all the pip dependencies required to run your code into a temporary # folder then add the handler file in the root of this directory. # Zip the contents of this folder into a single file and output to the dist # directory. path_to_zip_file = build( src, config_file=config_file, requirements=requirements, local_package=local_package, ) use_s3 = True s3_file = upload_s3(cfg, path_to_zip_file, use_s3) existing_config = get_function_config(cfg) if existing_config: update_function( cfg, path_to_zip_file, existing_config, use_s3=use_s3, s3_file=s3_file, preserve_vpc=preserve_vpc, ) else: create_function(cfg, path_to_zip_file, use_s3=use_s3, s3_file=s3_file) def upload( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, ): """Uploads a new function to AWS S3. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Copy all the pip dependencies required to run your code into a temporary # folder then add the handler file in the root of this directory. # Zip the contents of this folder into a single file and output to the dist # directory. path_to_zip_file = build( src, config_file=config_file, requirements=requirements, local_package=local_package, ) upload_s3(cfg, path_to_zip_file) def invoke( src, event_file="event.json", config_file="config.yaml", profile_name=None, verbose=False, ): """Simulates a call to your function. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str alt_event: An optional argument to override which event file to use. :param bool verbose: Whether to print out verbose details. """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Set AWS_PROFILE environment variable based on `--profile` option. if profile_name: os.environ["AWS_PROFILE"] = profile_name # Load environment variables from the config file into the actual # environment. env_vars = cfg.get("environment_variables") if env_vars: for key, value in env_vars.items(): os.environ[key] = get_environment_variable_value(value) # Load and parse event file. path_to_event_file = os.path.join(src, event_file) event = read(path_to_event_file, loader=json.loads) # Tweak to allow module to import local modules try: sys.path.index(src) except ValueError: sys.path.append(src) handler = cfg.get("handler") # Inspect the handler string (<module>.<function name>) and translate it # into a function we can execute. fn = get_callable_handler_function(src, handler) timeout = cfg.get("timeout") if timeout: context = LambdaContext(cfg.get("function_name"), timeout) else: context = LambdaContext(cfg.get("function_name")) start = time.time() results = fn(event, context) end = time.time() print("{0}".format(results)) if verbose: print( "\nexecution time: {:.8f}s\nfunction execution " "timeout: {:2}s".format(end - start, cfg.get("timeout", 15)) ) def init(src, minimal=False): """Copies template files to a given directory. :param str src: The path to output the template lambda project files. :param bool minimal: Minimal possible template files (excludes event.json). """ templates_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), "project_templates", ) for filename in os.listdir(templates_path): if (minimal and filename == "event.json") or filename.endswith(".pyc"): continue dest_path = os.path.join(templates_path, filename) if not os.path.isdir(dest_path): copy(dest_path, src) def build( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, ): """Builds the file bundle. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py). :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ # Load and parse the config file. path_to_config_file = os.path.join(src, config_file) cfg = read_cfg(path_to_config_file, profile_name) # Get the absolute path to the output directory and create it if it doesn't # already exist. dist_directory = cfg.get("dist_directory", "dist") path_to_dist = os.path.join(src, dist_directory) mkdir(path_to_dist) # Combine the name of the Lambda function with the current timestamp to use # for the output filename. function_name = cfg.get("function_name") output_filename = "{0}-{1}.zip".format(timestamp(), function_name) path_to_temp = mkdtemp(prefix="aws-lambda") pip_install_to_target( path_to_temp, requirements=requirements, local_package=local_package, ) # Hack for Zope. if "zope" in os.listdir(path_to_temp): print( "Zope packages detected; fixing Zope package paths to " "make them importable.", ) # Touch. with open(os.path.join(path_to_temp, "zope/__init__.py"), "wb"): pass # Gracefully handle whether ".zip" was included in the filename or not. output_filename = ( "{0}.zip".format(output_filename) if not output_filename.endswith(".zip") else output_filename ) # Allow definition of source code directories we want to build into our # zipped package. build_config = defaultdict(**cfg.get("build", {})) build_source_directories = build_config.get("source_directories", "") build_source_directories = ( build_source_directories if build_source_directories is not None else "" ) source_directories = [ d.strip() for d in build_source_directories.split(",") ] files = [] for filename in os.listdir(src): if os.path.isfile(filename): if filename == ".DS_Store": continue if filename == config_file: continue print("Bundling: %r" % filename) files.append(os.path.join(src, filename)) elif os.path.isdir(filename) and filename in source_directories: print("Bundling directory: %r" % filename) files.append(os.path.join(src, filename)) # "cd" into `temp_path` directory. os.chdir(path_to_temp) for f in files: if os.path.isfile(f): _, filename = os.path.split(f) # Copy handler file into root of the packages folder. copyfile(f, os.path.join(path_to_temp, filename)) copystat(f, os.path.join(path_to_temp, filename)) elif os.path.isdir(f): src_path_length = len(src) + 1 destination_folder = os.path.join( path_to_temp, f[src_path_length:] ) copytree(f, destination_folder) # Zip them together into a single file. # TODO: Delete temp directory created once the archive has been compiled. path_to_zip_file = archive("./", path_to_dist, output_filename) return path_to_zip_file def get_callable_handler_function(src, handler): """Translate a string of the form "module.function" into a callable function. :param str src: The path to your Lambda project containing a valid handler file. :param str handler: A dot delimited string representing the `<module>.<function name>`. """ # "cd" into `src` directory. os.chdir(src) module_name, function_name = handler.split(".") filename = get_handler_filename(handler) path_to_module_file = os.path.join(src, filename) module = load_source(module_name, path_to_module_file) return getattr(module, function_name) def get_handler_filename(handler): """Shortcut to get the filename from the handler string. :param str handler: A dot delimited string representing the `<module>.<function name>`. """ module_name, _ = handler.split(".") return "{0}.py".format(module_name) def _install_packages(path, packages): """Install all packages listed to the target directory. Ignores any package that includes Python itself and python-lambda as well since its only needed for deploying and not running the code :param str path: Path to copy installed pip packages to. :param list packages: A list of packages to be installed via pip. """ def _filter_blacklist(package): blacklist = ["-i", "#", "Python==", "python-lambda=="] return all(package.startswith(entry) is False for entry in blacklist) filtered_packages = filter(_filter_blacklist, packages) for package in filtered_packages: if package.startswith("-e "): package = package.replace("-e ", "") print("Installing {package}".format(package=package)) subprocess.check_call( [ sys.executable, "-m", "pip", "install", package, "-t", path, "--ignore-installed", ] ) print( "Install directory contents are now: {directory}".format( directory=os.listdir(path) ) ) def pip_install_to_target(path, requirements=None, local_package=None): """For a given active virtualenv, gather all installed pip packages then copy (re-install) them to the path provided. :param str path: Path to copy installed pip packages to. :param str requirements: If set, only the packages in the supplied requirements file are installed. If not set then installs all packages found via pip freeze. :param str local_package: The path to a local package with should be included in the deploy as well (and/or is not available on PyPi) """ packages = [] if not requirements: print("Gathering pip packages") pkgStr = subprocess.check_output( [sys.executable, "-m", "pip", "freeze"] ) packages.extend(pkgStr.decode("utf-8").splitlines()) else: if os.path.exists(requirements): print("Gathering requirement packages") data = read(requirements) packages.extend(data.splitlines()) if not packages: print("No dependency packages installed!") if local_package is not None: if not isinstance(local_package, (list, tuple)): local_package = [local_package] for l_package in local_package: packages.append(l_package) _install_packages(path, packages) def get_role_name(region, account_id, role): """Shortcut to insert the `account_id` and `role` into the iam string.""" prefix = ARN_PREFIXES.get(region, "aws") return "arn:{0}:iam::{1}:role/{2}".format(prefix, account_id, role) def get_account_id( profile_name, aws_access_key_id, aws_secret_access_key, region=None, ): """Query STS for a users' account_id""" client = get_client( "sts", profile_name, aws_access_key_id, aws_secret_access_key, region, ) return client.get_caller_identity().get("Account") def get_client( client, profile_name, aws_access_key_id, aws_secret_access_key, region=None, ): """Shortcut for getting an initialized instance of the boto3 client.""" boto3.setup_default_session( profile_name=profile_name, aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, region_name=region, ) return boto3.client(client) def create_function(cfg, path_to_zip_file, use_s3=False, s3_file=None): """Register and upload a function to AWS Lambda.""" print("Creating your new Lambda function") byte_stream = read(path_to_zip_file, binary_file=True) profile_name = cfg.get("profile") aws_access_key_id = cfg.get("aws_access_key_id") aws_secret_access_key = cfg.get("aws_secret_access_key") account_id = get_account_id( profile_name, aws_access_key_id, aws_secret_access_key, cfg.get("region",), ) role = get_role_name( cfg.get("region"), account_id, cfg.get("role", "lambda_basic_execution"), ) client = get_client( "lambda", profile_name, aws_access_key_id, aws_secret_access_key, cfg.get("region"), ) # Do we prefer development variable over config? buck_name = os.environ.get("S3_BUCKET_NAME") or cfg.get("bucket_name") func_name = os.environ.get("LAMBDA_FUNCTION_NAME") or cfg.get( "function_name" ) print("Creating lambda function with name: {}".format(func_name)) if use_s3: kwargs = { "FunctionName": func_name, "Runtime": cfg.get("runtime", "python2.7"), "Role": role, "Handler": cfg.get("handler"), "Code": { "S3Bucket": "{}".format(buck_name), "S3Key": "{}".format(s3_file), }, "Description": cfg.get("description", ""), "Timeout": cfg.get("timeout", 15), "MemorySize": cfg.get("memory_size", 512), "VpcConfig": { "SubnetIds": cfg.get("subnet_ids", []), "SecurityGroupIds": cfg.get("security_group_ids", []), }, "Publish": True, } else: kwargs = { "FunctionName": func_name, "Runtime": cfg.get("runtime", "python2.7"), "Role": role, "Handler": cfg.get("handler"), "Code": {"ZipFile": byte_stream}, "Description": cfg.get("description", ""), "Timeout": cfg.get("timeout", 15), "MemorySize": cfg.get("memory_size", 512), "VpcConfig": { "SubnetIds": cfg.get("subnet_ids", []), "SecurityGroupIds": cfg.get("security_group_ids", []), }, "Publish": True, } if "tags" in cfg: kwargs.update( Tags={key: str(value) for key, value in cfg.get("tags").items()} ) if "environment_variables" in cfg: kwargs.update( Environment={ "Variables": { key: get_environment_variable_value(value) for key, value in cfg.get("environment_variables").items() }, }, ) client.create_function(**kwargs) concurrency = get_concurrency(cfg) if concurrency > 0: client.put_function_concurrency( FunctionName=func_name, ReservedConcurrentExecutions=concurrency ) def update_function( cfg, path_to_zip_file, existing_cfg, use_s3=False, s3_file=None, preserve_vpc=False, ): """Updates the code of an existing Lambda function""" print("Updating your Lambda function") byte_stream = read(path_to_zip_file, binary_file=True) profile_name = cfg.get("profile") aws_access_key_id = cfg.get("aws_access_key_id") aws_secret_access_key = cfg.get("aws_secret_access_key") account_id = get_account_id( profile_name, aws_access_key_id, aws_secret_access_key, cfg.get("region",), ) role = get_role_name( cfg.get("region"), account_id, cfg.get("role", "lambda_basic_execution"), ) client = get_client( "lambda", profile_name, aws_access_key_id, aws_secret_access_key, cfg.get("region"), ) # Do we prefer development variable over config? buck_name = os.environ.get("S3_BUCKET_NAME") or cfg.get("bucket_name") if use_s3: client.update_function_code( FunctionName=cfg.get("function_name"), S3Bucket="{}".format(buck_name), S3Key="{}".format(s3_file), Publish=True, ) else: client.update_function_code( FunctionName=cfg.get("function_name"), ZipFile=byte_stream, Publish=True, ) kwargs = { "FunctionName": cfg.get("function_name"), "Role": role, "Runtime": cfg.get("runtime"), "Handler": cfg.get("handler"), "Description": cfg.get("description", ""), "Timeout": cfg.get("timeout", 15), "MemorySize": cfg.get("memory_size", 512), } if preserve_vpc: kwargs["VpcConfig"] = existing_cfg.get("Configuration", {}).get( "VpcConfig" ) if kwargs["VpcConfig"] is None: kwargs["VpcConfig"] = { "SubnetIds": cfg.get("subnet_ids", []), "SecurityGroupIds": cfg.get("security_group_ids", []), } else: del kwargs["VpcConfig"]["VpcId"] else: kwargs["VpcConfig"] = { "SubnetIds": cfg.get("subnet_ids", []), "SecurityGroupIds": cfg.get("security_group_ids", []), } if "environment_variables" in cfg: kwargs.update( Environment={ "Variables": { key: str(get_environment_variable_value(value)) for key, value in cfg.get("environment_variables").items() }, }, ) ret = client.update_function_configuration(**kwargs) concurrency = get_concurrency(cfg) if concurrency > 0: client.put_function_concurrency( FunctionName=cfg.get("function_name"), ReservedConcurrentExecutions=concurrency, ) elif "Concurrency" in existing_cfg: client.delete_function_concurrency( FunctionName=cfg.get("function_name") ) if "tags" in cfg: tags = {key: str(value) for key, value in cfg.get("tags").items()} if tags != existing_cfg.get("Tags"): if existing_cfg.get("Tags"): client.untag_resource( Resource=ret["FunctionArn"], TagKeys=list(existing_cfg["Tags"].keys()), ) client.tag_resource(Resource=ret["FunctionArn"], Tags=tags) def upload_s3(cfg, path_to_zip_file, *use_s3): """Upload a function to AWS S3.""" print("Uploading your new Lambda function") profile_name = cfg.get("profile") aws_access_key_id = cfg.get("aws_access_key_id") aws_secret_access_key = cfg.get("aws_secret_access_key") client = get_client( "s3", profile_name, aws_access_key_id, aws_secret_access_key, cfg.get("region"), ) byte_stream = b"" with open(path_to_zip_file, mode="rb") as fh: byte_stream = fh.read() s3_key_prefix = cfg.get("s3_key_prefix", "/dist") checksum = hashlib.new("md5", byte_stream).hexdigest() timestamp = str(time.time()) filename = "{prefix}{checksum}-{ts}.zip".format( prefix=s3_key_prefix, checksum=checksum, ts=timestamp, ) # Do we prefer development variable over config? buck_name = os.environ.get("S3_BUCKET_NAME") or cfg.get("bucket_name") func_name = os.environ.get("LAMBDA_FUNCTION_NAME") or cfg.get( "function_name" ) kwargs = { "Bucket": "{}".format(buck_name), "Key": "{}".format(filename), "Body": byte_stream, } client.put_object(**kwargs) print("Finished uploading {} to S3 bucket {}".format(func_name, buck_name)) if use_s3: return filename def get_function_config(cfg): """Check whether a function exists or not and return its config""" function_name = cfg.get("function_name") profile_name = cfg.get("profile") aws_access_key_id = cfg.get("aws_access_key_id") aws_secret_access_key = cfg.get("aws_secret_access_key") client = get_client( "lambda", profile_name, aws_access_key_id, aws_secret_access_key, cfg.get("region"), ) try: return client.get_function(FunctionName=function_name) except client.exceptions.ResourceNotFoundException as e: if "Function not found" in str(e): return False def get_concurrency(cfg): """Return the Reserved Concurrent Executions if present in the config""" concurrency = int(cfg.get("concurrency", 0)) return max(0, concurrency) def read_cfg(path_to_config_file, profile_name): cfg = read(path_to_config_file, loader=yaml.full_load) if profile_name is not None: cfg["profile"] = profile_name elif "AWS_PROFILE" in os.environ: cfg["profile"] = os.environ["AWS_PROFILE"] return cfg
nficano/python-lambda
aws_lambda/aws_lambda.py
Python
isc
26,779
# Copyright (c) 2015, Max Fillinger <max@max-fillinger.net> # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH # REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY # AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM # LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR # OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR # PERFORMANCE OF THIS SOFTWARE. # The epub format specification is available at http://idpf.org/epub/201 '''Contains the EpubBuilder class to build epub2.0.1 files with the getebook module.''' import html import re import datetime import getebook import os.path import re import zipfile __all__ = ['EpubBuilder', 'EpubTOC', 'Author'] def _normalize(name): '''Transform "Firstname [Middlenames] Lastname" into "Lastname, Firstname [Middlenames]".''' split = name.split() if len(split) == 1: return name return split[-1] + ', ' + ' '.join(name[0:-1]) def _make_starttag(tag, attrs): 'Write a starttag.' out = '<' + tag for key in attrs: out += ' {}="{}"'.format(key, html.escape(attrs[key])) out += '>' return out def _make_xml_elem(tag, text, attr = []): 'Write a flat xml element.' out = ' <' + tag for (key, val) in attr: out += ' {}="{}"'.format(key, val) if text: out += '>{}</{}>\n'.format(text, tag) else: out += ' />\n' return out class EpubTOC(getebook.TOC): 'Table of contents.' _head = (( '<?xml version="1.0" encoding="UTF-8"?>\n' '<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1" xml:lang="en-US">\n' ' <head>\n' ' <meta name="dtb:uid" content="{}" />\n' ' <meta name="dtb:depth" content="{}" />\n' ' <meta name="dtb:totalPageCount" content="0" />\n' ' <meta name="dtb:maxPageNumber" content="0" />\n' ' </head>\n' ' <docTitle>\n' ' <text>{}</text>\n' ' </docTitle>\n' )) _doc_author = (( ' <docAuthor>\n' ' <text>{}</text>\n' ' </docAuthor>\n' )) _navp = (( '{0}<navPoint id="nav{1}">\n' '{0} <navLabel>\n' '{0} <text>{2}</text>\n' '{0} </navLabel>\n' '{0} <content src="{3}" />\n' )) def _navp_xml(self, entry, indent_lvl): 'Write xml for an entry and all its subentries.' xml = self._navp.format(' '*indent_lvl, str(entry.no), entry.text, entry.target) for sub in entry.entries: xml += self._navp_xml(sub, indent_lvl+1) xml += ' '*indent_lvl + '</navPoint>\n' return xml def write_xml(self, uid, title, authors): 'Write the xml code for the table of contents.' xml = self._head.format(uid, self.max_depth, title) for aut in authors: xml += self._doc_author.format(aut) xml += ' <navMap>\n' for entry in self.entries: xml += self._navp_xml(entry, 2) xml += ' </navMap>\n</ncx>' return xml class _Fileinfo: 'Information about a component file of an epub.' def __init__(self, name, in_spine = True, guide_title = None, guide_type = None): '''Initialize the object. If the file does not belong in the reading order, in_spine should be set to False. If it should appear in the guide, set guide_title and guide_type.''' self.name = name (self.ident, ext) = os.path.splitext(name) name_split = name.rsplit('.', 1) self.ident = name_split[0] self.in_spine = in_spine self.guide_title = guide_title self.guide_type = guide_type # Infer media-type from file extension ext = ext.lower() if ext in ('.htm', '.html', '.xhtml'): self.media_type = 'application/xhtml+xml' elif ext in ('.png', '.gif', '.jpeg'): self.media_type = 'image/' + ext elif ext == '.jpg': self.media_type = 'image/jpeg' elif ext == '.css': self.media_type = 'text/css' elif ext == '.ncx': self.media_type = 'application/x-dtbncx+xml' else: raise ValueError('Can\'t infer media-type from extension: %s' % ext) def manifest_entry(self): 'Write the XML element for the manifest.' return _make_xml_elem('item', '', [ ('href', self.name), ('id', self.ident), ('media-type', self.media_type) ]) def spine_entry(self): '''Write the XML element for the spine. (Empty string if in_spine is False.)''' if self.in_spine: return _make_xml_elem('itemref', '', [('idref', self.ident)]) else: return '' def guide_entry(self): '''Write the XML element for the guide. (Empty string if no guide title and type are given.)''' if self.guide_title and self.guide_type: return _make_xml_elem('reference', '', [ ('title', self.guide_title), ('type', self.guide_type), ('href', self.name) ]) else: return '' class _EpubMeta: 'Metadata entry for an epub file.' def __init__(self, tag, text, *args): '''The metadata entry is an XML element. *args is used for supplying the XML element's attributes as (key, value) pairs.''' self.tag = tag self.text = text self.attr = args def write_xml(self): 'Write the XML element.' return _make_xml_elem(self.tag, self.text, self.attr) def __repr__(self): 'Returns the text.' return self.text def __str__(self): 'Returns the text.' return self.text class _EpubDate(_EpubMeta): 'Metadata element for the publication date.' _date_re = re.compile('^([0-9]{4})(-[0-9]{2}(-[0-9]{2})?)?$') def __init__(self, date): '''date must be a string of the form "YYYY[-MM[-DD]]". If it is not of this form, or if the date is invalid, ValueError is raised.''' m = self._date_re.match(date) if not m: raise ValueError('invalid date format') year = int(m.group(1)) try: mon = int(m.group(2)[1:]) if mon < 0 or mon > 12: raise ValueError('month must be in 1..12') except IndexError: pass try: day = int(m.group(3)[1:]) datetime.date(year, mon, day) # raises ValueError if invalid except IndexError: pass self.tag = 'dc:date' self.text = date self.attr = () class _EpubLang(_EpubMeta): 'Metadata element for the language of the book.' _lang_re = re.compile('^[a-z]{2}(-[A-Z]{2})?$') def __init__(self, lang): '''lang must be a lower-case two-letter language code, optionally followed by a "-" and a upper-case two-letter country code. (e.g., "en", "en-US", "en-UK", "de", "de-DE", "de-AT")''' if self._lang_re.match(lang): self.tag = 'dc:language' self.text = lang self.attr = () else: raise ValueError('invalid language format') class Author(_EpubMeta): '''To control the file-as and role attribute for the authors, pass an Author object to the EpubBuilder instead of a string. The file-as attribute is a form of the name used for sorting. The role attribute describes how the person was involved in the work. You ONLY need this if an author's name is not of the form "Given-name Family-name", or if you want to specify a role other than author. Otherwise, you can just pass a string. The value of role should be a MARC relator, e.g., "aut" for author or "edt" for editor. See http://www.loc.gov/marc/relators/ for a full list.''' def __init__(self, name, fileas = None, role = 'aut'): '''Initialize the object. If the argument "fileas" is not given, "Last-name, First-name" is used for the file-as attribute. If the argument "role" is not given, "aut" is used for the role attribute.''' if not fileas: fileas = _normalize(name) self.tag = 'dc:creator' self.text = name self.attr = (('opf:file-as', fileas), ('opf:role', role)) class _OPFfile: '''Class for writing the OPF (Open Packaging Format) file for an epub file. The OPF file contains the metadata, a manifest of all component files in the epub, a "spine" which specifies the reading order and a guide which points to important components of the book such as the title page.''' _opf = ( '<?xml version="1.0" encoding="UTF-8"?>\n' '<package version="2.0" xmlns="http://www.idpf.org/2007/opf" unique_identifier="uid_id">\n' ' <metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:opf="http://www.idpf.org/2007/opf">\n' '{}' ' </metadata>\n' ' <manifest>\n' '{}' ' </manifest>\n' ' <spine toc="toc">\n' '{}' ' </spine>\n' ' <guide>\n' '{}' ' </guide>\n' '</package>\n' ) def __init__(self): 'Initialize.' self.meta = [] self.filelist = [] def write_xml(self): 'Write the XML code for the OPF file.' metadata = '' for elem in self.meta: metadata += elem.write_xml() manif = '' spine = '' guide = '' for finfo in self.filelist: manif += finfo.manifest_entry() spine += finfo.spine_entry() guide += finfo.guide_entry() return self._opf.format(metadata, manif, spine, guide) class EpubBuilder: '''Builds an epub2.0.1 file. Some of the attributes of this class (title, uid, lang) are marked as "mandatory" because they represent metadata that is required by the epub specification. If these attributes are left unset, default values will be used.''' _style_css = ( 'h1, h2, h3, h4, h5, h6 {\n' ' text-align: center;\n' '}\n' 'p {\n' ' text-align: justify;\n' ' margin-top: 0.125em;\n' ' margin-bottom: 0em;\n' ' text-indent: 1.0em;\n' '}\n' '.getebook-tp {\n' ' margin-top: 8em;\n' '}\n' '.getebook-tp-authors {\n' ' font-size: 2em;\n' ' text-align: center;\n' ' margin-bottom: 1em;\n' '}\n' '.getebook-tp-title {\n' ' font-weight: bold;\n' ' font-size: 3em;\n' ' text-align: center;\n' '}\n' '.getebook-tp-sub {\n' ' text-align: center;\n' ' font-weight: normal;\n' ' font-size: 0.8em;\n' ' margin-top: 1em;\n' '}\n' '.getebook-false-h {\n' ' font-weight: bold;\n' ' font-size: 1.5em;\n' '}\n' '.getebook-small-h {\n' ' font-style: normal;\n' ' font-weight: normal;\n' ' font-size: 0.8em;\n' '}\n' ) _container_xml = ( '<?xml version="1.0"?>\n' '<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">\n' ' <rootfiles>\n' ' <rootfile full-path="package.opf" media-type="application/oebps-package+xml"/>\n' ' </rootfiles>\n' '</container>\n' ) _html = ( '<?xml version="1.0" encoding="utf-8"?>\n' '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">\n' '<html xmlns="http://www.w3.org/1999/xhtml">\n' ' <head>\n' ' <title>{}</title>\n' ' <meta http-equiv="content-type" content="application/xtml+xml; charset=utf-8" />\n' ' <link href="style.css" rel="stylesheet" type="text/css" />\n' ' </head>\n' ' <body>\n{}' ' </body>\n' '</html>\n' ) _finalized = False def __init__(self, epub_file): '''Initialize the EpubBuilder instance. "epub_file" is the filename of the epub to be created.''' self.epub_f = zipfile.ZipFile(epub_file, 'w', zipfile.ZIP_DEFLATED) self.epub_f.writestr('mimetype', 'application/epub+zip') self.epub_f.writestr('META-INF/container.xml', self._container_xml) self.toc = EpubTOC() self.opf = _OPFfile() self.opf.filelist.append(_Fileinfo('toc.ncx', False)) self.opf.filelist.append(_Fileinfo('style.css', False)) self._authors = [] self.opt_meta = {} # Optional metadata (other than authors) self.content = '' self.part_no = 0 self.cont_filename = 'part%03d.html' % self.part_no def __enter__(self): 'Return self for use in with ... as ... statement.' return self def __exit__(self, except_type, except_val, traceback): 'Call finalize() and close the file.' try: self.finalize() finally: # Close again in case an exception happened in finalize() self.epub_f.close() return False @property def uid(self): '''Unique identifier of the ebook. (mandatory) If this property is left unset, a pseudo-random string will be generated which is long enough for collisions with existing ebooks to be extremely unlikely.''' try: return self._uid except AttributeError: import random from string import (ascii_letters, digits) alnum = ascii_letters + digits self.uid = ''.join([random.choice(alnum) for i in range(15)]) return self._uid @uid.setter def uid(self, val): self._uid = _EpubMeta('dc:identifier', str(val), ('id', 'uid_id')) @property def title(self): '''Title of the ebook. (mandatory) If this property is left unset, it defaults to "Untitled".''' try: return self._title except AttributeError: self.title = 'Untitled' return self._title @title.setter def title(self, val): # If val is not a string, raise TypeError now rather than later. self._title = _EpubMeta('dc:title', '' + val) @property def lang(self): '''Language of the ebook. (mandatory) The language must be given as a lower-case two-letter code, optionally followed by a "-" and an upper-case two-letter country code. (e.g., "en", "en-US", "en-UK", "de", "de-DE", "de-AT") If this property is left unset, it defaults to "en".''' try: return self._lang except AttributeError: self.lang = 'en' return self._lang @lang.setter def lang(self, val): self._lang = _EpubLang(val) @property def author(self): '''Name of the author. (optional) If there are multiple authors, pass a list of strings. To control the file-as and role attribute, use author objects instead of strings; file-as is an alternate form of the name used for sorting. For a description of the role attribute, see the docstring of the author class.''' if len(self._authors) == 1: return self._authors[0] return tuple([aut for aut in self._authors]) @author.setter def author(self, val): if isinstance(val, Author) or isinstance(val, str): authors = [val] else: authors = val for aut in authors: try: self._authors.append(Author('' + aut)) except TypeError: # aut is not a string, so it should be an Author object self._authors.append(aut) @author.deleter def author(self): self._authors = [] @property def date(self): '''Publication date. (optional) Must be given in "YYYY[-MM[-DD]]" format.''' try: return self.opt_meta['date'] except KeyError: return None @date.setter def date(self, val): self.opt_meta['date'] = _EpubDate(val) @date.deleter def date(self): del self._date @property def rights(self): 'Copyright/licensing information. (optional)' try: return self.opt_meta['rights'] except KeyError: return None @rights.setter def rights(self, val): self.opt_meta['rights'] = _EpubMeta('dc:rights', '' + val) @rights.deleter def rights(self): del self._rights @property def publisher(self): 'Publisher name. (optional)' try: return self.opt_meta['publisher'] except KeyError: return None @publisher.setter def publisher(self, val): self.opt_meta['publisher'] = _EpubMeta('dc:publisher', '' + val) @publisher.deleter def publisher(self): del self._publisher @property def style_css(self): '''CSS stylesheet for the files that are generated by the EpubBuilder instance. Can be overwritten or extended, but not deleted.''' return self._style_css @style_css.setter def style_css(self, val): self._style_css = '' + val def titlepage(self, main_title = None, subtitle = None): '''Create a title page for the ebook. If no main_title is given, the title attribute of the EpubBuilder instance is used.''' tp = '<div class="getebook-tp">\n' if len(self._authors) >= 1: if len(self._authors) == 1: aut_str = str(self._authors[0]) else: aut_str = ', '.join(str(self._authors[0:-1])) + ', and ' \ + str(self._authors[-1]) tp += '<div class="getebook-tp-authors">%s</div>\n' % aut_str if not main_title: main_title = str(self.title) tp += '<div class="getebook-tp-title">%s' % main_title if subtitle: tp += '<div class="getebook-tp-sub">%s</div>' % subtitle tp += '</div>\n</div>\n' self.opf.filelist.insert(0, _Fileinfo('title.html', guide_title = 'Titlepage', guide_type = 'title-page')) self.epub_f.writestr('title.html', self._html.format(self.title, tp)) def headingpage(self, heading, subtitle = None, toc_text = None): '''Create a page containing only a (large) heading, optionally with a smaller subtitle. If toc_text is not given, it defaults to the heading.''' self.new_part() tag = 'h%d' % min(6, self.toc.depth) self.content += '<div class="getebook-tp">' self.content += '<{} class="getebook-tp-title">{}'.format(tag, heading) if subtitle: self.content += '<div class="getebook-tp-sub">%s</div>' % subtitle self.content += '</%s>\n' % tag if not toc_text: toc_text = heading self.toc.new_entry(toc_text, self.cont_filename) self.new_part() def insert_file(self, name, in_spine = False, guide_title = None, guide_type = None, arcname = None): '''Include an external file into the ebook. By default, it will be added to the archive under its basename; the argument "arcname" can be used to specify a different name.''' if not arcname: arcname = os.path.basename(name) self.opf.filelist.append(_Fileinfo(arcname, in_spine, guide_title, guide_type)) self.epub_f.write(name, arcname) def add_file(self, arcname, str_or_bytes, in_spine = False, guide_title = None, guide_type = None): '''Add the string or bytes instance str_or_bytes to the archive under the name arcname.''' self.opf.filelist.append(_Fileinfo(arcname, in_spine, guide_title, guide_type)) self.epub_f.writestr(arcname, str_or_bytes) def false_heading(self, elem): '''Handle a "false heading", i.e., text that appears in heading tags in the source even though it is not a chapter heading.''' elem.attrs['class'] = 'getebook-false-h' elem.tag = 'p' self.handle_elem(elem) def _heading(self, elem): '''Write a heading.''' # Handle paragraph heading if we have one waiting (see the # par_heading method). We don\'t use _handle_par_h here because # we merge it with the subsequent proper heading. try: par_h = self.par_h del self.par_h except AttributeError: toc_text = elem.text else: # There is a waiting paragraph heading, we merge it with the # new heading. toc_text = par_h.text + '. ' + elem.text par_h.tag = 'div' par_h.attrs['class'] = 'getebook-small-h' elem.children.insert(0, par_h) # Set the class attribute value. elem.attrs['class'] = 'getebook-chapter-h' self.toc.new_entry(toc_text, self.cont_filename) # Add heading to the epub. tag = 'h%d' % min(self.toc.depth, 6) self.content += _make_starttag(tag, elem.attrs) for elem in elem.children: self.handle_elem(elem) self.content += '</%s>\n' % tag def par_heading(self, elem): '''Handle a "paragraph heading", i.e., a chaper heading or part of a chapter heading inside paragraph tags. If it is immediately followed by a heading, they will be merged into one.''' self.par_h = elem def _handle_par_h(self): 'Check if there is a waiting paragraph heading and handle it.' try: self._heading(self.par_h) except AttributeError: pass def handle_elem(self, elem): 'Handle html element as supplied by getebook.EbookParser.' try: tag = elem.tag except AttributeError: # elem should be a string is_string = True tag = None else: is_string = False if tag in getebook._headings: self._heading(elem) else: # Handle waiting par_h if necessary (see par_heading) try: self._heading(self.par_h) except AttributeError: pass if is_string: self.content += elem elif tag == 'br': self.content += '<br />\n' elif tag == 'img': self.content += self._handle_image(elem.attrs) + '\n' elif tag == 'a' or tag == 'noscript': # Ignore tag, just write child elements for child in elem.children: self.handle_elem(child) else: self.content += _make_starttag(tag, elem.attrs) for child in elem.children: self.handle_elem(child) self.content += '</%s>' % tag if tag == 'p': self.content += '\n' def _handle_image(self, attrs): 'Returns the alt text of an image tag.' try: return attrs['alt'] except KeyError: return '' def new_part(self): '''Begin a new part of the epub. Write the current html document to the archive and begin a new one.''' # Handle waiting par_h (see par_heading) try: self._heading(self.par_h) except AttributeError: pass if self.content: html = self._html.format(self.title, self.content) self.epub_f.writestr(self.cont_filename, html) self.part_no += 1 self.content = '' self.cont_filename = 'part%03d.html' % self.part_no self.opf.filelist.append(_Fileinfo(self.cont_filename)) def finalize(self): 'Complete and close the epub file.' # Handle waiting par_h (see par_heading) if self._finalized: # Avoid finalizing twice. Otherwise, calling finalize inside # a with-block would lead to an exception when __exit__ # calls finalize again. return try: self._heading(self.par_h) except AttributeError: pass if self.content: html = self._html.format(self.title, self.content) self.epub_f.writestr(self.cont_filename, html) self.opf.meta = [self.uid, self.lang, self.title] + self._authors self.opf.meta += self.opt_meta.values() self.epub_f.writestr('package.opf', self.opf.write_xml()) self.epub_f.writestr('toc.ncx', self.toc.write_xml(self.uid, self.title, self._authors)) self.epub_f.writestr('style.css', self._style_css) self.epub_f.close() self._finalized = True
mfil/getebook
getebook/epub.py
Python
isc
25,314
import numpy as np import pandas as pd from pandas import Series, DataFrame from scipy.spatial import distance import matplotlib.pyplot as plt from sklearn.cluster import DBSCAN from sklearn import metrics from sklearn.datasets.samples_generator import make_blobs from sklearn.preprocessing import StandardScaler from sklearn import decomposition # PCA from sklearn.metrics import confusion_matrix import json import ml.Features as ft from utils import Utils class Identifier(object): def __init__(self): columns = ['mean_height', 'min_height', 'max_height', 'mean_width', 'min_width', 'max_width', 'time', 'girth','id'] self.data = DataFrame(columns=columns) self.event = [] @staticmethod def subscribe(ch, method, properties, body): """ prints the body message. It's the default callback method :param ch: keep null :param method: keep null :param properties: keep null :param body: the message :return: """ #first we get the JSON from body #we check if it's part of the walking event #if walking event is completed, we if __name__ == '__main__': # we setup needed params MAX_HEIGHT = 203 MAX_WIDTH = 142 SPEED = 3 SAMPLING_RATE = 8 mq_host = '172.26.56.122' queue_name = 'door_data' # setting up MQTT subscriber Utils.sub(queue_name=queue_name,callback=subscribe,host=mq_host)
banacer/door-wiz
src/identification/Identifier.py
Python
mit
1,449
#!-*- coding:utf-8 -*- import time def retries(times=3, timeout=1): """对未捕获异常进行重试""" def decorator(func): def _wrapper(*args, **kw): att, retry = 0, 0 while retry < times: retry += 1 try: return func(*args, **kw) except: att += timeout if retry < times: time.sleep(att) return _wrapper return decorator def empty_content_retries(times=3, timeout=2): """响应为空的进行重试""" def decorator(func): def _wrapper(*args, **kw): att, retry = 0, 0 while retry < times: retry += 1 ret = func(*args, **kw) if ret: return ret att += timeout time.sleep(att) return _wrapper return decorator def use_logging(level): """带参数的装饰器""" def decorator(func): print func.__name__ def wrapper(*args, **kwargs): if level == "warn": print ("level:%s, %s is running" % (level, func.__name__)) elif level == "info": print ("level:%s, %s is running" % (level, func.__name__)) return func(*args, **kwargs) return wrapper return decorator if __name__ == "__main__": @use_logging(level="warn") def foo(name='foo'): print("i am %s" % name) foo()
wanghuafeng/spider_tools
decorator.py
Python
mit
1,524
""" ******************************************************************** Test file for implementation check of CR3BP library. ******************************************************************** Last update: 21/01/2022 Description ----------- Contains a few sample orbit propagations to test the CR3BP library. The orbits currently found in test file include: - L2 southern NRHO (9:2 NRHO of Lunar Gateway Station) - Distant Retrograde Orbit (DRO) - Butterfly Orbit - L2 Vertical Orbit """ # Testing CR3BP implementation import matplotlib.pyplot as plt import numpy as np from astropy import units as u from CR3BP import getChar_CR3BP, propagate, propagateSTM from poliastro.bodies import Earth, Moon # Earth-Moon system properties k1 = Earth.k.to(u.km**3 / u.s**2).value k2 = Moon.k.to(u.km**3 / u.s**2).value r12 = 384747.99198 # Earth-Moon distance # Compute CR3BP characterisitic values mu, kstr, lstr, tstr, vstr, nstr = getChar_CR3BP(k1, k2, r12) # -- Lunar Gateway Station Orbit - 9:2 NRHO """ The orbit is a Near-Rectilinear Halo Orbit (NRHO) around the L2 Lagragian point of the Earth-Moon system. The orbit presented here is a southern sub-family of the L2-NRHO. This orbit is 9:2 resonant orbit currenly set as the candidate orbit for the Lunar Gateway Station (LOP-G). Its called 9:2 resonant since a spacecraft would complete 9 orbits in the NRHO for every 2 lunar month (slightly different from lunar orbit period). The exact orbital elements presented here are from the auther's simulations. The orbit states were obtained starting form guess solutions given in various references. A few are provided below: Ref: White Paper: Gateway Destination Orbit Model: A Continuous 15 Year NRHO Reference Trajectory - NASA, 2019 Ref: Strategies for Low-Thrust Transfer Design Based on Direct Collocation Techniques - Park, Howell and Folta The NRHO are subfamily of the Halo orbits. The 'Near-Rectilinear' term comes from the very elongated state of the orbit considering a regular Halo. Halo orbits occur in all three co-linear equilibrum points L1,L2 and L3. They occur in a pair of variants (nothern and southern) due to symmetry of CR3BP. """ # 9:2 L2 souther NRHO orbit r0 = np.array([[1.021881345465263, 0, -0.182000000000000]]) v0 = np.array([0, -0.102950816739606, 0]) tf = 1.509263667286943 # number of points to plot Nplt = 300 tofs = np.linspace(0, tf, Nplt) # propagate the base trajectory rf, vf = propagate(mu, r0, v0, tofs, rtol=1e-11) # ploting orbit rf = np.array(rf) fig = plt.figure() ax = plt.axes(projection="3d") ax.set_box_aspect( (np.ptp(rf[:, 0]), np.ptp(rf[:, 1]), np.ptp(rf[:, 2])) ) # aspect ratio is 1:1:1 in data space # ploting the moon ax.plot3D(1 - mu, 0, 0, "ok") ax.set_title("L2 Southern NRHO") ax.set_xlabel("x-axis [nd]") ax.set_ylabel("y-axis [nd]") ax.set_zlabel("z-axis [nd]") ax.plot3D(rf[:, 0], rf[:, 1], rf[:, 2], "b") plt.show() """ All other orbits in this section are computed from guess solutions available in Grebow's Master and PhD thesis. He lists a quite detailed set of methods to compute most of the major periodic orbits I have presented here. All of them use differntial correction methods which are not yet implemented in this library. Ref: GENERATING PERIODIC ORBITS IN THE CIRCULAR RESTRICTED THREEBODY PROBLEM WITH APPLICATIONS TO LUNAR SOUTH POLE COVERAGE - D.Grebow 2006 (Master thesis) Ref: TRAJECTORY DESIGN IN THE EARTH-MOON SYSTEM AND LUNAR SOUTH POLE COVERAGE - D.Grebow 2010 (PhD desertation) """ # -- DRO orbit # DRO orbit states r0 = np.array([0.783390492345344, 0, 0]) v0 = np.array([0, 0.548464515316651, 0]) tf = 3.63052604667440 # number of points to plot Nplt = 300 tofs = np.linspace(0, tf, Nplt) # propagate the base trajectory rf, vf = propagate(mu, r0, v0, tofs, rtol=1e-11) # ploting orbit rf = np.array(rf) fig = plt.figure() ax = plt.axes(projection="3d") ax.set_box_aspect( (np.ptp(rf[:, 0]), np.ptp(rf[:, 1]), np.ptp(rf[:, 2])) ) # aspect ratio is 1:1:1 in data space # ploting the moon ax.plot3D(1 - mu, 0, 0, "ok") ax.set_title("Distant Restrograde orbit (DRO)") ax.set_xlabel("x-axis [nd]") ax.set_ylabel("y-axis [nd]") ax.set_zlabel("z-axis [nd]") ax.plot3D(rf[:, 0], rf[:, 1], rf[:, 2], "m") plt.show() # -- Butterfly orbit # Butterfly orbit states r0 = np.array([1.03599510774957, 0, 0.173944812752286]) v0 = np.array([0, -0.0798042160573269, 0]) tf = 2.78676904546834 # number of points to plot Nplt = 300 tofs = np.linspace(0, tf, Nplt) # propagate the base trajectory rf, vf = propagate(mu, r0, v0, tofs, rtol=1e-11) # ploting orbit rf = np.array(rf) fig = plt.figure() ax = plt.axes(projection="3d") ax.set_box_aspect( (np.ptp(rf[:, 0]), np.ptp(rf[:, 1]), np.ptp(rf[:, 2])) ) # aspect ratio is 1:1:1 in data space # ploting the moon ax.plot3D(1 - mu, 0, 0, "ok") ax.set_title("Butterfly orbit") ax.set_xlabel("x-axis [nd]") ax.set_ylabel("y-axis [nd]") ax.set_zlabel("z-axis [nd]") ax.plot3D(rf[:, 0], rf[:, 1], rf[:, 2], "r") plt.show() # -- Vertical orbit # Vertical orbit states r0 = np.array([0.504689989562366, 0, 0.836429774762193]) v0 = np.array([0, 0.552722840538063, 0]) tf = 6.18448756121754 # number of points to plot Nplt = 300 tofs = np.linspace(0, tf, Nplt) # propagate the base trajectory rf, vf = propagate(mu, r0, v0, tofs, rtol=1e-11) # ploting orbit rf = np.array(rf) fig = plt.figure() ax = plt.axes(projection="3d") ax.set_box_aspect( (np.ptp(rf[:, 0]), np.ptp(rf[:, 1]), np.ptp(rf[:, 2])) ) # aspect ratio is 1:1:1 in data space # ploting the moon ax.plot3D(1 - mu, 0, 0, "ok") ax.set_title("L2 Vertical orbit") ax.set_xlabel("x-axis [nd]") ax.set_ylabel("y-axis [nd]") ax.set_zlabel("z-axis [nd]") ax.plot3D(rf[:, 0], rf[:, 1], rf[:, 2], "g") plt.show() # -- Propage STM # propagate base trajectory with state-transition-matrix STM0 = np.eye(6) rf, vf, STM = propagateSTM(mu, r0, v0, STM0, tofs, rtol=1e-11) # STM is a matrix of partial derivatives which are used in Newton-Raphson # methods for trajectory design
poliastro/poliastro
contrib/CR3BP/test_run_CR3BP.py
Python
mit
6,277
# -*- coding: utf8 -*- # Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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. # 操作失败。 FAILEDOPERATION = 'FailedOperation' # API网关触发器创建失败。 FAILEDOPERATION_APIGATEWAY = 'FailedOperation.ApiGateway' # 创建触发器失败。 FAILEDOPERATION_APIGW = 'FailedOperation.Apigw' # 获取Apm InstanceId失败。 FAILEDOPERATION_APMCONFIGINSTANCEID = 'FailedOperation.ApmConfigInstanceId' # 当前异步事件状态不支持此操作,请稍后重试。 FAILEDOPERATION_ASYNCEVENTSTATUS = 'FailedOperation.AsyncEventStatus' # 复制函数失败。 FAILEDOPERATION_COPYFAILED = 'FailedOperation.CopyFailed' # 不支持复制到该地域。 FAILEDOPERATION_COPYFUNCTION = 'FailedOperation.CopyFunction' # 操作COS资源失败。 FAILEDOPERATION_COS = 'FailedOperation.Cos' # 创建别名失败。 FAILEDOPERATION_CREATEALIAS = 'FailedOperation.CreateAlias' # 操作失败。 FAILEDOPERATION_CREATEFUNCTION = 'FailedOperation.CreateFunction' # 创建命名空间失败。 FAILEDOPERATION_CREATENAMESPACE = 'FailedOperation.CreateNamespace' # 当前函数状态无法进行此操作。 FAILEDOPERATION_CREATETRIGGER = 'FailedOperation.CreateTrigger' # 当前调试状态无法执行此操作。 FAILEDOPERATION_DEBUGMODESTATUS = 'FailedOperation.DebugModeStatus' # 调试状态下无法更新执行超时时间。 FAILEDOPERATION_DEBUGMODEUPDATETIMEOUTFAIL = 'FailedOperation.DebugModeUpdateTimeOutFail' # 删除别名失败。 FAILEDOPERATION_DELETEALIAS = 'FailedOperation.DeleteAlias' # 当前函数状态无法进行此操作,请在函数状态正常时重试。 FAILEDOPERATION_DELETEFUNCTION = 'FailedOperation.DeleteFunction' # 删除layer版本失败。 FAILEDOPERATION_DELETELAYERVERSION = 'FailedOperation.DeleteLayerVersion' # 无法删除默认Namespace。 FAILEDOPERATION_DELETENAMESPACE = 'FailedOperation.DeleteNamespace' # 删除触发器失败。 FAILEDOPERATION_DELETETRIGGER = 'FailedOperation.DeleteTrigger' # 当前函数状态无法更新代码,请在状态为正常时更新。 FAILEDOPERATION_FUNCTIONNAMESTATUSERROR = 'FailedOperation.FunctionNameStatusError' # 函数在部署中,无法做此操作。 FAILEDOPERATION_FUNCTIONSTATUSERROR = 'FailedOperation.FunctionStatusError' # 当前函数版本状态无法进行此操作,请在版本状态为正常时重试。 FAILEDOPERATION_FUNCTIONVERSIONSTATUSNOTACTIVE = 'FailedOperation.FunctionVersionStatusNotActive' # 获取别名信息失败。 FAILEDOPERATION_GETALIAS = 'FailedOperation.GetAlias' # 获取函数代码地址失败。 FAILEDOPERATION_GETFUNCTIONADDRESS = 'FailedOperation.GetFunctionAddress' # 当前账号或命名空间处于欠费状态,请在可用时重试。 FAILEDOPERATION_INSUFFICIENTBALANCE = 'FailedOperation.InsufficientBalance' # 调用函数失败。 FAILEDOPERATION_INVOKEFUNCTION = 'FailedOperation.InvokeFunction' # 命名空间已存在,请勿重复创建。 FAILEDOPERATION_NAMESPACE = 'FailedOperation.Namespace' # 服务开通失败。 FAILEDOPERATION_OPENSERVICE = 'FailedOperation.OpenService' # 操作冲突。 FAILEDOPERATION_OPERATIONCONFLICT = 'FailedOperation.OperationConflict' # 创建定时预置任务失败。 FAILEDOPERATION_PROVISIONCREATETIMER = 'FailedOperation.ProvisionCreateTimer' # 删除定时预置任务失败。 FAILEDOPERATION_PROVISIONDELETETIMER = 'FailedOperation.ProvisionDeleteTimer' # 当前函数版本已有预置任务处于进行中,请稍后重试。 FAILEDOPERATION_PROVISIONEDINPROGRESS = 'FailedOperation.ProvisionedInProgress' # 发布layer版本失败。 FAILEDOPERATION_PUBLISHLAYERVERSION = 'FailedOperation.PublishLayerVersion' # 当前函数状态无法发布版本,请在状态为正常时发布。 FAILEDOPERATION_PUBLISHVERSION = 'FailedOperation.PublishVersion' # 角色不存在。 FAILEDOPERATION_QCSROLENOTFOUND = 'FailedOperation.QcsRoleNotFound' # 当前函数已有保留并发设置任务处于进行中,请稍后重试。 FAILEDOPERATION_RESERVEDINPROGRESS = 'FailedOperation.ReservedInProgress' # Topic不存在。 FAILEDOPERATION_TOPICNOTEXIST = 'FailedOperation.TopicNotExist' # 用户并发内存配额设置任务处于进行中,请稍后重试。 FAILEDOPERATION_TOTALCONCURRENCYMEMORYINPROGRESS = 'FailedOperation.TotalConcurrencyMemoryInProgress' # 指定的服务未开通,可以提交工单申请开通服务。 FAILEDOPERATION_UNOPENEDSERVICE = 'FailedOperation.UnOpenedService' # 更新别名失败。 FAILEDOPERATION_UPDATEALIAS = 'FailedOperation.UpdateAlias' # 当前函数状态无法更新代码,请在状态为正常时更新。 FAILEDOPERATION_UPDATEFUNCTIONCODE = 'FailedOperation.UpdateFunctionCode' # UpdateFunctionConfiguration操作失败。 FAILEDOPERATION_UPDATEFUNCTIONCONFIGURATION = 'FailedOperation.UpdateFunctionConfiguration' # 内部错误。 INTERNALERROR = 'InternalError' # 创建apigw触发器内部错误。 INTERNALERROR_APIGATEWAY = 'InternalError.ApiGateway' # ckafka接口失败。 INTERNALERROR_CKAFKA = 'InternalError.Ckafka' # 删除cmq触发器失败。 INTERNALERROR_CMQ = 'InternalError.Cmq' # 更新触发器失败。 INTERNALERROR_COS = 'InternalError.Cos' # ES错误。 INTERNALERROR_ES = 'InternalError.ES' # 内部服务异常。 INTERNALERROR_EXCEPTION = 'InternalError.Exception' # 内部服务错误。 INTERNALERROR_GETROLEERROR = 'InternalError.GetRoleError' # 内部系统错误。 INTERNALERROR_SYSTEM = 'InternalError.System' # 内部服务错误。 INTERNALERROR_SYSTEMERROR = 'InternalError.SystemError' # FunctionName取值与规范不符,请修正后再试。可参考:https://tencentcs.com/5jXKFnBW。 INVALIDPARAMETER_FUNCTIONNAME = 'InvalidParameter.FunctionName' # 请求参数不合法。 INVALIDPARAMETER_PAYLOAD = 'InvalidParameter.Payload' # RoutingConfig参数传入错误。 INVALIDPARAMETER_ROUTINGCONFIG = 'InvalidParameter.RoutingConfig' # 参数取值错误。 INVALIDPARAMETERVALUE = 'InvalidParameterValue' # Action取值与规范不符,请修正后再试。可参考:https://tencentcs.com/5jXKFnBW。 INVALIDPARAMETERVALUE_ACTION = 'InvalidParameterValue.Action' # AdditionalVersionWeights参数传入错误。 INVALIDPARAMETERVALUE_ADDITIONALVERSIONWEIGHTS = 'InvalidParameterValue.AdditionalVersionWeights' # 不支持删除默认别名,请修正后重试。 INVALIDPARAMETERVALUE_ALIAS = 'InvalidParameterValue.Alias' # ApiGateway参数错误。 INVALIDPARAMETERVALUE_APIGATEWAY = 'InvalidParameterValue.ApiGateway' # ApmConfig参数传入错误。 INVALIDPARAMETERVALUE_APMCONFIG = 'InvalidParameterValue.ApmConfig' # ApmConfigInstanceId参数传入错误。 INVALIDPARAMETERVALUE_APMCONFIGINSTANCEID = 'InvalidParameterValue.ApmConfigInstanceId' # ApmConfigRegion参数传入错误。 INVALIDPARAMETERVALUE_APMCONFIGREGION = 'InvalidParameterValue.ApmConfigRegion' # Args 参数值有误。 INVALIDPARAMETERVALUE_ARGS = 'InvalidParameterValue.Args' # 函数异步重试配置参数无效。 INVALIDPARAMETERVALUE_ASYNCTRIGGERCONFIG = 'InvalidParameterValue.AsyncTriggerConfig' # Cdn传入错误。 INVALIDPARAMETERVALUE_CDN = 'InvalidParameterValue.Cdn' # cfs配置项重复。 INVALIDPARAMETERVALUE_CFSPARAMETERDUPLICATE = 'InvalidParameterValue.CfsParameterDuplicate' # cfs配置项取值与规范不符。 INVALIDPARAMETERVALUE_CFSPARAMETERERROR = 'InvalidParameterValue.CfsParameterError' # cfs参数格式与规范不符。 INVALIDPARAMETERVALUE_CFSSTRUCTIONERROR = 'InvalidParameterValue.CfsStructionError' # Ckafka传入错误。 INVALIDPARAMETERVALUE_CKAFKA = 'InvalidParameterValue.Ckafka' # 运行函数时的参数传入有误。 INVALIDPARAMETERVALUE_CLIENTCONTEXT = 'InvalidParameterValue.ClientContext' # Cls传入错误。 INVALIDPARAMETERVALUE_CLS = 'InvalidParameterValue.Cls' # 修改Cls配置需要传入Role参数,请修正后重试。 INVALIDPARAMETERVALUE_CLSROLE = 'InvalidParameterValue.ClsRole' # Cmq传入错误。 INVALIDPARAMETERVALUE_CMQ = 'InvalidParameterValue.Cmq' # Code传入错误。 INVALIDPARAMETERVALUE_CODE = 'InvalidParameterValue.Code' # CodeSecret传入错误。 INVALIDPARAMETERVALUE_CODESECRET = 'InvalidParameterValue.CodeSecret' # CodeSource传入错误。 INVALIDPARAMETERVALUE_CODESOURCE = 'InvalidParameterValue.CodeSource' # Command[Entrypoint] 参数值有误。 INVALIDPARAMETERVALUE_COMMAND = 'InvalidParameterValue.Command' # CompatibleRuntimes参数传入错误。 INVALIDPARAMETERVALUE_COMPATIBLERUNTIMES = 'InvalidParameterValue.CompatibleRuntimes' # Content参数传入错误。 INVALIDPARAMETERVALUE_CONTENT = 'InvalidParameterValue.Content' # Cos传入错误。 INVALIDPARAMETERVALUE_COS = 'InvalidParameterValue.Cos' # CosBucketName不符合规范。 INVALIDPARAMETERVALUE_COSBUCKETNAME = 'InvalidParameterValue.CosBucketName' # CosBucketRegion取值与规范不符,请修正后再试。可参考:https://tencentcs.com/5jXKFnBW。 INVALIDPARAMETERVALUE_COSBUCKETREGION = 'InvalidParameterValue.CosBucketRegion' # CosObjectName不符合规范。 INVALIDPARAMETERVALUE_COSOBJECTNAME = 'InvalidParameterValue.CosObjectName' # CustomArgument参数长度超限。 INVALIDPARAMETERVALUE_CUSTOMARGUMENT = 'InvalidParameterValue.CustomArgument' # DateTime传入错误。 INVALIDPARAMETERVALUE_DATETIME = 'InvalidParameterValue.DateTime' # DeadLetterConfig取值与规范不符,请修正后再试。可参考:https://tencentcs.com/5jXKFnBW。 INVALIDPARAMETERVALUE_DEADLETTERCONFIG = 'InvalidParameterValue.DeadLetterConfig' # 默认Namespace无法创建。 INVALIDPARAMETERVALUE_DEFAULTNAMESPACE = 'InvalidParameterValue.DefaultNamespace' # Description传入错误。 INVALIDPARAMETERVALUE_DESCRIPTION = 'InvalidParameterValue.Description' # 环境变量DNS[OS_NAMESERVER]配置有误。 INVALIDPARAMETERVALUE_DNSINFO = 'InvalidParameterValue.DnsInfo' # EipConfig参数错误。 INVALIDPARAMETERVALUE_EIPCONFIG = 'InvalidParameterValue.EipConfig' # Enable取值与规范不符,请修正后再试。可参考:https://tencentcs.com/5jXKFnBW。 INVALIDPARAMETERVALUE_ENABLE = 'InvalidParameterValue.Enable' # Environment传入错误。 INVALIDPARAMETERVALUE_ENVIRONMENT = 'InvalidParameterValue.Environment' # 环境变量大小超限,请保持在 4KB 以内。 INVALIDPARAMETERVALUE_ENVIRONMENTEXCEEDEDLIMIT = 'InvalidParameterValue.EnvironmentExceededLimit' # 不支持修改函数系统环境变量和运行环境变量。 INVALIDPARAMETERVALUE_ENVIRONMENTSYSTEMPROTECT = 'InvalidParameterValue.EnvironmentSystemProtect' # Filters参数错误。 INVALIDPARAMETERVALUE_FILTERS = 'InvalidParameterValue.Filters' # Function取值与规范不符,请修正后再试。可参考:https://tencentcs.com/5jXKFnBW。 INVALIDPARAMETERVALUE_FUNCTION = 'InvalidParameterValue.Function' # 函数不存在。 INVALIDPARAMETERVALUE_FUNCTIONNAME = 'InvalidParameterValue.FunctionName' # GitBranch不符合规范。 INVALIDPARAMETERVALUE_GITBRANCH = 'InvalidParameterValue.GitBranch' # GitCommitId取值与规范不符,请修正后再试。可参考:https://tencentcs.com/5jXKFnBW。 INVALIDPARAMETERVALUE_GITCOMMITID = 'InvalidParameterValue.GitCommitId' # GitDirectory不符合规范。 INVALIDPARAMETERVALUE_GITDIRECTORY = 'InvalidParameterValue.GitDirectory' # GitPassword不符合规范。 INVALIDPARAMETERVALUE_GITPASSWORD = 'InvalidParameterValue.GitPassword' # GitUrl不符合规范。 INVALIDPARAMETERVALUE_GITURL = 'InvalidParameterValue.GitUrl' # GitUserName不符合规范。 INVALIDPARAMETERVALUE_GITUSERNAME = 'InvalidParameterValue.GitUserName' # Handler传入错误。 INVALIDPARAMETERVALUE_HANDLER = 'InvalidParameterValue.Handler' # IdleTimeOut参数传入错误。 INVALIDPARAMETERVALUE_IDLETIMEOUT = 'InvalidParameterValue.IdleTimeOut' # imageUri 传入有误。 INVALIDPARAMETERVALUE_IMAGEURI = 'InvalidParameterValue.ImageUri' # InlineZipFile非法。 INVALIDPARAMETERVALUE_INLINEZIPFILE = 'InvalidParameterValue.InlineZipFile' # InvokeType取值与规范不符,请修正后再试。 INVALIDPARAMETERVALUE_INVOKETYPE = 'InvalidParameterValue.InvokeType' # L5Enable取值与规范不符,请修正后再试。 INVALIDPARAMETERVALUE_L5ENABLE = 'InvalidParameterValue.L5Enable' # LayerName参数传入错误。 INVALIDPARAMETERVALUE_LAYERNAME = 'InvalidParameterValue.LayerName' # Layers参数传入错误。 INVALIDPARAMETERVALUE_LAYERS = 'InvalidParameterValue.Layers' # Limit传入错误。 INVALIDPARAMETERVALUE_LIMIT = 'InvalidParameterValue.Limit' # 参数超出长度限制。 INVALIDPARAMETERVALUE_LIMITEXCEEDED = 'InvalidParameterValue.LimitExceeded' # Memory取值与规范不符,请修正后再试。可参考:https://tencentcs.com/5jXKFnBW。 INVALIDPARAMETERVALUE_MEMORY = 'InvalidParameterValue.Memory' # MemorySize错误。 INVALIDPARAMETERVALUE_MEMORYSIZE = 'InvalidParameterValue.MemorySize' # MinCapacity 参数传入错误。 INVALIDPARAMETERVALUE_MINCAPACITY = 'InvalidParameterValue.MinCapacity' # Name参数传入错误。 INVALIDPARAMETERVALUE_NAME = 'InvalidParameterValue.Name' # Namespace参数传入错误。 INVALIDPARAMETERVALUE_NAMESPACE = 'InvalidParameterValue.Namespace' # 规则不正确,Namespace为英文字母、数字、-_ 符号组成,长度30。 INVALIDPARAMETERVALUE_NAMESPACEINVALID = 'InvalidParameterValue.NamespaceInvalid' # NodeSpec 参数传入错误。 INVALIDPARAMETERVALUE_NODESPEC = 'InvalidParameterValue.NodeSpec' # NodeType 参数传入错误。 INVALIDPARAMETERVALUE_NODETYPE = 'InvalidParameterValue.NodeType' # 偏移量不合法。 INVALIDPARAMETERVALUE_OFFSET = 'InvalidParameterValue.Offset' # Order传入错误。 INVALIDPARAMETERVALUE_ORDER = 'InvalidParameterValue.Order' # OrderBy取值与规范不符,请修正后再试。可参考:https://tencentcs.com/5jXKFnBW。 INVALIDPARAMETERVALUE_ORDERBY = 'InvalidParameterValue.OrderBy' # 入参不是标准的json。 INVALIDPARAMETERVALUE_PARAM = 'InvalidParameterValue.Param' # ProtocolType参数传入错误。 INVALIDPARAMETERVALUE_PROTOCOLTYPE = 'InvalidParameterValue.ProtocolType' # 定时预置的cron配置重复。 INVALIDPARAMETERVALUE_PROVISIONTRIGGERCRONCONFIGDUPLICATE = 'InvalidParameterValue.ProvisionTriggerCronConfigDuplicate' # TriggerName参数传入错误。 INVALIDPARAMETERVALUE_PROVISIONTRIGGERNAME = 'InvalidParameterValue.ProvisionTriggerName' # TriggerName重复。 INVALIDPARAMETERVALUE_PROVISIONTRIGGERNAMEDUPLICATE = 'InvalidParameterValue.ProvisionTriggerNameDuplicate' # ProvisionType 参数传入错误。 INVALIDPARAMETERVALUE_PROVISIONTYPE = 'InvalidParameterValue.ProvisionType' # PublicNetConfig参数错误。 INVALIDPARAMETERVALUE_PUBLICNETCONFIG = 'InvalidParameterValue.PublicNetConfig' # 不支持的函数版本。 INVALIDPARAMETERVALUE_QUALIFIER = 'InvalidParameterValue.Qualifier' # 企业版镜像实例ID[RegistryId]传值错误。 INVALIDPARAMETERVALUE_REGISTRYID = 'InvalidParameterValue.RegistryId' # RetCode不合法。 INVALIDPARAMETERVALUE_RETCODE = 'InvalidParameterValue.RetCode' # RoutingConfig取值与规范不符,请修正后再试。可参考:https://tencentcs.com/5jXKFnBW。 INVALIDPARAMETERVALUE_ROUTINGCONFIG = 'InvalidParameterValue.RoutingConfig' # Runtime传入错误。 INVALIDPARAMETERVALUE_RUNTIME = 'InvalidParameterValue.Runtime' # searchkey 不是 Keyword,Tag 或者 Runtime。 INVALIDPARAMETERVALUE_SEARCHKEY = 'InvalidParameterValue.SearchKey' # SecretInfo错误。 INVALIDPARAMETERVALUE_SECRETINFO = 'InvalidParameterValue.SecretInfo' # ServiceName命名不规范。 INVALIDPARAMETERVALUE_SERVICENAME = 'InvalidParameterValue.ServiceName' # Stamp取值与规范不符,请修正后再试。 INVALIDPARAMETERVALUE_STAMP = 'InvalidParameterValue.Stamp' # 起始时间传入错误。 INVALIDPARAMETERVALUE_STARTTIME = 'InvalidParameterValue.StartTime' # 需要同时指定开始日期与结束日期。 INVALIDPARAMETERVALUE_STARTTIMEORENDTIME = 'InvalidParameterValue.StartTimeOrEndTime' # Status取值与规范不符,请修正后再试。 INVALIDPARAMETERVALUE_STATUS = 'InvalidParameterValue.Status' # 系统环境变量错误。 INVALIDPARAMETERVALUE_SYSTEMENVIRONMENT = 'InvalidParameterValue.SystemEnvironment' # 非法的TempCosObjectName。 INVALIDPARAMETERVALUE_TEMPCOSOBJECTNAME = 'InvalidParameterValue.TempCosObjectName' # TraceEnable取值与规范不符,请修正后再试。 INVALIDPARAMETERVALUE_TRACEENABLE = 'InvalidParameterValue.TraceEnable' # TrackingTarget 参数输入错误。 INVALIDPARAMETERVALUE_TRACKINGTARGET = 'InvalidParameterValue.TrackingTarget' # TriggerCronConfig参数传入错误。 INVALIDPARAMETERVALUE_TRIGGERCRONCONFIG = 'InvalidParameterValue.TriggerCronConfig' # TriggerCronConfig参数定时触发间隔小于指定值。 INVALIDPARAMETERVALUE_TRIGGERCRONCONFIGTIMEINTERVAL = 'InvalidParameterValue.TriggerCronConfigTimeInterval' # TriggerDesc传入参数错误。 INVALIDPARAMETERVALUE_TRIGGERDESC = 'InvalidParameterValue.TriggerDesc' # TriggerName传入错误。 INVALIDPARAMETERVALUE_TRIGGERNAME = 'InvalidParameterValue.TriggerName' # TriggerProvisionedConcurrencyNum参数传入错误。 INVALIDPARAMETERVALUE_TRIGGERPROVISIONEDCONCURRENCYNUM = 'InvalidParameterValue.TriggerProvisionedConcurrencyNum' # Type传入错误。 INVALIDPARAMETERVALUE_TYPE = 'InvalidParameterValue.Type' # 开启cfs配置的同时必须开启vpc。 INVALIDPARAMETERVALUE_VPCNOTSETWHENOPENCFS = 'InvalidParameterValue.VpcNotSetWhenOpenCfs' # WebSocketsParams参数传入错误。 INVALIDPARAMETERVALUE_WEBSOCKETSPARAMS = 'InvalidParameterValue.WebSocketsParams' # 检测到不是标准的zip文件,请重新压缩后再试。 INVALIDPARAMETERVALUE_ZIPFILE = 'InvalidParameterValue.ZipFile' # 压缩文件base64解码失败: `Incorrect padding`,请修正后再试。 INVALIDPARAMETERVALUE_ZIPFILEBASE64BINASCIIERROR = 'InvalidParameterValue.ZipFileBase64BinasciiError' # 别名个数超过最大限制。 LIMITEXCEEDED_ALIAS = 'LimitExceeded.Alias' # Cdn使用超过最大限制。 LIMITEXCEEDED_CDN = 'LimitExceeded.Cdn' # eip资源超限。 LIMITEXCEEDED_EIP = 'LimitExceeded.Eip' # 函数数量超出最大限制 ,可通过[提交工单](https://cloud.tencent.com/act/event/Online_service?from=scf%7Cindex)申请提升限制。 LIMITEXCEEDED_FUNCTION = 'LimitExceeded.Function' # 同一个主题下的函数超过最大限制。 LIMITEXCEEDED_FUNCTIONONTOPIC = 'LimitExceeded.FunctionOnTopic' # FunctionProvisionedConcurrencyMemory数量达到限制,可提交工单申请提升限制:https://tencentcs.com/7Fixwt63。 LIMITEXCEEDED_FUNCTIONPROVISIONEDCONCURRENCYMEMORY = 'LimitExceeded.FunctionProvisionedConcurrencyMemory' # 函数保留并发内存超限。 LIMITEXCEEDED_FUNCTIONRESERVEDCONCURRENCYMEMORY = 'LimitExceeded.FunctionReservedConcurrencyMemory' # FunctionTotalProvisionedConcurrencyMemory达到限制,可提交工单申请提升限制:https://tencentcs.com/7Fixwt63。 LIMITEXCEEDED_FUNCTIONTOTALPROVISIONEDCONCURRENCYMEMORY = 'LimitExceeded.FunctionTotalProvisionedConcurrencyMemory' # 函数预置并发总数达到限制。 LIMITEXCEEDED_FUNCTIONTOTALPROVISIONEDCONCURRENCYNUM = 'LimitExceeded.FunctionTotalProvisionedConcurrencyNum' # InitTimeout达到限制,可提交工单申请提升限制:https://tencentcs.com/7Fixwt63。 LIMITEXCEEDED_INITTIMEOUT = 'LimitExceeded.InitTimeout' # layer版本数量超出最大限制。 LIMITEXCEEDED_LAYERVERSIONS = 'LimitExceeded.LayerVersions' # layer数量超出最大限制。 LIMITEXCEEDED_LAYERS = 'LimitExceeded.Layers' # 内存超出最大限制。 LIMITEXCEEDED_MEMORY = 'LimitExceeded.Memory' # 函数异步重试配置消息保留时间超过限制。 LIMITEXCEEDED_MSGTTL = 'LimitExceeded.MsgTTL' # 命名空间数量超过最大限制,可通过[提交工单](https://cloud.tencent.com/act/event/Online_service?from=scf%7Cindex)申请提升限制。 LIMITEXCEEDED_NAMESPACE = 'LimitExceeded.Namespace' # Offset超出限制。 LIMITEXCEEDED_OFFSET = 'LimitExceeded.Offset' # 定时预置数量超过最大限制。 LIMITEXCEEDED_PROVISIONTRIGGERACTION = 'LimitExceeded.ProvisionTriggerAction' # 定时触发间隔小于最大限制。 LIMITEXCEEDED_PROVISIONTRIGGERINTERVAL = 'LimitExceeded.ProvisionTriggerInterval' # 配额超限。 LIMITEXCEEDED_QUOTA = 'LimitExceeded.Quota' # 函数异步重试配置异步重试次数超过限制。 LIMITEXCEEDED_RETRYNUM = 'LimitExceeded.RetryNum' # Timeout超出最大限制。 LIMITEXCEEDED_TIMEOUT = 'LimitExceeded.Timeout' # 用户并发内存配额超限。 LIMITEXCEEDED_TOTALCONCURRENCYMEMORY = 'LimitExceeded.TotalConcurrencyMemory' # 触发器数量超出最大限制,可通过[提交工单](https://cloud.tencent.com/act/event/Online_service?from=scf%7Cindex)申请提升限制。 LIMITEXCEEDED_TRIGGER = 'LimitExceeded.Trigger' # UserTotalConcurrencyMemory达到限制,可提交工单申请提升限制:https://tencentcs.com/7Fixwt63。 LIMITEXCEEDED_USERTOTALCONCURRENCYMEMORY = 'LimitExceeded.UserTotalConcurrencyMemory' # 缺少参数错误。 MISSINGPARAMETER = 'MissingParameter' # Code没有传入。 MISSINGPARAMETER_CODE = 'MissingParameter.Code' # 缺失 Runtime 字段。 MISSINGPARAMETER_RUNTIME = 'MissingParameter.Runtime' # 资源被占用。 RESOURCEINUSE = 'ResourceInUse' # Alias已被占用。 RESOURCEINUSE_ALIAS = 'ResourceInUse.Alias' # Cdn已被占用。 RESOURCEINUSE_CDN = 'ResourceInUse.Cdn' # Cmq已被占用。 RESOURCEINUSE_CMQ = 'ResourceInUse.Cmq' # Cos已被占用。 RESOURCEINUSE_COS = 'ResourceInUse.Cos' # 函数已存在。 RESOURCEINUSE_FUNCTION = 'ResourceInUse.Function' # FunctionName已存在。 RESOURCEINUSE_FUNCTIONNAME = 'ResourceInUse.FunctionName' # Layer版本正在使用中。 RESOURCEINUSE_LAYERVERSION = 'ResourceInUse.LayerVersion' # Namespace已存在。 RESOURCEINUSE_NAMESPACE = 'ResourceInUse.Namespace' # TriggerName已存在。 RESOURCEINUSE_TRIGGER = 'ResourceInUse.Trigger' # TriggerName已存在。 RESOURCEINUSE_TRIGGERNAME = 'ResourceInUse.TriggerName' # COS资源不足。 RESOURCEINSUFFICIENT_COS = 'ResourceInsufficient.COS' # 资源不存在。 RESOURCENOTFOUND = 'ResourceNotFound' # 别名不存在。 RESOURCENOTFOUND_ALIAS = 'ResourceNotFound.Alias' # 未找到指定的AsyncEvent,请创建后再试。 RESOURCENOTFOUND_ASYNCEVENT = 'ResourceNotFound.AsyncEvent' # Cdn不存在。 RESOURCENOTFOUND_CDN = 'ResourceNotFound.Cdn' # 指定的cfs下未找到您所指定的挂载点。 RESOURCENOTFOUND_CFSMOUNTINSNOTMATCH = 'ResourceNotFound.CfsMountInsNotMatch' # 检测cfs状态为不可用。 RESOURCENOTFOUND_CFSSTATUSERROR = 'ResourceNotFound.CfsStatusError' # cfs与云函数所处vpc不一致。 RESOURCENOTFOUND_CFSVPCNOTMATCH = 'ResourceNotFound.CfsVpcNotMatch' # Ckafka不存在。 RESOURCENOTFOUND_CKAFKA = 'ResourceNotFound.Ckafka' # Cmq不存在。 RESOURCENOTFOUND_CMQ = 'ResourceNotFound.Cmq' # Cos不存在。 RESOURCENOTFOUND_COS = 'ResourceNotFound.Cos' # 不存在的Demo。 RESOURCENOTFOUND_DEMO = 'ResourceNotFound.Demo' # 函数不存在。 RESOURCENOTFOUND_FUNCTION = 'ResourceNotFound.Function' # 函数不存在。 RESOURCENOTFOUND_FUNCTIONNAME = 'ResourceNotFound.FunctionName' # 函数版本不存在。 RESOURCENOTFOUND_FUNCTIONVERSION = 'ResourceNotFound.FunctionVersion' # 获取cfs挂载点信息错误。 RESOURCENOTFOUND_GETCFSMOUNTINSERROR = 'ResourceNotFound.GetCfsMountInsError' # 获取cfs信息错误。 RESOURCENOTFOUND_GETCFSNOTMATCH = 'ResourceNotFound.GetCfsNotMatch' # 未找到指定的ImageConfig,请创建后再试。 RESOURCENOTFOUND_IMAGECONFIG = 'ResourceNotFound.ImageConfig' # layer不存在。 RESOURCENOTFOUND_LAYER = 'ResourceNotFound.Layer' # Layer版本不存在。 RESOURCENOTFOUND_LAYERVERSION = 'ResourceNotFound.LayerVersion' # Namespace不存在。 RESOURCENOTFOUND_NAMESPACE = 'ResourceNotFound.Namespace' # 版本不存在。 RESOURCENOTFOUND_QUALIFIER = 'ResourceNotFound.Qualifier' # 角色不存在。 RESOURCENOTFOUND_ROLE = 'ResourceNotFound.Role' # Role不存在。 RESOURCENOTFOUND_ROLECHECK = 'ResourceNotFound.RoleCheck' # Timer不存在。 RESOURCENOTFOUND_TIMER = 'ResourceNotFound.Timer' # 并发内存配额资源未找到。 RESOURCENOTFOUND_TOTALCONCURRENCYMEMORY = 'ResourceNotFound.TotalConcurrencyMemory' # 触发器不存在。 RESOURCENOTFOUND_TRIGGER = 'ResourceNotFound.Trigger' # 版本不存在。 RESOURCENOTFOUND_VERSION = 'ResourceNotFound.Version' # VPC或子网不存在。 RESOURCENOTFOUND_VPC = 'ResourceNotFound.Vpc' # 余额不足,请先充值。 RESOURCEUNAVAILABLE_INSUFFICIENTBALANCE = 'ResourceUnavailable.InsufficientBalance' # Namespace不可用。 RESOURCEUNAVAILABLE_NAMESPACE = 'ResourceUnavailable.Namespace' # 未授权操作。 UNAUTHORIZEDOPERATION = 'UnauthorizedOperation' # CAM鉴权失败。 UNAUTHORIZEDOPERATION_CAM = 'UnauthorizedOperation.CAM' # 无访问代码权限。 UNAUTHORIZEDOPERATION_CODESECRET = 'UnauthorizedOperation.CodeSecret' # 没有权限。 UNAUTHORIZEDOPERATION_CREATETRIGGER = 'UnauthorizedOperation.CreateTrigger' # 没有权限的操作。 UNAUTHORIZEDOPERATION_DELETEFUNCTION = 'UnauthorizedOperation.DeleteFunction' # 没有权限。 UNAUTHORIZEDOPERATION_DELETETRIGGER = 'UnauthorizedOperation.DeleteTrigger' # 不是从控制台调用的该接口。 UNAUTHORIZEDOPERATION_NOTMC = 'UnauthorizedOperation.NotMC' # Region错误。 UNAUTHORIZEDOPERATION_REGION = 'UnauthorizedOperation.Region' # 没有权限访问您的Cos资源。 UNAUTHORIZEDOPERATION_ROLE = 'UnauthorizedOperation.Role' # TempCos的Appid和请求账户的APPID不一致。 UNAUTHORIZEDOPERATION_TEMPCOSAPPID = 'UnauthorizedOperation.TempCosAppid' # 无法进行此操作。 UNAUTHORIZEDOPERATION_UPDATEFUNCTIONCODE = 'UnauthorizedOperation.UpdateFunctionCode' # 操作不支持。 UNSUPPORTEDOPERATION = 'UnsupportedOperation' # 资源还有别名绑定,不支持当前操作,请解绑别名后重试。 UNSUPPORTEDOPERATION_ALIASBIND = 'UnsupportedOperation.AliasBind' # 指定的配置AsyncRunEnable暂不支持,请修正后再试。 UNSUPPORTEDOPERATION_ASYNCRUNENABLE = 'UnsupportedOperation.AsyncRunEnable' # Cdn不支持。 UNSUPPORTEDOPERATION_CDN = 'UnsupportedOperation.Cdn' # Cos操作不支持。 UNSUPPORTEDOPERATION_COS = 'UnsupportedOperation.Cos' # 指定的配置EipFixed暂不支持。 UNSUPPORTEDOPERATION_EIPFIXED = 'UnsupportedOperation.EipFixed' # 不支持此地域。 UNSUPPORTEDOPERATION_REGION = 'UnsupportedOperation.Region' # Trigger操作不支持。 UNSUPPORTEDOPERATION_TRIGGER = 'UnsupportedOperation.Trigger' # 指定的配置暂不支持,请修正后再试。 UNSUPPORTEDOPERATION_UPDATEFUNCTIONEVENTINVOKECONFIG = 'UnsupportedOperation.UpdateFunctionEventInvokeConfig' # 指定的配置VpcConfig暂不支持。 UNSUPPORTEDOPERATION_VPCCONFIG = 'UnsupportedOperation.VpcConfig'
tzpBingo/github-trending
codespace/python/tencentcloud/scf/v20180416/errorcodes.py
Python
mit
27,390
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AboutIteration(Koan): def test_iterators_are_a_type(self): it = iter(range(1,6)) total = 0 for num in it: total += num self.assertEqual(15 , total) def test_iterating_with_next(self): stages = iter(['alpha','beta','gamma']) try: self.assertEqual('alpha', next(stages)) next(stages) self.assertEqual('gamma', next(stages)) next(stages) except StopIteration as ex: err_msg = 'Ran out of iterations' self.assertRegex(err_msg, 'Ran out') # ------------------------------------------------------------------ def add_ten(self, item): return item + 10 def test_map_transforms_elements_of_a_list(self): seq = [1, 2, 3] mapped_seq = list() mapping = map(self.add_ten, seq) self.assertNotEqual(list, mapping.__class__) self.assertEqual(map, mapping.__class__) # In Python 3 built in iterator funcs return iterable view objects # instead of lists for item in mapping: mapped_seq.append(item) self.assertEqual([11, 12, 13], mapped_seq) # Note, iterator methods actually return objects of iter type in # python 3. In python 2 map() would give you a list. def test_filter_selects_certain_items_from_a_list(self): def is_even(item): return (item % 2) == 0 seq = [1, 2, 3, 4, 5, 6] even_numbers = list() for item in filter(is_even, seq): even_numbers.append(item) self.assertEqual([2,4,6], even_numbers) def test_just_return_first_item_found(self): def is_big_name(item): return len(item) > 4 names = ["Jim", "Bill", "Clarence", "Doug", "Eli"] name = None iterator = filter(is_big_name, names) try: name = next(iterator) except StopIteration: msg = 'Ran out of big names' self.assertEqual("Clarence", name) # ------------------------------------------------------------------ def add(self,accum,item): return accum + item def multiply(self,accum,item): return accum * item def test_reduce_will_blow_your_mind(self): import functools # As of Python 3 reduce() has been demoted from a builtin function # to the functools module. result = functools.reduce(self.add, [2, 3, 4]) self.assertEqual(int, result.__class__) # Reduce() syntax is same as Python 2 self.assertEqual(9, result) result2 = functools.reduce(self.multiply, [2, 3, 4], 1) self.assertEqual(24, result2) # Extra Credit: # Describe in your own words what reduce does. # ------------------------------------------------------------------ def test_use_pass_for_iterations_with_no_body(self): for num in range(1,5): pass self.assertEqual(4, num) # ------------------------------------------------------------------ def test_all_iteration_methods_work_on_any_sequence_not_just_lists(self): # Ranges are an iterable sequence result = map(self.add_ten, range(1,4)) self.assertEqual([11, 12, 13], list(result)) try: file = open("example_file.txt") try: def make_upcase(line): return line.strip().upper() upcase_lines = map(make_upcase, file.readlines()) self.assertEqual(["THIS", "IS", "A", "TEST"] , list(upcase_lines)) finally: # Arg, this is ugly. # We will figure out how to fix this later. file.close() except IOError: # should never happen self.fail()
bohdan7/python_koans
python3/koans/about_iteration.py
Python
mit
3,923
from api_request import Api from util import Util from twocheckout import Twocheckout class Sale(Twocheckout): def __init__(self, dict_): super(self.__class__, self).__init__(dict_) @classmethod def find(cls, params=None): if params is None: params = dict() response = cls(Api.call('sales/detail_sale', params)) return response.sale @classmethod def list(cls, params=None): if params is None: params = dict() response = cls(Api.call('sales/list_sales', params)) return response.sale_summary def refund(self, params=None): if params is None: params = dict() if hasattr(self, 'lineitem_id'): params['lineitem_id'] = self.lineitem_id url = 'sales/refund_lineitem' elif hasattr(self, 'invoice_id'): params['invoice_id'] = self.invoice_id url = 'sales/refund_invoice' else: params['sale_id'] = self.sale_id url = 'sales/refund_invoice' return Sale(Api.call(url, params)) def stop(self, params=None): if params is None: params = dict() if hasattr(self, 'lineitem_id'): params['lineitem_id'] = self.lineitem_id return Api.call('sales/stop_lineitem_recurring', params) elif hasattr(self, 'sale_id'): active_lineitems = Util.active(self) if dict(active_lineitems): result = dict() i = 0 for k, v in active_lineitems.items(): lineitem_id = v params = {'lineitem_id': lineitem_id} result[i] = Api.call('sales/stop_lineitem_recurring', params) i += 1 response = { "response_code": "OK", "response_message": str(len(result)) + " lineitems stopped successfully" } else: response = { "response_code": "NOTICE", "response_message": "No active recurring lineitems" } else: response = { "response_code": "NOTICE", "response_message": "This method can only be called on a sale or lineitem" } return Sale(response) def active(self): active_lineitems = Util.active(self) if dict(active_lineitems): result = dict() i = 0 for k, v in active_lineitems.items(): lineitem_id = v result[i] = lineitem_id i += 1 response = { "response_code": "ACTIVE", "response_message": str(len(result)) + " active recurring lineitems" } else: response = { "response_code": "NOTICE","response_message": "No active recurring lineitems" } return Sale(response) def comment(self, params=None): if params is None: params = dict() params['sale_id'] = self.sale_id return Sale(Api.call('sales/create_comment', params)) def ship(self, params=None): if params is None: params = dict() params['sale_id'] = self.sale_id return Sale(Api.call('sales/mark_shipped', params))
2Checkout/2checkout-python
twocheckout/sale.py
Python
mit
3,388
import json import os from flask import request, g, render_template, make_response, jsonify, Response from helpers.raw_endpoint import get_id, store_json_to_file from helpers.groups import get_groups from json_controller import JSONController from main import app from pymongo import MongoClient, errors HERE = os.path.dirname(os.path.abspath(__file__)) # setup database connection def connect_client(): """Connects to Mongo client""" try: return MongoClient(app.config['DB_HOST'], int(app.config['DB_PORT'])) except errors.ConnectionFailure as e: raise e def get_db(): """Connects to Mongo database""" if not hasattr(g, 'mongo_client'): g.mongo_client = connect_client() g.mongo_db = getattr(g.mongo_client, app.config['DB_NAME']) g.groups_collection = g.mongo_db[os.environ.get('DB_GROUPS_COLLECTION')] return g.mongo_db @app.teardown_appcontext def close_db(error): """Closes connection with Mongo client""" if hasattr(g, 'mongo_client'): g.mongo_client.close() # Begin view routes @app.route('/') @app.route('/index/') def index(): """Landing page for SciNet""" return render_template("index.html") @app.route('/faq/') def faq(): """FAQ page for SciNet""" return render_template("faq.html") @app.route('/leaderboard/') def leaderboard(): """Leaderboard page for SciNet""" get_db() groups = get_groups(g.groups_collection) return render_template("leaderboard.html", groups=groups) @app.route('/ping', methods=['POST']) def ping_endpoint(): """API endpoint determines potential article hash exists in db :return: status code 204 -- hash not present, continue submission :return: status code 201 -- hash already exists, drop submission """ db = get_db() target_hash = request.form.get('hash') if db.raw.find({'hash': target_hash}).count(): return Response(status=201) else: return Response(status=204) @app.route('/articles') def ArticleEndpoint(): """Eventual landing page for searching/retrieving articles""" if request.method == 'GET': return render_template("articles.html") @app.route('/raw', methods=['POST']) def raw_endpoint(): """API endpoint for submitting raw article data :return: status code 405 - invalid JSON or invalid request type :return: status code 400 - unsupported content-type or invalid publisher :return: status code 201 - successful submission """ # Ensure post's content-type is supported if request.headers['content-type'] == 'application/json': # Ensure data is a valid JSON try: user_submission = json.loads(request.data) except ValueError: return Response(status=405) # generate UID for new entry uid = get_id() # store incoming JSON in raw storage file_path = os.path.join( HERE, 'raw_payloads', str(uid) ) store_json_to_file(user_submission, file_path) # hand submission to controller and return Resposne db = get_db() controller_response = JSONController(user_submission, db=db, _id=uid).submit() return controller_response # User submitted an unsupported content-type else: return Response(status=400) #@TODO: Implicit or Explicit group additions? Issue #51 comments on the issues page #@TODO: Add form validation @app.route('/requestnewgroup/', methods=['POST']) def request_new_group(): # Grab submission form data and prepare email message data = request.json msg = "Someone has request that you add {group_name} to the leaderboard \ groups. The groups website is {group_website} and the submitter can \ be reached at {submitter_email}.".format( group_name=data['new_group_name'], group_website=data['new_group_website'], submitter_email=data['submitter_email']) return Response(status=200) ''' try: email( subject="SciNet: A new group has been requested", fro="no-reply@scinet.osf.io", to='harry@scinet.osf.io', msg=msg) return Response(status=200) except: return Response(status=500) ''' # Error handlers @app.errorhandler(404) def not_found(error): return make_response(jsonify( { 'error': 'Page Not Found' } ), 404) @app.errorhandler(405) def method_not_allowed(error): return make_response(jsonify( { 'error': 'Method Not Allowed' } ), 405)
CenterForOpenScience/scinet
scinet/views.py
Python
mit
4,696
from corecat.constants import OBJECT_CODES, MODEL_VERSION from ._sqlalchemy import Base, CoreCatBaseMixin from ._sqlalchemy import Column, \ Integer, \ String, Text class Project(CoreCatBaseMixin, Base): """Project Model class represent for the 'projects' table which is used to store project's basic information.""" # Add the real table name here. # TODO: Add the database prefix here __tablename__ = 'project' # Column definition project_id = Column('id', Integer, primary_key=True, autoincrement=True ) project_name = Column('name', String(100), nullable=False ) project_description = Column('description', Text, nullable=True ) # Relationship # TODO: Building relationship def __init__(self, project_name, created_by_user_id, **kwargs): """ Constructor of Project Model Class. :param project_name: Name of the project. :param created_by_user_id: Project is created under this user ID. :param project_description: Description of the project. """ self.set_up_basic_information( MODEL_VERSION[OBJECT_CODES['Project']], created_by_user_id ) self.project_name = project_name self.project_description = kwargs.get('project_description', None)
DanceCats/CoreCat
corecat/models/project.py
Python
mit
1,533
#!/usr/bin/env python from ansible.module_utils.hashivault import hashivault_argspec from ansible.module_utils.hashivault import hashivault_auth_client from ansible.module_utils.hashivault import hashivault_init from ansible.module_utils.hashivault import hashiwrapper ANSIBLE_METADATA = {'status': ['stableinterface'], 'supported_by': 'community', 'version': '1.1'} DOCUMENTATION = ''' --- module: hashivault_approle_role_get version_added: "3.8.0" short_description: Hashicorp Vault approle role get module description: - Module to get a approle role from Hashicorp Vault. options: name: description: - role name. mount_point: description: - mount point for role default: approle extends_documentation_fragment: hashivault ''' EXAMPLES = ''' --- - hosts: localhost tasks: - hashivault_approle_role_get: name: 'ashley' register: 'vault_approle_role_get' - debug: msg="Role is {{vault_approle_role_get.role}}" ''' def main(): argspec = hashivault_argspec() argspec['name'] = dict(required=True, type='str') argspec['mount_point'] = dict(required=False, type='str', default='approle') module = hashivault_init(argspec) result = hashivault_approle_role_get(module.params) if result.get('failed'): module.fail_json(**result) else: module.exit_json(**result) @hashiwrapper def hashivault_approle_role_get(params): name = params.get('name') client = hashivault_auth_client(params) result = client.get_role(name, mount_point=params.get('mount_point')) return {'role': result} if __name__ == '__main__': main()
TerryHowe/ansible-modules-hashivault
ansible/modules/hashivault/hashivault_approle_role_get.py
Python
mit
1,659
from scrapy.spiders import Spider from scrapy.selector import Selector from scrapy.http import HtmlResponse from FIFAscrape.items import PlayerItem from urlparse import urlparse, urljoin from scrapy.http.request import Request from scrapy.conf import settings import random import time class fifaSpider(Spider): name = "fifa" allowed_domains = ["futhead.com"] start_urls = [ "http://www.futhead.com/16/players/?level=all_nif&bin_platform=ps" ] def parse(self, response): #obtains links from page to page and passes links to parse_playerURL sel = Selector(response) #define selector based on response object (points to urls in start_urls by default) url_list = sel.xpath('//a[@class="display-block padding-0"]/@href') #obtain a list of href links that contain relative links of players for i in url_list: relative_url = self.clean_str(i.extract()) #i is a selector and hence need to extract it to obtain unicode object print urljoin(response.url, relative_url) #urljoin is able to merge absolute and relative paths to form 1 coherent link req = Request(urljoin(response.url, relative_url),callback=self.parse_playerURL) #pass on request with new urls to parse_playerURL req.headers["User-Agent"] = self.random_ua() yield req next_url=sel.xpath('//div[@class="right-nav pull-right"]/a[@rel="next"]/@href').extract_first() if(next_url): #checks if next page exists clean_next_url = self.clean_str(next_url) reqNext = Request(urljoin(response.url, clean_next_url),callback=self.parse) #calls back this function to repeat process on new list of links yield reqNext def parse_playerURL(self, response): #parses player specific data into items list site = Selector(response) items = [] item = PlayerItem() item['1name'] = (response.url).rsplit("/")[-2].replace("-"," ") title = self.clean_str(site.xpath('/html/head/title/text()').extract_first()) item['OVR'] = title.partition("FIFA 16 -")[1].split("-")[0] item['POS'] = self.clean_str(site.xpath('//div[@class="playercard-position"]/text()').extract_first()) #stats = site.xpath('//div[@class="row player-center-container"]/div/a') stat_names = site.xpath('//span[@class="player-stat-title"]') stat_values = site.xpath('//span[contains(@class, "player-stat-value")]') for index in range(len(stat_names)): attr_name = stat_names[index].xpath('.//text()').extract_first() item[attr_name] = stat_values[index].xpath('.//text()').extract_first() items.append(item) return items def clean_str(self,ustring): #removes wierd unicode chars (/u102 bla), whitespaces, tabspaces, etc to form clean string return str(ustring.encode('ascii', 'replace')).strip() def random_ua(self): #randomise user-agent from list to reduce chance of being banned ua = random.choice(settings.get('USER_AGENT_LIST')) if ua: ua='Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2226.0 Safari/537.36' return ua
HashirZahir/FIFA-Player-Ratings
FIFAscrape/spiders/fifa_spider.py
Python
mit
3,458
print("hello!!!!")
coolralf/KaggleTraining
HELP.py
Python
mit
18
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from copy import deepcopy from typing import Any, Awaitable, Optional, TYPE_CHECKING from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.mgmt.core import AsyncARMPipelineClient from msrest import Deserializer, Serializer from .. import models from ._configuration import SqlVirtualMachineManagementClientConfiguration from .operations import AvailabilityGroupListenersOperations, Operations, SqlVirtualMachineGroupsOperations, SqlVirtualMachinesOperations if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential class SqlVirtualMachineManagementClient: """The SQL virtual machine management API provides a RESTful set of web APIs that interact with Azure Compute, Network & Storage services to manage your SQL Server virtual machine. The API enables users to create, delete and retrieve a SQL virtual machine, SQL virtual machine group or availability group listener. :ivar availability_group_listeners: AvailabilityGroupListenersOperations operations :vartype availability_group_listeners: azure.mgmt.sqlvirtualmachine.aio.operations.AvailabilityGroupListenersOperations :ivar operations: Operations operations :vartype operations: azure.mgmt.sqlvirtualmachine.aio.operations.Operations :ivar sql_virtual_machine_groups: SqlVirtualMachineGroupsOperations operations :vartype sql_virtual_machine_groups: azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachineGroupsOperations :ivar sql_virtual_machines: SqlVirtualMachinesOperations operations :vartype sql_virtual_machines: azure.mgmt.sqlvirtualmachine.aio.operations.SqlVirtualMachinesOperations :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param subscription_id: Subscription ID that identifies an Azure subscription. :type subscription_id: str :param base_url: Service URL. Default value is 'https://management.azure.com'. :type base_url: str :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. """ def __init__( self, credential: "AsyncTokenCredential", subscription_id: str, base_url: str = "https://management.azure.com", **kwargs: Any ) -> None: self._config = SqlVirtualMachineManagementClientConfiguration(credential=credential, subscription_id=subscription_id, **kwargs) self._client = AsyncARMPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._deserialize = Deserializer(client_models) self._serialize.client_side_validation = False self.availability_group_listeners = AvailabilityGroupListenersOperations(self._client, self._config, self._serialize, self._deserialize) self.operations = Operations(self._client, self._config, self._serialize, self._deserialize) self.sql_virtual_machine_groups = SqlVirtualMachineGroupsOperations(self._client, self._config, self._serialize, self._deserialize) self.sql_virtual_machines = SqlVirtualMachinesOperations(self._client, self._config, self._serialize, self._deserialize) def _send_request( self, request: HttpRequest, **kwargs: Any ) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest >>> request = HttpRequest("GET", "https://www.example.org/") <HttpRequest [GET], url: 'https://www.example.org/'> >>> response = await client._send_request(request) <AsyncHttpResponse: 200 OK> For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart :param request: The network request you want to make. Required. :type request: ~azure.core.rest.HttpRequest :keyword bool stream: Whether the response payload will be streamed. Defaults to False. :return: The response of your network call. Does not do error handling on your response. :rtype: ~azure.core.rest.AsyncHttpResponse """ request_copy = deepcopy(request) request_copy.url = self._client.format_url(request_copy.url) return self._client.send_request(request_copy, **kwargs) async def close(self) -> None: await self._client.close() async def __aenter__(self) -> "SqlVirtualMachineManagementClient": await self._client.__aenter__() return self async def __aexit__(self, *exc_details) -> None: await self._client.__aexit__(*exc_details)
Azure/azure-sdk-for-python
sdk/sql/azure-mgmt-sqlvirtualmachine/azure/mgmt/sqlvirtualmachine/aio/_sql_virtual_machine_management_client.py
Python
mit
5,342
from flask import Blueprint, request, render_template from ..load import processing_results from ..abbr import get_abbr_map abbr_map = get_abbr_map() liner_mod = Blueprint('liner', __name__, template_folder='templates', static_folder='static') @liner_mod.route('/liner', methods=['GET', 'POST']) def liner(): if request.method == 'POST': query = request.form['liner-text'] text = query.split('.')[:-1] if len(text) == 0: return render_template('projects/line.html', message='Please separate each line with "."') abbr_expanded_text = "" for word in query.split(): if word in abbr_map: abbr_expanded_text += abbr_map[word] else: abbr_expanded_text += word abbr_expanded_text += " " data, emotion_sents, score, line_sentiment, text, length = processing_results(text) return render_template('projects/line.html', data=[data, emotion_sents, score, zip(text, line_sentiment), length, abbr_expanded_text]) else: return render_template('projects/line.html')
griimick/feature-mlsite
app/liner/views.py
Python
mit
1,108
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class Dimension(Model): """Dimension of a resource metric. For e.g. instance specific HTTP requests for a web app, where instance name is dimension of the metric HTTP request. :param name: :type name: str :param display_name: :type display_name: str :param internal_name: :type internal_name: str :param to_be_exported_for_shoebox: :type to_be_exported_for_shoebox: bool """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'display_name': {'key': 'displayName', 'type': 'str'}, 'internal_name': {'key': 'internalName', 'type': 'str'}, 'to_be_exported_for_shoebox': {'key': 'toBeExportedForShoebox', 'type': 'bool'}, } def __init__(self, name=None, display_name=None, internal_name=None, to_be_exported_for_shoebox=None): super(Dimension, self).__init__() self.name = name self.display_name = display_name self.internal_name = internal_name self.to_be_exported_for_shoebox = to_be_exported_for_shoebox
lmazuel/azure-sdk-for-python
azure-mgmt-web/azure/mgmt/web/models/dimension.py
Python
mit
1,562
import asyncio import discord import datetime import pytz from discord.ext import commands from Cogs import FuzzySearch from Cogs import Settings from Cogs import DisplayName from Cogs import Message from Cogs import Nullify class Time: # Init with the bot reference, and a reference to the settings var def __init__(self, bot, settings): self.bot = bot self.settings = settings @commands.command(pass_context=True) async def settz(self, ctx, *, tz : str = None): """Sets your TimeZone - Overrides your UTC offset - and accounts for DST.""" usage = 'Usage: `{}settz [Region/City]`\nYou can get a list of available TimeZones with `{}listtz`'.format(ctx.prefix, ctx.prefix) if not tz: self.settings.setGlobalUserStat(ctx.author, "TimeZone", None) await ctx.channel.send("*{}*, your TimeZone has been removed!".format(DisplayName.name(ctx.author))) return # Let's get the timezone list tz_list = FuzzySearch.search(tz, pytz.all_timezones, None, 3) if not tz_list[0]['Ratio'] == 1: # We didn't find a complete match msg = "I couldn't find that TimeZone!\n\nMaybe you meant one of the following?\n```" for tz in tz_list: msg += tz['Item'] + "\n" msg += '```' await ctx.channel.send(msg) return # We got a time zone self.settings.setGlobalUserStat(ctx.author, "TimeZone", tz_list[0]['Item']) await ctx.channel.send("TimeZone set to *{}!*".format(tz_list[0]['Item'])) @commands.command(pass_context=True) async def listtz(self, ctx, *, tz_search = None): """List all the supported TimeZones in PM.""" if not tz_search: msg = "__Available TimeZones:__\n\n" for tz in pytz.all_timezones: msg += tz + "\n" else: tz_list = FuzzySearch.search(tz_search, pytz.all_timezones) msg = "__Top 3 TimeZone Matches:__\n\n" for tz in tz_list: msg += tz['Item'] + "\n" await Message.say(self.bot, msg, ctx.channel, ctx.author, 1) @commands.command(pass_context=True) async def tz(self, ctx, *, member = None): """See a member's TimeZone.""" # Check if we're suppressing @here and @everyone mentions if self.settings.getServerStat(ctx.message.guild, "SuppressMentions").lower() == "yes": suppress = True else: suppress = False if member == None: member = ctx.message.author if type(member) == str: # Try to get a user first memberName = member member = DisplayName.memberForName(memberName, ctx.message.guild) if not member: msg = 'Couldn\'t find user *{}*.'.format(memberName) # Check for suppress if suppress: msg = Nullify.clean(msg) await ctx.channel.send(msg) return # We got one timezone = self.settings.getGlobalUserStat(member, "TimeZone") if timezone == None: msg = '*{}* hasn\'t set their TimeZone yet - they can do so with the `{}settz [Region/City]` command.'.format(DisplayName.name(member), ctx.prefix) await ctx.channel.send(msg) return msg = '*{}\'s* TimeZone is *{}*'.format(DisplayName.name(member), timezone) await ctx.channel.send(msg) @commands.command(pass_context=True) async def setoffset(self, ctx, *, offset : str = None): """Set your UTC offset.""" if offset == None: self.settings.setGlobalUserStat(ctx.message.author, "UTCOffset", None) msg = '*{}*, your UTC offset has been removed!'.format(DisplayName.name(ctx.message.author)) await ctx.channel.send(msg) return offset = offset.replace('+', '') # Split time string by : and get hour/minute values try: hours, minutes = map(int, offset.split(':')) except Exception: try: hours = int(offset) minutes = 0 except Exception: await ctx.channel.send('Offset has to be in +-H:M!') return off = "{}:{}".format(hours, minutes) self.settings.setGlobalUserStat(ctx.message.author, "UTCOffset", off) msg = '*{}*, your UTC offset has been set to *{}!*'.format(DisplayName.name(ctx.message.author), off) await ctx.channel.send(msg) @commands.command(pass_context=True) async def offset(self, ctx, *, member = None): """See a member's UTC offset.""" # Check if we're suppressing @here and @everyone mentions if self.settings.getServerStat(ctx.message.guild, "SuppressMentions").lower() == "yes": suppress = True else: suppress = False if member == None: member = ctx.message.author if type(member) == str: # Try to get a user first memberName = member member = DisplayName.memberForName(memberName, ctx.message.guild) if not member: msg = 'Couldn\'t find user *{}*.'.format(memberName) # Check for suppress if suppress: msg = Nullify.clean(msg) await ctx.channel.send(msg) return # We got one offset = self.settings.getGlobalUserStat(member, "UTCOffset") if offset == None: msg = '*{}* hasn\'t set their offset yet - they can do so with the `{}setoffset [+-offset]` command.'.format(DisplayName.name(member), ctx.prefix) await ctx.channel.send(msg) return # Split time string by : and get hour/minute values try: hours, minutes = map(int, offset.split(':')) except Exception: try: hours = int(offset) minutes = 0 except Exception: await ctx.channel.send('Offset has to be in +-H:M!') return msg = 'UTC' # Apply offset if hours > 0: # Apply positive offset msg += '+{}'.format(offset) elif hours < 0: # Apply negative offset msg += '{}'.format(offset) msg = '*{}\'s* offset is *{}*'.format(DisplayName.name(member), msg) await ctx.channel.send(msg) @commands.command(pass_context=True) async def time(self, ctx, *, offset : str = None): """Get UTC time +- an offset.""" timezone = None if offset == None: member = ctx.message.author else: # Try to get a user first member = DisplayName.memberForName(offset, ctx.message.guild) if member: # We got one # Check for timezone first offset = self.settings.getGlobalUserStat(member, "TimeZone") if offset == None: offset = self.settings.getGlobalUserStat(member, "UTCOffset") if offset == None: msg = '*{}* hasn\'t set their TimeZone or offset yet - they can do so with the `{}setoffset [+-offset]` or `{}settz [Region/City]` command.\nThe current UTC time is *{}*.'.format(DisplayName.name(member), ctx.prefix, ctx.prefix, datetime.datetime.utcnow().strftime("%I:%M %p")) await ctx.channel.send(msg) return # At this point - we need to determine if we have an offset - or possibly a timezone passed t = self.getTimeFromTZ(offset) if t == None: # We did not get an offset t = self.getTimeFromOffset(offset) if t == None: await ctx.channel.send("I couldn't find that TimeZone or offset!") return if member: msg = '{}; where *{}* is, it\'s currently *{}*'.format(t["zone"], DisplayName.name(member), t["time"]) else: msg = '{} is currently *{}*'.format(t["zone"], t["time"]) # Say message await ctx.channel.send(msg) def getTimeFromOffset(self, offset): offset = offset.replace('+', '') # Split time string by : and get hour/minute values try: hours, minutes = map(int, offset.split(':')) except Exception: try: hours = int(offset) minutes = 0 except Exception: return None # await ctx.channel.send('Offset has to be in +-H:M!') # return msg = 'UTC' # Get the time t = datetime.datetime.utcnow() # Apply offset if hours > 0: # Apply positive offset msg += '+{}'.format(offset) td = datetime.timedelta(hours=hours, minutes=minutes) newTime = t + td elif hours < 0: # Apply negative offset msg += '{}'.format(offset) td = datetime.timedelta(hours=(-1*hours), minutes=(-1*minutes)) newTime = t - td else: # No offset newTime = t return { "zone" : msg, "time" : newTime.strftime("%I:%M %p") } def getTimeFromTZ(self, tz): # Assume sanitized zones - as they're pulled from pytz # Let's get the timezone list tz_list = FuzzySearch.search(tz, pytz.all_timezones, None, 3) if not tz_list[0]['Ratio'] == 1: # We didn't find a complete match return None zone = pytz.timezone(tz_list[0]['Item']) zone_now = datetime.datetime.now(zone) return { "zone" : tz_list[0]['Item'], "time" : zone_now.strftime("%I:%M %p") }
TheMasterGhost/CorpBot
Cogs/Time.py
Python
mit
8,457
import unittest from katas.beta.what_color_is_your_name import string_color class StringColorTestCase(unittest.TestCase): def test_equal_1(self): self.assertEqual(string_color('Jack'), '79CAE5') def test_equal_2(self): self.assertEqual(string_color('Joshua'), '6A10D6') def test_equal_3(self): self.assertEqual(string_color('Joshua Smith'), '8F00FB') def test_equal_4(self): self.assertEqual(string_color('Hayden Smith'), '7E00EE') def test_equal_5(self): self.assertEqual(string_color('Mathew Smith'), '8B00F1') def test_is_none_1(self): self.assertIsNone(string_color('a'))
the-zebulan/CodeWars
tests/beta_tests/test_what_color_is_your_name.py
Python
mit
656

No dataset card yet

New: Create and edit this dataset card directly on the website!

Contribute a Dataset Card
Downloads last month
793
Add dataset card