hexsha
stringlengths
40
40
size
int64
4
1.02M
ext
stringclasses
8 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
209
max_stars_repo_name
stringlengths
5
121
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
209
max_issues_repo_name
stringlengths
5
121
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
209
max_forks_repo_name
stringlengths
5
121
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
4
1.02M
avg_line_length
float64
1.07
66.1k
max_line_length
int64
4
266k
alphanum_fraction
float64
0.01
1
f5cfa62fa665d8c85eb38d7744b3440c86a0c7ed
6,430
py
Python
pretraining/args/pretraining_args.py
marcelbra/academic-budget-bert
527053a618d781210b4faccb5fe9afef17b1324a
[ "Apache-2.0" ]
null
null
null
pretraining/args/pretraining_args.py
marcelbra/academic-budget-bert
527053a618d781210b4faccb5fe9afef17b1324a
[ "Apache-2.0" ]
null
null
null
pretraining/args/pretraining_args.py
marcelbra/academic-budget-bert
527053a618d781210b4faccb5fe9afef17b1324a
[ "Apache-2.0" ]
null
null
null
# coding=utf-8 # Copyright 2021 Intel Corporation. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from dataclasses import dataclass, field from typing import Optional @dataclass class PretrainScriptParamsArguments: """ PretrainScriptParamsArguments """ _argument_group_name = "Pretraining Arguments" seed: Optional[int] = field(default=42, metadata={"help": "random seed for initialization)"}) output_dir: Optional[str] = field( default=None, metadata={"help": "The output directory where the model checkpoints will be written."}, ) max_predictions_per_seq: Optional[int] = field( default=20, metadata={"help": "The maximum number of masked tokens in a sequence to be predicted."}, ) local_rank: Optional[int] = field( default=-1, metadata={"help": "local_rank for distributed model on gpus)"} ) load_training_checkpoint: Optional[str] = field( default=None, metadata={ "help": "This is the path to the TAR file which contains model+opt state_dict() checkpointed." }, ) load_checkpoint_id: Optional[str] = field( default=None, metadata={"help": "Checkpoint identifier to load from checkpoint path"} ) num_epochs_between_checkpoints: Optional[int] = field( default=-1, metadata={"help": "Number of epochs between a full checkpoint (used for pre-model)"}, ) job_name: Optional[str] = field( default="pretraining_experiment", metadata={"help": "Experiment job name"}, ) project_name: Optional[str] = field( default="budget-lm-pretraining", metadata={"help": "Project name (W&B)"} ) max_steps: Optional[int] = field( default=9223372036854775807, metadata={"help": "Maximum number of model steps of effective batch size to complete."}, ) max_steps_per_epoch: Optional[int] = field( default=9223372036854775807, metadata={ "help": "Maximum number of model steps of effective batch size within an epoch to complete." }, ) print_steps: Optional[int] = field( default=100, metadata={"help": "Interval to print model details.)"} ) do_validation: Optional[bool] = field( default=False, metadata={"help": "Enable/Disable running validation"} ) validation_epochs: Optional[int] = field( default=10, metadata={"help": "Number of epochs between running validation evaluation"} ) validation_epochs_begin: Optional[int] = field( default=1, metadata={"help": "Number of epochs between running validation evaluation in first stage"}, ) validation_epochs_end: Optional[int] = field( default=1, metadata={"help": "Number of epochs between running validation evaluation in last stage"}, ) validation_begin_proportion: Optional[float] = field( default=0.1, metadata={"help": "how long does the first stage of model last?"} ) validation_end_proportion: Optional[float] = field( default=0.1, metadata={"help": "how long does the last stage of model last?"} ) validation_micro_batch: Optional[int] = field( default=16, metadata={"help": "Per device validation batch size"} ) add_nsp: Optional[bool] = field( default=False, metadata={"help": "Create a model with NSP task; dataset assumed to have NSP labels"}, ) current_run_id: Optional[str] = field( default="", metadata={"help": "the current run id (mainly for hyperparams)"} ) early_exit_time_marker: Optional[float] = field( default=24.0, metadata={"help": "Max hours for pre-model)"} ) total_training_time: Optional[float] = field( default=24.0, metadata={"help": "Max hours for pre-model)"} ) finetune_time_markers: Optional[str] = field( default=None, metadata={"help": "Time markers for saving fine-tuning checkpoints"}, ) finetune_checkpoint_at_end: Optional[bool] = field( default=True, metadata={"help": "Save a finetuning checkpoint when model is done."}, ) gradient_accumulation_steps: Optional[int] = field( default=1, metadata={"help": "gradient accumulation steps"} ) train_batch_size: Optional[int] = field(default=65536, metadata={"help": "train_batch_size"}) train_micro_batch_size_per_gpu: Optional[int] = field( default=32, metadata={"help": "train_micro_batch_size_per_gpu"} ) num_epochs: Optional[int] = field( default=1000000, metadata={"help": "Number of model epochs"} ) lr: Optional[float] = field(default=0.011, metadata={"help": "lr"}) use_early_stopping: Optional[bool] = field( default=False, metadata={"help": "Should use early stopping?"}, ) early_stop_time: Optional[int] = field( default=720, metadata={"help": "The point after which the run should perform well enough? (in MINUTES)"}, ) early_stop_eval_loss: Optional[float] = field( default=2.1, metadata={ "help": "The upper bound value of the validation loss when *early_stop_time* has reached?" }, ) scale_cnt_limit: Optional[int] = field( default=100, metadata={"help": "The limit of the number of times the scale in the optimizer reached 1, in order to early stop."}, ) log_throughput_every: Optional[int] = field( default=20, metadata={"help": "How many steps should the throughput (im Samples/s) be logged."}, ) def __post_init__(self): self.no_nsp = not self.add_nsp self.learning_rate = self.lr if self.finetune_time_markers is not None: self.finetune_time_markers = [ float(x.strip()) for x in self.finetune_time_markers.split(",") ]
33.664921
124
0.654432
3667d5d820ec842514131744e4be3598acc3cc01
10,935
py
Python
ceilometer/storage/sqlalchemy/models.py
VeinFu/ceilometer_ha
fb0d3834d4db8a9eaeb8f5da088a2894c615770f
[ "Apache-2.0" ]
null
null
null
ceilometer/storage/sqlalchemy/models.py
VeinFu/ceilometer_ha
fb0d3834d4db8a9eaeb8f5da088a2894c615770f
[ "Apache-2.0" ]
null
null
null
ceilometer/storage/sqlalchemy/models.py
VeinFu/ceilometer_ha
fb0d3834d4db8a9eaeb8f5da088a2894c615770f
[ "Apache-2.0" ]
null
null
null
# 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. """ SQLAlchemy models for Ceilometer data. """ import hashlib import json from oslo_utils import timeutils import six from sqlalchemy import (Column, Integer, String, ForeignKey, Index, UniqueConstraint, BigInteger) from sqlalchemy import event from sqlalchemy import Float, Boolean, Text, DateTime from sqlalchemy.dialects.mysql import DECIMAL from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import deferred from sqlalchemy.orm import relationship from sqlalchemy.types import TypeDecorator from ceilometer import utils class JSONEncodedDict(TypeDecorator): """Represents an immutable structure as a json-encoded string.""" impl = Text @staticmethod def process_bind_param(value, dialect): if value is not None: value = json.dumps(value) return value @staticmethod def process_result_value(value, dialect): if value is not None: value = json.loads(value) return value class PreciseTimestamp(TypeDecorator): """Represents a timestamp precise to the microsecond.""" impl = DateTime def load_dialect_impl(self, dialect): if dialect.name == 'mysql': return dialect.type_descriptor(DECIMAL(precision=20, scale=6, asdecimal=True)) return self.impl @staticmethod def process_bind_param(value, dialect): if value is None: return value elif dialect.name == 'mysql': return utils.dt_to_decimal(value) return value @staticmethod def process_result_value(value, dialect): if value is None: return value elif dialect.name == 'mysql': return utils.decimal_to_dt(value) return value _COMMON_TABLE_ARGS = {'mysql_charset': "utf8", 'mysql_engine': "InnoDB"} class CeilometerBase(object): """Base class for Ceilometer Models.""" __table_args__ = _COMMON_TABLE_ARGS __table_initialized__ = False def __setitem__(self, key, value): setattr(self, key, value) def __getitem__(self, key): return getattr(self, key) def update(self, values): """Make the model object behave like a dict.""" for k, v in six.iteritems(values): setattr(self, k, v) Base = declarative_base(cls=CeilometerBase) class MetaText(Base): """Metering text metadata.""" __tablename__ = 'metadata_text' __table_args__ = ( Index('ix_meta_text_key', 'meta_key'), _COMMON_TABLE_ARGS, ) id = Column(Integer, ForeignKey('resource.internal_id'), primary_key=True) meta_key = Column(String(255), primary_key=True) value = Column(Text) class MetaBool(Base): """Metering boolean metadata.""" __tablename__ = 'metadata_bool' __table_args__ = ( Index('ix_meta_bool_key', 'meta_key'), _COMMON_TABLE_ARGS, ) id = Column(Integer, ForeignKey('resource.internal_id'), primary_key=True) meta_key = Column(String(255), primary_key=True) value = Column(Boolean) class MetaBigInt(Base): """Metering integer metadata.""" __tablename__ = 'metadata_int' __table_args__ = ( Index('ix_meta_int_key', 'meta_key'), _COMMON_TABLE_ARGS, ) id = Column(Integer, ForeignKey('resource.internal_id'), primary_key=True) meta_key = Column(String(255), primary_key=True) value = Column(BigInteger, default=False) class MetaFloat(Base): """Metering float metadata.""" __tablename__ = 'metadata_float' __table_args__ = ( Index('ix_meta_float_key', 'meta_key'), _COMMON_TABLE_ARGS, ) id = Column(Integer, ForeignKey('resource.internal_id'), primary_key=True) meta_key = Column(String(255), primary_key=True) value = Column(Float(53), default=False) class Meter(Base): """Meter definition data.""" __tablename__ = 'meter' __table_args__ = ( UniqueConstraint('name', 'type', 'unit', name='def_unique'), Index('ix_meter_name', 'name'), _COMMON_TABLE_ARGS, ) id = Column(Integer, primary_key=True) name = Column(String(255), nullable=False) type = Column(String(255)) unit = Column(String(255)) samples = relationship("Sample", backref="meter") class Resource(Base): """Resource data.""" __tablename__ = 'resource' __table_args__ = ( # TODO(gordc): this should exist but the attribute values we set # for user/project/source/resource id's are too large # for a uuid. # UniqueConstraint('resource_id', 'user_id', 'project_id', # 'source_id', 'metadata_hash', # name='res_def_unique'), Index('ix_resource_resource_id', 'resource_id'), Index('ix_resource_metadata_hash', 'metadata_hash'), _COMMON_TABLE_ARGS, ) internal_id = Column(Integer, primary_key=True) user_id = Column(String(255)) project_id = Column(String(255)) source_id = Column(String(255)) resource_id = Column(String(255), nullable=False) resource_metadata = deferred(Column(JSONEncodedDict())) metadata_hash = deferred(Column(String(32))) samples = relationship("Sample", backref="resource") meta_text = relationship("MetaText", backref="resource", cascade="all, delete-orphan") meta_float = relationship("MetaFloat", backref="resource", cascade="all, delete-orphan") meta_int = relationship("MetaBigInt", backref="resource", cascade="all, delete-orphan") meta_bool = relationship("MetaBool", backref="resource", cascade="all, delete-orphan") @event.listens_for(Resource, "before_insert") def before_insert(mapper, connection, target): metadata = json.dumps(target.resource_metadata, sort_keys=True) target.metadata_hash = hashlib.md5(metadata).hexdigest() class Sample(Base): """Metering data.""" __tablename__ = 'sample' __table_args__ = ( Index('ix_sample_timestamp', 'timestamp'), Index('ix_sample_resource_id', 'resource_id'), Index('ix_sample_meter_id', 'meter_id'), Index('ix_sample_meter_id_resource_id', 'meter_id', 'resource_id'), _COMMON_TABLE_ARGS, ) id = Column(Integer, primary_key=True) meter_id = Column(Integer, ForeignKey('meter.id')) resource_id = Column(Integer, ForeignKey('resource.internal_id')) volume = Column(Float(53)) timestamp = Column(PreciseTimestamp(), default=lambda: timeutils.utcnow()) recorded_at = Column(PreciseTimestamp(), default=lambda: timeutils.utcnow()) message_signature = Column(String(64)) message_id = Column(String(128)) class FullSample(object): """A fake model for query samples.""" id = Sample.id timestamp = Sample.timestamp message_id = Sample.message_id message_signature = Sample.message_signature recorded_at = Sample.recorded_at counter_name = Meter.name counter_type = Meter.type counter_unit = Meter.unit counter_volume = Sample.volume resource_id = Resource.resource_id source_id = Resource.source_id user_id = Resource.user_id project_id = Resource.project_id resource_metadata = Resource.resource_metadata internal_id = Resource.internal_id class EventType(Base): """Types of event records.""" __tablename__ = 'event_type' id = Column(Integer, primary_key=True) desc = Column(String(255), unique=True) def __init__(self, event_type): self.desc = event_type def __repr__(self): return "<EventType: %s>" % self.desc class Event(Base): __tablename__ = 'event' __table_args__ = ( Index('ix_event_message_id', 'message_id'), Index('ix_event_type_id', 'event_type_id'), Index('ix_event_generated', 'generated'), _COMMON_TABLE_ARGS, ) id = Column(Integer, primary_key=True) message_id = Column(String(50), unique=True) generated = Column(PreciseTimestamp()) raw = deferred(Column(JSONEncodedDict())) event_type_id = Column(Integer, ForeignKey('event_type.id')) event_type = relationship("EventType", backref='events') def __init__(self, message_id, event_type, generated, raw): self.message_id = message_id self.event_type = event_type self.generated = generated self.raw = raw def __repr__(self): return "<Event %d('Event: %s %s, Generated: %s')>" % (self.id, self.message_id, self.event_type, self.generated) class TraitText(Base): """Event text traits.""" __tablename__ = 'trait_text' __table_args__ = ( Index('ix_trait_text_event_id_key', 'event_id', 'key'), _COMMON_TABLE_ARGS, ) event_id = Column(Integer, ForeignKey('event.id'), primary_key=True) key = Column(String(255), primary_key=True) value = Column(String(255)) class TraitInt(Base): """Event integer traits.""" __tablename__ = 'trait_int' __table_args__ = ( Index('ix_trait_int_event_id_key', 'event_id', 'key'), _COMMON_TABLE_ARGS, ) event_id = Column(Integer, ForeignKey('event.id'), primary_key=True) key = Column(String(255), primary_key=True) value = Column(Integer) class TraitFloat(Base): """Event float traits.""" __tablename__ = 'trait_float' __table_args__ = ( Index('ix_trait_float_event_id_key', 'event_id', 'key'), _COMMON_TABLE_ARGS, ) event_id = Column(Integer, ForeignKey('event.id'), primary_key=True) key = Column(String(255), primary_key=True) value = Column(Float(53)) class TraitDatetime(Base): """Event datetime traits.""" __tablename__ = 'trait_datetime' __table_args__ = ( Index('ix_trait_datetime_event_id_key', 'event_id', 'key'), _COMMON_TABLE_ARGS, ) event_id = Column(Integer, ForeignKey('event.id'), primary_key=True) key = Column(String(255), primary_key=True) value = Column(PreciseTimestamp())
31.604046
78
0.6492
b3c553ddbd0e665ae9186ec3ad6fb4e2cf0cb20b
10,218
py
Python
src/oci/artifacts/models/create_repository_details.py
LaudateCorpus1/oci-python-sdk
b0d3ce629d5113df4d8b83b7a6502b2c5bfa3015
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
src/oci/artifacts/models/create_repository_details.py
LaudateCorpus1/oci-python-sdk
b0d3ce629d5113df4d8b83b7a6502b2c5bfa3015
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
src/oci/artifacts/models/create_repository_details.py
LaudateCorpus1/oci-python-sdk
b0d3ce629d5113df4d8b83b7a6502b2c5bfa3015
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
# coding: utf-8 # Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401 from oci.decorators import init_model_state_from_kwargs @init_model_state_from_kwargs class CreateRepositoryDetails(object): """ Parameters needed to create an artifact repository. """ def __init__(self, **kwargs): """ Initializes a new CreateRepositoryDetails object with values from keyword arguments. This class has the following subclasses and if you are using this class as input to a service operations then you should favor using a subclass over the base class: * :class:`~oci.artifacts.models.CreateGenericRepositoryDetails` The following keyword arguments are supported (corresponding to the getters/setters of this class): :param display_name: The value to assign to the display_name property of this CreateRepositoryDetails. :type display_name: str :param compartment_id: The value to assign to the compartment_id property of this CreateRepositoryDetails. :type compartment_id: str :param repository_type: The value to assign to the repository_type property of this CreateRepositoryDetails. :type repository_type: str :param description: The value to assign to the description property of this CreateRepositoryDetails. :type description: str :param is_immutable: The value to assign to the is_immutable property of this CreateRepositoryDetails. :type is_immutable: bool :param freeform_tags: The value to assign to the freeform_tags property of this CreateRepositoryDetails. :type freeform_tags: dict(str, str) :param defined_tags: The value to assign to the defined_tags property of this CreateRepositoryDetails. :type defined_tags: dict(str, dict(str, object)) """ self.swagger_types = { 'display_name': 'str', 'compartment_id': 'str', 'repository_type': 'str', 'description': 'str', 'is_immutable': 'bool', 'freeform_tags': 'dict(str, str)', 'defined_tags': 'dict(str, dict(str, object))' } self.attribute_map = { 'display_name': 'displayName', 'compartment_id': 'compartmentId', 'repository_type': 'repositoryType', 'description': 'description', 'is_immutable': 'isImmutable', 'freeform_tags': 'freeformTags', 'defined_tags': 'definedTags' } self._display_name = None self._compartment_id = None self._repository_type = None self._description = None self._is_immutable = None self._freeform_tags = None self._defined_tags = None @staticmethod def get_subtype(object_dictionary): """ Given the hash representation of a subtype of this class, use the info in the hash to return the class of the subtype. """ type = object_dictionary['repositoryType'] if type == 'GENERIC': return 'CreateGenericRepositoryDetails' else: return 'CreateRepositoryDetails' @property def display_name(self): """ Gets the display_name of this CreateRepositoryDetails. A user-friendly display name for the repository. If not present, will be auto-generated. It can be modified later. Avoid entering confidential information. :return: The display_name of this CreateRepositoryDetails. :rtype: str """ return self._display_name @display_name.setter def display_name(self, display_name): """ Sets the display_name of this CreateRepositoryDetails. A user-friendly display name for the repository. If not present, will be auto-generated. It can be modified later. Avoid entering confidential information. :param display_name: The display_name of this CreateRepositoryDetails. :type: str """ self._display_name = display_name @property def compartment_id(self): """ **[Required]** Gets the compartment_id of this CreateRepositoryDetails. The `OCID`__ of the repository's compartment. __ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm :return: The compartment_id of this CreateRepositoryDetails. :rtype: str """ return self._compartment_id @compartment_id.setter def compartment_id(self, compartment_id): """ Sets the compartment_id of this CreateRepositoryDetails. The `OCID`__ of the repository's compartment. __ https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm :param compartment_id: The compartment_id of this CreateRepositoryDetails. :type: str """ self._compartment_id = compartment_id @property def repository_type(self): """ **[Required]** Gets the repository_type of this CreateRepositoryDetails. The repository's supported artifact type. :return: The repository_type of this CreateRepositoryDetails. :rtype: str """ return self._repository_type @repository_type.setter def repository_type(self, repository_type): """ Sets the repository_type of this CreateRepositoryDetails. The repository's supported artifact type. :param repository_type: The repository_type of this CreateRepositoryDetails. :type: str """ self._repository_type = repository_type @property def description(self): """ Gets the description of this CreateRepositoryDetails. A short description of the repository. It can be updated later. :return: The description of this CreateRepositoryDetails. :rtype: str """ return self._description @description.setter def description(self, description): """ Sets the description of this CreateRepositoryDetails. A short description of the repository. It can be updated later. :param description: The description of this CreateRepositoryDetails. :type: str """ self._description = description @property def is_immutable(self): """ **[Required]** Gets the is_immutable of this CreateRepositoryDetails. Whether to make the repository immutable. The artifacts of an immutable repository cannot be overwritten. :return: The is_immutable of this CreateRepositoryDetails. :rtype: bool """ return self._is_immutable @is_immutable.setter def is_immutable(self, is_immutable): """ Sets the is_immutable of this CreateRepositoryDetails. Whether to make the repository immutable. The artifacts of an immutable repository cannot be overwritten. :param is_immutable: The is_immutable of this CreateRepositoryDetails. :type: bool """ self._is_immutable = is_immutable @property def freeform_tags(self): """ Gets the freeform_tags of this CreateRepositoryDetails. Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see `Resource Tags`__. Example: `{\"Department\": \"Finance\"}` __ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm :return: The freeform_tags of this CreateRepositoryDetails. :rtype: dict(str, str) """ return self._freeform_tags @freeform_tags.setter def freeform_tags(self, freeform_tags): """ Sets the freeform_tags of this CreateRepositoryDetails. Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace. For more information, see `Resource Tags`__. Example: `{\"Department\": \"Finance\"}` __ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm :param freeform_tags: The freeform_tags of this CreateRepositoryDetails. :type: dict(str, str) """ self._freeform_tags = freeform_tags @property def defined_tags(self): """ Gets the defined_tags of this CreateRepositoryDetails. Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see `Resource Tags`__. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}` __ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm :return: The defined_tags of this CreateRepositoryDetails. :rtype: dict(str, dict(str, object)) """ return self._defined_tags @defined_tags.setter def defined_tags(self, defined_tags): """ Sets the defined_tags of this CreateRepositoryDetails. Defined tags for this resource. Each key is predefined and scoped to a namespace. For more information, see `Resource Tags`__. Example: `{\"Operations\": {\"CostCenter\": \"42\"}}` __ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/resourcetags.htm :param defined_tags: The defined_tags of this CreateRepositoryDetails. :type: dict(str, dict(str, object)) """ self._defined_tags = defined_tags def __repr__(self): return formatted_flat_dict(self) def __eq__(self, other): if other is None: return False return self.__dict__ == other.__dict__ def __ne__(self, other): return not self == other
34.288591
245
0.661578
bc58cb531e495aba322dd904ee062f3deb10f945
653
py
Python
imageflow/migrations/0004_imageanalysispair_lightcurve.py
typpo/astrokit
f3c16f73ac842be26cdf20231ac5b915ab68e68f
[ "MIT" ]
8
2016-01-23T11:06:10.000Z
2021-06-27T01:38:19.000Z
imageflow/migrations/0004_imageanalysispair_lightcurve.py
typpo/astrokit
f3c16f73ac842be26cdf20231ac5b915ab68e68f
[ "MIT" ]
119
2017-02-06T18:41:47.000Z
2022-01-13T00:43:35.000Z
imageflow/migrations/0004_imageanalysispair_lightcurve.py
typpo/astrokit
f3c16f73ac842be26cdf20231ac5b915ab68e68f
[ "MIT" ]
7
2016-07-19T15:49:17.000Z
2020-10-03T05:53:52.000Z
# -*- coding: utf-8 -*- # Generated by Django 1.9.1 on 2018-03-09 04:25 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('lightcurve', '0003_lightcurve_ciband'), ('imageflow', '0003_imageanalysispair'), ] operations = [ migrations.AddField( model_name='imageanalysispair', name='lightcurve', field=models.ForeignKey(default=0, on_delete=django.db.models.deletion.CASCADE, to='lightcurve.LightCurve'), preserve_default=False, ), ]
27.208333
120
0.656968
2ceb4dcd0c83c4aa16684917980789b756726381
1,943
py
Python
train2.py
hanhanwu/mlflow-example
17280ded7b9b6d6ee81b71fedaffb50f23b04ff0
[ "Apache-2.0" ]
null
null
null
train2.py
hanhanwu/mlflow-example
17280ded7b9b6d6ee81b71fedaffb50f23b04ff0
[ "Apache-2.0" ]
null
null
null
train2.py
hanhanwu/mlflow-example
17280ded7b9b6d6ee81b71fedaffb50f23b04ff0
[ "Apache-2.0" ]
null
null
null
# The data set used in this example is from http://archive.ics.uci.edu/ml/datasets/Wine+Quality # P. Cortez, A. Cerdeira, F. Almeida, T. Matos and J. Reis. # Modeling wine preferences by data mining from physicochemical properties. In Decision Support Systems, Elsevier, 47(4):547-553, 2009. import os import warnings import sys import pandas as pd import numpy as np from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression import mlflow import mlflow.sklearn def eval_metrics(actual, pred): rmse = np.sqrt(mean_squared_error(actual, pred)) mae = mean_absolute_error(actual, pred) r2 = r2_score(actual, pred) return rmse, mae, r2 if __name__ == "__main__": warnings.filterwarnings("ignore") np.random.seed(10) # Read the wine-quality csv file (make sure you're running this from the root of MLflow!) wine_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "wine-quality.csv") data = pd.read_csv(wine_path) # Split the data into training and test sets. (0.75, 0.25) split. train, test = train_test_split(data) # The predicted column is "quality" which is a scalar from [3, 9] train_x = train.drop(["quality"], axis=1) test_x = test.drop(["quality"], axis=1) train_y = train[["quality"]] test_y = test[["quality"]] with mlflow.start_run(): lr = LinearRegression() lr.fit(train_x, train_y) predicted_qualities = lr.predict(test_x) (rmse, mae, r2) = eval_metrics(test_y, predicted_qualities) print("Linear Regression model") print(" RMSE: %s" % rmse) print(" MAE: %s" % mae) print(" R2: %s" % r2) mlflow.log_metric("rmse", rmse) mlflow.log_metric("r2", r2) mlflow.log_metric("mae", mae) mlflow.sklearn.log_model(lr, "model")
31.33871
135
0.683994
4cd76385c0ef5c5ab2b0e940b43ff3170de9886d
7,074
py
Python
tasks-deploy/calc-1/check.py
irdkwmnsb/lkshl-ctf
e5c0200ddc8ba73df5f321b87b9763fb1bbaba57
[ "MIT" ]
3
2021-03-30T06:27:58.000Z
2021-04-03T17:56:35.000Z
tasks-deploy/calc-1/check.py
irdkwmnsb/lkshl-ctf
e5c0200ddc8ba73df5f321b87b9763fb1bbaba57
[ "MIT" ]
null
null
null
tasks-deploy/calc-1/check.py
irdkwmnsb/lkshl-ctf
e5c0200ddc8ba73df5f321b87b9763fb1bbaba57
[ "MIT" ]
null
null
null
def check(attempt, context): if attempt.answer == flags[attempt.participant.id % len(flags)]: return Checked(True) if attempt.answer in flags: return CheckedPlagiarist(False, flags.index(attempt.answer)) return Checked(False) flags = ['LKL{U_r_a_calculator_MpU6R52l}', 'LKL{U_r_a_calculator_ZCMMryOX}', 'LKL{U_r_a_calculator_zQhyTruO}', 'LKL{U_r_a_calculator_ezQkaKy7}', 'LKL{U_r_a_calculator_NLOxU80o}', 'LKL{U_r_a_calculator_ZRqFdjDu}', 'LKL{U_r_a_calculator_XjYHUaTM}', 'LKL{U_r_a_calculator_nE0ykZCK}', 'LKL{U_r_a_calculator_btndlIfS}', 'LKL{U_r_a_calculator_7QWvlR6c}', 'LKL{U_r_a_calculator_9tSUJxJR}', 'LKL{U_r_a_calculator_emqWF9ZK}', 'LKL{U_r_a_calculator_WYHXD8v2}', 'LKL{U_r_a_calculator_YOLlduNM}', 'LKL{U_r_a_calculator_ptsxQFPA}', 'LKL{U_r_a_calculator_TLkf2QwS}', 'LKL{U_r_a_calculator_vlIcMnuY}', 'LKL{U_r_a_calculator_Y566J0wP}', 'LKL{U_r_a_calculator_FfG17GYR}', 'LKL{U_r_a_calculator_8tuDaVZ3}', 'LKL{U_r_a_calculator_l8gqhKJT}', 'LKL{U_r_a_calculator_W23Bkmqk}', 'LKL{U_r_a_calculator_8hzyzRLY}', 'LKL{U_r_a_calculator_ZwGIX4uq}', 'LKL{U_r_a_calculator_44VieoKJ}', 'LKL{U_r_a_calculator_1ye3W1ML}', 'LKL{U_r_a_calculator_Yp8019yg}', 'LKL{U_r_a_calculator_Gk2JkJ4C}', 'LKL{U_r_a_calculator_JHbX3ASk}', 'LKL{U_r_a_calculator_lD8P7Lp8}', 'LKL{U_r_a_calculator_qkSoFmWY}', 'LKL{U_r_a_calculator_Y0KCVTkt}', 'LKL{U_r_a_calculator_TW3PzAaP}', 'LKL{U_r_a_calculator_81iw5rtU}', 'LKL{U_r_a_calculator_w28abHkD}', 'LKL{U_r_a_calculator_Ow77dCSQ}', 'LKL{U_r_a_calculator_IKNynsBN}', 'LKL{U_r_a_calculator_0lfzdKzk}', 'LKL{U_r_a_calculator_GlobM4T3}', 'LKL{U_r_a_calculator_kwRJhgFm}', 'LKL{U_r_a_calculator_Fy9vUbvM}', 'LKL{U_r_a_calculator_XGs8L5Fy}', 'LKL{U_r_a_calculator_LjFlC4MO}', 'LKL{U_r_a_calculator_PL50o9fb}', 'LKL{U_r_a_calculator_YYysC0jQ}', 'LKL{U_r_a_calculator_myCNc6dE}', 'LKL{U_r_a_calculator_Ualz1eyO}', 'LKL{U_r_a_calculator_4nZ83c1i}', 'LKL{U_r_a_calculator_oADuZBNQ}', 'LKL{U_r_a_calculator_M4zyLLla}', 'LKL{U_r_a_calculator_YplV7fiy}', 'LKL{U_r_a_calculator_C8rLUsXI}', 'LKL{U_r_a_calculator_afko5NDt}', 'LKL{U_r_a_calculator_Wt92erop}', 'LKL{U_r_a_calculator_0IyiGj4U}', 'LKL{U_r_a_calculator_DYoPcY8o}', 'LKL{U_r_a_calculator_YJZNKCjk}', 'LKL{U_r_a_calculator_hzZaGpr1}', 'LKL{U_r_a_calculator_hoFOX7lK}', 'LKL{U_r_a_calculator_kWRAOpM3}', 'LKL{U_r_a_calculator_va8CToeH}', 'LKL{U_r_a_calculator_0IXPBSaV}', 'LKL{U_r_a_calculator_1PHgH0OJ}', 'LKL{U_r_a_calculator_zegEgcRK}', 'LKL{U_r_a_calculator_X0T92Ygd}', 'LKL{U_r_a_calculator_oH8uCjbo}', 'LKL{U_r_a_calculator_hNmOEMOl}', 'LKL{U_r_a_calculator_2bzSp4o8}', 'LKL{U_r_a_calculator_ZNizwyNt}', 'LKL{U_r_a_calculator_ODAJpXRI}', 'LKL{U_r_a_calculator_yhNcuMFr}', 'LKL{U_r_a_calculator_SUPcmZW5}', 'LKL{U_r_a_calculator_a3zhUcV0}', 'LKL{U_r_a_calculator_y9MErPu2}', 'LKL{U_r_a_calculator_FnoDGV1D}', 'LKL{U_r_a_calculator_BzZ9jOhb}', 'LKL{U_r_a_calculator_NtWTFvAH}', 'LKL{U_r_a_calculator_yAIiqPGQ}', 'LKL{U_r_a_calculator_PLLuo3xC}', 'LKL{U_r_a_calculator_GBmyws3v}', 'LKL{U_r_a_calculator_L8qcd6Ee}', 'LKL{U_r_a_calculator_gOavcaOr}', 'LKL{U_r_a_calculator_72Fpv8Nd}', 'LKL{U_r_a_calculator_XdYIByzj}', 'LKL{U_r_a_calculator_AoNTqkfl}', 'LKL{U_r_a_calculator_dEce2p7p}', 'LKL{U_r_a_calculator_ZTZpMU3W}', 'LKL{U_r_a_calculator_0LJoj4r2}', 'LKL{U_r_a_calculator_hvpnch9A}', 'LKL{U_r_a_calculator_hPtJpqbj}', 'LKL{U_r_a_calculator_kcUQsW0T}', 'LKL{U_r_a_calculator_oMSi6i7M}', 'LKL{U_r_a_calculator_7U98J5FF}', 'LKL{U_r_a_calculator_iWfQruwm}', 'LKL{U_r_a_calculator_WTJX7WGp}', 'LKL{U_r_a_calculator_PXUpDq40}', 'LKL{U_r_a_calculator_ffmtLw16}', 'LKL{U_r_a_calculator_B6P51HVa}', 'LKL{U_r_a_calculator_LjPAx2yL}', 'LKL{U_r_a_calculator_kFF5T4sh}', 'LKL{U_r_a_calculator_i9YfQRXC}', 'LKL{U_r_a_calculator_nAfXOzoO}', 'LKL{U_r_a_calculator_l19GSBTQ}', 'LKL{U_r_a_calculator_Wq72rKjA}', 'LKL{U_r_a_calculator_vGulPu0L}', 'LKL{U_r_a_calculator_31LfVROW}', 'LKL{U_r_a_calculator_Bg5w4bPr}', 'LKL{U_r_a_calculator_CotNy2m6}', 'LKL{U_r_a_calculator_FzCOV43h}', 'LKL{U_r_a_calculator_2FLo2IqC}', 'LKL{U_r_a_calculator_wgzIk4JM}', 'LKL{U_r_a_calculator_CAbTKm5l}', 'LKL{U_r_a_calculator_bJLYDIjv}', 'LKL{U_r_a_calculator_2SuV5Djb}', 'LKL{U_r_a_calculator_UAbkF5Qt}', 'LKL{U_r_a_calculator_LkphePoV}', 'LKL{U_r_a_calculator_TkoSBtQM}', 'LKL{U_r_a_calculator_KnO8ep7Z}', 'LKL{U_r_a_calculator_8kcWBc3E}', 'LKL{U_r_a_calculator_txPoYyDU}', 'LKL{U_r_a_calculator_qqWH5yDZ}', 'LKL{U_r_a_calculator_oLT4bj61}', 'LKL{U_r_a_calculator_bsgHv5vZ}', 'LKL{U_r_a_calculator_7VVEdmRg}', 'LKL{U_r_a_calculator_CUsV9aRJ}', 'LKL{U_r_a_calculator_ztKpinpx}', 'LKL{U_r_a_calculator_O5D53Xqr}', 'LKL{U_r_a_calculator_N0SkN3y4}', 'LKL{U_r_a_calculator_9RHNDx5Y}', 'LKL{U_r_a_calculator_IKHMdLJB}', 'LKL{U_r_a_calculator_RNsVjaae}', 'LKL{U_r_a_calculator_qKqrhLXJ}', 'LKL{U_r_a_calculator_9BLxNEdM}', 'LKL{U_r_a_calculator_MbXq5JC8}', 'LKL{U_r_a_calculator_CC77dsQ2}', 'LKL{U_r_a_calculator_P5ymw6CI}', 'LKL{U_r_a_calculator_OU3xO04b}', 'LKL{U_r_a_calculator_Y2s9hwqs}', 'LKL{U_r_a_calculator_AxeV9xVY}', 'LKL{U_r_a_calculator_UQZjqa81}', 'LKL{U_r_a_calculator_54dUN6Fd}', 'LKL{U_r_a_calculator_3XaAyjyo}', 'LKL{U_r_a_calculator_PakrVnJY}', 'LKL{U_r_a_calculator_UAgZQ2KG}', 'LKL{U_r_a_calculator_Av4FobCD}', 'LKL{U_r_a_calculator_z1oCuBvl}', 'LKL{U_r_a_calculator_RoIReUJ6}', 'LKL{U_r_a_calculator_XKBhtBaD}', 'LKL{U_r_a_calculator_geZpphgm}', 'LKL{U_r_a_calculator_5oYclsUG}', 'LKL{U_r_a_calculator_DYB4axYQ}', 'LKL{U_r_a_calculator_95ZSSocI}', 'LKL{U_r_a_calculator_BRmjWxOT}', 'LKL{U_r_a_calculator_zRcqvI5c}', 'LKL{U_r_a_calculator_LTPEDTgw}', 'LKL{U_r_a_calculator_tDJbMaOe}', 'LKL{U_r_a_calculator_N7A5y2Bh}', 'LKL{U_r_a_calculator_6U1pjBpG}', 'LKL{U_r_a_calculator_4aWt3Pwm}', 'LKL{U_r_a_calculator_R7m6W7GY}', 'LKL{U_r_a_calculator_FNUv7kjY}', 'LKL{U_r_a_calculator_h5FJKOTN}', 'LKL{U_r_a_calculator_BpKQW2jo}', 'LKL{U_r_a_calculator_oOcmFXbu}', 'LKL{U_r_a_calculator_0udlsiLR}', 'LKL{U_r_a_calculator_UtLKrM5Z}', 'LKL{U_r_a_calculator_IezKPuQo}', 'LKL{U_r_a_calculator_gOLFbOkl}', 'LKL{U_r_a_calculator_yK3oYGS7}', 'LKL{U_r_a_calculator_pYKf4yrG}', 'LKL{U_r_a_calculator_xHOeaHmu}', 'LKL{U_r_a_calculator_S7nttQ2d}', 'LKL{U_r_a_calculator_DVDlDC31}', 'LKL{U_r_a_calculator_FXMYbLbl}', 'LKL{U_r_a_calculator_vM1SUASp}', 'LKL{U_r_a_calculator_W0r0GiMM}', 'LKL{U_r_a_calculator_VA3vjxXb}', 'LKL{U_r_a_calculator_qsfd2cWP}', 'LKL{U_r_a_calculator_8VMjXdk0}', 'LKL{U_r_a_calculator_b9lgiQXh}', 'LKL{U_r_a_calculator_YVWtWb4I}', 'LKL{U_r_a_calculator_oDlVi728}', 'LKL{U_r_a_calculator_4FbLz39S}', 'LKL{U_r_a_calculator_DgYVWGF5}', 'LKL{U_r_a_calculator_wocR5QIX}', 'LKL{U_r_a_calculator_85FxZol2}', 'LKL{U_r_a_calculator_G7Sp8MJH}', 'LKL{U_r_a_calculator_tbOSCbqQ}', 'LKL{U_r_a_calculator_z7DHfLPs}', 'LKL{U_r_a_calculator_8UeFRm78}', 'LKL{U_r_a_calculator_OdO4c1ez}', 'LKL{U_r_a_calculator_TDhDo1wn}', 'LKL{U_r_a_calculator_1UVroyQp}', 'LKL{U_r_a_calculator_ACeiavV2}', 'LKL{U_r_a_calculator_iYaUikUR}', 'LKL{U_r_a_calculator_UKxpq2Pb}', 'LKL{U_r_a_calculator_37JUTyXf}', 'LKL{U_r_a_calculator_L34Knhkp}', 'LKL{U_r_a_calculator_bYDHgT35}', 'LKL{U_r_a_calculator_jK8xGcVY}']
884.25
6,808
0.817501
97a91fe228f2d04f8222568e1f8166184f741340
1,556
py
Python
mergecsv.py
hydrangeas/statRepo
6d26cf8ddcab620add22b195dc6149aca918bff6
[ "MIT" ]
null
null
null
mergecsv.py
hydrangeas/statRepo
6d26cf8ddcab620add22b195dc6149aca918bff6
[ "MIT" ]
null
null
null
mergecsv.py
hydrangeas/statRepo
6d26cf8ddcab620add22b195dc6149aca918bff6
[ "MIT" ]
null
null
null
#!/usr/bin/env python #-*- coding: utf-8 -*- # # usage: """ """ import csv import os import os.path import pandas as pd import sys def main(): load_path1 = "" load_path2 = "" save_path = "merged.csv" if len(sys.argv) > 1: # 引数解析 i = 1 while i < len(sys.argv): s = sys.argv[i] i = i + 1 if s == "--l1": load_path1 = sys.argv[i] elif s == "--l2": load_path2 = sys.argv[i] elif s == "--s": save_path = sys.argv[i] elif (s == "--help") or (s == "/?"): #usage() return else: continue i = i + 1 if not os.path.isfile(load_path1): print('{0}が存在しません'.format(load_path1)) return if not os.path.isfile(load_path2): print('{0}が存在しません'.format(load_path2)) return try: # CSVファイル読み込み df1 = pd.read_csv(load_path1) df2 = pd.read_csv(load_path2) # nameが同じならLOFを移送 for i, cccc in df1.iterrows(): for j, diff in df2.iterrows(): # 関数名だけ抽出 ccccFunc = cccc['name'].split('(')[0] diffFunc = diff['name'].split('(')[0] if ccccFunc == diffFunc: df1.ix[i, 'LOF'] = df2.ix[j, 'LOF'] df1.to_csv(path_or_buf=save_path, index=False, quoting=csv.QUOTE_ALL) except: import traceback traceback.print_exc() if __name__ == "__main__": ret = main()
25.508197
77
0.472365
bd899622856d80bb3ae01fdc3096e1092f9451e7
56,084
py
Python
src/sentry/south_migrations/0171_auto__chg_field_team_owner.py
AlexWayfer/sentry
ef935cda2b2e960bd602fda590540882d1b0712d
[ "BSD-3-Clause" ]
1
2022-02-09T22:56:49.000Z
2022-02-09T22:56:49.000Z
src/sentry/south_migrations/0171_auto__chg_field_team_owner.py
AlexWayfer/sentry
ef935cda2b2e960bd602fda590540882d1b0712d
[ "BSD-3-Clause" ]
6
2018-10-19T10:04:23.000Z
2019-12-09T20:29:12.000Z
src/sentry/south_migrations/0171_auto__chg_field_team_owner.py
AlexWayfer/sentry
ef935cda2b2e960bd602fda590540882d1b0712d
[ "BSD-3-Clause" ]
2
2021-01-26T09:53:39.000Z
2022-03-22T09:01:47.000Z
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Changing field 'Team.owner' db.alter_column( 'sentry_team', 'owner_id', self.gf('sentry.db.models.fields.foreignkey.FlexibleForeignKey')( to=orm['sentry.User'], null=True ) ) def backwards(self, orm): # User chose to not deal with backwards NULL issues for 'Team.owner' raise RuntimeError( "Cannot reverse this migration. 'Team.owner' and its values cannot be restored." ) models = { 'sentry.accessgroup': { 'Meta': { 'unique_together': "(('team', 'name'),)", 'object_name': 'AccessGroup' }, 'data': ( 'sentry.db.models.fields.gzippeddict.GzippedDictField', [], { 'null': 'True', 'blank': 'True' } ), 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'managed': ('django.db.models.fields.BooleanField', [], { 'default': 'False' }), 'members': ( 'django.db.models.fields.related.ManyToManyField', [], { 'to': "orm['sentry.User']", 'symmetrical': 'False' } ), 'name': ('django.db.models.fields.CharField', [], { 'max_length': '64' }), 'projects': ( 'django.db.models.fields.related.ManyToManyField', [], { 'to': "orm['sentry.Project']", 'symmetrical': 'False' } ), 'team': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Team']" } ), 'type': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], { 'default': '50' }) }, 'sentry.activity': { 'Meta': { 'object_name': 'Activity' }, 'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], { 'null': 'True' }), 'datetime': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'event': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Event']", 'null': 'True' } ), 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Group']", 'null': 'True' } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'ident': ('django.db.models.fields.CharField', [], { 'max_length': '64', 'null': 'True' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ), 'type': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.User']", 'null': 'True' } ) }, 'sentry.alert': { 'Meta': { 'object_name': 'Alert' }, 'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], { 'null': 'True' }), 'datetime': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Group']", 'null': 'True' } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'message': ('django.db.models.fields.TextField', [], {}), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ), 'related_groups': ( 'django.db.models.fields.related.ManyToManyField', [], { 'related_name': "'related_alerts'", 'symmetrical': 'False', 'through': "orm['sentry.AlertRelatedGroup']", 'to': "orm['sentry.Group']" } ), 'status': ( 'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0', 'db_index': 'True' } ) }, 'sentry.alertrelatedgroup': { 'Meta': { 'unique_together': "(('group', 'alert'),)", 'object_name': 'AlertRelatedGroup' }, 'alert': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Alert']" } ), 'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], { 'null': 'True' }), 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Group']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }) }, 'sentry.apikey': { 'Meta': { 'object_name': 'ApiKey' }, 'allowed_origins': ('django.db.models.fields.TextField', [], { 'null': 'True', 'blank': 'True' }), 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'key': ('django.db.models.fields.CharField', [], { 'unique': 'True', 'max_length': '32' }), 'label': ( 'django.db.models.fields.CharField', [], { 'default': "'Default'", 'max_length': '64', 'blank': 'True' } ), 'organization': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'key_set'", 'to': "orm['sentry.Organization']" } ), 'scopes': ('django.db.models.fields.BigIntegerField', [], { 'default': 'None' }), 'status': ( 'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0', 'db_index': 'True' } ) }, 'sentry.auditlogentry': { 'Meta': { 'object_name': 'AuditLogEntry' }, 'actor': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'audit_actors'", 'to': "orm['sentry.User']" } ), 'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {}), 'datetime': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'event': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], {}), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'ip_address': ( 'django.db.models.fields.GenericIPAddressField', [], { 'max_length': '39', 'null': 'True' } ), 'organization': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Organization']" } ), 'target_object': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'null': 'True' }), 'target_user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'blank': 'True', 'related_name': "'audit_targets'", 'null': 'True', 'to': "orm['sentry.User']" } ) }, 'sentry.authidentity': { 'Meta': { 'unique_together': "(('auth_provider', 'ident'), ('auth_provider', 'user'))", 'object_name': 'AuthIdentity' }, 'auth_provider': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.AuthProvider']" } ), 'data': ('jsonfield.fields.JSONField', [], { 'default': '{}' }), 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'ident': ('django.db.models.fields.CharField', [], { 'max_length': '128' }), 'last_synced': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'last_verified': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.User']" } ) }, 'sentry.authprovider': { 'Meta': { 'object_name': 'AuthProvider' }, 'config': ('jsonfield.fields.JSONField', [], { 'default': '{}' }), 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'default_global_access': ('django.db.models.fields.BooleanField', [], { 'default': 'True' }), 'default_role': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '50' }), 'default_teams': ( 'django.db.models.fields.related.ManyToManyField', [], { 'to': "orm['sentry.Team']", 'symmetrical': 'False', 'blank': 'True' } ), 'flags': ('django.db.models.fields.BigIntegerField', [], { 'default': '0' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'last_sync': ('django.db.models.fields.DateTimeField', [], { 'null': 'True' }), 'organization': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Organization']", 'unique': 'True' } ), 'provider': ('django.db.models.fields.CharField', [], { 'max_length': '128' }), 'sync_time': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'null': 'True' }) }, 'sentry.broadcast': { 'Meta': { 'object_name': 'Broadcast' }, 'badge': ( 'django.db.models.fields.CharField', [], { 'max_length': '32', 'null': 'True', 'blank': 'True' } ), 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'is_active': ('django.db.models.fields.BooleanField', [], { 'default': 'True', 'db_index': 'True' }), 'link': ( 'django.db.models.fields.URLField', [], { 'max_length': '200', 'null': 'True', 'blank': 'True' } ), 'message': ('django.db.models.fields.CharField', [], { 'max_length': '256' }) }, 'sentry.event': { 'Meta': { 'unique_together': "(('project', 'event_id'),)", 'object_name': 'Event', 'db_table': "'sentry_message'", 'index_together': "(('group', 'datetime'),)" }, 'checksum': ('django.db.models.fields.CharField', [], { 'max_length': '32', 'db_index': 'True' }), 'data': ('sentry.db.models.fields.node.NodeField', [], { 'null': 'True', 'blank': 'True' }), 'datetime': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'db_index': 'True' } ), 'event_id': ( 'django.db.models.fields.CharField', [], { 'max_length': '32', 'null': 'True', 'db_column': "'message_id'" } ), 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'blank': 'True', 'related_name': "'event_set'", 'null': 'True', 'to': "orm['sentry.Group']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'message': ('django.db.models.fields.TextField', [], {}), 'num_comments': ( 'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0', 'null': 'True' } ), 'platform': ('django.db.models.fields.CharField', [], { 'max_length': '64', 'null': 'True' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']", 'null': 'True' } ), 'time_spent': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], { 'null': 'True' }) }, 'sentry.eventmapping': { 'Meta': { 'unique_together': "(('project', 'event_id'),)", 'object_name': 'EventMapping' }, 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'event_id': ('django.db.models.fields.CharField', [], { 'max_length': '32' }), 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Group']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ) }, 'sentry.file': { 'Meta': { 'object_name': 'File' }, 'checksum': ('django.db.models.fields.CharField', [], { 'max_length': '40', 'null': 'True' }), 'headers': ('jsonfield.fields.JSONField', [], { 'default': '{}' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'name': ('django.db.models.fields.CharField', [], { 'max_length': '128' }), 'path': ('django.db.models.fields.TextField', [], { 'null': 'True' }), 'size': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'null': 'True' }), 'storage': ('django.db.models.fields.CharField', [], { 'max_length': '128', 'null': 'True' }), 'storage_options': ('jsonfield.fields.JSONField', [], { 'default': '{}' }), 'timestamp': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'db_index': 'True' } ), 'type': ('django.db.models.fields.CharField', [], { 'max_length': '64' }) }, 'sentry.group': { 'Meta': { 'unique_together': "(('project', 'checksum'),)", 'object_name': 'Group', 'db_table': "'sentry_groupedmessage'" }, 'active_at': ('django.db.models.fields.DateTimeField', [], { 'null': 'True', 'db_index': 'True' }), 'checksum': ('django.db.models.fields.CharField', [], { 'max_length': '32', 'db_index': 'True' }), 'culprit': ( 'django.db.models.fields.CharField', [], { 'max_length': '200', 'null': 'True', 'db_column': "'view'", 'blank': 'True' } ), 'data': ( 'sentry.db.models.fields.gzippeddict.GzippedDictField', [], { 'null': 'True', 'blank': 'True' } ), 'first_seen': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'db_index': 'True' } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'is_public': ( 'django.db.models.fields.NullBooleanField', [], { 'default': 'False', 'null': 'True', 'blank': 'True' } ), 'last_seen': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'db_index': 'True' } ), 'level': ( 'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '40', 'db_index': 'True', 'blank': 'True' } ), 'logger': ( 'django.db.models.fields.CharField', [], { 'default': "''", 'max_length': '64', 'db_index': 'True', 'blank': 'True' } ), 'message': ('django.db.models.fields.TextField', [], {}), 'num_comments': ( 'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0', 'null': 'True' } ), 'platform': ('django.db.models.fields.CharField', [], { 'max_length': '64', 'null': 'True' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']", 'null': 'True' } ), 'resolved_at': ('django.db.models.fields.DateTimeField', [], { 'null': 'True', 'db_index': 'True' }), 'score': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], { 'default': '0' }), 'status': ( 'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0', 'db_index': 'True' } ), 'time_spent_count': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], { 'default': '0' }), 'time_spent_total': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], { 'default': '0' }), 'times_seen': ( 'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '1', 'db_index': 'True' } ) }, 'sentry.groupassignee': { 'Meta': { 'object_name': 'GroupAssignee', 'db_table': "'sentry_groupasignee'" }, 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'assignee_set'", 'unique': 'True', 'to': "orm['sentry.Group']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'assignee_set'", 'to': "orm['sentry.Project']" } ), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'sentry_assignee_set'", 'to': "orm['sentry.User']" } ) }, 'sentry.groupbookmark': { 'Meta': { 'unique_together': "(('project', 'user', 'group'),)", 'object_name': 'GroupBookmark' }, 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'bookmark_set'", 'to': "orm['sentry.Group']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'bookmark_set'", 'to': "orm['sentry.Project']" } ), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'sentry_bookmark_set'", 'to': "orm['sentry.User']" } ) }, 'sentry.grouphash': { 'Meta': { 'unique_together': "(('project', 'hash'),)", 'object_name': 'GroupHash' }, 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Group']", 'null': 'True' } ), 'hash': ('django.db.models.fields.CharField', [], { 'max_length': '32', 'db_index': 'True' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']", 'null': 'True' } ) }, 'sentry.groupmeta': { 'Meta': { 'unique_together': "(('group', 'key'),)", 'object_name': 'GroupMeta' }, 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Group']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'key': ('django.db.models.fields.CharField', [], { 'max_length': '64' }), 'value': ('django.db.models.fields.TextField', [], {}) }, 'sentry.grouprulestatus': { 'Meta': { 'unique_together': "(('rule', 'group'),)", 'object_name': 'GroupRuleStatus' }, 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Group']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'last_active': ('django.db.models.fields.DateTimeField', [], { 'null': 'True' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ), 'rule': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Rule']" } ), 'status': ('django.db.models.fields.PositiveSmallIntegerField', [], { 'default': '0' }) }, 'sentry.groupseen': { 'Meta': { 'unique_together': "(('user', 'group'),)", 'object_name': 'GroupSeen' }, 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Group']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'last_seen': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.User']", 'db_index': 'False' } ) }, 'sentry.grouptagkey': { 'Meta': { 'unique_together': "(('project', 'group', 'key'),)", 'object_name': 'GroupTagKey' }, 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Group']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'key': ('django.db.models.fields.CharField', [], { 'max_length': '32' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']", 'null': 'True' } ), 'values_seen': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0' }) }, 'sentry.grouptagvalue': { 'Meta': { 'unique_together': "(('project', 'key', 'value', 'group'),)", 'object_name': 'GroupTagValue', 'db_table': "'sentry_messagefiltervalue'" }, 'first_seen': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True' } ), 'group': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'grouptag'", 'to': "orm['sentry.Group']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'key': ('django.db.models.fields.CharField', [], { 'max_length': '32' }), 'last_seen': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True' } ), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'grouptag'", 'null': 'True', 'to': "orm['sentry.Project']" } ), 'times_seen': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0' }), 'value': ('django.db.models.fields.CharField', [], { 'max_length': '200' }) }, 'sentry.helppage': { 'Meta': { 'object_name': 'HelpPage' }, 'content': ('django.db.models.fields.TextField', [], {}), 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'is_visible': ('django.db.models.fields.BooleanField', [], { 'default': 'True' }), 'key': ( 'django.db.models.fields.CharField', [], { 'max_length': '64', 'unique': 'True', 'null': 'True' } ), 'priority': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '50' }), 'title': ('django.db.models.fields.CharField', [], { 'max_length': '64' }) }, 'sentry.lostpasswordhash': { 'Meta': { 'object_name': 'LostPasswordHash' }, 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'hash': ('django.db.models.fields.CharField', [], { 'max_length': '32' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.User']", 'unique': 'True' } ) }, 'sentry.option': { 'Meta': { 'object_name': 'Option' }, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'key': ('django.db.models.fields.CharField', [], { 'unique': 'True', 'max_length': '64' }), 'last_updated': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'value': ('sentry.db.models.fields.pickle.UnicodePickledObjectField', [], {}) }, 'sentry.organization': { 'Meta': { 'object_name': 'Organization' }, 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'flags': ('django.db.models.fields.BigIntegerField', [], { 'default': '0' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'members': ( 'django.db.models.fields.related.ManyToManyField', [], { 'related_name': "'org_memberships'", 'symmetrical': 'False', 'through': "orm['sentry.OrganizationMember']", 'to': "orm['sentry.User']" } ), 'name': ('django.db.models.fields.CharField', [], { 'max_length': '64' }), 'owner': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.User']" } ), 'slug': ('django.db.models.fields.SlugField', [], { 'unique': 'True', 'max_length': '50' }), 'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0' }) }, 'sentry.organizationaccessrequest': { 'Meta': { 'unique_together': "(('team', 'member'),)", 'object_name': 'OrganizationAccessRequest' }, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'member': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.OrganizationMember']" } ), 'team': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Team']" } ) }, 'sentry.organizationmember': { 'Meta': { 'unique_together': "(('organization', 'user'), ('organization', 'email'))", 'object_name': 'OrganizationMember' }, 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'email': ( 'django.db.models.fields.EmailField', [], { 'max_length': '75', 'null': 'True', 'blank': 'True' } ), 'flags': ('django.db.models.fields.BigIntegerField', [], { 'default': '0' }), 'has_global_access': ('django.db.models.fields.BooleanField', [], { 'default': 'True' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'organization': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'member_set'", 'to': "orm['sentry.Organization']" } ), 'teams': ( 'django.db.models.fields.related.ManyToManyField', [], { 'to': "orm['sentry.Team']", 'symmetrical': 'False', 'through': "orm['sentry.OrganizationMemberTeam']", 'blank': 'True' } ), 'type': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '50' }), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'blank': 'True', 'related_name': "'sentry_orgmember_set'", 'null': 'True', 'to': "orm['sentry.User']" } ) }, 'sentry.organizationmemberteam': { 'Meta': { 'unique_together': "(('team', 'organizationmember'),)", 'object_name': 'OrganizationMemberTeam', 'db_table': "'sentry_organizationmember_teams'" }, 'id': ('sentry.db.models.fields.bounded.BoundedAutoField', [], { 'primary_key': 'True' }), 'is_active': ('django.db.models.fields.BooleanField', [], { 'default': 'True' }), 'organizationmember': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.OrganizationMember']" } ), 'team': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Team']" } ) }, 'sentry.pendingteammember': { 'Meta': { 'unique_together': "(('team', 'email'),)", 'object_name': 'PendingTeamMember' }, 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'email': ('django.db.models.fields.EmailField', [], { 'max_length': '75' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'team': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'pending_member_set'", 'to': "orm['sentry.Team']" } ), 'type': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], { 'default': '50' }) }, 'sentry.project': { 'Meta': { 'unique_together': "(('team', 'slug'), ('organization', 'slug'))", 'object_name': 'Project' }, 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'name': ('django.db.models.fields.CharField', [], { 'max_length': '200' }), 'organization': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Organization']" } ), 'platform': ('django.db.models.fields.CharField', [], { 'max_length': '32', 'null': 'True' }), 'public': ('django.db.models.fields.BooleanField', [], { 'default': 'False' }), 'slug': ('django.db.models.fields.SlugField', [], { 'max_length': '50', 'null': 'True' }), 'status': ( 'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0', 'db_index': 'True' } ), 'team': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Team']" } ) }, 'sentry.projectkey': { 'Meta': { 'object_name': 'ProjectKey' }, 'date_added': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'null': 'True' } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'label': ( 'django.db.models.fields.CharField', [], { 'max_length': '64', 'null': 'True', 'blank': 'True' } ), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'key_set'", 'to': "orm['sentry.Project']" } ), 'public_key': ( 'django.db.models.fields.CharField', [], { 'max_length': '32', 'unique': 'True', 'null': 'True' } ), 'roles': ('django.db.models.fields.BigIntegerField', [], { 'default': '1' }), 'secret_key': ( 'django.db.models.fields.CharField', [], { 'max_length': '32', 'unique': 'True', 'null': 'True' } ), 'status': ( 'sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0', 'db_index': 'True' } ), 'user_added': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'related_name': "'keys_added_set'", 'null': 'True', 'to': "orm['sentry.User']" } ) }, 'sentry.projectoption': { 'Meta': { 'unique_together': "(('project', 'key'),)", 'object_name': 'ProjectOption', 'db_table': "'sentry_projectoptions'" }, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'key': ('django.db.models.fields.CharField', [], { 'max_length': '64' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ), 'value': ('sentry.db.models.fields.pickle.UnicodePickledObjectField', [], {}) }, 'sentry.release': { 'Meta': { 'unique_together': "(('project', 'version'),)", 'object_name': 'Release' }, 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ), 'version': ('django.db.models.fields.CharField', [], { 'max_length': '64' }) }, 'sentry.releasefile': { 'Meta': { 'unique_together': "(('release', 'ident'),)", 'object_name': 'ReleaseFile' }, 'file': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.File']" } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'ident': ('django.db.models.fields.CharField', [], { 'max_length': '40' }), 'name': ('django.db.models.fields.TextField', [], {}), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ), 'release': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Release']" } ) }, 'sentry.rule': { 'Meta': { 'object_name': 'Rule' }, 'data': ('sentry.db.models.fields.gzippeddict.GzippedDictField', [], {}), 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'label': ('django.db.models.fields.CharField', [], { 'max_length': '64' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ) }, 'sentry.tagkey': { 'Meta': { 'unique_together': "(('project', 'key'),)", 'object_name': 'TagKey', 'db_table': "'sentry_filterkey'" }, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'key': ('django.db.models.fields.CharField', [], { 'max_length': '32' }), 'label': ('django.db.models.fields.CharField', [], { 'max_length': '64', 'null': 'True' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']" } ), 'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0' }), 'values_seen': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0' }) }, 'sentry.tagvalue': { 'Meta': { 'unique_together': "(('project', 'key', 'value'),)", 'object_name': 'TagValue', 'db_table': "'sentry_filtervalue'" }, 'data': ( 'sentry.db.models.fields.gzippeddict.GzippedDictField', [], { 'null': 'True', 'blank': 'True' } ), 'first_seen': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True' } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'key': ('django.db.models.fields.CharField', [], { 'max_length': '32' }), 'last_seen': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'null': 'True', 'db_index': 'True' } ), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']", 'null': 'True' } ), 'times_seen': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0' }), 'value': ('django.db.models.fields.CharField', [], { 'max_length': '200' }) }, 'sentry.team': { 'Meta': { 'unique_together': "(('organization', 'slug'),)", 'object_name': 'Team' }, 'date_added': ( 'django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now', 'null': 'True' } ), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'name': ('django.db.models.fields.CharField', [], { 'max_length': '64' }), 'organization': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Organization']" } ), 'owner': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.User']", 'null': 'True' } ), 'slug': ('django.db.models.fields.SlugField', [], { 'max_length': '50' }), 'status': ('sentry.db.models.fields.bounded.BoundedPositiveIntegerField', [], { 'default': '0' }) }, 'sentry.teammember': { 'Meta': { 'unique_together': "(('team', 'user'),)", 'object_name': 'TeamMember' }, 'date_added': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'team': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Team']" } ), 'type': ('sentry.db.models.fields.bounded.BoundedIntegerField', [], { 'default': '50' }), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.User']" } ) }, 'sentry.user': { 'Meta': { 'object_name': 'User', 'db_table': "'auth_user'" }, 'date_joined': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'email': ('django.db.models.fields.EmailField', [], { 'max_length': '75', 'blank': 'True' }), 'first_name': ('django.db.models.fields.CharField', [], { 'max_length': '30', 'blank': 'True' }), 'id': ('sentry.db.models.fields.bounded.BoundedAutoField', [], { 'primary_key': 'True' }), 'is_active': ('django.db.models.fields.BooleanField', [], { 'default': 'True' }), 'is_managed': ('django.db.models.fields.BooleanField', [], { 'default': 'False' }), 'is_staff': ('django.db.models.fields.BooleanField', [], { 'default': 'False' }), 'is_superuser': ('django.db.models.fields.BooleanField', [], { 'default': 'False' }), 'last_login': ('django.db.models.fields.DateTimeField', [], { 'default': 'datetime.datetime.now' }), 'last_name': ('django.db.models.fields.CharField', [], { 'max_length': '30', 'blank': 'True' }), 'password': ('django.db.models.fields.CharField', [], { 'max_length': '128' }), 'username': ('django.db.models.fields.CharField', [], { 'unique': 'True', 'max_length': '128' }) }, 'sentry.useroption': { 'Meta': { 'unique_together': "(('user', 'project', 'key'),)", 'object_name': 'UserOption' }, 'id': ('sentry.db.models.fields.bounded.BoundedBigAutoField', [], { 'primary_key': 'True' }), 'key': ('django.db.models.fields.CharField', [], { 'max_length': '64' }), 'project': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.Project']", 'null': 'True' } ), 'user': ( 'sentry.db.models.fields.foreignkey.FlexibleForeignKey', [], { 'to': "orm['sentry.User']" } ), 'value': ('sentry.db.models.fields.pickle.UnicodePickledObjectField', [], {}) } } complete_apps = ['sentry']
36.276843
93
0.396691
e4d456f9b04c791e78a3cb6e21f59d758c2b0457
12,334
py
Python
luigi/contrib/ssh.py
shouldsee/luigi
54a347361ae1031f06105eaf30ff88f5ef65b00c
[ "Apache-2.0" ]
5
2015-02-26T18:52:56.000Z
2017-07-07T05:47:18.000Z
luigi/contrib/ssh.py
shouldsee/luigi
54a347361ae1031f06105eaf30ff88f5ef65b00c
[ "Apache-2.0" ]
9
2017-03-22T23:38:48.000Z
2019-01-28T21:13:06.000Z
luigi/contrib/ssh.py
shouldsee/luigi
54a347361ae1031f06105eaf30ff88f5ef65b00c
[ "Apache-2.0" ]
9
2015-01-26T14:47:57.000Z
2020-07-07T17:01:25.000Z
# -*- coding: utf-8 -*- # # Copyright 2012-2015 Spotify AB # # 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. # """ Light-weight remote execution library and utilities. There are some examples in the unittest but I added another that is more luigi-specific in the examples directory (examples/ssh_remote_execution.py) :class:`RemoteContext` is meant to provide functionality similar to that of the standard library subprocess module, but where the commands executed are run on a remote machine instead, without the user having to think about prefixing everything with "ssh" and credentials etc. Using this mini library (which is just a convenience wrapper for subprocess), :class:`RemoteTarget` is created to let you stream data from a remotely stored file using the luigi :class:`~luigi.target.FileSystemTarget` semantics. As a bonus, :class:`RemoteContext` also provides a really cool feature that let's you set up ssh tunnels super easily using a python context manager (there is an example in the integration part of unittests). This can be super convenient when you want secure communication using a non-secure protocol or circumvent firewalls (as long as they are open for ssh traffic). """ import contextlib import logging import os import random import subprocess import posixpath import luigi import luigi.format import luigi.target logger = logging.getLogger('luigi-interface') class RemoteCalledProcessError(subprocess.CalledProcessError): def __init__(self, returncode, command, host, output=None): super(RemoteCalledProcessError, self).__init__(returncode, command, output) self.host = host def __str__(self): return "Command '%s' on host %s returned non-zero exit status %d" % ( self.cmd, self.host, self.returncode) class RemoteContext(object): def __init__(self, host, **kwargs): self.host = host self.username = kwargs.get('username', None) self.key_file = kwargs.get('key_file', None) self.connect_timeout = kwargs.get('connect_timeout', None) self.port = kwargs.get('port', None) self.no_host_key_check = kwargs.get('no_host_key_check', False) self.sshpass = kwargs.get('sshpass', False) self.tty = kwargs.get('tty', False) def __repr__(self): return '%s(%r, %r, %r, %r, %r)' % ( type(self).__name__, self.host, self.username, self.key_file, self.connect_timeout, self.port) def __eq__(self, other): return repr(self) == repr(other) def __hash__(self): return hash(repr(self)) def _host_ref(self): if self.username: return "{0}@{1}".format(self.username, self.host) else: return self.host def _prepare_cmd(self, cmd): connection_cmd = ["ssh", self._host_ref(), "-o", "ControlMaster=no"] if self.sshpass: connection_cmd = ["sshpass", "-e"] + connection_cmd else: connection_cmd += ["-o", "BatchMode=yes"] # no password prompts etc if self.port: connection_cmd.extend(["-p", self.port]) if self.connect_timeout is not None: connection_cmd += ['-o', 'ConnectTimeout=%d' % self.connect_timeout] if self.no_host_key_check: connection_cmd += ['-o', 'UserKnownHostsFile=/dev/null', '-o', 'StrictHostKeyChecking=no'] if self.key_file: connection_cmd.extend(["-i", self.key_file]) if self.tty: connection_cmd.append('-t') return connection_cmd + cmd def Popen(self, cmd, **kwargs): """ Remote Popen. """ prefixed_cmd = self._prepare_cmd(cmd) return subprocess.Popen(prefixed_cmd, **kwargs) def check_output(self, cmd): """ Execute a shell command remotely and return the output. Simplified version of Popen when you only want the output as a string and detect any errors. """ p = self.Popen(cmd, stdout=subprocess.PIPE) output, _ = p.communicate() if p.returncode != 0: raise RemoteCalledProcessError(p.returncode, cmd, self.host, output=output) return output @contextlib.contextmanager def tunnel(self, local_port, remote_port=None, remote_host="localhost"): """ Open a tunnel between localhost:local_port and remote_host:remote_port via the host specified by this context. Remember to close() the returned "tunnel" object in order to clean up after yourself when you are done with the tunnel. """ tunnel_host = "{0}:{1}:{2}".format(local_port, remote_host, remote_port) proc = self.Popen( # cat so we can shut down gracefully by closing stdin ["-L", tunnel_host, "echo -n ready && cat"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, ) # make sure to get the data so we know the connection is established ready = proc.stdout.read(5) assert ready == b"ready", "Didn't get ready from remote echo" yield # user code executed here proc.communicate() assert proc.returncode == 0, "Tunnel process did an unclean exit (returncode %s)" % (proc.returncode,) class RemoteFileSystem(luigi.target.FileSystem): def __init__(self, host, **kwargs): self.remote_context = RemoteContext(host, **kwargs) def exists(self, path): """ Return `True` if file or directory at `path` exist, False otherwise. """ try: self.remote_context.check_output(["test", "-e", path]) except subprocess.CalledProcessError as e: if e.returncode == 1: return False else: raise return True def listdir(self, path): while path.endswith('/'): path = path[:-1] path = path or '.' listing = self.remote_context.check_output(["find", "-L", path, "-type", "f"]).splitlines() return [v.decode('utf-8') for v in listing] def isdir(self, path): """ Return `True` if directory at `path` exist, False otherwise. """ try: self.remote_context.check_output(["test", "-d", path]) except subprocess.CalledProcessError as e: if e.returncode == 1: return False else: raise return True def remove(self, path, recursive=True): """ Remove file or directory at location `path`. """ if recursive: cmd = ["rm", "-r", path] else: cmd = ["rm", path] self.remote_context.check_output(cmd) def mkdir(self, path, parents=True, raise_if_exists=False): if self.exists(path): if raise_if_exists: raise luigi.target.FileAlreadyExists() elif not self.isdir(path): raise luigi.target.NotADirectory() else: return if parents: cmd = ['mkdir', '-p', path] else: cmd = ['mkdir', path, '2>&1'] try: self.remote_context.check_output(cmd) except subprocess.CalledProcessError as e: if b'no such file' in e.output.lower(): raise luigi.target.MissingParentDirectory() raise def _scp(self, src, dest): cmd = ["scp", "-q", "-C", "-o", "ControlMaster=no"] if self.remote_context.sshpass: cmd = ["sshpass", "-e"] + cmd else: cmd.append("-B") if self.remote_context.no_host_key_check: cmd.extend(['-o', 'UserKnownHostsFile=/dev/null', '-o', 'StrictHostKeyChecking=no']) if self.remote_context.key_file: cmd.extend(["-i", self.remote_context.key_file]) if self.remote_context.port: cmd.extend(["-P", self.remote_context.port]) if os.path.isdir(src): cmd.extend(["-r"]) cmd.extend([src, dest]) p = subprocess.Popen(cmd) output, _ = p.communicate() if p.returncode != 0: raise subprocess.CalledProcessError(p.returncode, cmd, output=output) def put(self, local_path, path): # create parent folder if not exists normpath = posixpath.normpath(path) folder = os.path.dirname(normpath) if folder and not self.exists(folder): self.remote_context.check_output(['mkdir', '-p', folder]) tmp_path = path + '-luigi-tmp-%09d' % random.randrange(0, 1e10) self._scp(local_path, "%s:%s" % (self.remote_context._host_ref(), tmp_path)) self.remote_context.check_output(['mv', tmp_path, path]) def get(self, path, local_path): # Create folder if it does not exist normpath = os.path.normpath(local_path) folder = os.path.dirname(normpath) if folder: try: os.makedirs(folder) except OSError: pass tmp_local_path = local_path + '-luigi-tmp-%09d' % random.randrange(0, 1e10) self._scp("%s:%s" % (self.remote_context._host_ref(), path), tmp_local_path) os.rename(tmp_local_path, local_path) class AtomicRemoteFileWriter(luigi.format.OutputPipeProcessWrapper): def __init__(self, fs, path): self._fs = fs self.path = path # create parent folder if not exists normpath = os.path.normpath(self.path) folder = os.path.dirname(normpath) if folder: self.fs.mkdir(folder) self.__tmp_path = self.path + '-luigi-tmp-%09d' % random.randrange(0, 1e10) super(AtomicRemoteFileWriter, self).__init__( self.fs.remote_context._prepare_cmd(['cat', '>', self.__tmp_path])) def __del__(self): super(AtomicRemoteFileWriter, self).__del__() try: if self.fs.exists(self.__tmp_path): self.fs.remote_context.check_output(['rm', self.__tmp_path]) except Exception: # Don't propagate the exception; bad things can happen. logger.exception('Failed to delete in-flight file') def close(self): super(AtomicRemoteFileWriter, self).close() self.fs.remote_context.check_output(['mv', self.__tmp_path, self.path]) @property def tmp_path(self): return self.__tmp_path @property def fs(self): return self._fs class RemoteTarget(luigi.target.FileSystemTarget): """ Target used for reading from remote files. The target is implemented using ssh commands streaming data over the network. """ def __init__(self, path, host, format=None, **kwargs): super(RemoteTarget, self).__init__(path) if format is None: format = luigi.format.get_default_format() self.format = format self._fs = RemoteFileSystem(host, **kwargs) @property def fs(self): return self._fs def open(self, mode='r'): if mode == 'w': file_writer = AtomicRemoteFileWriter(self.fs, self.path) if self.format: return self.format.pipe_writer(file_writer) else: return file_writer elif mode == 'r': file_reader = luigi.format.InputPipeProcessWrapper( self.fs.remote_context._prepare_cmd(["cat", self.path])) if self.format: return self.format.pipe_reader(file_reader) else: return file_reader else: raise Exception("mode must be 'r' or 'w' (got: %s)" % mode) def put(self, local_path): self.fs.put(local_path, self.path) def get(self, local_path): self.fs.get(self.path, local_path)
34.743662
118
0.616913
2a7aced2c217c3eedd49e65c607abaf15275a58f
1,096
py
Python
tests/test_adfgx.py
Malmosmo/pycipher2
9460cd4028dfe520f7bd4cc20f45116df3551495
[ "MIT" ]
null
null
null
tests/test_adfgx.py
Malmosmo/pycipher2
9460cd4028dfe520f7bd4cc20f45116df3551495
[ "MIT" ]
null
null
null
tests/test_adfgx.py
Malmosmo/pycipher2
9460cd4028dfe520f7bd4cc20f45116df3551495
[ "MIT" ]
null
null
null
import unittest from pycipher2 import ADFGX class TestADFGX(unittest.TestCase): def test_encrypt(self): keys = (('ypgknveqzxmdhwcblfisrauto', 'GERMAN'), ('haoqkzdmpieslycbwvgufntrx', 'ciphers')) plaintext = 'abcdefghiklmnopqrstuvwxyz' ciphertext = ('FGGFAGDADDFGXFGGGXFAAADXFDADFDXAFXXFGADXAAGDFGXXXD', 'ADAFDDGAFAADXXFAXXXGGXDFADGXDGADFAFXXGXAGGGDGFFFFD') for i, key in enumerate(keys): enc = ADFGX(*key).encrypt(plaintext) self.assertEqual(enc, ciphertext[i]) def test_decrypt(self): keys = (('ypgknveqzxmdhwcblfisrauto', 'GERMAN'), ('haoqkzdmpieslycbwvgufntrx', 'ciphers')) plaintext = 'abcdefghiklmnopqrstuvwxyz' ciphertext = ('FGGFAGDADDFGXFGGGXFAAADXFDADFDXAFXXFGADXAAGDFGXXXD', 'ADAFDDGAFAADXXFAXXXGGXDFADGXDGADFAFXXGXAGGGDGFFFFD') for i, key in enumerate(keys): dec = ADFGX(*key).decrypt(ciphertext[i]) self.assertEqual(dec, plaintext) if __name__ == '__main__': unittest.main()
33.212121
75
0.65146
ea647857c4b71de9bfa8f37825d7677cad5a45d0
365
py
Python
lab3/palindromeChecker/palindromeChecker.py
sirflano/dt228-cloud-repo
0e58503e7cd454522fac40efef4cd67bffb7bf8e
[ "MIT" ]
null
null
null
lab3/palindromeChecker/palindromeChecker.py
sirflano/dt228-cloud-repo
0e58503e7cd454522fac40efef4cd67bffb7bf8e
[ "MIT" ]
null
null
null
lab3/palindromeChecker/palindromeChecker.py
sirflano/dt228-cloud-repo
0e58503e7cd454522fac40efef4cd67bffb7bf8e
[ "MIT" ]
null
null
null
class readin: #read in string teBeChecked = input("Input string to be checked please: ") #strip string of whitespace teBeChecked = teBeChecked.replace(" ", "") #copy a reverse of the sting tempString = teBeChecked[::-1] #check if the strings are the same, print result if teBeChecked == tempString: print("True") else: print("False")
20.277778
60
0.676712
89d6f5ec490d305ff6905ef2efd4f8d5f6470ad7
12,008
py
Python
python/ccxt/lykke.py
hippylover/ccxt
db304e95b699c1971ad37b9053ae71fcb5dc3b03
[ "MIT" ]
2
2018-02-28T02:51:59.000Z
2018-02-28T03:25:51.000Z
python/ccxt/lykke.py
August-Ghost/ccxt
886c596ffde611b5a92cb5b6e3788ff010324c74
[ "MIT" ]
null
null
null
python/ccxt/lykke.py
August-Ghost/ccxt
886c596ffde611b5a92cb5b6e3788ff010324c74
[ "MIT" ]
9
2018-02-20T18:24:00.000Z
2019-06-18T14:23:11.000Z
# -*- coding: utf-8 -*- from ccxt.base.exchange import Exchange import math class lykke (Exchange): def describe(self): return self.deep_extend(super(lykke, self).describe(), { 'id': 'lykke', 'name': 'Lykke', 'countries': 'CH', 'version': 'v1', 'rateLimit': 200, 'has': { 'CORS': False, 'fetchOHLCV': False, 'fetchTrades': False, }, 'requiredCredentials': { 'apiKey': True, 'secret': False, }, 'urls': { 'logo': 'https://user-images.githubusercontent.com/1294454/34487620-3139a7b0-efe6-11e7-90f5-e520cef74451.jpg', 'api': { 'mobile': 'https://api.lykkex.com/api', 'public': 'https://hft-api.lykke.com/api', 'private': 'https://hft-api.lykke.com/api', 'test': { 'mobile': 'https://api.lykkex.com/api', 'public': 'https://hft-service-dev.lykkex.net/api', 'private': 'https://hft-service-dev.lykkex.net/api', }, }, 'www': 'https://www.lykke.com', 'doc': [ 'https://hft-api.lykke.com/swagger/ui/', 'https://www.lykke.com/lykke_api', ], 'fees': 'https://www.lykke.com/trading-conditions', }, 'api': { 'mobile': { 'get': [ 'AllAssetPairRates/{market}', ], }, 'public': { 'get': [ 'AssetPairs', 'AssetPairs/{id}', 'IsAlive', 'OrderBooks', 'OrderBooks/{AssetPairId}', ], }, 'private': { 'get': [ 'Orders', 'Orders/{id}', 'Wallets', ], 'post': [ 'Orders/limit', 'Orders/market', 'Orders/{id}/Cancel', ], }, }, 'fees': { 'trading': { 'tierBased': False, 'percentage': True, 'maker': 0.0010, 'taker': 0.0019, }, 'funding': { 'tierBased': False, 'percentage': False, 'withdraw': { 'BTC': 0.001, }, 'deposit': { 'BTC': 0, }, }, }, }) def fetch_balance(self, params={}): self.load_markets() balances = self.privateGetWallets() result = {'info': balances} for i in range(0, len(balances)): balance = balances[i] currency = balance['AssetId'] total = balance['Balance'] used = balance['Reserved'] free = total - used result[currency] = { 'free': free, 'used': used, 'total': total, } return self.parse_balance(result) def cancel_order(self, id, symbol=None, params={}): return self.privatePostOrdersIdCancel({'id': id}) def create_order(self, symbol, type, side, amount, price=None, params={}): self.load_markets() market = self.market(symbol) query = { 'AssetPairId': market['id'], 'OrderAction': self.capitalize(side), 'Volume': amount, } if type == 'market': query['Asset'] = market['base'] if (side == 'buy') else market['quote'] elif type == 'limit': query['Price'] = price method = 'privatePostOrders' + self.capitalize(type) result = getattr(self, method)(self.extend(query, params)) return { 'id': None, 'info': result, } def fetch_markets(self): markets = self.publicGetAssetPairs() result = [] for i in range(0, len(markets)): market = markets[i] id = market['Id'] base = market['BaseAssetId'] quote = market['QuotingAssetId'] base = self.common_currency_code(base) quote = self.common_currency_code(quote) symbol = market['Name'] precision = { 'amount': market['Accuracy'], 'price': market['InvertedAccuracy'], } result.append(self.extend(self.fees['trading'], { 'id': id, 'symbol': symbol, 'base': base, 'quote': quote, 'active': True, 'info': market, 'lot': math.pow(10, -precision['amount']), 'precision': precision, 'limits': { 'amount': { 'min': math.pow(10, -precision['amount']), 'max': math.pow(10, precision['amount']), }, 'price': { 'min': math.pow(10, -precision['price']), 'max': math.pow(10, precision['price']), }, }, })) return result def parse_ticker(self, ticker, market=None): timestamp = self.milliseconds() symbol = None if market: symbol = market['symbol'] ticker = ticker['Result'] return { 'symbol': symbol, 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'high': None, 'low': None, 'bid': float(ticker['Rate']['Bid']), 'ask': float(ticker['Rate']['Ask']), 'vwap': None, 'open': None, 'close': None, 'first': None, 'last': None, 'change': None, 'percentage': None, 'average': None, 'baseVolume': None, 'quoteVolume': None, 'info': ticker, } def fetch_ticker(self, symbol, params={}): self.load_markets() market = self.market(symbol) ticker = self.mobileGetAllAssetPairRatesMarket(self.extend({ 'market': market['id'], }, params)) return self.parse_ticker(ticker, market) def parse_order_status(self, status): if status == 'Pending': return 'open' elif status == 'InOrderBook': return 'open' elif status == 'Processing': return 'open' elif status == 'Matched': return 'closed' elif status == 'Cancelled': return 'canceled' elif status == 'NotEnoughFunds': return 'NotEnoughFunds' elif status == 'NoLiquidity': return 'NoLiquidity' elif status == 'UnknownAsset': return 'UnknownAsset' elif status == 'LeadToNegativeSpread': return 'LeadToNegativeSpread' return status def parse_order(self, order, market=None): status = self.parse_order_status(order['Status']) symbol = None if not market: if 'AssetPairId' in order: if order['AssetPairId'] in self.markets_by_id: market = self.markets_by_id[order['AssetPairId']] if market: symbol = market['symbol'] timestamp = None if 'LastMatchTime' in order: timestamp = self.parse8601(order['LastMatchTime']) elif 'Registered' in order: timestamp = self.parse8601(order['Registered']) elif 'CreatedAt' in order: timestamp = self.parse8601(order['CreatedAt']) price = self.safe_float(order, 'Price') amount = self.safe_float(order, 'Volume') remaining = self.safe_float(order, 'RemainingVolume') filled = amount - remaining cost = filled * price result = { 'info': order, 'id': order['Id'], 'timestamp': timestamp, 'datetime': self.iso8601(timestamp), 'symbol': symbol, 'type': None, 'side': None, 'price': price, 'cost': cost, 'average': None, 'amount': amount, 'filled': filled, 'remaining': remaining, 'status': status, 'fee': None, } return result def fetch_order(self, id, symbol=None, params={}): response = self.privateGetOrdersId(self.extend({ 'id': id, }, params)) return self.parse_order(response) def fetch_orders(self, symbol=None, since=None, limit=None, params={}): response = self.privateGetOrders() return self.parse_orders(response, None, since, limit) def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}): response = self.privateGetOrders(self.extend({ 'status': 'InOrderBook', }, params)) return self.parse_orders(response, None, since, limit) def fetch_closed_orders(self, symbol=None, since=None, limit=None, params={}): response = self.privateGetOrders(self.extend({ 'status': 'Matched', }, params)) return self.parse_orders(response, None, since, limit) def fetch_order_book(self, symbol=None, params={}): self.load_markets() response = self.publicGetOrderBooksAssetPairId(self.extend({ 'AssetPairId': self.market_id(symbol), }, params)) orderbook = { 'timestamp': None, 'bids': [], 'asks': [], } timestamp = None for i in range(0, len(response)): side = response[i] if side['IsBuy']: orderbook['bids'] = self.array_concat(orderbook['bids'], side['Prices']) else: orderbook['asks'] = self.array_concat(orderbook['asks'], side['Prices']) timestamp = self.parse8601(side['Timestamp']) if not orderbook['timestamp']: orderbook['timestamp'] = timestamp else: orderbook['timestamp'] = max(orderbook['timestamp'], timestamp) if not timestamp: timestamp = self.milliseconds() return self.parse_order_book(orderbook, orderbook['timestamp'], 'bids', 'asks', 'Price', 'Volume') def parse_bid_ask(self, bidask, priceKey=0, amountKey=1): price = float(bidask[priceKey]) amount = float(bidask[amountKey]) if amount < 0: amount = -amount return [price, amount] def sign(self, path, api='public', method='GET', params={}, headers=None, body=None): url = self.urls['api'][api] + '/' + self.implode_params(path, params) query = self.omit(params, self.extract_params(path)) if api == 'public': if query: url += '?' + self.urlencode(query) elif api == 'private': if method == 'GET': if query: url += '?' + self.urlencode(query) self.check_required_credentials() headers = { 'api-key': self.apiKey, 'Accept': 'application/json', 'Content-Type': 'application/json', } if method == 'POST': if params: body = self.json(params) return {'url': url, 'method': method, 'body': body, 'headers': headers}
35.421829
126
0.461942
8984f586dc582596a1ac4a5d1bd624f72b1e11b4
1,109
py
Python
main.py
tejaskj/youtube-mp3-downloader
e91ebf2399cdcdb287f1931c73149b1b575792cd
[ "MIT" ]
null
null
null
main.py
tejaskj/youtube-mp3-downloader
e91ebf2399cdcdb287f1931c73149b1b575792cd
[ "MIT" ]
null
null
null
main.py
tejaskj/youtube-mp3-downloader
e91ebf2399cdcdb287f1931c73149b1b575792cd
[ "MIT" ]
null
null
null
# add the below to yld_opts dict to set the download location # 'outtmpl': 'somewhere/%(extractor_key)s/%(extractor)s-%(id)s-%(title)s.%(ext)s', from __future__ import unicode_literals import youtube_dl from datetime import datetime import sys def my_hook(d): if d['status'] == 'finished': print('Done downloading, now converting ...') def main(): try: link = sys.argv[1] link = link.replace('music', 'www') date_time = datetime.now() date_time_string = datetime.strftime(date_time, '%Y_%m_%d_%H_%M_%S') folder_name_by_date = date_time_string + '_folder' ydl_opts = { 'format': 'bestaudio/best', 'ffmpeg_location': 'ffmpeg/bin', 'outtmpl': folder_name_by_date+'/%(title)s.%(ext)s', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], 'progress_hooks': [my_hook], } with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([str(link)]) except Exception as e: print("Please enter link!") print(f"Please you the format - [python {sys.argv[0]} '<link>']") if __name__ == '__main__': main()
25.204545
82
0.670875
3b879f3be16270620b7a8c8b5186e9271eec9a3a
14,960
py
Python
tensortrade/feed/api/float/window/ewm.py
nicomon24/tensortrade
870ae06a4440045edde4f5306e64264bd33d5b67
[ "Apache-2.0" ]
2
2020-10-22T01:01:50.000Z
2021-03-06T17:27:51.000Z
tensortrade/feed/api/float/window/ewm.py
nicomon24/tensortrade
870ae06a4440045edde4f5306e64264bd33d5b67
[ "Apache-2.0" ]
1
2020-09-01T09:38:23.000Z
2020-09-01T09:38:23.000Z
tensortrade/feed/api/float/window/ewm.py
nicomon24/tensortrade
870ae06a4440045edde4f5306e64264bd33d5b67
[ "Apache-2.0" ]
1
2020-09-20T21:39:35.000Z
2020-09-20T21:39:35.000Z
""" ewm.py contains functions and classes for exponential weighted moving stream operations. """ from typing import List, Tuple import numpy as np from tensortrade.feed.core.base import Stream from tensortrade.feed.api.float import Float class ExponentialWeightedMovingAverage(Stream[float]): r"""A stream operator that computes an exponential weighted moving average on a given float stream. Parameters ---------- alpha : float The smoothing factor :math:`\alpha` directly, :math:`0 < \alpha \leq 1`. adjust : bool Divide by decaying adjustment factor in beginning periods to account for imbalance in relative weightings (viewing EWMA as a moving average). ignore_na : bool Ignore missing values when calculating weights. min_periods : int Minimum number of observations in window required to have a value (otherwise result is NA). References ---------- .. [1] https://github.com/pandas-dev/pandas/blob/d9fff2792bf16178d4e450fe7384244e50635733/pandas/_libs/window/aggregations.pyx#L1801 """ def __init__(self, alpha: float, adjust: bool, ignore_na: bool, min_periods: int) -> None: super().__init__() self.alpha = alpha self.adjust = adjust self.ignore_na = ignore_na self.min_periods = max(min_periods, 1) self.i = 0 self.n = 0 self.avg = None self.factor = 1 - alpha self.new_wt = 1 if self.adjust else self.alpha self.old_wt = 1 def forward(self) -> float: value = self.inputs[0].value if self.avg is None: is_observation = (value == value) self.n += int(is_observation) self.avg = value return self.avg if self.n >= self.min_periods else np.nan is_observation = (value == value) self.n += is_observation if self.avg == self.avg: if is_observation or not self.ignore_na: self.old_wt *= self.factor if is_observation: # avoid numerical errors on constant series if self.avg != value: num = self.old_wt * self.avg + self.new_wt * value den = self.old_wt + self.new_wt self.avg = num / den if self.adjust: self.old_wt += self.new_wt else: self.old_wt = 1 elif is_observation: self.avg = value return self.avg if self.n >= self.min_periods else np.nan def has_next(self) -> bool: return True def reset(self) -> None: self.i = 0 self.n = 0 self.avg = None self.old_wt = 1 class ExponentialWeightedMovingCovariance(Stream[float]): r"""A stream operator that computes an exponential weighted moving average on a given float stream. Parameters ---------- alpha : float The smoothing factor :math:`\alpha` directly, :math:`0 < \alpha \leq 1`. adjust : bool Divide by decaying adjustment factor in beginning periods to account for imbalance in relative weightings (viewing EWMA as a moving average). ignore_na : bool Ignore missing values when calculating weights. min_periods : int Minimum number of observations in window required to have a value (otherwise result is NA). bias : bool Use a standard estimation bias correction """ def __init__(self, alpha: float, adjust: bool, ignore_na: bool, min_periods: int, bias: bool) -> None: super().__init__() self.alpha = alpha self.adjust = adjust self.ignore_na = ignore_na self.min_periods = min_periods self.bias = bias self.i = 0 self.n = 0 self.minp = max(self.min_periods, 1) self.avg = None self.factor = 1 - alpha self.new_wt = 1 if self.adjust else self.alpha self.old_wt = 1 self.mean_x = None self.mean_y = None self.cov = 0 self.sum_wt = 1 self.sum_wt2 = 1 self.old_wt = 1 def forward(self) -> float: v1 = self.inputs[0].value v2 = self.inputs[1].value if self.mean_x is None and self.mean_y is None: self.mean_x = v1 self.mean_y = v2 is_observation = (self.mean_x == self.mean_x) and (self.mean_y == self.mean_y) self.n += int(is_observation) if not is_observation: self.mean_x = np.nan self.mean_y = np.nan return (0. if self.bias else np.nan) if self.n >= self.minp else np.nan is_observation = (v1 == v1) and (v2 == v2) self.n += is_observation if self.mean_x == self.mean_x: if is_observation or not self.ignore_na: self.sum_wt *= self.factor self.sum_wt2 *= (self.factor * self.factor) self.old_wt *= self.factor if is_observation: old_mean_x = self.mean_x old_mean_y = self.mean_y # avoid numerical errors on constant streams wt_sum = self.old_wt + self.new_wt if self.mean_x != v1: self.mean_x = ((self.old_wt * old_mean_x) + (self.new_wt * v1)) / wt_sum # avoid numerical errors on constant series if self.mean_y != v2: self.mean_y = ((self.old_wt * old_mean_y) + (self.new_wt * v2)) / wt_sum d1 = old_mean_x - self.mean_x d2 = old_mean_y - self.mean_y d3 = v1 - self.mean_x d4 = v2 - self.mean_y t1 = self.old_wt * (self.cov + d1 * d2) t2 = self.new_wt * d3 * d4 self.cov = (t1 + t2) / wt_sum self.sum_wt += self.new_wt self.sum_wt2 += self.new_wt * self.new_wt self.old_wt += self.new_wt if not self.adjust: self.sum_wt /= self.old_wt self.sum_wt2 /= self.old_wt * self.old_wt self.old_wt = 1 elif is_observation: self.mean_x = v1 self.mean_y = v2 if self.n >= self.minp: if not self.bias: numerator = self.sum_wt * self.sum_wt denominator = numerator - self.sum_wt2 if denominator > 0: output = ((numerator / denominator) * self.cov) else: output = np.nan else: output = self.cov else: output = np.nan return output def has_next(self) -> bool: return True def reset(self) -> None: self.avg = None self.new_wt = 1 if self.adjust else self.alpha self.old_wt = 1 self.mean_x = None self.mean_y = None self.cov = 0 self.sum_wt = 1 self.sum_wt2 = 1 self.old_wt = 1 class EWM(Stream[List[float]]): r"""Provide exponential weighted (EW) functions. Exactly one parameter: `com`, `span`, `halflife`, or `alpha` must be provided. Parameters ---------- com : float, optional Specify decay in terms of center of mass, :math:`\alpha = 1 / (1 + com)`, for :math:`com \geq 0`. span : float, optional Specify decay in terms of span, :math:`\alpha = 2 / (span + 1)`, for :math:`span \geq 1`. halflife : float, str, timedelta, optional Specify decay in terms of half-life, :math:`\alpha = 1 - \exp\left(-\ln(2) / halflife\right)`, for :math:`halflife > 0`. If ``times`` is specified, the time unit (str or timedelta) over which an observation decays to half its value. Only applicable to ``mean()`` and halflife value will not apply to the other functions. alpha : float, optional Specify smoothing factor :math:`\alpha` directly, :math:`0 < \alpha \leq 1`. min_periods : int, default 0 Minimum number of observations in window required to have a value (otherwise result is NA). adjust : bool, default True Divide by decaying adjustment factor in beginning periods to account for imbalance in relative weightings (viewing EWMA as a moving average). - When ``adjust=True`` (default), the EW function is calculated using weights :math:`w_i = (1 - \alpha)^i`. For example, the EW moving average of the series [:math:`x_0, x_1, ..., x_t`] would be: .. math:: y_t = \frac{x_t + (1 - \alpha)x_{t-1} + (1 - \alpha)^2 x_{t-2} + ... + (1 - \alpha)^t x_0}{1 + (1 - \alpha) + (1 - \alpha)^2 + ... + (1 - \alpha)^t} - When ``adjust=False``, the exponentially weighted function is calculated recursively: .. math:: \begin{split} y_0 &= x_0\\ y_t &= (1 - \alpha) y_{t-1} + \alpha x_t, \end{split} ignore_na : bool, default False Ignore missing values when calculating weights. - When ``ignore_na=False`` (default), weights are based on absolute positions. - When ``ignore_na=True``, weights are based on relative positions. See Also -------- .. [1] https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.ewm.html References ---------- .. [1] https://github.com/pandas-dev/pandas/blob/d9fff2792bf16178d4e450fe7384244e50635733/pandas/core/window/ewm.py#L65 """ def __init__( self, com: float = None, span: float = None, halflife: float = None, alpha: float = None, min_periods: int = 0, adjust: bool = True, ignore_na: bool = False): super().__init__() self.com = com self.span = span self.halflife = halflife self.min_periods = min_periods self.adjust = adjust self.ignore_na = ignore_na if alpha: assert 0 < alpha <= 1 self.alpha = alpha elif com: assert com >= 0 self.alpha = 1 / (1 + com) elif span: assert span >= 1 self.alpha = 2 / (1 + span) elif halflife: assert halflife > 0 self.alpha = 1 - np.exp(np.log(0.5) / halflife) self.history = [] self.weights = [] def forward(self) -> "Tuple[List[float], List[float]]": value = self.inputs[0].value if self.ignore_na: if not np.isnan(value): self.history += [value] # Compute weights if not self.adjust and len(self.weights) > 0: self.weights[-1] *= self.alpha self.weights += [(1 - self.alpha) ** len(self.history)] else: self.history += [value] # Compute weights if not self.adjust and len(self.weights) > 0: self.weights[-1] *= self.alpha self.weights += [(1 - self.alpha)**len(self.history)] return self.history, self.weights def has_next(self) -> bool: return True def mean(self) -> "Stream[float]": """Computes the exponential weighted moving average. Returns ------- `Stream[float]` The exponential weighted moving average stream based on the underlying stream of values. """ return ExponentialWeightedMovingAverage( alpha=self.alpha, min_periods=self.min_periods, adjust=self.adjust, ignore_na=self.ignore_na )(self.inputs[0]).astype("float") def var(self, bias=False) -> "Stream[float]": """Computes the exponential weighted moving variance. Returns ------- `Stream[float]` The exponential weighted moving variance stream based on the underlying stream of values. """ return ExponentialWeightedMovingCovariance( alpha=self.alpha, adjust=self.adjust, ignore_na=self.ignore_na, min_periods=self.min_periods, bias=bias )(self.inputs[0], self.inputs[0]).astype("float") def std(self, bias=False) -> "Stream[float]": """Computes the exponential weighted moving standard deviation. Returns ------- `Stream[float]` The exponential weighted moving standard deviation stream based on the underlying stream of values. """ return self.var(bias).sqrt() @Float.register(["ewm"]) def ewm(s: "Stream[float]", com: float = None, span: float = None, halflife: float = None, alpha: float = None, min_periods: int = 0, adjust: bool = True, ignore_na: bool = False) -> "Stream[Tuple[List[float], List[float]]]": r"""Computes the weights and values in order to perform an exponential weighted moving operation. Parameters ---------- s : `Stream[float]` A float stream. com : float, optional Specify decay in terms of center of mass, :math:`\alpha = 1 / (1 + com)`, for :math:`com \geq 0`. span : float, optional Specify decay in terms of span, :math:`\alpha = 2 / (span + 1)`, for :math:`span \geq 1`. halflife : float, optional Specify decay in terms of half-life, :math:`\alpha = 1 - \exp\left(-\ln(2) / halflife\right)`, for :math:`halflife > 0`. alpha : float, optional Specify smoothing factor :math:`\alpha` directly, :math:`0 < \alpha \leq 1`. min_periods : int, default 0 Minimum number of observations in window required to have a value (otherwise result is NA). adjust : bool, default True Divide by decaying adjustment factor in beginning periods to account for imbalance in relative weightings (viewing EWMA as a moving average). ignore_na : bool, default False Ignore missing values when calculating weights. Returns ------- `Stream[Tuple[List[float], List[float]]]` A stream of weights and values to be used for computation of exponential weighted moving operations. """ return EWM( com=com, span=span, halflife=halflife, alpha=alpha, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na )(s)
33.024283
136
0.549198
04074615c69392ff0430b1404394d47adc6c6009
851
py
Python
bspider/agent/controller/node.py
littlebai3618/bspider
ff4d003cd0825247db4efe62db95f9245c0a303c
[ "BSD-3-Clause" ]
3
2020-06-19T03:52:29.000Z
2021-05-21T05:50:46.000Z
bspider/agent/controller/node.py
littlebai3618/bspider
ff4d003cd0825247db4efe62db95f9245c0a303c
[ "BSD-3-Clause" ]
2
2021-03-31T19:39:03.000Z
2021-05-12T02:10:26.000Z
bspider/agent/controller/node.py
littlebai3618/bspider
ff4d003cd0825247db4efe62db95f9245c0a303c
[ "BSD-3-Clause" ]
null
null
null
""" 封装查看节点信息操作为api """ from flask import Blueprint from bspider.agent.service.node import NodeService from bspider.core.api import auth from .validators.worker_forms import RegisterForm node = Blueprint('node_bp', __name__) node_service = NodeService() @node.route('/node', methods=['GET']) def status(): """node-status 路由无需保护""" return node_service.node_status() @node.route('/worker', methods=['POST']) @auth.login_required def start_worker(): form = RegisterForm() return node_service.start_worker(**form.to_dict()) @node.route('/worker/<int:worker_id>', methods=['DELETE']) @auth.login_required def stop_worker(worker_id): return node_service.stop_worker(worker_id) @node.route('/worker/<int:worker_id>', methods=['GET']) @auth.login_required def get_worker(worker_id): return node_service.get_worker(worker_id)
25.029412
58
0.741481
8d3b58aff9c0cdcf90b57bf5e5da87bf85db3719
17,891
py
Python
pyaoscx/device.py
aruba/pyaoscx
913506eef8643f4e7b92f0d1633310e62ec5f7e2
[ "Apache-2.0" ]
25
2020-03-12T15:55:03.000Z
2022-03-25T14:39:17.000Z
pyaoscx/device.py
aruba/pyaoscx
913506eef8643f4e7b92f0d1633310e62ec5f7e2
[ "Apache-2.0" ]
13
2020-09-25T18:59:30.000Z
2022-01-19T05:46:51.000Z
pyaoscx/device.py
aruba/pyaoscx
913506eef8643f4e7b92f0d1633310e62ec5f7e2
[ "Apache-2.0" ]
11
2020-05-20T15:08:13.000Z
2022-03-21T18:42:12.000Z
# (C) Copyright 2019-2021 Hewlett Packard Enterprise Development LP. # Apache License 2.0 from copy import deepcopy import logging import json from urllib.parse import quote_plus from pyaoscx.exceptions.generic_op_error import GenericOperationError from pyaoscx.exceptions.response_error import ResponseError from pyaoscx.exceptions.verification_error import VerificationError from pyaoscx.utils import util as utils from pyaoscx.session import Session from pyaoscx.pyaoscx_factory import PyaoscxFactory, Singleton from pyaoscx.pyaoscx_module import PyaoscxModule class Device(PyaoscxFactory, metaclass=Singleton): ''' Represents a Device and all of its attributes. Keeping all the important information inside one class. ''' base_uri = "system" def __init__(self, session): self.session = session self.firmware_version = None # Used to set attributes self.config_attrs = [] self.materialized = False self.__original_attributes = {} # Set firmware version self.get_firmware_version() @PyaoscxModule.connected def get(self): ''' Perform a GET call to retrieve device attributes After data from response, Device class attributes are generated using create_attrs() ''' logging.info("Retrieving the switch attributes and capabilities") non_configurable_attrs = [ "admin_password_set", "aruba_central", "boot_time", "capabilities", "capacities", "mgmt_intf_status", "platform_name", "software_images", "software_info", "software_version", "qos_defaults", ] configurable_attrs = [ "domain_name", "hostname", "other_config", "qos_config", "qos_default", "q_profile_default", ] # Concatenate both config and non-config attrs without duplicates all_attributes = list(set(non_configurable_attrs + configurable_attrs)) attributes_list = ','.join(all_attributes) uri = "system?attributes={}&depth={}".format( attributes_list, self.session.api.default_depth ) try: response = self.session.request("GET", uri) except Exception as e: raise ResponseError("GET", e) if not utils._response_ok(response, "GET"): raise GenericOperationError(response.text, response.status_code) # Load into json format data = json.loads(response.text) # Create class attributes using util.create_attrs utils.create_attrs(self, data) utils.set_config_attrs( self, data, "config_attrs", non_configurable_attrs ) # Save original attributes self.__original_attributes = deepcopy( utils.get_attrs(self, self.config_attrs) ) # Set device as materialized self.materialized = True @property def modified(self): """ Verifies if there has been a modification for this object or not. """ device_data = utils.get_attrs(self, self.config_attrs) return device_data != self.__original_attributes @PyaoscxModule.connected def get_subsystems(self): ''' Perform GET call to retrieve subsystem attributes and create a dictionary containing them ''' # Log logging.info( "Retrieving the switch subsystem attributes and capabilities") # Attribute list attributes = [ 'product_info', 'power_supplies', 'interfaces', 'fans', 'resource_utilization' ] # Format attribute list by joining every element with a comma attributes_list = ','.join(attributes) # Build URI uri = "{}system/subsystems?attributes={}&depth={}".format( self.session.base_url, attributes_list, self.session.api.default_subsystem_facts_depth) try: # Try to perform a GET call and retrieve the data response = self.session.s.get( uri, verify=False, proxies=self.session.proxy) except Exception as e: raise ResponseError('GET', e) if not utils._response_ok(response, "GET"): raise GenericOperationError(response.text, response.status_code) # Load into json format data = json.loads(response.text) data_subsystems = {'subsystems' : data} # Create class attributes using util.create_attrs utils.create_attrs(self, data_subsystems) @PyaoscxModule.connected def get_firmware_version(self): ''' Perform a GET call to retrieve device firmware version :return: firmware_version: The firmware version ''' uri = "{}firmware".format(self.session.base_url) try: response = self.session.s.get( uri, verify=False, proxies=self.session.proxy) except Exception as e: raise ResponseError('GET', e) if not utils._response_ok(response, "GET"): raise GenericOperationError(response.text, response.status_code) data = json.loads(response.text) self.firmware_version = data["current_version"] # Return Version return self.firmware_version @PyaoscxModule.materialized def apply(self): """ Main method to update an existing Device object. :return modified: Boolean, True if object was created or modified False otherwise. """ return self.update() @PyaoscxModule.materialized def update(self): """ Perform a PUT call to apply changes to a Device object. :return modified: Boolean, True if object was created or modified False otherwise. """ if not self.modified: return False device_data = utils.get_attrs(self, self.config_attrs) put_data = json.dumps(device_data) try: response = self.session.request("PUT", "system", data=put_data) except Exception as e: raise ResponseError("PUT", e) if not utils._response_ok(response, "PUT"): raise GenericOperationError( response.text, response.status_code ) # Set new original attributes self.__original_attributes = deepcopy(device_data) return True #################################################################### # IMPERATIVE FUNCTIONS #################################################################### def update_banner(self, banner_info, banner_type='banner'): ''' Perform a PUT request to modify a Device's Banner :param banner_info: String to be configured as the banner. :param banner_type: Type of banner being configured on the switch. Either banner or banner_exec :return modified: Returns True if Banner was modified. False otherwise ''' modified = False logging.info("Setting Banner") depth = self.session.api.default_depth # Second GET request to obtain just the variables that are writable selector = self.session.api.default_selector payload = { "depth": depth, "selector": selector } uri = "{base_url}{class_uri}".format( base_url=self.session.base_url, class_uri=Device.base_uri, depth=self.session.api.default_depth ) try: response = self.session.s.get( uri, verify=False, proxies=self.session.proxy, params=payload) except Exception as e: raise ResponseError('GET', e) if not utils._response_ok(response, "GET"): raise GenericOperationError(response.text, response.status_code) # Configurable data config_data = json.loads(response.text) # If Banner type does not exist if banner_type not in config_data['other_config']: # Create Banner type config_data['other_config'][banner_type] = "" # Verify data is different if config_data['other_config'][banner_type] == banner_info: modified = False else: # Modify Banner config_data['other_config'][banner_type] = banner_info # UPDATE Banner put_uri = "{base_url}{class_uri}".format( base_url=self.session.base_url, class_uri=Device.base_uri ) # Set data to be used inside PUT put_data = json.dumps(config_data, sort_keys=True, indent=4) try: response = self.session.s.put( put_uri, verify=False, data=put_data, proxies=self.session.proxy) except Exception as e: raise ResponseError('PUT', e) if not utils._response_ok(response, "PUT"): raise GenericOperationError( response.text, response.status_code, "UPDATE SYSTEM BANNER") # Object was modified, returns True modified = True return modified def delete_banner(self, banner_type='banner'): ''' Perform a DELETE request to delete a device's Banner :param banner_type: Type of banner being removed on the switch. Either banner or banner_exec :return modified: Returns True if Banner was modified. False otherwise ''' logging.info("Removing Banner") depth = self.session.api.default_depth # Second GET request to obtain just the variables that are writable selector = self.session.api.default_selector payload = { "depth": depth, "selector": selector } uri = "{base_url}{class_uri}".format( base_url=self.session.base_url, class_uri=Device.base_uri, depth=self.session.api.default_depth ) try: response = self.session.s.get( uri, verify=False, proxies=self.session.proxy, params=payload) except Exception as e: raise ResponseError('GET', e) if not utils._response_ok(response, "GET"): raise GenericOperationError(response.text, response.status_code) # Configurable data config_data = json.loads(response.text) # If Banner type does not exist if banner_type not in config_data['other_config']: modified = False else: # Delete Banner config_data['other_config'].pop(banner_type) # UPDATE Banner uri = "{base_url}{class_uri}".format( base_url=self.session.base_url, class_uri=Device.base_uri ) put_data = json.dumps(config_data, sort_keys=True, indent=4) try: response = self.session.s.put( uri, verify=False, data=put_data, proxies=self.session.proxy) except Exception as e: raise ResponseError('PUT', e) if not utils._response_ok(response, "PUT"): raise GenericOperationError( response.text, response.status_code, "DELETE Banner") # Object was modified, returns True modified = True return modified def boot_firmware(self, partition_name='primary'): ''' Perform a POST request to Boot the AOS-CX switch with image present to the specified partition :param partition_name: String name of the partition for device to boot to. :return bool: True if success ''' # Lower case for partition name partition_name = partition_name.lower() if partition_name not in ['primary', 'secondary']: raise VerificationError('Boot Firmware', 'Bad partition name') success = False uri = '{base_url}boot?image={part}'.format( base_url=self.session.base_url, part=partition_name) try: self.session.s.post( uri, verify=False, proxies=self.session.proxy) except Exception as e: raise ResponseError('POST', e) success = True # Return result return success def upload_firmware_http(self, remote_firmware_file_path, vrf, partition_name='primary'): ''' Perform a PUT request to upload a firmware image given a http_request :param remote_firmware_file_path: "HTTP server address and path for uploading firmware image, must be reachable through provided vrf ex: http://192.168.1.2:8000/TL_10_04_0030A.swi" :param vrf: VRF to be used to contact HTTP server, required if remote_firmware_file_path is provided :param partition_name: Name of the partition for the image to be uploaded to. :return bool: True if success ''' http_path = remote_firmware_file_path unsupported_versions = [ "10.00", "10.01", "10.02", "10.03", ] # Verify Version for version in unsupported_versions: if version in self.firmware_version: raise VerificationError( 'Upload Firmware through HTTPs', "Minimum supported firmware version is 10.04 for" + " remote firmware upload, your version is {firmware}" .format(firmware=self.firmware_version)) # Verify VRF if vrf is None: raise VerificationError( 'VRF', "VRF needs to be provided in order" + " to upload firmware from HTTP server") http_path_encoded = quote_plus(http_path) # Build URI uri = '{base_url}firmware?image={part}&from={path}&vrf={vrf}'\ .format( base_url=self.session.base_url, part=partition_name, path=http_path_encoded, vrf=vrf) # PUT for a HTTP Request try: response = self.session.s.put( uri, verify=False, proxies=self.session.proxy) except Exception as e: raise ResponseError('PUT', e) if not utils._response_ok(response, "PUT"): raise GenericOperationError( response.text, response.status_code) # True if successful return True def upload_firmware_local(self, partition_name='primary', firmware_file_path=None): ''' Perform a POST request to upload a firmware image from a local file :param partition_name: Name of the partition for the image to be uploaded to. :param firmware_file_path: File name and path for local file uploading firmware image :return success: True if success ''' uri = '{base_url}firmware?image={part}'.format( base_url=self.session.base_url, part=partition_name) # Upload file success = utils.file_upload(self.session, firmware_file_path, uri) # If no errors detected return success def upload_firmware(self, partition_name=None, firmware_file_path=None, remote_firmware_file_path=None, vrf=None): ''' Upload a firmware image from a local file OR from a remote location :param partition_name: Name of the partition for the image to be uploaded to. :param firmware_file_path: File name and path for local file uploading firmware image. IMPORTANT: For this to be used, the remote_firmware_file_path parameter must be left as NONE :param remote_firmware_file_path: HTTP server address and path for uploading firmware image, must be reachable through provided vrf ex: http://192.168.1.2:8000/TL_10_04_0030A.swi :param vrf: VRF to be used to contact HTTP server, required if remote_firmware_file_path is provided :return bool: True if success ''' result = None if partition_name is None: partition_name = 'primary' # Use HTTP Server if remote_firmware_file_path is not None: result = self.upload_firmware_http( remote_firmware_file_path, vrf, partition_name) # Locally else: result = self.upload_firmware_local( partition_name, firmware_file_path) # If no errors detected return result def vsx_capable(self): """ Return whether this device supports the VSX functionality :return: True if device supports VSX """ return hasattr(self, "capabilities") and "vsx" in self.capabilities def is_capable(self, capability): """ Check if the current Device has the given capability. :param capability: String name of a Device capability. :return: True if Device is capable; False otherwise. """ if not self.materialized: self.get() return capability in self.capabilities
32.707495
98
0.587782
daa201f17ec57967905e3dbd0ab337507d23ba09
17,012
py
Python
calliope/backend/pyomo/constraints/capacity.py
Dustin231/calliope
31e489a573fffc077d1124444bd2116b95ca13ae
[ "Apache-2.0" ]
1
2021-09-06T18:42:08.000Z
2021-09-06T18:42:08.000Z
calliope/backend/pyomo/constraints/capacity.py
ahilbers/calliope
72bfa063303f9c03fb234d95889a0742fcd2fd69
[ "Apache-2.0" ]
null
null
null
calliope/backend/pyomo/constraints/capacity.py
ahilbers/calliope
72bfa063303f9c03fb234d95889a0742fcd2fd69
[ "Apache-2.0" ]
null
null
null
""" Copyright (C) since 2013 Calliope contributors listed in AUTHORS. Licensed under the Apache 2.0 License (see LICENSE file). capacity.py ~~~~~~~~~~~~~~~~~ Capacity constraints for technologies (output, resource, area, and storage). """ import pyomo.core as po # pylint: disable=import-error import numpy as np from calliope.backend.pyomo.util import get_param, split_comma_list from calliope import exceptions ORDER = 10 # order in which to invoke constraints relative to other constraint files def load_constraints(backend_model): sets = backend_model.__calliope_model_data["sets"] if backend_model.__calliope_run_config["mode"] == "operate": return None else: if "loc_techs_storage_capacity_constraint" in sets: backend_model.storage_capacity_constraint = po.Constraint( backend_model.loc_techs_storage_capacity_constraint, rule=storage_capacity_constraint_rule, ) if "loc_techs_energy_capacity_storage_min_constraint" in sets: backend_model.energy_capacity_storage_min_constraint = po.Constraint( backend_model.loc_techs_energy_capacity_storage_min_constraint, rule=energy_capacity_storage_min_constraint_rule, ) if "loc_techs_energy_capacity_storage_max_constraint" in sets: backend_model.energy_capacity_storage_max_constraint = po.Constraint( backend_model.loc_techs_energy_capacity_storage_max_constraint, rule=energy_capacity_storage_max_constraint_rule, ) if "loc_techs_energy_capacity_storage_equals_constraint" in sets: backend_model.energy_capacity_storage_equals_constraint = po.Constraint( backend_model.loc_techs_energy_capacity_storage_equals_constraint, rule=energy_capacity_storage_equals_constraint_rule, ) if "loc_techs_energy_capacity_storage_constraint_old" in sets: backend_model.energy_capacity_storage_constraint_old = po.Constraint( backend_model.loc_techs_energy_capacity_storage_constraint_old, rule=energy_capacity_storage_constraint_rule_old, ) if "loc_techs_resource_capacity_constraint" in sets: backend_model.resource_capacity_constraint = po.Constraint( backend_model.loc_techs_resource_capacity_constraint, rule=resource_capacity_constraint_rule, ) if "loc_techs_resource_capacity_equals_energy_capacity_constraint" in sets: backend_model.resource_capacity_equals_energy_capacity_constraint = po.Constraint( backend_model.loc_techs_resource_capacity_equals_energy_capacity_constraint, rule=resource_capacity_equals_energy_capacity_constraint_rule, ) if "loc_techs_resource_area_constraint" in sets: backend_model.resource_area_constraint = po.Constraint( backend_model.loc_techs_resource_area_constraint, rule=resource_area_constraint_rule, ) if "loc_techs_resource_area_per_energy_capacity_constraint" in sets: backend_model.resource_area_per_energy_capacity_constraint = po.Constraint( backend_model.loc_techs_resource_area_per_energy_capacity_constraint, rule=resource_area_per_energy_capacity_constraint_rule, ) if "locs_resource_area_capacity_per_loc_constraint" in sets: backend_model.resource_area_capacity_per_loc_constraint = po.Constraint( backend_model.locs_resource_area_capacity_per_loc_constraint, rule=resource_area_capacity_per_loc_constraint_rule, ) if "loc_techs_energy_capacity_constraint" in sets: backend_model.energy_capacity_constraint = po.Constraint( backend_model.loc_techs_energy_capacity_constraint, rule=energy_capacity_constraint_rule, ) if "techs_energy_capacity_systemwide_constraint" in sets: backend_model.energy_capacity_systemwide_constraint = po.Constraint( backend_model.techs_energy_capacity_systemwide_constraint, rule=energy_capacity_systemwide_constraint_rule, ) def get_capacity_constraint( backend_model, parameter, loc_tech, _equals=None, _max=None, _min=None, scale=None ): decision_variable = getattr(backend_model, parameter) if not _equals: _equals = get_param(backend_model, parameter + "_equals", loc_tech) if not _max: _max = get_param(backend_model, parameter + "_max", loc_tech) if not _min: _min = get_param(backend_model, parameter + "_min", loc_tech) if po.value(_equals) is not False and po.value(_equals) is not None: if np.isinf(po.value(_equals)): e = exceptions.ModelError raise e( "Cannot use inf for {}_equals for loc:tech `{}`".format( parameter, loc_tech ) ) if scale: _equals *= scale return decision_variable[loc_tech] == _equals else: if po.value(_min) == 0 and np.isinf(po.value(_max)): return po.Constraint.NoConstraint else: if scale: _max *= scale _min *= scale return (_min, decision_variable[loc_tech], _max) def storage_capacity_constraint_rule(backend_model, loc_tech): """ Set maximum storage capacity. Supply_plus & storage techs only The first valid case is applied: .. container:: scrolling-wrapper .. math:: \\boldsymbol{storage_{cap}}(loc::tech) \\begin{cases} = storage_{cap, equals}(loc::tech),& \\text{if } storage_{cap, equals}(loc::tech)\\\\ \\leq storage_{cap, max}(loc::tech),& \\text{if } storage_{cap, max}(loc::tech)\\\\ \\text{unconstrained},& \\text{otherwise} \\end{cases} \\forall loc::tech \\in loc::techs_{store} and (if ``equals`` not enforced): .. container:: scrolling-wrapper .. math:: \\boldsymbol{storage_{cap}}(loc::tech) \\geq storage_{cap, min}(loc::tech) \\quad \\forall loc::tech \\in loc::techs_{store} """ return get_capacity_constraint(backend_model, "storage_cap", loc_tech) def energy_capacity_storage_constraint_rule_old(backend_model, loc_tech): """ Set an additional energy capacity constraint on storage technologies, based on their use of `charge_rate`. This is deprecated and will be removed in Calliope 0.7.0. Instead of `charge_rate`, please use `energy_cap_per_storage_cap_max`. .. container:: scrolling-wrapper .. math:: \\boldsymbol{energy_{cap}}(loc::tech) \\leq \\boldsymbol{storage_{cap}}(loc::tech) \\times charge\\_rate(loc::tech) \\quad \\forall loc::tech \\in loc::techs_{store} """ charge_rate = get_param(backend_model, "charge_rate", loc_tech) return backend_model.energy_cap[loc_tech] <= ( backend_model.storage_cap[loc_tech] * charge_rate ) def energy_capacity_storage_min_constraint_rule(backend_model, loc_tech): """ Limit energy capacities of storage technologies based on their storage capacities. .. container:: scrolling-wrapper .. math:: \\boldsymbol{energy_{cap}}(loc::tech) \\geq \\boldsymbol{storage_{cap}}(loc::tech) \\times energy\\_cap\\_per\\_storage\\_cap\\_min(loc::tech)\\\\ \\forall loc::tech \\in loc::techs_{store} """ return backend_model.energy_cap[loc_tech] >= ( backend_model.storage_cap[loc_tech] * get_param(backend_model, "energy_cap_per_storage_cap_min", loc_tech) ) def energy_capacity_storage_max_constraint_rule(backend_model, loc_tech): """ Limit energy capacities of storage technologies based on their storage capacities. .. container:: scrolling-wrapper .. math:: \\boldsymbol{energy_{cap}}(loc::tech) \\leq \\boldsymbol{storage_{cap}}(loc::tech) \\times energy\\_cap\\_per\\_storage\\_cap\\_max(loc::tech)\\\\ \\forall loc::tech \\in loc::techs_{store} """ return backend_model.energy_cap[loc_tech] <= ( backend_model.storage_cap[loc_tech] * get_param(backend_model, "energy_cap_per_storage_cap_max", loc_tech) ) def energy_capacity_storage_equals_constraint_rule(backend_model, loc_tech): """ Limit energy capacities of storage technologies based on their storage capacities. .. container:: scrolling-wrapper .. math:: \\boldsymbol{energy_{cap}}(loc::tech) = \\boldsymbol{storage_{cap}}(loc::tech) \\times energy\\_cap\\_per\\_storage\\_cap\\_equals(loc::tech) \\forall loc::tech \\in loc::techs_{store} """ return backend_model.energy_cap[loc_tech] == ( backend_model.storage_cap[loc_tech] * get_param(backend_model, "energy_cap_per_storage_cap_equals", loc_tech) ) def resource_capacity_constraint_rule(backend_model, loc_tech): """ Add upper and lower bounds for resource_cap. The first valid case is applied: .. container:: scrolling-wrapper .. math:: \\boldsymbol{resource_{cap}}(loc::tech) \\begin{cases} = resource_{cap, equals}(loc::tech),& \\text{if } resource_{cap, equals}(loc::tech)\\\\ \\leq resource_{cap, max}(loc::tech),& \\text{if } resource_{cap, max}(loc::tech)\\\\ \\text{unconstrained},& \\text{otherwise} \\end{cases} \\forall loc::tech \\in loc::techs_{finite\\_resource\\_supply\\_plus} and (if ``equals`` not enforced): .. container:: scrolling-wrapper .. math:: \\boldsymbol{resource_{cap}}(loc::tech) \\geq resource_{cap, min}(loc::tech) \\quad \\forall loc::tech \\in loc::techs_{finite\\_resource\\_supply\\_plus} """ return get_capacity_constraint(backend_model, "resource_cap", loc_tech) def resource_capacity_equals_energy_capacity_constraint_rule(backend_model, loc_tech): """ Add equality constraint for resource_cap to equal energy_cap, for any technologies which have defined resource_cap_equals_energy_cap. .. container:: scrolling-wrapper .. math:: \\boldsymbol{resource_{cap}}(loc::tech) = \\boldsymbol{energy_{cap}}(loc::tech) \\quad \\forall loc::tech \\in loc::techs_{finite\\_resource\\_supply\\_plus} \\text{ if } resource\\_cap\\_equals\\_energy\\_cap = \\text{True} """ return backend_model.resource_cap[loc_tech] == backend_model.energy_cap[loc_tech] def resource_area_constraint_rule(backend_model, loc_tech): """ Set upper and lower bounds for resource_area. The first valid case is applied: .. container:: scrolling-wrapper .. math:: \\boldsymbol{resource_{area}}(loc::tech) \\begin{cases} = resource_{area, equals}(loc::tech),& \\text{if } resource_{area, equals}(loc::tech)\\\\ \\leq resource_{area, max}(loc::tech),& \\text{if } resource_{area, max}(loc::tech)\\\\ \\text{unconstrained},& \\text{otherwise} \\end{cases} \\forall loc::tech \\in loc::techs_{area} and (if ``equals`` not enforced): .. container:: scrolling-wrapper .. math:: \\boldsymbol{resource_{area}}(loc::tech) \\geq resource_{area, min}(loc::tech) \\quad \\forall loc::tech \\in loc::techs_{area} """ energy_cap_max = get_param(backend_model, "energy_cap_max", loc_tech) area_per_energy_cap = get_param( backend_model, "resource_area_per_energy_cap", loc_tech ) if po.value(energy_cap_max) == 0 and not po.value(area_per_energy_cap): # If a technology has no energy_cap here, we force resource_area to zero, # so as not to accrue spurious costs return backend_model.resource_area[loc_tech] == 0 else: return get_capacity_constraint(backend_model, "resource_area", loc_tech) def resource_area_per_energy_capacity_constraint_rule(backend_model, loc_tech): """ Add equality constraint for resource_area to equal a percentage of energy_cap, for any technologies which have defined resource_area_per_energy_cap .. container:: scrolling-wrapper .. math:: \\boldsymbol{resource_{area}}(loc::tech) = \\boldsymbol{energy_{cap}}(loc::tech) \\times area\\_per\\_energy\\_cap(loc::tech) \\quad \\forall loc::tech \\in locs::techs_{area} \\text{ if } area\\_per\\_energy\\_cap(loc::tech) """ area_per_energy_cap = get_param( backend_model, "resource_area_per_energy_cap", loc_tech ) return ( backend_model.resource_area[loc_tech] == backend_model.energy_cap[loc_tech] * area_per_energy_cap ) def resource_area_capacity_per_loc_constraint_rule(backend_model, loc): """ Set upper bound on use of area for all locations which have `available_area` constraint set. Does not consider resource_area applied to demand technologies .. container:: scrolling-wrapper .. math:: \\sum_{tech} \\boldsymbol{resource_{area}}(loc::tech) \\leq available\\_area \\quad \\forall loc \\in locs \\text{ if } available\\_area(loc) """ model_data_dict = backend_model.__calliope_model_data["data"] available_area = model_data_dict["available_area"][loc] loc_techs = split_comma_list(model_data_dict["lookup_loc_techs_area"][loc]) return ( sum(backend_model.resource_area[loc_tech] for loc_tech in loc_techs) <= available_area ) def energy_capacity_constraint_rule(backend_model, loc_tech): """ Set upper and lower bounds for energy_cap. The first valid case is applied: .. container:: scrolling-wrapper .. math:: \\frac{\\boldsymbol{energy_{cap}}(loc::tech)}{energy_{cap, scale}(loc::tech)} \\begin{cases} = energy_{cap, equals}(loc::tech),& \\text{if } energy_{cap, equals}(loc::tech)\\\\ \\leq energy_{cap, max}(loc::tech),& \\text{if } energy_{cap, max}(loc::tech)\\\\ \\text{unconstrained},& \\text{otherwise} \\end{cases} \\forall loc::tech \\in loc::techs and (if ``equals`` not enforced): .. container:: scrolling-wrapper .. math:: \\frac{\\boldsymbol{energy_{cap}}(loc::tech)}{energy_{cap, scale}(loc::tech)} \\geq energy_{cap, min}(loc::tech) \\quad \\forall loc::tech \\in loc::techs """ scale = get_param(backend_model, "energy_cap_scale", loc_tech) return get_capacity_constraint(backend_model, "energy_cap", loc_tech, scale=scale) def energy_capacity_systemwide_constraint_rule(backend_model, tech): """ Set constraints to limit the capacity of a single technology type across all locations in the model. The first valid case is applied: .. container:: scrolling-wrapper .. math:: \\sum_{loc}\\boldsymbol{energy_{cap}}(loc::tech) \\begin{cases} = energy_{cap, equals, systemwide}(loc::tech),& \\text{if } energy_{cap, equals, systemwide}(loc::tech)\\\\ \\leq energy_{cap, max, systemwide}(loc::tech),& \\text{if } energy_{cap, max, systemwide}(loc::tech)\\\\ \\text{unconstrained},& \\text{otherwise} \\end{cases} \\forall tech \\in techs """ if tech in getattr(backend_model, "techs_transmission_names", []): all_loc_techs = [ i for i in backend_model.loc_techs_transmission if i.split("::")[1].split(":")[0] == tech ] multiplier = 2 # there are always two technologies associated with one link else: all_loc_techs = [i for i in backend_model.loc_techs if i.split("::")[1] == tech] multiplier = 1 max_systemwide = get_param(backend_model, "energy_cap_max_systemwide", tech) equals_systemwide = get_param(backend_model, "energy_cap_equals_systemwide", tech) if np.isinf(po.value(max_systemwide)) and not equals_systemwide: return po.Constraint.NoConstraint elif equals_systemwide and np.isinf(po.value(equals_systemwide)): raise exceptions.ModelError( "Cannot use inf for energy_cap_equals_systemwide for tech `{}`".format(tech) ) sum_expr = sum(backend_model.energy_cap[loc_tech] for loc_tech in all_loc_techs) if equals_systemwide: return sum_expr == equals_systemwide * multiplier else: return sum_expr <= max_systemwide * multiplier
37.063181
124
0.65348
51c893bfc3cc0f79d482c3495614509c9cd5321c
32,004
py
Python
sudoku/labeled_printer.py
dinkumsoftware/dinkum
57fd217b81a5c95b08653977c8df17f7783ae3f6
[ "Apache-2.0" ]
null
null
null
sudoku/labeled_printer.py
dinkumsoftware/dinkum
57fd217b81a5c95b08653977c8df17f7783ae3f6
[ "Apache-2.0" ]
null
null
null
sudoku/labeled_printer.py
dinkumsoftware/dinkum
57fd217b81a5c95b08653977c8df17f7783ae3f6
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python3 # dinkum/sudoku/labeled_printer.py ''' Has a function, print_labeled_board, which prints a human-readable board with all the cell numbers, row numbers, column numbers, and block numbers labeled. Cell values are shown in middle of cell and number of possible_values for unsolved cells are shown in lower left of the cell. It's a rather busy printout, probably only of interest to developers. Example empty board: (with want_cell_nums==True and want_num_possibles==True) 0 1 2 3 4 5 6 7 8 /---------------------------------------------------------\ |0------------------1------------------2------------------| |0 1 2 |3 4 5 |6 7 8 || 0|| | | || | | || | | ||0 ||9 |9 |9 ||9 |9 |9 ||9 |9 |9 || |---------------------------------------------------------| |9 10 11 |12 13 14 |15 16 17 || 1|| | | || | | || | | ||1 ||9 |9 |9 ||9 |9 |9 ||9 |9 |9 || |---------------------------------------------------------| |18 19 20 |21 22 23 |24 25 26 || 2|| | | || | | || | | ||2 ||9 |9 |9 ||9 |9 |9 ||9 |9 |9 || |---------------------------------------------------------| |3------------------4------------------5------------------| |27 28 29 |30 31 32 |33 34 35 || 3|| | | || | | || | | ||3 ||9 |9 |9 ||9 |9 |9 ||9 |9 |9 || |---------------------------------------------------------| |36 37 38 |39 40 41 |42 43 44 || 4|| | | || | | || | | ||4 ||9 |9 |9 ||9 |9 |9 ||9 |9 |9 || |---------------------------------------------------------| |45 46 47 |48 49 50 |51 52 53 || 5|| | | || | | || | | ||5 ||9 |9 |9 ||9 |9 |9 ||9 |9 |9 || |---------------------------------------------------------| |6------------------7------------------8------------------| |54 55 56 |57 58 59 |60 61 62 || 6|| | | || | | || | | ||6 ||9 |9 |9 ||9 |9 |9 ||9 |9 |9 || |---------------------------------------------------------| |63 64 65 |66 67 68 |69 70 71 || 7|| | | || | | || | | ||7 ||9 |9 |9 ||9 |9 |9 ||9 |9 |9 || |---------------------------------------------------------| |72 73 74 |75 76 77 |78 79 80 || 8|| | | || | | || | | ||8 ||9 |9 |9 ||9 |9 |9 ||9 |9 |9 || \---------------------------------------------------------/ 0 1 2 3 4 5 6 7 8 ''' # 2019-11-23 tc Refactored from dinkum_print_sukoku_worksheet.py # worksheet() ==> print_labeled_board() # added cell values # 2019-11-25 tc print_labeled_board() ==> labeled_board_lines() # Made print_labeled_board() actually print the lines # Added cell values # Moved block label location # 2019-11-26 tc Fixed import problem # 2019-12-01 tc minor todo knockoff. get row# from rgb rather than cell # 2019-12-03 tc Made cell# and num_possible printouts optional #-------------------------------------------------------------- from dinkum.sudoku.board import * from dinkum.utils.str_utils import * # What we make lines with horz_line_char = '-' vert_line_char = '|' # size of printed cell # includes rightmost | and topmost - # does NOT include leftmost | and bottom - # does NOT include any block separators cell_width = 6 cell_height = 4 # Width of whole printed board left_offset_to_first_cell = 2 # Accounts for row label and one | right_pad_after_last_cell = 3 # || + row_label width_of_internal_block_separators = 2 # Two internal |'s output_width = left_offset_to_first_cell + cell_width * RCB_SIZE + \ width_of_internal_block_separators + right_pad_after_last_cell # Height of whole printed board top_offset_to_first_cell = 2 # column label + '-' bot_pad_after_last_cell = 2 # bottom cell '-' + '-' + column_label def print_labeled_board(board=None, want_cell_nums=True, want_num_possibles=False) : ''' prints the output of labeled_board() resulting in a human-readable board showing cell values with everything (cell#,row#, col#,blk#) labeled. If board isn't supplied, produces output for an empty board. want_cell_nums controls whether cell number labels are output want_num_possibles controls whether num_possibles for each cell are output. ''' for l in labeled_board(board, want_cell_nums, want_num_possibles) : print (l) def labeled_board(board=None, want_cell_nums=True, want_num_possibles=False) : ''' outputs board with all column, row, block, and cell's labeled along with the cell values in human readable format. Returns a [] of lines (NOT terminated by new line) that make up the board If board is not supplied, produces output for an empty board ''' if not board : board = Board(None, None, "created by labeled_board()") ws = [] # What we return # 0 1 2 ... # /--------------------------------\ # ws += top_or_bottom_lines(is_top=True) # Stuff in the middle, e.g. # 1| 9 10 11 | 12 13 14 | 15 16 17 |1 for row in board.rows : ws += row_line(row, want_cell_nums, want_num_possibles) # \ --------------------------------/ # # 0 1 2 ... ws += top_or_bottom_lines(is_top=False) return ws def top_or_bottom_lines(is_top) : ''' returns [] of [column label line, horz separator line. e.g. is_top controls whether top or bottom lines. Example of a top line 0 1 2 3 4 5 6 7 8 /---------------------------------------------------------\ ''' if is_top : # column label and separator line ret_list = col_label_lines() # 0 1 2 ... ret_list += horz_separator_lines('/', '\\') # /----------\ assert len(ret_list) == top_offset_to_first_cell return ret_list else : # bottom ret_list = horz_separator_lines('\\', '/') # \---------------/ ret_list += col_label_lines() # 0 1 2 ... assert len(ret_list) == bot_pad_after_last_cell return ret_list assert False, "Impossible Place" def row_line(row, want_cell_nums, want_num_possibles) : ''' returns [] of lines that make up a row of cells lines are NOT \n terminated. want_cell_nums controls whether the cell number is labeled. want_num_possibles controls whether num_possibles is output The top line, left, and right cell outlines are include in returned lines. A horizontal block separator may be included in the output. The bottom cell lines are NOT in the returned lines. The cell number is written in the upper left corner of the cell area Example return: |---------------------------------------------------------| |9 10 11 |12 13 14 |15 16 17 || 1|| | | || | | || | | ||1 || | | || | | || | | || ''' # Which row we are working on row_num = row.rcb_num # What we return. Gets filled in below ret_lines= [None] * cell_height # A cell consists of the left and top border, spaces inside, # but NOT the bottom and right border # Start with a separator line. This is top line of all cells in # the row. block number labels will be inserted into this line # above and below the middle cell in the block. Example: # |---------------------------------------------------------| ret_lines = horz_separator_lines() # Each individual row is made of multiple output lines. # Iterate over them first_line_of_cell_content = 1 # skips horz_separator_lines for line_num_in_row in range(first_line_of_cell_content, cell_height) : # example: # 1|| | | || | | || | | ||1 line = '' # start with an empty line and append to it # moving left to right # Time to place row label on outside ? line += str(row_num) if line_num_in_row == cell_height//2 else ' ' line += vert_line_char # We iterate over a row of Cells in a Board so # we don't have to do the arithmetic for cell#, block#, etc # Output the left edge and appropriate number of spaces for cell in row : # Need to label the block in prior line? # example: # |3------------------4------------------5------------------| # |27 28 29 |30 31 32 |33 34 35 || if line_num_in_row == first_line_of_cell_content and cell.blk_idx == 0 : # yes, it's first cell in block ret_lines[0] = replace_substr_at(ret_lines[0], str(cell.blk_num), block_label_offset_in_line(cell)) # cell's left edge line += vert_line_char # spaces of the cell cell_content = ' ' * (cell_width-1) # The -1 is for vert_line_char we just printed # Time to write the cell's value (if there is one)? # example: # |72 73 74 |75 76 77 |78 79 80 || # 8|| 1 | | || | | 2 || 5 | 3 | 4 ||8 # || |6 |3 ||2 |4 | || | | || # \---------------------------------------------------------/ # number in middle is cell's value # number in lower left is num_possibles # Note: This is so complicated because I originally indended # to write the value multiple times in a square. I thought # this looked better, but I left the more general code in. value_label_vert_offset_in_cell = 2 value_label_vert_num = 1 value_label_horz_offset_in_cell = 2 value_label_horz_num = 1 if cell.value != Cell.unsolved_cell_value : # There is value to print, on the right line? if (value_label_vert_offset_in_cell <= line_num_in_row < (value_label_vert_offset_in_cell + value_label_vert_num)) : # Yes, replace the chars cell_content = replace_substr_at(cell_content, str(cell.value) * value_label_horz_num, value_label_horz_offset_in_cell) else : # cell is unsolved, maybe a number of possible values # in lower left corner on last line num_possibles_label_horz_offset_in_cell = 0 if want_num_possibles : if line_num_in_row == (cell_height-1) : cell_content=replace_substr_at(cell_content, str(len(cell.possible_values)), num_possibles_label_horz_offset_in_cell) line += cell_content # Tack it on # We have entirely written the output associated with this cell # on top line only, maybe label the cell number # We overwrite the left vertical separater and the # first char in cell_content if want_cell_nums and line_num_in_row == first_line_of_cell_content: cell_label = "%d" % cell.cell_num line = replace_substr_at(line, cell_label, -cell_width) # Time to place an internal (not on edges) vertical block separator ? if is_cell_rightmost_in_block_and_internal(cell.col_num) : line += vert_line_char # right border of last cell in the row (the one we just output) line += vert_line_char # Outside right line line += vert_line_char # Time to place row label on outside ? line += str(row_num) if line_num_in_row == cell_height//2 else ' ' # All done composing line assert len(line) == output_width, "is: %d, should be:%d" %(len(line), output_width) # Set our result in the [] we return ret_lines.append(line) assert len(ret_lines) == cell_height # If this is the bottom row of an internal block, we need # to separate it by adding another line of ----------'s if is_cell_bottom_most_in_block_and_internal(row_num) : ret_lines += horz_separator_lines() return ret_lines def horz_separator_lines(first_char=vert_line_char, last_char=vert_line_char) : ''' Returns [] of lines making up top or bottom lines, e.g. 0 1 2 3 4 5 6 7 8 /---------------------------------------------------------\ The first and last chars of each line are set to first_char and last_char lines are NOT new line terminated. ''' # ----------- # Start with full line of lines # and overwrite what we need to sep_line = horz_line_char * output_width # Overwrite first and last chars with spaces # to account for row label's sep_line = replace_substr_at(sep_line, ' ', 0) sep_line = replace_substr_at(sep_line, ' ' , -1) # overwrite first and last chars that were passed in sep_line = replace_substr_at(sep_line, first_char, 1) sep_line = replace_substr_at(sep_line, last_char , -2) # All done return [sep_line] def col_label_lines() : ''' returns [] of lines that label the columns. Each line is NOT \n terminated. ''' # Start with stuff on left before first Cell # " " col_label_line = left_pad() # Do the stuff above a row of cells # We don't care which row row = Board().rows[0] for cell in row : # A cell_width blank string cell_line = ' ' * cell_width # Write column label in the middle cell_line = replace_substr_at(cell_line, str(cell.col_num), len(cell_line)//2 ) # We have to account for vertical block separators # to keep the center alignment of column numbers if is_cell_rightmost_in_block_and_internal(cell.col_num) : cell_line += ' ' # Tack it on col_label_line += cell_line # Fill out the rest of the line # " " col_label_line += right_pad() # Give them back list of our one generated line return [col_label_line] def is_cell_rightmost_in_block_and_internal(col_num) : ''' Returns true if cell in col_num needs a block separator to it's right AND it isn't the last cell on the line. Hence the internal word ''' return col_num==2 or col_num==5 def is_cell_bottom_most_in_block_and_internal(row_num) : ''' Returns True if the row at row_num is the bottommost row of the block AND and not on the bottom row of the board, hence the use of internal. ''' return row_num==2 or row_num==5 def is_cell_above_in_middle_of_block(cell) : ''' returns TRUE if cell is the center cell of it's block ''' return cell.row_num in [1,4,7] and cell.col_num in [1,4,7] def is_cell_in_middle_of_block(cell) : ''' returns TRUE if cell is the center cell in the bottom row of it's block. ''' return cell.row_num in [2,5,8] and cell.col_num in [1,4,7] def block_label_offset_in_line(cell) : ''' Returns the offset in a full output line where the block label of cell should be placed. :example |0------------------1------------------2------------------| ''' # The label is in the upper right corner of the first # cell (upper left) in the block block_label_offset = top_offset_to_first_cell # offset for cell 0 # Move it over as required blk_in_line = cell.blk_num % BLK_SIZE # 0,1,or 2 num_vert_separator_lines = blk_in_line # How many internal |s there are block_label_offset += blk_in_line * BLK_SIZE * cell_width + num_vert_separator_lines return block_label_offset def left_pad() : ''' Returns a string that makes up the left edge of the output board. ''' ret_str = ' ' assert len(ret_str) == left_offset_to_first_cell return ret_str def right_pad() : ''' Returns a string that makes up the right edge of the output board. It's all spaces. ''' ret_str = ' ' assert len(ret_str) == right_pad_after_last_cell return ret_str # Test code import unittest class Test_labeled_printer(unittest.TestCase): # How an empty board is printed with various combinations # of Used in multiple tests expected_empty_output_cell_and_num_possible =\ [\ " 0 1 2 3 4 5 6 7 8 ", " /---------------------------------------------------------\ ", " |0------------------1------------------2------------------| ", " |0 1 2 |3 4 5 |6 7 8 || ", "0|| | | || | | || | | ||0", " ||9 |9 |9 ||9 |9 |9 ||9 |9 |9 || ", " |---------------------------------------------------------| ", " |9 10 11 |12 13 14 |15 16 17 || ", "1|| | | || | | || | | ||1", " ||9 |9 |9 ||9 |9 |9 ||9 |9 |9 || ", " |---------------------------------------------------------| ", " |18 19 20 |21 22 23 |24 25 26 || ", "2|| | | || | | || | | ||2", " ||9 |9 |9 ||9 |9 |9 ||9 |9 |9 || ", " |---------------------------------------------------------| ", " |3------------------4------------------5------------------| ", " |27 28 29 |30 31 32 |33 34 35 || ", "3|| | | || | | || | | ||3", " ||9 |9 |9 ||9 |9 |9 ||9 |9 |9 || ", " |---------------------------------------------------------| ", " |36 37 38 |39 40 41 |42 43 44 || ", "4|| | | || | | || | | ||4", " ||9 |9 |9 ||9 |9 |9 ||9 |9 |9 || ", " |---------------------------------------------------------| ", " |45 46 47 |48 49 50 |51 52 53 || ", "5|| | | || | | || | | ||5", " ||9 |9 |9 ||9 |9 |9 ||9 |9 |9 || ", " |---------------------------------------------------------| ", " |6------------------7------------------8------------------| ", " |54 55 56 |57 58 59 |60 61 62 || ", "6|| | | || | | || | | ||6", " ||9 |9 |9 ||9 |9 |9 ||9 |9 |9 || ", " |---------------------------------------------------------| ", " |63 64 65 |66 67 68 |69 70 71 || ", "7|| | | || | | || | | ||7", " ||9 |9 |9 ||9 |9 |9 ||9 |9 |9 || ", " |---------------------------------------------------------| ", " |72 73 74 |75 76 77 |78 79 80 || ", "8|| | | || | | || | | ||8", " ||9 |9 |9 ||9 |9 |9 ||9 |9 |9 || ", " \---------------------------------------------------------/ ", " 0 1 2 3 4 5 6 7 8 ", ] expected_empty_output =\ [\ " 0 1 2 3 4 5 6 7 8 ", " /---------------------------------------------------------\ ", " |0------------------1------------------2------------------| ", " || | | || | | || | | || ", "0|| | | || | | || | | ||0", " || | | || | | || | | || ", " |---------------------------------------------------------| ", " || | | || | | || | | || ", "1|| | | || | | || | | ||1", " || | | || | | || | | || ", " |---------------------------------------------------------| ", " || | | || | | || | | || ", "2|| | | || | | || | | ||2", " || | | || | | || | | || ", " |---------------------------------------------------------| ", " |3------------------4------------------5------------------| ", " || | | || | | || | | || ", "3|| | | || | | || | | ||3", " || | | || | | || | | || ", " |---------------------------------------------------------| ", " || | | || | | || | | || ", "4|| | | || | | || | | ||4", " || | | || | | || | | || ", " |---------------------------------------------------------| ", " || | | || | | || | | || ", "5|| | | || | | || | | ||5", " || | | || | | || | | || ", " |---------------------------------------------------------| ", " |6------------------7------------------8------------------| ", " || | | || | | || | | || ", "6|| | | || | | || | | ||6", " || | | || | | || | | || ", " |---------------------------------------------------------| ", " || | | || | | || | | || ", "7|| | | || | | || | | ||7", " || | | || | | || | | || ", " |---------------------------------------------------------| ", " || | | || | | || | | || ", "8|| | | || | | || | | ||8", " || | | || | | || | | || ", " \---------------------------------------------------------/ ", " 0 1 2 3 4 5 6 7 8 ", ] expected_empty_output_cell_nums=\ [\ " 0 1 2 3 4 5 6 7 8 ", " /---------------------------------------------------------\ ", " |0------------------1------------------2------------------| ", " |0 1 2 |3 4 5 |6 7 8 || ", "0|| | | || | | || | | ||0", " || | | || | | || | | || ", " |---------------------------------------------------------| ", " |9 10 11 |12 13 14 |15 16 17 || ", "1|| | | || | | || | | ||1", " || | | || | | || | | || ", " |---------------------------------------------------------| ", " |18 19 20 |21 22 23 |24 25 26 || ", "2|| | | || | | || | | ||2", " || | | || | | || | | || ", " |---------------------------------------------------------| ", " |3------------------4------------------5------------------| ", " |27 28 29 |30 31 32 |33 34 35 || ", "3|| | | || | | || | | ||3", " || | | || | | || | | || ", " |---------------------------------------------------------| ", " |36 37 38 |39 40 41 |42 43 44 || ", "4|| | | || | | || | | ||4", " || | | || | | || | | || ", " |---------------------------------------------------------| ", " |45 46 47 |48 49 50 |51 52 53 || ", "5|| | | || | | || | | ||5", " || | | || | | || | | || ", " |---------------------------------------------------------| ", " |6------------------7------------------8------------------| ", " |54 55 56 |57 58 59 |60 61 62 || ", "6|| | | || | | || | | ||6", " || | | || | | || | | || ", " |---------------------------------------------------------| ", " |63 64 65 |66 67 68 |69 70 71 || ", "7|| | | || | | || | | ||7", " || | | || | | || | | || ", " |---------------------------------------------------------| ", " |72 73 74 |75 76 77 |78 79 80 || ", "8|| | | || | | || | | ||8", " || | | || | | || | | || ", " \---------------------------------------------------------/ ", " 0 1 2 3 4 5 6 7 8 ", ] def test_empty_board(self) : # Make empty board with all the labels got = labeled_board(None, want_cell_nums=True, want_num_possibles=True) self.assertEqual(got, Test_labeled_printer.expected_empty_output_cell_and_num_possible) # Make empty board with no extra labels got = labeled_board(None, want_cell_nums=False, want_num_possibles=False) self.assertEqual(got, Test_labeled_printer.expected_empty_output) # Make default empty board. # Should be: want_cell_nums=True, want_num_possibles=False) got = labeled_board() self.assertEqual(got, Test_labeled_printer.expected_empty_output_cell_nums) got = labeled_board(None, want_cell_nums=True, want_num_possibles=False) self.assertEqual(got, Test_labeled_printer.expected_empty_output_cell_nums) def test_caller_supplied_empty(self) : got = labeled_board( Board(), want_cell_nums=True, want_num_possibles=True ) self.assertEqual(got, Test_labeled_printer.expected_empty_output_cell_and_num_possible) test_board = [\ [0, 0, 6, 1, 0, 0, 0, 0, 8], [0, 8, 0, 0, 9, 0, 0, 3, 0], [2, 0, 0, 0, 0, 5, 4, 0, 0], [4, 0, 0, 0, 0, 1, 8, 0, 0], [0, 3, 0, 0, 7, 0, 0, 4, 0], [0, 0, 7, 9, 0, 0, 0, 0, 3], [0, 0, 8, 4, 0, 0, 0, 0, 6], [0, 2, 0, 0, 5, 0, 0, 8, 0], [1, 0, 0, 0, 0, 2, 5, 0, 0] ] test_board_output_cell_and_num_possibles = [\ " 0 1 2 3 4 5 6 7 8 ", " /---------------------------------------------------------\ ", " |0------------------1------------------2------------------| ", " |0 1 2 |3 4 5 |6 7 8 || ", "0|| | | 6 || 1 | | || | | 8 ||0", " ||4 |4 | || |3 |3 ||3 |4 | || ", " |---------------------------------------------------------| ", " |9 10 11 |12 13 14 |15 16 17 || ", "1|| | 8 | || | 9 | || | 3 | ||1", " ||2 | |3 ||3 | |3 ||4 | |4 || ", " |---------------------------------------------------------| ", " |18 19 20 |21 22 23 |24 25 26 || ", "2|| 2 | | || | | 5 || 4 | | ||2", " || |3 |3 ||4 |3 | || |4 |3 || ", " |---------------------------------------------------------| ", " |3------------------4------------------5------------------| ", " |27 28 29 |30 31 32 |33 34 35 || ", "3|| 4 | | || | | 1 || 8 | | ||3", " || |3 |3 ||4 |3 | || |5 |4 || ", " |---------------------------------------------------------| ", " |36 37 38 |39 40 41 |42 43 44 || ", "4|| | 3 | || | 7 | || | 4 | ||4", " ||4 | |4 ||4 | |2 ||4 | |4 || ", " |---------------------------------------------------------| ", " |45 46 47 |48 49 50 |51 52 53 || ", "5|| | | 7 || 9 | | || | | 3 ||5", " ||3 |3 | || |4 |3 ||3 |4 | || ", " |---------------------------------------------------------| ", " |6------------------7------------------8------------------| ", " |54 55 56 |57 58 59 |60 61 62 || ", "6|| | | 8 || 4 | | || | | 6 ||6", " ||4 |3 | || |2 |3 ||5 |4 | || ", " |---------------------------------------------------------| ", " |63 64 65 |66 67 68 |69 70 71 || ", "7|| | 2 | || | 5 | || | 8 | ||7", " ||4 | |3 ||3 | |4 ||4 | |4 || ", " |---------------------------------------------------------| ", " |72 73 74 |75 76 77 |78 79 80 || ", "8|| 1 | | || | | 2 || 5 | | ||8", " || |4 |3 ||4 |3 | || |2 |3 || ", " \---------------------------------------------------------/ ", " 0 1 2 3 4 5 6 7 8 ", ] def test_populated_board(self) : board = Board(Test_labeled_printer.test_board, None, "created by test_populated_board()", ) got = labeled_board( board, want_cell_nums=True, want_num_possibles=True ) self.assertEqual(got, Test_labeled_printer.test_board_output_cell_and_num_possibles) if __name__ == "__main__" : # Run the unittests unittest.main()
47.343195
106
0.347832
81f8e529b873cfea17537db72cab9b4fe446f187
1,557
py
Python
ttest_ngram_metrics.py
KaijuML/dtt-multi-branch
a49850a95034e58d387b9d48c647cfc2b83c45b5
[ "Apache-2.0" ]
8
2021-02-25T08:19:55.000Z
2022-03-12T06:25:36.000Z
ttest_ngram_metrics.py
KaijuML/dtt-multi-branch
a49850a95034e58d387b9d48c647cfc2b83c45b5
[ "Apache-2.0" ]
5
2021-05-20T19:11:58.000Z
2021-07-14T07:46:33.000Z
ttest_ngram_metrics.py
KaijuML/dtt-multi-branch
a49850a95034e58d387b9d48c647cfc2b83c45b5
[ "Apache-2.0" ]
null
null
null
import argparse from pprint import pprint import numpy as np from nltk.translate.bleu_score import sentence_bleu from scipy.stats import ttest_rel from data.utils import FileIterable from parent import parent_instance_level def t_test(packed): stat, p_value = ttest_rel(*packed) return {'t-statistic': stat, 'p-value': p_value} if __name__ == '__main__': parser = argparse.ArgumentParser(description='Compute instance-level BLEU and PARENT metrics for two different ' 'hypothesis files. For each metric, perform a t-test over the two ' 'files.') parser.add_argument('tables') parser.add_argument('references') parser.add_argument('hypotheses_1') parser.add_argument('hypotheses_2') args = parser.parse_args() tables = FileIterable.from_filename(args.tables, fmt='jl') references = FileIterable.from_filename(args.references, fmt='txt') hypotheses = [FileIterable.from_filename(args.hypotheses_1, fmt='txt'), FileIterable.from_filename(args.hypotheses_2, fmt='txt')] bleus = tuple([sentence_bleu([r], h) for r, h in zip(references, hyps)] for hyps in hypotheses) parents = np.array([[parent_instance_level((h, r, t)) for h, r, t in zip(hyps, references, tables)] for hyps in hypotheses]) t_tests = { 'bleu': t_test(bleus), **{f'parent_{mt}': t_test(parents[:, :, i]) for i, mt in enumerate(['p', 'r', 'F1'])} } pprint(t_tests)
36.209302
116
0.648041
355702196091f100d11978415dbfcb1872b4e6ef
1,059
py
Python
tensorflow_datasets/audio/fuss_test.py
shubhamkumaR630/datasets
fe9ee91849cefed0953141ea3588f73b7def78fd
[ "Apache-2.0" ]
2
2022-02-14T09:51:39.000Z
2022-02-14T13:27:49.000Z
tensorflow_datasets/audio/fuss_test.py
shubhamkumaR630/datasets
fe9ee91849cefed0953141ea3588f73b7def78fd
[ "Apache-2.0" ]
null
null
null
tensorflow_datasets/audio/fuss_test.py
shubhamkumaR630/datasets
fe9ee91849cefed0953141ea3588f73b7def78fd
[ "Apache-2.0" ]
1
2020-12-13T22:11:33.000Z
2020-12-13T22:11:33.000Z
# coding=utf-8 # Copyright 2022 The TensorFlow Datasets Authors. # # 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. """Tests for fuss dataset module.""" from tensorflow_datasets import testing from tensorflow_datasets.audio import fuss import tensorflow_datasets.public_api as tfds class FussTest(testing.DatasetBuilderTestCase): DATASET_CLASS = fuss.Fuss BUILDER_CONFIG_NAMES_TO_TEST = ["reverberant"] SPLITS = { tfds.Split.TRAIN: 2, tfds.Split.VALIDATION: 1, tfds.Split.TEST: 1, } if __name__ == "__main__": testing.test_main()
30.257143
74
0.753541
1ea1a6ce9cfe5fddfdf0cf8c1a3988c685ba958e
11,114
py
Python
var/spack/repos/builtin/packages/bazel/package.py
vitodb/spack
b9ab1de4c5f7b21d9f9cb88b7251820a48e82d27
[ "ECL-2.0", "Apache-2.0", "MIT" ]
1
2021-02-22T18:04:31.000Z
2021-02-22T18:04:31.000Z
var/spack/repos/builtin/packages/bazel/package.py
danlipsa/spack
699ae50ebf13ee425a482988ccbd4c3c994ab5e6
[ "ECL-2.0", "Apache-2.0", "MIT" ]
1
2020-04-24T13:30:08.000Z
2020-04-24T13:40:08.000Z
var/spack/repos/builtin/packages/bazel/package.py
danlipsa/spack
699ae50ebf13ee425a482988ccbd4c3c994ab5e6
[ "ECL-2.0", "Apache-2.0", "MIT" ]
null
null
null
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Bazel(Package): """Bazel is an open-source build and test tool similar to Make, Maven, and Gradle. It uses a human-readable, high-level build language. Bazel supports projects in multiple languages and builds outputs for multiple platforms. Bazel supports large codebases across multiple repositories, and large numbers of users.""" homepage = "https://bazel.build/" url = "https://github.com/bazelbuild/bazel/releases/download/1.2.0/bazel-1.2.0-dist.zip" maintainers = ['adamjstewart'] version('1.2.1', sha256='255da49d0f012bc4f2c1d6d3ccdbe578e22fe97b8d124e1629a486fe2a09d3e1') version('1.2.0', sha256='9cb46b0a18b9166730307a0e82bf4c02281a1cc6da0fb11239e6fe4147bdee6e') version('1.1.0', sha256='4b66a8c93af7832ed32e7236cf454a05f3aa06d25a8576fc3f83114f142f95ab') version('1.0.1', sha256='f4d2dfad011ff03a5fae41b9b02cd96cd7297c1205d496603d66516934fbcfee') version('1.0.0', sha256='c61daf0b69dd95205c695b2f9022d296d052c727062cfd396d54ffb2154f8cac') version('0.29.1', sha256='872a52cff208676e1169b3e1cae71b1fe572c4109cbd66eab107d8607c378de5') version('0.29.0', sha256='01cb6f2e808bd016cf0e217e12373c9efb808123e58b37885be8364458d3a40a') version('0.28.1', sha256='2cea463d611f5255d2f3d41c8de5dcc0961adccb39cf0ac036f07070ba720314') version('0.28.0', sha256='26ad8cdadd413b8432cf46d9fc3801e8db85d9922f85dd8a7f5a92fec876557f') version('0.27.2', sha256='5e1bf2b48e54eb7e518430667d29aef53695d6dd7c718665a52131ab27aadab2') version('0.27.1', sha256='8051d77da4ec338acd91770f853e4c25f4407115ed86fd35a6de25921673e779') version('0.27.0', sha256='c3080d3b959ac08502ad5c84a51608c291accb1481baad88a628bbf79b30c67a') version('0.26.1', sha256='c0e94f8f818759f3f67af798c38683520c540f469cb41aea8f5e5a0e43f11600') version('0.26.0', sha256='d26dadf62959255d58e523da3448a6222af768fe1224e321b120c1d5bbe4b4f2') version('0.25.3', sha256='23eafd3e439bc71baba9c592b52cb742dabc8640a13b9da1751fec090a2dda99') version('0.25.2', sha256='7456032199852c043e6c5b3e4c71dd8089c1158f72ec554e6ec1c77007f0ab51') version('0.25.1', sha256='a52bb31aeb1f821e649d25ef48023cfb54a12887aff875c6349ebcac36c2f056') version('0.25.0', sha256='f624fe9ca8d51de192655369ac538c420afb7cde16e1ad052554b582fff09287') version('0.24.1', sha256='56ea1b199003ad832813621744178e42b39e6206d34fbae342562c287da0cd54') version('0.24.0', sha256='621d2a97899a88850a913eabf9285778331a309fd4658b225b1377f80060fa85') version('0.23.2', sha256='293a5a7d851e0618eeb5e6958d94a11d45b6a00f2ba9376de61ac2bd5f917439') version('0.23.1', sha256='dd47199f92452bf67b2c5d60ad4b7143554eaf2c6196ab6e8713449d81a0491d') version('0.23.0', sha256='2daf9c2c6498836ed4ebae7706abb809748b1350cacd35b9f89452f31ac0acc1') version('0.22.0', sha256='6860a226c8123770b122189636fb0c156c6e5c9027b5b245ac3b2315b7b55641') version('0.21.0', sha256='6ccb831e683179e0cfb351cb11ea297b4db48f9eab987601c038aa0f83037db4') version('0.20.0', sha256='1945afa84fd8858b0a3c68c09915a4bc81065c61df2591387b2985e2297d30bd') version('0.19.2', sha256='11234cce4f6bdc62c3ac688f41c7b5c178eecb6f7e2c4ba0bcf00ba8565b1d19') version('0.19.1', sha256='c9405f7b8c79ebc81f9f0e49bb656df4a0da246771d010c2cdd6bb30e2500ac0') version('0.19.0', sha256='ee6135c5c47306c8421d43ad83aabc4f219cb065376ee37797f2c8ba9a615315') version('0.18.1', sha256='baed9f28c317000a4ec1ad2571b3939356d22746ca945ac2109148d7abb860d4') version('0.18.0', sha256='d0e86d2f7881ec8742a9823a986017452d2da0dfe4e989111da787cb89257155') version('0.17.2', sha256='b6e87acfa0a405bb8b3417c58477b66d5bc27dc0d31ba6fa12bc255b9278d33b') version('0.17.1', sha256='23e4281c3628cbd746da3f51330109bbf69780bd64461b63b386efae37203f20') version('0.16.1', sha256='09c66b94356c82c52f212af52a81ac28eb06de1313755a2f23eeef84d167b36c') version('0.16.0', sha256='c730593916ef0ba62f3d113cc3a268e45f7e8039daf7b767c8641b6999bd49b1') version('0.15.2', sha256='bf53ec73be3a6d412d85ef612cec6e9c85db45da42001fab0cf1dad44cfc03f1') version('0.15.1', sha256='c62b351fa4c1ba5aeb34d0a137176f8e8f1d89a32f548a10e96c11df176ffc6c') version('0.15.0', sha256='c3b716e6625e6b8c323350c95cd3ae0f56aeb00458dddd10544d5bead8a7b602') version('0.14.1', sha256='d49cdcd82618ae7a7a190e6f0a80d9bf85c1a66b732f994f37732dc14ffb0025') version('0.14.0', sha256='259627de8b9d415cc80904523facf3d50e6e8e68448ab968eb1c9cb8ca1ef843') version('0.13.1', sha256='b0269e75b40d87ff87886e5f3432cbf88f70c96f907ab588e6c21b2922d72db0') version('0.13.0', sha256='82e9035084660b9c683187618a29aa896f8b05b5f16ae4be42a80b5e5b6a7690') version('0.12.0', sha256='3b3e7dc76d145046fdc78db7cac9a82bc8939d3b291e53a7ce85315feb827754') version('0.11.1', sha256='e8d762bcc01566fa50952c8028e95cfbe7545a39b8ceb3a0d0d6df33b25b333f') version('0.11.0', sha256='abfeccc94728cb46be8dbb3507a23ccffbacef9fbda96a977ef4ea8d6ab0d384') version('0.10.1', sha256='708248f6d92f2f4d6342006c520f22dffa2f8adb0a9dc06a058e3effe7fee667') version('0.10.0', sha256='47e0798caaac4df499bce5fe554a914abd884a855a27085a4473de1d737d9548') version('0.9.0', sha256='efb28fed4ffcfaee653e0657f6500fc4cbac61e32104f4208da385676e76312a') version('0.8.1', sha256='dfd0761e0b7e36c1d74c928ad986500c905be5ebcfbc29914d574af1db7218cf') version('0.8.0', sha256='aa840321d056abd3c6be10c4a1e98a64f9f73fff9aa89c468dae8c003974a078') version('0.7.0', sha256='a084a9c5d843e2343bf3f319154a48abe3d35d52feb0ad45dec427a1c4ffc416') version('0.6.1', sha256='dada1f60a512789747011184b2767d2b44136ef3b036d86947f1896d200d2ba7') version('0.6.0', sha256='a0e53728a9541ef87934831f3d05f2ccfdc3b8aeffe3e037be2b92b12400598e') version('0.5.4', sha256='2157b05309614d6af0e4bbc6065987aede590822634a0522161f3af5d647abc9') version('0.5.3', sha256='76b5c5880a0b15f5b91f7d626c5bc3b76ce7e5d21456963c117ab711bf1c5333') version('0.5.2', sha256='2418c619bdd44257a170b85b9d2ecb75def29e751b725e27186468ada2e009ea') version('0.5.1', sha256='85e6a18b111afeea2e475fe991db2a441ec3824211d659bee7b0012c36be9a40') version('0.5.0', sha256='ebba7330a8715e96a6d6dc0aa085125d529d0740d788f0544c6169d892e4f861') version('0.4.5', sha256='2b737be42678900470ae9e48c975ac5b2296d9ae23c007bf118350dbe7c0552b') version('0.4.4', sha256='d52a21dda271ae645711ce99c70cf44c5d3a809138e656bbff00998827548ebb') version('0.4.3', sha256='cbd2ab580181c17317cf18b2bf825bcded2d97cab01cd5b5fe4f4d520b64f90f') version('0.4.2', sha256='8e6f41252abadcdb2cc7a07f910ec4b45fb12c46f0a578672c6a186c7efcdb36') version('0.4.1', sha256='008c648d3c46ece063ae8b5008480d8ae6d359d35967356685d1c09da07e1064') version('0.4.0', sha256='6474714eee72ba2d4e271ed00ce8c05d67a9d15327bc03962b821b2af2c5ca36') version('0.3.2', sha256='ca5caf7b2b48c7639f45d815b32e76d69650f3199eb8caa541d402722e3f6c10') version('0.3.1', sha256='218d0e28b4d1ee34585f2ac6b18d169c81404d93958815e73e60cc0368efcbb7') version('0.3.0', sha256='357fd8bdf86034b93902616f0844bd52e9304cccca22971ab7007588bf9d5fb3') # https://docs.bazel.build/versions/master/install-compile-source.html#bootstrap-bazel # Until https://github.com/spack/spack/issues/14058 is fixed, use jdk to build bazel # Strict dependency on java@8 as per # https://docs.bazel.build/versions/master/install-compile-source.html#bootstrap-unix-prereq depends_on('jdk@1.8.0:1.8.999', type=('build', 'run')) depends_on('python', type=('build', 'run')) depends_on('zip', type=('build', 'run')) # Pass Spack environment variables to the build patch('bazelruleclassprovider-0.25.patch', when='@0.25:') patch('bazelruleclassprovider-0.14.patch', when='@0.14:0.24') patch('bazelconfiguration-0.3.patch', when='@:0.13') # Inject include paths patch('unix_cc_configure-0.15.patch', when='@0.15:') patch('unix_cc_configure-0.10.patch', when='@0.10:0.14') patch('unix_cc_configure-0.5.3.patch', when='@0.5.3:0.9') patch('cc_configure-0.5.0.patch', when='@0.5.0:0.5.2') patch('cc_configure-0.3.0.patch', when='@:0.4') # Set CC and CXX patch('compile-0.29.patch', when='@0.29:') patch('compile-0.21.patch', when='@0.21:0.28') patch('compile-0.16.patch', when='@0.16:0.20') patch('compile-0.13.patch', when='@0.13:0.15') patch('compile-0.9.patch', when='@0.9:0.12') patch('compile-0.6.patch', when='@0.6:0.8') patch('compile-0.4.patch', when='@0.4:0.5') patch('compile-0.3.patch', when='@:0.3') phases = ['bootstrap', 'install'] def url_for_version(self, version): if version >= Version('0.4.1'): url = 'https://github.com/bazelbuild/bazel/releases/download/{0}/bazel-{0}-dist.zip' else: url = 'https://github.com/bazelbuild/bazel/archive/{0}.tar.gz' return url.format(version) def setup_build_environment(self, env): env.set('EXTRA_BAZEL_ARGS', # Spack's logs don't handle colored output well '--color=no --host_javabase=@local_jdk//:jdk' # Enable verbose output for failures ' --verbose_failures' # Ask bazel to explain what it's up to # Needs a filename as argument ' --explain=explainlogfile.txt' # Increase verbosity of explanation, ' --verbose_explanations' # Show (formatted) subcommands being executed ' --subcommands=pretty_print' ' --jobs={0}'.format(make_jobs)) def bootstrap(self, spec, prefix): bash = which('bash') bash('./compile.sh') def install(self, spec, prefix): mkdir(prefix.bin) install('output/bazel', prefix.bin) @run_after('install') @on_package_attributes(run_tests=True) def test(self): # https://github.com/Homebrew/homebrew-core/blob/master/Formula/bazel.rb # Bazel does not work properly on NFS, switch to /tmp with working_dir('/tmp/spack/bazel/spack-test', create=True): touch('WORKSPACE') with open('ProjectRunner.java', 'w') as f: f.write("""\ public class ProjectRunner { public static void main(String args[]) { System.out.println("Hi!"); } }""") with open('BUILD', 'w') as f: f.write("""\ java_binary( name = "bazel-test", srcs = glob(["*.java"]), main_class = "ProjectRunner", )""") # Spack's logs don't handle colored output well bazel = Executable(self.prefix.bin.bazel) bazel('--output_user_root=/tmp/spack/bazel/spack-test', 'build', '--color=no', '//:bazel-test') exe = Executable('bazel-bin/bazel-test') assert exe(output=str) == 'Hi!\n' def setup_dependent_package(self, module, dependent_spec): module.bazel = Executable('bazel')
59.433155
97
0.741857
46391dd7a5971dbdae86f59980acd65317e38919
4,680
py
Python
tests/test_summary_items.py
lizy331/bert-extractive-summarizer
a7529fa968e87196b47c80c4dcd7dc4a59052cbc
[ "MIT" ]
2
2021-01-15T08:38:11.000Z
2021-07-22T06:01:10.000Z
tests/test_summary_items.py
lizy331/bert-extractive-summarizer
a7529fa968e87196b47c80c4dcd7dc4a59052cbc
[ "MIT" ]
null
null
null
tests/test_summary_items.py
lizy331/bert-extractive-summarizer
a7529fa968e87196b47c80c4dcd7dc4a59052cbc
[ "MIT" ]
null
null
null
import pytest from summarizer import Summarizer, TransformerSummarizer from summarizer.coreference_handler import CoreferenceHandler from transformers import AlbertTokenizer, AlbertModel @pytest.fixture() def custom_summarizer(): albert_model = AlbertModel.from_pretrained('albert-base-v1', output_hidden_states=True) albert_tokenizer = AlbertTokenizer.from_pretrained('albert-base-v1') return Summarizer(custom_model=albert_model, custom_tokenizer=albert_tokenizer) @pytest.fixture() def albert_transformer(): return TransformerSummarizer('Albert', 'albert-base-v1') @pytest.fixture() def summarizer(): return Summarizer('distilbert-base-uncased') @pytest.fixture() def coreference_handler(): return CoreferenceHandler() @pytest.fixture() def passage(): return ''' The Chrysler Building, the famous art deco New York skyscraper, will be sold for a small fraction of its previous sales price. The deal, first reported by The Real Deal, was for $150 million, according to a source familiar with the deal. Mubadala, an Abu Dhabi investment fund, purchased 90% of the building for $800 million in 2008. Real estate firm Tishman Speyer had owned the other 10%. The buyer is RFR Holding, a New York real estate company. Officials with Tishman and RFR did not immediately respond to a request for comments. It's unclear when the deal will close. The building sold fairly quickly after being publicly placed on the market only two months ago. The sale was handled by CBRE Group. The incentive to sell the building at such a huge loss was due to the soaring rent the owners pay to Cooper Union, a New York college, for the land under the building. The rent is rising from $7.75 million last year to $32.5 million this year to $41 million in 2028. Meantime, rents in the building itself are not rising nearly that fast. While the building is an iconic landmark in the New York skyline, it is competing against newer office towers with large floor-to-ceiling windows and all the modern amenities. Still the building is among the best known in the city, even to people who have never been to New York. It is famous for its triangle-shaped, vaulted windows worked into the stylized crown, along with its distinctive eagle gargoyles near the top. It has been featured prominently in many films, including Men in Black 3, Spider-Man, Armageddon, Two Weeks Notice and Independence Day. The previous sale took place just before the 2008 financial meltdown led to a plunge in real estate prices. Still there have been a number of high profile skyscrapers purchased for top dollar in recent years, including the Waldorf Astoria hotel, which Chinese firm Anbang Insurance purchased in 2016 for nearly $2 billion, and the Willis Tower in Chicago, which was formerly known as Sears Tower, once the world's tallest. Blackstone Group (BX) bought it for $1.3 billion 2015. The Chrysler Building was the headquarters of the American automaker until 1953, but it was named for and owned by Chrysler chief Walter Chrysler, not the company itself. Walter Chrysler had set out to build the tallest building in the world, a competition at that time with another Manhattan skyscraper under construction at 40 Wall Street at the south end of Manhattan. He kept secret the plans for the spire that would grace the top of the building, building it inside the structure and out of view of the public until 40 Wall Street was complete. Once the competitor could rise no higher, the spire of the Chrysler building was raised into view, giving it the title. ''' def test_summary_creation(summarizer, passage): res = summarizer(passage, ratio=0.15, min_length=25, max_length=500) assert len(res) > 10 def test_summary_larger_ratio(summarizer, passage): res = summarizer(passage, ratio=0.5) assert len(res) > 10 def test_cluster_algorithm(summarizer, passage): res = summarizer(passage, algorithm='gmm') assert len(res) > 10 def test_do_not_use_first(summarizer, passage): res = summarizer(passage, ratio=0.1, use_first=False) assert res is not None def test_albert(custom_summarizer, passage): res = custom_summarizer(passage) assert len(res) > 10 def test_transformer_clz(albert_transformer, passage): res = albert_transformer(passage) assert len(res) > 10 def test_coreference_handler(coreference_handler): orig = '''My sister has a dog. She loves him.''' resolved = '''My sister has a dog. My sister loves a dog.''' result = coreference_handler.process(orig, min_length=2) assert ' '.join(result) == resolved
51.428571
383
0.764744
ecd8d6f3d796681cb546f1dba8268e4b307031d5
525
py
Python
setup.py
storesund/dash_elasticsearch_autosuggest
24012c41c6f9a95c55a0359be2be7372fd344508
[ "MIT" ]
12
2019-08-14T18:41:22.000Z
2021-12-14T23:12:15.000Z
setup.py
storesund/dash_elasticsearch_autosuggest
24012c41c6f9a95c55a0359be2be7372fd344508
[ "MIT" ]
4
2020-07-07T20:07:31.000Z
2021-05-09T06:47:48.000Z
setup.py
storesund/dash_elasticsearch_autosuggest
24012c41c6f9a95c55a0359be2be7372fd344508
[ "MIT" ]
7
2019-06-22T17:29:50.000Z
2021-10-30T10:24:10.000Z
import json import os from setuptools import setup with open(os.path.join('dash_elasticsearch_autosuggest', 'package.json')) as f: package = json.load(f) package_name = package["name"].replace(" ", "_").replace("-", "_") setup( name=package_name, version=package["version"], author=package['author'], packages=[package_name], include_package_data=True, license=package['license'], description=package['description'] if 'description' in package else package_name, install_requires=[] )
25
85
0.702857
b57807972f9ab6b9b1aeacd17bee891808e072e4
16,105
py
Python
namsel.py
BuddhistDigitalResourceCenter/namsel
f6f112b7e1710db07d47cbaed1dee33a33bfd814
[ "MIT" ]
25
2017-02-18T04:03:36.000Z
2021-03-06T17:44:21.000Z
namsel.py
buda-base/namsel
f6f112b7e1710db07d47cbaed1dee33a33bfd814
[ "MIT" ]
12
2017-02-19T13:47:48.000Z
2019-09-04T07:42:08.000Z
namsel.py
buda-base/namsel
f6f112b7e1710db07d47cbaed1dee33a33bfd814
[ "MIT" ]
13
2017-02-19T11:15:24.000Z
2020-12-08T09:37:21.000Z
#! /usr/bin/env python # encoding: utf-8 import logging import sys from PIL import Image from config_manager import Config, default_config from config_util import load_config, save_config from line_breaker import LineCluster, LineCut import numpy as np from page_elements2 import PageElements as PE2 from recognize import cls, rbfcls from recognize import recognize_chars_probout, recognize_chars_hmm, \ viterbi_post_process, hmm_recognize_bigram from segment import Segmenter, combine_many_boxes import argparse from utils_extra.scantailor_multicore import run_scantailor from fast_utils import fadd_padding import codecs import os from yik import word_parts_set from root_based_finder import is_non_std from termset import syllables import tempfile from subprocess import check_call class FailedPageException(Exception): pass class PageRecognizer(object): def __init__(self, imagefile, conf, page_info={}): confpath = conf.path self.conf = conf.conf self.imagefile = imagefile self.page_array = np.asarray(Image.open(imagefile).convert('L'))/255 if self.page_array.all(): self.conf['line_break_method'] = 'line_cut' # Determine whether a page is of type book or pecha # Define line break method and page type if needed self.line_break_method = self.conf['line_break_method'] self.page_type = self.conf['page_type'] self.retries = 0 self.page_info = page_info self.imgheight = self.page_array.shape[0] self.imgwidth = self.page_array.shape[1] # Determine line break method and page_type if not specified if not self.line_break_method and not self.page_type: if self.page_array.shape[1] > 2*self.page_array.shape[0]: print 'Setting page type as pecha' self.line_break_method = 'line_cluster' self.page_type = 'pecha' else: print 'setting page type as book' self.line_break_method = 'line_cut' self.page_type = 'book' self.conf['page_type'] = self.page_type self.conf['line_break_method'] = self.line_break_method if self.line_break_method == 'line_cluster' and self.page_type != 'pecha': print 'Must use page_type=pecha with line_cluster. Changing page_type' self.page_type = 'pecha' self.detect_o = self.conf.get('detect_o', False) ################################ # The main recognition pipeline ################################ def get_page_elements(self): '''PageElements (PE2) does a first-pass segmentation of blob (characters/punc) ona page, gathers information about width of page objects, isolates body text of pecha-style pages, and determines the number of lines on a page for use in line breaking''' self.shapes = PE2(self.page_array, cls, page_type=self.page_type, low_ink=self.conf['low_ink'], flpath=self.page_info.get('flname',''), detect_o=self.detect_o, clear_hr = self.conf.get('clear_hr', False)) self.shapes.conf = self.conf if self.page_type == 'pecha' or self.line_break_method == 'line_cluster': if not hasattr(self.shapes, 'num_lines'): print 'Error. This page can not be processed. Please inspect the image for problems' raise FailedPageException('The page ({}) you are attempting to process failed'.format(self.imagefile)) self.k_groups = self.shapes.num_lines self.shapes.viterbi_post = self.conf['viterbi_postprocess'] def extract_lines(self): '''Identify lines on a page of text''' if self.line_break_method == 'line_cut': self.line_info = LineCut(self.shapes) if not self.line_info: # immediately skip to re-run with LineCluster sys.exit() elif self.line_break_method == 'line_cluster': self.line_info = LineCluster(self.shapes, k=self.k_groups) self.line_info.rbfcls = rbfcls def generate_segmentation(self): self.segmentation = Segmenter(self.line_info) def recognize_page(self, text=False): try: self.get_page_elements() self.extract_lines() except: import traceback;traceback.print_exc() self.results = [] return self.results self.generate_segmentation() conf = self.conf results = [] try: if not conf['viterbi_postprocessing']: if conf['recognizer'] == 'probout': results = recognize_chars_probout(self.segmentation) elif conf['recognizer'] == 'hmm': results = recognize_chars_hmm(self.segmentation) if conf['postprocess']: # print 'running viterbi post processing as next iter' results = self.viterbi_post_process(self.page_array, results) else: # Should only be call from *within* a non viterbi run... # print 'Debug: Running within viterbi post proc' prob, results = hmm_recognize_bigram(self.segmentation) return prob, results output = [] for n, line in enumerate(results): for m,k in enumerate(line): if isinstance(k[-1], int): print n,m,k self.page_array[k[1]:k[1]+k[3], k[0]:k[0]+k[2]] = 0 Image.fromarray(self.page_array*255).show() output.append(k[-1]) output.append(u'\n') out = ''.join(output) print out if text: results = out self.results = results return results except: import traceback;traceback.print_exc() if not results and not conf['viterbi_postprocessing']: print 'WARNING', '*'*40 print self.page_info['flname'], 'failed to return a result.' print 'WARNING', '*'*40 print if self.line_break_method == 'line_cut' and self.retries < 1: print 'retrying with line_cluster instead of line_cut' try: pr = PageRecognizer(self.imagefile, Config(path=self.confpath, line_break_method='line_cluster', page_type='pecha'), page_info=self.page_info, retries = 1, text=text) return pr.recognize_page() except: logging.info('Exited after failure of second run.') return [] if not conf['viterbi_postprocessing']: if not results: logging.info('***** No OCR output for %s *****' % self.page_info['flname']) if text: results = out self.results = results return results ############################# # Helper and debug methods ############################# def generate_line_imgs(self): pass ############################# ## Experimental ############################# def viterbi_post_process(self, img_arr, results): '''Go through all results and attempts to correct invalid syllables''' final = [[] for i in range(len(results))] for i, line in enumerate(results): syllable = [] for j, char in enumerate(line): if char[-1] in u'་། ' or not word_parts_set.intersection(char[-1]) or j == len(line)-1: if syllable: syl_str = ''.join(s[-1] for s in syllable) if is_non_std(syl_str) and syl_str not in syllables: print syl_str, 'HAS PROBLEMS. TRYING TO FIX' bx = combine_many_boxes([ch[0:4] for ch in syllable]) bx = list(bx) arr = img_arr[bx[1]:bx[1]+bx[3], bx[0]:bx[0]+bx[2]] arr = fadd_padding(arr, 3) try: temp_dir = tempfile.mkdtemp() tmpimg = os.path.join(temp_dir, 'tmp.tif') Image.fromarray(arr*255).convert('L').save(tmpimg) pgrec = PageRecognizer(tmpimg, Config(line_break_method='line_cut', page_type='book', postprocess=False, viterbi_postprocessing=True, clear_hr=False, detect_o=False)) prob, hmm_res = pgrec.recognize_page() os.remove(tmpimg) os.removedirs(temp_dir) except TypeError: print 'HMM run exited with an error.' prob = 0 hmm_res = '' logging.info(u'VPP Correction: %s\t%s' % (syl_str, hmm_res)) if prob == 0 and hmm_res == '': print 'hit problem. using unmodified output' for s in syllable: final[i].append(s) else: bx.append(prob) bx.append(hmm_res) final[i].append(bx) else: for s in syllable: final[i].append(s) final[i].append(char) syllable = [] else: syllable.append(char) if syllable: for s in syllable: final[i].append(s) return final def generate_formatted_page(page_info): pass def run_recognize(imagepath): global args command_args = args if command_args.conf: conf_dict = load_config(command_args.conf) else: conf_dict = default_config # Override any confs with command line versions for key in conf_dict: if not hasattr(command_args, key): continue val = getattr(command_args, key) if val: conf_dict[key] = val rec = PageRecognizer(imagepath, conf=Config(**conf_dict)) if args.format == 'text': text = True else: text = False return rec.recognize_page(text=text) def run_recognize_remote(imagepath, conf_dict, text=False): rec = PageRecognizer(imagepath, conf=Config(**conf_dict)) results = rec.recognize_page(text=text) return results if __name__ == '__main__': DEFAULT_OUTFILE = 'ocr_output.txt' parser = argparse.ArgumentParser(description='Namsel OCR') action_choices = ['preprocess', 'recognize-page', 'isolate-lines', 'view-page-info', 'recognize-volume'] parser.add_argument('action', type=str, choices=action_choices, help='The Namsel function to be executed') parser.add_argument('imagepath', type=str, help="Path to jpeg, tiff, or png image (or a folder containing them, in the case of recognize-volume)") parser.add_argument('--conf', type=str, help='Path to a valid configuration file') parser.add_argument('--format', type=str, choices=['text', 'page-info'], help='Format returned by the recogizer') parser.add_argument('--outfile', type=str, help='Name of the file saved in the ocr_ouput folder. If not specified, filename will be "ocr_output.txt"') # Config override options confgroup = parser.add_argument_group('Config', 'Namsel options') confgroup.add_argument('--page_type', type=str, choices=['pecha', 'book'], help='Type of page') confgroup.add_argument('--line_break_method', type=str, choices=['line_cluster', 'line_cut'], help='Line breaking method. Use line_cluster for page type "pecha"') confgroup.add_argument('--recognizer', type=str, choices=['hmm', 'probout'], help='The recognizer to use. Use HMM unless page contains many hard-to-segment and unusual characters') confgroup.add_argument('--break_width', type=float, help='Threshold value to determine segmentation, measured in stdev above the mean char width') confgroup.add_argument('--segmenter', type=str, help='Type of segmenter to use', choices=['stochastic', 'experimental']) confgroup.add_argument('--low_ink', type=bool, help='Attempt to enhance results for poorly inked prints') confgroup.add_argument('--line_cluster_pos', type=str, choices=['top', 'center']) confgroup.add_argument('--postprocess', type=bool, help='Run viterbi post-processing') confgroup.add_argument('--detect_o', type=bool, help='Detect and set aside na-ro vowels in first pass recognition') confgroup.add_argument('--clear_hr', type=bool, help='Clear all content above a horizontal rule on top of a page') confgroup.add_argument('--line_cut_inflation', type=int, help='The number of iterations to use when dilating image in line breaking. Increase this value when you want to blob things together') scantailor_conf = parser.add_argument_group('Scantailor', 'Preprocessing options') scantailor_conf.add_argument('--layout', choices=['single', 'double'], type=str, help='Option for telling scantailor to expect double or single pages') scantailor_conf.add_argument('--threshold', type=int, help="The amount of thinning or thickening of the output of scantailor. Good values are -40 to 40 (for thinning and thickening respectively)") args = parser.parse_args() if not os.path.exists('ocr_results'): os.mkdir('ocr_results') if args.outfile: outfilename = args.outfile else: outfilename = DEFAULT_OUTFILE if args.action == 'recognize-page': results = run_recognize(args.imagepath) if args.format == 'text': with codecs.open(outfilename, 'w', 'utf-8') as outfile: outmessage = '''OCR text\n\n''' outfile.write(outmessage) outfile.write(os.path.basename(args.imagepath)+'\n') if not isinstance(results, str) or not isinstance(results, unicode): results = 'No content captured for this image' print '****************' print results print "Saving empty page to output" print '****************' outfile.write(results) elif args.action == 'recognize-volume': import multiprocessing import glob if not os.path.isdir(args.imagepath): print 'Error: You must specify the name of a directory containing tif images in order to recognize a volume' sys.exit() pool = multiprocessing.Pool() pages = glob.glob(os.path.join(args.imagepath, '*tif')) pages.sort() results = pool.map(run_recognize, pages) if args.format == 'text': with codecs.open(outfilename, 'w', 'utf-8') as outfile: outmessage = '''OCR text\n\n''' outfile.write(outmessage) for k, r in enumerate(results): outfile.write(os.path.basename(pages[k])+'\n') if not isinstance(r, str) and not isinstance(r, unicode): r = 'No content captured' outfile.write(r + '\n\n') elif args.action == 'preprocess': run_scantailor(args.imagepath, args.threshold, layout=args.layout)
45.49435
200
0.568395
e795444c071a2316a658711d7d83347f9be31a91
1,431
py
Python
src/application/urls.py
yjkimjunior/yjkimjunior
48700fb05e5bfafa6ca55bdf43929b4b12de7f2c
[ "MIT", "CC-BY-3.0", "BSD-2-Clause", "BSD-3-Clause" ]
null
null
null
src/application/urls.py
yjkimjunior/yjkimjunior
48700fb05e5bfafa6ca55bdf43929b4b12de7f2c
[ "MIT", "CC-BY-3.0", "BSD-2-Clause", "BSD-3-Clause" ]
null
null
null
src/application/urls.py
yjkimjunior/yjkimjunior
48700fb05e5bfafa6ca55bdf43929b4b12de7f2c
[ "MIT", "CC-BY-3.0", "BSD-2-Clause", "BSD-3-Clause" ]
null
null
null
""" urls.py URL dispatch route mappings and error handlers """ from flask import render_template from application import app from application import views ## URL dispatch rules # App Engine warm up handler # See http://code.google.com/appengine/docs/python/config/appconfig.html#Warming_Requests # app.add_url_rule('/_ah/warmup', 'warmup', view_func=views.warmup) # Home page app.add_url_rule('/', 'index', view_func=views.index) # # Say hello # app.add_url_rule('/hello/<username>', 'say_hello', view_func=views.say_hello) # # Examples list page # app.add_url_rule('/examples', 'list_examples', view_func=views.list_examples, methods=['GET', 'POST']) # # Examples list page (cached) # app.add_url_rule('/examples/cached', 'cached_examples', view_func=views.cached_examples, methods=['GET']) # # Contrived admin-only view example # app.add_url_rule('/admin_only', 'admin_only', view_func=views.admin_only) # # Edit an example # app.add_url_rule('/examples/<int:example_id>/edit', 'edit_example', view_func=views.edit_example, methods=['GET', 'POST']) # # Delete an example # app.add_url_rule('/examples/<int:example_id>/delete', view_func=views.delete_example, methods=['POST']) ## Error handlers # Handle 404 errors @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 # Handle 500 errors @app.errorhandler(500) def server_error(e): return render_template('500.html'), 500
28.058824
124
0.744235
c3b3133eb875f1a2651bf66846699a87a11e07ff
5,494
py
Python
crm/views.py
wlcobb/foodservice
bafebef79e0322e926c88d2cd16ac1fe77337f76
[ "MIT" ]
null
null
null
crm/views.py
wlcobb/foodservice
bafebef79e0322e926c88d2cd16ac1fe77337f76
[ "MIT" ]
null
null
null
crm/views.py
wlcobb/foodservice
bafebef79e0322e926c88d2cd16ac1fe77337f76
[ "MIT" ]
null
null
null
from django.contrib.auth.decorators import login_required from .models import * from .forms import * from django.shortcuts import render, get_object_or_404 from django.shortcuts import redirect from django.shortcuts import render from django.db.models import Sum now = timezone.now() def home(request): return render(request, 'crm/home.html', {'crm': home}) @login_required def customer_list(request): customer = Customer.objects.filter(created_date__lte=timezone.now()) return render(request, 'crm/customer_list.html', {'customers': customer}) @login_required def customer_edit(request, pk): customer = get_object_or_404(Customer, pk=pk) if request.method == "POST": # update form = CustomerForm(request.POST, instance=customer) if form.is_valid(): customer = form.save(commit=False) customer.updated_date = timezone.now() customer.save() customer = Customer.objects.filter(created_date__lte=timezone.now()) return render(request, 'crm/customer_list.html', {'customers': customer}) else: # edit form = CustomerForm(instance=customer) return render(request, 'crm/customer_edit.html', {'form': form}) @login_required def customer_delete(request, pk): customer = get_object_or_404(Customer, pk=pk) customer.delete() return redirect('portfolio:customer_list') @login_required def service_list(request): services = Service.objects.filter(created_date__lte=timezone.now()) return render(request, 'crm/service_list.html', {'services': services}) @login_required def service_new(request): if request.method == "POST": form = ServiceForm(request.POST) if form.is_valid(): service = form.save(commit=False) service.created_date = timezone.now() service.save() services = Service.objects.filter(created_date__lte=timezone.now()) return render(request, 'crm/service_list.html', {'services': services}) else: form = ServiceForm() # print("Else") return render(request, 'crm/service_new.html', {'form': form}) @login_required def service_edit(request, pk): service = get_object_or_404(Service, pk=pk) if request.method == "POST": form = ServiceForm(request.POST, instance=service) if form.is_valid(): service = form.save() # service.customer = service.id service.updated_date = timezone.now() service.save() services = Service.objects.filter(created_date__lte=timezone.now()) return render(request, 'crm/service_list.html', {'services': services}) else: # print("else") form = ServiceForm(instance=service) return render(request, 'crm/service_edit.html', {'form': form}) @login_required def service_delete(request, pk): service = get_object_or_404(Service, pk=pk) service.delete() return redirect('crm:service_list') @login_required def product_list(request): products = Product.objects.filter(created_date__lte=timezone.now()) return render(request, 'crm/product_list.html', {'products': products}) @login_required def product_new(request): if request.method == "POST": form = ProductForm(request.POST) if form.is_valid(): product = form.save(commit=False) product.created_date = timezone.now() product.save() products = Product.objects.filter(created_date__lte=timezone.now()) return render(request, 'crm/product_list.html', {'products': products}) else: form = ProductForm() # print("Else") return render(request, 'crm/product_new.html', {'form': form}) @login_required def product_edit(request, pk): product = get_object_or_404(Product, pk=pk) if request.method == "POST": form = ProductForm(request.POST, instance=product) if form.is_valid(): product = form.save() # product.customer = product.id product.updated_date = timezone.now() product.save() products = Product.objects.filter(created_date__lte=timezone.now()) return render(request, 'crm/product_list.html', {'services': products}) else: # print("else") form = ProductForm(instance=product) return render(request, 'crm/product_edit.html', {'form': form}) @login_required def product_delete(request, pk): product = get_object_or_404(Service, pk=pk) product.delete() return redirect('crm:service_list') @login_required def summary(request, pk): customer = get_object_or_404(Customer, pk=pk) customers = Customer.objects.filter(created_date__lte=timezone.now()) services = Service.objects.filter(cust_name=pk) products = Product.objects.filter(cust_name=pk) sum_service_charge = Service.objects.filter(cust_name=pk).aggregate(Sum('service_charge')) sum_product_charge = Product.objects.filter(cust_name=pk).aggregate(Sum('charge')) return render(request, 'crm/summary.html', {'customers': customers, 'products': products, 'services': services, 'sum_service_charge': sum_service_charge, 'sum_product_charge': sum_product_charge,})
37.121622
95
0.648162
d15ac8c09ebcabea45b628cb5ef56b63865139eb
1,828
py
Python
cluster.py
CycloChen/small_RNA
3aa4011f6b19a782c353e76103a9ddc3a541fc3c
[ "Unlicense" ]
null
null
null
cluster.py
CycloChen/small_RNA
3aa4011f6b19a782c353e76103a9ddc3a541fc3c
[ "Unlicense" ]
null
null
null
cluster.py
CycloChen/small_RNA
3aa4011f6b19a782c353e76103a9ddc3a541fc3c
[ "Unlicense" ]
null
null
null
#/usr/bin/env python import csv import sys import argparse from collections import OrderedDict #Cluster genome def cluster1(file): with open(file) as f: line=f.readline() cluster={} while line: if line[0]=="@": pass else: i=line.split() #Convert line string to a list a=int(i[3]) #Position in float b=int(i[0].split('_')[1]) #Reads in float c=i[2] #Which chromosome if c+'_' + str(a//1000) in cluster: #Here cluster by 1000bp, it can be change to any length. It can be changed to any length. cluster[c+'_' + str(a//1000)]+=b else: cluster[c+'_' + str(a//1000)]=b line=f.readline() return cluster #Cluster-overlpping def cluster2(file): with open(file) as f: line=f.readline() cluster={} while line: if line[0]=="@": pass else: i=line.split() a=int(i[3]) b=int(i[0].split('_')[1]) c=i[2] if c+'_' + str((a+500)//1000) in cluster: #over-lap 500 bp with the first one. If change, over-lapping half of the full length. cluster[c+'_' + str((a+500)//1000)]+=b else: cluster[c+'_' + str((a+500)//1000)]=b line=f.readline() return cluster #add 0.5 to the key def cluster3(dict): cluster3={} for key, val in dict.items(): s=key.split('_') cluster3[s[0] +'_'+ str(int(s[1])+0.5)]=val return cluster3 #Combine two dicts def combin_dict(x, y): z=x.copy() z.update(y) return z def save_dic(dict): w = csv.writer(open("1_output.csv", "w")) for key, val in dict.items(): w.writerow([key, val]) def main(): parser = argparse.ArgumentParser() parser.add_argument('file', help='first read file') args = parser.parse_args() result1=cluster1(args.file) result2=cluster2(args.file) result3=cluster3(result2) result=combin_dict(result1, result3) save_dic(result) if __name__ == '__main__': main()
23.139241
131
0.636761
08f2510e6e680f42b1c8e30e75ff5ffa3bb4ec13
11,641
py
Python
tf_quant_finance/experimental/dates/date_tensor_test.py
kuangche-james/tf-quant-finance
25251a75ab19147e72f89704f841ed41fbc354db
[ "Apache-2.0" ]
1
2021-09-01T06:27:02.000Z
2021-09-01T06:27:02.000Z
tf_quant_finance/experimental/dates/date_tensor_test.py
bacoco/tf-quant-finance
25251a75ab19147e72f89704f841ed41fbc354db
[ "Apache-2.0" ]
null
null
null
tf_quant_finance/experimental/dates/date_tensor_test.py
bacoco/tf-quant-finance
25251a75ab19147e72f89704f841ed41fbc354db
[ "Apache-2.0" ]
1
2021-09-01T06:26:57.000Z
2021-09-01T06:26:57.000Z
# Lint as: python3 # Copyright 2019 Google LLC # # 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 # # https://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. """Tests for date_tensor.py.""" import datetime import numpy as np import tensorflow.compat.v2 as tf from tf_quant_finance.experimental import dates as dateslib from tf_quant_finance.experimental.dates import test_data from tensorflow.python.framework import test_util # pylint: disable=g-direct-tensorflow-import @test_util.run_all_in_graph_and_eager_modes class DateTensorTest(tf.test.TestCase): def test_convert_to_date_tensor_tuples(self): inputs = [(2018, 5, 4), (2042, 11, 22), (1947, 8, 15)] date_tensor = dateslib.convert_to_date_tensor(inputs) y, m, d = zip(*inputs) self.assert_date_tensor_components(date_tensor, y, m, d, None) def test_convert_to_date_tensor_datetimes(self): inputs = [ datetime.date(2018, 5, 4), datetime.date(2042, 11, 22), datetime.date(1947, 8, 15) ] date_tensor = dateslib.convert_to_date_tensor(inputs) y, m, d = [2018, 2042, 1947], [5, 11, 8], [4, 22, 15] self.assert_date_tensor_components(date_tensor, y, m, d, None) def test_convert_to_date_tensor_ordinals(self): inputs = [1, 2, 3, 4, 5] inputs2 = tf.constant(inputs) date_tensor = dateslib.convert_to_date_tensor(inputs) date_tensor2 = dateslib.convert_to_date_tensor(inputs2) self.assert_date_tensor_components(date_tensor, [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 2, 3, 4, 5], inputs) self.assert_date_tensor_components(date_tensor2, [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 2, 3, 4, 5], inputs) def test_convert_to_date_tensor_tensor_tuples(self): inputs = [ tf.constant([2018, 2042, 1947]), tf.constant([5, 11, 8]), tf.constant([4, 22, 15]) ] date_tensor = dateslib.convert_to_date_tensor(inputs) y, m, d = [2018, 2042, 1947], [5, 11, 8], [4, 22, 15] self.assert_date_tensor_components(date_tensor, y, m, d, None) def test_convert_to_date_tensor_npdatetime(self): inputs = np.array([ datetime.date(2018, 5, 4), datetime.date(2042, 11, 22), datetime.date(1947, 8, 15) ], dtype='datetime64') date_tensor = dateslib.convert_to_date_tensor(inputs) y, m, d = [2018, 2042, 1947], [5, 11, 8], [4, 22, 15] self.assert_date_tensor_components(date_tensor, y, m, d, None) def test_create_from_date_time_list(self): dates = test_data.test_dates y, m, d, o, datetimes = unpack_test_dates(dates) date_tensor = dateslib.from_datetimes(datetimes) self.assert_date_tensor_components(date_tensor, y, m, d, o) def test_create_from_np_datetimes(self): dates = test_data.test_dates y, m, d, o, datetimes = unpack_test_dates(dates) np_datetimes = np.array(datetimes, dtype=np.datetime64) date_tensor = dateslib.from_np_datetimes(np_datetimes) self.assert_date_tensor_components(date_tensor, y, m, d, o) def test_create_from_tuples(self): dates = test_data.test_dates y, m, d, o, _ = unpack_test_dates(dates) date_tensor = dateslib.from_tuples(dates) self.assert_date_tensor_components(date_tensor, y, m, d, o) def test_create_from_year_month_day(self): dates = test_data.test_dates y, m, d, o, _ = unpack_test_dates(dates) date_tensor = dateslib.from_year_month_day(y, m, d) self.assert_date_tensor_components(date_tensor, y, m, d, o) def test_create_from_ordinals(self): dates = test_data.test_dates y, m, d, o, _ = unpack_test_dates(dates) date_tensor = dateslib.from_ordinals(o) self.assert_date_tensor_components(date_tensor, y, m, d, o) def test_to_and_from_tensor(self): dates = [[[2020, 1, 21], [2021, 2, 22], [2022, 3, 23]], [[2023, 4, 24], [2024, 5, 25], [2025, 6, 26]]] date_tensor = dateslib.from_tensor(dates) with self.subTest('from_tensor'): self.assert_date_tensor_components( date_tensor, [[2020, 2021, 2022], [2023, 2024, 2025]], [[1, 2, 3], [4, 5, 6]], [[21, 22, 23], [24, 25, 26]]) with self.subTest('to_tensor'): self.assertAllEqual(dates, date_tensor.to_tensor()) def test_validation(self): not_raised = [] for y, m, d in test_data.invalid_dates: try: self.evaluate(dateslib.from_tuples([(y, m, d)]).month()) not_raised.append((y, m, d)) except tf.errors.InvalidArgumentError: pass self.assertEmpty(not_raised) for invalid_ordinal in [-5, 0]: with self.assertRaises(tf.errors.InvalidArgumentError): self.evaluate(dateslib.from_ordinals([invalid_ordinal]).month()) def test_day_of_week(self): dates = test_data.test_dates datetimes = unpack_test_dates(dates)[-1] date_tensor = dateslib.from_datetimes(datetimes) expected_day_of_week = np.array([dt.weekday() for dt in datetimes]) self.assertAllEqual(expected_day_of_week, date_tensor.day_of_week()) def test_days_until(self): dates = test_data.test_dates diffs = np.arange(0, len(dates)) _, _, _, o, datetimes = unpack_test_dates(dates) date_tensor = dateslib.from_datetimes(datetimes) target_ordinals = o + diffs target_datetimes = [datetime.date.fromordinal(o) for o in target_ordinals] target_date_tensor = dateslib.from_datetimes(target_datetimes) self.assertAllEqual(diffs, date_tensor.days_until(target_date_tensor)) def test_days_addition(self): self.perform_addition_test(test_data.day_addition_data, dateslib.PeriodType.DAY) def test_week_addition(self): self.perform_addition_test(test_data.week_addition_data, dateslib.PeriodType.WEEK) def test_month_addition(self): self.perform_addition_test(test_data.month_addition_data, dateslib.PeriodType.MONTH) def test_year_addition(self): self.perform_addition_test(test_data.year_addition_data, dateslib.PeriodType.YEAR) def perform_addition_test(self, data, period_type): dates_from, quantities, expected_dates = [], [], [] for date_from, quantity, expected_date in data: dates_from.append(date_from) quantities.append(quantity) expected_dates.append(expected_date) datetimes = unpack_test_dates(dates_from)[-1] date_tensor = dateslib.from_datetimes(datetimes) period_tensor = dateslib.periods.PeriodTensor(quantities, period_type) result_date_tensor = date_tensor + period_tensor y, m, d, o, _ = unpack_test_dates(expected_dates) self.assert_date_tensor_components(result_date_tensor, y, m, d, o) def test_date_subtraction(self): # Subtraction trivially transforms to addition, so we don't test # extensively. dates_from = dateslib.from_tuples([(2020, 3, 15), (2020, 3, 31)]) period = dateslib.periods.PeriodTensor([2, 1], dateslib.PeriodType.MONTH) expected_ordinals = np.array([datetime.date(2020, 1, 15).toordinal(), datetime.date(2020, 2, 29).toordinal()]) self.assertAllEqual(expected_ordinals, (dates_from - period).ordinal()) def test_comparisons(self): dates1 = dateslib.from_tuples([(2020, 3, 15), (2020, 3, 31), (2021, 2, 28)]) dates2 = dateslib.from_tuples([(2020, 3, 18), (2020, 3, 31), (2019, 2, 28)]) self.assertAllEqual(np.array([False, True, False]), dates1 == dates2) self.assertAllEqual(np.array([True, False, True]), dates1 != dates2) self.assertAllEqual(np.array([False, False, True]), dates1 > dates2) self.assertAllEqual(np.array([False, True, True]), dates1 >= dates2) self.assertAllEqual(np.array([True, False, False]), dates1 < dates2) self.assertAllEqual(np.array([True, True, False]), dates1 <= dates2) def test_tensor_wrapper_ops(self): dates1 = dateslib.from_tuples([(2019, 3, 25), (2020, 1, 2), (2019, 1, 2)]) dates2 = dateslib.from_tuples([(2019, 4, 25), (2020, 5, 2), (2018, 1, 2)]) dates = dateslib.DateTensor.stack((dates1, dates2), axis=-1) self.assertEqual((3, 2), dates.shape) self.assertEqual((2,), dates[0].shape) self.assertEqual((2, 2), dates[1:].shape) self.assertEqual((2, 1), dates[1:, :-1].shape) self.assertEqual((3, 1, 2), dates.expand_dims(axis=1).shape) self.assertEqual((3, 3, 2), dates.broadcast_to((3, 3, 2)).shape) def test_boolean_mask(self): dates = dateslib.from_tuples([(2019, 3, 25), (2020, 1, 2), (2019, 1, 2)]) mask = [True, False, True] expected = dateslib.DateTensor.stack((dates[0], dates[2])) self.assert_date_tensor_equals(expected, dates.boolean_mask(mask)) def test_day_of_year(self): data = test_data.day_of_year_data date_tuples, expected_days_of_year = zip(*data) dates = dateslib.from_tuples(date_tuples) self.assertAllEqual(expected_days_of_year, dates.day_of_year()) def test_random_dates(self): start_dates = dateslib.from_tuples([(2020, 5, 16), (2020, 6, 13)]) end_dates = dateslib.from_tuples([(2021, 5, 21)]) size = 3 # Generate 3 dates for each pair of (start, end date). sample = dateslib.random_dates( start_date=start_dates, end_date=end_dates, size=size, seed=42) self.assertEqual(sample.shape, (3, 2)) self.assertTrue(self.evaluate(tf.reduce_all(sample < end_dates))) self.assertTrue(self.evaluate(tf.reduce_all(sample >= start_dates))) def test_is_end_of_month(self): cases = test_data.end_of_month_test_cases dates = dateslib.from_tuples([case[0] for case in cases]) expected = tf.constant([case[1] for case in cases]) self.assertAllEqual(expected, dates.is_end_of_month()) def test_to_end_of_month(self): cases = test_data.end_of_month_test_cases dates = dateslib.from_tuples([case[0] for case in cases]) expected = dateslib.from_tuples([case[2] for case in cases]) self.assert_date_tensor_equals(expected, dates.to_end_of_month()) def assert_date_tensor_equals(self, expected_date_tensor, actual_date_tensor): """Asserts given two DateTensors are equal.""" self.assertAllEqual(expected_date_tensor.ordinal(), actual_date_tensor.ordinal()) def assert_date_tensor_components(self, date_tensor, expected_years_np, expected_months_np, expected_days_np, expected_ordinals_np=None): """Asserts given DateTensor has expected components.""" self.assertAllEqual(expected_years_np, date_tensor.year()) self.assertAllEqual(expected_months_np, date_tensor.month()) self.assertAllEqual(expected_days_np, date_tensor.day()) if expected_ordinals_np is not None: self.assertAllEqual(expected_ordinals_np, date_tensor.ordinal()) def unpack_test_dates(dates): y, m, d = (np.array([d[i] for d in dates], dtype=np.int32) for i in range(3)) datetimes = [datetime.date(y, m, d) for y, m, d in dates] o = np.array([datetime.date(y, m, d).toordinal() for y, m, d in dates], dtype=np.int32) return y, m, d, o, datetimes if __name__ == '__main__': tf.test.main()
42.330909
95
0.685422
08222af6f3570a2ec4b64f179d46b5a8abf8e80c
74,190
py
Python
flair/trainers/finetune_trainer.py
CharlieKC/ACE
ba8909e49dd5408881684f080f2de81b6ec224c2
[ "MIT" ]
161
2020-10-28T03:11:50.000Z
2022-03-28T11:24:29.000Z
flair/trainers/finetune_trainer.py
CharlieKC/ACE
ba8909e49dd5408881684f080f2de81b6ec224c2
[ "MIT" ]
30
2020-11-24T05:43:26.000Z
2022-03-16T04:02:47.000Z
flair/trainers/finetune_trainer.py
CharlieKC/ACE
ba8909e49dd5408881684f080f2de81b6ec224c2
[ "MIT" ]
23
2020-10-14T02:35:37.000Z
2022-03-28T03:10:09.000Z
""" Fine-tune trainer: a trainer for finetuning BERT and able to be parallelized based on flair Author: Xinyu Wang Contact: wangxy1@shanghaitech.edu.cn """ from .distillation_trainer import * from transformers import ( AdamW, get_linear_schedule_with_warmup, ) from flair.models.biaffine_attention import BiaffineAttention, BiaffineFunction from torch.optim.lr_scheduler import ExponentialLR, LambdaLR import random import copy from flair.parser.utils.alg import crf import h5py import numpy as np START_TAG: str = "<START>" STOP_TAG: str = "<STOP>" dependency_tasks={'enhancedud', 'dependency', 'srl', 'ner_dp'} def get_inverse_square_root_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, fix_embedding_steps, steepness = 0.5, factor = 5, model_size=1, last_epoch=-1): """ Create a schedule with a learning rate that decreases linearly after linearly increasing during a warmup period. """ def lr_lambda(current_step): # step 0 ~ fix_embedding_steps: no modification # step fix_embedding_steps ~ num_warmup_steps + fix_embedding_steps: warmup embedding training # step num_warmup_steps + fix_embedding_steps ~ : square root decay if current_step < fix_embedding_steps: return 1 elif current_step < num_warmup_steps + fix_embedding_steps: return float(current_step-fix_embedding_steps) / float(max(1, num_warmup_steps)) step = max(current_step - num_warmup_steps - fix_embedding_steps, 1) return max(0.0, factor * (model_size ** (-0.5) * min(step ** (-steepness), step * num_warmup_steps ** (-steepness - 1)))) return LambdaLR(optimizer, lr_lambda, last_epoch) class ModelFinetuner(ModelDistiller): def __init__( self, model: flair.nn.Model, teachers: List[flair.nn.Model], corpus: ListCorpus, optimizer = AdamW, professors: List[flair.nn.Model] = [], epoch: int = 0, optimizer_state: dict = None, scheduler_state: dict = None, use_tensorboard: bool = False, distill_mode: bool = False, ensemble_distill_mode: bool = False, config = None, train_with_professor: bool = False, is_test: bool = False, language_resample: bool = False, direct_upsample_rate: int = -1, down_sample_amount: int = -1, sentence_level_batch: bool = False, clip_sentences: int = -1, remove_sentences: bool = False, assign_doc_id: bool = False, train_with_doc: bool = False, pretrained_file_dict: dict = {}, sentence_level_pretrained_data: bool = False, ): """ Initialize a model trainer :param model: The model that you want to train. The model should inherit from flair.nn.Model :param teachers: The teacher models for knowledge distillation. The model should inherit from flair.nn.Model :param corpus: The dataset used to train the model, should be of type Corpus :param optimizer: The optimizer to use (Default AdamW for finetuning BERT) :param epoch: The starting epoch (normally 0 but could be higher if you continue training model) :param optimizer_state: Optimizer state (necessary if continue training from checkpoint) :param scheduler_state: Scheduler state (necessary if continue training from checkpoint) :param use_tensorboard: If True, writes out tensorboard information :param sentence_level_batch: If True, count the batch size by the number of sentences, otherwise the number of tokens :param assign_doc_id: Set to True if using document-level embeddings :param pretrained_file_dict: The dictionary of predicted embeddings. Set to True if using document-level embeddings :param down_sample_amount: Downsample the training set """ # if teachers is not None: # assert len(teachers)==len(corpus.train_list), 'Training data and teachers should be the same length now!' self.model: flair.nn.Model = model self.config = config self.corpus: ListCorpus = corpus num_languages = len(self.corpus.targets) self.corpus2id = {x:i for i,x in enumerate(self.corpus.targets)} self.sentence_level_batch = sentence_level_batch if language_resample or direct_upsample_rate>0: sent_per_set=torch.FloatTensor([len(x) for x in self.corpus.train_list]) total_sents=sent_per_set.sum() sent_each_dataset=sent_per_set/total_sents exp_sent_each_dataset=sent_each_dataset.pow(0.7) sent_sample_prob=exp_sent_each_dataset/exp_sent_each_dataset.sum() self.sentence_level_pretrained_data=sentence_level_pretrained_data if assign_doc_id: doc_sentence_dict = {} same_corpus_mapping = {'CONLL_06_GERMAN': 'CONLL_03_GERMAN_NEW', 'CONLL_03_GERMAN_DP': 'CONLL_03_GERMAN_NEW', 'CONLL_03_DP': 'CONLL_03_ENGLISH', 'CONLL_03_DUTCH_DP': 'CONLL_03_DUTCH_NEW', 'CONLL_03_SPANISH_DP': 'CONLL_03_SPANISH_NEW'} for corpus_id in range(len(self.corpus2id)): if self.corpus.targets[corpus_id] in same_corpus_mapping: corpus_name = same_corpus_mapping[self.corpus.targets[corpus_id]].lower()+'_' else: corpus_name = self.corpus.targets[corpus_id].lower()+'_' doc_sentence_dict = self.assign_documents(self.corpus.train_list[corpus_id], 'train_', doc_sentence_dict, corpus_name, train_with_doc) doc_sentence_dict = self.assign_documents(self.corpus.dev_list[corpus_id], 'dev_', doc_sentence_dict, corpus_name, train_with_doc) doc_sentence_dict = self.assign_documents(self.corpus.test_list[corpus_id], 'test_', doc_sentence_dict, corpus_name, train_with_doc) if train_with_doc: new_sentences=[] for sentid, sentence in enumerate(self.corpus.train_list[corpus_id]): if sentence[0].text=='-DOCSTART-': continue new_sentences.append(sentence) self.corpus.train_list[corpus_id].sentences = new_sentences.copy() self.corpus.train_list[corpus_id].reset_sentence_count new_sentences=[] for sentid, sentence in enumerate(self.corpus.dev_list[corpus_id]): if sentence[0].text=='-DOCSTART-': continue new_sentences.append(sentence) self.corpus.dev_list[corpus_id].sentences = new_sentences.copy() self.corpus.dev_list[corpus_id].reset_sentence_count new_sentences=[] for sentid, sentence in enumerate(self.corpus.test_list[corpus_id]): if sentence[0].text=='-DOCSTART-': continue new_sentences.append(sentence) self.corpus.test_list[corpus_id].sentences = new_sentences.copy() self.corpus.test_list[corpus_id].reset_sentence_count if train_with_doc: self.corpus._train: FlairDataset = ConcatDataset([data for data in self.corpus.train_list]) self.corpus._dev: FlairDataset = ConcatDataset([data for data in self.corpus.dev_list]) self.corpus._test: FlairDataset = ConcatDataset([data for data in self.corpus.test_list]) # for key in pretrained_file_dict: # pdb.set_trace() for embedding in self.model.embeddings.embeddings: if embedding.name in pretrained_file_dict: self.assign_predicted_embeddings(doc_sentence_dict,embedding,pretrained_file_dict[embedding.name]) for corpus_name in self.corpus2id: i = self.corpus2id[corpus_name] for sentence in self.corpus.train_list[i]: sentence.lang_id=i if len(self.corpus.dev_list)>i: for sentence in self.corpus.dev_list[i]: sentence.lang_id=i if len(self.corpus.test_list)>i: for sentence in self.corpus.test_list[i]: sentence.lang_id=i if language_resample: length = len(self.corpus.train_list[i]) # idx = random.sample(range(length), int(sent_sample_prob[i] * total_sents)) idx = torch.randint(length, (int(sent_sample_prob[i] * total_sents),)) self.corpus.train_list[i].sentences = [self.corpus.train_list[i][x] for x in idx] if direct_upsample_rate>0: if len(self.corpus.train_list[i].sentences)<(sent_per_set.max()/direct_upsample_rate).item(): res_sent=[] dev_res_sent=[] for sent_batch in range(direct_upsample_rate): res_sent+=copy.deepcopy(self.corpus.train_list[i].sentences) if config['train']['train_with_dev']: dev_res_sent+=copy.deepcopy(self.corpus.dev_list[i].sentences) self.corpus.train_list[i].sentences = res_sent self.corpus.train_list[i].reset_sentence_count if config['train']['train_with_dev']: self.corpus.dev_list[i].sentences = dev_res_sent self.corpus.dev_list[i].reset_sentence_count if down_sample_amount>0: if len(self.corpus.train_list[i].sentences)>down_sample_amount: if 'use_unlabeled_data' in config['train'] and config['train']['use_unlabeled_data']: if 'unlabel' not in corpus_name.lower(): continue self.corpus.train_list[i].sentences = self.corpus.train_list[i].sentences[:down_sample_amount] self.corpus.train_list[i].reset_sentence_count if config['train']['train_with_dev']: self.corpus.dev_list[i].sentences = self.corpus.dev_list[i].sentences[:down_sample_amount] self.corpus.dev_list[i].reset_sentence_count if clip_sentences>-1: new_sentences=[] removed_count=0 max_len = 0 for sentence in self.corpus.train_list[i].sentences: subtoken_length = self.get_subtoken_length(sentence) if subtoken_length>max_len: max_len = subtoken_length if subtoken_length > clip_sentences: removed_count+=1 else: new_sentences.append(sentence) self.corpus.train_list[i].sentences = new_sentences self.corpus.train_list[i].reset_sentence_count log.info(f"Longest subwords in the training set {max_len}") log.info(f"Removed {removed_count} sentences whose subwords are longer than {clip_sentences}") if direct_upsample_rate>0 or down_sample_amount: self.corpus._train: FlairDataset = ConcatDataset([data for data in self.corpus.train_list]) if config['train']['train_with_dev']: self.corpus._dev: FlairDataset = ConcatDataset([data for data in self.corpus.dev_list]) print(self.corpus) self.distill_mode = distill_mode if self.distill_mode: # self.corpus_mixed_train: ListCorpus = [CoupleDataset(student_set,self.corpus_teacher.train_list[index]) for index,student_set in enumerate(self.corpus.train_list)] self.teachers: List[flair.nn.Model] = teachers self.professors: List[flair.nn.Model] = professors if self.teachers is not None: for teacher in self.teachers: teacher.eval() for professor in self.professors: professor.eval() try: num_teachers = len(self.teachers)+int(len(self.professors)>0) self.num_teachers=num_teachers except: num_teachers = 0 self.num_teachers=num_teachers # self.corpus = self.assign_pretrained_teacher_predictions(self.corpus,self.corpus_teacher,self.teachers) self.update_params_group=[] self.optimizer: torch.optim.Optimizer = optimizer if type(optimizer)==str: self.optimizer = getattr(torch.optim,optimizer) self.epoch: int = epoch self.scheduler_state: dict = scheduler_state self.optimizer_state: dict = optimizer_state self.use_tensorboard: bool = use_tensorboard self.use_bert = False self.bert_tokenizer = None for embedding in self.model.embeddings.embeddings: if 'bert' in embedding.__class__.__name__.lower(): self.use_bert=True self.bert_tokenizer = embedding.tokenizer self.ensemble_distill_mode: bool = ensemble_distill_mode self.train_with_professor: bool = train_with_professor # if self.train_with_professor: # assert len(self.professors) == len(self.corpus.train_list), 'Now only support same number of professors and corpus!' def train( self, base_path: Union[Path, str], learning_rate: float = 5e-5, mini_batch_size: int = 32, eval_mini_batch_size: int = None, max_epochs: int = 100, anneal_factor: float = 0.5, patience: int = 10, min_learning_rate: float = 5e-9, train_with_dev: bool = False, macro_avg: bool = True, monitor_train: bool = False, monitor_test: bool = False, embeddings_storage_mode: str = "cpu", checkpoint: bool = False, save_final_model: bool = True, anneal_with_restarts: bool = False, shuffle: bool = True, true_reshuffle: bool = False, param_selection_mode: bool = False, num_workers: int = 4, sampler=None, use_amp: bool = False, language_attention_warmup_and_fix: bool = False, language_attention_warmup: bool = False, language_attention_entropy: bool = False, train_language_attention_by_dev: bool = False, calc_teachers_target_loss: bool = False, entropy_loss_rate: float = 1, amp_opt_level: str = "O1", professor_interpolation = 0.5, best_k = 10, max_epochs_without_improvement = 100, gold_reward = False, warmup_steps: int = 0, use_warmup: bool = False, gradient_accumulation_steps: int = 1, lr_rate: int = 1, decay: float = 0.75, decay_steps: int = 5000, use_unlabeled_data: bool =False, sort_data: bool = True, fine_tune_mode: bool = False, debug: bool = False, min_freq: int = -1, min_lemma_freq: int = -1, min_pos_freq: int = -1, unlabeled_data_for_zeroshot: bool = False, rootschedule: bool = False, freezing: bool = False, save_finetuned_embedding: bool = False, **kwargs, ) -> dict: """ Trains any class that implements the flair.nn.Model interface. :param base_path: Main path to which all output during training is logged and models are saved :param learning_rate: Initial learning rate :param mini_batch_size: Size of mini-batches during training :param eval_mini_batch_size: Size of mini-batches during evaluation :param max_epochs: Maximum number of epochs to train. Terminates training if this number is surpassed. :param anneal_factor: The factor by which the learning rate is annealed :param patience: Patience is the number of epochs with no improvement the Trainer waits until annealing the learning rate :param min_learning_rate: If the learning rate falls below this threshold, training terminates :param train_with_dev: If True, training is performed using both train+dev data :param monitor_train: If True, training data is evaluated at end of each epoch :param monitor_test: If True, test data is evaluated at end of each epoch :param embeddings_storage_mode: One of 'none' (all embeddings are deleted and freshly recomputed), 'cpu' (embeddings are stored on CPU) or 'gpu' (embeddings are stored on GPU) :param checkpoint: If True, a full checkpoint is saved at end of each epoch :param save_final_model: If True, final model is saved :param anneal_with_restarts: If True, the last best model is restored when annealing the learning rate :param shuffle: If True, data is shuffled during training :param param_selection_mode: If True, testing is performed against dev data. Use this mode when doing parameter selection. :param num_workers: Number of workers in your data loader. :param sampler: You can pass a data sampler here for special sampling of data. :param kwargs: Other arguments for the Optimizer :return: """ self.n_gpu = torch.cuda.device_count() min_learning_rate = learning_rate/1000 self.gold_reward = gold_reward self.embeddings_storage_mode=embeddings_storage_mode self.mini_batch_size=mini_batch_size if self.use_tensorboard: try: from torch.utils.tensorboard import SummaryWriter writer = SummaryWriter() except: log_line(log) log.warning( "ATTENTION! PyTorch >= 1.1.0 and pillow are required for TensorBoard support!" ) log_line(log) self.use_tensorboard = False pass if use_amp: if sys.version_info < (3, 0): raise RuntimeError("Apex currently only supports Python 3. Aborting.") if amp is None: raise RuntimeError( "Failed to import apex. Please install apex from https://www.github.com/nvidia/apex " "to enable mixed-precision training." ) if eval_mini_batch_size is None: eval_mini_batch_size = mini_batch_size # cast string to Path if type(base_path) is str: base_path = Path(base_path) log_handler = add_file_handler(log, base_path / "training.log") log_line(log) log.info(f'Model: "{self.model}"') log_line(log) log.info(f'Corpus: "{self.corpus}"') log_line(log) log.info("Parameters:") log.info(f' - Optimizer: "{self.optimizer.__name__}"') log.info(f' - learning_rate: "{learning_rate}"') log.info(f' - mini_batch_size: "{mini_batch_size}"') log.info(f' - patience: "{patience}"') log.info(f' - anneal_factor: "{anneal_factor}"') log.info(f' - max_epochs: "{max_epochs}"') log.info(f' - shuffle: "{shuffle}"') log.info(f' - train_with_dev: "{train_with_dev}"') log.info(f' - word min_freq: "{min_freq}"') log_line(log) log.info(f'Model training base path: "{base_path}"') log_line(log) log.info(f"Device: {flair.device}") log_line(log) log.info(f"Embeddings storage mode: {embeddings_storage_mode}") # determine what splits (train, dev, test) to evaluate and log if monitor_train: assert 0, 'monitor_train is not supported now!' # if train_with_dev: # assert 0, 'train_with_dev is not supported now!' log_train = True if monitor_train else False log_test = ( True if (not param_selection_mode and self.corpus.test and monitor_test) else False ) log_dev = True if not train_with_dev else False # prepare loss logging file and set up header loss_txt = init_output_file(base_path, "loss.tsv") # weight_extractor = WeightExtractor(base_path) # finetune_params = {name:param for name,param in self.model.named_parameters()} finetune_params=[param for name,param in self.model.named_parameters() if 'embedding' in name or name=='linear.weight' or name=='linear.bias'] other_params=[param for name,param in self.model.named_parameters() if 'embedding' not in name and name !='linear.weight' and name !='linear.bias'] # other_params = {name:param for name,param in self.model.named_parameters() if 'embeddings' not in name} if len(self.update_params_group)>0: optimizer: torch.optim.Optimizer = self.optimizer( [{"params":other_params,"lr":learning_rate*lr_rate}, {"params":self.update_params_group,"lr":learning_rate*lr_rate}, {"params":finetune_params} ], lr=learning_rate, **kwargs ) else: optimizer: torch.optim.Optimizer = self.optimizer( [{"params":other_params,"lr":learning_rate*lr_rate}, {"params":finetune_params} ], lr=learning_rate, **kwargs ) if self.optimizer_state is not None: optimizer.load_state_dict(self.optimizer_state) if use_amp: self.model, optimizer = amp.initialize( self.model, optimizer, opt_level=amp_opt_level ) # minimize training loss if training with dev data, else maximize dev score # start from here, the train data is a list now train_data = self.corpus.train_list # if self.distill_mode: # train_data_teacher = self.corpus_teacher.train_list # train_data = self.corpus_mixed # if training also uses dev data, include in training set if train_with_dev: train_data = [ConcatDataset([train, self.corpus.dev_list[index]]) for index, train in enumerate(self.corpus.train_list)] # if self.distill_mode: # train_data_teacher = [ConcatDataset([train, self.corpus_teacher.dev_list[index]]) for index, train in enumerate(self.corpus_teacher.train_list)] # train_data = [ConcatDataset([train, self.corpus_mixed.dev_list[index]]) for index, train in self.corpus_mixed.train_list] # train_data_teacher = ConcatDataset([self.corpus_teacher.train, self.corpus_teacher.dev]) # train_data = ConcatDataset([self.corpus_mixed.train, self.corpus_mixed.dev]) if self.distill_mode: # coupled_train_data = [CoupleDataset(data,train_data_teacher[index]) for index, data in enumerate(train_data)] coupled_train_data = train_data # faster=True # if 'fast' in self.model.__class__.__name__.lower(): # faster=True # else: # faster=False faster = False if self.train_with_professor: log.info(f"Predicting professor prediction") # train_data_teacher = self.corpus_teacher.train_list coupled_train_data=self.assign_pretrained_teacher_predictions(coupled_train_data,self.professors,is_professor=True,faster=faster) for professor in self.professors: del professor del self.professors if self.model.distill_crf or self.model.distill_posterior: train_data=self.assign_pretrained_teacher_targets(coupled_train_data,self.teachers,best_k=best_k) else: train_data=self.assign_pretrained_teacher_predictions(coupled_train_data,self.teachers,faster=faster) # if self.ensemble_distill_mode: # log.info(f"Ensembled distillation mode") # coupled_train_data = ConcatDataset(coupled_train_data) # train_data=self.assign_ensembled_teacher_predictions(coupled_train_data,self.teachers) # # coupled_train_data = [] # else: # train_data=self.assign_pretrained_teacher_predictions(coupled_train_data,self.teachers) # #train_data=ConcatDataset(train_data) for teacher in self.teachers: del teacher del self.teachers batch_loader=ColumnDataLoader(train_data,mini_batch_size,shuffle,use_bert=self.use_bert,tokenizer=self.bert_tokenizer, sort_data=sort_data, model = self.model, sentence_level_batch = self.sentence_level_batch) else: batch_loader=ColumnDataLoader(ConcatDataset(train_data),mini_batch_size,shuffle,use_bert=self.use_bert,tokenizer=self.bert_tokenizer, sort_data=sort_data, model = self.model, sentence_level_batch = self.sentence_level_batch) batch_loader.assign_tags(self.model.tag_type,self.model.tag_dictionary) if self.distill_mode: batch_loader=self.resort(batch_loader,is_crf=self.model.distill_crf, is_posterior = self.model.distill_posterior, is_token_att = self.model.token_level_attention) if not train_with_dev: if macro_avg: dev_loaders=[ColumnDataLoader(list(subcorpus),eval_mini_batch_size,use_bert=self.use_bert,tokenizer=self.bert_tokenizer, sort_data=sort_data, model = self.model, sentence_level_batch = self.sentence_level_batch) \ for subcorpus in self.corpus.dev_list] for loader in dev_loaders: loader.assign_tags(self.model.tag_type,self.model.tag_dictionary) else: dev_loader=ColumnDataLoader(list(self.corpus.dev),eval_mini_batch_size,use_bert=self.use_bert,tokenizer=self.bert_tokenizer, sort_data=sort_data, model = self.model, sentence_level_batch = self.sentence_level_batch) dev_loader.assign_tags(self.model.tag_type,self.model.tag_dictionary) test_loader=ColumnDataLoader(list(self.corpus.test),eval_mini_batch_size,use_bert=self.use_bert,tokenizer=self.bert_tokenizer, sort_data=sort_data, model = self.model, sentence_level_batch = self.sentence_level_batch) test_loader.assign_tags(self.model.tag_type,self.model.tag_dictionary) # if self.distill_mode: # batch_loader.expand_teacher_predictions() # if sampler is not None: # sampler = sampler(train_data) # shuffle = False if not fine_tune_mode: if self.model.tag_type in dependency_tasks: scheduler = ExponentialLR(optimizer, decay**(1/decay_steps)) else: anneal_mode = "min" if train_with_dev else "max" scheduler: ReduceLROnPlateau = ReduceLROnPlateau( optimizer, factor=anneal_factor, patience=patience, mode=anneal_mode, verbose=True, ) else: ### Finetune Scheduler t_total = (len(batch_loader) // gradient_accumulation_steps + int((len(batch_loader) % gradient_accumulation_steps)>0)) * max_epochs if rootschedule: warmup_steps = (len(batch_loader) // gradient_accumulation_steps + int((len(batch_loader) % gradient_accumulation_steps)>0)) scheduler = get_inverse_square_root_schedule_with_warmup(optimizer, num_warmup_steps=warmup_steps, num_training_steps=t_total, fix_embedding_steps = warmup_steps) else: if use_warmup: warmup_steps = (len(batch_loader) // gradient_accumulation_steps + int((len(batch_loader) % gradient_accumulation_steps)>0)) scheduler = get_linear_schedule_with_warmup( optimizer, num_warmup_steps=warmup_steps, num_training_steps=t_total ) if self.scheduler_state is not None: scheduler.load_state_dict(self.scheduler_state) ### Finetune Scheduler if freezing: for embedding in self.model.embeddings.embeddings: embedding.fine_tune = False dev_score_history = [] dev_loss_history = [] train_loss_history = [] # At any point you can hit Ctrl + C to break out of training early. best_score=0 interpolation=1 if fine_tune_mode: pass else: self.model.embeddings=self.model.embeddings.to('cpu') if log_test: loaders = [batch_loader,test_loader] else: loaders = [batch_loader] if not train_with_dev: if macro_avg: self.gpu_friendly_assign_embedding(loaders+dev_loaders) else: self.gpu_friendly_assign_embedding(loaders+[dev_loader]) else: self.gpu_friendly_assign_embedding(loaders) try: previous_learning_rate = learning_rate training_order = None bad_epochs2=0 for epoch in range(0 + self.epoch, max_epochs + self.epoch): log_line(log) # get new learning rate if self.model.use_crf: learning_rate = optimizer.param_groups[0]["lr"] else: for group in optimizer.param_groups: learning_rate = group["lr"] if freezing and epoch == 1+self.epoch and fine_tune_mode: for embedding in self.model.embeddings.embeddings: if 'flair' in embedding.__class__.__name__.lower(): embedding.fine_tune = False continue embedding.fine_tune = True # reload last best model if annealing with restarts is enabled if ( learning_rate != previous_learning_rate and anneal_with_restarts and (base_path / "best-model.pt").exists() ): log.info("resetting to best model") self.model.load(base_path / "best-model.pt") previous_learning_rate = learning_rate # stop training if learning rate becomes too small if learning_rate < min_learning_rate and warmup_steps <= 0: log_line(log) log.info("learning rate too small - quitting training!") log_line(log) break if self.model.tag_type in dependency_tasks: if bad_epochs2>=max_epochs_without_improvement: log_line(log) log.info(str(bad_epochs2) + " epochs after improvement - quitting training!") log_line(log) break if shuffle: batch_loader.reshuffle() if true_reshuffle: batch_loader.true_reshuffle() batch_loader.assign_tags(self.model.tag_type,self.model.tag_dictionary) if self.distill_mode: batch_loader=self.resort(batch_loader,is_crf=self.model.distill_crf, is_posterior = self.model.distill_posterior, is_token_att = self.model.token_level_attention) self.model.train() # TODO: check teacher parameters fixed and with eval() mode train_loss: float = 0 seen_batches = 0 #total_number_of_batches = sum([len(loader) for loader in batch_loader]) total_number_of_batches = len(batch_loader) modulo = max(1, int(total_number_of_batches / 10)) # process mini-batches batch_time = 0 total_sent=0 if self.distill_mode: if self.teacher_annealing: # interpolation=1 interpolation=1-(((epoch-warmup_bias)*total_number_of_batches)/total_number_of_batches*self.anneal_factor)/100.0 if interpolation<0: interpolation=0 else: interpolation=self.interpolation log.info("Current loss interpolation: "+ str(interpolation)) name_list=sorted([x.name for x in self.model.embeddings.embeddings]) print(name_list) for batch_no, student_input in enumerate(batch_loader): # for group in optimizer.param_groups: # temp_lr = group["lr"] # log.info('lr: '+str(temp_lr)) if self.distill_mode: if self.teacher_annealing: interpolation=1-(((epoch-warmup_bias)*total_number_of_batches+batch_no)/total_number_of_batches*self.anneal_factor)/100.0 if interpolation<0: interpolation=0 else: interpolation=self.interpolation # log.info("Current loss interpolation: "+ str(interpolation)) start_time = time.time() total_sent+=len(student_input) try: if self.distill_mode: loss = self.model.simple_forward_distillation_loss(student_input, interpolation = interpolation, train_with_professor=self.train_with_professor) else: loss = self.model.forward_loss(student_input) if self.model.use_decoder_timer: decode_time=time.time() - self.model.time # Backward if batch_no >= total_number_of_batches//gradient_accumulation_steps * gradient_accumulation_steps: # only accumulate the rest of batch loss = loss/(total_number_of_batches-total_number_of_batches//gradient_accumulation_steps * gradient_accumulation_steps) else: loss = loss/gradient_accumulation_steps if use_amp: with amp.scale_loss(loss, optimizer) as scaled_loss: scaled_loss.backward() else: loss.backward() pass except Exception: traceback.print_exc() pdb.set_trace() # pdb.set_trace() # print(self.model.linear.weight.sum()) train_loss += loss.item() seen_batches += 1 batch_time += time.time() - start_time if (batch_no+1)%gradient_accumulation_steps==0 or (batch_no == total_number_of_batches - 1): torch.nn.utils.clip_grad_norm_(self.model.parameters(), 5.0) if len(self.update_params_group)>0: torch.nn.utils.clip_grad_norm_(self.update_params_group, 5.0) # print("update model") optimizer.step() self.model.zero_grad() # optimizer.zero_grad() if (fine_tune_mode or self.model.tag_type in dependency_tasks): scheduler.step() if batch_no % modulo == 0: if self.model.use_decoder_timer: log.info( f"epoch {epoch + 1} - iter {batch_no}/{total_number_of_batches} - loss " f"{train_loss / (seen_batches) * gradient_accumulation_steps:.8f} - samples/sec: {total_sent / batch_time:.2f} - decode_sents/sec: {total_sent / decode_time:.2f}" ) else: log.info( f"epoch {epoch + 1} - iter {batch_no}/{total_number_of_batches} - loss " f"{train_loss / seen_batches* gradient_accumulation_steps:.8f} - samples/sec: {total_sent / batch_time:.2f}" ) total_sent=0 batch_time = 0 iteration = epoch * total_number_of_batches + batch_no # if not param_selection_mode: # weight_extractor.extract_weights( # self.model.state_dict(), iteration # ) # depending on memory mode, embeddings are moved to CPU, GPU or deleted store_embeddings(student_input, embeddings_storage_mode) if self.distill_mode: store_teacher_predictions(student_input, embeddings_storage_mode) # if self.model.embedding_selector: # print(sorted(student_input.features.keys())) # print(self.model.selector) # print(torch.argmax(self.model.selector,-1)) train_loss /= seen_batches self.model.eval() log_line(log) log.info( f"EPOCH {epoch + 1} done: loss {train_loss:.4f} - lr {learning_rate}" ) if self.use_tensorboard: writer.add_scalar("train_loss", train_loss, epoch + 1) # anneal against train loss if training with dev, otherwise anneal against dev score current_score = train_loss # evaluate on train / dev / test split depending on training settings result_line: str = "" if log_train: train_eval_result, train_loss = self.model.evaluate( batch_loader, embeddings_storage_mode=embeddings_storage_mode, ) result_line += f"\t{train_eval_result.log_line}" # depending on memory mode, embeddings are moved to CPU, GPU or deleted store_embeddings(self.corpus.train, embeddings_storage_mode) log_line(log) if log_dev: if macro_avg: if type(self.corpus) is ListCorpus: result_dict={} loss_list=[] print_sent='\n' for index, loader in enumerate(dev_loaders): # log_line(log) # log.info('current corpus: '+self.corpus.targets[index]) if len(loader) == 0: continue current_result, dev_loss = self.model.evaluate( loader, embeddings_storage_mode=embeddings_storage_mode, ) result_dict[self.corpus.targets[index]]=current_result.main_score*100 print_sent+=self.corpus.targets[index]+'\t'+f'{result_dict[self.corpus.targets[index]]:.2f}'+'\t' loss_list.append(dev_loss) # log.info(current_result.log_line) # log.info(current_result.detailed_results) else: assert 0, 'not defined!' mavg=sum(result_dict.values())/len(result_dict) log.info('Macro Average: '+f'{mavg:.2f}'+'\tMacro avg loss: ' + f'{((sum(loss_list)/len(loss_list)).item()):.2f}' + print_sent) dev_score_history.append(mavg) dev_loss_history.append((sum(loss_list)/len(loss_list)).item()) current_score = mavg else: dev_eval_result, dev_loss = self.model.evaluate( dev_loader, embeddings_storage_mode=embeddings_storage_mode, ) result_line += f"\t{dev_loss}\t{dev_eval_result.log_line}" log.info( f"DEV : loss {dev_loss} - score {dev_eval_result.main_score}" ) # calculate scores using dev data if available # append dev score to score history dev_score_history.append(dev_eval_result.main_score) dev_loss_history.append(dev_loss) current_score = dev_eval_result.main_score # depending on memory mode, embeddings are moved to CPU, GPU or deleted store_embeddings(self.corpus.dev, embeddings_storage_mode) if self.use_tensorboard: writer.add_scalar("dev_loss", dev_loss, epoch + 1) writer.add_scalar( "dev_score", dev_eval_result.main_score, epoch + 1 ) log_line(log) if log_test: test_eval_result, test_loss = self.model.evaluate( test_loader, base_path / "test.tsv", embeddings_storage_mode=embeddings_storage_mode, ) result_line += f"\t{test_loss}\t{test_eval_result.log_line}" log.info( f"TEST : loss {test_loss} - score {test_eval_result.main_score}" ) # depending on memory mode, embeddings are moved to CPU, GPU or deleted store_embeddings(self.corpus.test, embeddings_storage_mode) if self.use_tensorboard: writer.add_scalar("test_loss", test_loss, epoch + 1) writer.add_scalar( "test_score", test_eval_result.main_score, epoch + 1 ) log.info(test_eval_result.log_line) log.info(test_eval_result.detailed_results) if type(self.corpus) is MultiCorpus: for subcorpus in self.corpus.corpora: log_line(log) log.info('current corpus: '+subcorpus.name) current_result, test_loss = self.model.evaluate( ColumnDataLoader(list(subcorpus.test),eval_mini_batch_size,use_bert=self.use_bert,tokenizer=self.bert_tokenizer, sort_data=sort_data, model = self.model, sentence_level_batch = self.sentence_level_batch), out_path=base_path / f"{subcorpus.name}-test.tsv", embeddings_storage_mode=embeddings_storage_mode, ) log.info(current_result.log_line) log.info(current_result.detailed_results) elif type(self.corpus) is ListCorpus: for index,subcorpus in enumerate(self.corpus.test_list): log_line(log) log.info('current corpus: '+self.corpus.targets[index]) current_result, test_loss = self.model.evaluate( ColumnDataLoader(list(subcorpus),eval_mini_batch_size,use_bert=self.use_bert,tokenizer=self.bert_tokenizer, sort_data=sort_data, model = self.model, sentence_level_batch = self.sentence_level_batch), out_path=base_path / f"{self.corpus.targets[index]}-test.tsv", embeddings_storage_mode=embeddings_storage_mode, ) log.info(current_result.log_line) log.info(current_result.detailed_results) # determine learning rate annealing through scheduler if not fine_tune_mode and self.model.tag_type not in dependency_tasks: scheduler.step(current_score) if current_score>best_score: best_score=current_score bad_epochs2=0 else: bad_epochs2+=1 if train_with_dev: # train as the learning rate gradually drops bad_epochs2 = 0 train_loss_history.append(train_loss) # determine bad epoch number try: bad_epochs = scheduler.num_bad_epochs except: bad_epochs = 0 for group in optimizer.param_groups: new_learning_rate = group["lr"] if new_learning_rate != previous_learning_rate: bad_epochs = patience + 1 # log bad epochs log.info(f"BAD EPOCHS (no improvement): {bad_epochs}") log.info(f"GLOBAL BAD EPOCHS (no improvement): {bad_epochs2}") # output log file # with open(loss_txt, "a") as f: # # make headers on first epoch # if epoch == 0: # f.write( # f"EPOCH\tTIMESTAMP\tBAD_EPOCHS\tLEARNING_RATE\tTRAIN_LOSS" # ) # if log_train: # f.write( # "\tTRAIN_" # + "\tTRAIN_".join( # train_eval_result.log_header.split("\t") # ) # ) # if log_dev: # f.write( # "\tDEV_LOSS\tDEV_" # + "\tDEV_".join(dev_eval_result.log_header.split("\t")) # ) # if log_test: # f.write( # "\tTEST_LOSS\tTEST_" # + "\tTEST_".join( # test_eval_result.log_header.split("\t") # ) # ) # f.write( # f"\n{epoch}\t{datetime.datetime.now():%H:%M:%S}\t{bad_epochs}\t{learning_rate:.4f}\t{train_loss}" # ) # f.write(result_line) # if checkpoint is enable, save model at each epoch if checkpoint and not param_selection_mode: self.model.save_checkpoint( base_path / "checkpoint.pt", optimizer.state_dict(), scheduler.state_dict(), epoch + 1, train_loss, ) # if we use dev data, remember best model based on dev evaluation score if ( not train_with_dev and not param_selection_mode and current_score == best_score ): log.info(f"==================Saving the current best model: {current_score}==================") self.model.save(base_path / "best-model.pt") if save_finetuned_embedding: # pdb.set_trace() log.info(f"==================Saving the best language model: {current_score}==================") for embedding in self.model.embeddings.embeddings: if hasattr(embedding,'fine_tune') and embedding.fine_tune: if not os.path.exists(base_path/embedding.name.split('/')[-1]): os.mkdir(base_path/embedding.name.split('/')[-1]) embedding.tokenizer.save_pretrained(base_path/embedding.name.split('/')[-1]) embedding.model.save_pretrained(base_path/embedding.name.split('/')[-1]) # torch.save(embedding,base_path/(embedding.name.split('/')[-1]+'.bin')) # if we do not use dev data for model selection, save final model if save_final_model and not param_selection_mode: self.model.save(base_path / "final-model.pt") if save_finetuned_embedding and train_with_dev: # pdb.set_trace() log.info(f"==================Saving the best language model: {current_score}==================") for embedding in self.model.embeddings.embeddings: if hasattr(embedding,'fine_tune') and embedding.fine_tune: if not os.path.exists(base_path/embedding.name.split('/')[-1]): os.mkdir(base_path/embedding.name.split('/')[-1]) embedding.tokenizer.save_pretrained(base_path/embedding.name.split('/')[-1]) embedding.model.save_pretrained(base_path/embedding.name.split('/')[-1]) # torch.save(embedding,base_path/(embedding.name.split('/')[-1]+'.bin')) except KeyboardInterrupt: log_line(log) log.info("Exiting from training early.") if self.use_tensorboard: writer.close() if not param_selection_mode: log.info("Saving model ...") self.model.save(base_path / "final-model.pt") log.info("Done.") # test best model if test data is present if self.corpus.test: final_score = self.final_test(base_path, eval_mini_batch_size, num_workers) else: final_score = 0 log.info("Test data not provided setting final score to 0") # pdb.set_trace() log.removeHandler(log_handler) if self.use_tensorboard: writer.close() return { "test_score": final_score, "dev_score_history": dev_score_history, "train_loss_history": train_loss_history, "dev_loss_history": dev_loss_history, } @property def interpolation(self): try: return self.config['interpolation'] except: return 0.5 @property def teacher_annealing(self): try: return self.config['teacher_annealing'] except: return False @property def anneal_factor(self): try: return self.config['anneal_factor'] except: return 2 def assign_pretrained_teacher_predictions(self,coupled_train_data,teachers,is_professor=False,faster=False): if not is_professor: log.info('Distilling sentences...') else: log.info('Distilling professor sentences...') assert len(self.corpus.targets) == len(coupled_train_data), 'Coupled train data is not equal to target!' counter=0 # res_input=[] use_bert=False for teacher in teachers: if teacher.use_bert: use_bert=True # break start_time=time.time() for teacher in teachers: teacher = teacher.to(flair.device) for index, train_data in enumerate(coupled_train_data): target = self.corpus.targets[index] if target not in teacher.targets: continue loader=ColumnDataLoader(list(train_data),self.mini_batch_size,grouped_data=False,use_bert=use_bert, model = teacher, sentence_level_batch = self.sentence_level_batch) loader.word_map = teacher.word_map loader.char_map = teacher.char_map if self.model.tag_dictionary.item2idx !=teacher.tag_dictionary.item2idx: pdb.set_trace() assert 0, "the tag_dictionaries of the teacher and student are not same" for batch in loader: counter+=len(batch) # student_input, teacher_input = zip(*batch) # student_input=list(student_input) teacher_input=list(batch) lengths1 = torch.Tensor([len(sentence.tokens) for sentence in teacher_input]) # lengths2 = torch.Tensor([len(sentence.tokens) for sentence in student_input]) # assert (lengths1==lengths2).all(), 'two batches are not equal!' max_len = max(lengths1) mask=self.model.sequence_mask(lengths1, max_len).unsqueeze(-1).cuda().float() with torch.no_grad(): # assign tags for the dependency parsing teacher_input=loader.assign_tags(teacher.tag_type,teacher.tag_dictionary,teacher_input=teacher_input) teacher_input=teacher_input[0] if self.model.tag_type=='dependency': arc_scores, rel_scores=teacher.forward(teacher_input) if self.model.distill_arc: logits = arc_scores if hasattr(self.model,'distill_rel') and self.model.distill_rel: arc_probs = arc_scores.softmax(-1) rel_probs = rel_scores.softmax(-1) if self.model.distill_factorize: logits = arc_probs else: logits = arc_probs.unsqueeze(-1) * rel_probs else: logits=teacher.forward(teacher_input) if self.model.distill_prob: logits=F.softmax(logits,-1) if hasattr(teacher_input,'features'): teacher_input.features = {} for idx, sentence in enumerate(teacher_input): # if hasattr(sentence,'_teacher_target'): # assert 0, 'The sentence has been filled with teacher target!' if not faster: if self.model.tag_type=="dependency": if self.model.distill_factorize: sentence.set_teacher_rel_prediction(rel_probs[idx][:len(sentence),:len(sentence),:], self.embeddings_storage_mode) sentence.set_teacher_prediction(logits[idx][:len(sentence),:len(sentence)], self.embeddings_storage_mode) else: sentence.set_teacher_prediction(logits[idx][:len(sentence)], self.embeddings_storage_mode) else: sentence.set_teacher_prediction(logits[idx]*mask[idx], self.embeddings_storage_mode) teacher_input[idx].clear_embeddings() del logits # res_input+=student_input # store_embeddings(teacher_input, "none") # del teacher teacher = teacher.to('cpu') end_time=time.time() print("Distilling Costs: ", f"{end_time-start_time:.2f}","senconds") res_input=[] for data in coupled_train_data: for sentence in data: res_input.append(sentence) if is_professor: log.info('Distilled '+str(counter)+' professor sentences') return coupled_train_data else: log.info('Distilled '+str(counter)+' sentences by '+str(len(teachers))+' models') return res_input def assign_pretrained_teacher_targets(self,coupled_train_data,teachers,best_k=10): log.info('Distilling sentences as targets...') assert len(self.corpus.targets) == len(coupled_train_data), 'Coupled train data is not equal to target!' counter=0 use_bert=False for teacher in teachers: if teacher.use_bert: use_bert=True for teacherid, teacher in enumerate(teachers): teacher = teacher.to(flair.device) for index, train_data in enumerate(coupled_train_data): target = self.corpus.targets[index] if target not in teacher.targets: continue loader=ColumnDataLoader(list(train_data),self.mini_batch_size,grouped_data=False,use_bert=use_bert, model = teacher, sentence_level_batch = self.sentence_level_batch) loader.word_map = teacher.word_map loader.char_map = teacher.char_map if self.model.tag_dictionary.item2idx !=teacher.tag_dictionary.item2idx: # pdb.set_trace() assert 0, "the tag_dictionaries of the teacher and student are not same" for batch in loader: counter+=len(batch) # student_input, teacher_input = zip(*batch) # student_input=list(student_input) teacher_input=list(batch) lengths1 = torch.Tensor([len(sentence.tokens) for sentence in teacher_input]) # lengths2 = torch.Tensor([len(sentence.tokens) for sentence in student_input]) # assert (lengths1==lengths2).all(), 'two batches are not equal!' max_len = max(lengths1) mask=self.model.sequence_mask(lengths1, max_len).unsqueeze(-1).cuda().long() lengths1=lengths1.long() with torch.no_grad(): teacher_input=loader.assign_tags(teacher.tag_type,teacher.tag_dictionary,teacher_input=teacher_input) teacher_input=teacher_input[0] if self.model.tag_type=='dependency': mask[:,0] = 0 arc_scores, rel_scores=teacher.forward(teacher_input) logits = arc_scores else: logits=teacher.forward(teacher_input) if self.model.distill_crf: if self.model.tag_type=='dependency': if self.model.distill_rel: arc_probs = arc_scores.softmax(-1) rel_probs = rel_scores.softmax(-1) arc_rel_probs = arc_probs.unsqueeze(-1) * rel_probs arc_rel_scores = (arc_rel_probs+1e-100).log() dist=generate_tree(arc_rel_scores,mask.squeeze(-1).long(),is_mst=self.model.is_mst) decode_idx = dist.topk(best_k) decode_idx = decode_idx.permute(1,2,3,4,0) decode_idx = convert_score_back(decode_idx) # dependency, head arc_predictions = decode_idx.sum(-2).argmax(-2) rel_predictions = decode_idx.sum(-3).argmax(-2) decode_idx = arc_predictions # decode_idx = convert_score_back(arc_predictions.permute(1,2,0)) # rel_predictions = convert_score_back(rel_predictions.permute(1,2,0)) else: dist=generate_tree(arc_scores,mask.squeeze(-1).long(),is_mst=self.model.is_mst) decode_idx = dist.topk(best_k) decode_idx = decode_idx.permute(1,2,3,0) decode_idx = convert_score_back(decode_idx) decode_idx = decode_idx.argmax(-2) maximum_num_trees = dist.count # sentence_lens = sentence_lens ** 2 # generate the top-k mask path_mask = torch.arange(best_k).expand(len(mask), best_k).type_as(mask) < maximum_num_trees.unsqueeze(1) if self.model.crf_attention: path_score = dist.kmax(best_k).transpose(0,1) path_score.masked_fill_(~path_mask.bool(), float('-inf')) path_score = path_score.softmax(-1) else: path_score = path_mask else: if self.gold_reward: for s_id, sentence in enumerate(batch): # get the tags in this sentence tag_idx: List[int] = [ tag_dictionary.get_idx_for_item(token.get_tag(tag_type).value) for token in sentence ] # add tags as tensor tag_template = torch.zeros(max_len,device='cpu') tag = torch.tensor(tag_idx, device='cpu') tag_template[:len(sentence)]=tag path_score, decode_idx=teacher._viterbi_decode_nbest(logits,mask,best_k) # test=(decode_idx- decode_idx[:,:,0][:,:,None]).abs().sum(1)[:,[1,2,3,4]] # sent_len=mask.sum([-1,-2]) # if 0 in test: # for i,line in enumerate(test): # if 0 in line and sent_len[i]!=1: # pdb.set_trace() if self.model.distill_posterior: if self.model.tag_type=='dependency': if self.model.distill_rel: assert 0 arc_probs = arc_scores.softmax(-1) rel_probs = rel_scores.softmax(-1) arc_rel_probs = arc_probs.unsqueeze(-1) * rel_probs arc_rel_scores = (arc_rel_probs+1e-100).log() # arc_rel_scores.masked_fill_(~mask.unsqueeze(1).unsqueeze(1).bool(), float(-1e9)) dist=generate_tree(arc_rel_scores,mask.squeeze(-1).long(),is_mst=self.model.is_mst) else: # calculate the marginal distribution forward_backward_score = crf(arc_scores, mask.squeeze(-1).bool()) # dist=generate_tree(arc_scores,mask.squeeze(-1).long(),is_mst=self.model.is_mst) # forward_backward_score = dist.marginals # forward_backward_score = forward_backward_score.detach() else: # forward_var = self.model._forward_alg(logits, lengths1, distill_mode=True) # backward_var = self.model._backward_alg(logits, lengths1) logits[:,:,teacher.tag_dictionary.get_idx_for_item(STOP_TAG)]-=1e12 logits[:,:,teacher.tag_dictionary.get_idx_for_item(START_TAG)]-=1e12 logits[:,:,teacher.tag_dictionary.get_idx_for_item('<unk>')]-=1e12 if not hasattr(teacher,'transitions'): forward_backward_score = logits else: forward_var = teacher._forward_alg(logits, lengths1, distill_mode=True) backward_var = teacher._backward_alg(logits, lengths1) forward_backward_score = (forward_var + backward_var) * mask.float() # pdb.set_trace() # temperature = 10 # partition_score = teacher._forward_alg(logits,lengths1, T = temperature) # forward_var = teacher._forward_alg(logits, lengths1, distill_mode=True, T = temperature) # backward_var = teacher._backward_alg(logits, lengths1, T = temperature) # forward_backward_score2 = (forward_var + backward_var) * mask.float() # fw_bw_partition = forward_backward_score2.logsumexp(-1) # fw_bw_partition = fw_bw_partition * mask.squeeze(-1) # print(((fw_bw_partition - partition_score[:,None]) * mask.squeeze(-1)).abs().max()) # print(max(lengths1)) # (logits[:,0]/temperature+teacher.transitions[None,:,teacher.tag_dictionary.get_idx_for_item(START_TAG)]/temperature).logsumexp(-1) # (teacher.transitions[teacher.tag_dictionary.get_idx_for_item(STOP_TAG)]/temperature).logsumexp(-1) # backward_partition = teacher._backward_alg(logits,lengths1, distill_mode = False) # print(((forward_backward_score.logsumexp(-1)[:,0]-partition_score).abs()).max()) # print((backward_partition-partition_score).abs().max()) # print((((forward_backward_score.logsumexp(-1)[:,0]-partition_score).abs())>0).sum()/float(len(forward_backward_score))) # print((((backward_partition-partition_score).abs())>0).sum()/float(len(forward_backward_score))) # print(max(lengths1)) # torch.logsumexp(forward_backward_score,-1) # temp_var = forward_var[range(forward_var.shape[0]), lengths1-1, :] # terminal_var = temp_var + teacher.transitions[teacher.tag_dictionary.get_idx_for_item(STOP_TAG)][None,:] # temp_var = backward_var[range(forward_var.shape[0]), 0, :] # terminal_var = temp_var + teacher.transitions[:,teacher.tag_dictionary.get_idx_for_item(START_TAG)][None,:] # forward_backward_score.logsumexp(-1) for idx, sentence in enumerate(teacher_input): # if hasattr(sentence,'_teacher_target'): # assert 0, 'The sentence has been filled with teacher target!' if self.model.distill_crf: if self.model.crf_attention or self.model.tag_type=='dependency': sentence.set_teacher_weights(path_score[idx], self.embeddings_storage_mode) sentence.set_teacher_target(decode_idx[idx]*mask[idx], self.embeddings_storage_mode) if hasattr(self.model,'distill_rel') and self.model.distill_rel: sentence.set_teacher_rel_target(rel_predictions[idx]*mask[idx], self.embeddings_storage_mode) if self.model.distill_posterior: # sentence.set_teacher_posteriors(forward_backward_score[idx][:len(sentence)-1,:len(sentence)-1], self.embeddings_storage_mode) sentence.set_teacher_posteriors(forward_backward_score[idx], self.embeddings_storage_mode) teacher_input[idx].clear_embeddings() del logits # store_embeddings(teacher_input, "none") teacher = teacher.to('cpu') # del teacher log.info('Distilled '+str(counter)+' sentences') res_input=[] for data in coupled_train_data: for sentence in data: res_input.append(sentence) return res_input def resort(self,loader,is_crf=False, is_posterior=False, is_token_att=False): for batch in loader: if is_posterior: try: posteriors=[x._teacher_posteriors for x in batch] posterior_lens=[len(x[0]) for x in posteriors] lens=posterior_lens.copy() targets=posteriors.copy() except: pdb.set_trace() if is_token_att: sentfeats=[x._teacher_sentfeats for x in batch] sentfeats_lens=[len(x[0]) for x in sentfeats] # lens=sentfeats_lens.copy() # targets=sentfeats.copy() if is_crf: targets=[x._teacher_target for x in batch] lens=[len(x[0]) for x in targets] if hasattr(self.model,'distill_rel') and self.model.distill_rel: rel_targets=[x._teacher_rel_target for x in batch] if (not is_crf and not is_posterior): targets=[x._teacher_prediction for x in batch] if hasattr(self.model, 'distill_factorize') and self.model.distill_factorize: rel_targets=[x._teacher_rel_prediction for x in batch] # pdb.set_trace() lens=[len(x[0]) for x in targets] sent_lens=[len(x) for x in batch] if is_posterior: assert posterior_lens==lens, 'lengths of two targets not match' if max(lens)>min(lens) or max(sent_lens)!=max(lens) or (is_posterior and self.model.tag_type=='dependency'): # if max(sent_lens)!=max(lens): max_shape=max(sent_lens) for index, target in enumerate(targets): new_targets=[] new_rel_targets=[] new_posteriors=[] new_sentfeats=[] new_starts=[] new_ends=[] if is_posterior: post_vals=posteriors[index] if is_token_att: sentfeats_vals=sentfeats[index] for idx, val in enumerate(target): if self.model.tag_type=='dependency': if is_crf: shape=[max_shape]+list(val.shape[1:]) new_target=torch.zeros(shape).type_as(val) new_target[:sent_lens[index]]=val[:sent_lens[index]] new_targets.append(new_target) if hasattr(self.model,'distill_rel') and self.model.distill_rel: cur_val = rel_targets[index][idx] rel_shape=[max_shape]+list(cur_val.shape[1:]) new_rel_target=torch.zeros(rel_shape).type_as(cur_val) new_rel_target[:sent_lens[index]]=cur_val[:sent_lens[index]] new_rel_targets.append(new_rel_target) if not is_crf and not is_posterior: shape=[max_shape,max_shape]+list(val.shape[2:]) new_target=torch.zeros(shape).type_as(val) new_target[:sent_lens[index],:sent_lens[index]]=val[:sent_lens[index],:sent_lens[index]] new_targets.append(new_target) if hasattr(self.model, 'distill_factorize') and self.model.distill_factorize: cur_val = rel_targets[index][idx] rel_shape=[max_shape,max_shape]+list(cur_val.shape[2:]) new_rel_target=torch.zeros(rel_shape).type_as(cur_val) new_rel_target[:sent_lens[index],:sent_lens[index]]=cur_val[:sent_lens[index],:sent_lens[index]] new_rel_targets.append(new_rel_target) if is_posterior: post_val=post_vals[idx] # shape=[max_shape-1,max_shape-1] + list(post_val.shape[2:]) shape=[max_shape,max_shape] + list(post_val.shape[2:]) # if max_shape==8: # pdb.set_trace() new_posterior=torch.zeros(shape).type_as(post_val) # remove the root token # new_posterior[:sent_lens[index]-1,:sent_lens[index]-1]=post_val[:sent_lens[index]-1,:sent_lens[index]-1] new_posterior[:sent_lens[index],:sent_lens[index]]=post_val[:sent_lens[index],:sent_lens[index]] new_posteriors.append(new_posterior) else: if is_crf or (not is_crf and not is_posterior): shape=[max_shape]+list(val.shape[1:])+list(val.shape[2:]) new_target=torch.zeros(shape).type_as(val) new_target[:sent_lens[index]]=val[:sent_lens[index]] new_targets.append(new_target) if is_token_att: sentfeats_val=sentfeats_vals[idx] shape=[max_shape]+list(sentfeats_val.shape[1:]) new_sentfeat=torch.zeros(shape).type_as(sentfeats_val) new_sentfeat[:sent_lens[index]]=sentfeats_val[:sent_lens[index]] new_sentfeats.append(new_sentfeat) if is_posterior: bias = 0 # pdb.set_trace() # if max_shape - bias == 0: # pdb.set_trace() # if sent_lens[index] == 1: # pdb.set_trace() post_val=post_vals[idx] shape=[max_shape-bias]+list(post_val.shape[1:]) new_posterior=torch.zeros(shape).type_as(post_val) new_posterior[:sent_lens[index]-bias]=post_val[:sent_lens[index]-bias] new_posteriors.append(new_posterior) # pdb.set_trace() if is_crf: batch[index]._teacher_target=new_targets if hasattr(self.model,'distill_rel') and self.model.distill_rel: batch[index]._teacher_rel_target=new_rel_targets if is_posterior: batch[index]._teacher_posteriors=new_posteriors if is_token_att: batch[index]._teacher_sentfeats=new_sentfeats if (not is_crf and not is_posterior): if hasattr(self.model, 'distill_factorize') and self.model.distill_factorize: batch[index]._teacher_rel_prediction=new_rel_targets batch[index]._teacher_prediction=new_targets if hasattr(batch,'teacher_features'): if is_posterior: try: batch.teacher_features['posteriors']=torch.stack([sentence.get_teacher_posteriors() for sentence in batch],0).cpu() except: pdb.set_trace() # lens=[len(x) for x in batch] # posteriors = batch.teacher_features['posteriors'] # if max(lens) == posteriors.shape[-1]: # pdb.set_trace() if (not is_crf and not is_posterior): batch.teacher_features['distributions'] = torch.stack([sentence.get_teacher_prediction() for sentence in batch],0).cpu() if hasattr(self.model, 'distill_factorize') and self.model.distill_factorize: batch.teacher_features['rel_distributions'] = torch.stack([sentence.get_teacher_rel_prediction() for sentence in batch],0).cpu() if is_crf: batch.teacher_features['topk']=torch.stack([sentence.get_teacher_target() for sentence in batch],0).cpu() if self.model.crf_attention or self.model.tag_type=='dependency': batch.teacher_features['weights']=torch.stack([sentence.get_teacher_weights() for sentence in batch],0).cpu() if hasattr(self.model,'distill_rel') and self.model.distill_rel: batch.teacher_features['topk_rels']=torch.stack([sentence.get_teacher_rel_target() for sentence in batch],0).cpu() return loader def compare_posterior(self, base_path: Path, eval_mini_batch_size: int, max_k=21, min_k=1): self.model.eval() if (base_path / "best-model.pt").exists(): self.model = self.model.load(base_path / "best-model.pt") log.info("Testing using best model ...") elif (base_path / "final-model.pt").exists(): self.model = self.model.load(base_path / "final-model.pt") log.info("Testing using final model ...") loader=ColumnDataLoader(list(self.corpus.test),eval_mini_batch_size, use_bert=self.use_bert,tokenizer=self.bert_tokenizer) loader.assign_tags(self.model.tag_type,self.model.tag_dictionary) XE=torch.zeros(len(range(min_k,max_k))).float().cuda() weighted_XE=torch.zeros(len(range(min_k,max_k))).float().cuda() total_tp=0 total=0 with torch.no_grad(): total_length=0 for batch in loader: total_length+=len(batch) lengths1 = torch.Tensor([len(sentence.tokens) for sentence in batch]) max_len = max(lengths1) mask=self.model.sequence_mask(lengths1, max_len).unsqueeze(-1).cuda().long() lengths1=lengths1.long() batch_range=torch.arange(len(batch)) logits=self.model.forward(batch) forward_var = self.model._forward_alg(logits, lengths1, distill_mode=True) backward_var = self.model._backward_alg(logits, lengths1) forward_backward_score = (forward_var + backward_var) * mask.float() fwbw_probability = F.softmax(forward_backward_score,dim=-1) total_tp+=((fwbw_probability.max(-1)[0]>0.98).type_as(mask)*mask.squeeze(-1)).sum().item() total+=mask.sum().item() # log_prob=torch.log(fwbw_probability+1e-12) # for current_idx,best_k in enumerate(range(min_k,max_k)): # path_score, decode_idx=self.model._viterbi_decode_nbest(logits,mask,best_k) # # tag_distribution = torch.zeros(fwbw_probability.shape).type_as(fwbw_probability) # weighted_tag_distribution = torch.zeros(fwbw_probability.shape).type_as(fwbw_probability) # for k in range(best_k): # for i in range(max_len.long().item()): # tag_distribution[batch_range,i,decode_idx[:,i,k]]+=1 # weighted_tag_distribution[batch_range,i,decode_idx[:,i,k]]+=path_score[:,k] # tag_distribution=tag_distribution/tag_distribution.sum(-1,keepdim=True) # weighted_tag_distribution=weighted_tag_distribution/weighted_tag_distribution.sum(-1,keepdim=True) # XE[current_idx]+=((log_prob*tag_distribution*mask.float()).sum(-1).sum(-1)/(mask.float().sum(-1).sum(-1)*tag_distribution.shape[-1])).sum() # weighted_XE[current_idx]+=((log_prob*weighted_tag_distribution*mask.float()).sum(-1).sum(-1)/(mask.float().sum(-1).sum(-1)*weighted_tag_distribution.shape[-1])).sum() # if best_k==min_k or best_k==max_k-1: # pdb.set_trace() pdb.set_trace() print(total) print(total_tp) # print('XE: ',XE) # print('weighted_XE: ',weighted_XE) # print('total_length: ',total_length) def final_test( self, base_path: Path, eval_mini_batch_size: int, num_workers: int = 8, overall_test: bool = True, quiet_mode: bool = False, nocrf: bool = False, predict_posterior: bool = False, debug: bool = False, keep_embedding: int = -1, sort_data=False, ): log_line(log) self.model.eval() if quiet_mode: #blockPrint() log.disabled=True if (base_path / "best-model.pt").exists(): self.model = self.model.load(base_path / "best-model.pt") log.info("Testing using best model ...") elif (base_path / "final-model.pt").exists(): self.model = self.model.load(base_path / "final-model.pt") log.info("Testing using final model ...") if debug: self.model.debug=True else: self.model.debug=False if nocrf: self.model.use_crf=False if predict_posterior: self.model.predict_posterior=True if keep_embedding>-1: self.model.keep_embedding=keep_embedding for embedding in self.model.embeddings.embeddings: # manually fix the bug for the tokenizer becoming None if hasattr(embedding,'tokenizer') and embedding.tokenizer is None: from transformers import AutoTokenizer name = embedding.name if '_v2doc' in name: name = name.replace('_v2doc','') if '_extdoc' in name: name = name.replace('_extdoc','') embedding.tokenizer = AutoTokenizer.from_pretrained(name, do_lower_case=True) if overall_test: loader=ColumnDataLoader(list(self.corpus.test),eval_mini_batch_size, use_bert=self.use_bert,tokenizer=self.bert_tokenizer, model = self.model, sentence_level_batch = self.sentence_level_batch, sort_data=sort_data) loader.assign_tags(self.model.tag_type,self.model.tag_dictionary) with torch.no_grad(): self.gpu_friendly_assign_embedding([loader]) for x in sorted(loader[0].features.keys()): print(x) test_results, test_loss = self.model.evaluate( loader, out_path=base_path / "test.tsv", embeddings_storage_mode="cpu", ) test_results: Result = test_results log.info(test_results.log_line) log.info(test_results.detailed_results) log_line(log) # if self.model.embedding_selector: # print(sorted(loader[0].features.keys())) # print(self.model.selector) # print(torch.argmax(self.model.selector,-1)) if quiet_mode: enablePrint() if overall_test: if keep_embedding>-1: embedding_name = sorted(loader[0].features.keys())[keep_embedding].split() embedding_name = '_'.join(embedding_name) if 'lm-' in embedding_name.lower(): embedding_name = 'Flair' elif 'bert' in embedding_name.lower(): embedding_name = 'MBERT' elif 'word' in embedding_name.lower(): embedding_name = 'Word' elif 'char' in embedding_name.lower(): embedding_name = 'char' print(embedding_name,end=' ') print('Average', end=' ') print(test_results.main_score, end=' ') # if we are training over multiple datasets, do evaluation for each if type(self.corpus) is MultiCorpus: for subcorpus in self.corpus.corpora: log_line(log) log.info('current corpus: '+subcorpus.name) loader=ColumnDataLoader(list(subcorpus.test),eval_mini_batch_size,use_bert=self.use_bert,tokenizer=self.bert_tokenizer, model = self.model, sentence_level_batch = self.sentence_level_batch, sort_data=sort_data) loader.assign_tags(self.model.tag_type,self.model.tag_dictionary) with torch.no_grad(): self.gpu_friendly_assign_embedding([loader]) current_result, test_loss = self.model.evaluate( loader, out_path=base_path / f"{subcorpus.name}-test.tsv", embeddings_storage_mode="none", ) log.info(current_result.log_line) log.info(current_result.detailed_results) if quiet_mode: if keep_embedding>-1: embedding_name = sorted(loader[0].features.keys())[keep_embedding].split() embedding_name = '_'.join(embedding_name) if 'lm-' in embedding_name.lower() or 'forward' in embedding_name.lower() or 'backward' in embedding_name.lower(): embedding_name = 'Flair' elif 'bert' in embedding_name.lower(): embedding_name = 'MBERT' elif 'word' in embedding_name.lower(): embedding_name = 'Word' elif 'char' in embedding_name.lower(): embedding_name = 'char' print(embedding_name,end=' ') print(subcorpus.name,end=' ') print(current_result.main_score,end=' ') elif type(self.corpus) is ListCorpus: for index,subcorpus in enumerate(self.corpus.test_list): log_line(log) log.info('current corpus: '+self.corpus.targets[index]) loader=ColumnDataLoader(list(subcorpus),eval_mini_batch_size,use_bert=self.use_bert,tokenizer=self.bert_tokenizer, model = self.model, sentence_level_batch = self.sentence_level_batch, sort_data=sort_data) loader.assign_tags(self.model.tag_type,self.model.tag_dictionary) with torch.no_grad(): self.gpu_friendly_assign_embedding([loader]) current_result, test_loss = self.model.evaluate( loader, out_path=base_path / f"{self.corpus.targets[index]}-test.tsv", embeddings_storage_mode="none", ) log.info(current_result.log_line) log.info(current_result.detailed_results) if quiet_mode: if keep_embedding>-1: embedding_name = sorted(loader[0].features.keys())[keep_embedding].split() embedding_name = '_'.join(embedding_name) if 'lm-' in embedding_name.lower() or 'forward' in embedding_name.lower() or 'backward' in embedding_name.lower(): embedding_name = 'Flair' elif 'bert' in embedding_name.lower(): embedding_name = 'MBERT' elif 'word' in embedding_name.lower(): embedding_name = 'Word' elif 'char' in embedding_name.lower(): embedding_name = 'char' print(embedding_name,end=' ') print(self.corpus.targets[index],end=' ') print(current_result.main_score,end=' ') # if self.model.embedding_selector: # print(sorted(loader[0].features.keys())) # print(self.model.selector) # print(torch.argmax(self.model.selector,-1)) if keep_embedding<0: print() if overall_test: # get and return the final test score of best model final_score = test_results.main_score return final_score return 0 def find_learning_rate( self, base_path: Union[Path, str], file_name: str = "learning_rate.tsv", start_learning_rate: float = 1e-7, end_learning_rate: float = 10, iterations: int = 200, mini_batch_size: int = 32, stop_early: bool = False, smoothing_factor: float = 0.98, **kwargs, ) -> Path: best_loss = None moving_avg_loss = 0 # cast string to Path if type(base_path) is str: base_path = Path(base_path) learning_rate_tsv = init_output_file(base_path, file_name) with open(learning_rate_tsv, "a") as f: f.write("ITERATION\tTIMESTAMP\tLEARNING_RATE\tTRAIN_LOSS\n") optimizer = self.optimizer( self.model.parameters(), lr=start_learning_rate, **kwargs ) train_data = self.corpus.train scheduler = ExpAnnealLR(optimizer, end_learning_rate, iterations) model_state = self.model.state_dict() self.model.train() print('Batch Size: ', mini_batch_size) step = 0 while step < iterations: batch_loader=ColumnDataLoader(list(train_data),mini_batch_size,use_bert=self.use_bert,tokenizer=self.bert_tokenizer) # batch_loader = DataLoader( # train_data, batch_size=mini_batch_size, shuffle=True # ) for batch in batch_loader: batch_loader.true_reshuffle() step += 1 # forward pass loss = self.model.forward_loss(batch) # update optimizer and scheduler optimizer.zero_grad() loss.backward() torch.nn.utils.clip_grad_norm_(self.model.parameters(), 5.0) optimizer.step() scheduler.step(step) print(scheduler.get_lr()) learning_rate = scheduler.get_lr()[0] loss_item = loss.item() if step == 1: best_loss = loss_item else: if smoothing_factor > 0: moving_avg_loss = ( smoothing_factor * moving_avg_loss + (1 - smoothing_factor) * loss_item ) loss_item = moving_avg_loss / ( 1 - smoothing_factor ** (step + 1) ) if loss_item < best_loss: best_loss = loss if step > iterations: break if stop_early and (loss_item > 4 * best_loss or torch.isnan(loss)): log_line(log) log.info("loss diverged - stopping early!") step = iterations break with open(str(learning_rate_tsv), "a") as f: f.write( f"{step}\t{datetime.datetime.now():%H:%M:%S}\t{learning_rate}\t{loss_item}\n" ) self.model.load_state_dict(model_state) self.model.to(flair.device) log_line(log) log.info(f"learning rate finder finished - plot {learning_rate_tsv}") log_line(log) return Path(learning_rate_tsv) def get_subtoken_length(self,sentence): return len(self.model.embeddings.embeddings[0].tokenizer.tokenize(sentence.to_tokenized_string()))
42.711572
245
0.690201
9fcf2c88afda2753e3b40a5da1bbc2721be19032
1,264
py
Python
setup.py
oremanj/greenback
b6127448c181b5b5c995f3d7dddc4c16b803ebbf
[ "Apache-2.0", "MIT" ]
45
2020-05-02T16:29:32.000Z
2022-03-29T06:58:11.000Z
setup.py
oremanj/greenback
b6127448c181b5b5c995f3d7dddc4c16b803ebbf
[ "Apache-2.0", "MIT" ]
14
2020-06-29T05:44:50.000Z
2022-01-05T22:18:11.000Z
setup.py
oremanj/greenback
b6127448c181b5b5c995f3d7dddc4c16b803ebbf
[ "Apache-2.0", "MIT" ]
1
2020-07-05T01:22:31.000Z
2020-07-05T01:22:31.000Z
from setuptools import setup, find_packages exec(open("greenback/_version.py", encoding="utf-8").read()) LONG_DESC = open("README.rst", encoding="utf-8").read() setup( name="greenback", version=__version__, description="Reenter an async event loop from synchronous code", url="https://github.com/oremanj/greenback", long_description=LONG_DESC, author="Joshua Oreman", author_email="oremanj@gmail.com", license="MIT -or- Apache License 2.0", packages=find_packages(), include_package_data=True, install_requires=["greenlet != 0.4.17", "sniffio", "outcome"], keywords=["async", "io", "trio", "asyncio"], python_requires=">=3.6", classifiers=[ "License :: OSI Approved :: MIT License", "License :: OSI Approved :: Apache Software License", "Framework :: Trio", "Framework :: AsyncIO", "Operating System :: POSIX :: Linux", "Operating System :: MacOS :: MacOS X", "Operating System :: Microsoft :: Windows", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Development Status :: 4 - Beta", ], )
36.114286
70
0.631329
2aa98255b92dbdf4e3ce21a94b4cb572a469aacf
1,030
py
Python
load_script.py
JacobJustice/SneakerPricePrediction
34598fb1a3235762e1239e14224c7eddfb33f64f
[ "MIT" ]
null
null
null
load_script.py
JacobJustice/SneakerPricePrediction
34598fb1a3235762e1239e14224c7eddfb33f64f
[ "MIT" ]
1
2021-03-11T02:19:12.000Z
2021-03-11T05:44:13.000Z
load_script.py
JacobJustice/SneakerPricePrediction
34598fb1a3235762e1239e14224c7eddfb33f64f
[ "MIT" ]
null
null
null
from predict import normalize_pixels from predict import load_df from pprint import pprint import pandas as pd import argparse import sys import numpy as np import autokeras as ak from tensorflow import keras import joblib # load model loaded_model = keras.models.load_model("./autokeras_out_2/", custom_objects=ak.CUSTOM_OBJECTS) # load validation_set train_df = load_df('./training_aj1.csv') df_mean = train_df['average_sale_price'].mean() df = load_df('./validation_aj1.csv') df = normalize_pixels(df) df_x = df.drop(['average_sale_price','ticker'], axis=1) df_y = df['average_sale_price'] df_y_hat = loaded_model.predict(df_x, verbose=0) df_y_hat = [x[0] for x in df_y_hat] print(df_y_hat) print(list(df_y)) pprint(list(zip(df_y, df_y_hat))) mae = keras.metrics.MeanAbsoluteError() mae.update_state(df_y, df_y_hat) print('using the model mae\t', mae.result().numpy()) df_mean_y_hat = [df_mean for x in df_y] mae.update_state(df_y, df_mean_y_hat) print('guessing the mean mae\t', mae.result().numpy()) print(df_mean)
24.52381
94
0.767961
544236219820264c51cce6b762d3bcc488088940
42,733
py
Python
main.py
PatcailH/BattleX
4b25160297158aa82b7d02a38f3e0a8b542d479c
[ "MIT" ]
1
2022-03-07T20:17:53.000Z
2022-03-07T20:17:53.000Z
main.py
PatcailH/BattleX
4b25160297158aa82b7d02a38f3e0a8b542d479c
[ "MIT" ]
null
null
null
main.py
PatcailH/BattleX
4b25160297158aa82b7d02a38f3e0a8b542d479c
[ "MIT" ]
null
null
null
#!/usr/bin/env python ''' BattleX ''' import pygame # import pygame from pygame import mixer # music import os # operating system import random # random variables import csv # data saving def checkClick(x1,y1,x2,y2): # this method checks if a boxed area is clicked global mouseDown # the mouseDown variable prevents double clicking pos = pygame.mouse.get_pos() if pygame.mouse.get_pressed()[0]: if x1 < pos[0] < x1+x2 and y1 < pos[1] < y1+y2: # python comparison operator is the boss mouseDown = True return True else: mouseDown = False return False # initializing music and pygame mixer.init() pygame.init() SCREEN_WIDTH = 800 SCREEN_HEIGHT = int(SCREEN_WIDTH * 0.8) screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption('Shooter') # set framerate clock = pygame.time.Clock() FPS = 60 # game variables GRAVITY = 0.75 SCROLL_THRESH = 200 ROWS = 16 COLS = 150 TILE_SIZE = SCREEN_HEIGHT // ROWS TILE_TYPES = 21 MAX_LEVELS = 3 screen_scroll = 0 bg_scroll = 0 level = 1 target_level=1 score = 0 killCount = 0 start_game = False start_intro = False bestScores = [0,0,0,0] mode = 1 # player actions moving_left = False moving_right = False shoot = False grenade = False grenade_thrown = False # music and sound pygame.mixer.music.load('audio/HumbleMatch.ogg') pygame.mixer.music.set_volume(0.15) pygame.mixer.music.play(-1, 0.0, 5000) jump_fx = pygame.mixer.Sound('audio/jump.wav') jump_fx.set_volume(0.5) shot_fx = pygame.mixer.Sound('audio/shot.wav') shot_fx.set_volume(0.5) grenade_fx = pygame.mixer.Sound('audio/grenade.wav') grenade_fx.set_volume(0.5) # background images pine1_img = pygame.image.load('img/Background/pine1.png').convert_alpha() pine2_img = pygame.image.load('img/Background/pine2.png').convert_alpha() mountain_img = pygame.image.load('img/Background/mountain.png').convert_alpha() sky_img = pygame.image.load('img/Background/sky_cloud.png').convert_alpha() # store tiles in a list img_list = [] for x in range(TILE_TYPES): img = pygame.image.load(f'img/Tile/{x}.png') img = pygame.transform.scale(img, (TILE_SIZE, TILE_SIZE)) img_list.append(img) # bullet bullet_img = pygame.image.load('img/icons/bullet.png').convert_alpha() # grenade grenade_img = pygame.image.load('img/icons/grenade.png').convert_alpha() # pick up boxes health_box_img = pygame.image.load('img/icons/health_box.png').convert_alpha() ammo_box_img = pygame.image.load('img/icons/ammo_box.png').convert_alpha() grenade_box_img = pygame.image.load('img/icons/grenade_box.png').convert_alpha() item_boxes = { 'Health': health_box_img, 'Ammo' : ammo_box_img, 'Grenade' : grenade_box_img } # colors BG = (144, 201, 120) RED = (255, 0, 0) WHITE = (255, 255, 255) GREEN = (0, 255, 0) BLACK = (0, 0, 0) PINK = (235, 65, 54) # define font - ArcadeClassic font = pygame.font.Font('arcadeclassic.ttf', 30) # size = 30 def arcadeFont(size): return pygame.font.Font('arcadeclassic.ttf', size) # set the score def setScore(s): global bestScores global score global killCount if s == score + 100: killCount +=1 if s == 0: killCount = 0 if s >= bestScores[level-1]: bestScores[level-1] = s score = s def addScore(s): setScore(score+s) # text engine def draw_text(text, font, text_col, x, y): img = font.render(text, True, text_col) screen.blit(img, (x, y)) # rectangle engine def draw_rect(x1,y1,x2,y2,col): pygame.draw.rect(screen, col, (x1, y1, x2, y2), 0) # fill in background def draw_bg(): screen.fill(BG) width = sky_img.get_width() for x in range(5): screen.blit(sky_img, ((x * width) - bg_scroll * 0.5, 0)) screen.blit(mountain_img, ((x * width) - bg_scroll * 0.6, SCREEN_HEIGHT - mountain_img.get_height() - 300)) screen.blit(pine1_img, ((x * width) - bg_scroll * 0.7, SCREEN_HEIGHT - pine1_img.get_height() - 150)) screen.blit(pine2_img, ((x * width) - bg_scroll * 0.8, SCREEN_HEIGHT - pine2_img.get_height())) # function to reset level def reset_level(): enemy_group.empty() bullet_group.empty() grenade_group.empty() explosion_group.empty() item_box_group.empty() decoration_group.empty() water_group.empty() exit_group.empty() # create empty tile list data = [] for row in range(ROWS): r = [-1] * COLS data.append(r) return data # the Soldier class class Soldier(pygame.sprite.Sprite): def __init__(self, char_type, x, y, scale, speed, ammo, grenades): pygame.sprite.Sprite.__init__(self) self.alive = True self.char_type = char_type self.speed = speed self.ammo = ammo self.start_ammo = ammo self.shoot_cooldown = 100 self.grenades = grenades self.health = 30 if char_type == "player": self.health = 40 if char_type == "enemy" and level == 3: self.health = 1000 self.grenades = 1e9 ##effectively unlimited self.ammo = 1e9 ##effectively unlimited self.max_health = self.health self.direction = 1 self.vel_y = 0 self.jump = False self.in_air = True self.flip = False self.animation_list = [] self.frame_index = 0 self.action = 0 self.update_time = pygame.time.get_ticks() # ai specific variables self.move_counter = 0 self.vision = pygame.Rect(0, 0, 150, 20) self.idling = False self.idling_counter = 0 # load all images for the players animation_types = ['Idle', 'Run', 'Jump', 'Death'] for animation in animation_types: # reset temporary list of images temp_list = [] # count number of files in the folder num_of_frames = len(os.listdir(f'img/{self.char_type}/{animation}')) for i in range(num_of_frames): img = pygame.image.load(f'img/{self.char_type}/{animation}/{i}.png').convert_alpha() img = pygame.transform.scale(img, (int(img.get_width() * scale), int(img.get_height() * scale))) temp_list.append(img) self.animation_list.append(temp_list) # animation list self.image = self.animation_list[self.action][self.frame_index] self.rect = self.image.get_rect() self.rect.center = (x, y) self.width = self.image.get_width() self.height = self.image.get_height() # update itself def update(self): self.update_animation() # animation self.check_alive() # check if it is alive # update cooldown if self.shoot_cooldown > 0: self.shoot_cooldown -= 1 def move(self, moving_left, moving_right): # movement function # reset movement variables screen_scroll = 0 dx = 0 # change of x dy = 0 # change of y # assign movement variables if moving left or right if moving_left: dx = -self.speed self.flip = True self.direction = -1 if moving_right: dx = self.speed self.flip = False self.direction = 1 # jump if self.jump == True and self.in_air == False: self.vel_y = -11 if pygame.sprite.spritecollide(self, water_group, False): # if in water, then swimming self.vel_y = -11/3 self.jump = False self.in_air = True # apply gravity self.vel_y += GRAVITY if pygame.sprite.spritecollide(self, water_group, False): # gravity is less in water self.vel_y -= GRAVITY*2/3 if self.vel_y > 10: self.vel_y dy += self.vel_y # check for collision - COLLISION DETECTION for tile in world.obstacle_list: # compares to the tile list # check collision in the x direction if tile[1].colliderect(self.rect.x + dx, self.rect.y, self.width, self.height): dx = 0 # reset dx to 0 # if the ai has hit a wall then make it turn around if self.char_type == 'enemy': self.direction *= -1 self.move_counter = 0 # check for collision in the y direction if tile[1].colliderect(self.rect.x, self.rect.y + dy, self.width, self.height): # check if below the ground, i.e. jumping if self.vel_y < 0: self.vel_y = 0 dy = tile[1].bottom - self.rect.top # check if above the ground, i.e. falling elif self.vel_y >= 0: self.vel_y = 0 self.in_air = False dy = tile[1].top - self.rect.bottom # check for collision with water, then it is now swimming if pygame.sprite.spritecollide(self, water_group, False): self.in_air=False # check for collision with level end level_complete = False if (pygame.sprite.spritecollide(self, exit_group, False) and (killCount >= ([8,12,0,0][level-1]) or mode != 2)) or (score >= 999 and level == 3): level_complete = True # check if below the map if self.rect.bottom > SCREEN_HEIGHT: self.health = 0 # then die # if it goes off the screen if self.char_type == 'player': if self.rect.left + dx < 0 or self.rect.right + dx > SCREEN_WIDTH: dx = 0 # update the player position self.rect.x += dx self.rect.y += dy # update scrolling level based on player position if self.char_type == 'player': if (self.rect.right > SCREEN_WIDTH - SCROLL_THRESH and bg_scroll < (world.level_length * TILE_SIZE) - SCREEN_WIDTH) \ or (self.rect.left < SCROLL_THRESH and bg_scroll > abs(dx)): self.rect.x -= dx screen_scroll = -dx return screen_scroll, level_complete def shoot(self): # shooting if self.shoot_cooldown == 0 and self.ammo > 0 and (self.char_type=="enemy" or mode != 3 or level == 3): self.shoot_cooldown = 10 # cooldown is 1/6 of a second bullet = Bullet(self.rect.centerx + (0.75 * self.rect.size[0] * self.direction), self.rect.centery, self.direction) bullet_group.add(bullet) # reduce ammo self.ammo -= 1 shot_fx.play() def ai(self): # AI if self.alive and player.alive: if self.idling == False and random.randint(1, 200) <= 1: # randomly, it may idle self.update_action(0) # 0: idle self.idling = True self.idling_counter = 50 # check if the ai in near the player, or if it is in level 3 if self.vision.colliderect(player.rect) or (level == 3 and random.randint(1, 10) <= 1): # stop running and face the player self.update_action(0) # 0: idle # shoot, or possibly grenade depending on the level if (random.randint(1,40)==1 or (random.randint(1,10)==1 and level == 3)) and enemy.grenades > 0 and level > 1: grenade = Grenade(self.rect.centerx + (0.5 * self.rect.size[0] * self.direction), \ self.rect.top, self.direction) grenade_group.add(grenade) # reduce grenades self.grenades -= 1 else: self.shoot() else: if self.idling == False: # if it is not idling, then it moves if self.direction == 1: ai_moving_right = True else: ai_moving_right = False ai_moving_left = not ai_moving_right self.move(ai_moving_left, ai_moving_right) self.update_action(1) # 1: run self.move_counter += 1 # update ai vision as the enemy moves self.vision.center = (self.rect.centerx + 75 * self.direction, self.rect.centery) if self.move_counter > TILE_SIZE: # if it moves enough, it might switch directions self.direction *= -1 self.move_counter *= -1 else: # if it is idling, it does nothing self.idling_counter -= 1 if self.idling_counter <= 0: self.idling = False # scroll self.rect.x += screen_scroll def update_animation(self): # animated sprites # update animation ANIMATION_COOLDOWN = 100 # update image depending on current frame self.image = self.animation_list[self.action][self.frame_index] # has a list of animations # check if enough time has passed since the last update if pygame.time.get_ticks() - self.update_time > ANIMATION_COOLDOWN: self.update_time = pygame.time.get_ticks() self.frame_index += 1 # if the animation has run out the reset back to the start if self.frame_index >= len(self.animation_list[self.action]): if self.action == 3: self.frame_index = len(self.animation_list[self.action]) - 1 else: self.frame_index = 0 def update_action(self, new_action): # does a new action # check if the new action is different to the previous one if new_action != self.action: self.action = new_action # update the animation settings self.frame_index = 0 self.update_time = pygame.time.get_ticks() def check_alive(self): # check if it is alive if self.health <= 0: if self.alive == True and self.char_type == "enemy": # if you kill an enemy, you gain points! if level == 3: addScore(999) else: addScore(100) self.health = 0 self.speed = 0 self.alive = False self.update_action(3) def draw(self): # drawing a soldier screen.blit(pygame.transform.flip(self.image, self.flip, False), self.rect) class World(): # the World class def __init__(self): self.obstacle_list = [] def process_data(self, data): # process through csv data self.level_length = len(data[0]) # iterate through each value in level data file for y, row in enumerate(data): for x, tile in enumerate(row): if tile >= 0: img = img_list[tile] img_rect = img.get_rect() img_rect.x = x * TILE_SIZE # positioning img_rect.y = y * TILE_SIZE tile_data = (img, img_rect) if tile >= 0 and tile <= 8: # normal tile or box self.obstacle_list.append(tile_data) elif tile >= 9 and tile <= 10: # water water = Water(img, x * TILE_SIZE, y * TILE_SIZE) water_group.add(water) elif tile >= 11 and tile <= 14: # random decorative features decoration = Decoration(img, x * TILE_SIZE, y * TILE_SIZE) decoration_group.add(decoration) elif tile == 15: # create the main player ammo = 10 grenades = 2 if level == 3: # for the final boss ammo = 50 grenades = 0 player = Soldier('player', x * TILE_SIZE, y * TILE_SIZE, 1.65, 5, ammo, grenades) health_bar = HealthBar(10, 10, player.health, player.health) # need a health bar elif tile == 16: # create the enemies scale = 1.65 if level == 3: # for the final boss scale = 4 enemy = Soldier('enemy', x * TILE_SIZE, y * TILE_SIZE, scale, 2, 10, 5) enemy_group.add(enemy) elif tile == 17: # create ammo loot item_box = ItemBox('Ammo', x * TILE_SIZE, y * TILE_SIZE) item_box_group.add(item_box) elif tile == 18: # create grenade loot item_box = ItemBox('Grenade', x * TILE_SIZE, y * TILE_SIZE) item_box_group.add(item_box) elif tile == 19: # create health loot item_box = ItemBox('Health', x * TILE_SIZE, y * TILE_SIZE) item_box_group.add(item_box) elif tile == 20: # create the level goal! exit = Exit(img, x * TILE_SIZE, y * TILE_SIZE) exit_group.add(exit) return player, health_bar def draw(self): # drawing the tiles for tile in self.obstacle_list: tile[1][0] += screen_scroll # the screen scroll is used to translate the tile positions screen.blit(tile[0], tile[1]) # random decorative stuff class Decoration(pygame.sprite.Sprite): def __init__(self, img, x, y): pygame.sprite.Sprite.__init__(self) self.image = img self.rect = self.image.get_rect() self.rect.midtop = (x + TILE_SIZE // 2, y + (TILE_SIZE - self.image.get_height())) def update(self): # it scrolls self.rect.x += screen_scroll # water, you can swim, or you can drown! class Water(pygame.sprite.Sprite): def __init__(self, img, x, y): pygame.sprite.Sprite.__init__(self) self.image = img self.rect = self.image.get_rect() self.rect.midtop = (x + TILE_SIZE // 2, y + (TILE_SIZE - self.image.get_height())) def update(self): # and it scrolls self.rect.x += screen_scroll # complete the level class Exit(pygame.sprite.Sprite): def __init__(self, img, x, y): pygame.sprite.Sprite.__init__(self) self.image = img self.rect = self.image.get_rect() self.rect.midtop = (x + TILE_SIZE // 2, y + (TILE_SIZE - self.image.get_height())) def update(self): # and it scrolls self.rect.x += screen_scroll # The ItemBox class is used to gain items and loot. They also score 50 points class ItemBox(pygame.sprite.Sprite): def __init__(self, item_type, x, y): pygame.sprite.Sprite.__init__(self) self.item_type = item_type self.image = item_boxes[self.item_type] self.rect = self.image.get_rect() self.rect.midtop = (x + TILE_SIZE // 2, y + (TILE_SIZE - self.image.get_height())) def update(self): # it scrolls # scroll self.rect.x += screen_scroll # check if the player has picked up the box if pygame.sprite.collide_rect(self, player): # check what kind of box it was if self.item_type == 'Health': # Health - Gain 12 / 40 HP player.health += 12 if player.health > player.max_health: player.health = player.max_health addScore(50) # +50 pts elif self.item_type == 'Ammo': # Ammo - Gain 5 bullets player.ammo += 5 addScore(50) # +50 pts elif self.item_type == 'Grenade': # Grenade - Gain 1 grenade player.grenades += 1 addScore(50) # +50 pts # remove the item box self.kill() # Health Bar of player and boss class HealthBar(): def __init__(self, x, y, health, max_health): self.x = x self.y = y self.health = health self.max_health = max_health def draw(self, health): # drawing the health bar # update with new health self.health = health # calculate health ratio ratio = self.health / self.max_health pygame.draw.rect(screen, BLACK, (self.x - 2, self.y - 2, 154, 24)) pygame.draw.rect(screen, RED, (self.x, self.y, 150, 20)) pygame.draw.rect(screen, GREEN, (self.x, self.y, 150 * ratio, 20)) def drawBossBar(self, health): # drawing the boss bar global level_complete ratio = health / 1000 if (health <= 0): # if the boss is dead, the level is completed level_complete=True scale=3 # the boss bar is bigger pygame.draw.rect(screen, BLACK, (self.x - 2 + 300, self.y - 2, 150*scale+4, 24)) pygame.draw.rect(screen, RED, (self.x + 300, self.y, 150*scale, 20)) pygame.draw.rect(screen, GREEN, (self.x + 300, self.y, 150 * ratio*scale, 20)) draw_text('BOSS ', arcadeFont(30), BLACK, 500, 5) # the boss gets the boss label # The bullet can hit enemies or you! class Bullet(pygame.sprite.Sprite): def __init__(self, x, y, direction): pygame.sprite.Sprite.__init__(self) self.speed = 10 self.image = bullet_img self.rect = self.image.get_rect() self.rect.center = (x, y) self.direction = direction self.yvel = 0 def update(self): # projectile motion # move bullet self.rect.x += (self.direction * self.speed) + screen_scroll # x movement self.yvel += 0.2 # gravity affected self.rect.y += self.yvel # y movement # removes the bullet if it goes off screen if self.rect.right < 0 or self.rect.left > SCREEN_WIDTH: self.kill() # removes the bullet if it collides with the world for tile in world.obstacle_list: if tile[1].colliderect(self.rect): self.kill() # removes the bullet if it hits a player or enemy if pygame.sprite.spritecollide(player, bullet_group, False): if player.alive: player.health -= 5 # players take 5 health points of damage self.kill() for enemy in enemy_group: if pygame.sprite.spritecollide(enemy, bullet_group, False): if enemy.alive: enemy.health -= 25 # the boss takes 25 health points of damage if (level != 3): enemy.health += 12.5 # but normal enemies only take 12.5 points of damage self.kill() # the grenade has an explosion class Grenade(pygame.sprite.Sprite): def __init__(self, x, y, direction): pygame.sprite.Sprite.__init__(self) self.timer = 100 # fuse is 1.667 seconds self.vel_y = -11 # thrown up self.speed = 7 self.image = grenade_img self.rect = self.image.get_rect() self.rect.center = (x, y) self.width = self.image.get_width() self.height = self.image.get_height() self.direction = direction # projectile of the grenade def update(self): self.vel_y += GRAVITY # gravity affected dx = self.direction * self.speed # change x position dy = self.vel_y # change y position # check for collision with the world for tile in world.obstacle_list: # if it hit a wall, it bounces back if tile[1].colliderect(self.rect.x + dx, self.rect.y, self.width, self.height): self.direction *= -1 dx = self.direction * self.speed # check for collision in the y direction if tile[1].colliderect(self.rect.x, self.rect.y + dy, self.width, self.height): self.speed = 0 # check if below the ground, it gets knocked down if self.vel_y < 0: self.vel_y = 0 dy = tile[1].bottom - self.rect.top # check if above the ground, it bounces back up elif self.vel_y >= 0: self.vel_y = 0 dy = tile[1].top - self.rect.bottom # change grenade position self.rect.x += dx + screen_scroll self.rect.y += dy # countdown timer self.timer -= 1 if self.timer <= 0: # when the grenade goes off self.kill() grenade_fx.play() explosion = Explosion(self.rect.x, self.rect.y, 2) # it explodes explosion_group.add(explosion) # do damage to anyone that is nearby player.health -= 150000/((self.rect.centerx - player.rect.centerx)**2+(self.rect.centery - player.rect.centery)**2) if level == 3: # take double damage on level 3 for players only player.health -= 150000 / ((self.rect.centerx - player.rect.centerx) ** 2 + ( self.rect.centery - player.rect.centery) ** 2) for enemy in enemy_group: # enemies also take damage if level != 3: # the boss is immune to explosions enemy.health -= 150000/((self.rect.centerx - enemy.rect.centerx)**2+(self.rect.centery - enemy.rect.centery)**2) # explosions are everyone's favorite part class Explosion(pygame.sprite.Sprite): def __init__(self, x, y, scale): pygame.sprite.Sprite.__init__(self) self.images = [] for num in range(1, 6): # makes an animation list img = pygame.image.load(f'img/explosion/exp{num}.png').convert_alpha() img = pygame.transform.scale(img, (int(img.get_width() * scale), int(img.get_height() * scale))) self.images.append(img) self.frame_index = 0 self.image = self.images[self.frame_index] # cycles through the animated list self.rect = self.image.get_rect() self.rect.center = (x, y) self.counter = 0 def update(self): # scrolling explosion self.rect.x += screen_scroll EXPLOSION_SPEED = 4 # update explosion amimation, roughly once per 1/15th of a second self.counter += 1 if self.counter >= EXPLOSION_SPEED: self.counter = 0 self.frame_index += 1 # if the animation is complete then delete the explosion if self.frame_index >= len(self.images): self.kill() else: self.image = self.images[self.frame_index] # update animation # screen fading class ScreenFade(): def __init__(self, direction, colour, speed): self.direction = direction self.colour = colour self.speed = speed self.fade_counter = 0 def fade(self): fade_complete = False self.fade_counter += self.speed if self.direction == 1: # whole screen fade, middle fade out pygame.draw.rect(screen, self.colour, (0 - self.fade_counter, 0, SCREEN_WIDTH // 2, SCREEN_HEIGHT)) pygame.draw.rect(screen, self.colour, (SCREEN_WIDTH // 2 + self.fade_counter, 0, SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.draw.rect(screen, self.colour, (0, 0 - self.fade_counter, SCREEN_WIDTH, SCREEN_HEIGHT // 2)) pygame.draw.rect(screen, self.colour, (0, SCREEN_HEIGHT // 2 + self.fade_counter, SCREEN_WIDTH, SCREEN_HEIGHT)) if self.direction == 2: # vertical screen fade down, such as death pygame.draw.rect(screen, self.colour, (0, 0, SCREEN_WIDTH, 0 + self.fade_counter)) if self.fade_counter >= SCREEN_WIDTH: fade_complete = True return fade_complete # returns true if fading is complete # create screen fades intro_fade = ScreenFade(1, BLACK, 4) # opening level death_fade = ScreenFade(2, BLACK, 10) # also used for level complete # create sprite groups, these groups are just list of objects enemy_group = pygame.sprite.Group() bullet_group = pygame.sprite.Group() grenade_group = pygame.sprite.Group() explosion_group = pygame.sprite.Group() item_box_group = pygame.sprite.Group() decoration_group = pygame.sprite.Group() water_group = pygame.sprite.Group() exit_group = pygame.sprite.Group() # create empty tile list world_data = [] for row in range(ROWS): # traverses through the rows r = [-1] * COLS world_data.append(r) # load in level data and create world with open(f'level{level}_data.csv', newline='') as csvfile: # level loading is awesome! reader = csv.reader(csvfile, delimiter=',') for x, row in enumerate(reader): for y, tile in enumerate(row): world_data[x][y] = int(tile) world = World() # create a new world player, health_bar = world.process_data(world_data) run = True # run is the program running page = 1 # page for menu selection mouseDown = False # this is for button pressing while run: clock.tick(FPS) # 60 frames per second if start_game == False and page == 1: # start screen menu # draw menu screen.fill(BG) # background for menu # draw the START button draw_rect(250,200,300,100,WHITE) draw_rect(260, 210, 280, 80, BLACK) draw_text("START", arcadeFont(80), WHITE, 295, 210) if checkClick(250,200,300,100): page = 4 # draw the INSTRUCTIONS button draw_rect(150, 320, 500, 100, WHITE) draw_rect(160, 330, 480, 80, BLACK) draw_text("INSTRUCTIONS", arcadeFont(60), WHITE, 200, 340) if checkClick(150, 320, 500, 100): page = 2 # draw the LEADERBOARD button draw_rect(150, 440, 500, 100, WHITE) draw_rect(160, 450, 480, 80, BLACK) draw_text("LEADERBOARD", arcadeFont(60), WHITE, 220, 460) if checkClick(150, 440, 500, 100): page = 3 # draw the QUIT button draw_rect(250, 560, 300, 80, WHITE) draw_rect(260, 570, 280, 60, BLACK) draw_text("QUIT", arcadeFont(60), WHITE, 330, 570) # draw the title if mouseDown == False and checkClick(250, 560, 300, 80): run = False draw_text("BattleX",arcadeFont(150),RED,120,50) if start_game == False and page == 2: # page 2 is the How to Play screen.fill(BG) # add the back button draw_rect(30, 30, 200, 100, WHITE) draw_rect(40, 40, 180, 80, BLACK) draw_text("BACK", arcadeFont(60), WHITE, 60, 50) if checkClick(30, 30, 200, 100): page = 1 draw_text("You are a soldier in BattleX", arcadeFont(40), BLACK, 100, 150) draw_text("Your goal is to kill the enemy", arcadeFont(40), BLACK, 100, 190) draw_text("And make it to the end of level", arcadeFont(40), BLACK, 100, 230) draw_text("Used WASD or Arrow Keys to move", arcadeFont(40), BLACK, 100, 310) draw_text("Spacebar or Left Click to Shoot", arcadeFont(40), BLACK, 100, 350) draw_text("Q E or Right Click to Grenade", arcadeFont(40), BLACK, 100, 390) draw_text("Have Fun!!! Credit goes to", arcadeFont(40), BLACK, 100, 470) draw_text("Ryan Elyakoubi Patrick Hoang", arcadeFont(40), BLACK, 100, 510) draw_text("Afnan Habib and Samet Cimen", arcadeFont(40), BLACK, 100, 550) if start_game == False and page == 3: # Page 3 is the leaderboard screen.fill(BG) # add the Back button draw_rect(30, 30, 200, 100, WHITE) draw_rect(40, 40, 180, 80, BLACK) draw_text("BACK", arcadeFont(60), WHITE, 60, 50) if checkClick(30, 30, 200, 100): page = 1 draw_text("Leaderboard", arcadeFont(60), BLACK, 200, 150) draw_text("Level 1 Highscore is " + bestScores[0].__str__(), arcadeFont(60), BLACK, 30, 250) draw_text("Level 2 Highscore is " + bestScores[1].__str__(), arcadeFont(60), BLACK, 30, 310) draw_text("Level 3 Highscore is " + bestScores[2].__str__(), arcadeFont(60), BLACK, 30, 370) if start_game == False and page == 4: # page 4 is the level select page screen.fill(BG) # add the back button draw_rect(30, 30, 200, 100, WHITE) draw_rect(40, 40, 180, 80, BLACK) draw_text("BACK", arcadeFont(60), WHITE, 60, 50) if checkClick(30, 30, 200, 100): page = 1 # what level is it? draw_rect(150, 200, 500, 100, WHITE) draw_rect(160, 210, 480, 80, BLACK) draw_text("Level " + level.__str__(), arcadeFont(80), WHITE, 250, 210) # level cycling if mouseDown == False and checkClick(150, 200, 500, 100): level += 1 if (level == 4): level = 1 # what mode is it? draw_rect(150, 350, 500, 100, WHITE) draw_rect(160, 360, 480, 80, BLACK) if mode == 1: # normal draw_text("Normal", arcadeFont(80), WHITE, 250, 360) draw_text("Normal Mode is the basic mode", arcadeFont(40), BLACK, 100, 470) if mode == 2: # serial draw_text("Serial", arcadeFont(80), WHITE, 250, 360) draw_text("You must kill all enemies", arcadeFont(40), BLACK, 100, 470) if mode == 3: # pacifist draw_text("Pacifist", arcadeFont(80), WHITE, 250, 360) draw_text("You can only fight on lvl 3", arcadeFont(40), BLACK, 100, 470) if mouseDown == False and checkClick(150, 350, 500, 100): # mode cycling mode += 1 if (mode == 4): mode = 1 # draw the play button draw_rect(250, 520, 300, 100, WHITE) draw_rect(260, 530, 280, 80, BLACK) draw_text("PLAY", arcadeFont(80), WHITE, 295, 530) if checkClick(250, 520, 300, 100): # play the game start_game = True start_intro = True target_level=level level=1 if start_game == False and page == 5: # page 5 is the winner page screen.fill(BLACK) draw_text("Game Beaten!", arcadeFont(80), GREEN, 150, 210) # you won the game draw_text("You defeated the final boss", arcadeFont(40), WHITE, 100, 370) draw_text("Thank you for playing", arcadeFont(40), WHITE, 100, 420) draw_rect(250, 520, 300, 100, WHITE) draw_rect(260, 530, 280, 80, BLACK) draw_text("MENU", arcadeFont(80), WHITE, 295, 530) # go to menu if checkClick(250, 520, 300, 100): page = 1 if start_game == True: # if the game is running # update background draw_bg() # draw the world world.draw() # update player health health_bar.draw(player.health) # show the ammo draw_text('AMMO', arcadeFont(30), WHITE, 10, 35) for x in range(player.ammo): screen.blit(bullet_img, (90 + (x * 10), 45)) # show the grenades draw_text('GRENADES', arcadeFont(30), WHITE, 10, 60) for x in range(player.grenades): screen.blit(grenade_img, (155 + (x * 15), 70)) # show the score draw_text('SCORE ' + score.__str__(), arcadeFont(30), WHITE, 10, 85) # update the player player.update() player.draw() for enemy in enemy_group: # update the enemies, such as AI enemy.ai() enemy.update() enemy.draw() if level == 3: # draw a boss bar is needed health_bar.drawBossBar(enemy.health) # update plus draw all of these extra groups bullet_group.update() grenade_group.update() explosion_group.update() item_box_group.update() decoration_group.update() water_group.update() exit_group.update() bullet_group.draw(screen) grenade_group.draw(screen) explosion_group.draw(screen) item_box_group.draw(screen) decoration_group.draw(screen) water_group.draw(screen) exit_group.draw(screen) # intro fading animation if start_intro == True: if intro_fade.fade(): start_intro = False intro_fade.fade_counter = 0 # player actions if player.alive and not (level == 3 and level_complete): # shooting if shoot: player.shoot() # grenades elif grenade and grenade_thrown == False and player.grenades > 0 and (mode != 3): grenade = Grenade(player.rect.centerx + (0.5 * player.rect.size[0] * player.direction), \ player.rect.top, player.direction) grenade_group.add(grenade) # reduce grenades player.grenades -= 1 grenade_thrown = True if player.in_air: player.update_action(2) # 2: jumping elif moving_left or moving_right: player.update_action(1) # 1: running else: player.update_action(0) # 0: idle screen_scroll, level_complete = player.move(moving_left, moving_right) bg_scroll -= screen_scroll # check if player has completed the level if level_complete or target_level > level: start_intro = True level_complete = False setScore(0) # reset score level += 1 # increment the level bg_scroll = 0 if True: # ignore the If True world_data = reset_level() if level <= MAX_LEVELS: # load in the level data with open(f'level{level}_data.csv', newline='') as csvfile: reader = csv.reader(csvfile, delimiter=',') for x, row in enumerate(reader): for y, tile in enumerate(row): world_data[x][y] = int(tile) world = World() player, health_bar = world.process_data(world_data) else: # this is used if player is either dead OR completed the game screen_scroll = 0 if death_fade.fade(): if player.alive: # if completed the game page = 5 setScore(0) level = 1 # reset the stuff bg_scroll = 0 if True: world_data = reset_level() if level <= MAX_LEVELS: # load in level data and create world with open(f'level{level}_data.csv', newline='') as csvfile: reader = csv.reader(csvfile, delimiter=',') for x, row in enumerate(reader): for y, tile in enumerate(row): world_data[x][y] = int(tile) world = World() player, health_bar = world.process_data(world_data) start_game=False else: # otherwise, the player must be dead draw_text("You died!", arcadeFont(100), RED, 180, 150) # death screen draw_rect(150, 320, 500, 100, WHITE) draw_rect(160, 330, 480, 80, BLACK) draw_text("Restart", arcadeFont(60), WHITE, 290, 340) # restart button if checkClick(150, 320, 500, 100): # restarts the level death_fade.fade_counter = 0 start_intro = True bg_scroll = 0 setScore(0) world_data = reset_level() # reload the level when restarting with open(f'level{level}_data.csv', newline='') as csvfile: reader = csv.reader(csvfile, delimiter=',') for x, row in enumerate(reader): for y, tile in enumerate(row): world_data[x][y] = int(tile) world = World() player, health_bar = world.process_data(world_data) for event in pygame.event.get(): # possible events # quit game if event.type == pygame.QUIT: run = False # stop running # keyboard pressing if event.type == pygame.KEYDOWN: if event.key == pygame.K_a or event.key == pygame.K_LEFT: # A or Left = Move Left moving_left = True if event.key == pygame.K_d or event.key == pygame.K_RIGHT: # D or Right = Move Right moving_right = True if event.key == pygame.K_SPACE: # Spacebar does shooting shoot = True if event.key == pygame.K_q or event.key == pygame.K_e: # Q or E for grenades grenade = True if (event.key == pygame.K_w or event.key == pygame.K_UP) and player.alive: # W or Up is jumping, can't jump if you are dead player.jump = True jump_fx.play() if event.key == pygame.K_ESCAPE: # escape = Leave the game - QUIT run = False if event.type == pygame.MOUSEBUTTONDOWN: # mouse press if event.button == 1: # Left click for shoot shoot = True if event.button == 3: # Right click for grenade grenade = True if event.type == pygame.MOUSEBUTTONUP: # mouse release if event.button == 1: # Left click for shoot shoot = False if event.button == 3: # Right click for grenade grenade = False grenade_thrown = False # keyboard released, same as above if event.type == pygame.KEYUP: if event.key == pygame.K_a or event.key == pygame.K_LEFT: moving_left = False if event.key == pygame.K_d or event.key == pygame.K_RIGHT: moving_right = False if event.key == pygame.K_SPACE: shoot = False if event.key == pygame.K_q or event.key == pygame.K_e: grenade = False grenade_thrown = False pygame.display.update() # update the display pygame.quit() # after the program is finished, QUIT the game and exit!
39.641002
153
0.564084
180dfa1133cfae5577a70fbbf7ccf8f02ca65aef
161
py
Python
datetime_practise.py
Ahsanul08/IPython-shortsSnippets
5de76226aff2400508468f0a050b0e5cc7a77801
[ "Apache-2.0" ]
null
null
null
datetime_practise.py
Ahsanul08/IPython-shortsSnippets
5de76226aff2400508468f0a050b0e5cc7a77801
[ "Apache-2.0" ]
null
null
null
datetime_practise.py
Ahsanul08/IPython-shortsSnippets
5de76226aff2400508468f0a050b0e5cc7a77801
[ "Apache-2.0" ]
null
null
null
from datetime import datetime print "Today is {dt:%d-%m-%Y} and now it is {dt:%H}'o clock with {dt:%M} minutes and {dt:%S} seconds".format(dt = datetime.now())
40.25
129
0.670807
a7a96b85d1a4966c28e6d5285b27a3113cbb71b0
1,474
py
Python
setup-cx_freeze.py
Spferical/Conway-s-Game-of-Pong
ef89e4caaeb512ae6b033d2878349c51a30c2ca5
[ "MIT" ]
1
2018-06-12T10:58:24.000Z
2018-06-12T10:58:24.000Z
setup-cx_freeze.py
Spferical/Conway-s-Game-of-Pong
ef89e4caaeb512ae6b033d2878349c51a30c2ca5
[ "MIT" ]
null
null
null
setup-cx_freeze.py
Spferical/Conway-s-Game-of-Pong
ef89e4caaeb512ae6b033d2878349c51a30c2ca5
[ "MIT" ]
null
null
null
import sys from cx_Freeze import setup, Executable from config import VERSION # Dependencies are automatically detected, but it might need fine tuning. build_exe_options = {"packages": [], "excludes": [], "compressed": True, "include_files": [("README.txt", "README.txt"), ("README-SDL.txt", "README-SDL.txt"), ("arial12x12.png", "arial12x12.png"), ("LIBTCOD-LICENSE.txt", "LIBTCOD_LICENSE.txt")], } # GUI applications require a different base on Windows (the default is for a # console application). base = None if sys.platform == "win32": base = "Win32GUI" windows_libs = [("SDL.dll", "SDL.dll"), ("libtcod-gui-mingw.dll", "libtcod-gui-mingw.dll"), ("libtcod-mingw.dll", "libtcod-mingw.dll")] build_exe_options["include_files"].extend(windows_libs) elif sys.platform.startswith("linux"): linux_libs = [("libSDL.so", "libSDL.so"), ("libtcod.so", "libtcod.so")] build_exe_options["include_files"].extend(linux_libs) else: print "add options for " + sys.platform; sys.exit() setup(name="Conway's Game of Pong", version=VERSION, description="A mashup of Pong and Conway's Game of Life", options={"build_exe": build_exe_options}, executables=[Executable("main.py", base=base)])
38.789474
76
0.580733
d1a99ed8b72c442be8a1d4c419edc68d97b2022e
1,383
py
Python
.github/check-status/check-status.py
bl0x/symbiflow-arch-defs
5fa5e71526e443d589971f2649d8b189df982d72
[ "ISC" ]
null
null
null
.github/check-status/check-status.py
bl0x/symbiflow-arch-defs
5fa5e71526e443d589971f2649d8b189df982d72
[ "ISC" ]
118
2022-02-20T15:05:04.000Z
2022-03-31T18:26:13.000Z
.github/check-status/check-status.py
bl0x/symbiflow-arch-defs
5fa5e71526e443d589971f2649d8b189df982d72
[ "ISC" ]
null
null
null
#!/usr/bin/env python3 import re from os import environ, path from github import Github from stdm import get_latest_artifact_url gh_ref = environ['GITHUB_REPOSITORY'] gh_sha = environ['INPUT_SHA'] MAIN_CI = "Architecture Definitions" print('Getting status of %s @ %s...' % (gh_ref, gh_sha)) status = Github(environ['INPUT_TOKEN'] ).get_repo(gh_ref).get_commit(sha=gh_sha).get_combined_status() for item in status.statuses: print('· %s: %s' % (item.context, item.state)) if status.state != 'success': print('Status not successful. Skipping...') exit(1) if not any([item.context == MAIN_CI for item in status.statuses]): print('Main CI has not completed. Skipping...') exit(1) artifacts, _ = get_latest_artifact_url() PACKAGE_RE = re.compile("symbiflow-arch-defs-([a-zA-Z0-9_-]+)-([a-z0-9])") for artifact in artifacts: name = artifact["name"].split(".")[0] url = artifact["url"] m = PACKAGE_RE.match(name) assert m, "Package name not recognized! {}".format(name) package_name = m.group(1) if package_name == "install": file_name = "symbiflow-toolchain-latest" elif package_name == "benchmarks": file_name = "symbiflow-benchmarks-latest" else: file_name = "symbiflow-{}-latest".format(package_name) with open(path.join("install", file_name), "w") as f: f.write(url)
27.117647
79
0.666667
4ac1a5b1399c0c8762bf850010cebddee047cfb0
6,509
py
Python
supervised_path_based.py
kwashio/filling_missing_path
b5ab85c9d1e42ee47857299df3fcd79b6127e1fe
[ "Apache-2.0" ]
null
null
null
supervised_path_based.py
kwashio/filling_missing_path
b5ab85c9d1e42ee47857299df3fcd79b6127e1fe
[ "Apache-2.0" ]
null
null
null
supervised_path_based.py
kwashio/filling_missing_path
b5ab85c9d1e42ee47857299df3fcd79b6127e1fe
[ "Apache-2.0" ]
null
null
null
# coding: utf-8 import argparse import os import pickle import numpy as np from supervised_model_common import * def pickle_load(file): with open(file, 'rb') as f: return pickle.load(f) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--data_prefix', type=str) parser.add_argument('--batchsize', '-b', type=int, default=100, help='Number of examples in each mini-batch') parser.add_argument('--lr', '-l', type=float, default=0.001) parser.add_argument('--gpu', '-g', type=int, default=0, help='GPU ID (negative value indicates CPU)') parser.add_argument('--out', '-o', default='result', help='Directory to output the result') parser.add_argument('--use_cudnn', '-c', type=int, default=0, help='Use CuDNN if the value is 1') args = parser.parse_args() if not os.path.exists(args.out): os.mkdir(args.out) if args.use_cudnn == 0: chainer.global_config.use_cudnn = 'never' if args.gpu >= 0: chainer.cuda.get_device_from_id(args.gpu).use() xp = cuda.cupy else: xp = np print('Data reading...') with open(args.data_prefix + '/train_data.dump', 'rb') as f: train_data = pickle.load(f) train_w1s, train_w2s, train_paths, train_labels = train_data train_paths = np.array(train_paths) with open(args.data_prefix + '/test_data.dump', 'rb') as f: test_data = pickle.load(f) test_w1s, test_w2s, test_paths, test_labels = test_data with open(args.data_prefix + '/val_data.dump', 'rb') as f: val_data = pickle.load(f) val_w1s, val_w2s, val_paths, val_labels = val_data with open(args.data_prefix + '/relations.txt', 'r') as f: lines = f.read().strip().split('\n') classes = {line.split('\t')[0]: int(line.split('\t')[1]) for line in lines} n_classes = len(classes) train_labels = np.array([classes[i] for i in train_labels]) test_labels = np.array([classes[i] for i in test_labels]) val_labels = np.array([classes[i] for i in val_labels]) val_w1s = xp.array(val_w1s, dtype=xp.int32) val_w2s = xp.array(val_w2s, dtype=xp.int32) val_paths = list(val_paths) test_w1s = xp.array(test_w1s, dtype=xp.int32) test_w2s = xp.array(test_w2s, dtype=xp.int32) test_paths = list(test_paths) print('Data are read!') print('Model building...') lemma_index = pickle_load('work/glove_index.dump') pos_index = pickle_load('work/pos_index.dump') dep_index = pickle_load('work/dep_index.dump') dir_index = pickle_load('work/dir_index.dump') lemma_embed = np.load('work/glove50.npy') n_lemma = len(lemma_index) n_pos = len(pos_index) n_dep = len(dep_index) n_dir = len(dir_index) max_val_score = 0 dropout_rate = [0.0, 0.2, 0.4] n_layers = [2] f = open(args.out + '/log.txt', 'w') f.close() val_f = open(args.out + '/val_log.txt', 'w') val_f.close() test_f = open(args.out + '/test_score.txt', 'w') test_f.close() test_score = 0 for layer_num in n_layers: for d_r in dropout_rate: lstm = BaseLSTM(n_layers=layer_num, emb_size=60, n_units=60, dropout=0, n_lemma_vocab=n_lemma, lemma_emb_size=50, lemma_embed_initial=lemma_embed, n_pos_vocab=n_pos, pos_emb_size=4, n_dep_vocab=n_dep, dep_emb_size=5, n_dir_vocab=n_dir, dir_emb_size=1 ) path_encoder = Path_Encoder(lstm) path_based = Path_Based(path_encoder, class_n=n_classes, dropout=d_r) model = Classifier_Path_Based(path_based) if args.gpu >= 0: chainer.cuda.get_device_from_id(args.gpu).use() model.to_gpu() optimizer = optimizers.Adam(args.lr) optimizer.setup(model) n_train = len(train_w1s) test_score = 0 c_val = 0 c_max_val_score = 0 e = 0 while c_val <= 7: perm = np.random.permutation(n_train) for i in range(0, n_train, args.batchsize): c_w1s = xp.array(train_w1s[perm[i:i + args.batchsize]], dtype=xp.int32) c_w2s = xp.array(train_w2s[perm[i:i + args.batchsize]], dtype=xp.int32) c_paths = train_paths[perm[i:i + args.batchsize]] c_labels = xp.array(train_labels[perm[i:i + args.batchsize]], dtype=xp.int32) loss = model(c_paths, c_labels) optimizer.target.cleargrads() loss.backward() optimizer.update() cur_result = '# epoch = {}, minibatch = {}/{}, loss = {}'.format(e + 1, int(i / args.batchsize) + 1, int(n_train / args.batchsize) + 1, loss.data ) with open(args.out + '/log.txt', 'a') as f: f.write('dropout: {} n_layer: {},'.format(str(d_r), str(layer_num)) + cur_result + '\n') current_val_score = path_based.evaluate(val_paths, val_labels) if current_val_score > c_max_val_score: c_val = 0 c_max_val_score = current_val_score c_val += 1 e += 1 with open(args.out + '/val_log.txt', 'a') as f: f.write('{}\t{}'.format(str(d_r), str(layer_num)) + '\t' + str(current_val_score) + '\n') if current_val_score > max_val_score: max_val_score = current_val_score serializers.save_npz(args.out + '/best.model', path_based) test_score = path_based.evaluate(test_paths, test_labels) with open(args.out + '/test_score.txt', 'a') as f: f.write('dropout: {}, n_layers: {}\ttest_score: {}\n'.format(str(d_r), str(layer_num), str(test_score)))
38.514793
119
0.537102
df54fdb6ff27a4fa614ff50e154bb3c8ee0b99ba
631
py
Python
polling_stations/apps/api/fields.py
chris48s/UK-Polling-Stations
4742b527dae94f0276d35c80460837be743b7d17
[ "BSD-3-Clause" ]
null
null
null
polling_stations/apps/api/fields.py
chris48s/UK-Polling-Stations
4742b527dae94f0276d35c80460837be743b7d17
[ "BSD-3-Clause" ]
null
null
null
polling_stations/apps/api/fields.py
chris48s/UK-Polling-Stations
4742b527dae94f0276d35c80460837be743b7d17
[ "BSD-3-Clause" ]
null
null
null
from rest_framework import serializers class PointField(serializers.Field): type_name = 'PointField' type_label = 'point' def to_representation(self, value): """ Transform POINT object to a geojson feature. """ if value is None: return value value = { "type": "Feature", "geometry": { "point": { "type": "Point", "coordinates": [ value.x, value.y ], }, }, } return value
22.535714
52
0.415214
4a342e50ee3d484ae1e1db79025454ac586c1010
3,498
py
Python
test/test_functional.py
bkk003/text_de_duplication_monitoring-
11f40daa2c591299b3d2d8340ff7a78d5f7cad01
[ "MIT" ]
3
2020-02-05T09:32:50.000Z
2021-06-16T12:54:22.000Z
test/test_functional.py
bkk003/text_de_duplication_monitoring-
11f40daa2c591299b3d2d8340ff7a78d5f7cad01
[ "MIT" ]
9
2020-02-05T09:58:59.000Z
2020-09-18T09:05:33.000Z
test/test_functional.py
bkk003/text_de_duplication_monitoring-
11f40daa2c591299b3d2d8340ff7a78d5f7cad01
[ "MIT" ]
1
2020-02-05T09:33:22.000Z
2020-02-05T09:33:22.000Z
"""Koninklijke Philips N.V., 2019 - 2020. All rights reserved. This file does the functional test of the "Text similarity from IO layer as well as UI later """ import os import unittest import subprocess from test.test_resource import TestResource from test.verify_path import FunctionalTestVerification from similarity.similarity_io import SimilarityIO # Below codes are comments as they cannot be executed in CI # from tkinter import Tk # from similarity.similarity_ui import TextSimilarityWindow class MyFunctionalTestCase(unittest.TestCase): """ This test class verifies the Text similarity index processing to cover similarity_io.py and similarity_core.py file with a test resources which simulates the user input file with defined formats required / allowed by the tool """ verify_func_obj = FunctionalTestVerification() @classmethod def tearDown(cls): """"Deletes the files created: merged, recommendation and duplicate.""" TestResource.clean_unnecessary_files() def test_below_ui(self): """ Test function which injects the user input data skipping the presentation later to the IO layer to check the underlying functionality """ cosine = SimilarityIO(TestResource.file_path, TestResource.testcase_id, TestResource.teststeps_id, TestResource.sim_range, TestResource.num_row, TestResource.var, TestResource.get_new_text) cosine.orchestrate_similarity() self.verify_func_obj.verify_functional_test() # # Below codes are comments as they cannot be executed in CI # def test_from_ui_new_text(self): # """Test function which injects the user input data at the presentation later # to check the end to end functionality""" # window = Tk() # win = TextSimilarityWindow(window) # win.check_is_new_text.invoke() # win.path_t.insert(0, str(TestResource.file_path)) # win.uniq_id_t.insert(0, 0) # win.steps_t.insert(0, "1,2") # win.new_text.insert(0, "a3 d4") # win.submit.invoke() # window.quit() # self.verify_func_objs.verify_functional_test(True) def test_from_command_line(self): """Test function which provides input using command line interface""" script = os.path.abspath(os.path.join(TestResource.par_dir, "similarity")) cmd = 'python %s --p "%s" --u "%s" --c "%s" --n "%s"' % ( script, TestResource.file_path, TestResource.command_unique_id, TestResource.command_colint, TestResource.num_row) os.system(cmd) self.verify_func_obj.verify_functional_test() def test_invalid_file(self): """Function test the empty file/ incorrect data/ extra sheet in the input file""" text_check = 'Input data is incorrect/ file is invalid/It has more than one sheet' flag = False cos_io_obj = SimilarityIO(TestResource.empty_file_path, TestResource.command_unique_id, TestResource.command_colint, TestResource.num_row, 0) cos_io_obj.orchestrate_similarity() line = subprocess.check_output(["tail", "-1", TestResource.log_file_path]) line = line.decode("UTF-8") if text_check in line: flag = True self.assertEqual(True, flag, "Validating empty input file from log file") if __name__ == '__main__': unittest.main()
45.428571
119
0.680675
1762a6ab4af477399871f0ee2a2e68072fd13729
1,421
py
Python
qiskit/extensions/standard/y.py
kifumi/qiskit-terra
203fca6d694a18824a6b12cbabd3dd2c64dd12ae
[ "Apache-2.0" ]
1
2018-11-01T01:35:43.000Z
2018-11-01T01:35:43.000Z
qiskit/extensions/standard/y.py
a-amaral/qiskit-terra
e73beba1e68de2617046a7e1e9eeac375b61de81
[ "Apache-2.0" ]
null
null
null
qiskit/extensions/standard/y.py
a-amaral/qiskit-terra
e73beba1e68de2617046a7e1e9eeac375b61de81
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # Copyright 2017, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. # pylint: disable=invalid-name """ Pauli Y (bit-phase-flip) gate. """ from qiskit import CompositeGate from qiskit import Gate from qiskit import InstructionSet from qiskit import QuantumCircuit from qiskit import QuantumRegister from qiskit.extensions.standard import header # pylint: disable=unused-import class YGate(Gate): """Pauli Y (bit-phase-flip) gate.""" def __init__(self, qubit, circ=None): """Create new Y gate.""" super().__init__("y", [], [qubit], circ) def qasm(self): """Return OPENQASM string.""" qubit = self.arg[0] return self._qasmif("y %s[%d];" % (qubit[0].name, qubit[1])) def inverse(self): """Invert this gate.""" return self # self-inverse def reapply(self, circuit): """Reapply this gate to corresponding qubits in circ.""" self._modifiers(circuit.y(self.arg[0])) def y(self, q): """Apply Y to q.""" if isinstance(q, QuantumRegister): instructions = InstructionSet() for j in range(q.size): instructions.add(self.y((q, j))) return instructions self._check_qubit(q) return self._attach(YGate(q, self)) QuantumCircuit.y = y CompositeGate.y = y
25.375
78
0.643913
72d16edb3dbd3f8957440946d3781f41557ac747
4,114
py
Python
benchmark/startCirq1519.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
benchmark/startCirq1519.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
benchmark/startCirq1519.py
UCLA-SEAL/QDiff
d968cbc47fe926b7f88b4adf10490f1edd6f8819
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 5/15/20 4:49 PM # @File : grover.py # qubit number=5 # total number=57 import cirq import cirq.google as cg from typing import Optional import sys from math import log2 import numpy as np #thatsNoCode from cirq.contrib.svg import SVGCircuit # Symbols for the rotation angles in the QAOA circuit. def make_circuit(n: int, input_qubit): c = cirq.Circuit() # circuit begin c.append(cirq.H.on(input_qubit[0])) # number=3 c.append(cirq.H.on(input_qubit[1])) # number=4 c.append(cirq.H.on(input_qubit[2])) # number=5 c.append(cirq.H.on(input_qubit[3])) # number=6 c.append(cirq.H.on(input_qubit[0])) # number=41 c.append(cirq.CZ.on(input_qubit[1],input_qubit[0])) # number=42 c.append(cirq.H.on(input_qubit[0])) # number=43 c.append(cirq.Z.on(input_qubit[1])) # number=37 c.append(cirq.H.on(input_qubit[0])) # number=51 c.append(cirq.CZ.on(input_qubit[1],input_qubit[0])) # number=52 c.append(cirq.H.on(input_qubit[0])) # number=53 c.append(cirq.H.on(input_qubit[4])) # number=21 c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2])) # number=54 c.append(cirq.X.on(input_qubit[2])) # number=55 c.append(cirq.CNOT.on(input_qubit[0],input_qubit[2])) # number=56 for i in range(2): c.append(cirq.H.on(input_qubit[0])) # number=1 c.append(cirq.H.on(input_qubit[1])) # number=2 c.append(cirq.H.on(input_qubit[2])) # number=7 c.append(cirq.H.on(input_qubit[3])) # number=8 c.append(cirq.CNOT.on(input_qubit[3],input_qubit[0])) # number=33 c.append(cirq.H.on(input_qubit[0])) # number=48 c.append(cirq.CZ.on(input_qubit[3],input_qubit[0])) # number=49 c.append(cirq.H.on(input_qubit[0])) # number=50 c.append(cirq.Z.on(input_qubit[3])) # number=46 c.append(cirq.CNOT.on(input_qubit[3],input_qubit[0])) # number=47 c.append(cirq.X.on(input_qubit[4])) # number=40 c.append(cirq.CNOT.on(input_qubit[3],input_qubit[0])) # number=35 c.append(cirq.H.on(input_qubit[0])) # number=17 c.append(cirq.H.on(input_qubit[1])) # number=18 c.append(cirq.H.on(input_qubit[2])) # number=19 c.append(cirq.H.on(input_qubit[3])) # number=20 c.append(cirq.X.on(input_qubit[0])) # number=9 c.append(cirq.CNOT.on(input_qubit[0],input_qubit[1])) # number=29 c.append(cirq.X.on(input_qubit[1])) # number=30 c.append(cirq.CNOT.on(input_qubit[0],input_qubit[1])) # number=31 c.append(cirq.X.on(input_qubit[2])) # number=11 c.append(cirq.X.on(input_qubit[1])) # number=44 c.append(cirq.X.on(input_qubit[3])) # number=12 c.append(cirq.CNOT.on(input_qubit[1],input_qubit[0])) # number=24 c.append(cirq.X.on(input_qubit[0])) # number=25 c.append(cirq.CNOT.on(input_qubit[1],input_qubit[0])) # number=26 c.append(cirq.X.on(input_qubit[1])) # number=14 c.append(cirq.X.on(input_qubit[2])) # number=15 c.append(cirq.X.on(input_qubit[3])) # number=16 c.append(cirq.X.on(input_qubit[1])) # number=22 c.append(cirq.Y.on(input_qubit[1])) # number=32 c.append(cirq.X.on(input_qubit[1])) # number=23 # circuit end c.append(cirq.measure(*input_qubit, key='result')) return c def bitstring(bits): return ''.join(str(int(b)) for b in bits) if __name__ == '__main__': qubit_count = 5 input_qubits = [cirq.GridQubit(i, 0) for i in range(qubit_count)] circuit = make_circuit(qubit_count,input_qubits) circuit = cg.optimized_for_sycamore(circuit, optimizer_type='sqrt_iswap') circuit_sample_count =2000 simulator = cirq.Simulator() result = simulator.run(circuit, repetitions=circuit_sample_count) frequencies = result.histogram(key='result', fold_func=bitstring) writefile = open("../data/startCirq1519.csv","w+") print(format(frequencies),file=writefile) print("results end", file=writefile) print(circuit.__len__(), file=writefile) print(circuit,file=writefile) writefile.close()
38.811321
77
0.654594
ea62611873abe96ac9c74a989700431897a2d7ce
11,796
py
Python
code/utils/constants.py
minthantsin/opensourcegames
ead0b89cff79918b98745df7c3fd9b374ecf3b87
[ "CC0-1.0" ]
1
2021-03-17T08:44:54.000Z
2021-03-17T08:44:54.000Z
code/utils/constants.py
minthantsin/opensourcegames
ead0b89cff79918b98745df7c3fd9b374ecf3b87
[ "CC0-1.0" ]
null
null
null
code/utils/constants.py
minthantsin/opensourcegames
ead0b89cff79918b98745df7c3fd9b374ecf3b87
[ "CC0-1.0" ]
null
null
null
""" Paths, properties. """ import os import configparser # paths root_path = os.path.realpath(os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir)) entries_path = os.path.join(root_path, 'entries') tocs_path = os.path.join(entries_path, 'tocs') code_path = os.path.join(root_path, 'code') web_path = os.path.join(root_path, 'docs') web_template_path = os.path.join(code_path, 'html') web_css_path = os.path.join(web_path, 'css') private_properties_file = os.path.join(root_path, 'private.properties') inspirations_file = os.path.join(root_path, 'inspirations.md') developer_file = os.path.join(root_path, 'developers.md') backlog_file = os.path.join(code_path, 'backlog.txt') rejected_file = os.path.join(code_path, 'rejected.txt') statistics_file = os.path.join(root_path, 'statistics.md') json_db_file = os.path.join(root_path, 'docs', 'data.json') # local config local_config_file = os.path.join(root_path, 'local-config.ini') config = configparser.ConfigParser() config.read(local_config_file) def get_config(key): """ :param key: :return: """ return config['general'][key] # database entry constants generic_comment_string = '[comment]: # (partly autogenerated content, edit with care, read the manual before)' # these fields have to be present in each entry (in this order) essential_fields = ('File', 'Title', 'Home', 'State', 'Keyword', 'Code language', 'Code license') # only these fields can be used currently (in this order) valid_properties = ('Home', 'Media', 'Inspiration', 'State', 'Play', 'Download', 'Platform', 'Keyword', 'Code repository', 'Code language', 'Code license', 'Code dependency', 'Assets license', 'Developer') valid_fields = ('File', 'Title') + valid_properties + ('Note', 'Building') url_fields = ('Home', 'Media', 'Play', 'Download', 'Code repository') valid_url_prefixes = ('http://', 'https://', 'git://', 'svn://', 'ftp://', 'bzr://') valid_building_properties = ('Build system', 'Build instruction') valid_building_fields = valid_building_properties + ('Note',) # these are the only valid platforms currently (and must be given in this order) valid_platforms = ('Windows', 'Linux', 'macOS', 'Android', 'iOS', 'Web') # these fields are not allowed to have comments fields_without_comments = ('Inspiration', 'Play', 'Download', 'Platform', 'Code dependency') # at least one of these must be used for every entry, this gives the principal categories and the order of the categories recommended_keywords = ( 'action', 'arcade', 'adventure', 'visual novel', 'sports', 'platform', 'puzzle', 'role playing', 'simulation', 'strategy', 'cards', 'board', 'music', 'educational', 'tool', 'game engine', 'framework', 'library', 'remake') framework_keywords = ('framework', 'library', 'tool') # known programming languages, anything else will result in a warning during a maintenance operation # only these will be used when gathering statistics language_urls = { 'AGS Script': 'https://en.wikipedia.org/wiki/Adventure_Game_Studio', 'ActionScript': 'https://en.wikipedia.org/wiki/ActionScript', 'Ada': 'https://en.wikipedia.org/wiki/Ada_(programming_language)', 'AngelScript': 'https://en.wikipedia.org/wiki/AngelScript', 'Assembly': 'https://en.wikipedia.org/wiki/Assembly_language', 'Basic': 'https://en.wikipedia.org/wiki/BASIC', 'Blender Script': 'https://en.wikipedia.org/wiki/Blender_(software)', 'BlitzMax': 'https://en.wikipedia.org/wiki/Blitz_BASIC', 'C': 'https://en.wikipedia.org/wiki/C_(programming_language)', 'C#': 'https://en.wikipedia.org/wiki/C_Sharp_(programming_language)', 'C++': 'https://en.wikipedia.org/wiki/C%2B%2B', 'Clojure': 'https://en.wikipedia.org/wiki/Clojure', 'CoffeeScript': 'https://en.wikipedia.org/wiki/CoffeeScript', 'ColdFusion': 'https://en.wikipedia.org/wiki/ColdFusion_Markup_Language', 'D': 'https://en.wikipedia.org/wiki/D_(programming_language)', 'DM': 'http://www.byond.com/docs/guide/', 'Dart': 'https://en.wikipedia.org/wiki/Dart_(programming_language)', 'Elm': 'https://en.wikipedia.org/wiki/Elm_(programming_language)', 'Emacs Lisp': 'https://en.wikipedia.org/wiki/Emacs_Lisp', 'F#': 'https://en.wikipedia.org/wiki/F_Sharp_(programming_language)', 'GDScript': 'https://en.wikipedia.org/wiki/Godot_(game_engine)#Scripting', 'Game Maker Script': 'https://en.wikipedia.org/wiki/GameMaker#GameMaker_Language', 'Go': 'https://en.wikipedia.org/wiki/Go_(programming_language)', 'Groovy': 'https://en.wikipedia.org/wiki/Apache_Groovy', 'Haskell': 'https://en.wikipedia.org/wiki/Haskell_(programming_language)', 'Haxe': 'https://en.wikipedia.org/wiki/Haxe', 'Io': 'https://en.wikipedia.org/wiki/Io_(programming_language)', 'Java': 'https://en.wikipedia.org/wiki/Java_(programming_language)', 'JavaScript': 'https://en.wikipedia.org/wiki/JavaScript', 'Kotlin': 'https://en.wikipedia.org/wiki/Kotlin_(programming_language)', 'Lisp': 'https://en.wikipedia.org/wiki/Lisp_(programming_language)', 'Lua': 'https://en.wikipedia.org/wiki/Lua_(programming_language)', 'MoonScript': 'https://moonscript.org/', 'OCaml': 'https://en.wikipedia.org/wiki/OCaml', 'Objective-C': 'https://en.wikipedia.org/wiki/Objective-C', 'ooc': 'https://ooc-lang.org/', 'PHP': 'https://en.wikipedia.org/wiki/PHP', 'Pascal': 'https://en.wikipedia.org/wiki/Pascal_(programming_language)', 'Perl': 'https://en.wikipedia.org/wiki/Perl', 'Python': 'https://en.wikipedia.org/wiki/Python_(programming_language)', 'QuakeC': 'https://en.wikipedia.org/wiki/QuakeC', "Ren'Py": 'https://en.wikipedia.org/wiki/Ren%27Py', 'Ruby': 'https://en.wikipedia.org/wiki/Ruby_(programming_language)', 'Rust': 'https://en.wikipedia.org/wiki/Rust_(programming_language)', 'Scala': 'https://en.wikipedia.org/wiki/Scala_(programming_language)', 'Scheme': 'https://en.wikipedia.org/wiki/Scheme_(programming_language)', 'Swift': 'https://en.wikipedia.org/wiki/Swift_(programming_language)', 'TorqueScript': 'https://en.wikipedia.org/wiki/Torque_(game_engine)', 'TypeScript': 'https://en.wikipedia.org/wiki/TypeScript', 'Vala': 'https://en.wikipedia.org/wiki/Vala_(programming_language)', 'Visual Basic': 'https://en.wikipedia.org/wiki/Visual_Basic', 'XUL': 'https://en.wikipedia.org/wiki/XUL', 'ZenScript': 'https://github.com/CraftTweaker/ZenScript' } known_languages = tuple(sorted(list(language_urls.keys()) + ['None', 'Script', 'Shell', '?'], key=str.casefold)) # known licenses, anything outside of this will result in a warning during a maintenance operation # only these will be used when gathering statistics known_licenses = ( '2-clause BSD', '3-clause BSD', 'AFL-3.0', 'AGPL-3.0', 'Apache-2.0', 'Artistic License-1.0', 'Artistic License-2.0', 'Boost-1.0', 'CC-BY-NC-3.0', 'CC-BY-NC-SA-2.0', 'CC-BY-NC-SA-3.0', 'CC-BY-SA-3.0', 'CC-BY-NC-SA-4.0', 'CC-BY-SA-4.0', 'CC0', 'Custom', 'EPL-2.0', 'GPL-2.0', 'GPL-3.0', 'IJG', 'ISC', 'Java Research License', 'LGPL-2.0', 'LGPL-2.1', 'LGPL-3.0', 'MAME', 'MIT', 'MPL-1.1', 'MPL-2.0', 'MS-PL', 'MS-RL', 'NetHack General Public License', 'None', 'Proprietary', 'Public domain', 'SWIG license', 'Unlicense', 'WTFPL', 'wxWindows license', 'zlib', '?') license_urls_repo = { '2-clause BSD': 'https://en.wikipedia.org/wiki/BSD_licenses#2-clause_license_(%22Simplified_BSD_License%22_or_%22FreeBSD_License%22)', '3-clause BSD': 'https://en.wikipedia.org/wiki/BSD_licenses#3-clause_license_(%22BSD_License_2.0%22,_%22Revised_BSD_License%22,_%22New_BSD_License%22,_or_%22Modified_BSD_License%22)', 'AFL': 'https://en.wikipedia.org/wiki/Academic_Free_License', 'AGPL': 'https://en.wikipedia.org/wiki/GNU_Affero_General_Public_License', 'Apache': 'https://en.wikipedia.org/wiki/Apache_License', 'Artistic License': 'https://en.wikipedia.org/wiki/Artistic_License', 'Boost': 'https://en.wikipedia.org/wiki/Boost_(C%2B%2B_libraries)#License', 'CC': 'https://en.wikipedia.org/wiki/Creative_Commons_license', 'EPL': 'https://en.wikipedia.org/wiki/Eclipse_Public_License', 'GPL': 'https://en.wikipedia.org/wiki/GNU_General_Public_License', 'IJG': 'https://spdx.org/licenses/IJG.html', 'ISC': 'https://en.wikipedia.org/wiki/ISC_license', 'Java Research License': 'https://en.wikipedia.org/wiki/Java_Research_License', 'LGPL': 'https://en.wikipedia.org/wiki/GNU_Lesser_General_Public_License', 'MAME': 'https://docs.mamedev.org/license.html', 'MIT': 'https://en.wikipedia.org/wiki/MIT_License', 'MPL': 'https://en.wikipedia.org/wiki/Mozilla_Public_License', 'MS': 'https://en.wikipedia.org/wiki/Shared_Source_Initiative#Microsoft_Public_License_(Ms-PL)', 'Nethack': 'https://en.wikipedia.org/wiki/NetHack#Licensing,_ports,_and_derivative_ports', 'Public domain': 'https://en.wikipedia.org/wiki/Public_domain', 'Unlicense': 'https://en.wikipedia.org/wiki/Unlicense', 'WTFPL': 'https://en.wikipedia.org/wiki/WTFPL', 'wxWindows': 'https://en.wikipedia.org/wiki/WxWidgets#License', 'zlib': 'https://en.wikipedia.org/wiki/Zlib_License' } def get_license_url(license): if license not in known_licenses: raise RuntimeError('Unknown license') for k, v in license_urls_repo.items(): if license.startswith(k): return v return None license_urls = {license: get_license_url(license) for license in known_licenses if get_license_url(license) is not None} # valid multiplayer modes (can be combined with "+" ) valid_multiplayer_modes = ( 'competitive', 'co-op', 'hotseat', 'LAN', 'local', 'massive', 'matchmaking', 'online', 'split-screen') # TODO put the abbreviations directly in the name line (parenthesis maybe), that is more natural # this is a mapping of entry name to abbreviation and the abbreviations are used when specifying code dependencies code_dependencies_aliases = {'Simple DirectMedia Layer': ('SDL', 'SDL2'), 'Simple and Fast Multimedia Library': ('SFML',), 'Boost (C++ Libraries)': ('Boost',), 'SGE Game Engine': ('SGE',), 'MegaGlest': ('MegaGlest Engine',)} # no developers needed for libraries # these are code dependencies that won't get their own entry, because they are not centered on gaming general_code_dependencies_without_entry = {'OpenGL': 'https://www.opengl.org/', 'GLUT': 'https://www.opengl.org/resources/libraries/', 'WebGL': 'https://www.khronos.org/webgl/', 'Unity': 'https://unity.com/solutions/game', '.NET': 'https://dotnet.microsoft.com/', 'Vulkan': 'https://www.khronos.org/vulkan/', 'KDE Frameworks': 'https://kde.org/products/frameworks/', 'jQuery': 'https://jquery.com/', 'node.js': 'https://nodejs.org/en/', 'GNU Guile': 'https://www.gnu.org/software/guile/', 'tkinter': 'https://docs.python.org/3/library/tk.html'} # developer information (in the file all fields will be capitalized) essential_developer_fields = ('Name', 'Games') optional_developer_fields = ('Home', 'Contact', 'Organization') valid_developer_fields = essential_developer_fields + optional_developer_fields url_developer_fields = ('Home',) # inspiration/original game information (in the file all fields will be capitalized) essential_inspiration_fields = ('Name', 'Inspired entries') optional_inspiration_fields = ('Media','Included') valid_inspiration_fields = essential_inspiration_fields + optional_inspiration_fields url_inspiration_fields = ('Media',)
55.121495
187
0.686843
68525ebad9141605b156c06147749bb2d4a23a51
1,262
py
Python
projekt.py
pawelhandrysik/mapki
534cfca2433a6b030677c6f046bde3e7be540b76
[ "MIT" ]
null
null
null
projekt.py
pawelhandrysik/mapki
534cfca2433a6b030677c6f046bde3e7be540b76
[ "MIT" ]
null
null
null
projekt.py
pawelhandrysik/mapki
534cfca2433a6b030677c6f046bde3e7be540b76
[ "MIT" ]
null
null
null
#!/usr/bin/python file = open('labirynt3.txt') mapa = file.readlines() mapa = ''.join(mapa) # import pdb; pdb.set_trace() visited = [] def findpath(mapa): mapa = mapa.split("\n") size = map(int, mapa[0].split(' ')) mapa = mapa[1:] mapa = map(list, mapa) start = None for y in range(size[0]): for x in range(size[1]): if mapa[y][x] == '@': start = x,y break if start != None: break _findpath(mapa, start[0], start[1]) visited.remove(start) for pos in visited: mapa[pos[1]][pos[0]] = '.' mapa = map(''.join, mapa) print('\n'.join(mapa)) def _findpath(mapa, x,y): if mapa[y][x] == '$': return True visited.append((x,y)) if mapa[y][x+1] != '#' and (x+1, y) not in visited: if _findpath(mapa, x+1, y): return True if mapa[y-1][x] != '#' and (x, y-1) not in visited: if _findpath(mapa, x, y-1): return True if mapa[y][x-1] != '#' and (x-1, y) not in visited: if _findpath(mapa, x-1, y): return True if mapa[y+1][x] != '#' and (x, y+1) not in visited: if _findpath(mapa, x, y+1): return True return False findpath(mapa)
23.811321
55
0.500792
38d77446a322f86eac9efec485006859281c13d8
1,903
py
Python
aionotion/bridge.py
bachya/aionotion
974782a31d8d29c55b9a21d2f55fc6b028bb0c53
[ "MIT" ]
null
null
null
aionotion/bridge.py
bachya/aionotion
974782a31d8d29c55b9a21d2f55fc6b028bb0c53
[ "MIT" ]
50
2019-06-17T15:20:49.000Z
2022-03-01T18:05:35.000Z
aionotion/bridge.py
bachya/aionotion
974782a31d8d29c55b9a21d2f55fc6b028bb0c53
[ "MIT" ]
1
2021-02-03T16:13:22.000Z
2021-02-03T16:13:22.000Z
"""Define endpoints for interacting with bridges.""" from typing import Any, Callable, Dict, List, cast class Bridge: # pylint: disable=too-few-public-methods """Define an object to interact with all endpoints.""" def __init__(self, request: Callable) -> None: """Initialize.""" self._request = request async def async_all(self) -> List[Dict[str, Any]]: """Get all bridges.""" resp = await self._request("get", "base_stations") return cast(List[Dict[str, Any]], resp["base_stations"]) async def async_create(self, attributes: Dict[str, Any]) -> Dict[str, Any]: """Create a bridge with a specific attribute payload.""" resp = await self._request( "post", "base_stations", json={"base_stations": attributes} ) return cast(Dict[str, Any], resp["base_stations"]) async def async_delete(self, bridge_id: int) -> None: """Delete a bridge by ID.""" await self._request("delete", f"base_stations/{bridge_id}") async def async_get(self, bridge_id: int) -> Dict[str, Any]: """Get a bridge by ID.""" resp = await self._request("get", f"base_stations/{bridge_id}") return cast(Dict[str, Any], resp["base_stations"]) async def async_reset(self, bridge_id: int) -> Dict[str, Any]: """Reset a bridge (clear its wifi credentials) by ID.""" resp = await self._request("put", f"base_stations/{bridge_id}/reset") return cast(Dict[str, Any], resp["base_stations"]) async def async_update( self, bridge_id: int, new_attributes: Dict[str, Any] ) -> Dict[str, Any]: """Update a bridge with a specific attribute payload.""" resp = await self._request( "put", f"base_stations/{bridge_id}", json={"base_stations": new_attributes} ) return cast(Dict[str, Any], resp["base_stations"])
41.369565
87
0.626905
e5209c7369e587a1c9a5c914c12ccc44282d9f40
1,724
py
Python
Hackbot/bot.py
starwiz-7/HackBot
27c1928d4b11f66ee334580324f77ca16ae2d859
[ "MIT" ]
10
2021-02-20T23:43:41.000Z
2022-02-15T20:55:44.000Z
Hackbot/bot.py
starwiz-7/HackBot
27c1928d4b11f66ee334580324f77ca16ae2d859
[ "MIT" ]
18
2021-01-23T07:35:48.000Z
2022-03-01T10:29:00.000Z
Hackbot/bot.py
yoki31/HackBot
7607013d63ccb8e26517d13b3a81b8a76a7be323
[ "MIT" ]
4
2021-06-23T04:07:43.000Z
2022-01-14T05:55:25.000Z
import os from os import environ import logging from pathlib import Path import discord from discord.ext import commands from discord.utils import find from utils.db import new_hackathon def main(): DISCORD_TOKEN = os.environ.get('DISCORD_TOKEN') if not DISCORD_TOKEN: logging.error('Token missing') return bot = commands.Bot(command_prefix=commands.when_mentioned_or(';hack '), case_sensitive=False) for filename in os.listdir('./cogs'): if filename.endswith('.py'): bot.load_extension(f'cogs.{filename[:-3]}') print(f'Cogs loaded: {", ".join(bot.cogs)}') def no_dm_check(ctx): if ctx.guild is None: raise commands.NoPrivateMessage('No Private Hacking!!') return True bot.add_check(no_dm_check) @bot.event async def on_ready(): await bot.change_presence( activity=discord.Activity( type=discord.ActivityType.watching, name='Netflix' ) ) @bot.event async def on_guild_join(guild): for channel in guild.text_channels: if channel.permissions_for(guild.me).send_messages: await channel.send("```Hello guyss! HackBot is here to notify you all about the upcoming hackathons\nCommand Prefix: ;hack\nFor help in commands type: ;hack help```") await channel.send("To start receiving notification enter `;hack notify <channel_name>` command.") break @bot.event async def on_command_error(ctx,error): if isinstance(error, commands.CommandNotFound): await ctx.send("Please type `;hack help` for list of commands") bot.run(DISCORD_TOKEN) if __name__ == '__main__': main()
35.183673
182
0.661253
f1fbaca80725f987ef5d3cef20c27b2ffe5f1191
739
py
Python
docs/Machine-Learning/ipython/embedding/start_ipython_config.py
MitchellTesla/Quantm
57045e0ea9ee7b965ecd26e4a8d0c1902df65245
[ "MIT" ]
7
2021-02-15T06:43:23.000Z
2022-01-13T10:43:32.000Z
ipython-7.29.0/examples/Embedding/start_ipython_config.py
JohnLauFoo/clc_packages_Yu
259f01d9b5c02154ce258734d519ae8995cd0991
[ "MIT" ]
1
2021-04-19T12:32:49.000Z
2021-04-19T12:32:49.000Z
ipython-7.29.0/examples/Embedding/start_ipython_config.py
JohnLauFoo/clc_packages_Yu
259f01d9b5c02154ce258734d519ae8995cd0991
[ "MIT" ]
2
2020-11-18T19:39:31.000Z
2021-11-17T07:49:09.000Z
"""Quick snippet explaining how to set config options when using start_ipython.""" # First create a config object from the traitlets library from traitlets.config import Config c = Config() # Now we can set options as we would in a config file: # c.Class.config_value = value # For example, we can set the exec_lines option of the InteractiveShellApp # class to run some code when the IPython REPL starts c.InteractiveShellApp.exec_lines = [ 'print("\\nimporting some things\\n")', 'import math', "math" ] c.InteractiveShell.colors = 'LightBG' c.InteractiveShell.confirm_exit = False c.TerminalIPythonApp.display_banner = False # Now we start ipython with our configuration import IPython IPython.start_ipython(config=c)
32.130435
82
0.764547
d7da622a418aff14a28ee1df9a279e14a72b48f5
524
py
Python
tests/test_utils.py
KatyKasilina/StumbleUpon-Evergreen-DataMining
de8824bb85f00aef5b9ad57690191dbc984b9384
[ "MIT" ]
null
null
null
tests/test_utils.py
KatyKasilina/StumbleUpon-Evergreen-DataMining
de8824bb85f00aef5b9ad57690191dbc984b9384
[ "MIT" ]
null
null
null
tests/test_utils.py
KatyKasilina/StumbleUpon-Evergreen-DataMining
de8824bb85f00aef5b9ad57690191dbc984b9384
[ "MIT" ]
null
null
null
import pandas as pd from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier from src.utils import read_data, load_pkl_file def test_read_data(synthetic_data_path: str): df = read_data(synthetic_data_path) assert isinstance(df, pd.DataFrame) assert (200, 15) == df.shape def test_load_pkl_file(load_model_path: str): model = load_pkl_file(load_model_path) assert isinstance(model, RandomForestClassifier) or isinstance(model, LogisticRegression)
22.782609
93
0.793893
d58a1c4265b84c09e29f3c3bfbc79a6a3ba19ab3
3,911
py
Python
simple_example_with_mean_py2.py
JulienPeloton/bigviz
205f5ef29d60b25e11db2e3c76fe248b56952bd8
[ "Apache-2.0" ]
null
null
null
simple_example_with_mean_py2.py
JulienPeloton/bigviz
205f5ef29d60b25e11db2e3c76fe248b56952bd8
[ "Apache-2.0" ]
null
null
null
simple_example_with_mean_py2.py
JulienPeloton/bigviz
205f5ef29d60b25e11db2e3c76fe248b56952bd8
[ "Apache-2.0" ]
null
null
null
# Copyright 2018 Julien Peloton # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from pyspark.sql import SparkSession import numpy as np import argparse def quiet_logs(sc, log_level="ERROR"): """ Set the level of log in Spark. Parameters ---------- sc : SparkContext The SparkContext for the session log_level : String [optional] Level of log wanted: INFO, WARN, ERROR, OFF, etc. """ ## Get the logger logger = sc._jvm.org.apache.log4j ## Set the level level = getattr(logger.Level, log_level, "INFO") logger.LogManager.getLogger("org"). setLevel(level) logger.LogManager.getLogger("akka").setLevel(level) def mean(partition): """Compute the centroid of the partition. It can be viewed as a k-means for k=1. Parameters ---------- partition : Iterator Iterator over the elements of the Spark partition. Returns ------- Generator of (list, int) Yield tuple with the centroid and the total number of points in the partition. If the partition is empty, return (None, 0). Examples ------- List of coordinates (can be 2D, 3D, ..., nD) >>> mylist = [[1., 2.], [3., 4.], [5., 6.], [7., 8.], [9., 10.]] Considering only 1 partition >>> myit = iter(mylist) >>> list(mean(myit)) [(array([ 5., 6.]), 5)] Distribute over 2 partitions >>> rdd = sc.parallelize(mylist, 2) Compute the centroid for each partition >>> data = rdd.mapPartitions( ... lambda partition: cf.mean(partition)).collect() >>> print(data) [(array([ 2., 3.]), 2), (array([ 7., 8.]), 3)] """ # Unwrap the iterator xyz = [item for item in partition] size = len(xyz) # Compute the centroid only if the partition is not empty if size > 0: mean = np.mean(xyz, axis=0) else: mean = None yield (mean, size) def addargs(parser): """ Parse command line arguments for simple_example.py """ ## Arguments parser.add_argument( '-fn', dest='fn', required=True, help='Path to a FITS file') ## Arguments parser.add_argument( '-hdu', dest='hdu', required=True, help='HDU index to load.') if __name__ == "__main__": """ Visualise the elements of a spatial RDD """ parser = argparse.ArgumentParser( description=""" Visualise the elements of a spatial RDD """) addargs(parser) args = parser.parse_args(None) # Initialize the Spark Session spark = SparkSession\ .builder\ .getOrCreate() # Set logs to be quiet quiet_logs(spark.sparkContext, log_level="OFF") # Load the data inside a DataFrame df = spark.read.format("fits").option("hdu", args.hdu).load(args.fn) # Apply a collapse function # Before, repartition our DataFrame to mimick a large data set. data = df.repartition(256).rdd.mapPartitions(mean).collect() # Re-organise the data into lists of x, y, z coordinates x = [p[0][0] for p in data if p[0] is not None] y = [p[0][1] for p in data if p[0] is not None] z = [p[0][2] for p in data if p[0] is not None] # This is the place where you will pass those lists to the C routines. # Alternatively, you could save the data on disk and load it inside the # C program. import hello_ext print(hello_ext.greet())
28.97037
75
0.628484
a700f68a3cebcc21ce7d7ad1b5861248d132872f
246
py
Python
ebb_lint/checkers/registration.py
AndrewLvov/ebb-lint
3ed549f0e83f1c2bbba50e87923577259bd33b75
[ "PSF-2.0" ]
null
null
null
ebb_lint/checkers/registration.py
AndrewLvov/ebb-lint
3ed549f0e83f1c2bbba50e87923577259bd33b75
[ "PSF-2.0" ]
null
null
null
ebb_lint/checkers/registration.py
AndrewLvov/ebb-lint
3ed549f0e83f1c2bbba50e87923577259bd33b75
[ "PSF-2.0" ]
null
null
null
import venusian def register_checker(pattern, **extra): def deco(func): def callback(scanner, name, obj): scanner.register(pattern, obj, extra) venusian.attach(func, callback) return func return deco
22.363636
49
0.638211
3fffff12e6cf9402bd4f21b8f4c56fa81cae0393
9,047
py
Python
sicer/src/find_islands_in_pr.py
jeffreyyoo/SICER2
412581f4bd4345d8100c62bf2bee8ae2bc7a2d6b
[ "MIT" ]
null
null
null
sicer/src/find_islands_in_pr.py
jeffreyyoo/SICER2
412581f4bd4345d8100c62bf2bee8ae2bc7a2d6b
[ "MIT" ]
1
2019-11-24T16:35:21.000Z
2019-11-24T16:35:21.000Z
sicer/src/find_islands_in_pr.py
jinyongyoo/SICER2
412581f4bd4345d8100c62bf2bee8ae2bc7a2d6b
[ "MIT" ]
null
null
null
# Authors: Chongzhi Zang, Weiqun Peng, Dustin E Schones and Keji Zhao # Modified by: Jin Yong Yoo import multiprocessing as mp import os from functools import partial from math import * import numpy as np from sicer.lib import Background_island_probscore_statistics from sicer.lib import GenomeData """ Take in coords for bed_gaph type summary files and find 'islands' of modifications. There are a number options here that can be turned on or off depending on need Right now: (1) scan for all 'islands' where the single window or consecutive windows (2) remove all single window 'islands' -- this can be commented out when looking for more localized signals (such as TF binding sites?) (3) try to combine islands that are within gap distance of each other. This gap distance is supplemented by a window_buffer just so we don't do anything stupid with window sizes (4) Remove all single window combined islands -- if step (2) was done, this is redundant (5) Lastly, filter out all the islands we've found that have a total score < islands_minimum_tags """ # Factorial def fact(m): value = 1.0; if m != 0: while m != 1: value = value * m; m = m - 1; return value; # Return the log of a factorial, using Srinivasa Ramanujan's approximation when m>=20 def factln(m): if m < 20: value = 1.0; if m != 0: while m != 1: value = value * m; m = m - 1; return log(value); else: return m * log(m) - m + log(m * (1 + 4 * m * (1 + 2 * m))) / 6.0 + log(pi) / 2; def poisson(i, average): if i < 20: return exp(-average) * average ** i / fact(i); else: exponent = -average + i * log(average) - factln(i); return exp(exponent); def combine_proximal_islands(islands, gap, window_size_buffer=3): """ islands: a list of tuples of following format: (chrom, start, end, score) Therefore, "islands[index][1]" would mean the start position of the window at the given index Extend the regions found in the find_continuous_region function. If gap is not allowed, gap = 0, if one window is allowed, gap = window_size (200) Return a list of combined regions. """ proximal_island_dist = gap + window_size_buffer; final_islands = [] current_island = islands[0]; if len(islands) == 1: final_islands = islands; else: for index in range(1, len(islands)): dist = islands[index][1] - current_island[2]; if dist <= proximal_island_dist: current_island[2] = islands[index][2]; current_island[3] += islands[index][3]; else: final_islands.append(current_island); current_island = islands[index]; # The last island: final_islands.append(current_island); return final_islands; def find_region_above_threshold(island_list, score_threshold): filtered_islands = []; for island in island_list: if island[3] >= (score_threshold - .0000000001): filtered_islands.append(island); return filtered_islands; def filter_ineligible_windows(chrom_graph, min_tags_in_window, average): '''Filters windows that have tag count lower than the minimum threshold count and calculates score for windows that meet the minimum count. Score is defined as s = -log(Poisson(read_count,lambda))''' filtered_chrom_graph = [] for window in chrom_graph: read_count = window[3] score = -1 if (read_count >= min_tags_in_window): prob = poisson(read_count, average); if prob < 1e-250: score = 1000; # outside of the scale, take an arbitrary number. else: score = -log(prob) eligible_window = (window[0], window[1], window[2], score) if score > 0: filtered_chrom_graph.append(eligible_window); np_filtered_chrom_graph = np.array(filtered_chrom_graph, dtype=object) return np_filtered_chrom_graph def filter_and_find_islands(min_tags_in_window, gap_size, score_threshold, average, verbose, graph_file): '''Function for handling multiprocessing. Calls functions for filtering windows and finding islands.''' number_of_islands = 0 print_return = "" chrom_graph = np.load(graph_file, allow_pickle=True) if (len(chrom_graph) > 0): chrom = chrom_graph[0][0] filtered_chrom_graph = filter_ineligible_windows(chrom_graph, min_tags_in_window, average) islands = combine_proximal_islands(filtered_chrom_graph, gap_size, 2); islands = find_region_above_threshold(islands, score_threshold); number_of_islands += len(islands) if not (len(islands) > 0): if verbose: print_return += chrom + " does not have any islands meeting the required significance" np.save(graph_file, islands) return (graph_file, number_of_islands, print_return) def main(args, total_read_count, pool): print("Species: ", args.species); print("Window_size: ", args.window_size); print("Gap size: ", args.gap_size); print("E value is:", args.e_value); print("Total read count:", total_read_count) chroms = GenomeData.species_chroms[ args.species]; # list of chromsomes for the given species (e.g. chr1, chr2, ... , chrx) genome_length = sum(GenomeData.species_chrom_lengths[args.species].values()); # list of length of each chromsomes effective_genome_length = int(args.effective_genome_fraction * genome_length); average = float(total_read_count) * args.window_size / effective_genome_length; # average read count print("Genome Length: ", genome_length); print("Effective genome Length: ", effective_genome_length); print("Window average:", average); window_pvalue = 0.20; bin_size = 0.001; background = Background_island_probscore_statistics.Background_island_probscore_statistics(total_read_count, args.window_size, args.gap_size, window_pvalue, effective_genome_length, bin_size); min_tags_in_window = background.min_tags_in_window print("Window pvalue:", window_pvalue) print("Minimum num of tags in a qualified window: ", min_tags_in_window) # first threshold cutoff print("\nDetermining the score threshold from random background..."); # determine threshold from random background score_threshold = background.find_island_threshold(args.e_value); print("The score threshold is:", score_threshold); # generate the probscore summary graph file, only care about enrichment # filter the summary graph to get rid of windows whose scores are less than window_score_threshold file = args.treatment_file.replace('.bed', '') list_of_graph_files = [] for chrom in chroms: list_of_graph_files.append(file + '_' + chrom + '_graph.npy') # Use multiprocessing to filter windows with tag count below minimum requirement print( "Generating the enriched probscore summary graph and filtering the summary graph to eliminate ineligible windows... "); #pool = mp.Pool(processes=min(args.cpu, len(chroms))) filter_and_find_islands_partial = partial(filter_and_find_islands, min_tags_in_window, args.gap_size, score_threshold, average, args.verbose) filtered_islands_result = pool.map(filter_and_find_islands_partial, list_of_graph_files) #pool.close() file_name = args.treatment_file.replace('.bed', '') outfile_path = os.path.join(args.output_directory, (file_name + '-W' + str(args.window_size) + '-G' + str(args.gap_size) + '.scoreisland')) total_number_islands = 0 path_to_filtered_graph = [] with open(outfile_path, 'w') as outfile: for i in range(0, len(filtered_islands_result)): filtered_chrom_graph = np.load(filtered_islands_result[i][0],allow_pickle=True) path_to_filtered_graph.append(filtered_islands_result[i][0]) total_number_islands += filtered_islands_result[i][1] if (filtered_islands_result[i][2] != ""): print(filtered_islands_result[i][2]) for window in filtered_chrom_graph: chrom = window[0] line = (chrom + '\t' + str(window[1]) + '\t' + str(window[2]) + '\t' + str(window[3]) + '\n') outfile.write(line) print("Total number of islands: ", total_number_islands);
41.122727
143
0.635017
63f9606648f782faa32dc8a17cc83ab7f36805bb
366
py
Python
app/hotelrecipe/urls.py
zohaib089/rest-hotelrecipe-api
a03203a569e8ac9391a8d15427c6fca95ab21aea
[ "MIT" ]
1
2019-08-27T00:18:49.000Z
2019-08-27T00:18:49.000Z
app/hotelrecipe/urls.py
zohaib089/rest-hotelrecipe-api
a03203a569e8ac9391a8d15427c6fca95ab21aea
[ "MIT" ]
null
null
null
app/hotelrecipe/urls.py
zohaib089/rest-hotelrecipe-api
a03203a569e8ac9391a8d15427c6fca95ab21aea
[ "MIT" ]
null
null
null
from django.urls import path,include from rest_framework.routers import DefaultRouter from hotelrecipe import views router = DefaultRouter() router.register('tag',views.TagViewSet) router.register('ingredients',views.IngredientViewSet) router.register('recipes',views.RecipeViewSet) app_name = 'hotelrecipe' urlpatterns = [ path('',include(router.urls)) ]
20.333333
54
0.789617
cea014e886923d3e301516e4402a1864a4494674
3,080
py
Python
train_origin_tacotron.py
HappyBall/asr_guided_tacotron
be36f0895b81e338c5c51a7ab6d421fbf3aa055b
[ "MIT" ]
5
2018-08-02T13:44:11.000Z
2020-04-27T23:48:21.000Z
train_origin_tacotron.py
HappyBall/asr_guided_tacotron
be36f0895b81e338c5c51a7ab6d421fbf3aa055b
[ "MIT" ]
1
2019-08-19T06:47:26.000Z
2020-05-24T01:18:22.000Z
train_origin_tacotron.py
HappyBall/asr_guided_tacotron
be36f0895b81e338c5c51a7ab6d421fbf3aa055b
[ "MIT" ]
5
2019-02-18T16:39:47.000Z
2021-08-19T14:10:43.000Z
''' modified from https://www.github.com/kyubyong/tacotron ''' import os import sys from hyperparams import Hyperparams as hp import tensorflow as tf from tqdm import tqdm from utils import * from graph import Graph FLAGS = tf.app.flags.FLAGS tf.app.flags.DEFINE_string("keep_train", "False", "keep training from existed model or not") if __name__ == '__main__': keep_train = FLAGS.keep_train g = Graph(mode='train_tacotron'); print("Training Graph loaded") if keep_train == "True": logfile = open(os.path.join(hp.taco_logdir,hp.taco_logfile), "a") else: if not os.path.exists(hp.taco_logdir): os.makedirs(hp.taco_logdir) logfile = open(os.path.join(hp.taco_logdir,hp.taco_logfile), "w") saver = tf.train.Saver(max_to_keep=10) #saver_las = tf.train.Saver(var_list=g.las_variable) # used to restore only las variable init = tf.global_variables_initializer() #sv = tf.train.Supervisor(taco_logdir=hp.taco_logdir, save_summaries_secs=60, save_model_secs=0) with tf.Session() as sess: #while 1: writer = tf.summary.FileWriter(hp.taco_logdir, graph = sess.graph) # load graph from las_logdir #saver_las.restore(sess, tf.train.latest_checkpoint(hp.las_logdir)) #print('finish loading las varaible') if keep_train == "True": saver.restore(sess, tf.train.latest_checkpoint(hp.taco_logdir)) print("Continue training from existed latest model...") else: sess.run(init) print("Initial new training...") coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(coord=coord) for epoch in range(1, hp.taco_num_epochs + 1): total_loss, total_mel_loss, total_linear_loss = 0.0, 0.0, 0.0 for _ in tqdm(range(g.num_batch), total=g.num_batch, ncols=70, leave=False, unit='b'): _, gs, l, l_mel, l_linear = sess.run([g.train_op, g.global_step, g.loss, g.loss1, g.loss2]) total_loss += l total_mel_loss += l_mel total_linear_loss += l_linear # Write checkpoint files if gs % 1000 == 0: al = sess.run(g.alignments_taco) plot_alignment(al[0], gs, hp.taco_logdir, name='taco') log = "Epoch " + str(epoch) + " average loss: " + str(total_loss/float(g.num_batch)) + ", average mel loss: " + str(total_mel_loss/float(g.num_batch)) + ", average linear loss: " + str(total_linear_loss/float(g.num_batch)) + "\n" print(log) sys.stdout.flush() logfile.write(log) # Write checkpoint files if epoch % 10 == 0: #sv.saver.save(sess, hp.taco_logdir + '/model_gs_{}k'.format(gs//1000)) saver.save(sess, hp.taco_logdir + '/model_epoch_{}.ckpt'.format(epoch)) result = sess.run(g.merged) writer.add_summary(result, epoch) coord.request_stop() coord.join(threads) print("Done")
39.487179
242
0.619156
7eff54e78c15d2bd71af274c2148d7aa5f284941
32,664
py
Python
floris/simulation/flow_field.py
jialrs/floris-enhanced
66cdf1c9597aa3bb4f956cc9a0cb497312a690bf
[ "Apache-2.0" ]
null
null
null
floris/simulation/flow_field.py
jialrs/floris-enhanced
66cdf1c9597aa3bb4f956cc9a0cb497312a690bf
[ "Apache-2.0" ]
null
null
null
floris/simulation/flow_field.py
jialrs/floris-enhanced
66cdf1c9597aa3bb4f956cc9a0cb497312a690bf
[ "Apache-2.0" ]
null
null
null
# Copyright 2020 NREL # 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. # See https://floris.readthedocs.io for documentation import numpy as np from ..utilities import Vec3 from ..utilities import cosd, sind, tand from ..utilities import setup_logger import scipy as sp from scipy.interpolate import griddata class FlowField(): """ FlowField is at the core of the FLORIS software. This class handles creating the wind farm domain and initializing and computing the flow field based on the chosen wake models and farm model. """ def __init__(self, wind_shear, wind_veer, air_density, wake, turbine_map, wind_map, specified_wind_height): """ Calls :py:meth:`~.flow_field.FlowField.reinitialize_flow_field` to initialize the required data. Args: wind_shear (float): Wind shear coefficient. wind_veer (float): Amount of veer across the rotor. air_density (float): Wind farm air density. wake (:py:class:`~.wake.Wake`): The object containing the model definition for the wake calculation. turbine_map (:py:obj:`~.turbine_map.TurbineMap`): The object describing the farm layout and turbine location. wind_map (:py:obj:`~.wind_map.WindMap`): The object describing the atmospheric conditions throughout the farm. specified_wind_height (float): The focal center of the farm in elevation; this value sets where the given wind speed is set and about where initial velocity profile is applied. """ self.reinitialize_flow_field( wind_shear=wind_shear, wind_veer=wind_veer, air_density=air_density, wake=wake, turbine_map=turbine_map, wind_map=wind_map, with_resolution=wake.velocity_model.model_grid_resolution, specified_wind_height=specified_wind_height) #TODO consider remapping wake_list with reinitialize flow field self.wake_list = { turbine: None for _, turbine in self.turbine_map.items } def _discretize_turbine_domain(self): """ Create grid points at each turbine """ xt = [coord.x1 for coord in self.turbine_map.coords] rotor_points = int( np.sqrt(self.turbine_map.turbines[0].grid_point_count)) x_grid = np.zeros((len(xt), rotor_points, rotor_points)) y_grid = np.zeros((len(xt), rotor_points, rotor_points)) z_grid = np.zeros((len(xt), rotor_points, rotor_points)) for i, (coord, turbine) in enumerate(self.turbine_map.items): xt = [coord.x1 for coord in self.turbine_map.coords] yt = np.linspace(coord.x2 - turbine.rotor_radius, coord.x2 + turbine.rotor_radius, rotor_points) zt = np.linspace(coord.x3 - turbine.rotor_radius, coord.x3 + turbine.rotor_radius, rotor_points) for j in range(len(yt)): for k in range(len(zt)): x_grid[i, j, k] = xt[i] y_grid[i, j, k] = yt[j] z_grid[i, j, k] = zt[k] xoffset = x_grid[i, j, k] - coord.x1 yoffset = y_grid[i, j, k] - coord.x2 x_grid[i, j, k] = xoffset * cosd(-1 * self.wind_map.turbine_wind_direction[i]) - \ yoffset * sind(-1 * self.wind_map.turbine_wind_direction[i]) + coord.x1 y_grid[i, j, k] = yoffset * cosd(-1 * self.wind_map.turbine_wind_direction[i]) + \ xoffset * sind(-1*self.wind_map.turbine_wind_direction[i]) + coord.x2 return x_grid, y_grid, z_grid def _discretize_gridded_domain(self, xmin, xmax, ymin, ymax, zmin, zmax, resolution): """ Generate a structured grid for the entire flow field domain. resolution: Vec3 PF: NOTE, PERHAPS A BETTER NAME IS SETUP_GRIDDED_DOMAIN """ x = np.linspace(xmin, xmax, int(resolution.x1)) y = np.linspace(ymin, ymax, int(resolution.x2)) z = np.linspace(zmin, zmax, int(resolution.x3)) return np.meshgrid(x, y, z, indexing="ij") def _compute_initialized_domain(self, with_resolution=None, points=None): """ Establish the layout of grid points for the flow field domain and calculate initial values at these points. Note this function is currently complex to understand, and could be recast, but for now it has 3 main uses 1) Initializing a non-curl model (gauss, multizone), using a call to _discretize_turbine_domain 2) Initializing a gridded curl model (using a call to _discretize_gridded_domain) 3) Appending points to a non-curl model, this could either be for adding additional points to calculate for use in visualization, or else to enable calculation of additional points. Note this assumes the flow has previously been discritized in a prior call to _compute_initialized_domain / _discretize_turbine_domain Args: points: An array that contains the x, y, and z coordinates of user-specified points, at which the flow field velocity is recorded. with_resolution: Vec3 Returns: *None* -- The flow field is updated directly in the :py:class:`floris.simulation.floris.flow_field` object. """ if with_resolution is not None: xmin, xmax, ymin, ymax, zmin, zmax = self.domain_bounds self.x, self.y, self.z = self._discretize_gridded_domain( xmin, xmax, ymin, ymax, zmin, zmax, with_resolution) else: if points is not None: # # # Alayna's Original method******************************* # Append matrices of idential points equal to the number of turbine grid points # print('APPEND THE POINTS') # shape = ((len(self.x)) + len(points[0]), len(self.x[0,:]), len(self.x[0,0,:])) # elem_shape = np.shape(self.x[0]) # # print(elem_shape) # # print(np.full(elem_shape, points[0][0])) # # quit() # for i in range(len(points[0])): # self.x = np.append(self.x, np.full(elem_shape, points[0][i])) # self.y = np.append(self.y, np.full(elem_shape, points[1][i])) # self.z = np.append(self.z, np.full(elem_shape, points[2][i])) # self.x = np.reshape(self.x, shape) # self.y = np.reshape(self.y, shape) # self.z = np.reshape(self.z, shape) # print('DONE APPEND THE POINTS') # # # END Alayna's Original method******************************* # # # Faster equivalent method I think***************************** # # Reshape same as above but vectorized I think # print('APPEND THE POINTS') # elem_num_el = np.size(self.x[0]) # shape = ((len(self.x)) + len(points[0]), len(self.x[0,:]), len(self.x[0,0,:])) # self.x = np.append(self.x, np.repeat(points[0,:],elem_num_el)) # self.y = np.append(self.y, np.repeat(points[1,:],elem_num_el)) # self.z = np.append(self.z, np.repeat(points[2,:],elem_num_el)) # self.x = np.reshape(self.x, shape) # self.y = np.reshape(self.y, shape) # self.z = np.reshape(self.z, shape) # print('DONE APPEND THE POINTS') # # # END Faster equivalent method I think***************************** # # Faster equivalent method with less final points ******************** # Don't replicate points to be 25x (num points on turbine plane) # This will yield less overall points by removing redundant points and make later steps faster elem_num_el = np.size(self.x[0]) num_points_to_add = len(points[0]) matrices_to_add = int(np.ceil(num_points_to_add / elem_num_el)) buffer_amount = matrices_to_add * elem_num_el - num_points_to_add shape = ((len(self.x)) + matrices_to_add, len(self.x[0, :]), len(self.x[0, 0, :])) self.x = np.append( self.x, np.append(points[0, :], np.repeat(points[0, 0], buffer_amount))) self.y = np.append( self.y, np.append(points[1, :], np.repeat(points[1, 0], buffer_amount))) self.z = np.append( self.z, np.append(points[2, :], np.repeat(points[2, 0], buffer_amount))) self.x = np.reshape(self.x, shape) self.y = np.reshape(self.y, shape) self.z = np.reshape(self.z, shape) # # Faster equivalent method with less final points ******************** else: self.x, self.y, self.z = self._discretize_turbine_domain() # set grid point locations in wind_map self.wind_map.grid_layout = (self.x, self.y) # interpolate for initial values of flow field grid self.wind_map.calculate_turbulence_intensity(grid=True) self.wind_map.calculate_wind_direction(grid=True) self.wind_map.calculate_wind_speed(grid=True) self.u_initial = self.wind_map.grid_wind_speed * \ (self.z / self.specified_wind_height)**self.wind_shear self.v_initial = np.zeros(np.shape(self.u_initial)) self.w_initial = np.zeros(np.shape(self.u_initial)) self.u = self.u_initial.copy() self.v = self.v_initial.copy() self.w = self.w_initial.copy() def _compute_turbine_velocity_deficit(self, x, y, z, turbine, coord, deflection, flow_field): """Implement current wake velocity model. Args: x ([type]): [description] y ([type]): [description] z ([type]): [description] turbine ([type]): [description] coord ([type]): [description] deflection ([type]): [description] flow_field ([type]): [description] """ # velocity deficit calculation u_deficit, v_deficit, w_deficit = self.wake.velocity_function( x, y, z, turbine, coord, deflection, flow_field) # calculate spanwise and streamwise velocities if needed if hasattr(self.wake.velocity_model, 'calculate_VW'): v_deficit, w_deficit = \ self.wake.velocity_model.calculate_VW( v_deficit, w_deficit, coord, turbine, flow_field, x, y, z ) # correction step if hasattr(self.wake.velocity_model, 'correction_steps'): u_deficit = self.wake.velocity_model.correction_steps( flow_field.u_initial, u_deficit, v_deficit, w_deficit, x, y, turbine, coord) return u_deficit, v_deficit, w_deficit def _compute_turbine_wake_turbulence(self, ambient_TI, coord_ti, turbine_coord, turbine): """Implement current wake turbulence model Args: x ([type]): [description] y ([type]): [description] z ([type]): [description] turbine ([type]): [description] coord ([type]): [description] flow_field ([type]): [description] turb_u_wake ([type]): [description] sorted_map ([type]): [description] Returns: [type]: [description] """ return self.wake.turbulence_function(ambient_TI, coord_ti, turbine_coord, turbine) def _compute_turbine_wake_deflection(self, x, y, z, turbine, coord, flow_field): return self.wake.deflection_function(x, y, z, turbine, coord, flow_field) def _rotated_grid(self, angle, center_of_rotation): """ Rotate the discrete flow field grid. """ xoffset = self.x - center_of_rotation.x1 yoffset = self.y - center_of_rotation.x2 rotated_x = xoffset * \ cosd(angle) - yoffset * \ sind(angle) + center_of_rotation.x1 rotated_y = xoffset * \ sind(angle) + yoffset * \ cosd(angle) + center_of_rotation.x2 return rotated_x, rotated_y, self.z def _rotated_dir(self, angle, center_of_rotation, rotated_map): """ Rotate the discrete flow field grid and turbine map. """ # get new boundaries for the wind farm once rotated x_coord = [] y_coord = [] for coord in rotated_map.coords: x_coord.append(coord.x1) y_coord.append(coord.x2) if self.wake.velocity_model.model_string == 'curl': # re-setup the grid for the curl model xmin = np.min(x_coord) - 2 * self.max_diameter xmax = np.max(x_coord) + 10 * self.max_diameter ymin = np.min(y_coord) - 2 * self.max_diameter ymax = np.max(y_coord) + 2 * self.max_diameter zmin = 0.1 zmax = 6 * self.specified_wind_height # Save these bounds self._xmin = xmin self._xmax = xmax self._ymin = ymin self._ymax = ymax self._zmin = zmin self._zmax = zmax resolution = self.wake.velocity_model.model_grid_resolution self.x, self.y, self.z = self._discretize_gridded_domain( xmin, xmax, ymin, ymax, zmin, zmax, resolution) rotated_x, rotated_y, rotated_z = self._rotated_grid( 0.0, center_of_rotation) else: rotated_x, rotated_y, rotated_z = self._rotated_grid( self.wind_map.grid_wind_direction, center_of_rotation) return rotated_x, rotated_y, rotated_z def _calculate_area_overlap(self, wake_velocities, freestream_velocities, turbine): """ compute wake overlap based on the number of points that are not freestream velocity, i.e. affected by the wake """ count = np.sum(freestream_velocities - wake_velocities <= 0.05) return (turbine.grid_point_count - count) / turbine.grid_point_count # Public methods def set_bounds(self, bounds_to_set=None): """ Calculates the domain bounds for the current wake model. The bounds can be given directly of calculated based on preset extents from the given layout. The bounds consist of the minimum and maximum values in the x-, y-, and z-directions. If the Curl model is used, the predefined bounds are always set. # TODO: describe how the bounds are set based on the wind direction. Args: bounds_to_set (list(float), optional): Values representing the minimum and maximum values for the domain in each direction: [xmin, xmax, ymin, ymax, zmin, zmax]. Defaults to None. """ if self.wake.velocity_model.model_string == 'curl': # For the curl model, bounds are hard coded coords = self.turbine_map.coords x = [coord.x1 for coord in coords] y = [coord.x2 for coord in coords] eps = 0.1 self._xmin = min(x) - 2 * self.max_diameter self._xmax = max(x) + 10 * self.max_diameter self._ymin = min(y) - 2 * self.max_diameter self._ymax = max(y) + 2 * self.max_diameter self._zmin = 0 + eps self._zmax = 6 * self.specified_wind_height elif bounds_to_set is not None: # Set the boundaries self._xmin = bounds_to_set[0] self._xmax = bounds_to_set[1] self._ymin = bounds_to_set[2] self._ymax = bounds_to_set[3] self._zmin = bounds_to_set[4] self._zmax = bounds_to_set[5] else: # Else, if none provided, use a shorter boundary for other models coords = self.turbine_map.coords x = [coord.x1 for coord in coords] y = [coord.x2 for coord in coords] eps = 0.1 # find circular mean of wind directions at turbines wd = sp.stats.circmean( np.array(self.wind_map.turbine_wind_direction) * np.pi / 180) * 180 / np.pi # set bounds based on the mean wind direction to avoid # cutting off wakes near boundaries in visualization if wd < 270 and wd > 90: self._xmin = min(x) - 10 * self.max_diameter else: self._xmin = min(x) - 2 * self.max_diameter if wd <= 90 or wd >= 270: self._xmax = max(x) + 10 * self.max_diameter else: self._xmax = max(x) + 2 * self.max_diameter if wd <= 175 and wd >= 5: self._ymin = min(y) - 5 * self.max_diameter else: self._ymin = min(y) - 2 * self.max_diameter if wd >= 185 and wd <= 355: self._ymax = max(y) + 5 * self.max_diameter else: self._ymax = max(y) + 2 * self.max_diameter self._zmin = 0 + eps self._zmax = 2 * self.specified_wind_height def reinitialize_flow_field(self, wind_shear=None, wind_veer=None, air_density=None, wake=None, turbine_map=None, wind_map=None, with_resolution=None, bounds_to_set=None, specified_wind_height=None): """ Reiniaitilzies the flow field when a parameter needs to be updated. This method allows for changing/updating a variety of flow related parameters. This would typically be used in loops or optimizations where the user is calculating AEP over a wind rose or investigating wind farm performance at different conditions. Args: wind_shear (float, optional): Wind shear coefficient. Defaults to None. wind_veer (float, optional): Amount of veer across the rotor. Defaults to None. air_density (float, optional): Wind farm air density. Defaults to None. wake (:py:class:`~.wake.Wake`, optional): The object containing the model definition for the wake calculation. Defaults to None. turbine_map (:py:obj:`~.turbine_map.TurbineMap`, optional): The object describing the farm layout and turbine location. Defaults to None. wind_map (:py:obj:`~.wind_map.WindMap`, optional): The object describing the atmospheric conditions throughout the farm. Defaults to None. with_resolution (:py:class:`~.utilities.Vec3`, optional): Resolution components to use for the gridded domain in the flow field wake calculation. Defaults to None. bounds_to_set (list(float), optional): Values representing the minimum and maximum values for the domain in each direction: [xmin, xmax, ymin, ymax, zmin, zmax]. Defaults to None. specified_wind_height (float, optional): The focal center of the farm in elevation; this value sets where the given wind speed is set and about where initial velocity profile is applied. Defaults to None. """ # reset the given parameters if turbine_map is not None: self.turbine_map = turbine_map if wind_map is not None: self.wind_map = wind_map if wind_shear is not None: self.wind_shear = wind_shear if wind_veer is not None: self.wind_veer = wind_veer if specified_wind_height is not None: self.specified_wind_height = specified_wind_height if air_density is not None: self.air_density = air_density for turbine in self.turbine_map.turbines: turbine.air_density = self.air_density if wake is not None: self.wake = wake if with_resolution is None: with_resolution = self.wake.velocity_model.model_grid_resolution # initialize derived attributes and constants self.max_diameter = max( [turbine.rotor_diameter for turbine in self.turbine_map.turbines]) # FOR BUG FIX NOTICE THAT THIS ASSUMES THAT THE FIRST TURBINE DETERMINES WIND HEIGHT MAKING # CHANGING IT MOOT # self.specified_wind_height = self.turbine_map.turbines[0].hub_height # Set the domain bounds self.set_bounds(bounds_to_set=bounds_to_set) # reinitialize the flow field self._compute_initialized_domain(with_resolution=with_resolution) # reinitialize the turbines for i, turbine in enumerate(self.turbine_map.turbines): turbine.current_turbulence_intensity = self.wind_map.turbine_turbulence_intensity[ i] turbine.reset_velocities() def calculate_wake(self, no_wake=False, points=None, track_n_upstream_wakes=False): """ Updates the flow field based on turbine activity. This method rotates the turbine farm such that the wind direction is coming from 270 degrees. It then loops over the turbines, updating their velocities, calculating the wake deflection/deficit, and combines the wake with the flow field. Args: no_wake (bool, optional): Flag to enable updating the turbine properties without adding the wake calculation to the freestream flow field. Defaults to *False*. points (list(), optional): An array that contains the x-, y-, and z-coordinates of user-specified points at which the flow field velocity is recorded. Defaults to None. track_n_upstream_wakes (bool, optional): When *True*, will keep track of the number of upstream wakes a turbine is experiencing. Defaults to *False*. """ if points is not None: # add points to flow field grid points self._compute_initialized_domain(points=points) if track_n_upstream_wakes: # keep track of the wakes upstream of each turbine self.wake_list = { turbine: 0 for _, turbine in self.turbine_map.items } # reinitialize the turbines for i, turbine in enumerate(self.turbine_map.turbines): turbine.current_turbulence_intensity = \ self.wind_map.turbine_turbulence_intensity[i] turbine.reset_velocities() # define the center of rotation with reference to 270 deg as center of # flow field x0 = np.mean([np.min(self.x), np.max(self.x)]) y0 = np.mean([np.min(self.y), np.max(self.y)]) center_of_rotation = Vec3(x0, y0, 0) # Rotate the turbines such that they are now in the frame of reference # of the wind direction simplifying computing the wakes and wake overlap rotated_map = self.turbine_map.rotated( self.wind_map.turbine_wind_direction, center_of_rotation) # rotate the discrete grid and turbine map initial_rotated_x, initial_rotated_y, rotated_z = self._rotated_dir( self.wind_map.grid_wind_direction, center_of_rotation, rotated_map) # sort the turbine map sorted_map = rotated_map.sorted_in_x_as_list() # calculate the velocity deficit and wake deflection on the mesh u_wake = np.zeros(np.shape(self.u)) # v_wake = np.zeros(np.shape(self.u)) # w_wake = np.zeros(np.shape(self.u)) # Empty the stored variables of v and w at start, these will be updated # and stored within the loop self.v = np.zeros(np.shape(self.u)) self.w = np.zeros(np.shape(self.u)) rx = np.zeros(len(self.turbine_map.coords)) ry = np.zeros(len(self.turbine_map.coords)) for i, cord in enumerate(self.turbine_map.coords): rx[i], ry[i] = cord.x1prime, cord.x2prime for coord, turbine in sorted_map: xloc, yloc = np.array(rx == coord.x1), np.array(ry == coord.x2) idx = int(np.where(np.logical_and(yloc == True, xloc == True))[0]) if np.unique(self.wind_map.grid_wind_direction).size == 1: # only rotate grid once for homogeneous wind direction rotated_x, rotated_y = initial_rotated_x, initial_rotated_y else: # adjust grid rotation with respect to current turbine for # heterogeneous wind direction wd = self.wind_map.turbine_wind_direction[idx] \ - self.wind_map.grid_wind_direction # for straight wakes, change rx[idx] to initial_rotated_x xoffset = center_of_rotation.x1 - rx[idx] # for straight wakes, change ry[idx] to initial_rotated_y yoffset = center_of_rotation.x2 - ry[idx] y_grid_offset = xoffset * sind(wd) + yoffset * cosd( wd) - yoffset rotated_y = initial_rotated_y - y_grid_offset xoffset = center_of_rotation.x1 - initial_rotated_x yoffset = center_of_rotation.x2 - initial_rotated_y x_grid_offset = xoffset * cosd(wd) - yoffset * sind( wd) - xoffset rotated_x = initial_rotated_x - x_grid_offset # update the turbine based on the velocity at its hub turbine.update_velocities(u_wake, coord, self, rotated_x, rotated_y, rotated_z) # get the wake deflection field deflection = self._compute_turbine_wake_deflection( rotated_x, rotated_y, rotated_z, turbine, coord, self) # get the velocity deficit accounting for the deflection turb_u_wake, turb_v_wake, turb_w_wake = \ self._compute_turbine_velocity_deficit( rotated_x, rotated_y, rotated_z, turbine, coord, deflection, self ) ########### # include turbulence model for the gaussian wake model from # Porte-Agel if 'crespo_hernandez' == self.wake.turbulence_model.model_string \ or self.wake.turbulence_model.model_string == 'ishihara_qian': # compute area overlap of wake on other turbines and update # downstream turbine turbulence intensities for coord_ti, turbine_ti in sorted_map: xloc, yloc = np.array(rx == coord_ti.x1), np.array( ry == coord_ti.x2) idx = int( np.where(np.logical_and(yloc == True, xloc == True))[0]) if coord_ti.x1 > coord.x1 and np.abs( coord.x2 - coord_ti.x2) < 2 * turbine.rotor_diameter: # only assess the effects of the current wake freestream_velocities = \ turbine_ti.calculate_swept_area_velocities( self.u_initial, coord_ti, rotated_x, rotated_y, rotated_z ) wake_velocities = \ turbine_ti.calculate_swept_area_velocities( self.u_initial - turb_u_wake, coord_ti, rotated_x, rotated_y, rotated_z ) area_overlap = self._calculate_area_overlap( wake_velocities, freestream_velocities, turbine) # placeholder for TI/stability influence on how far # wakes (and wake added TI) propagate downstream downstream_influence_length = \ 15 * turbine.rotor_diameter if area_overlap > 0.0 and coord_ti.x1 \ <= downstream_influence_length + coord.x1: ##### Call wake turbulence model # wake.turbulence_function(inputs) ti_calculation = \ self._compute_turbine_wake_turbulence( self.wind_map. turbine_turbulence_intensity[idx], coord_ti, coord, turbine ) # multiply by area overlap ti_added = area_overlap * ti_calculation turbine_ti.current_turbulence_intensity = np.sqrt( ti_added**2 + turbine.current_turbulence_intensity**2) if track_n_upstream_wakes: # increment by one for each upstream wake self.wake_list[turbine_ti] += 1 # combine this turbine's wake into the full wake field if not no_wake: u_wake = self.wake.combination_function(u_wake, turb_u_wake) if self.wake.velocity_model.model_string == 'curl': self.v = turb_v_wake self.w = turb_w_wake else: # v_wake = (v_wake + turb_v_wake) # w_wake = (w_wake + turb_w_wake) self.v = self.wake.combination_function(turb_v_wake, self.v) self.w = self.wake.combination_function(turb_w_wake, self.w) # apply the velocity deficit field to the freestream if not no_wake: self.u = self.u_initial - u_wake # self.v = self.v_initial + v_wake # self.w = self.w_initial + w_wake # rotate the grid if it is curl if self.wake.velocity_model.model_string == 'curl': self.x, self.y, self.z = self._rotated_grid( -1 * self.wind_map.grid_wind_direction, center_of_rotation) # Getters & Setters @property def domain_bounds(self): """ The minimum and maximum values of the bounds of the flow field domain. Returns: float, float, float, float, float, float: minimum-x, maximum-x, minimum-y, maximum-y, minimum-z, maximum-z """ return self._xmin, self._xmax, self._ymin, self._ymax, self._zmin, self._zmax
44.622951
118
0.561689
578f06b179733750c010392cee2c16b10cc0785f
12,963
py
Python
tests/commands/test_commands.py
Bilel2038/bigchaindb
b1c34523edc96ea1f0acdf4c1d3a7a5ef36e0116
[ "Apache-2.0" ]
null
null
null
tests/commands/test_commands.py
Bilel2038/bigchaindb
b1c34523edc96ea1f0acdf4c1d3a7a5ef36e0116
[ "Apache-2.0" ]
null
null
null
tests/commands/test_commands.py
Bilel2038/bigchaindb
b1c34523edc96ea1f0acdf4c1d3a7a5ef36e0116
[ "Apache-2.0" ]
null
null
null
import json from unittest.mock import Mock, patch from argparse import Namespace import pytest @pytest.mark.tendermint def test_make_sure_we_dont_remove_any_command(): # thanks to: http://stackoverflow.com/a/18161115/597097 from bigchaindb.commands.bigchaindb import create_parser parser = create_parser() assert parser.parse_args(['configure', 'localmongodb']).command assert parser.parse_args(['show-config']).command assert parser.parse_args(['init']).command assert parser.parse_args(['drop']).command assert parser.parse_args(['start']).command assert parser.parse_args(['upsert-validator', 'TEMP_PUB_KEYPAIR', '10']).command @pytest.mark.tendermint @patch('bigchaindb.commands.utils.start') def test_main_entrypoint(mock_start): from bigchaindb.commands.bigchaindb import main main() assert mock_start.called def test_bigchain_run_start(mock_run_configure, mock_processes_start, mock_db_init_with_existing_db, mocked_setup_logging): from bigchaindb import config from bigchaindb.commands.bigchaindb import run_start args = Namespace(config=None, yes=True, skip_initialize_database=False) run_start(args) mocked_setup_logging.assert_called_once_with(user_log_config=config['log']) # TODO Please beware, that if debugging, the "-s" switch for pytest will # interfere with capsys. # See related issue: https://github.com/pytest-dev/pytest/issues/128 @pytest.mark.tendermint @pytest.mark.usefixtures('ignore_local_config_file') def test_bigchain_show_config(capsys): from bigchaindb.commands.bigchaindb import run_show_config args = Namespace(config=None) _, _ = capsys.readouterr() run_show_config(args) output_config = json.loads(capsys.readouterr()[0]) # Note: This test passed previously because we were always # using the default configuration parameters, but since we # are running with docker-compose now and expose parameters like # BIGCHAINDB_SERVER_BIND, BIGCHAINDB_WSSERVER_HOST, BIGCHAINDB_WSSERVER_ADVERTISED_HOST # the default comparison fails i.e. when config is imported at the beginning the # dict returned is different that what is expected after run_show_config # and run_show_config updates the bigchaindb.config from bigchaindb import config del config['CONFIGURED'] assert output_config == config @pytest.mark.tendermint def test_bigchain_run_init_when_db_exists(mocker, capsys): from bigchaindb.commands.bigchaindb import run_init from bigchaindb.common.exceptions import DatabaseAlreadyExists init_db_mock = mocker.patch( 'bigchaindb.commands.bigchaindb.schema.init_database', autospec=True, spec_set=True, ) init_db_mock.side_effect = DatabaseAlreadyExists args = Namespace(config=None) run_init(args) output_message = capsys.readouterr()[1] print(output_message) assert output_message == ( 'The database already exists.\n' 'If you wish to re-initialize it, first drop it.\n' ) @pytest.mark.tendermint def test__run_init(mocker): from bigchaindb.commands.bigchaindb import _run_init bigchain_mock = mocker.patch( 'bigchaindb.commands.bigchaindb.bigchaindb.BigchainDB') init_db_mock = mocker.patch( 'bigchaindb.commands.bigchaindb.schema.init_database', autospec=True, spec_set=True, ) _run_init() bigchain_mock.assert_called_once_with() init_db_mock.assert_called_once_with( connection=bigchain_mock.return_value.connection) @pytest.mark.tendermint @patch('bigchaindb.backend.schema.drop_database') def test_drop_db_when_assumed_yes(mock_db_drop): from bigchaindb.commands.bigchaindb import run_drop args = Namespace(config=None, yes=True) run_drop(args) assert mock_db_drop.called @pytest.mark.tendermint @patch('bigchaindb.backend.schema.drop_database') def test_drop_db_when_interactive_yes(mock_db_drop, monkeypatch): from bigchaindb.commands.bigchaindb import run_drop args = Namespace(config=None, yes=False) monkeypatch.setattr( 'bigchaindb.commands.bigchaindb.input_on_stderr', lambda x: 'y') run_drop(args) assert mock_db_drop.called @pytest.mark.tendermint @patch('bigchaindb.backend.schema.drop_database') def test_drop_db_when_db_does_not_exist(mock_db_drop, capsys): from bigchaindb import config from bigchaindb.commands.bigchaindb import run_drop from bigchaindb.common.exceptions import DatabaseDoesNotExist args = Namespace(config=None, yes=True) mock_db_drop.side_effect = DatabaseDoesNotExist run_drop(args) output_message = capsys.readouterr()[1] assert output_message == "Cannot drop '{name}'. The database does not exist.\n".format( name=config['database']['name']) @pytest.mark.tendermint @patch('bigchaindb.backend.schema.drop_database') def test_drop_db_does_not_drop_when_interactive_no(mock_db_drop, monkeypatch): from bigchaindb.commands.bigchaindb import run_drop args = Namespace(config=None, yes=False) monkeypatch.setattr( 'bigchaindb.commands.bigchaindb.input_on_stderr', lambda x: 'n') run_drop(args) assert not mock_db_drop.called # TODO Beware if you are putting breakpoints in there, and using the '-s' # switch with pytest. It will just hang. Seems related to the monkeypatching of # input_on_stderr. @pytest.mark.tendermint def test_run_configure_when_config_does_not_exist(monkeypatch, mock_write_config, mock_generate_key_pair, mock_bigchaindb_backup_config): from bigchaindb.commands.bigchaindb import run_configure monkeypatch.setattr('os.path.exists', lambda path: False) monkeypatch.setattr('builtins.input', lambda: '\n') args = Namespace(config=None, backend='localmongodb', yes=True) return_value = run_configure(args) assert return_value is None @pytest.mark.tendermint def test_run_configure_when_config_does_exist(monkeypatch, mock_write_config, mock_generate_key_pair, mock_bigchaindb_backup_config): value = {} def mock_write_config(newconfig, filename=None): value['return'] = newconfig from bigchaindb.commands.bigchaindb import run_configure monkeypatch.setattr('os.path.exists', lambda path: True) monkeypatch.setattr('builtins.input', lambda: '\n') monkeypatch.setattr( 'bigchaindb.config_utils.write_config', mock_write_config) args = Namespace(config=None, yes=None) run_configure(args) assert value == {} @pytest.mark.skip @pytest.mark.tendermint @pytest.mark.parametrize('backend', ( 'localmongodb', )) def test_run_configure_with_backend(backend, monkeypatch, mock_write_config): import bigchaindb from bigchaindb.commands.bigchaindb import run_configure value = {} def mock_write_config(new_config, filename=None): value['return'] = new_config monkeypatch.setattr('os.path.exists', lambda path: False) monkeypatch.setattr('builtins.input', lambda: '\n') monkeypatch.setattr('bigchaindb.config_utils.write_config', mock_write_config) args = Namespace(config=None, backend=backend, yes=True) expected_config = bigchaindb.config run_configure(args) # update the expected config with the correct backend and keypair backend_conf = getattr(bigchaindb, '_database_' + backend) expected_config.update({'database': backend_conf, 'keypair': value['return']['keypair']}) assert value['return'] == expected_config def test_run_start_when_db_already_exists(mocker, monkeypatch, run_start_args, mocked_setup_logging): from bigchaindb import config from bigchaindb.commands.bigchaindb import run_start from bigchaindb.common.exceptions import DatabaseAlreadyExists mocked_start = mocker.patch('bigchaindb.processes.start') def mock_run_init(): raise DatabaseAlreadyExists() monkeypatch.setattr('builtins.input', lambda: '\x03') monkeypatch.setattr( 'bigchaindb.commands.bigchaindb._run_init', mock_run_init) run_start(run_start_args) mocked_setup_logging.assert_called_once_with(user_log_config=config['log']) assert mocked_start.called @pytest.mark.tendermint @patch('argparse.ArgumentParser.parse_args') @patch('bigchaindb.commands.utils.base_parser') @patch('bigchaindb.commands.utils.start') def test_calling_main(start_mock, base_parser_mock, parse_args_mock, monkeypatch): from bigchaindb.commands.bigchaindb import main argparser_mock = Mock() parser = Mock() subparsers = Mock() subsubparsers = Mock() subparsers.add_parser.return_value = subsubparsers parser.add_subparsers.return_value = subparsers argparser_mock.return_value = parser monkeypatch.setattr('argparse.ArgumentParser', argparser_mock) main() assert argparser_mock.called is True parser.add_subparsers.assert_called_with(title='Commands', dest='command') subparsers.add_parser.assert_any_call('configure', help='Prepare the config file.') subparsers.add_parser.assert_any_call('show-config', help='Show the current ' 'configuration') subparsers.add_parser.assert_any_call('init', help='Init the database') subparsers.add_parser.assert_any_call('drop', help='Drop the database') subparsers.add_parser.assert_any_call('start', help='Start BigchainDB') assert start_mock.called is True @patch('bigchaindb.config_utils.autoconfigure') @patch('bigchaindb.commands.bigchaindb.run_recover') @patch('bigchaindb.start.start') def test_recover_db_on_start(mock_autoconfigure, mock_run_recover, mock_start, mocked_setup_logging): from bigchaindb.commands.bigchaindb import run_start args = Namespace(config=None, yes=True, skip_initialize_database=False) run_start(args) assert mock_run_recover.called assert mock_start.called @pytest.mark.tendermint @pytest.mark.bdb def test_run_recover(b, alice, bob): from bigchaindb.commands.bigchaindb import run_recover from bigchaindb.models import Transaction from bigchaindb.lib import Block, PreCommitState from bigchaindb.backend.query import PRE_COMMIT_ID from bigchaindb.backend import query tx1 = Transaction.create([alice.public_key], [([alice.public_key], 1)], asset={'cycle': 'hero'}, metadata={'name': 'hohenheim'}) \ .sign([alice.private_key]) tx2 = Transaction.create([bob.public_key], [([bob.public_key], 1)], asset={'cycle': 'hero'}, metadata={'name': 'hohenheim'}) \ .sign([bob.private_key]) # store the transactions b.store_bulk_transactions([tx1, tx2]) # create a random block block8 = Block(app_hash='random_app_hash1', height=8, transactions=['txid_doesnt_matter'])._asdict() b.store_block(block8) # create the next block block9 = Block(app_hash='random_app_hash1', height=9, transactions=[tx1.id])._asdict() b.store_block(block9) # create a pre_commit state which is ahead of the commit state pre_commit_state = PreCommitState(commit_id=PRE_COMMIT_ID, height=10, transactions=[tx2.id])._asdict() b.store_pre_commit_state(pre_commit_state) run_recover(b) assert not query.get_transaction(b.connection, tx2.id) # Helper class MockResponse(): def __init__(self, height): self.height = height def json(self): return {'result': {'latest_block_height': self.height}} @patch('bigchaindb.config_utils.autoconfigure') @patch('bigchaindb.backend.query.store_validator_update') @pytest.mark.tendermint def test_upsert_validator(mock_autoconfigure, mock_store_validator_update): from bigchaindb.commands.bigchaindb import run_upsert_validator args = Namespace(public_key='CJxdItf4lz2PwEf4SmYNAu/c/VpmX39JEgC5YpH7fxg=', power='10', config={}) run_upsert_validator(args) assert mock_store_validator_update.called
36.515493
91
0.691198
5517c96888bdad40ff7b0b670f9b567850c3d50d
113,994
py
Python
sdk/storage/azure-storage-file-datalake/azure/storage/filedatalake/_generated/operations/_path_operations.py
rsdoherty/azure-sdk-for-python
6bba5326677468e6660845a703686327178bb7b1
[ "MIT" ]
207
2017-11-29T06:59:41.000Z
2022-03-31T10:00:53.000Z
sdk/storage/azure-storage-file-datalake/azure/storage/filedatalake/_generated/operations/_path_operations.py
rsdoherty/azure-sdk-for-python
6bba5326677468e6660845a703686327178bb7b1
[ "MIT" ]
4,061
2017-10-27T23:19:56.000Z
2022-03-31T23:18:30.000Z
sdk/storage/azure-storage-file-datalake/azure/storage/filedatalake/_generated/operations/_path_operations.py
rsdoherty/azure-sdk-for-python
6bba5326677468e6660845a703686327178bb7b1
[ "MIT" ]
802
2017-10-11T17:36:26.000Z
2022-03-31T22:24:32.000Z
# 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. # -------------------------------------------------------------------------- import datetime from typing import TYPE_CHECKING import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import HttpRequest, HttpResponse from .. import models as _models if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from typing import Any, Callable, Dict, Generic, IO, Optional, TypeVar, Union T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] class PathOperations(object): """PathOperations operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.storage.filedatalake.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer): self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config def create( self, request_id_parameter=None, # type: Optional[str] timeout=None, # type: Optional[int] resource=None, # type: Optional[Union[str, "_models.PathResourceType"]] continuation=None, # type: Optional[str] mode=None, # type: Optional[Union[str, "_models.PathRenameMode"]] rename_source=None, # type: Optional[str] source_lease_id=None, # type: Optional[str] properties=None, # type: Optional[str] permissions=None, # type: Optional[str] umask=None, # type: Optional[str] path_http_headers=None, # type: Optional["_models.PathHTTPHeaders"] lease_access_conditions=None, # type: Optional["_models.LeaseAccessConditions"] modified_access_conditions=None, # type: Optional["_models.ModifiedAccessConditions"] source_modified_access_conditions=None, # type: Optional["_models.SourceModifiedAccessConditions"] **kwargs # type: Any ): # type: (...) -> None """Create File | Create Directory | Rename File | Rename Directory. Create or rename a file or directory. By default, the destination is overwritten and if the destination already exists and has a lease the lease is broken. This operation supports conditional HTTP requests. For more information, see `Specifying Conditional Headers for Blob Service Operations <https://docs.microsoft.com/en-us/rest/api/storageservices/specifying- conditional-headers-for-blob-service-operations>`_. To fail if the destination already exists, use a conditional request with If-None-Match: "*". :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. :type request_id_parameter: str :param timeout: The timeout parameter is expressed in seconds. For more information, see :code:`<a href="https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/setting- timeouts-for-blob-service-operations">Setting Timeouts for Blob Service Operations.</a>`. :type timeout: int :param resource: Required only for Create File and Create Directory. The value must be "file" or "directory". :type resource: str or ~azure.storage.filedatalake.models.PathResourceType :param continuation: Optional. When deleting a directory, the number of paths that are deleted with each invocation is limited. If the number of paths to be deleted exceeds this limit, a continuation token is returned in this response header. When a continuation token is returned in the response, it must be specified in a subsequent invocation of the delete operation to continue deleting the directory. :type continuation: str :param mode: Optional. Valid only when namespace is enabled. This parameter determines the behavior of the rename operation. The value must be "legacy" or "posix", and the default value will be "posix". :type mode: str or ~azure.storage.filedatalake.models.PathRenameMode :param rename_source: An optional file or directory to be renamed. The value must have the following format: "/{filesystem}/{path}". If "x-ms-properties" is specified, the properties will overwrite the existing properties; otherwise, the existing properties will be preserved. This value must be a URL percent-encoded string. Note that the string may only contain ASCII characters in the ISO-8859-1 character set. :type rename_source: str :param source_lease_id: A lease ID for the source path. If specified, the source path must have an active lease and the lease ID must match. :type source_lease_id: str :param properties: Optional. User-defined properties to be stored with the filesystem, in the format of a comma-separated list of name and value pairs "n1=v1, n2=v2, ...", where each value is a base64 encoded string. Note that the string may only contain ASCII characters in the ISO-8859-1 character set. If the filesystem exists, any properties not included in the list will be removed. All properties are removed if the header is omitted. To merge new and existing properties, first get all existing properties and the current E-Tag, then make a conditional request with the E-Tag and include values for all properties. :type properties: str :param permissions: Optional and only valid if Hierarchical Namespace is enabled for the account. Sets POSIX access permissions for the file owner, the file owning group, and others. Each class may be granted read, write, or execute permission. The sticky bit is also supported. Both symbolic (rwxrw-rw-) and 4-digit octal notation (e.g. 0766) are supported. :type permissions: str :param umask: Optional and only valid if Hierarchical Namespace is enabled for the account. When creating a file or directory and the parent folder does not have a default ACL, the umask restricts the permissions of the file or directory to be created. The resulting permission is given by p bitwise and not u, where p is the permission and u is the umask. For example, if p is 0777 and u is 0057, then the resulting permission is 0720. The default permission is 0777 for a directory and 0666 for a file. The default umask is 0027. The umask must be specified in 4-digit octal notation (e.g. 0766). :type umask: str :param path_http_headers: Parameter group. :type path_http_headers: ~azure.storage.filedatalake.models.PathHTTPHeaders :param lease_access_conditions: Parameter group. :type lease_access_conditions: ~azure.storage.filedatalake.models.LeaseAccessConditions :param modified_access_conditions: Parameter group. :type modified_access_conditions: ~azure.storage.filedatalake.models.ModifiedAccessConditions :param source_modified_access_conditions: Parameter group. :type source_modified_access_conditions: ~azure.storage.filedatalake.models.SourceModifiedAccessConditions :keyword callable cls: A custom type or function that will be passed the direct response :return: None, or the result of cls(response) :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _cache_control = None _content_encoding = None _content_language = None _content_disposition = None _content_type = None _lease_id = None _if_match = None _if_none_match = None _if_modified_since = None _if_unmodified_since = None _source_if_match = None _source_if_none_match = None _source_if_modified_since = None _source_if_unmodified_since = None if lease_access_conditions is not None: _lease_id = lease_access_conditions.lease_id if modified_access_conditions is not None: _if_match = modified_access_conditions.if_match _if_none_match = modified_access_conditions.if_none_match _if_modified_since = modified_access_conditions.if_modified_since _if_unmodified_since = modified_access_conditions.if_unmodified_since if path_http_headers is not None: _cache_control = path_http_headers.cache_control _content_encoding = path_http_headers.content_encoding _content_language = path_http_headers.content_language _content_disposition = path_http_headers.content_disposition _content_type = path_http_headers.content_type if source_modified_access_conditions is not None: _source_if_match = source_modified_access_conditions.source_if_match _source_if_none_match = source_modified_access_conditions.source_if_none_match _source_if_modified_since = source_modified_access_conditions.source_if_modified_since _source_if_unmodified_since = source_modified_access_conditions.source_if_unmodified_since accept = "application/json" # Construct URL url = self.create.metadata['url'] # type: ignore path_format_arguments = { 'url': self._serialize.url("self._config.url", self._config.url, 'str', skip_quote=True), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] if timeout is not None: query_parameters['timeout'] = self._serialize.query("timeout", timeout, 'int', minimum=0) if resource is not None: query_parameters['resource'] = self._serialize.query("resource", resource, 'str') if continuation is not None: query_parameters['continuation'] = self._serialize.query("continuation", continuation, 'str') if mode is not None: query_parameters['mode'] = self._serialize.query("mode", mode, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] if request_id_parameter is not None: header_parameters['x-ms-client-request-id'] = self._serialize.header("request_id_parameter", request_id_parameter, 'str') header_parameters['x-ms-version'] = self._serialize.header("self._config.version", self._config.version, 'str') if _cache_control is not None: header_parameters['x-ms-cache-control'] = self._serialize.header("cache_control", _cache_control, 'str') if _content_encoding is not None: header_parameters['x-ms-content-encoding'] = self._serialize.header("content_encoding", _content_encoding, 'str') if _content_language is not None: header_parameters['x-ms-content-language'] = self._serialize.header("content_language", _content_language, 'str') if _content_disposition is not None: header_parameters['x-ms-content-disposition'] = self._serialize.header("content_disposition", _content_disposition, 'str') if _content_type is not None: header_parameters['x-ms-content-type'] = self._serialize.header("content_type", _content_type, 'str') if rename_source is not None: header_parameters['x-ms-rename-source'] = self._serialize.header("rename_source", rename_source, 'str') if _lease_id is not None: header_parameters['x-ms-lease-id'] = self._serialize.header("lease_id", _lease_id, 'str') if source_lease_id is not None: header_parameters['x-ms-source-lease-id'] = self._serialize.header("source_lease_id", source_lease_id, 'str') if properties is not None: header_parameters['x-ms-properties'] = self._serialize.header("properties", properties, 'str') if permissions is not None: header_parameters['x-ms-permissions'] = self._serialize.header("permissions", permissions, 'str') if umask is not None: header_parameters['x-ms-umask'] = self._serialize.header("umask", umask, 'str') if _if_match is not None: header_parameters['If-Match'] = self._serialize.header("if_match", _if_match, 'str') if _if_none_match is not None: header_parameters['If-None-Match'] = self._serialize.header("if_none_match", _if_none_match, 'str') if _if_modified_since is not None: header_parameters['If-Modified-Since'] = self._serialize.header("if_modified_since", _if_modified_since, 'rfc-1123') if _if_unmodified_since is not None: header_parameters['If-Unmodified-Since'] = self._serialize.header("if_unmodified_since", _if_unmodified_since, 'rfc-1123') if _source_if_match is not None: header_parameters['x-ms-source-if-match'] = self._serialize.header("source_if_match", _source_if_match, 'str') if _source_if_none_match is not None: header_parameters['x-ms-source-if-none-match'] = self._serialize.header("source_if_none_match", _source_if_none_match, 'str') if _source_if_modified_since is not None: header_parameters['x-ms-source-if-modified-since'] = self._serialize.header("source_if_modified_since", _source_if_modified_since, 'rfc-1123') if _source_if_unmodified_since is not None: header_parameters['x-ms-source-if-unmodified-since'] = self._serialize.header("source_if_unmodified_since", _source_if_unmodified_since, 'rfc-1123') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.put(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [201]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.StorageError, response) raise HttpResponseError(response=response, model=error) response_headers = {} response_headers['Date']=self._deserialize('rfc-1123', response.headers.get('Date')) response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) response_headers['Last-Modified']=self._deserialize('rfc-1123', response.headers.get('Last-Modified')) response_headers['x-ms-request-id']=self._deserialize('str', response.headers.get('x-ms-request-id')) response_headers['x-ms-version']=self._deserialize('str', response.headers.get('x-ms-version')) response_headers['x-ms-continuation']=self._deserialize('str', response.headers.get('x-ms-continuation')) response_headers['Content-Length']=self._deserialize('long', response.headers.get('Content-Length')) if cls: return cls(pipeline_response, None, response_headers) create.metadata = {'url': '/{filesystem}/{path}'} # type: ignore def update( self, action, # type: Union[str, "_models.PathUpdateAction"] mode, # type: Union[str, "_models.PathSetAccessControlRecursiveMode"] body, # type: IO request_id_parameter=None, # type: Optional[str] timeout=None, # type: Optional[int] max_records=None, # type: Optional[int] continuation=None, # type: Optional[str] force_flag=None, # type: Optional[bool] position=None, # type: Optional[int] retain_uncommitted_data=None, # type: Optional[bool] close=None, # type: Optional[bool] content_length=None, # type: Optional[int] properties=None, # type: Optional[str] owner=None, # type: Optional[str] group=None, # type: Optional[str] permissions=None, # type: Optional[str] acl=None, # type: Optional[str] path_http_headers=None, # type: Optional["_models.PathHTTPHeaders"] lease_access_conditions=None, # type: Optional["_models.LeaseAccessConditions"] modified_access_conditions=None, # type: Optional["_models.ModifiedAccessConditions"] **kwargs # type: Any ): # type: (...) -> Optional["_models.SetAccessControlRecursiveResponse"] """Append Data | Flush Data | Set Properties | Set Access Control. Uploads data to be appended to a file, flushes (writes) previously uploaded data to a file, sets properties for a file or directory, or sets access control for a file or directory. Data can only be appended to a file. Concurrent writes to the same file using multiple clients are not supported. This operation supports conditional HTTP requests. For more information, see `Specifying Conditional Headers for Blob Service Operations <https://docs.microsoft.com/en- us/rest/api/storageservices/specifying-conditional-headers-for-blob-service-operations>`_. :param action: The action must be "append" to upload data to be appended to a file, "flush" to flush previously uploaded data to a file, "setProperties" to set the properties of a file or directory, "setAccessControl" to set the owner, group, permissions, or access control list for a file or directory, or "setAccessControlRecursive" to set the access control list for a directory recursively. Note that Hierarchical Namespace must be enabled for the account in order to use access control. Also note that the Access Control List (ACL) includes permissions for the owner, owning group, and others, so the x-ms-permissions and x-ms-acl request headers are mutually exclusive. :type action: str or ~azure.storage.filedatalake.models.PathUpdateAction :param mode: Mode "set" sets POSIX access control rights on files and directories, "modify" modifies one or more POSIX access control rights that pre-exist on files and directories, "remove" removes one or more POSIX access control rights that were present earlier on files and directories. :type mode: str or ~azure.storage.filedatalake.models.PathSetAccessControlRecursiveMode :param body: Initial data. :type body: IO :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. :type request_id_parameter: str :param timeout: The timeout parameter is expressed in seconds. For more information, see :code:`<a href="https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/setting- timeouts-for-blob-service-operations">Setting Timeouts for Blob Service Operations.</a>`. :type timeout: int :param max_records: Optional. Valid for "SetAccessControlRecursive" operation. It specifies the maximum number of files or directories on which the acl change will be applied. If omitted or greater than 2,000, the request will process up to 2,000 items. :type max_records: int :param continuation: Optional. The number of paths processed with each invocation is limited. If the number of paths to be processed exceeds this limit, a continuation token is returned in the response header x-ms-continuation. When a continuation token is returned in the response, it must be percent-encoded and specified in a subsequent invocation of setAcessControlRecursive operation. :type continuation: str :param force_flag: Optional. Valid for "SetAccessControlRecursive" operation. If set to false, the operation will terminate quickly on encountering user errors (4XX). If true, the operation will ignore user errors and proceed with the operation on other sub-entities of the directory. Continuation token will only be returned when forceFlag is true in case of user errors. If not set the default value is false for this. :type force_flag: bool :param position: This parameter allows the caller to upload data in parallel and control the order in which it is appended to the file. It is required when uploading data to be appended to the file and when flushing previously uploaded data to the file. The value must be the position where the data is to be appended. Uploaded data is not immediately flushed, or written, to the file. To flush, the previously uploaded data must be contiguous, the position parameter must be specified and equal to the length of the file after all data has been written, and there must not be a request entity body included with the request. :type position: long :param retain_uncommitted_data: Valid only for flush operations. If "true", uncommitted data is retained after the flush operation completes; otherwise, the uncommitted data is deleted after the flush operation. The default is false. Data at offsets less than the specified position are written to the file when flush succeeds, but this optional parameter allows data after the flush position to be retained for a future flush operation. :type retain_uncommitted_data: bool :param close: Azure Storage Events allow applications to receive notifications when files change. When Azure Storage Events are enabled, a file changed event is raised. This event has a property indicating whether this is the final change to distinguish the difference between an intermediate flush to a file stream and the final close of a file stream. The close query parameter is valid only when the action is "flush" and change notifications are enabled. If the value of close is "true" and the flush operation completes successfully, the service raises a file change notification with a property indicating that this is the final update (the file stream has been closed). If "false" a change notification is raised indicating the file has changed. The default is false. This query parameter is set to true by the Hadoop ABFS driver to indicate that the file stream has been closed.". :type close: bool :param content_length: Required for "Append Data" and "Flush Data". Must be 0 for "Flush Data". Must be the length of the request content in bytes for "Append Data". :type content_length: long :param properties: Optional. User-defined properties to be stored with the filesystem, in the format of a comma-separated list of name and value pairs "n1=v1, n2=v2, ...", where each value is a base64 encoded string. Note that the string may only contain ASCII characters in the ISO-8859-1 character set. If the filesystem exists, any properties not included in the list will be removed. All properties are removed if the header is omitted. To merge new and existing properties, first get all existing properties and the current E-Tag, then make a conditional request with the E-Tag and include values for all properties. :type properties: str :param owner: Optional. The owner of the blob or directory. :type owner: str :param group: Optional. The owning group of the blob or directory. :type group: str :param permissions: Optional and only valid if Hierarchical Namespace is enabled for the account. Sets POSIX access permissions for the file owner, the file owning group, and others. Each class may be granted read, write, or execute permission. The sticky bit is also supported. Both symbolic (rwxrw-rw-) and 4-digit octal notation (e.g. 0766) are supported. :type permissions: str :param acl: Sets POSIX access control rights on files and directories. The value is a comma- separated list of access control entries. Each access control entry (ACE) consists of a scope, a type, a user or group identifier, and permissions in the format "[scope:][type]:[id]:[permissions]". :type acl: str :param path_http_headers: Parameter group. :type path_http_headers: ~azure.storage.filedatalake.models.PathHTTPHeaders :param lease_access_conditions: Parameter group. :type lease_access_conditions: ~azure.storage.filedatalake.models.LeaseAccessConditions :param modified_access_conditions: Parameter group. :type modified_access_conditions: ~azure.storage.filedatalake.models.ModifiedAccessConditions :keyword callable cls: A custom type or function that will be passed the direct response :return: SetAccessControlRecursiveResponse, or the result of cls(response) :rtype: ~azure.storage.filedatalake.models.SetAccessControlRecursiveResponse or None :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.SetAccessControlRecursiveResponse"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _content_md5 = None _lease_id = None _cache_control = None _content_type = None _content_disposition = None _content_encoding = None _content_language = None _if_match = None _if_none_match = None _if_modified_since = None _if_unmodified_since = None if lease_access_conditions is not None: _lease_id = lease_access_conditions.lease_id if modified_access_conditions is not None: _if_match = modified_access_conditions.if_match _if_none_match = modified_access_conditions.if_none_match _if_modified_since = modified_access_conditions.if_modified_since _if_unmodified_since = modified_access_conditions.if_unmodified_since if path_http_headers is not None: _content_md5 = path_http_headers.content_md5 _cache_control = path_http_headers.cache_control _content_type = path_http_headers.content_type _content_disposition = path_http_headers.content_disposition _content_encoding = path_http_headers.content_encoding _content_language = path_http_headers.content_language content_type = kwargs.pop("content_type", "application/octet-stream") accept = "application/json" # Construct URL url = self.update.metadata['url'] # type: ignore path_format_arguments = { 'url': self._serialize.url("self._config.url", self._config.url, 'str', skip_quote=True), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] if timeout is not None: query_parameters['timeout'] = self._serialize.query("timeout", timeout, 'int', minimum=0) query_parameters['action'] = self._serialize.query("action", action, 'str') if max_records is not None: query_parameters['maxRecords'] = self._serialize.query("max_records", max_records, 'int', minimum=1) if continuation is not None: query_parameters['continuation'] = self._serialize.query("continuation", continuation, 'str') query_parameters['mode'] = self._serialize.query("mode", mode, 'str') if force_flag is not None: query_parameters['forceFlag'] = self._serialize.query("force_flag", force_flag, 'bool') if position is not None: query_parameters['position'] = self._serialize.query("position", position, 'long') if retain_uncommitted_data is not None: query_parameters['retainUncommittedData'] = self._serialize.query("retain_uncommitted_data", retain_uncommitted_data, 'bool') if close is not None: query_parameters['close'] = self._serialize.query("close", close, 'bool') # Construct headers header_parameters = {} # type: Dict[str, Any] if request_id_parameter is not None: header_parameters['x-ms-client-request-id'] = self._serialize.header("request_id_parameter", request_id_parameter, 'str') header_parameters['x-ms-version'] = self._serialize.header("self._config.version", self._config.version, 'str') if content_length is not None: header_parameters['Content-Length'] = self._serialize.header("content_length", content_length, 'long', minimum=0) if _content_md5 is not None: header_parameters['x-ms-content-md5'] = self._serialize.header("content_md5", _content_md5, 'bytearray') if _lease_id is not None: header_parameters['x-ms-lease-id'] = self._serialize.header("lease_id", _lease_id, 'str') if _cache_control is not None: header_parameters['x-ms-cache-control'] = self._serialize.header("cache_control", _cache_control, 'str') if _content_type is not None: header_parameters['x-ms-content-type'] = self._serialize.header("content_type", _content_type, 'str') if _content_disposition is not None: header_parameters['x-ms-content-disposition'] = self._serialize.header("content_disposition", _content_disposition, 'str') if _content_encoding is not None: header_parameters['x-ms-content-encoding'] = self._serialize.header("content_encoding", _content_encoding, 'str') if _content_language is not None: header_parameters['x-ms-content-language'] = self._serialize.header("content_language", _content_language, 'str') if properties is not None: header_parameters['x-ms-properties'] = self._serialize.header("properties", properties, 'str') if owner is not None: header_parameters['x-ms-owner'] = self._serialize.header("owner", owner, 'str') if group is not None: header_parameters['x-ms-group'] = self._serialize.header("group", group, 'str') if permissions is not None: header_parameters['x-ms-permissions'] = self._serialize.header("permissions", permissions, 'str') if acl is not None: header_parameters['x-ms-acl'] = self._serialize.header("acl", acl, 'str') if _if_match is not None: header_parameters['If-Match'] = self._serialize.header("if_match", _if_match, 'str') if _if_none_match is not None: header_parameters['If-None-Match'] = self._serialize.header("if_none_match", _if_none_match, 'str') if _if_modified_since is not None: header_parameters['If-Modified-Since'] = self._serialize.header("if_modified_since", _if_modified_since, 'rfc-1123') if _if_unmodified_since is not None: header_parameters['If-Unmodified-Since'] = self._serialize.header("if_unmodified_since", _if_unmodified_since, 'rfc-1123') header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content_kwargs['stream_content'] = body request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.StorageError, response) raise HttpResponseError(response=response, model=error) response_headers = {} deserialized = None if response.status_code == 200: response_headers['Date']=self._deserialize('rfc-1123', response.headers.get('Date')) response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) response_headers['Last-Modified']=self._deserialize('rfc-1123', response.headers.get('Last-Modified')) response_headers['Accept-Ranges']=self._deserialize('str', response.headers.get('Accept-Ranges')) response_headers['Cache-Control']=self._deserialize('str', response.headers.get('Cache-Control')) response_headers['Content-Disposition']=self._deserialize('str', response.headers.get('Content-Disposition')) response_headers['Content-Encoding']=self._deserialize('str', response.headers.get('Content-Encoding')) response_headers['Content-Language']=self._deserialize('str', response.headers.get('Content-Language')) response_headers['Content-Length']=self._deserialize('long', response.headers.get('Content-Length')) response_headers['Content-Range']=self._deserialize('str', response.headers.get('Content-Range')) response_headers['Content-Type']=self._deserialize('str', response.headers.get('Content-Type')) response_headers['Content-MD5']=self._deserialize('str', response.headers.get('Content-MD5')) response_headers['x-ms-properties']=self._deserialize('str', response.headers.get('x-ms-properties')) response_headers['x-ms-continuation']=self._deserialize('str', response.headers.get('x-ms-continuation')) response_headers['x-ms-request-id']=self._deserialize('str', response.headers.get('x-ms-request-id')) response_headers['x-ms-version']=self._deserialize('str', response.headers.get('x-ms-version')) deserialized = self._deserialize('SetAccessControlRecursiveResponse', pipeline_response) if response.status_code == 202: response_headers['Content-MD5']=self._deserialize('str', response.headers.get('Content-MD5')) response_headers['Date']=self._deserialize('rfc-1123', response.headers.get('Date')) response_headers['x-ms-request-id']=self._deserialize('str', response.headers.get('x-ms-request-id')) response_headers['x-ms-version']=self._deserialize('str', response.headers.get('x-ms-version')) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized update.metadata = {'url': '/{filesystem}/{path}'} # type: ignore def lease( self, x_ms_lease_action, # type: Union[str, "_models.PathLeaseAction"] request_id_parameter=None, # type: Optional[str] timeout=None, # type: Optional[int] x_ms_lease_duration=None, # type: Optional[int] x_ms_lease_break_period=None, # type: Optional[int] proposed_lease_id=None, # type: Optional[str] lease_access_conditions=None, # type: Optional["_models.LeaseAccessConditions"] modified_access_conditions=None, # type: Optional["_models.ModifiedAccessConditions"] **kwargs # type: Any ): # type: (...) -> None """Lease Path. Create and manage a lease to restrict write and delete access to the path. This operation supports conditional HTTP requests. For more information, see `Specifying Conditional Headers for Blob Service Operations <https://docs.microsoft.com/en- us/rest/api/storageservices/specifying-conditional-headers-for-blob-service-operations>`_. :param x_ms_lease_action: There are five lease actions: "acquire", "break", "change", "renew", and "release". Use "acquire" and specify the "x-ms-proposed-lease-id" and "x-ms-lease-duration" to acquire a new lease. Use "break" to break an existing lease. When a lease is broken, the lease break period is allowed to elapse, during which time no lease operation except break and release can be performed on the file. When a lease is successfully broken, the response indicates the interval in seconds until a new lease can be acquired. Use "change" and specify the current lease ID in "x-ms-lease-id" and the new lease ID in "x-ms-proposed-lease-id" to change the lease ID of an active lease. Use "renew" and specify the "x-ms-lease-id" to renew an existing lease. Use "release" and specify the "x-ms-lease-id" to release a lease. :type x_ms_lease_action: str or ~azure.storage.filedatalake.models.PathLeaseAction :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. :type request_id_parameter: str :param timeout: The timeout parameter is expressed in seconds. For more information, see :code:`<a href="https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/setting- timeouts-for-blob-service-operations">Setting Timeouts for Blob Service Operations.</a>`. :type timeout: int :param x_ms_lease_duration: The lease duration is required to acquire a lease, and specifies the duration of the lease in seconds. The lease duration must be between 15 and 60 seconds or -1 for infinite lease. :type x_ms_lease_duration: int :param x_ms_lease_break_period: The lease break period duration is optional to break a lease, and specifies the break period of the lease in seconds. The lease break duration must be between 0 and 60 seconds. :type x_ms_lease_break_period: int :param proposed_lease_id: Proposed lease ID, in a GUID string format. The Blob service returns 400 (Invalid request) if the proposed lease ID is not in the correct format. See Guid Constructor (String) for a list of valid GUID string formats. :type proposed_lease_id: str :param lease_access_conditions: Parameter group. :type lease_access_conditions: ~azure.storage.filedatalake.models.LeaseAccessConditions :param modified_access_conditions: Parameter group. :type modified_access_conditions: ~azure.storage.filedatalake.models.ModifiedAccessConditions :keyword callable cls: A custom type or function that will be passed the direct response :return: None, or the result of cls(response) :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _lease_id = None _if_match = None _if_none_match = None _if_modified_since = None _if_unmodified_since = None if lease_access_conditions is not None: _lease_id = lease_access_conditions.lease_id if modified_access_conditions is not None: _if_match = modified_access_conditions.if_match _if_none_match = modified_access_conditions.if_none_match _if_modified_since = modified_access_conditions.if_modified_since _if_unmodified_since = modified_access_conditions.if_unmodified_since accept = "application/json" # Construct URL url = self.lease.metadata['url'] # type: ignore path_format_arguments = { 'url': self._serialize.url("self._config.url", self._config.url, 'str', skip_quote=True), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] if timeout is not None: query_parameters['timeout'] = self._serialize.query("timeout", timeout, 'int', minimum=0) # Construct headers header_parameters = {} # type: Dict[str, Any] if request_id_parameter is not None: header_parameters['x-ms-client-request-id'] = self._serialize.header("request_id_parameter", request_id_parameter, 'str') header_parameters['x-ms-version'] = self._serialize.header("self._config.version", self._config.version, 'str') header_parameters['x-ms-lease-action'] = self._serialize.header("x_ms_lease_action", x_ms_lease_action, 'str') if x_ms_lease_duration is not None: header_parameters['x-ms-lease-duration'] = self._serialize.header("x_ms_lease_duration", x_ms_lease_duration, 'int') if x_ms_lease_break_period is not None: header_parameters['x-ms-lease-break-period'] = self._serialize.header("x_ms_lease_break_period", x_ms_lease_break_period, 'int') if _lease_id is not None: header_parameters['x-ms-lease-id'] = self._serialize.header("lease_id", _lease_id, 'str') if proposed_lease_id is not None: header_parameters['x-ms-proposed-lease-id'] = self._serialize.header("proposed_lease_id", proposed_lease_id, 'str') if _if_match is not None: header_parameters['If-Match'] = self._serialize.header("if_match", _if_match, 'str') if _if_none_match is not None: header_parameters['If-None-Match'] = self._serialize.header("if_none_match", _if_none_match, 'str') if _if_modified_since is not None: header_parameters['If-Modified-Since'] = self._serialize.header("if_modified_since", _if_modified_since, 'rfc-1123') if _if_unmodified_since is not None: header_parameters['If-Unmodified-Since'] = self._serialize.header("if_unmodified_since", _if_unmodified_since, 'rfc-1123') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.post(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201, 202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.StorageError, response) raise HttpResponseError(response=response, model=error) response_headers = {} if response.status_code == 200: response_headers['Date']=self._deserialize('rfc-1123', response.headers.get('Date')) response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) response_headers['Last-Modified']=self._deserialize('rfc-1123', response.headers.get('Last-Modified')) response_headers['x-ms-request-id']=self._deserialize('str', response.headers.get('x-ms-request-id')) response_headers['x-ms-version']=self._deserialize('str', response.headers.get('x-ms-version')) response_headers['x-ms-lease-id']=self._deserialize('str', response.headers.get('x-ms-lease-id')) if response.status_code == 201: response_headers['Date']=self._deserialize('rfc-1123', response.headers.get('Date')) response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) response_headers['Last-Modified']=self._deserialize('rfc-1123', response.headers.get('Last-Modified')) response_headers['x-ms-request-id']=self._deserialize('str', response.headers.get('x-ms-request-id')) response_headers['x-ms-version']=self._deserialize('str', response.headers.get('x-ms-version')) response_headers['x-ms-lease-id']=self._deserialize('str', response.headers.get('x-ms-lease-id')) if response.status_code == 202: response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) response_headers['Last-Modified']=self._deserialize('rfc-1123', response.headers.get('Last-Modified')) response_headers['x-ms-request-id']=self._deserialize('str', response.headers.get('x-ms-request-id')) response_headers['x-ms-version']=self._deserialize('str', response.headers.get('x-ms-version')) response_headers['x-ms-lease-time']=self._deserialize('str', response.headers.get('x-ms-lease-time')) if cls: return cls(pipeline_response, None, response_headers) lease.metadata = {'url': '/{filesystem}/{path}'} # type: ignore def read( self, request_id_parameter=None, # type: Optional[str] timeout=None, # type: Optional[int] range=None, # type: Optional[str] x_ms_range_get_content_md5=None, # type: Optional[bool] lease_access_conditions=None, # type: Optional["_models.LeaseAccessConditions"] modified_access_conditions=None, # type: Optional["_models.ModifiedAccessConditions"] **kwargs # type: Any ): # type: (...) -> IO """Read File. Read the contents of a file. For read operations, range requests are supported. This operation supports conditional HTTP requests. For more information, see `Specifying Conditional Headers for Blob Service Operations <https://docs.microsoft.com/en- us/rest/api/storageservices/specifying-conditional-headers-for-blob-service-operations>`_. :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. :type request_id_parameter: str :param timeout: The timeout parameter is expressed in seconds. For more information, see :code:`<a href="https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/setting- timeouts-for-blob-service-operations">Setting Timeouts for Blob Service Operations.</a>`. :type timeout: int :param range: The HTTP Range request header specifies one or more byte ranges of the resource to be retrieved. :type range: str :param x_ms_range_get_content_md5: Optional. When this header is set to "true" and specified together with the Range header, the service returns the MD5 hash for the range, as long as the range is less than or equal to 4MB in size. If this header is specified without the Range header, the service returns status code 400 (Bad Request). If this header is set to true when the range exceeds 4 MB in size, the service returns status code 400 (Bad Request). :type x_ms_range_get_content_md5: bool :param lease_access_conditions: Parameter group. :type lease_access_conditions: ~azure.storage.filedatalake.models.LeaseAccessConditions :param modified_access_conditions: Parameter group. :type modified_access_conditions: ~azure.storage.filedatalake.models.ModifiedAccessConditions :keyword callable cls: A custom type or function that will be passed the direct response :return: IO, or the result of cls(response) :rtype: IO :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType[IO] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _lease_id = None _if_match = None _if_none_match = None _if_modified_since = None _if_unmodified_since = None if lease_access_conditions is not None: _lease_id = lease_access_conditions.lease_id if modified_access_conditions is not None: _if_match = modified_access_conditions.if_match _if_none_match = modified_access_conditions.if_none_match _if_modified_since = modified_access_conditions.if_modified_since _if_unmodified_since = modified_access_conditions.if_unmodified_since accept = "application/json" # Construct URL url = self.read.metadata['url'] # type: ignore path_format_arguments = { 'url': self._serialize.url("self._config.url", self._config.url, 'str', skip_quote=True), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] if timeout is not None: query_parameters['timeout'] = self._serialize.query("timeout", timeout, 'int', minimum=0) # Construct headers header_parameters = {} # type: Dict[str, Any] if request_id_parameter is not None: header_parameters['x-ms-client-request-id'] = self._serialize.header("request_id_parameter", request_id_parameter, 'str') header_parameters['x-ms-version'] = self._serialize.header("self._config.version", self._config.version, 'str') if range is not None: header_parameters['Range'] = self._serialize.header("range", range, 'str') if _lease_id is not None: header_parameters['x-ms-lease-id'] = self._serialize.header("lease_id", _lease_id, 'str') if x_ms_range_get_content_md5 is not None: header_parameters['x-ms-range-get-content-md5'] = self._serialize.header("x_ms_range_get_content_md5", x_ms_range_get_content_md5, 'bool') if _if_match is not None: header_parameters['If-Match'] = self._serialize.header("if_match", _if_match, 'str') if _if_none_match is not None: header_parameters['If-None-Match'] = self._serialize.header("if_none_match", _if_none_match, 'str') if _if_modified_since is not None: header_parameters['If-Modified-Since'] = self._serialize.header("if_modified_since", _if_modified_since, 'rfc-1123') if _if_unmodified_since is not None: header_parameters['If-Unmodified-Since'] = self._serialize.header("if_unmodified_since", _if_unmodified_since, 'rfc-1123') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=True, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 206]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.StorageError, response) raise HttpResponseError(response=response, model=error) response_headers = {} if response.status_code == 200: response_headers['Accept-Ranges']=self._deserialize('str', response.headers.get('Accept-Ranges')) response_headers['Cache-Control']=self._deserialize('str', response.headers.get('Cache-Control')) response_headers['Content-Disposition']=self._deserialize('str', response.headers.get('Content-Disposition')) response_headers['Content-Encoding']=self._deserialize('str', response.headers.get('Content-Encoding')) response_headers['Content-Language']=self._deserialize('str', response.headers.get('Content-Language')) response_headers['Content-Length']=self._deserialize('long', response.headers.get('Content-Length')) response_headers['Content-Range']=self._deserialize('str', response.headers.get('Content-Range')) response_headers['Content-Type']=self._deserialize('str', response.headers.get('Content-Type')) response_headers['Content-MD5']=self._deserialize('str', response.headers.get('Content-MD5')) response_headers['Date']=self._deserialize('rfc-1123', response.headers.get('Date')) response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) response_headers['Last-Modified']=self._deserialize('rfc-1123', response.headers.get('Last-Modified')) response_headers['x-ms-request-id']=self._deserialize('str', response.headers.get('x-ms-request-id')) response_headers['x-ms-version']=self._deserialize('str', response.headers.get('x-ms-version')) response_headers['x-ms-resource-type']=self._deserialize('str', response.headers.get('x-ms-resource-type')) response_headers['x-ms-properties']=self._deserialize('str', response.headers.get('x-ms-properties')) response_headers['x-ms-lease-duration']=self._deserialize('str', response.headers.get('x-ms-lease-duration')) response_headers['x-ms-lease-state']=self._deserialize('str', response.headers.get('x-ms-lease-state')) response_headers['x-ms-lease-status']=self._deserialize('str', response.headers.get('x-ms-lease-status')) deserialized = response.stream_download(self._client._pipeline) if response.status_code == 206: response_headers['Accept-Ranges']=self._deserialize('str', response.headers.get('Accept-Ranges')) response_headers['Cache-Control']=self._deserialize('str', response.headers.get('Cache-Control')) response_headers['Content-Disposition']=self._deserialize('str', response.headers.get('Content-Disposition')) response_headers['Content-Encoding']=self._deserialize('str', response.headers.get('Content-Encoding')) response_headers['Content-Language']=self._deserialize('str', response.headers.get('Content-Language')) response_headers['Content-Length']=self._deserialize('long', response.headers.get('Content-Length')) response_headers['Content-Range']=self._deserialize('str', response.headers.get('Content-Range')) response_headers['Content-Type']=self._deserialize('str', response.headers.get('Content-Type')) response_headers['Content-MD5']=self._deserialize('str', response.headers.get('Content-MD5')) response_headers['x-ms-content-md5']=self._deserialize('str', response.headers.get('x-ms-content-md5')) response_headers['Date']=self._deserialize('rfc-1123', response.headers.get('Date')) response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) response_headers['Last-Modified']=self._deserialize('rfc-1123', response.headers.get('Last-Modified')) response_headers['x-ms-request-id']=self._deserialize('str', response.headers.get('x-ms-request-id')) response_headers['x-ms-version']=self._deserialize('str', response.headers.get('x-ms-version')) response_headers['x-ms-resource-type']=self._deserialize('str', response.headers.get('x-ms-resource-type')) response_headers['x-ms-properties']=self._deserialize('str', response.headers.get('x-ms-properties')) response_headers['x-ms-lease-duration']=self._deserialize('str', response.headers.get('x-ms-lease-duration')) response_headers['x-ms-lease-state']=self._deserialize('str', response.headers.get('x-ms-lease-state')) response_headers['x-ms-lease-status']=self._deserialize('str', response.headers.get('x-ms-lease-status')) deserialized = response.stream_download(self._client._pipeline) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized read.metadata = {'url': '/{filesystem}/{path}'} # type: ignore def get_properties( self, request_id_parameter=None, # type: Optional[str] timeout=None, # type: Optional[int] action=None, # type: Optional[Union[str, "_models.PathGetPropertiesAction"]] upn=None, # type: Optional[bool] lease_access_conditions=None, # type: Optional["_models.LeaseAccessConditions"] modified_access_conditions=None, # type: Optional["_models.ModifiedAccessConditions"] **kwargs # type: Any ): # type: (...) -> None """Get Properties | Get Status | Get Access Control List. Get Properties returns all system and user defined properties for a path. Get Status returns all system defined properties for a path. Get Access Control List returns the access control list for a path. This operation supports conditional HTTP requests. For more information, see `Specifying Conditional Headers for Blob Service Operations <https://docs.microsoft.com/en- us/rest/api/storageservices/specifying-conditional-headers-for-blob-service-operations>`_. :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. :type request_id_parameter: str :param timeout: The timeout parameter is expressed in seconds. For more information, see :code:`<a href="https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/setting- timeouts-for-blob-service-operations">Setting Timeouts for Blob Service Operations.</a>`. :type timeout: int :param action: Optional. If the value is "getStatus" only the system defined properties for the path are returned. If the value is "getAccessControl" the access control list is returned in the response headers (Hierarchical Namespace must be enabled for the account), otherwise the properties are returned. :type action: str or ~azure.storage.filedatalake.models.PathGetPropertiesAction :param upn: Optional. Valid only when Hierarchical Namespace is enabled for the account. If "true", the user identity values returned in the x-ms-owner, x-ms-group, and x-ms-acl response headers will be transformed from Azure Active Directory Object IDs to User Principal Names. If "false", the values will be returned as Azure Active Directory Object IDs. The default value is false. Note that group and application Object IDs are not translated because they do not have unique friendly names. :type upn: bool :param lease_access_conditions: Parameter group. :type lease_access_conditions: ~azure.storage.filedatalake.models.LeaseAccessConditions :param modified_access_conditions: Parameter group. :type modified_access_conditions: ~azure.storage.filedatalake.models.ModifiedAccessConditions :keyword callable cls: A custom type or function that will be passed the direct response :return: None, or the result of cls(response) :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _lease_id = None _if_match = None _if_none_match = None _if_modified_since = None _if_unmodified_since = None if lease_access_conditions is not None: _lease_id = lease_access_conditions.lease_id if modified_access_conditions is not None: _if_match = modified_access_conditions.if_match _if_none_match = modified_access_conditions.if_none_match _if_modified_since = modified_access_conditions.if_modified_since _if_unmodified_since = modified_access_conditions.if_unmodified_since accept = "application/json" # Construct URL url = self.get_properties.metadata['url'] # type: ignore path_format_arguments = { 'url': self._serialize.url("self._config.url", self._config.url, 'str', skip_quote=True), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] if timeout is not None: query_parameters['timeout'] = self._serialize.query("timeout", timeout, 'int', minimum=0) if action is not None: query_parameters['action'] = self._serialize.query("action", action, 'str') if upn is not None: query_parameters['upn'] = self._serialize.query("upn", upn, 'bool') # Construct headers header_parameters = {} # type: Dict[str, Any] if request_id_parameter is not None: header_parameters['x-ms-client-request-id'] = self._serialize.header("request_id_parameter", request_id_parameter, 'str') header_parameters['x-ms-version'] = self._serialize.header("self._config.version", self._config.version, 'str') if _lease_id is not None: header_parameters['x-ms-lease-id'] = self._serialize.header("lease_id", _lease_id, 'str') if _if_match is not None: header_parameters['If-Match'] = self._serialize.header("if_match", _if_match, 'str') if _if_none_match is not None: header_parameters['If-None-Match'] = self._serialize.header("if_none_match", _if_none_match, 'str') if _if_modified_since is not None: header_parameters['If-Modified-Since'] = self._serialize.header("if_modified_since", _if_modified_since, 'rfc-1123') if _if_unmodified_since is not None: header_parameters['If-Unmodified-Since'] = self._serialize.header("if_unmodified_since", _if_unmodified_since, 'rfc-1123') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.head(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.StorageError, response) raise HttpResponseError(response=response, model=error) response_headers = {} response_headers['Accept-Ranges']=self._deserialize('str', response.headers.get('Accept-Ranges')) response_headers['Cache-Control']=self._deserialize('str', response.headers.get('Cache-Control')) response_headers['Content-Disposition']=self._deserialize('str', response.headers.get('Content-Disposition')) response_headers['Content-Encoding']=self._deserialize('str', response.headers.get('Content-Encoding')) response_headers['Content-Language']=self._deserialize('str', response.headers.get('Content-Language')) response_headers['Content-Length']=self._deserialize('long', response.headers.get('Content-Length')) response_headers['Content-Range']=self._deserialize('str', response.headers.get('Content-Range')) response_headers['Content-Type']=self._deserialize('str', response.headers.get('Content-Type')) response_headers['Content-MD5']=self._deserialize('str', response.headers.get('Content-MD5')) response_headers['Date']=self._deserialize('rfc-1123', response.headers.get('Date')) response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) response_headers['Last-Modified']=self._deserialize('rfc-1123', response.headers.get('Last-Modified')) response_headers['x-ms-request-id']=self._deserialize('str', response.headers.get('x-ms-request-id')) response_headers['x-ms-version']=self._deserialize('str', response.headers.get('x-ms-version')) response_headers['x-ms-resource-type']=self._deserialize('str', response.headers.get('x-ms-resource-type')) response_headers['x-ms-properties']=self._deserialize('str', response.headers.get('x-ms-properties')) response_headers['x-ms-owner']=self._deserialize('str', response.headers.get('x-ms-owner')) response_headers['x-ms-group']=self._deserialize('str', response.headers.get('x-ms-group')) response_headers['x-ms-permissions']=self._deserialize('str', response.headers.get('x-ms-permissions')) response_headers['x-ms-acl']=self._deserialize('str', response.headers.get('x-ms-acl')) response_headers['x-ms-lease-duration']=self._deserialize('str', response.headers.get('x-ms-lease-duration')) response_headers['x-ms-lease-state']=self._deserialize('str', response.headers.get('x-ms-lease-state')) response_headers['x-ms-lease-status']=self._deserialize('str', response.headers.get('x-ms-lease-status')) if cls: return cls(pipeline_response, None, response_headers) get_properties.metadata = {'url': '/{filesystem}/{path}'} # type: ignore def delete( self, request_id_parameter=None, # type: Optional[str] timeout=None, # type: Optional[int] recursive=None, # type: Optional[bool] continuation=None, # type: Optional[str] lease_access_conditions=None, # type: Optional["_models.LeaseAccessConditions"] modified_access_conditions=None, # type: Optional["_models.ModifiedAccessConditions"] **kwargs # type: Any ): # type: (...) -> None """Delete File | Delete Directory. Delete the file or directory. This operation supports conditional HTTP requests. For more information, see `Specifying Conditional Headers for Blob Service Operations <https://docs.microsoft.com/en-us/rest/api/storageservices/specifying-conditional-headers-for- blob-service-operations>`_. :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. :type request_id_parameter: str :param timeout: The timeout parameter is expressed in seconds. For more information, see :code:`<a href="https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/setting- timeouts-for-blob-service-operations">Setting Timeouts for Blob Service Operations.</a>`. :type timeout: int :param recursive: Required. :type recursive: bool :param continuation: Optional. When deleting a directory, the number of paths that are deleted with each invocation is limited. If the number of paths to be deleted exceeds this limit, a continuation token is returned in this response header. When a continuation token is returned in the response, it must be specified in a subsequent invocation of the delete operation to continue deleting the directory. :type continuation: str :param lease_access_conditions: Parameter group. :type lease_access_conditions: ~azure.storage.filedatalake.models.LeaseAccessConditions :param modified_access_conditions: Parameter group. :type modified_access_conditions: ~azure.storage.filedatalake.models.ModifiedAccessConditions :keyword callable cls: A custom type or function that will be passed the direct response :return: None, or the result of cls(response) :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _lease_id = None _if_match = None _if_none_match = None _if_modified_since = None _if_unmodified_since = None if lease_access_conditions is not None: _lease_id = lease_access_conditions.lease_id if modified_access_conditions is not None: _if_match = modified_access_conditions.if_match _if_none_match = modified_access_conditions.if_none_match _if_modified_since = modified_access_conditions.if_modified_since _if_unmodified_since = modified_access_conditions.if_unmodified_since accept = "application/json" # Construct URL url = self.delete.metadata['url'] # type: ignore path_format_arguments = { 'url': self._serialize.url("self._config.url", self._config.url, 'str', skip_quote=True), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] if timeout is not None: query_parameters['timeout'] = self._serialize.query("timeout", timeout, 'int', minimum=0) if recursive is not None: query_parameters['recursive'] = self._serialize.query("recursive", recursive, 'bool') if continuation is not None: query_parameters['continuation'] = self._serialize.query("continuation", continuation, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] if request_id_parameter is not None: header_parameters['x-ms-client-request-id'] = self._serialize.header("request_id_parameter", request_id_parameter, 'str') header_parameters['x-ms-version'] = self._serialize.header("self._config.version", self._config.version, 'str') if _lease_id is not None: header_parameters['x-ms-lease-id'] = self._serialize.header("lease_id", _lease_id, 'str') if _if_match is not None: header_parameters['If-Match'] = self._serialize.header("if_match", _if_match, 'str') if _if_none_match is not None: header_parameters['If-None-Match'] = self._serialize.header("if_none_match", _if_none_match, 'str') if _if_modified_since is not None: header_parameters['If-Modified-Since'] = self._serialize.header("if_modified_since", _if_modified_since, 'rfc-1123') if _if_unmodified_since is not None: header_parameters['If-Unmodified-Since'] = self._serialize.header("if_unmodified_since", _if_unmodified_since, 'rfc-1123') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.StorageError, response) raise HttpResponseError(response=response, model=error) response_headers = {} response_headers['Date']=self._deserialize('rfc-1123', response.headers.get('Date')) response_headers['x-ms-request-id']=self._deserialize('str', response.headers.get('x-ms-request-id')) response_headers['x-ms-version']=self._deserialize('str', response.headers.get('x-ms-version')) response_headers['x-ms-continuation']=self._deserialize('str', response.headers.get('x-ms-continuation')) response_headers['x-ms-deletion-id']=self._deserialize('str', response.headers.get('x-ms-deletion-id')) if cls: return cls(pipeline_response, None, response_headers) delete.metadata = {'url': '/{filesystem}/{path}'} # type: ignore def set_access_control( self, timeout=None, # type: Optional[int] owner=None, # type: Optional[str] group=None, # type: Optional[str] permissions=None, # type: Optional[str] acl=None, # type: Optional[str] request_id_parameter=None, # type: Optional[str] lease_access_conditions=None, # type: Optional["_models.LeaseAccessConditions"] modified_access_conditions=None, # type: Optional["_models.ModifiedAccessConditions"] **kwargs # type: Any ): # type: (...) -> None """Set the owner, group, permissions, or access control list for a path. :param timeout: The timeout parameter is expressed in seconds. For more information, see :code:`<a href="https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/setting- timeouts-for-blob-service-operations">Setting Timeouts for Blob Service Operations.</a>`. :type timeout: int :param owner: Optional. The owner of the blob or directory. :type owner: str :param group: Optional. The owning group of the blob or directory. :type group: str :param permissions: Optional and only valid if Hierarchical Namespace is enabled for the account. Sets POSIX access permissions for the file owner, the file owning group, and others. Each class may be granted read, write, or execute permission. The sticky bit is also supported. Both symbolic (rwxrw-rw-) and 4-digit octal notation (e.g. 0766) are supported. :type permissions: str :param acl: Sets POSIX access control rights on files and directories. The value is a comma- separated list of access control entries. Each access control entry (ACE) consists of a scope, a type, a user or group identifier, and permissions in the format "[scope:][type]:[id]:[permissions]". :type acl: str :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. :type request_id_parameter: str :param lease_access_conditions: Parameter group. :type lease_access_conditions: ~azure.storage.filedatalake.models.LeaseAccessConditions :param modified_access_conditions: Parameter group. :type modified_access_conditions: ~azure.storage.filedatalake.models.ModifiedAccessConditions :keyword callable cls: A custom type or function that will be passed the direct response :return: None, or the result of cls(response) :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _lease_id = None _if_match = None _if_none_match = None _if_modified_since = None _if_unmodified_since = None if lease_access_conditions is not None: _lease_id = lease_access_conditions.lease_id if modified_access_conditions is not None: _if_match = modified_access_conditions.if_match _if_none_match = modified_access_conditions.if_none_match _if_modified_since = modified_access_conditions.if_modified_since _if_unmodified_since = modified_access_conditions.if_unmodified_since action = "setAccessControl" accept = "application/json" # Construct URL url = self.set_access_control.metadata['url'] # type: ignore path_format_arguments = { 'url': self._serialize.url("self._config.url", self._config.url, 'str', skip_quote=True), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['action'] = self._serialize.query("action", action, 'str') if timeout is not None: query_parameters['timeout'] = self._serialize.query("timeout", timeout, 'int', minimum=0) # Construct headers header_parameters = {} # type: Dict[str, Any] if _lease_id is not None: header_parameters['x-ms-lease-id'] = self._serialize.header("lease_id", _lease_id, 'str') if owner is not None: header_parameters['x-ms-owner'] = self._serialize.header("owner", owner, 'str') if group is not None: header_parameters['x-ms-group'] = self._serialize.header("group", group, 'str') if permissions is not None: header_parameters['x-ms-permissions'] = self._serialize.header("permissions", permissions, 'str') if acl is not None: header_parameters['x-ms-acl'] = self._serialize.header("acl", acl, 'str') if _if_match is not None: header_parameters['If-Match'] = self._serialize.header("if_match", _if_match, 'str') if _if_none_match is not None: header_parameters['If-None-Match'] = self._serialize.header("if_none_match", _if_none_match, 'str') if _if_modified_since is not None: header_parameters['If-Modified-Since'] = self._serialize.header("if_modified_since", _if_modified_since, 'rfc-1123') if _if_unmodified_since is not None: header_parameters['If-Unmodified-Since'] = self._serialize.header("if_unmodified_since", _if_unmodified_since, 'rfc-1123') if request_id_parameter is not None: header_parameters['x-ms-client-request-id'] = self._serialize.header("request_id_parameter", request_id_parameter, 'str') header_parameters['x-ms-version'] = self._serialize.header("self._config.version", self._config.version, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.patch(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.StorageError, response) raise HttpResponseError(response=response, model=error) response_headers = {} response_headers['Date']=self._deserialize('rfc-1123', response.headers.get('Date')) response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) response_headers['Last-Modified']=self._deserialize('rfc-1123', response.headers.get('Last-Modified')) response_headers['x-ms-client-request-id']=self._deserialize('str', response.headers.get('x-ms-client-request-id')) response_headers['x-ms-request-id']=self._deserialize('str', response.headers.get('x-ms-request-id')) response_headers['x-ms-version']=self._deserialize('str', response.headers.get('x-ms-version')) if cls: return cls(pipeline_response, None, response_headers) set_access_control.metadata = {'url': '/{filesystem}/{path}'} # type: ignore def set_access_control_recursive( self, mode, # type: Union[str, "_models.PathSetAccessControlRecursiveMode"] timeout=None, # type: Optional[int] continuation=None, # type: Optional[str] force_flag=None, # type: Optional[bool] max_records=None, # type: Optional[int] acl=None, # type: Optional[str] request_id_parameter=None, # type: Optional[str] **kwargs # type: Any ): # type: (...) -> "_models.SetAccessControlRecursiveResponse" """Set the access control list for a path and subpaths. :param mode: Mode "set" sets POSIX access control rights on files and directories, "modify" modifies one or more POSIX access control rights that pre-exist on files and directories, "remove" removes one or more POSIX access control rights that were present earlier on files and directories. :type mode: str or ~azure.storage.filedatalake.models.PathSetAccessControlRecursiveMode :param timeout: The timeout parameter is expressed in seconds. For more information, see :code:`<a href="https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/setting- timeouts-for-blob-service-operations">Setting Timeouts for Blob Service Operations.</a>`. :type timeout: int :param continuation: Optional. When deleting a directory, the number of paths that are deleted with each invocation is limited. If the number of paths to be deleted exceeds this limit, a continuation token is returned in this response header. When a continuation token is returned in the response, it must be specified in a subsequent invocation of the delete operation to continue deleting the directory. :type continuation: str :param force_flag: Optional. Valid for "SetAccessControlRecursive" operation. If set to false, the operation will terminate quickly on encountering user errors (4XX). If true, the operation will ignore user errors and proceed with the operation on other sub-entities of the directory. Continuation token will only be returned when forceFlag is true in case of user errors. If not set the default value is false for this. :type force_flag: bool :param max_records: Optional. It specifies the maximum number of files or directories on which the acl change will be applied. If omitted or greater than 2,000, the request will process up to 2,000 items. :type max_records: int :param acl: Sets POSIX access control rights on files and directories. The value is a comma- separated list of access control entries. Each access control entry (ACE) consists of a scope, a type, a user or group identifier, and permissions in the format "[scope:][type]:[id]:[permissions]". :type acl: str :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. :type request_id_parameter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: SetAccessControlRecursiveResponse, or the result of cls(response) :rtype: ~azure.storage.filedatalake.models.SetAccessControlRecursiveResponse :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.SetAccessControlRecursiveResponse"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) action = "setAccessControlRecursive" accept = "application/json" # Construct URL url = self.set_access_control_recursive.metadata['url'] # type: ignore path_format_arguments = { 'url': self._serialize.url("self._config.url", self._config.url, 'str', skip_quote=True), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['action'] = self._serialize.query("action", action, 'str') if timeout is not None: query_parameters['timeout'] = self._serialize.query("timeout", timeout, 'int', minimum=0) if continuation is not None: query_parameters['continuation'] = self._serialize.query("continuation", continuation, 'str') query_parameters['mode'] = self._serialize.query("mode", mode, 'str') if force_flag is not None: query_parameters['forceFlag'] = self._serialize.query("force_flag", force_flag, 'bool') if max_records is not None: query_parameters['maxRecords'] = self._serialize.query("max_records", max_records, 'int', minimum=1) # Construct headers header_parameters = {} # type: Dict[str, Any] if acl is not None: header_parameters['x-ms-acl'] = self._serialize.header("acl", acl, 'str') if request_id_parameter is not None: header_parameters['x-ms-client-request-id'] = self._serialize.header("request_id_parameter", request_id_parameter, 'str') header_parameters['x-ms-version'] = self._serialize.header("self._config.version", self._config.version, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.patch(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.StorageError, response) raise HttpResponseError(response=response, model=error) response_headers = {} response_headers['Date']=self._deserialize('rfc-1123', response.headers.get('Date')) response_headers['x-ms-client-request-id']=self._deserialize('str', response.headers.get('x-ms-client-request-id')) response_headers['x-ms-continuation']=self._deserialize('str', response.headers.get('x-ms-continuation')) response_headers['x-ms-request-id']=self._deserialize('str', response.headers.get('x-ms-request-id')) response_headers['x-ms-version']=self._deserialize('str', response.headers.get('x-ms-version')) deserialized = self._deserialize('SetAccessControlRecursiveResponse', pipeline_response) if cls: return cls(pipeline_response, deserialized, response_headers) return deserialized set_access_control_recursive.metadata = {'url': '/{filesystem}/{path}'} # type: ignore def flush_data( self, timeout=None, # type: Optional[int] position=None, # type: Optional[int] retain_uncommitted_data=None, # type: Optional[bool] close=None, # type: Optional[bool] content_length=None, # type: Optional[int] request_id_parameter=None, # type: Optional[str] path_http_headers=None, # type: Optional["_models.PathHTTPHeaders"] lease_access_conditions=None, # type: Optional["_models.LeaseAccessConditions"] modified_access_conditions=None, # type: Optional["_models.ModifiedAccessConditions"] **kwargs # type: Any ): # type: (...) -> None """Set the owner, group, permissions, or access control list for a path. :param timeout: The timeout parameter is expressed in seconds. For more information, see :code:`<a href="https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/setting- timeouts-for-blob-service-operations">Setting Timeouts for Blob Service Operations.</a>`. :type timeout: int :param position: This parameter allows the caller to upload data in parallel and control the order in which it is appended to the file. It is required when uploading data to be appended to the file and when flushing previously uploaded data to the file. The value must be the position where the data is to be appended. Uploaded data is not immediately flushed, or written, to the file. To flush, the previously uploaded data must be contiguous, the position parameter must be specified and equal to the length of the file after all data has been written, and there must not be a request entity body included with the request. :type position: long :param retain_uncommitted_data: Valid only for flush operations. If "true", uncommitted data is retained after the flush operation completes; otherwise, the uncommitted data is deleted after the flush operation. The default is false. Data at offsets less than the specified position are written to the file when flush succeeds, but this optional parameter allows data after the flush position to be retained for a future flush operation. :type retain_uncommitted_data: bool :param close: Azure Storage Events allow applications to receive notifications when files change. When Azure Storage Events are enabled, a file changed event is raised. This event has a property indicating whether this is the final change to distinguish the difference between an intermediate flush to a file stream and the final close of a file stream. The close query parameter is valid only when the action is "flush" and change notifications are enabled. If the value of close is "true" and the flush operation completes successfully, the service raises a file change notification with a property indicating that this is the final update (the file stream has been closed). If "false" a change notification is raised indicating the file has changed. The default is false. This query parameter is set to true by the Hadoop ABFS driver to indicate that the file stream has been closed.". :type close: bool :param content_length: Required for "Append Data" and "Flush Data". Must be 0 for "Flush Data". Must be the length of the request content in bytes for "Append Data". :type content_length: long :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. :type request_id_parameter: str :param path_http_headers: Parameter group. :type path_http_headers: ~azure.storage.filedatalake.models.PathHTTPHeaders :param lease_access_conditions: Parameter group. :type lease_access_conditions: ~azure.storage.filedatalake.models.LeaseAccessConditions :param modified_access_conditions: Parameter group. :type modified_access_conditions: ~azure.storage.filedatalake.models.ModifiedAccessConditions :keyword callable cls: A custom type or function that will be passed the direct response :return: None, or the result of cls(response) :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _content_md5 = None _lease_id = None _cache_control = None _content_type = None _content_disposition = None _content_encoding = None _content_language = None _if_match = None _if_none_match = None _if_modified_since = None _if_unmodified_since = None if lease_access_conditions is not None: _lease_id = lease_access_conditions.lease_id if modified_access_conditions is not None: _if_match = modified_access_conditions.if_match _if_none_match = modified_access_conditions.if_none_match _if_modified_since = modified_access_conditions.if_modified_since _if_unmodified_since = modified_access_conditions.if_unmodified_since if path_http_headers is not None: _content_md5 = path_http_headers.content_md5 _cache_control = path_http_headers.cache_control _content_type = path_http_headers.content_type _content_disposition = path_http_headers.content_disposition _content_encoding = path_http_headers.content_encoding _content_language = path_http_headers.content_language action = "flush" accept = "application/json" # Construct URL url = self.flush_data.metadata['url'] # type: ignore path_format_arguments = { 'url': self._serialize.url("self._config.url", self._config.url, 'str', skip_quote=True), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['action'] = self._serialize.query("action", action, 'str') if timeout is not None: query_parameters['timeout'] = self._serialize.query("timeout", timeout, 'int', minimum=0) if position is not None: query_parameters['position'] = self._serialize.query("position", position, 'long') if retain_uncommitted_data is not None: query_parameters['retainUncommittedData'] = self._serialize.query("retain_uncommitted_data", retain_uncommitted_data, 'bool') if close is not None: query_parameters['close'] = self._serialize.query("close", close, 'bool') # Construct headers header_parameters = {} # type: Dict[str, Any] if content_length is not None: header_parameters['Content-Length'] = self._serialize.header("content_length", content_length, 'long', minimum=0) if _content_md5 is not None: header_parameters['x-ms-content-md5'] = self._serialize.header("content_md5", _content_md5, 'bytearray') if _lease_id is not None: header_parameters['x-ms-lease-id'] = self._serialize.header("lease_id", _lease_id, 'str') if _cache_control is not None: header_parameters['x-ms-cache-control'] = self._serialize.header("cache_control", _cache_control, 'str') if _content_type is not None: header_parameters['x-ms-content-type'] = self._serialize.header("content_type", _content_type, 'str') if _content_disposition is not None: header_parameters['x-ms-content-disposition'] = self._serialize.header("content_disposition", _content_disposition, 'str') if _content_encoding is not None: header_parameters['x-ms-content-encoding'] = self._serialize.header("content_encoding", _content_encoding, 'str') if _content_language is not None: header_parameters['x-ms-content-language'] = self._serialize.header("content_language", _content_language, 'str') if _if_match is not None: header_parameters['If-Match'] = self._serialize.header("if_match", _if_match, 'str') if _if_none_match is not None: header_parameters['If-None-Match'] = self._serialize.header("if_none_match", _if_none_match, 'str') if _if_modified_since is not None: header_parameters['If-Modified-Since'] = self._serialize.header("if_modified_since", _if_modified_since, 'rfc-1123') if _if_unmodified_since is not None: header_parameters['If-Unmodified-Since'] = self._serialize.header("if_unmodified_since", _if_unmodified_since, 'rfc-1123') if request_id_parameter is not None: header_parameters['x-ms-client-request-id'] = self._serialize.header("request_id_parameter", request_id_parameter, 'str') header_parameters['x-ms-version'] = self._serialize.header("self._config.version", self._config.version, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.patch(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.StorageError, response) raise HttpResponseError(response=response, model=error) response_headers = {} response_headers['Date']=self._deserialize('rfc-1123', response.headers.get('Date')) response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) response_headers['Last-Modified']=self._deserialize('rfc-1123', response.headers.get('Last-Modified')) response_headers['Content-Length']=self._deserialize('long', response.headers.get('Content-Length')) response_headers['x-ms-client-request-id']=self._deserialize('str', response.headers.get('x-ms-client-request-id')) response_headers['x-ms-request-id']=self._deserialize('str', response.headers.get('x-ms-request-id')) response_headers['x-ms-version']=self._deserialize('str', response.headers.get('x-ms-version')) if cls: return cls(pipeline_response, None, response_headers) flush_data.metadata = {'url': '/{filesystem}/{path}'} # type: ignore def append_data( self, body, # type: IO position=None, # type: Optional[int] timeout=None, # type: Optional[int] content_length=None, # type: Optional[int] transactional_content_crc64=None, # type: Optional[bytearray] request_id_parameter=None, # type: Optional[str] path_http_headers=None, # type: Optional["_models.PathHTTPHeaders"] lease_access_conditions=None, # type: Optional["_models.LeaseAccessConditions"] **kwargs # type: Any ): # type: (...) -> None """Append data to the file. :param body: Initial data. :type body: IO :param position: This parameter allows the caller to upload data in parallel and control the order in which it is appended to the file. It is required when uploading data to be appended to the file and when flushing previously uploaded data to the file. The value must be the position where the data is to be appended. Uploaded data is not immediately flushed, or written, to the file. To flush, the previously uploaded data must be contiguous, the position parameter must be specified and equal to the length of the file after all data has been written, and there must not be a request entity body included with the request. :type position: long :param timeout: The timeout parameter is expressed in seconds. For more information, see :code:`<a href="https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/setting- timeouts-for-blob-service-operations">Setting Timeouts for Blob Service Operations.</a>`. :type timeout: int :param content_length: Required for "Append Data" and "Flush Data". Must be 0 for "Flush Data". Must be the length of the request content in bytes for "Append Data". :type content_length: long :param transactional_content_crc64: Specify the transactional crc64 for the body, to be validated by the service. :type transactional_content_crc64: bytearray :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. :type request_id_parameter: str :param path_http_headers: Parameter group. :type path_http_headers: ~azure.storage.filedatalake.models.PathHTTPHeaders :param lease_access_conditions: Parameter group. :type lease_access_conditions: ~azure.storage.filedatalake.models.LeaseAccessConditions :keyword callable cls: A custom type or function that will be passed the direct response :return: None, or the result of cls(response) :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) _transactional_content_hash = None _lease_id = None if lease_access_conditions is not None: _lease_id = lease_access_conditions.lease_id if path_http_headers is not None: _transactional_content_hash = path_http_headers.transactional_content_hash action = "append" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.append_data.metadata['url'] # type: ignore path_format_arguments = { 'url': self._serialize.url("self._config.url", self._config.url, 'str', skip_quote=True), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['action'] = self._serialize.query("action", action, 'str') if position is not None: query_parameters['position'] = self._serialize.query("position", position, 'long') if timeout is not None: query_parameters['timeout'] = self._serialize.query("timeout", timeout, 'int', minimum=0) # Construct headers header_parameters = {} # type: Dict[str, Any] if content_length is not None: header_parameters['Content-Length'] = self._serialize.header("content_length", content_length, 'long', minimum=0) if _transactional_content_hash is not None: header_parameters['Content-MD5'] = self._serialize.header("transactional_content_hash", _transactional_content_hash, 'bytearray') if transactional_content_crc64 is not None: header_parameters['x-ms-content-crc64'] = self._serialize.header("transactional_content_crc64", transactional_content_crc64, 'bytearray') if _lease_id is not None: header_parameters['x-ms-lease-id'] = self._serialize.header("lease_id", _lease_id, 'str') if request_id_parameter is not None: header_parameters['x-ms-client-request-id'] = self._serialize.header("request_id_parameter", request_id_parameter, 'str') header_parameters['x-ms-version'] = self._serialize.header("self._config.version", self._config.version, 'str') header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content_kwargs['stream_content'] = body request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [202]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.StorageError, response) raise HttpResponseError(response=response, model=error) response_headers = {} response_headers['Date']=self._deserialize('rfc-1123', response.headers.get('Date')) response_headers['x-ms-request-id']=self._deserialize('str', response.headers.get('x-ms-request-id')) response_headers['x-ms-client-request-id']=self._deserialize('str', response.headers.get('x-ms-client-request-id')) response_headers['x-ms-version']=self._deserialize('str', response.headers.get('x-ms-version')) response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) response_headers['Content-MD5']=self._deserialize('bytearray', response.headers.get('Content-MD5')) response_headers['x-ms-content-crc64']=self._deserialize('bytearray', response.headers.get('x-ms-content-crc64')) response_headers['x-ms-request-server-encrypted']=self._deserialize('bool', response.headers.get('x-ms-request-server-encrypted')) if cls: return cls(pipeline_response, None, response_headers) append_data.metadata = {'url': '/{filesystem}/{path}'} # type: ignore def set_expiry( self, expiry_options, # type: Union[str, "_models.PathExpiryOptions"] timeout=None, # type: Optional[int] request_id_parameter=None, # type: Optional[str] expires_on=None, # type: Optional[str] **kwargs # type: Any ): # type: (...) -> None """Sets the time a blob will expire and be deleted. :param expiry_options: Required. Indicates mode of the expiry time. :type expiry_options: str or ~azure.storage.filedatalake.models.PathExpiryOptions :param timeout: The timeout parameter is expressed in seconds. For more information, see :code:`<a href="https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/setting- timeouts-for-blob-service-operations">Setting Timeouts for Blob Service Operations.</a>`. :type timeout: int :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. :type request_id_parameter: str :param expires_on: The time to set the blob to expiry. :type expires_on: str :keyword callable cls: A custom type or function that will be passed the direct response :return: None, or the result of cls(response) :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) comp = "expiry" accept = "application/json" # Construct URL url = self.set_expiry.metadata['url'] # type: ignore path_format_arguments = { 'url': self._serialize.url("self._config.url", self._config.url, 'str', skip_quote=True), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['comp'] = self._serialize.query("comp", comp, 'str') if timeout is not None: query_parameters['timeout'] = self._serialize.query("timeout", timeout, 'int', minimum=0) # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['x-ms-version'] = self._serialize.header("self._config.version", self._config.version, 'str') if request_id_parameter is not None: header_parameters['x-ms-client-request-id'] = self._serialize.header("request_id_parameter", request_id_parameter, 'str') header_parameters['x-ms-expiry-option'] = self._serialize.header("expiry_options", expiry_options, 'str') if expires_on is not None: header_parameters['x-ms-expiry-time'] = self._serialize.header("expires_on", expires_on, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.put(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.StorageError, response) raise HttpResponseError(response=response, model=error) response_headers = {} response_headers['ETag']=self._deserialize('str', response.headers.get('ETag')) response_headers['Last-Modified']=self._deserialize('rfc-1123', response.headers.get('Last-Modified')) response_headers['x-ms-client-request-id']=self._deserialize('str', response.headers.get('x-ms-client-request-id')) response_headers['x-ms-request-id']=self._deserialize('str', response.headers.get('x-ms-request-id')) response_headers['x-ms-version']=self._deserialize('str', response.headers.get('x-ms-version')) response_headers['Date']=self._deserialize('rfc-1123', response.headers.get('Date')) if cls: return cls(pipeline_response, None, response_headers) set_expiry.metadata = {'url': '/{filesystem}/{path}'} # type: ignore def undelete( self, timeout=None, # type: Optional[int] undelete_source=None, # type: Optional[str] request_id_parameter=None, # type: Optional[str] **kwargs # type: Any ): # type: (...) -> None """Undelete a path that was previously soft deleted. :param timeout: The timeout parameter is expressed in seconds. For more information, see :code:`<a href="https://docs.microsoft.com/en-us/rest/api/storageservices/fileservices/setting- timeouts-for-blob-service-operations">Setting Timeouts for Blob Service Operations.</a>`. :type timeout: int :param undelete_source: Only for hierarchical namespace enabled accounts. Optional. The path of the soft deleted blob to undelete. :type undelete_source: str :param request_id_parameter: Provides a client-generated, opaque value with a 1 KB character limit that is recorded in the analytics logs when storage analytics logging is enabled. :type request_id_parameter: str :keyword callable cls: A custom type or function that will be passed the direct response :return: None, or the result of cls(response) :rtype: None :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) comp = "undelete" accept = "application/json" # Construct URL url = self.undelete.metadata['url'] # type: ignore path_format_arguments = { 'url': self._serialize.url("self._config.url", self._config.url, 'str', skip_quote=True), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['comp'] = self._serialize.query("comp", comp, 'str') if timeout is not None: query_parameters['timeout'] = self._serialize.query("timeout", timeout, 'int', minimum=0) # Construct headers header_parameters = {} # type: Dict[str, Any] if undelete_source is not None: header_parameters['x-ms-undelete-source'] = self._serialize.header("undelete_source", undelete_source, 'str') header_parameters['x-ms-version'] = self._serialize.header("self._config.version", self._config.version, 'str') if request_id_parameter is not None: header_parameters['x-ms-client-request-id'] = self._serialize.header("request_id_parameter", request_id_parameter, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.put(url, query_parameters, header_parameters) pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.StorageError, response) raise HttpResponseError(response=response, model=error) response_headers = {} response_headers['x-ms-client-request-id']=self._deserialize('str', response.headers.get('x-ms-client-request-id')) response_headers['x-ms-request-id']=self._deserialize('str', response.headers.get('x-ms-request-id')) response_headers['x-ms-resource-type']=self._deserialize('str', response.headers.get('x-ms-resource-type')) response_headers['x-ms-version']=self._deserialize('str', response.headers.get('x-ms-version')) response_headers['Date']=self._deserialize('rfc-1123', response.headers.get('Date')) if cls: return cls(pipeline_response, None, response_headers) undelete.metadata = {'url': '/{filesystem}/{path}'} # type: ignore
63.683799
160
0.689291
f21c07588877737ff1a347604cf20229bdd4a97d
3,530
py
Python
jupyterlab_gcsfilebrowser/jupyterlab_gcsfilebrowser/tests/handlers_test.py
mkalil/jupyter-extensions
2949aa8fb08b2e0b7a0a14e1b977f62c3c6ddfb4
[ "Apache-2.0" ]
2
2020-06-25T19:29:03.000Z
2020-08-17T08:36:04.000Z
jupyterlab_gcsfilebrowser/jupyterlab_gcsfilebrowser/tests/handlers_test.py
mkalil/jupyter-extensions
2949aa8fb08b2e0b7a0a14e1b977f62c3c6ddfb4
[ "Apache-2.0" ]
25
2020-06-17T17:58:59.000Z
2020-08-11T14:53:58.000Z
jupyterlab_gcsfilebrowser/jupyterlab_gcsfilebrowser/tests/handlers_test.py
mkalil/jupyter-extensions
2949aa8fb08b2e0b7a0a14e1b977f62c3c6ddfb4
[ "Apache-2.0" ]
null
null
null
import unittest import datetime from unittest.mock import Mock, MagicMock, patch from jupyterlab_gcsfilebrowser import handlers from google.cloud import storage # used for connecting to GCS from google.cloud.storage import Blob, Bucket import pprint pp = pprint.PrettyPrinter(indent=2) class TestGCSDirectory(unittest.TestCase): def testGetPathContentsRoot(self): requests = ['/', ''] gcs_buckets = [ Bucket(client=Mock(), name='dummy_bucket1'), Bucket(client=Mock(), name='dummy_bucket2'), ] storage_client = Mock() storage_client.list_buckets = MagicMock(return_value=gcs_buckets) wanted = { 'type': 'directory', 'content': [ { 'name': 'dummy_bucket1/', 'path': 'dummy_bucket1/', 'type': 'directory', 'last_modified': '', }, { 'name': 'dummy_bucket2/', 'path': 'dummy_bucket2/', 'type': 'directory', 'last_modified': '', }, ] } for req in requests: got = handlers.getPathContents(req, storage_client) self.assertEqual(wanted, got) def testGetPathContentsDir(self): requests = ['dummy_bucket1/', 'dummy_bucket1'] dummy_bucket1 = Bucket(client=Mock(), name='dummy_bucket1') gcs_buckets = [ dummy_bucket1, ] gcs_blobs = [ Blob(name='dummy_file', bucket=dummy_bucket1), Blob(name='dummy_dir/', bucket=dummy_bucket1), ] storage_client = Mock() storage_client.list_buckets = MagicMock(return_value=gcs_buckets) storage_client.list_blobs = MagicMock(return_value=gcs_blobs) wanted = { 'type': 'directory', 'content': [ { 'name': 'dummy_file', 'path': 'dummy_bucket1/dummy_file', 'type': 'file', 'last_modified': '', }, { 'name': 'dummy_dir/', 'path': 'dummy_bucket1/dummy_dir/', 'type': 'directory', 'last_modified': '', }, ] } for req in requests: got = handlers.getPathContents(req, storage_client) self.assertDictEqual(wanted, got) def testGetPathContentsSubDir(self): requests = ['dummy_bucket1/subdir/', 'dummy_bucket1/subdir'] dummy_bucket1 = Bucket(client=Mock(), name='dummy_bucket1') gcs_buckets = [ dummy_bucket1, ] gcs_blobs = [ Blob(name='subdir/dummy_file', bucket=dummy_bucket1), Blob(name='subdir/dummy_dir/', bucket=dummy_bucket1), ] storage_client = Mock() storage_client.list_buckets = MagicMock(return_value=gcs_buckets) storage_client.list_blobs = MagicMock(return_value=gcs_blobs) wanted = { 'type': 'directory', 'content': [ { 'name': 'dummy_file', 'path': 'dummy_bucket1/subdir/dummy_file', 'type': 'file', 'last_modified': '', }, { 'name': 'dummy_dir/', 'path': 'dummy_bucket1/subdir/dummy_dir/', 'type': 'directory', 'last_modified': '', }, ] } for req in requests: got = handlers.getPathContents(req, storage_client) self.assertEqual(wanted['content'], got['content']) if __name__ == '__main__': unittest.main()
26.541353
69
0.550992
fa0e5a5b30d9e9710919b37c4ffd9a9bcdf293a5
9,204
py
Python
identify_domain_v3.py
gkovacs/tmi-browsing-behavior-prediction
0e7d44574003272ce457bf221bfa3e92002ad217
[ "MIT" ]
1
2019-12-16T11:44:18.000Z
2019-12-16T11:44:18.000Z
identify_domain_v3.py
gkovacs/tmi-browsing-behavior-prediction
0e7d44574003272ce457bf221bfa3e92002ad217
[ "MIT" ]
null
null
null
identify_domain_v3.py
gkovacs/tmi-browsing-behavior-prediction
0e7d44574003272ce457bf221bfa3e92002ad217
[ "MIT" ]
null
null
null
#!/usr/bin/env python # md5: bd300914dd85774d27f7ff523c56b0ab # coding: utf-8 from tmilib import * #user = get_test_users()[0] #print user #tab_focus_times = get_tab_focus_times_for_user(user) #print tab_focus_times[0].keys() #print active_second_to_domain_id.keys()[:10] #seen_domains_only_real = get_seen_urls_and_domains_real_and_history()['seen_domains_only_real'] #[domain_to_id(x) for x in ['www.mturk.com', 'apps.facebook.com', 'www.facebook.com', 'www.reddit.com', 'www.youtube.com']] #sumkeys(total_tabbed_back_domains_all, 'www.mturk.com', 'apps.facebook.com', 'www.facebook.com', 'www.reddit.com', 'www.youtube.com') #728458.0/2382221 #print_counter(total_tabbed_back_domains_first) ''' total_active_seconds = 0 for user in get_test_users(): total_active_seconds += len(get_active_seconds_for_user(user)) #for span in get_active_seconds_for_user(user) print total_active_seconds ''' #for user in get_test_users(): # print user # print (get_recently_seen_domain_stats_for_user(user)['stats']) @memoized def get_recently_seen_domain_stats_for_user_v3(user): ordered_visits = get_history_ordered_visits_corrected_for_user(user) ordered_visits = exclude_bad_visits(ordered_visits) active_domain_at_time = get_active_domain_at_time_for_user(user) active_seconds_set = set(get_active_insession_seconds_for_user(user)) #active_second_to_domain_id = get_active_second_to_domain_id_for_user(user) active_second_to_domain_id = {int(k):v for k,v in get_active_second_to_domain_id_for_user(user).viewitems()} recently_seen_domain_ids = [-1]*100 seen_domain_ids_set = set() stats = Counter() nomatch_domains = Counter() tabbed_back_domains_first = Counter() tabbed_back_domains_second = Counter() tabbed_back_domains_all = Counter() distractors_list = [domain_to_id(x) for x in ['www.mturk.com', 'apps.facebook.com', 'www.facebook.com', 'www.reddit.com', 'www.youtube.com']] distractors = set(distractors_list) most_recent_distractor = distractors_list[0] for idx,visit in enumerate(ordered_visits): if idx+1 >= len(ordered_visits): break next_visit = ordered_visits[idx+1] cur_domain = url_to_domain(visit['url']) cur_domain_id = domain_to_id(cur_domain) if cur_domain_id in distractors: most_recent_distractor = cur_domain_id recently_seen_domain_ids.append(cur_domain_id) #if cur_domain_id != recently_seen_domain_ids[-1]: # if cur_domain_id in seen_domain_ids_set: # recently_seen_domain_ids.remove(cur_domain_id) # seen_domain_ids_set.add(cur_domain_id) # recently_seen_domain_ids.append(cur_domain_id) #if cur_domain_id != recently_seen_domain_ids[-1]: # if cur_domain_id in seen_domain_ids_set: # recently_seen_domain_ids.remove(cur_domain_id) # seen_domain_ids_set.add(cur_domain_id) # recently_seen_domain_ids.append(cur_domain_id) next_domain = url_to_domain(next_visit['url']) next_domain_id = domain_to_id(next_domain) cur_time_sec = int(round(visit['visitTime'] / 1000.0)) next_time_sec = int(round(next_visit['visitTime'] / 1000.0)) if cur_time_sec > next_time_sec: continue for time_sec in xrange(cur_time_sec, next_time_sec+1): if time_sec not in active_seconds_set: continue ref_domain_id = active_second_to_domain_id[time_sec] stats['total'] += 1 if most_recent_distractor == ref_domain_id: stats['most_recent_distractor_total'] += 1 if cur_domain_id == ref_domain_id: stats['most_recent_distractor_curdomain'] += 1 elif cur_domain_id == next_domain_id: stats['most_recent_distractor_nextdomain'] += 1 else: stats['most_recent_distractor_some_prev_domain'] += 1 if cur_domain_id == ref_domain_id: if next_domain_id == cur_domain_id: stats['first and next equal and correct'] += 1 else: stats['first correct only'] += 1 continue #if next_domain_id == ref_domain_id: # stats['next correct only'] += 1 # continue stats['both incorrect'] += 1 found_match = False ref_domain = id_to_domain(ref_domain_id) for i in range(1,101): if recently_seen_domain_ids[-1-i] == ref_domain_id: stats['nth previous correct ' + str(abs(i))] += 1 stats['some previous among past 100 correct'] += 1 found_match = True tabbed_back_domains_all[ref_domain] += 1 if i == 1: tabbed_back_domains_first[ref_domain] += 1 if i == 2: tabbed_back_domains_second[ref_domain] += 1 break if not found_match: ref_domain = id_to_domain(ref_domain_id) #if ref_domain == 'newtab': # stats['newtab'] += 1 # continue stats['no match found'] += 1 nomatch_domains[id_to_domain(ref_domain_id)] += 1 ''' if cur_domain_id == ref_domain_id: if next_domain_id == cur_domain_id: stats['first and next equal and correct'] += 1 continue else: stats['first correct only'] += 1 continue else: if next_domain_id == cur_domain_id: stats['both incorrect'] += 1 found_match = False for i in range(1,101): if recently_seen_domain_ids[-1-i] == ref_domain_id: stats['nth previous correct ' + str(abs(i))] += 1 stats['some previous among past 100 correct'] += 1 found_match = True break if not found_match: ref_domain = id_to_domain(ref_domain_id) if ref_domain == 'newtab': stats['newtab'] += 1 continue stats['no match found'] += 1 nomatch_domains[id_to_domain(ref_domain_id)] += 1 continue if next_domain_id == ref_domain_id: stats['next correct only'] += 1 continue ''' return { 'stats': stats, 'nomatch_domains': nomatch_domains, 'tabbed_back_domains_all': tabbed_back_domains_all, 'tabbed_back_domains_first': tabbed_back_domains_first, 'tabbed_back_domains_second': tabbed_back_domains_second, } #total_stats = Counter({'total': 544544, 'first and next equal and correct': 351081, 'first correct only': 88522, 'both incorrect': 51663, 'some previous among past 20 correct': 41231, 'nth previous correct 1': 31202, 'next correct only': 23569, 'no match found': 10432, 'nth previous correct 2': 3311, 'nth previous correct 3': 1635, 'nth previous correct 4': 905, 'nth previous correct 5': 862, 'nth previous correct 6': 545, 'nth previous correct 7': 412, 'nth previous correct 8': 357, 'nth previous correct 9': 269, 'nth previous correct 10': 259, 'nth previous correct 13': 234, 'nth previous correct 11': 229, 'nth previous correct 12': 190, 'nth previous correct 15': 183, 'nth previous correct 14': 140, 'nth previous correct 17': 139, 'nth previous correct 20': 95, 'nth previous correct 16': 90, 'nth previous correct 19': 88, 'nth previous correct 18': 86}) total_stats = Counter() for user in get_test_users(): for k,v in get_recently_seen_domain_stats_for_user_v3(user)['stats'].viewitems(): total_stats[k] += v #total_stats = Counter({'total': 544544, 'first and next equal and correct': 351081, 'first correct only': 88522, 'both incorrect': 51663, 'some previous among past 20 correct': 41136, 'nth previous correct 2': 31202, 'next correct only': 23569, 'no match found': 10527, 'nth previous correct 3': 3311, 'nth previous correct 4': 1635, 'nth previous correct 5': 905, 'nth previous correct 6': 862, 'nth previous correct 7': 545, 'nth previous correct 8': 412, 'nth previous correct 9': 357, 'nth previous correct 10': 269, 'nth previous correct 11': 259, 'nth previous correct 14': 234, 'nth previous correct 12': 229, 'nth previous correct 13': 190, 'nth previous correct 16': 183, 'nth previous correct 15': 140, 'nth previous correct 18': 139, 'nth previous correct 17': 90, 'nth previous correct 20': 88, 'nth previous correct 19': 86}) print_counter(total_stats) def sumkeys(d, *args): return sum(d.get(x, 0.0) for x in args) norm = {k:float(v)/total_stats['total'] for k,v in total_stats.viewitems()} print 'select prev gets answer correct', sumkeys(norm, 'first and next equal and correct', 'first correct only') print 'prev or next gets answer correct', sumkeys(norm, 'first and next equal and correct', 'first correct only', 'next correct only') print 'prev or next or newtab gets answer correct', sumkeys(norm, 'first and next equal and correct', 'first correct only', 'next correct only', 'newtab') for i in range(1, 101): sumprev = sum([norm.get('nth previous correct '+str(x),0.0) for x in range(i+1)]) print 'prev or next or past ' + str(i), sumkeys(norm, 'first and next equal and correct', 'first correct only', 'next correct only', 'newtab')+sumprev #print norm['most_recent_distractor_total'] #print norm['most_recent_distractor_curdomain'] #print norm['most_recent_distractor_nextdomain'] #print norm['most_recent_distractor_some_prev_domain']
34.088889
869
0.690895
bc15bdf610e9b1f737d4ddc01d83395a6a566ea9
1,479
py
Python
pyjbox.py
aanastasiou/pyjunix
a2deb9a5e159155a175098918e3514e30714185d
[ "Apache-2.0" ]
1
2020-09-30T02:59:37.000Z
2020-09-30T02:59:37.000Z
pyjbox.py
aanastasiou/pyjunix
a2deb9a5e159155a175098918e3514e30714185d
[ "Apache-2.0" ]
1
2021-06-02T00:30:47.000Z
2021-06-02T00:30:47.000Z
pyjbox.py
aanastasiou/pyjunix
a2deb9a5e159155a175098918e3514e30714185d
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python3 import sys from pyjunix import (PyJKeys, PyJArray, PyJUnArray, PyJLs, PyJGrep, PyJPrtPrn, PyJSort, PyJLast, PyJPs, PyJJoin, PyJPaste, PyJCat, PyJSplit, PyJDiff, PyJUniq) script_dir = { "pyjkeys": PyJKeys, "pyjarray": PyJArray, "pyjunarray": PyJUnArray, "pyjls": PyJLs, "pyjgrep": PyJGrep, "pyjprtprn": PyJPrtPrn, "pyjsort": PyJSort, "pyjlast": PyJLast, "pyjps": PyJPs, "pyjjoin": PyJJoin, "pyjpaste": PyJPaste, "pyjcat": PyJCat, "pyjsplit": PyJSplit, "pyjdiff": PyJDiff, "pyjuniq": PyJUniq, } if __name__ == "__main__": # Complain if pyjbox doesn't know what to do. if len(sys.argv)<2: print(f"pyjbox is used to launch pyjunix scripts.\n\tUsage: pyjbox <script> [script parameters]\n\tScripts " f"supported in this version:\n\t\t{', '.join(script_dir.keys())}\n") sys.exit(-2) if "pyjbox" in sys.argv[0]: script_to_run = sys.argv[1] script_params = sys.argv[1:] else: script_to_run = sys.argv[0] script_params = sys.argv script_to_run = script_to_run.lower().replace("./","").replace(".py","") result = script_dir[script_to_run](script_params)() sys.stdout.write(result)
33.613636
116
0.535497
eb1f1fe0efaf7045d9a0b2842e0b134a19f30191
6,175
py
Python
UsedElecPred.py
snova301/UsedElecPred
7d85f78270921f48cf01c3f8e32273b270956638
[ "MIT" ]
null
null
null
UsedElecPred.py
snova301/UsedElecPred
7d85f78270921f48cf01c3f8e32273b270956638
[ "MIT" ]
null
null
null
UsedElecPred.py
snova301/UsedElecPred
7d85f78270921f48cf01c3f8e32273b270956638
[ "MIT" ]
null
null
null
import pandas as pd import numpy as np import matplotlib.pyplot as plt import pickle from pycaret.regression import * import jpholiday class ClassGetData: # データ保存場所 foldername = 'data/' def __init__(self, str_year): self.str_year = str_year # 電力使用量 def load_used_elec(self): elec_filename = self.foldername + 'TEPCO' + self.str_year + '.csv' csvreader_elec = pd.read_csv(elec_filename, delimiter=',', dtype='str', skiprows=2)[1:] return csvreader_elec # 電力使用量 def get_used_elec(self): # データ読込 csvreader_elec = self.load_used_elec() # データ列の抜出 dat_elec = csvreader_elec['実績(万kW)'] pd_dat_elec = pd.DataFrame({'Used Elec (x10 MW)' : dat_elec}) pd_dat_elec = pd_dat_elec.reset_index(drop=True) return pd_dat_elec # 気温 def get_temp_data(self): # データ読込 temp_filename = self.foldername + 'Tmp' + self.str_year + '.csv' csvreader_temp = pd.read_csv(temp_filename, encoding='Shift-JIS' ,delimiter=',', dtype='str', skiprows=4) # データ列の抜出 dat_temp = csvreader_temp['Unnamed: 1'] pd_dat_temp = pd.DataFrame({'Temp (Deg)' : dat_temp[:-1]}) return pd_dat_temp # 風速 def get_wind_data(self): # データ読込 wind_filename = self.foldername + 'Wind' + self.str_year + '.csv' csvreader_wind = pd.read_csv(wind_filename, encoding='Shift-JIS' ,delimiter=',', dtype='str', skiprows=5) # データ列の抜出 dat_wind = csvreader_wind['Unnamed: 1'] pd_dat_wind = pd.DataFrame({'Wind (m/s)' : dat_wind[:-1]}) return pd_dat_wind # 天気 def get_weather_data(self): # データ読込 weather_filename = self.foldername + 'We' + self.str_year + '.csv' csvreader_weather = pd.read_csv(weather_filename, encoding='Shift-JIS' ,delimiter=',', dtype='str', skiprows=4) # データ列の抜出 dat_weather = csvreader_weather['Unnamed: 1'] pd_dat_weather = pd.DataFrame({'Weather' : dat_weather[:-1]}, dtype='float') # 補完 pd_dat_weather = pd_dat_weather.interpolate('ffill').interpolate('bfill') return pd_dat_weather # 日付データ分割と曜日祝日取得 def get_date_data(self): # データ読込 csvreader_elec = self.load_used_elec() dt_date = pd.to_datetime(list(csvreader_elec['DATE'])) pd_dt_date = pd.Series(dt_date) # 曜日の取得 dt_dayofweek = dt_date.dayofweek pd_dt_dayofweek = pd.Series(dt_dayofweek) # 祝日の取得 list_holiday = [jpholiday.is_holiday(i) for i in dt_date] list_holiday = ['1' if i == True else '0' for i in list_holiday] # DataFrameに変換 pd_dt_ymdw = pd.DataFrame({'year' : pd_dt_date.dt.year, 'month' : pd_dt_date.dt.month, 'day' : pd_dt_date.dt.day, 'DoW' : pd_dt_dayofweek, 'holiday' : list_holiday}) return pd_dt_ymdw # 時刻データの取得 def get_time_data(self): # データ読込 csvreader_elec = self.load_used_elec() dt_time = pd.to_datetime(list(csvreader_elec['TIME'])) # DataFrameに変換 pd_dt_time = pd.DataFrame({'time' : pd.Series(dt_time).dt.hour}) return pd_dt_time def get_data(self): # データ取得 pd_dat_elec = self.get_used_elec() pd_dat_temp = self.get_temp_data() pd_dat_wind = self.get_wind_data() pd_dat_weather = self.get_weather_data() pd_dt_ymdw = self.get_date_data() pd_dt_time = self.get_time_data() # データの結合 pd_dt_EYMTWDTW = pd.concat([pd_dat_elec, pd_dt_ymdw, pd_dt_time, pd_dat_temp, pd_dat_wind, pd_dat_weather], axis = 1) return pd_dt_EYMTWDTW # tsvデータ保存 def save_tsv(self, save_pd_dt): savefilename = self.foldername + 'data.tsv' save_pd_dt.to_csv(savefilename, sep = '\t', index = False) class ClassLearning: # データ保存場所 foldername = 'data/' # tsvデータのロード def load_data(self): filename = self.foldername + 'data.tsv' tsvreader_data = pd.read_csv(filename, delimiter='\t', dtype='float') return tsvreader_data def data_split(self, tsvreader_data): train_test_indexlist = np.arange(11000, 11200) train_data = tsvreader_data.drop(train_test_indexlist) test_data = tsvreader_data.loc[train_test_indexlist] return train_data, test_data def pycaret_learning(self, tsvreader_data): exp = setup(tsvreader_data, target='Used Elec (x10 MW)') # compare_models() pycaret_create_model = create_model('lightgbm') pycaret_tune_model = tune_model(lgb) # pycaret_final_model = finalize_model(pycaret_tune_model) evaluate_model(pycaret_final_model) return pycaret_tune_model # pickelで学習モデル保存 def save_learningmodel(self, model, modelname): savename_model = self.foldername + modelname + 'model.pkl' pickle.dump(model, open(savename_model, 'wb')) # pickelで学習モデルロード def load_learningmodel(self, modelname): loadname_model = self.foldername + modelname + 'model.pkl' model = pickle.load(open(loadname_model, 'rb')) return model def pycaret_predplot(self, pycaret_final_model, test_data): # 予測 pred_ = predict_model(pycaret_final_model, data = test_data) # 図示 fig, ax = plt.subplots() ax.plot(pred_['Used Elec (x10 MW)'], color='red', label='Prediction Value') ax.plot(pred_['Label'], color='blue', label='True Value') ax.axes.xaxis.set_visible(False) ax.legend() def learning_main(self): # 学習データの準備 tsvreader_data = self.load_data() print(tsvreader_data) train_data, test_data = self.data_split(tsvreader_data) # pycaret学習 pycaret_final_model = self.pycaret_learning(train_data) # pycaret予測 self.pycaret_predplot(pycaret_final_model, test_data) # 学習モデルの保存 self.save_learningmodel(pycaret_final_model, 'pycaret') # 学習モデルの読込 pred_ = self.load_learningmodel('pycaret') def main(): pd_dt4save = pd.DataFrame() for int_year in range(2016, 2022): # データ年の設定 str_year = str(int_year) print(str_year) class_get_data = ClassGetData(str_year) # データ読込と編集 pd_dt_EYMTWDTW = class_get_data.get_data() # データ保管 pd_dt4save = pd.concat([pd_dt4save, pd_dt_EYMTWDTW]) # データ保存 print(pd_dt4save) ClassGetData('2022').save_tsv(pd_dt4save) ClassLearning().learning_main() if __name__ == '__main__': main()
27.815315
121
0.683239
d7adad435330b142025d326da26a926d4facc1bf
4,025
py
Python
agent/thingscope_api.py
irtlab/thingscope
5f0ea230b7aebdb270b7be2ad329e0ed5eabec68
[ "MIT" ]
null
null
null
agent/thingscope_api.py
irtlab/thingscope
5f0ea230b7aebdb270b7be2ad329e0ed5eabec68
[ "MIT" ]
8
2021-05-07T01:52:32.000Z
2021-05-07T02:00:13.000Z
agent/thingscope_api.py
irtlab/thingscope
5f0ea230b7aebdb270b7be2ad329e0ed5eabec68
[ "MIT" ]
null
null
null
import sys import json import requests import traceback class JWTData: def __init__(self, jwt_data): if jwt_data is None: raise Exception('Authorization failed') if not jwt_data['access_token'] or not jwt_data['refresh_token']: raise Exception('Authorization failed') self.access_token = jwt_data['access_token'] self.refresh_token = jwt_data['refresh_token'] class ThingScopeAPI: def __init__(self): self.api_key = '5f7fa6c24816a06e310ca8af' self.secret_key = '406dd70950a5f82c1a45777e91baeca6149581cf0f29084a7d5da6225e60908e' self.url = 'https://thingscope.cs.columbia.edu/api' payload = {'api_key': self.api_key, 'secret_key': self.secret_key} try: res = self.api_request('POST', self.url + '/agent/sign_in', payload) self.jwt_data = JWTData(res) except Exception as e: traceback.print_exc() sys.exit(0) def sign_out(self): auth = {'access_token': self.jwt_data.access_token, 'refresh_token': self.jwt_data.refresh_token} headers = {'authorization': json.dumps(auth)} self.api_request('GET', self.url + '/agent/sign_out', {}, headers) def get_headers(self): return {'authorization': self.jwt_data.access_token} def make_request(self, req_type, url, payload, headers = {}): try: res = None if req_type == 'POST': res = requests.post(url, json=payload, headers=headers) elif req_type == 'GET': res = requests.get(url, json=payload, headers=headers) return res except Exception as e: traceback.print_exc() return None def api_request(self, req_type, url, payload, headers = {}): res = self.make_request(req_type, url, payload, headers) if res is None: return None if res.status_code == 401: # Update access token and repeat the request. tmp_url = self.url + '/agent/' + self.api_key + '/update_access_token' rv = self.make_request('POST', tmp_url, {'refresh_token': self.jwt_data.refresh_token}) if rv and rv.status_code == 200 and rv.text: self.jwt_data = JWTData(rv.json()) else: raise Exception('Failed to update access token') updated_headers = self.get_headers() res = self.make_request(req_type, url, payload, updated_headers) if res.status_code == 200 and res.text: try: data = res.json() return data except Exception as e: return None return res def insert(self, dev_schema): """ Method stores the given device schema and returns stored schema which also contains a unique _id property. Args: -dev_schema: Device schema to be stored. """ headers = self.get_headers() rv = self.api_request('POST', self.url + '/device', dev_schema, headers) if rv is None: raise Exception('Failed to store device schema') return rv def update(self, dev_id, update): """ Method updates a device schema by the given ID and returns updated schema. Args: -dev_id: Unique ID of the device schema. _id property. -dev_schema: Device schema to be stored. """ headers = self.get_headers() url = self.url + '/device/' + str(dev_id) rv = self.api_request('POST', url, update, headers) if rv is None: raise Exception('Failed to update device schema') return rv def get_devices(self): """Returns a list of devices""" return self.api_request('GET', self.url + '/device', {}) def get_device(self, dev_id): """Returns a device by the given device ID""" return self.api_request('GET', self.url + '/device/' + str(dev_id), {})
34.698276
105
0.598012
126672f92d255baa886fdc333493ff6260a7dfa5
19,036
py
Python
easy_thumbnails/tests/test_files.py
fdemmer/easy-thumbnails
bc39d7ec3f4c72b000a82f7838eb3c16bcaa86c7
[ "BSD-3-Clause" ]
null
null
null
easy_thumbnails/tests/test_files.py
fdemmer/easy-thumbnails
bc39d7ec3f4c72b000a82f7838eb3c16bcaa86c7
[ "BSD-3-Clause" ]
null
null
null
easy_thumbnails/tests/test_files.py
fdemmer/easy-thumbnails
bc39d7ec3f4c72b000a82f7838eb3c16bcaa86c7
[ "BSD-3-Clause" ]
1
2022-02-15T15:35:49.000Z
2022-02-15T15:35:49.000Z
from io import BytesIO from os import path from django.test import TestCase from easy_thumbnails import files, utils, signals, exceptions, models, engine from easy_thumbnails.conf import settings from easy_thumbnails.options import ThumbnailOptions from easy_thumbnails.tests import utils as test from PIL import Image try: from testfixtures import LogCapture except ImportError: LogCapture = None import unittest class FilesTest(test.BaseTest): def setUp(self): super().setUp() self.storage = test.TemporaryStorage() self.remote_storage = test.FakeRemoteStorage() # Save a test image in both storages. filename = self.create_image(self.storage, 'test.jpg') self.thumbnailer = files.get_thumbnailer(self.storage, filename) self.thumbnailer.thumbnail_storage = self.storage filename = self.create_image(self.remote_storage, 'test.jpg') self.remote_thumbnailer = files.get_thumbnailer( self.remote_storage, filename) self.remote_thumbnailer.thumbnail_storage = self.remote_storage # Create another thumbnailer for extension test. self.ext_thumbnailer = files.get_thumbnailer(self.storage, filename) self.ext_thumbnailer.thumbnail_storage = self.storage # Generate test transparent images. filename = self.create_image( self.storage, 'transparent.png', image_mode='RGBA', image_format='PNG') self.transparent_thumbnailer = files.get_thumbnailer( self.storage, filename) self.transparent_thumbnailer.thumbnail_storage = self.storage filename = self.create_image( self.storage, 'transparent-greyscale.png', image_mode='LA', image_format='PNG') self.transparent_greyscale_thumbnailer = files.get_thumbnailer( self.storage, filename) self.transparent_greyscale_thumbnailer.thumbnail_storage = self.storage def tearDown(self): self.storage.delete_temporary_storage() self.remote_storage.delete_temporary_storage() super().tearDown() def test_tag(self): local = self.thumbnailer.get_thumbnail({'size': (100, 100)}) remote = self.remote_thumbnailer.get_thumbnail({'size': (100, 100)}) self.assertEqual( local.tag(), '<img alt="" height="75" src="%s" width="100" ' '/>' % local.url) self.assertEqual( local.tag(alt='A & B'), '<img alt="A &amp; B" height="75" ' 'src="%s" width="100" />' % local.url) # Can turn off dimensions. self.assertEqual( remote.tag(use_size=False), '<img alt="" src="%s" />' % remote.url) # Even a remotely generated thumbnail has the dimensions cached if it # was just created. self.assertEqual( remote.tag(), '<img alt="" height="75" src="%s" width="100" />' % remote.url) # Future requests to thumbnails on remote storage don't get # dimensions... remote = self.remote_thumbnailer.get_thumbnail({'size': (100, 100)}) self.assertEqual( remote.tag(), '<img alt="" src="%s" />' % remote.url) # ...unless explicitly requested. self.assertEqual( remote.tag(use_size=True), '<img alt="" height="75" src="%s" width="100" />' % remote.url) # All other arguments are passed through as attributes. self.assertEqual( local.tag(**{'rel': 'A&B', 'class': 'fish'}), '<img alt="" class="fish" height="75" rel="A&amp;B" ' 'src="%s" width="100" />' % local.url) def test_tag_cached_dimensions(self): settings.THUMBNAIL_CACHE_DIMENSIONS = True self.remote_thumbnailer.get_thumbnail({'size': (100, 100)}) # Look up thumbnail again to ensure dimensions are a *really* cached. remote = self.remote_thumbnailer.get_thumbnail({'size': (100, 100)}) self.assertEqual( remote.tag(), '<img alt="" height="75" src="%s" width="100" />' % remote.url) def test_transparent_thumbnailing(self): thumb_file = self.thumbnailer.get_thumbnail( {'size': (100, 100)}) thumb_file.seek(0) with Image.open(thumb_file) as thumb: self.assertFalse( utils.is_transparent(thumb), "%s shouldn't be transparent." % thumb_file.name) thumb_file = self.transparent_thumbnailer.get_thumbnail( {'size': (100, 100)}) thumb_file.seek(0) with Image.open(thumb_file) as thumb: self.assertTrue( utils.is_transparent(thumb), "%s should be transparent." % thumb_file.name) thumb_file = self.transparent_greyscale_thumbnailer.get_thumbnail( {'size': (100, 100)}) thumb_file.seek(0) with Image.open(thumb_file) as thumb: self.assertTrue( utils.is_transparent(thumb), "%s should be transparent." % thumb_file.name) def test_missing_thumb(self): opts = {'size': (100, 100)} thumb = self.thumbnailer.get_thumbnail(opts) thumb_cache = self.thumbnailer.get_thumbnail_cache( thumbnail_name=thumb.name) thumb_cache.delete() thumb.storage.delete(thumb.name) self.thumbnailer.get_thumbnail(opts) def test_missing_thumb_from_storage(self): opts = {'size': (100, 100)} thumb = self.thumbnailer.get_thumbnail(opts) thumb.storage.delete(thumb.name) new_thumb = self.thumbnailer.get_thumbnail(opts) self.assertEqual(thumb.name, new_thumb.name) self.assertTrue(thumb.storage.exists(new_thumb.name)) def test_missing_remote_thumb(self): opts = {'size': (100, 100)} thumb = self.remote_thumbnailer.get_thumbnail(opts) thumb_cache = self.remote_thumbnailer.get_thumbnail_cache( thumbnail_name=thumb.name) thumb_cache.delete() thumb.storage.delete(thumb.name) self.remote_thumbnailer.get_thumbnail(opts) def test_missing_source(self): opts = {'size': (100, 100)} self.storage.delete(self.thumbnailer.name) self.assertRaises( exceptions.InvalidImageFormatError, self.thumbnailer.get_thumbnail, opts) def test_extensions(self): self.ext_thumbnailer.thumbnail_extension = 'png' thumb = self.ext_thumbnailer.get_thumbnail({'size': (100, 100)}) self.assertEqual(path.splitext(thumb.name)[1], '.png') self.ext_thumbnailer.thumbnail_preserve_extensions = ('foo',) thumb = self.ext_thumbnailer.get_thumbnail({'size': (100, 100)}) self.assertEqual(path.splitext(thumb.name)[1], '.png') self.ext_thumbnailer.thumbnail_preserve_extensions = True thumb = self.ext_thumbnailer.get_thumbnail({'size': (100, 100)}) self.assertEqual(path.splitext(thumb.name)[1], '.jpg') self.ext_thumbnailer.thumbnail_preserve_extensions = ('foo', 'jpg') thumb = self.ext_thumbnailer.get_thumbnail({'size': (100, 100)}) self.assertEqual(path.splitext(thumb.name)[1], '.jpg') def test_subsampling(self): samplings = { 0: (1, 1, 1, 1, 1, 1), 1: (2, 1, 1, 1, 1, 1), 2: (2, 2, 1, 1, 1, 1), } thumb = self.ext_thumbnailer.get_thumbnail({'size': (100, 100)}) with Image.open(thumb.path) as im: self.assertNotIn('ss', thumb.name) sampling = im.layer[0][1:3] + im.layer[1][1:3] + im.layer[2][1:3] self.assertEqual(sampling, samplings[2]) thumb = self.ext_thumbnailer.get_thumbnail( {'size': (100, 100), 'subsampling': 1}) with Image.open(thumb.path) as im: self.assertIn('ss1', thumb.name) sampling = im.layer[0][1:3] + im.layer[1][1:3] + im.layer[2][1:3] self.assertEqual(sampling, samplings[1]) thumb = self.ext_thumbnailer.get_thumbnail( {'size': (100, 100), 'subsampling': 0}) with Image.open(thumb.path) as im: self.assertIn('ss0', thumb.name) sampling = im.layer[0][1:3] + im.layer[1][1:3] + im.layer[2][1:3] self.assertEqual(sampling, samplings[0]) def test_default_subsampling(self): settings.THUMBNAIL_DEFAULT_OPTIONS = {'subsampling': 1} thumb = self.ext_thumbnailer.get_thumbnail({'size': (100, 100)}) with Image.open(thumb.path) as im: self.assertIn('ss1', thumb.name) sampling = im.layer[0][1:3] + im.layer[1][1:3] + im.layer[2][1:3] self.assertEqual(sampling, (2, 1, 1, 1, 1, 1)) @unittest.skipIf( 'easy_thumbnails.optimize' not in settings.INSTALLED_APPS, 'optimize app not installed') @unittest.skipIf(LogCapture is None, 'testfixtures not installed') def test_postprocessor(self): """use a mock image optimizing post processor doing nothing""" settings.THUMBNAIL_OPTIMIZE_COMMAND = { 'png': 'easy_thumbnails/tests/mockoptim.py {filename}'} with LogCapture() as logcap: self.ext_thumbnailer.thumbnail_extension = 'png' self.ext_thumbnailer.get_thumbnail({'size': (10, 10)}) actual = tuple(logcap.actual())[0] self.assertEqual(actual[0], 'easy_thumbnails.optimize') self.assertEqual(actual[1], 'INFO') self.assertRegex( actual[2], '^easy_thumbnails/tests/mockoptim.py [^ ]+ returned nothing$') @unittest.skipIf( 'easy_thumbnails.optimize' not in settings.INSTALLED_APPS, 'optimize app not installed') @unittest.skipIf(LogCapture is None, 'testfixtures not installed') def test_postprocessor_fail(self): """use a mock image optimizing post processor doing nothing""" settings.THUMBNAIL_OPTIMIZE_COMMAND = { 'png': 'easy_thumbnails/tests/mockoptim_fail.py {filename}'} with LogCapture() as logcap: self.ext_thumbnailer.thumbnail_extension = 'png' self.ext_thumbnailer.get_thumbnail({'size': (10, 10)}) actual = tuple(logcap.actual())[0] self.assertEqual(actual[0], 'easy_thumbnails.optimize') self.assertEqual(actual[1], 'ERROR') self.assertRegex( actual[2], r'^Command\ .+returned non-zero exit status 1.?$') def test_USE_TZ(self): settings.USE_TZ = True self.thumbnailer.get_thumbnail({'size': (10, 20)}) settings.USE_TZ = False self.thumbnailer.get_thumbnail({'size': (20, 40)}) def test_thumbnailfile_options(self): opts = {'size': (50, 50), 'crop': True, 'upscale': True} thumb = self.thumbnailer.get_thumbnail(opts) self.assertEqual(thumb.thumbnail_options, ThumbnailOptions(opts)) def test_get_thumbnail_name(self): opts = { 'size': (50, 50), 'crop': 'smart', 'upscale': True, 'target': (10, 10)} self.assertEqual( self.thumbnailer.get_thumbnail_name(opts), 'test.jpg.50x50_q85_crop-smart_target-10,10_upscale.jpg') def test_default_options_setting(self): settings.THUMBNAIL_DEFAULT_OPTIONS = {'crop': True} opts = {'size': (50, 50)} thumb = self.thumbnailer.get_thumbnail(opts) self.assertEqual((thumb.width, thumb.height), (50, 50)) def test_dimensions_of_cached_image(self): opts = {'size': (50, 50)} thumb = self.thumbnailer.get_thumbnail(opts) self.assertEqual((thumb.width, thumb.height), (50, 38)) # Now the thumb has been created, check that retrieving this still # gives access to the dimensions. thumb = self.thumbnailer.get_thumbnail(opts) self.assertEqual((thumb.width, thumb.height), (50, 38)) def test_cached_dimensions_of_cached_image(self): settings.THUMBNAIL_CACHE_DIMENSIONS = True opts = {'size': (50, 50)} thumb = self.thumbnailer.get_thumbnail(opts) self.assertEqual((thumb.width, thumb.height), (50, 38)) # Now the thumb has been created, check that dimesions are in the # database. dimensions = models.ThumbnailDimensions.objects.all()[0] self.assertEqual( (thumb.width, thumb.height), (dimensions.width, dimensions.height)) def test_remote_cached_dimensions_queries(self): settings.THUMBNAIL_CACHE_DIMENSIONS = True opts = {'size': (50, 50)} thumb = self.remote_thumbnailer.get_thumbnail(opts) thumb.height # Trigger dimension caching. # Get thumb again (which now has cached dimensions). thumb = self.remote_thumbnailer.get_thumbnail(opts) with self.assertNumQueries(0): self.assertEqual(thumb.width, 50) def test_add_dimension_cache(self): settings.THUMBNAIL_CACHE_DIMENSIONS = True opts = {'size': (50, 50)} thumb = self.thumbnailer.get_thumbnail(opts) self.assertEqual((thumb.width, thumb.height), (50, 38)) # Delete the created dimensions. models.ThumbnailDimensions.objects.all().delete() # Now access the thumbnail again. thumb = self.thumbnailer.get_thumbnail(opts) self.assertEqual(models.ThumbnailDimensions.objects.count(), 0) thumb.height dimensions = models.ThumbnailDimensions.objects.get() # and make sure they match when fetched again. thumb = self.thumbnailer.get_thumbnail(opts) self.assertEqual( (thumb.width, thumb.height), (dimensions.width, dimensions.height)) # close the filefield (cause unclosed file ResourceWarning) thumb.close() def test_thumbnail_created_signal(self): def signal_handler(sender, **kwargs): sender.signal_received = True signals.thumbnail_created.connect(signal_handler) try: thumb = self.thumbnailer.get_thumbnail({'size': (10, 20)}) self.assertTrue(hasattr(thumb, 'signal_received')) finally: signals.thumbnail_created.disconnect(signal_handler) def test_passive_thumbnailer(self): options = {'size': (10, 10)} # Explicitly using the generate=False option on get_thumbnail won't # generate a missing thumb. thumb = self.thumbnailer.get_thumbnail(options, generate=False) self.assertEqual(thumb, None) # If the thumbnailer has generate=False, get_thumbnail won't generate a # missing thumb by default. self.thumbnailer.generate = False thumb = self.thumbnailer.get_thumbnail(options) self.assertEqual(thumb, None) # If the thumbnailer has generate=False, get_thumbnail with # generate=True will stiff force generation a missing thumb. thumb = self.thumbnailer.get_thumbnail(options, generate=True) self.assertTrue(thumb) # If the thumbnailer has generate=False, get_thumbnail will still # return existing thumbnails. thumb = self.thumbnailer.get_thumbnail(options) self.assertTrue(thumb) # Explicitly using the generate=False option on get_thumbnail will # still return existing thumbnails. thumb = self.thumbnailer.get_thumbnail(options, generate=False) self.assertTrue(thumb) def test_thumbnail_missed_signal(self): def signal_handler(sender, **kwargs): sender.missed_signal = kwargs.get('options') signals.thumbnail_missed.connect(signal_handler) try: # Standard generation doesn't trigger signal. self.thumbnailer.get_thumbnail({'size': (100, 100)}) self.assertFalse(hasattr(self.thumbnailer, 'missed_signal')) # Retrieval doesn't trigger signal. self.thumbnailer.get_thumbnail( {'size': (100, 100)}, generate=False) self.assertFalse(hasattr(self.thumbnailer, 'missed_signal')) # A thumbnail miss does trigger it. options = {'size': (10, 20)} thumb = self.thumbnailer.get_thumbnail(options, generate=False) self.assertEqual(thumb, None) self.assertEqual( self.thumbnailer.missed_signal, ThumbnailOptions(options)) finally: signals.thumbnail_created.disconnect(signal_handler) def test_progressive_encoding(self): thumb = self.thumbnailer.generate_thumbnail( {'size': (99, 99), 'crop': True}) with Image.open(thumb) as thumb_image: self.assertFalse(utils.is_progressive(thumb_image)) thumb = self.thumbnailer.generate_thumbnail( {'size': (1, 100), 'crop': True}) with Image.open(thumb) as thumb_image: self.assertTrue(utils.is_progressive(thumb_image)) thumb = self.thumbnailer.generate_thumbnail( {'size': (100, 1), 'crop': True}) with Image.open(thumb) as thumb_image: self.assertTrue(utils.is_progressive(thumb_image)) thumb = self.thumbnailer.generate_thumbnail({'size': (200, 200)}) with Image.open(thumb) as thumb_image: self.assertTrue(utils.is_progressive(thumb_image)) def test_no_progressive_encoding(self): settings.THUMBNAIL_PROGRESSIVE = False thumb = self.thumbnailer.generate_thumbnail({'size': (200, 200)}) with Image.open(thumb) as thumb_image: self.assertFalse(utils.is_progressive(thumb_image)) class FakeSourceGenerator: def __init__(self, fail=False): self.fail = fail def __call__(self, source, **kwargs): if self.fail: raise ValueError("Fake source generator failed") return source class EngineTest(TestCase): def setUp(self): self.source = BytesIO(b'file-contents') def test_single_fail(self): source_generators = [FakeSourceGenerator(fail=True)] self.assertRaises( ValueError, engine.generate_source_image, self.source, {}, source_generators, fail_silently=False) def test_single_silent_fail(self): source_generators = [FakeSourceGenerator(fail=True)] image = engine.generate_source_image( self.source, {}, source_generators) self.assertEqual(image, None) def test_multiple_fail(self): source_generators = [ FakeSourceGenerator(fail=True), FakeSourceGenerator(fail=True)] self.assertRaises( engine.NoSourceGenerator, engine.generate_source_image, self.source, {}, source_generators, fail_silently=False) def test_multiple_silent_fail(self): source_generators = [ FakeSourceGenerator(fail=True), FakeSourceGenerator(fail=True)] image = engine.generate_source_image( self.source, {}, source_generators) self.assertEqual(image, None)
41.654267
79
0.636426
ddf0c68809b0e35b5ae9ab4f8ecebfd183bfcc8a
6,816
py
Python
goose3/text.py
Noblis/goose3
67305444549b00ab02398ee44128a36f5e9f8cba
[ "Apache-2.0" ]
575
2017-03-13T18:34:07.000Z
2022-03-28T07:06:42.000Z
goose3/text.py
Noblis/goose3
67305444549b00ab02398ee44128a36f5e9f8cba
[ "Apache-2.0" ]
101
2017-03-22T11:35:58.000Z
2022-03-29T17:23:28.000Z
goose3/text.py
lun3322/goose3
67305444549b00ab02398ee44128a36f5e9f8cba
[ "Apache-2.0" ]
86
2017-03-28T17:02:24.000Z
2022-03-28T07:06:53.000Z
# -*- coding: utf-8 -*- """\ This is a python port of "Goose" orignialy licensed to Gravity.com under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Python port was written by Xavier Grangier for Recrutae Gravity.com licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ import os import re import string from goose3.utils import FileHelper from goose3.utils.encoding import (smart_unicode, smart_str, DjangoUnicodeDecodeError) SPACE_SYMBOLS = re.compile(r'[\s\xa0\t]') TABSSPACE = re.compile(r'[\s\t]+') def get_encodings_from_content(content): """ Code from: https://github.com/sigmavirus24/requests-toolbelt/blob/master/requests_toolbelt/utils/deprecated.py Return encodings from given content string. :param content: string to extract encodings from. """ if isinstance(content, bytes): find_charset = re.compile( br'<meta.*?charset=["\']*([a-zA-Z0-9\-_]+?) *?["\'>]', flags=re.I ).findall find_xml = re.compile( br'^<\?xml.*?encoding=["\']*([a-zA-Z0-9\-_]+?) *?["\'>]' ).findall return [encoding.decode('utf-8') for encoding in find_charset(content) + find_xml(content)] else: find_charset = re.compile( r'<meta.*?charset=["\']*([a-zA-Z0-9\-_]+?) *?["\'>]', flags=re.I ).findall find_xml = re.compile( r'^<\?xml.*?encoding=["\']*([a-zA-Z0-9\-_]+?) *?["\'>]' ).findall return find_charset(content) + find_xml(content) def innerTrim(value): if isinstance(value, str): # remove tab and white space value = re.sub(TABSSPACE, ' ', value) value = ''.join(value.splitlines()) return value.strip() return '' def encodeValue(value): string_org = value try: value = smart_unicode(value) except (UnicodeEncodeError, DjangoUnicodeDecodeError): value = smart_str(value) except Exception: value = string_org return value class WordStats(object): def __init__(self): # total number of stopwords or # good words that we can calculate self.stop_word_count = 0 # total number of words on a node self.word_count = 0 # holds an actual list # of the stop words we found self.stop_words = [] def get_stop_words(self): return self.stop_words def set_stop_words(self, words): self.stop_words = words def get_stopword_count(self): return self.stop_word_count def set_stopword_count(self, wordcount): self.stop_word_count = wordcount def get_word_count(self): return self.word_count def set_word_count(self, cnt): self.word_count = cnt class StopWords(object): _cached_stop_words = {} def __init__(self, language='en'): if language not in self._cached_stop_words: path = os.path.join('text', 'stopwords-%s.txt' % language) try: content = FileHelper.loadResourceFile(path) word_list = content.splitlines() except IOError: word_list = [] self._cached_stop_words[language] = set(word_list) self._stop_words = self._cached_stop_words[language] @staticmethod def remove_punctuation(content): # code taken form # http://stackoverflow.com/questions/265960/best-way-to-strip-punctuation-from-a-string-in-python if not isinstance(content, str): content = content.decode('utf-8') tbl = dict.fromkeys(ord(x) for x in string.punctuation) return content.translate(tbl) @staticmethod def candidate_words(stripped_input): return re.split(SPACE_SYMBOLS, stripped_input) def get_stopword_count(self, content): if not content: return WordStats() stats = WordStats() stripped_input = self.remove_punctuation(content) candidate_words = self.candidate_words(stripped_input) overlapping_stopwords = [] i = 0 for word in candidate_words: i += 1 if word.lower() in self._stop_words: overlapping_stopwords.append(word.lower()) stats.set_word_count(i) stats.set_stopword_count(len(overlapping_stopwords)) stats.set_stop_words(overlapping_stopwords) return stats class StopWordsChinese(StopWords): """ Chinese segmentation """ def __init__(self, language='zh'): # force zh languahe code super(StopWordsChinese, self).__init__(language='zh') @staticmethod def candidate_words(stripped_input): # jieba build a tree that takes sometime # avoid building the tree if we don't use # chinese language import jieba return jieba.cut(stripped_input, cut_all=True) class StopWordsArabic(StopWords): """ Arabic segmentation """ def __init__(self, language='ar'): # force ar languahe code super(StopWordsArabic, self).__init__(language='ar') @staticmethod def remove_punctuation(content): return content @staticmethod def candidate_words(stripped_input): import nltk stemmer = nltk.stem.isri.ISRIStemmer() words = [] for word in nltk.tokenize.wordpunct_tokenize(stripped_input): words.append(stemmer.stem(word)) return words class StopWordsKorean(StopWords): """ Korean segmentation """ def __init__(self, language='ko'): super(StopWordsKorean, self).__init__(language='ko') def get_stopword_count(self, content): if not content: return WordStats() stats = WordStats() stripped_input = self.remove_punctuation(content) candidate_words = self.candidate_words(stripped_input) overlapping_stopwords = [] i = 0 for _ in candidate_words: i += 1 for stop_word in self._stop_words: overlapping_stopwords.append(stop_word) stats.set_word_count(i) stats.set_stopword_count(len(overlapping_stopwords)) stats.set_stop_words(overlapping_stopwords) return stats
30.293333
105
0.646127
37f5b5cbf4ad3e575490669d46bc90143626f1de
1,663
py
Python
wazimap_ng/profile/serializers/highlights_serializer.py
CodeForAfrica/wazimap-ng
691d92a4685e60b6846d38a9cb0e60f1549c1d0d
[ "Apache-2.0" ]
null
null
null
wazimap_ng/profile/serializers/highlights_serializer.py
CodeForAfrica/wazimap-ng
691d92a4685e60b6846d38a9cb0e60f1549c1d0d
[ "Apache-2.0" ]
1
2021-03-18T14:02:24.000Z
2021-04-14T15:23:30.000Z
wazimap_ng/profile/serializers/highlights_serializer.py
CodeForAfrica/wazimap-ng
691d92a4685e60b6846d38a9cb0e60f1549c1d0d
[ "Apache-2.0" ]
null
null
null
from wazimap_ng.datasets.models import IndicatorData from .helpers import MetricCalculator def get_indicator_data(highlight, geographies): return IndicatorData.objects.filter( indicator__profilehighlight=highlight, geography__in=geographies ) def absolute_value(highlight, geography): indicator_data = get_indicator_data(highlight, [geography]).first() if indicator_data: return MetricCalculator.absolute_value( indicator_data.data, highlight, geography ) return None def subindicator(highlight, geography): indicator_data = get_indicator_data(highlight, [geography]).first() if indicator_data: return MetricCalculator.subindicator( indicator_data.data, highlight, geography ) return None def sibling(highlight, geography): siblings = list(geography.get_siblings()) indicator_data = get_indicator_data(highlight, [geography] + siblings) if indicator_data: return MetricCalculator.sibling(indicator_data, highlight, geography) return None algorithms = { "absolute_value": absolute_value, "sibling": sibling, "subindicators": subindicator } def HighlightsSerializer(profile, geography): highlights = [] profile_highlights = profile.profilehighlight_set.all().order_by("order") for highlight in profile_highlights: denominator = highlight.denominator method = algorithms.get(denominator, absolute_value) val = method(highlight, geography) if val is not None: highlights.append({"label": highlight.label, "value": val, "method": denominator}) return highlights
30.236364
94
0.72279
6580a3b1c72947b38f43bef0175d7e1e37128063
3,239
py
Python
todopy/todopy/settings.py
riihikallio/kubernetes
4506f55def6f21557675f1e07b8f4e436fba43e4
[ "MIT" ]
null
null
null
todopy/todopy/settings.py
riihikallio/kubernetes
4506f55def6f21557675f1e07b8f4e436fba43e4
[ "MIT" ]
null
null
null
todopy/todopy/settings.py
riihikallio/kubernetes
4506f55def6f21557675f1e07b8f4e436fba43e4
[ "MIT" ]
null
null
null
""" Django settings for todopy project. Generated by 'django-admin startproject' using Django 3.2.5. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-3x47slrx11a_%*=fgx^5(8z1f^^kl25wffi!lo&%8w^)5swv6n' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'todopy.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'todopy.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
25.706349
91
0.701451
79e7a16f60abad0dd057b28c9765212b60ecd032
10,026
py
Python
evoMPS/tests/tdvp_common_tests.py
asirabrar7/evoMPS
afae13f055ba2352ce0c9b275e4799c7c135b4ff
[ "BSD-3-Clause" ]
57
2015-05-06T17:50:52.000Z
2022-03-21T19:06:05.000Z
evoMPS/tests/tdvp_common_tests.py
asirabrar7/evoMPS
afae13f055ba2352ce0c9b275e4799c7c135b4ff
[ "BSD-3-Clause" ]
10
2016-03-02T22:18:05.000Z
2022-03-16T23:02:33.000Z
evoMPS/tests/tdvp_common_tests.py
asirabrar7/evoMPS
afae13f055ba2352ce0c9b275e4799c7c135b4ff
[ "BSD-3-Clause" ]
20
2015-03-19T08:49:34.000Z
2022-03-10T09:52:19.000Z
# -*- coding: utf-8 -*- """ Created on Fri Jan 11 18:11:02 2013 @author: ash """ from __future__ import absolute_import, division, print_function import scipy as sp import evoMPS.matmul as mm import evoMPS.tdvp_common as tc import unittest def make_E_noop(A, B): res = sp.zeros((A.shape[1]**2, A.shape[2]**2), dtype=A.dtype) for s in range(A.shape[0]): res += sp.kron(A[s], B[s].conj()) return res def make_E_1s(A, B, op): res = sp.zeros((A.shape[1]**2, A.shape[2]**2), dtype=A.dtype) for s in range(A.shape[0]): for t in range(A.shape[0]): res += sp.kron(A[s], B[t].conj()) * op[t, s] return res def make_E_2s(A1, A2, B1, B2, op): res = sp.zeros((A1.shape[1]**2, A2.shape[2]**2), dtype=A1.dtype) for s in range(A1.shape[0]): for t in range(A2.shape[0]): for u in range(A1.shape[0]): for v in range(A2.shape[0]): res += sp.kron(A1[s].dot(A2[t]), B1[u].dot(B2[v]).conj()) * op[u, v, s, t] return res class TestOps(unittest.TestCase): def setUp(self): #TODO: Test rectangular x as well self.d = [2, 3] self.D = [2, 4, 3] self.l0 = sp.rand(self.D[0], self.D[0]) + 1.j * sp.rand(self.D[0], self.D[0]) self.r1 = sp.rand(self.D[1], self.D[1]) + 1.j * sp.rand(self.D[1], self.D[1]) self.r2 = sp.rand(self.D[2], self.D[2]) + 1.j * sp.rand(self.D[2], self.D[2]) self.ld0 = mm.simple_diag_matrix(sp.rand(self.D[0]) + 1.j * sp.rand(self.D[0])) self.rd1 = mm.simple_diag_matrix(sp.rand(self.D[1]) + 1.j * sp.rand(self.D[1])) self.rd2 = mm.simple_diag_matrix(sp.rand(self.D[2]) + 1.j * sp.rand(self.D[2])) self.eye0 = mm.eyemat(self.D[0], dtype=sp.complex128) self.eye1 = mm.eyemat(self.D[1], dtype=sp.complex128) self.eye2 = mm.eyemat(self.D[2], dtype=sp.complex128) self.A0 = sp.rand(self.d[0], self.D[0], self.D[0]) + 1.j * sp.rand(self.d[0], self.D[0], self.D[0]) self.A1 = sp.rand(self.d[0], self.D[0], self.D[1]) + 1.j * sp.rand(self.d[0], self.D[0], self.D[1]) self.A2 = sp.rand(self.d[1], self.D[1], self.D[2]) + 1.j * sp.rand(self.d[1], self.D[1], self.D[2]) self.A3 = sp.rand(self.d[1], self.D[2], self.D[2]) + 1.j * sp.rand(self.d[1], self.D[2], self.D[2]) self.B1 = sp.rand(self.d[0], self.D[0], self.D[1]) + 1.j * sp.rand(self.d[0], self.D[0], self.D[1]) self.B2 = sp.rand(self.d[1], self.D[1], self.D[2]) + 1.j * sp.rand(self.d[1], self.D[1], self.D[2]) self.E1_AB = make_E_noop(self.A1, self.B1) self.E2_AB = make_E_noop(self.A2, self.B2) self.op1s_1 = sp.rand(self.d[0], self.d[0]) + 1.j * sp.rand(self.d[0], self.d[0]) self.E1_op_AB = make_E_1s(self.A1, self.B1, self.op1s_1) self.op2s = sp.rand(self.d[0], self.d[1], self.d[0], self.d[1]) + 1.j * sp.rand(self.d[0], self.d[1], self.d[0], self.d[1]) self.E12_op = make_E_2s(self.A1, self.A2, self.B1, self.B2, self.op2s) self.AA12 = tc.calc_AA(self.A1, self.A2) self.BB12 = tc.calc_AA(self.B1, self.B2) self.C_A12 = tc.calc_C_mat_op_AA(self.op2s, self.AA12) self.C_conj_B12 = tc.calc_C_conj_mat_op_AA(self.op2s, self.BB12) self.C01 = sp.rand(self.d[0], self.d[0], self.D[0], self.D[1]) + 1.j * sp.rand(self.d[0], self.d[0], self.D[0], self.D[1]) def test_eps_l_noop(self): l1 = tc.eps_l_noop(self.l0, self.A1, self.B1) l1_ = self.E1_AB.conj().T.dot(self.l0.ravel()).reshape(self.D[1], self.D[1]) self.assertTrue(sp.allclose(l1, l1_)) def test_eps_l_noop_diag(self): l1 = tc.eps_l_noop(self.ld0, self.A1, self.B1) l1_ = self.E1_AB.conj().T.dot(self.ld0.A.ravel()).reshape(self.D[1], self.D[1]) self.assertTrue(sp.allclose(l1, l1_)) def test_eps_l_noop_eye(self): l1 = tc.eps_l_noop(self.eye0, self.A1, self.B1) l1_ = self.E1_AB.conj().T.dot(self.eye0.A.ravel()).reshape(self.D[1], self.D[1]) self.assertTrue(sp.allclose(l1, l1_)) def test_eps_l_noop_inplace(self): l1 = sp.zeros_like(self.r1) l1_ = tc.eps_l_noop_inplace(self.l0, self.A1, self.B1, l1) self.assertTrue(l1 is l1_) l1__ = tc.eps_l_noop(self.l0, self.A1, self.B1) self.assertTrue(sp.allclose(l1, l1__)) def test_eps_r_noop(self): r0 = tc.eps_r_noop(self.r1, self.A1, self.B1) r0_ = self.E1_AB.dot(self.r1.ravel()).reshape(self.D[0], self.D[0]) self.assertTrue(sp.allclose(r0, r0_)) r1 = tc.eps_r_noop(self.r2, self.A2, self.B2) r1_ = self.E2_AB.dot(self.r2.ravel()).reshape(self.D[1], self.D[1]) self.assertTrue(sp.allclose(r1, r1_)) def test_eps_r_noop_diag(self): r0 = tc.eps_r_noop(self.rd1, self.A1, self.B1) r0_ = self.E1_AB.dot(self.rd1.A.ravel()).reshape(self.D[0], self.D[0]) self.assertTrue(sp.allclose(r0, r0_)) def test_eps_r_noop_eye(self): r0 = tc.eps_r_noop(self.eye1, self.A1, self.B1) r0_ = self.E1_AB.dot(self.eye1.A.ravel()).reshape(self.D[0], self.D[0]) self.assertTrue(sp.allclose(r0, r0_)) def test_eps_r_noop_multi(self): r0 = tc.eps_r_noop(tc.eps_r_noop(self.r2, self.A2, self.B2), self.A1, self.B1) r0_ = tc.eps_r_noop_multi(self.r2, [self.A1, self.A2], [self.B1, self.B2]) self.assertTrue(sp.allclose(r0, r0_)) r0__ = tc.eps_r_noop_multi(self.r2, [self.AA12], [self.BB12]) self.assertTrue(sp.allclose(r0, r0__)) r0C = tc.eps_r_op_2s_C12(self.r2, self.C_A12, self.B1, self.B2) r0C_ = tc.eps_r_noop_multi(self.r2, [self.C_A12], [self.B1, self.B2]) self.assertTrue(sp.allclose(r0C, r0C_)) r0C2 = tc.eps_r_op_2s_C12_AA34(self.r2, self.C_A12, self.BB12) r0C2_ = tc.eps_r_noop_multi(self.r2, [self.C_A12], [self.BB12]) self.assertTrue(sp.allclose(r0C2, r0C2_)) r0CA2 = tc.eps_r_op_2s_C12(tc.eps_r_noop(self.r2, self.A2, self.B2), self.C01, self.A0, self.B1) r0CA2_ = tc.eps_r_noop_multi(self.r2, [self.C01, self.A2], [self.A0, self.BB12]) self.assertTrue(sp.allclose(r0CA2, r0CA2_)) def test_eps_r_noop_inplace(self): r0 = sp.zeros_like(self.l0) r0_ =tc.eps_r_noop_inplace(self.r1, self.A1, self.B1, r0) self.assertTrue(r0 is r0_) r0__ = tc.eps_r_noop(self.r1, self.A1, self.B1) self.assertTrue(sp.allclose(r0, r0__)) def test_eps_l_op_1s(self): l1 = tc.eps_l_op_1s(self.l0, self.A1, self.B1, self.op1s_1) l1_ = self.E1_op_AB.conj().T.dot(self.l0.ravel()).reshape(self.D[1], self.D[1]) self.assertTrue(sp.allclose(l1, l1_)) def test_eps_r_op_1s(self): r0 = tc.eps_r_op_1s(self.r1, self.A1, self.B1, self.op1s_1) r0_ = self.E1_op_AB.dot(self.r1.ravel()).reshape(self.D[0], self.D[0]) self.assertTrue(sp.allclose(r0, r0_)) def test_eps_r_op_2s_A(self): r0 = tc.eps_r_op_2s_A(self.r2, self.A1, self.A2, self.B1, self.B2, self.op2s) r0_ = self.E12_op.dot(self.r2.ravel()).reshape(self.D[0], self.D[0]) self.assertTrue(sp.allclose(r0, r0_)) def test_eps_r_op_2s_AA12(self): r0 = tc.eps_r_op_2s_AA12(self.r2, self.AA12, self.B1, self.B2, self.op2s) r0_ = tc.eps_r_op_2s_A(self.r2, self.A1, self.A2, self.B1, self.B2, self.op2s) self.assertTrue(sp.allclose(r0, r0_)) def test_eps_r_op_2s_AA_func_op(self): r0 = tc.eps_r_op_2s_AA_func_op(self.r2, self.AA12, self.BB12, lambda s,t,u,v: self.op2s[s,t,u,v]) r0_ = tc.eps_r_op_2s_A(self.r2, self.A1, self.A2, self.B1, self.B2, self.op2s) self.assertTrue(sp.allclose(r0, r0_)) def test_eps_r_op_2s_C12(self): r0 = tc.eps_r_op_2s_C12(self.r2, self.C_A12, self.B1, self.B2) r0_ = tc.eps_r_op_2s_A(self.r2, self.A1, self.A2, self.B1, self.B2, self.op2s) self.assertTrue(sp.allclose(r0, r0_)) def test_eps_r_op_2s_C34(self): r0 = tc.eps_r_op_2s_C34(self.r2, self.A1, self.A2, self.C_conj_B12) r0_ = tc.eps_r_op_2s_A(self.r2, self.A1, self.A2, self.B1, self.B2, self.op2s) self.assertTrue(sp.allclose(r0, r0_)) def test_eps_r_op_2s_C12_AA34(self): r0 = tc.eps_r_op_2s_C12_AA34(self.r2, self.C_A12, self.BB12) r0_ = tc.eps_r_op_2s_A(self.r2, self.A1, self.A2, self.B1, self.B2, self.op2s) self.assertTrue(sp.allclose(r0, r0_)) def test_eps_r_op_2s_AA12_C34(self): r0 = tc.eps_r_op_2s_AA12_C34(self.r2, self.AA12, self.C_conj_B12) r0_ = tc.eps_r_op_2s_A(self.r2, self.A1, self.A2, self.B1, self.B2, self.op2s) self.assertTrue(sp.allclose(r0, r0_)) def test_eps_l_op_2s_AA12_C34(self): l2 = tc.eps_l_op_2s_AA12_C34(self.l0, self.AA12, self.C_conj_B12) l2_ = self.E12_op.conj().T.dot(self.l0.ravel()).reshape(self.D[2], self.D[2]) self.assertTrue(sp.allclose(l2, l2_)) def test_calc_C_func_op(self): C = tc.calc_C_func_op(lambda s,t,u,v: self.op2s[s,t,u,v], self.A1, self.A2) self.assertTrue(sp.allclose(C, self.C_A12)) def test_calc_C_func_op_AA(self): C = tc.calc_C_func_op_AA(lambda s,t,u,v: self.op2s[s,t,u,v], self.AA12) self.assertTrue(sp.allclose(C, self.C_A12)) if __name__ == '__main__': unittest.main()
39.164063
131
0.569918
d93a9855a41fb4057e017acfa18718abfa6fdcb3
9,523
py
Python
thirdeye/thirdeye-frontend/docs/conf.py
mrkeremyilmaz/incubator-pinot
b658925f82602d9a877d42af10957515fe055146
[ "Apache-2.0" ]
2
2019-10-21T18:33:43.000Z
2019-12-21T19:57:16.000Z
thirdeye/thirdeye-frontend/docs/conf.py
mrkeremyilmaz/incubator-pinot
b658925f82602d9a877d42af10957515fe055146
[ "Apache-2.0" ]
43
2019-10-14T16:22:39.000Z
2021-08-02T16:58:41.000Z
thirdeye/thirdeye-frontend/docs/conf.py
mrkeremyilmaz/incubator-pinot
b658925f82602d9a877d42af10957515fe055146
[ "Apache-2.0" ]
2
2020-07-08T12:56:07.000Z
2020-07-29T05:51:15.000Z
# -*- coding: utf-8 -*- # # pinot documentation build configuration file, created by # sphinx-quickstart on Tue Feb 7 12:21:42 2017. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: #source_suffix = '.rst' source_suffix = ['.rst', '.md'] # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'pinot-thirdeye' copyright = u'' author = u'newsummit' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = u'1.0.0' # The full version, including alpha/beta/rc tags. release = u'1.0.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. #html_theme = 'alabaster' html_theme = 'sphinx_rtd_theme' # Markdown support from recommonmark.parser import CommonMarkParser source_parsers = { '.md': CommonMarkParser, } # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. # "<project> v<release> documentation" by default. #html_title = u'pinot v1.0.0' # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (relative to this directory) to use as a favicon of # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not None, a 'Last updated on:' timestamp is inserted at every page # bottom, using the given strftime format. # The empty string is equivalent to '%b %d, %Y'. #html_last_updated_fmt = None # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh' #html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # 'ja' uses this config value. # 'zh' user can custom change `jieba` dictionary path. #html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. #html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'thirdeye-doc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', # Latex figure (float) alignment #'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'pinot-thirdeye.tex', u'ThirdEye Documentation', u'newsummit', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'pinot-thirdeye', u'ThirdEye Documentation', [author], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'pinot-thirdeye', u'ThirdEye Documentation', author, 'pinot-thirdeye', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False
32.391156
80
0.718786
87f6a65571c8526446b9394df504ec70457e4df8
2,492
py
Python
findatapy_examples/flatfile_example.py
alexanu/findatapy
b6d6482d6dcbf88a913b0546db72880b2a195022
[ "Apache-2.0" ]
6
2019-06-07T10:43:03.000Z
2020-09-19T21:59:11.000Z
findatapy_examples/flatfile_example.py
alexanu/findatapy
b6d6482d6dcbf88a913b0546db72880b2a195022
[ "Apache-2.0" ]
null
null
null
findatapy_examples/flatfile_example.py
alexanu/findatapy
b6d6482d6dcbf88a913b0546db72880b2a195022
[ "Apache-2.0" ]
2
2019-09-18T21:32:11.000Z
2020-06-28T16:29:38.000Z
__author__ = 'saeedamen' # Saeed Amen # # Copyright 2018 Cuemacro # # 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. # if __name__ == '__main__': ###### below line CRUCIAL when running Windows, otherwise multiprocessing doesn't work! (not necessary on Linux) from findatapy.util import SwimPool; SwimPool() from findatapy.market import Market, MarketDataRequest, MarketDataGenerator market = Market(market_data_generator=MarketDataGenerator()) # choose run_example = 0 for everything # run_example = 1 - read in CSV file (daily) # run_example = 2 - read in HD5 file in market data (intraday) run_example = 0 if run_example == 1 or run_example == 0: md_request = MarketDataRequest( start_date='01 Jan 2002', finish_date='31 Jan 2016', tickers='S&P500', fields='close', data_source="../tests/S&P500.csv", freq='daily', ) market = Market(market_data_generator=MarketDataGenerator()) df = market.fetch_market(md_request=md_request) print(df) if run_example == 2 or run_example == 0: # load tick data from DukasCopy and then resample to 15s buckets md_request = MarketDataRequest( start_date='01 Jun 2016', finish_date='31 Jul 2016', tickers='EURUSD', fields='bid', data_source="../tests/EURUSD_tick.h5", freq='intraday', resample='15s', resample_how='last_dropna' ) market = Market(market_data_generator=MarketDataGenerator()) df = market.fetch_market(md_request=md_request) print(df) # the second time we call it, if we have Redis installed, we will fetch from memory, so it will be quicker # also don't need to run the resample operation again # need to specify cache_algo_return md_request.cache_algo = 'cache_algo_return' df = market.fetch_market(md_request) print(df)
34.611111
121
0.667737
325dd0a0195b9723f59f64e5940a964fba3ef23e
5,349
py
Python
src/archive/clay_bricks/PatternBrickLibrary/v2/polylineClass.py
JonasWard/ClayAdventures
a716445ac690e4792e70658319aa1d5299f9c9e9
[ "MIT" ]
1
2020-03-25T10:55:10.000Z
2020-03-25T10:55:10.000Z
src/archive/clay_bricks/PatternBrickLibrary/v2/polylineClass.py
JonasWard/ClayAdventures
a716445ac690e4792e70658319aa1d5299f9c9e9
[ "MIT" ]
null
null
null
src/archive/clay_bricks/PatternBrickLibrary/v2/polylineClass.py
JonasWard/ClayAdventures
a716445ac690e4792e70658319aa1d5299f9c9e9
[ "MIT" ]
null
null
null
# polylineInterfaceClass import Rhino.Geometry as rg from ghpythonlib.components import Area as gh_area import math class ClayPolyline(object): def __init__(self, pt_set, closed = False): self.pts = pt_set self.closed = closed self.cnt = len(self.pts) self.has_crv_rep = False self.tolerance = .01 def __add__(self, other): if isinstance(other, list): other = ClayPolyline(other) return ClayPolyline(self.pts + other.pts) def __updatePolyline__(self, new_set = None): if not(new_set == None): self.pts = new_set if self.has_crv_rep: self.GetCurve() self.cnt = len(self.pts) @ staticmethod def StartIndex(self): return 0 @ staticmethod def Start(self): return self.pts[self.StartIndex] @ staticmethod def EndIndex(self): return len(self.pts) - 1 @ staticmethod def End(self): return self.pts[self.EndIndex] def GetLength(self): if not(self.has_crv_rep): self.GetCurve() return self.crv_rep.GetLength() def GetArea(self): # this is a hack using the rhino grasshopper component area, _ = gh_area(x) return area def Reverse(self): self.__updatePolyline__(self.pts[::-1]) def GetCurve(self): self.has_crv_rep = True self.crv_rep = rg.Polyline(self.pts + self.Start if self.closed else self.pts).ToNurbsCurve() return self.crv_rep def ClosestPoint(self): if not(self.has_crv_rep): self.GetCurve() def PointAtLength(self, val, return_index = False): if val < 0.0: print("you gave me a negative value, here is the first point") new_pt = self.Start i = self.StartIndex elif val > self.GetLength(): print("""you gave me a value larger than the length of the curve /n" therefore I return you the last point!""") new_pt = self.End i = self.EndIndex else: length = 0.0 for i in range(self.StartIndex, self.EndIndex, 1): pt_0 = self.pts[i] pt_1 = self.pts[i + 1] local_length = pt_0.DistanceTo(pt_1) if length + local_length > val: break else: length += local_length new_pt = interpolatePts(pt_0, pt_1, val - length) if return_index: return new_pt, i else: return new_pt def ReaseamAt(self, value, index_or_length = "index"): if self.closed: if index_or_length == "index": pl_a, pl_b = self.SplitAtIndex(value) def SplitAtIndex(self, *indexes): indexes = list(indexes).sort() indexes.reverse() pl_list = [] local_pt_list = self.pts[:] for index in indexes: end = math.floor(index) start = math.ceil(index) delta = index - end if delta < self.tolerance: # case that the polyline is very short pass def SplitAtLength(self, *lengths): pass def Orient(self): if self.closed: else: print("I can not be oriented") def Shorten(self, length, side = "start"): polyline_length = self.GetLength() # length check: length = abs(length) half_pl_length = polyline_length * .5 if length > half_pl_length: # reducing the length value to a mod of the polyline length = length % half_pl_length if side == "start" or side == "both": new_pt, pt_index = self.PointAtLength(length, True) self.__updatePolyline__([new_pt] + self.pts[pt_index + 1:]) if side == "end" or side == "both": new_pt, pt_index = self.PointAtLength(polyline_length - length, True) self.__updatePolyline__(self.pts[:pt_index] + [new_pt]) def RemoveIndex(self, *index_args): indexes = list(index_args).sort() indexes.reverse() for index in indexes: if index > len(self.pts): print("You can only remove points at a certain index if that index is within the domain ...") else: self.pts.pop(index) self.__updatePolyline__() def AddPoint(self, *pt_args): self.pts += list(pt_args) self.__updatePolyline__() def Offset(self, *offset_args): offset_set = [] for offset_val in offset_args: offset_crv = self.crv_rep.Offset(pln, offset_val, .01, o_type)[0] offset_crv = offset_crv.ToPolyline() offset_set.append(offset_crv) if len(offset_set) == 1: return offset_set[0] else: return offset_set def Close(self, collapse_distance = 1.0): if not self.closed: print("I have to be closed") if self.Start.DistanceTo(self.End) < collapse_distance: print("& I have to collapse onto myself") self.RemoveIndex(self.cnt - 1)
19.241007
109
0.55244
796376a8c985919c8729a2e025160cc2a2c52e6e
16,203
py
Python
sdks/python/apache_beam/typehints/trivial_inference.py
a-satyateja/beam
30a04b912979adf5f316cc8ace334d921ca71838
[ "Apache-2.0" ]
null
null
null
sdks/python/apache_beam/typehints/trivial_inference.py
a-satyateja/beam
30a04b912979adf5f316cc8ace334d921ca71838
[ "Apache-2.0" ]
null
null
null
sdks/python/apache_beam/typehints/trivial_inference.py
a-satyateja/beam
30a04b912979adf5f316cc8ace334d921ca71838
[ "Apache-2.0" ]
1
2019-10-26T12:26:16.000Z
2019-10-26T12:26:16.000Z
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You 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. # """Trivial type inference for simple functions. For internal use only; no backwards-compatibility guarantees. """ from __future__ import absolute_import from __future__ import print_function import collections import dis import inspect import pprint import sys import traceback import types from builtins import object from builtins import zip from functools import reduce from apache_beam.typehints import Any from apache_beam.typehints import typehints # pylint: disable=wrong-import-order, wrong-import-position, ungrouped-imports try: # Python 2 import __builtin__ as builtins except ImportError: # Python 3 import builtins # pylint: enable=wrong-import-order, wrong-import-position, ungrouped-imports class TypeInferenceError(ValueError): """Error to raise when type inference failed.""" pass def instance_to_type(o): """Given a Python object o, return the corresponding type hint. """ t = type(o) if o is None: return type(None) elif t not in typehints.DISALLOWED_PRIMITIVE_TYPES: # pylint: disable=deprecated-types-field if sys.version_info[0] == 2 and t == types.InstanceType: return o.__class__ if t == BoundMethod: return types.MethodType return t elif t == tuple: return typehints.Tuple[[instance_to_type(item) for item in o]] elif t == list: return typehints.List[ typehints.Union[[instance_to_type(item) for item in o]] ] elif t == set: return typehints.Set[ typehints.Union[[instance_to_type(item) for item in o]] ] elif t == dict: return typehints.Dict[ typehints.Union[[instance_to_type(k) for k, v in o.items()]], typehints.Union[[instance_to_type(v) for k, v in o.items()]], ] else: raise TypeInferenceError('Unknown forbidden type: %s' % t) def union_list(xs, ys): assert len(xs) == len(ys) return [union(x, y) for x, y in zip(xs, ys)] class Const(object): def __init__(self, value): self.value = value self.type = instance_to_type(value) def __eq__(self, other): return isinstance(other, Const) and self.value == other.value def __ne__(self, other): # TODO(BEAM-5949): Needed for Python 2 compatibility. return not self == other def __hash__(self): return hash(self.value) def __repr__(self): return 'Const[%s]' % str(self.value)[:100] @staticmethod def unwrap(x): if isinstance(x, Const): return x.type return x @staticmethod def unwrap_all(xs): return [Const.unwrap(x) for x in xs] class FrameState(object): """Stores the state of the frame at a particular point of execution. """ def __init__(self, f, local_vars=None, stack=()): self.f = f self.co = f.__code__ self.vars = list(local_vars) self.stack = list(stack) def __eq__(self, other): return isinstance(other, FrameState) and self.__dict__ == other.__dict__ def __ne__(self, other): # TODO(BEAM-5949): Needed for Python 2 compatibility. return not self == other def __hash__(self): return hash(tuple(sorted(self.__dict__.items()))) def copy(self): return FrameState(self.f, self.vars, self.stack) def const_type(self, i): return Const(self.co.co_consts[i]) def get_closure(self, i): num_cellvars = len(self.co.co_cellvars) if i < num_cellvars: return self.vars[i] else: return self.f.__closure__[i - num_cellvars].cell_contents def closure_type(self, i): """Returns a TypeConstraint or Const.""" val = self.get_closure(i) if isinstance(val, typehints.TypeConstraint): return val else: return Const(val) def get_global(self, i): name = self.get_name(i) if name in self.f.__globals__: return Const(self.f.__globals__[name]) if name in builtins.__dict__: return Const(builtins.__dict__[name]) return Any def get_name(self, i): return self.co.co_names[i] def __repr__(self): return 'Stack: %s Vars: %s' % (self.stack, self.vars) def __or__(self, other): if self is None: return other.copy() elif other is None: return self.copy() return FrameState(self.f, union_list(self.vars, other.vars), union_list( self.stack, other.stack)) def __ror__(self, left): return self | left def union(a, b): """Returns the union of two types or Const values. """ if a == b: return a elif not a: return b elif not b: return a a = Const.unwrap(a) b = Const.unwrap(b) # TODO(robertwb): Work this into the Union code in a more generic way. if type(a) == type(b) and element_type(a) == typehints.Union[()]: return b elif type(a) == type(b) and element_type(b) == typehints.Union[()]: return a return typehints.Union[a, b] def finalize_hints(type_hint): """Sets type hint for empty data structures to Any.""" def visitor(tc, unused_arg): if isinstance(tc, typehints.DictConstraint): empty_union = typehints.Union[()] if tc.key_type == empty_union: tc.key_type = Any if tc.value_type == empty_union: tc.value_type = Any if isinstance(type_hint, typehints.TypeConstraint): type_hint.visit(visitor, None) def element_type(hint): """Returns the element type of a composite type. """ hint = Const.unwrap(hint) if isinstance(hint, typehints.SequenceTypeConstraint): return hint.inner_type elif isinstance(hint, typehints.TupleHint.TupleConstraint): return typehints.Union[hint.tuple_types] return Any def key_value_types(kv_type): """Returns the key and value type of a KV type. """ # TODO(robertwb): Unions of tuples, etc. # TODO(robertwb): Assert? if (isinstance(kv_type, typehints.TupleHint.TupleConstraint) and len(kv_type.tuple_types) == 2): return kv_type.tuple_types return Any, Any known_return_types = {len: int, hash: int,} class BoundMethod(object): """Used to create a bound method when we only know the type of the instance. """ def __init__(self, func, type): """Instantiates a bound method object. Args: func (types.FunctionType): The method's underlying function type (type): The class of the method. """ self.func = func self.type = type def hashable(c): try: hash(c) return True except TypeError: return False def infer_return_type(c, input_types, debug=False, depth=5): """Analyses a callable to deduce its return type. Args: c: A Python callable to infer the return type of. input_types: A sequence of inputs corresponding to the input types. debug: Whether to print verbose debugging information. depth: Maximum inspection depth during type inference. Returns: A TypeConstraint that that the return value of this function will (likely) satisfy given the specified inputs. """ try: if hashable(c) and c in known_return_types: return known_return_types[c] elif isinstance(c, types.FunctionType): return infer_return_type_func(c, input_types, debug, depth) elif isinstance(c, types.MethodType): if c.__self__ is not None: input_types = [Const(c.__self__)] + input_types return infer_return_type_func(c.__func__, input_types, debug, depth) elif isinstance(c, BoundMethod): input_types = [c.type] + input_types return infer_return_type_func(c.func, input_types, debug, depth) elif inspect.isclass(c): if c in typehints.DISALLOWED_PRIMITIVE_TYPES: return { list: typehints.List[Any], set: typehints.Set[Any], tuple: typehints.Tuple[Any, ...], dict: typehints.Dict[Any, Any] }[c] return c else: return Any except TypeInferenceError: if debug: traceback.print_exc() return Any except Exception: if debug: sys.stdout.flush() raise else: return Any def infer_return_type_func(f, input_types, debug=False, depth=0): """Analyses a function to deduce its return type. Args: f: A Python function object to infer the return type of. input_types: A sequence of inputs corresponding to the input types. debug: Whether to print verbose debugging information. depth: Maximum inspection depth during type inference. Returns: A TypeConstraint that that the return value of this function will (likely) satisfy given the specified inputs. Raises: TypeInferenceError: if no type can be inferred. """ if debug: print() print(f, id(f), input_types) dis.dis(f) from . import opcodes simple_ops = dict((k.upper(), v) for k, v in opcodes.__dict__.items()) co = f.__code__ code = co.co_code end = len(code) pc = 0 extended_arg = 0 # Python 2 only. free = None yields = set() returns = set() # TODO(robertwb): Default args via inspect module. local_vars = list(input_types) + [typehints.Union[()]] * (len(co.co_varnames) - len(input_types)) state = FrameState(f, local_vars) states = collections.defaultdict(lambda: None) jumps = collections.defaultdict(int) # In Python 3, use dis library functions to disassemble bytecode and handle # EXTENDED_ARGs. is_py3 = sys.version_info[0] == 3 if is_py3: ofs_table = {} # offset -> instruction for instruction in dis.get_instructions(f): ofs_table[instruction.offset] = instruction # Python 2 - 3.5: 1 byte opcode + optional 2 byte arg (1 or 3 bytes). # Python 3.6+: 1 byte opcode + 1 byte arg (2 bytes, arg may be ignored). if sys.version_info >= (3, 6): inst_size = 2 opt_arg_size = 0 else: inst_size = 1 opt_arg_size = 2 last_pc = -1 while pc < end: start = pc if is_py3: instruction = ofs_table[pc] op = instruction.opcode else: op = ord(code[pc]) if debug: print('-->' if pc == last_pc else ' ', end=' ') print(repr(pc).rjust(4), end=' ') print(dis.opname[op].ljust(20), end=' ') pc += inst_size if op >= dis.HAVE_ARGUMENT: if is_py3: arg = instruction.arg else: arg = ord(code[pc]) + ord(code[pc + 1]) * 256 + extended_arg extended_arg = 0 pc += opt_arg_size if op == dis.EXTENDED_ARG: extended_arg = arg * 65536 if debug: print(str(arg).rjust(5), end=' ') if op in dis.hasconst: print('(' + repr(co.co_consts[arg]) + ')', end=' ') elif op in dis.hasname: print('(' + co.co_names[arg] + ')', end=' ') elif op in dis.hasjrel: print('(to ' + repr(pc + arg) + ')', end=' ') elif op in dis.haslocal: print('(' + co.co_varnames[arg] + ')', end=' ') elif op in dis.hascompare: print('(' + dis.cmp_op[arg] + ')', end=' ') elif op in dis.hasfree: if free is None: free = co.co_cellvars + co.co_freevars print('(' + free[arg] + ')', end=' ') # Actually emulate the op. if state is None and states[start] is None: # No control reaches here (yet). if debug: print() continue state |= states[start] opname = dis.opname[op] jmp = jmp_state = None if opname.startswith('CALL_FUNCTION'): if sys.version_info < (3, 6): # Each keyword takes up two arguments on the stack (name and value). standard_args = (arg & 0xFF) + 2 * (arg >> 8) var_args = 'VAR' in opname kw_args = 'KW' in opname pop_count = standard_args + var_args + kw_args + 1 if depth <= 0: return_type = Any elif arg >> 8: # TODO(robertwb): Handle this case. return_type = Any elif isinstance(state.stack[-pop_count], Const): # TODO(robertwb): Handle this better. if var_args or kw_args: state.stack[-1] = Any state.stack[-var_args - kw_args] = Any return_type = infer_return_type(state.stack[-pop_count].value, state.stack[1 - pop_count:], debug=debug, depth=depth - 1) else: return_type = Any state.stack[-pop_count:] = [return_type] else: # Python 3.6+ if opname == 'CALL_FUNCTION': pop_count = arg + 1 if depth <= 0: return_type = Any else: return_type = infer_return_type(state.stack[-pop_count].value, state.stack[1 - pop_count:], debug=debug, depth=depth - 1) elif opname == 'CALL_FUNCTION_KW': # TODO(udim): Handle keyword arguments. Requires passing them by name # to infer_return_type. pop_count = arg + 2 return_type = Any elif opname == 'CALL_FUNCTION_EX': # TODO(udim): Handle variable argument lists. Requires handling kwargs # first. pop_count = (arg & 1) + 3 return_type = Any else: raise TypeInferenceError('unable to handle %s' % opname) state.stack[-pop_count:] = [return_type] elif opname == 'CALL_METHOD': pop_count = 1 + arg # LOAD_METHOD will return a non-Const (Any) if loading from an Any. if isinstance(state.stack[-pop_count], Const) and depth > 0: return_type = infer_return_type(state.stack[-pop_count].value, state.stack[1 - pop_count:], debug=debug, depth=depth - 1) else: return_type = typehints.Any state.stack[-pop_count:] = [return_type] elif opname in simple_ops: if debug: print("Executing simple op " + opname) simple_ops[opname](state, arg) elif opname == 'RETURN_VALUE': returns.add(state.stack[-1]) state = None elif opname == 'YIELD_VALUE': yields.add(state.stack[-1]) elif opname == 'JUMP_FORWARD': jmp = pc + arg jmp_state = state state = None elif opname == 'JUMP_ABSOLUTE': jmp = arg jmp_state = state state = None elif opname in ('POP_JUMP_IF_TRUE', 'POP_JUMP_IF_FALSE'): state.stack.pop() jmp = arg jmp_state = state.copy() elif opname in ('JUMP_IF_TRUE_OR_POP', 'JUMP_IF_FALSE_OR_POP'): jmp = arg jmp_state = state.copy() state.stack.pop() elif opname == 'FOR_ITER': jmp = pc + arg jmp_state = state.copy() jmp_state.stack.pop() state.stack.append(element_type(state.stack[-1])) else: raise TypeInferenceError('unable to handle %s' % opname) if jmp is not None: # TODO(robertwb): Is this guaranteed to converge? new_state = states[jmp] | jmp_state if jmp < pc and new_state != states[jmp] and jumps[pc] < 5: jumps[pc] += 1 pc = jmp states[jmp] = new_state if debug: print() print(state) pprint.pprint(dict(item for item in states.items() if item[1])) if yields: result = typehints.Iterable[reduce(union, Const.unwrap_all(yields))] else: result = reduce(union, Const.unwrap_all(returns)) finalize_hints(result) if debug: print(f, id(f), input_types, '->', result) return result
30.342697
80
0.630254
6ec43c4a4e08fcfbe2584b8304ef6a6e2179e209
10,085
py
Python
colour_demosaicing/bayer/demosaicing/menon2007.py
MaxSchambach/colour-demosaicing
76c4428c3453f40ec35c57f729bc4474da4ed26b
[ "BSD-3-Clause" ]
null
null
null
colour_demosaicing/bayer/demosaicing/menon2007.py
MaxSchambach/colour-demosaicing
76c4428c3453f40ec35c57f729bc4474da4ed26b
[ "BSD-3-Clause" ]
null
null
null
colour_demosaicing/bayer/demosaicing/menon2007.py
MaxSchambach/colour-demosaicing
76c4428c3453f40ec35c57f729bc4474da4ed26b
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- """ DDFAPD - Menon (2007) Bayer CFA Demosaicing =========================================== *Bayer* CFA (Colour Filter Array) DDFAPD - *Menon (2007)* demosaicing. References ---------- - :cite:`Menon2007c` : Menon, D., Andriani, S., & Calvagno, G. (2007). Demosaicing With Directional Filtering and a posteriori Decision. IEEE Transactions on Image Processing, 16(1), 132-141. doi:10.1109/TIP.2006.884928 """ from __future__ import division, unicode_literals import numpy as np from scipy.ndimage.filters import convolve, convolve1d from colour.utilities import tsplit, tstack from colour_demosaicing.bayer import masks_CFA_Bayer __author__ = 'Colour Developers' __copyright__ = 'Copyright (C) 2015-2018 - Colour Developers' __license__ = 'New BSD License - http://opensource.org/licenses/BSD-3-Clause' __maintainer__ = 'Colour Developers' __email__ = 'colour-science@googlegroups.com' __status__ = 'Production' __all__ = [ 'demosaicing_CFA_Bayer_Menon2007', 'demosaicing_CFA_Bayer_DDFAPD', 'refining_step_Menon2007' ] def _cnv_h(x, y): """ Helper function for horizontal convolution. """ return convolve1d(x, y, mode='mirror') def _cnv_v(x, y): """ Helper function for vertical convolution. """ return convolve1d(x, y, mode='mirror', axis=0) def demosaicing_CFA_Bayer_Menon2007(CFA, pattern='RGGB', refining_step=True): """ Returns the demosaiced *RGB* colourspace array from given *Bayer* CFA using DDFAPD - *Menon (2007)* demosaicing algorithm. Parameters ---------- CFA : array_like *Bayer* CFA. pattern : unicode, optional **{'RGGB', 'BGGR', 'GRBG', 'GBRG'}**, Arrangement of the colour filters on the pixel array. refining_step : bool Perform refining step. Returns ------- ndarray *RGB* colourspace array. Notes ----- - The definition output is not clipped in range [0, 1] : this allows for direct HDRI / radiance image generation on *Bayer* CFA data and post demosaicing of the high dynamic range data as showcased in this `Jupyter Notebook <https://github.com/colour-science/colour-hdri/\ blob/develop/colour_hdri/examples/\ examples_merge_from_raw_files_with_post_demosaicing.ipynb>`_. References ---------- - :cite:`Menon2007c` Examples -------- >>> CFA = np.array( ... [[ 0.30980393, 0.36078432, 0.30588236, 0.3764706 ], ... [ 0.35686275, 0.39607844, 0.36078432, 0.40000001]]) >>> demosaicing_CFA_Bayer_Menon2007(CFA) array([[[ 0.30980393, 0.35686275, 0.39215687], [ 0.30980393, 0.36078432, 0.39607844], [ 0.30588236, 0.36078432, 0.39019608], [ 0.32156864, 0.3764706 , 0.40000001]], <BLANKLINE> [[ 0.30980393, 0.35686275, 0.39215687], [ 0.30980393, 0.36078432, 0.39607844], [ 0.30588236, 0.36078432, 0.39019609], [ 0.32156864, 0.3764706 , 0.40000001]]]) >>> CFA = np.array( ... [[ 0.3764706 , 0.36078432, 0.40784314, 0.3764706 ], ... [ 0.35686275, 0.30980393, 0.36078432, 0.29803923]]) >>> demosaicing_CFA_Bayer_Menon2007(CFA, 'BGGR') array([[[ 0.30588236, 0.35686275, 0.3764706 ], [ 0.30980393, 0.36078432, 0.39411766], [ 0.29607844, 0.36078432, 0.40784314], [ 0.29803923, 0.3764706 , 0.42352942]], <BLANKLINE> [[ 0.30588236, 0.35686275, 0.3764706 ], [ 0.30980393, 0.36078432, 0.39411766], [ 0.29607844, 0.36078432, 0.40784314], [ 0.29803923, 0.3764706 , 0.42352942]]]) """ CFA = np.asarray(CFA) R_m, G_m, B_m = masks_CFA_Bayer(CFA.shape, pattern) h_0 = np.array([0, 0.5, 0, 0.5, 0]) h_1 = np.array([-0.25, 0, 0.5, 0, -0.25]) R = CFA * R_m G = CFA * G_m B = CFA * B_m G_H = np.where(G_m == 0, _cnv_h(CFA, h_0) + _cnv_h(CFA, h_1), G) G_V = np.where(G_m == 0, _cnv_v(CFA, h_0) + _cnv_v(CFA, h_1), G) C_H = np.where(R_m == 1, R - G_H, 0) C_H = np.where(B_m == 1, B - G_H, C_H) C_V = np.where(R_m == 1, R - G_V, 0) C_V = np.where(B_m == 1, B - G_V, C_V) D_H = np.abs(C_H - np.pad(C_H, ((0, 0), (0, 2)), mode=str('reflect'))[:, 2:]) D_V = np.abs(C_V - np.pad(C_V, ((0, 2), (0, 0)), mode=str('reflect'))[2:, :]) del h_0, h_1, CFA, C_V, C_H k = np.array( [[0, 0, 1, 0, 1], [0, 0, 0, 1, 0], [0, 0, 3, 0, 3], [0, 0, 0, 1, 0], [0, 0, 1, 0, 1]]) # yapf: disable d_H = convolve(D_H, k, mode='constant') d_V = convolve(D_V, np.transpose(k), mode='constant') del D_H, D_V mask = d_V >= d_H G = np.where(mask, G_H, G_V) M = np.where(mask, 1, 0) del d_H, d_V, G_H, G_V # Red rows. R_r = np.transpose(np.any(R_m == 1, axis=1)[np.newaxis]) * np.ones(R.shape) # Blue rows. B_r = np.transpose(np.any(B_m == 1, axis=1)[np.newaxis]) * np.ones(B.shape) k_b = np.array([0.5, 0, 0.5]) R = np.where( np.logical_and(G_m == 1, R_r == 1), G + _cnv_h(R, k_b) - _cnv_h(G, k_b), R) R = np.where( np.logical_and(G_m == 1, B_r == 1) == 1, G + _cnv_v(R, k_b) - _cnv_v(G, k_b), R) B = np.where( np.logical_and(G_m == 1, B_r == 1), G + _cnv_h(B, k_b) - _cnv_h(G, k_b), B) B = np.where( np.logical_and(G_m == 1, R_r == 1) == 1, G + _cnv_v(B, k_b) - _cnv_v(G, k_b), B) R = np.where( np.logical_and(B_r == 1, B_m == 1), np.where(M == 1, B + _cnv_h(R, k_b) - _cnv_h(B, k_b), B + _cnv_v(R, k_b) - _cnv_v(B, k_b)), R) B = np.where( np.logical_and(R_r == 1, R_m == 1), np.where(M == 1, R + _cnv_h(B, k_b) - _cnv_h(R, k_b), R + _cnv_v(B, k_b) - _cnv_v(R, k_b)), B) RGB = tstack((R, G, B)) del R, G, B, k_b, R_r, B_r if refining_step: RGB = refining_step_Menon2007(RGB, tstack((R_m, G_m, B_m)), M) del M, R_m, G_m, B_m return RGB demosaicing_CFA_Bayer_DDFAPD = demosaicing_CFA_Bayer_Menon2007 def refining_step_Menon2007(RGB, RGB_m, M): """ Performs the refining step on given *RGB* colourspace array. Parameters ---------- RGB : array_like *RGB* colourspace array. RGB_m : array_like *Bayer* CFA red, green and blue masks. M : array_like Estimation for the best directional reconstruction. Returns ------- ndarray Refined *RGB* colourspace array. Examples -------- >>> RGB = np.array( ... [[[0.30588236, 0.35686275, 0.3764706], ... [0.30980393, 0.36078432, 0.39411766], ... [0.29607844, 0.36078432, 0.40784314], ... [0.29803923, 0.37647060, 0.42352942]], ... [[0.30588236, 0.35686275, 0.3764706], ... [0.30980393, 0.36078432, 0.39411766], ... [0.29607844, 0.36078432, 0.40784314], ... [0.29803923, 0.37647060, 0.42352942]]]) >>> RGB_m = np.array( ... [[[0, 0, 1], ... [0, 1, 0], ... [0, 0, 1], ... [0, 1, 0]], ... [[0, 1, 0], ... [1, 0, 0], ... [0, 1, 0], ... [1, 0, 0]]]) >>> M = np.array( ... [[0, 1, 0, 1], ... [1, 0, 1, 0]]) >>> refining_step_Menon2007(RGB, RGB_m, M) array([[[ 0.30588236, 0.35686275, 0.3764706 ], [ 0.30980393, 0.36078432, 0.39411765], [ 0.29607844, 0.36078432, 0.40784314], [ 0.29803923, 0.3764706 , 0.42352942]], <BLANKLINE> [[ 0.30588236, 0.35686275, 0.3764706 ], [ 0.30980393, 0.36078432, 0.39411766], [ 0.29607844, 0.36078432, 0.40784314], [ 0.29803923, 0.3764706 , 0.42352942]]]) """ R, G, B = tsplit(RGB) R_m, G_m, B_m = tsplit(RGB_m) M = np.asarray(M) del RGB, RGB_m # Updating of the green component. R_G = R - G B_G = B - G FIR = np.ones(3) / 3 B_G_m = np.where(B_m == 1, np.where(M == 1, _cnv_h(B_G, FIR), _cnv_v(B_G, FIR)), 0) R_G_m = np.where(R_m == 1, np.where(M == 1, _cnv_h(R_G, FIR), _cnv_v(R_G, FIR)), 0) del B_G, R_G G = np.where(R_m == 1, R - R_G_m, G) G = np.where(B_m == 1, B - B_G_m, G) # Updating of the red and blue components in the green locations. # Red rows. R_r = np.transpose(np.any(R_m == 1, axis=1)[np.newaxis]) * np.ones(R.shape) # Red columns. R_c = np.any(R_m == 1, axis=0)[np.newaxis] * np.ones(R.shape) # Blue rows. B_r = np.transpose(np.any(B_m == 1, axis=1)[np.newaxis]) * np.ones(B.shape) # Blue columns. B_c = np.any(B_m == 1, axis=0)[np.newaxis] * np.ones(B.shape) R_G = R - G B_G = B - G k_b = np.array([0.5, 0, 0.5]) R_G_m = np.where( np.logical_and(G_m == 1, B_r == 1), _cnv_v(R_G, k_b), R_G_m) R = np.where(np.logical_and(G_m == 1, B_r == 1), G + R_G_m, R) R_G_m = np.where( np.logical_and(G_m == 1, B_c == 1), _cnv_h(R_G, k_b), R_G_m) R = np.where(np.logical_and(G_m == 1, B_c == 1), G + R_G_m, R) del B_r, R_G_m, B_c, R_G B_G_m = np.where( np.logical_and(G_m == 1, R_r == 1), _cnv_v(B_G, k_b), B_G_m) B = np.where(np.logical_and(G_m == 1, R_r == 1), G + B_G_m, B) B_G_m = np.where( np.logical_and(G_m == 1, R_c == 1), _cnv_h(B_G, k_b), B_G_m) B = np.where(np.logical_and(G_m == 1, R_c == 1), G + B_G_m, B) del B_G_m, R_r, R_c, G_m, B_G # Updating of the red (blue) component in the blue (red) locations. R_B = R - B R_B_m = np.where(B_m == 1, np.where(M == 1, _cnv_h(R_B, FIR), _cnv_v(R_B, FIR)), 0) R = np.where(B_m == 1, B + R_B_m, R) R_B_m = np.where(R_m == 1, np.where(M == 1, _cnv_h(R_B, FIR), _cnv_v(R_B, FIR)), 0) B = np.where(R_m == 1, R - R_B_m, B) del R_B, R_B_m, R_m return tstack((R, G, B))
30.560606
79
0.539316
5f713a36f4389ae1b11a464dacf20bd3527e590e
2,085
py
Python
Python/paint.py
gilecheverria/TC1001S-202111
21388ca97227ab9079a36ce79f9800a235f9bfd8
[ "MIT" ]
null
null
null
Python/paint.py
gilecheverria/TC1001S-202111
21388ca97227ab9079a36ce79f9800a235f9bfd8
[ "MIT" ]
null
null
null
Python/paint.py
gilecheverria/TC1001S-202111
21388ca97227ab9079a36ce79f9800a235f9bfd8
[ "MIT" ]
2
2021-05-06T05:13:53.000Z
2021-05-07T15:31:20.000Z
"""Paint, for drawing shapes. Exercises 1. Add a color. 2. Complete circle. 3. Complete rectangle. 4. Complete triangle. 5. Add width parameter. """ from turtle import * from freegames import vector def line(start, end): "Draw line from start to end." up() goto(start.x, start.y) down() goto(end.x, end.y) def square(start, end): "Draw square from start to end." up() goto(start.x, start.y) down() begin_fill() for count in range(4): forward(end.x - start.x) left(90) end_fill() def circle(start, end): "Draw circle from start to end." up() goto(start.x, start.y) down() begin_fill() for count in range(8): forward(end.x - start.x) left(45) end_fill() def rectangle(start, end): "Draw rectangle from start to end." up() goto(start.x, start.y) down() begin_fill() for count in range(4): forward(end.x - start.x) left(90) end_fill() def triangle(start, end): "Draw triangle from start to end." pass # TODO def tap(x, y): "Store starting point or draw shape." start = state['start'] if start is None: state['start'] = vector(x, y) else: shape = state['shape'] end = vector(x, y) shape(start, end) state['start'] = None def store(key, value): "Store value in state at key." state[key] = value state = {'start': None, 'shape': line} setup(420, 420, 370, 0) onscreenclick(tap) listen() onkey(undo, 'u') onkey(lambda: color('black'), 'K') onkey(lambda: color('white'), 'W') onkey(lambda: color('green'), 'G') onkey(lambda: color('blue'), 'B') onkey(lambda: color('red'), 'R') onkey(lambda: color('yellow'), 'Y') onkey(lambda: color('cyan'), 'C') onkey(lambda: color('orange'), 'O') onkey(lambda: color('magenta'), 'M') onkey(lambda: store('shape', line), 'l') onkey(lambda: store('shape', square), 's') onkey(lambda: store('shape', circle), 'c') onkey(lambda: store('shape', rectangle), 'r') onkey(lambda: store('shape', triangle), 't') done()
19.669811
45
0.597122
a4d641993f3794edf35e9c421c3006377f1da547
1,162
py
Python
train/graph_fingers.py
papoutsa20/Capstone-Sign-Glove
62b4faf40146f17a42a52d0604e984a5d79233c6
[ "MIT" ]
null
null
null
train/graph_fingers.py
papoutsa20/Capstone-Sign-Glove
62b4faf40146f17a42a52d0604e984a5d79233c6
[ "MIT" ]
3
2021-09-08T03:00:03.000Z
2022-03-12T00:54:32.000Z
train/graph_fingers.py
papoutsa20/Capstone-Sign-Glove
62b4faf40146f17a42a52d0604e984a5d79233c6
[ "MIT" ]
null
null
null
""" Graphs the normailized resister sensor values on a graph """ import numpy as np import matplotlib.pyplot as plt import os # use colors for letters here colors = { 'K': 'g', 'V': 'red' } # letters to graph letters = ['K','V'] x = np.arange(8) y = {} for letter in letters: y[letter] = {0:[],1:[],2:[],3:[],4:[],5:[],6:[],7:[]} for file in os.listdir(os.path.join('./data', letter)): if os.path.isfile(os.path.join('./data', letter,file)) and file[-4:] == '.csv': with open(os.path.join('./data', letter ,file), 'r') as f: for line in f.readlines(): line = line.split(',') for i in range(5): y[letter][i].append(int(line[i])/1023) for i in range(3): y[letter][5+i].append(float(line[5+i])) for x in range(8): for letter in letters: plt.scatter([x]*len(y[letter][x]), y[letter][x], color=colors[letter], label=letter if x == 0 else None) plt.title('Sensor Values Normalized') plt.legend() plt.xticks(range(8), ['Thumb','Index','Middle','Ring','Pinky','AccX','AccY','AccZ']) plt.show()
27.666667
112
0.541308
c411c5b7199e32469957d2bf7368108c9df000d7
6,215
py
Python
oeshoot/narx/narx.py
antonior92/oe-multiple-shooting
49479d13fbb618097a3f881bb01b1a6d61d8c3db
[ "MIT" ]
2
2019-03-05T16:46:45.000Z
2020-05-02T15:33:02.000Z
oeshoot/narx/narx.py
antonior92/oe-multiple-shooting
49479d13fbb618097a3f881bb01b1a6d61d8c3db
[ "MIT" ]
1
2019-03-26T11:25:38.000Z
2019-12-27T08:43:50.000Z
oeshoot/narx/narx.py
antonior92/oe-multiple-shooting
49479d13fbb618097a3f881bb01b1a6d61d8c3db
[ "MIT" ]
1
2019-03-05T08:54:40.000Z
2019-03-05T08:54:40.000Z
""" Abstract base class that define basic features for NARX models. """ from __future__ import division, print_function, absolute_import import numpy as np from abc import (ABCMeta, abstractmethod) from six import add_metaclass import numdifftools as nd __all__ = [ 'NarxModel' ] @add_metaclass(ABCMeta) class NarxModel(object): """ Define a NARX model: ``y[n] = F(y[n-1],..., y[n-N], u[n-delay],..., u[n-M], params)`` """ def __init__(self, Nparams, N, M, Ny=1, Nu=1, delay=1): if M != 0 and Nu != 0 and delay > M: raise ValueError("delay should be smaller than M.") self.Nparams = Nparams self.N = N self.Ny = Ny self.Nu = Nu if Nu != 0: self.delay = delay self.Mu = M-delay+1 self.M = M else: self.delay = 0 self.Mu = 0 self.M = 0 @abstractmethod def __call__(self, y, u, params): """ Given current system state and inputs compute next state. Parameters ---------- y : array_like Array containing previous system outputs. It should have dimension (N, Ny). u : array_like Array containing system inputs. it should have dimension (M-delay+1, Nu). params : array_like Parameter array. It should have dimension (Nparams,). Returns ------- ynext : array_like Array containing next system output accordingly to the NARX model. Dimension (Ny,). """ return def derivatives(self, y, u, params, deriv_y=True, deriv_u=True, deriv_params=True): """ Given current system state and inputs compute derivatives at a given point Parameters ---------- y : array_like Array containing previous system outputs. It should have dimension (N, Ny). u : array_like Array containing system inputs. it should have dimension (M-delay+1, Nu). params : array_like Parameter array. It should have dimension (Nparams,). deriv_y : boolean, optional Specify if the derivatives in relation to y should be returned by this function. By default, it is True. deriv_u : boolean, optional Specify if the derivatives in relation to u should be returned by this function. By default, it is True. deriv_params : boolean, optional Specify if the derivatives in relation to the parameters should be returned by this function. By default, it is True. Returns ------- dy : array_like, optional Array containing model derivatives in relation to y. Dimension (Ny, N, Ny) du : array_like, optional Array containing model derivatives in relation to u. Dimension (Ny, M-delay+1, Nu) dparams : array_like, optional Array containing model derivatives in relation to params. Dimension (Ny, Nparams) """ return self._numeric_derivatives(y, u, params, deriv_y, deriv_u, deriv_params) def _numeric_derivatives(self, y, u, params, deriv_y=True, deriv_u=True, deriv_params=True): """ Given current system state and inputs compute an numeric aproximation of the derivatives at a given point """ # Check Arguments y, u, params = self._arg_check(y, u, params) # Use numdifftools to estimate derivatives returns = [] if deriv_y: def fun_y(x): return self.__call__(x.reshape(self.N, self.Ny), u, params) if self.N != 0: dy = nd.Jacobian(fun_y)(y.flatten()).reshape((self.Ny, self.N, self.Ny)) else: dy = np.reshape([], (self.Ny, self.N, self.Ny)) returns.append(dy) if deriv_u: def fun_u(x): return self.__call__(y, x.reshape(self.Mu, self.Nu), params) if self.Mu != 0 and self.Nu != 0: du = nd.Jacobian(fun_u)(u.flatten()).reshape((self.Ny, self.Mu, self.Nu)) else: du = np.reshape([], (self.Ny, self.Mu, self.Nu)) returns.append(du) if deriv_params: def fun_params(x): return self.__call__(y, u, x) dparams = nd.Jacobian(fun_params)(params).reshape((self.Ny, self.Nparams)) returns.append(dparams) if len(returns) == 1: return returns[0] else: return tuple(returns) def _arg_check(self, y, u, params): """ Check input arguments. """ params = np.atleast_1d(params) if params.shape != (self.Nparams,): raise ValueError("Wrong params vector size.") y = np.reshape(y, (self.N, self.Ny)) u = np.reshape(u, (self.Mu, self.Nu)) return y, u, params def marshalling_input(self, y, u): """ Generate input for a generic function from dinamic data. Usefull when the input for a NARX model need to be passed on to template functions. Parameters ---------- y : array_like Array containing previous system outputs. It should have dimension (N, Ny). u : array_like Array containing system inputs. it should have dimension (M-delay+1, Nu). Returns ------- x : array_like Unidimensional vector containing concatenation of values from y and u. """ y = np.atleast_1d(y) u = np.atleast_1d(u) x = np.hstack((y.flatten(), u.flatten())) return x
31.871795
79
0.525503
debfe2644ee6ea5cfe472c8d9cffe4bfe78c6551
1,057
py
Python
botorch/logging.py
SamuelMarks/botorch
7801e2f56dc447322b2b6c92cab683d8900e4c7f
[ "MIT" ]
2,344
2019-05-01T04:57:26.000Z
2022-03-29T17:00:41.000Z
botorch/logging.py
SamuelMarks/botorch
7801e2f56dc447322b2b6c92cab683d8900e4c7f
[ "MIT" ]
942
2019-05-01T05:11:30.000Z
2022-03-31T21:58:24.000Z
botorch/logging.py
SamuelMarks/botorch
7801e2f56dc447322b2b6c92cab683d8900e4c7f
[ "MIT" ]
280
2019-05-01T05:14:53.000Z
2022-03-29T16:00:33.000Z
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging LOG_LEVEL_DEFAULT = logging.CRITICAL def _get_logger( name: str = "botorch", level: int = LOG_LEVEL_DEFAULT ) -> logging.Logger: """Gets a default botorch logger Logging level can be tuned via botorch.setting.log_level Args: name: Name for logger instance level: Logging threshhold for the given logger. Logs of greater or equal severity will be printed to STDERR """ logger = logging.getLogger(name) logger.setLevel(level) # Add timestamps to log messages. console = logging.StreamHandler() formatter = logging.Formatter( fmt="[%(levelname)s %(asctime)s] %(name)s: %(message)s", datefmt="%m-%d %H:%M:%S", ) console.setFormatter(formatter) logger.addHandler(console) logger.propagate = False return logger logger = _get_logger()
26.425
74
0.681173
7475e99eaa068e5c5d80ede7443a35a621a8914e
20,872
py
Python
certbot/tests/cli_test.py
unicorn-owl/certbot
4fa1df307573abf79324c1ece3b228b6dba31d74
[ "Apache-2.0" ]
5
2021-01-26T08:47:29.000Z
2021-01-30T00:42:12.000Z
certbot/tests/cli_test.py
unicorn-owl/certbot
4fa1df307573abf79324c1ece3b228b6dba31d74
[ "Apache-2.0" ]
null
null
null
certbot/tests/cli_test.py
unicorn-owl/certbot
4fa1df307573abf79324c1ece3b228b6dba31d74
[ "Apache-2.0" ]
1
2020-10-28T05:49:43.000Z
2020-10-28T05:49:43.000Z
"""Tests for certbot._internal.cli.""" import argparse import copy import tempfile import unittest try: import mock except ImportError: # pragma: no cover from unittest import mock import six from six.moves import reload_module # pylint: disable=import-error from acme import challenges from certbot import errors from certbot._internal import cli from certbot._internal import constants from certbot._internal.plugins import disco from certbot.compat import filesystem from certbot.compat import os import certbot.tests.util as test_util from certbot.tests.util import TempDirTestCase PLUGINS = disco.PluginsRegistry.find_all() class TestReadFile(TempDirTestCase): """Test cli.read_file""" def test_read_file(self): curr_dir = os.getcwd() try: # On Windows current directory may be on a different drive than self.tempdir. # However a relative path between two different drives is invalid. So we move to # self.tempdir to ensure that we stay on the same drive. os.chdir(self.tempdir) # The read-only filesystem introduced with macOS Catalina can break # code using relative paths below. See # https://bugs.python.org/issue38295 for another example of this. # Eliminating any possible symlinks in self.tempdir before passing # it to os.path.relpath solves the problem. This is done by calling # filesystem.realpath which removes any symlinks in the path on # POSIX systems. real_path = filesystem.realpath(os.path.join(self.tempdir, 'foo')) relative_path = os.path.relpath(real_path) self.assertRaises( argparse.ArgumentTypeError, cli.read_file, relative_path) test_contents = b'bar\n' with open(relative_path, 'wb') as f: f.write(test_contents) path, contents = cli.read_file(relative_path) self.assertEqual(path, os.path.abspath(path)) self.assertEqual(contents, test_contents) finally: os.chdir(curr_dir) class FlagDefaultTest(unittest.TestCase): """Tests cli.flag_default""" def test_default_directories(self): if os.name != 'nt': self.assertEqual(cli.flag_default('config_dir'), '/etc/letsencrypt') self.assertEqual(cli.flag_default('work_dir'), '/var/lib/letsencrypt') self.assertEqual(cli.flag_default('logs_dir'), '/var/log/letsencrypt') else: self.assertEqual(cli.flag_default('config_dir'), 'C:\\Certbot') self.assertEqual(cli.flag_default('work_dir'), 'C:\\Certbot\\lib') self.assertEqual(cli.flag_default('logs_dir'), 'C:\\Certbot\\log') class ParseTest(unittest.TestCase): '''Test the cli args entrypoint''' def setUp(self): reload_module(cli) @staticmethod def _unmocked_parse(*args, **kwargs): """Get result of cli.prepare_and_parse_args.""" return cli.prepare_and_parse_args(PLUGINS, *args, **kwargs) @staticmethod def parse(*args, **kwargs): """Mocks zope.component.getUtility and calls _unmocked_parse.""" with test_util.patch_get_utility(): return ParseTest._unmocked_parse(*args, **kwargs) def _help_output(self, args): "Run a command, and return the output string for scrutiny" output = six.StringIO() def write_msg(message, *args, **kwargs): # pylint: disable=missing-docstring,unused-argument output.write(message) with mock.patch('certbot._internal.main.sys.stdout', new=output): with test_util.patch_get_utility() as mock_get_utility: mock_get_utility().notification.side_effect = write_msg with mock.patch('certbot._internal.main.sys.stderr'): self.assertRaises(SystemExit, self._unmocked_parse, args, output) return output.getvalue() @mock.patch("certbot._internal.cli.helpful.flag_default") def test_cli_ini_domains(self, mock_flag_default): with tempfile.NamedTemporaryFile() as tmp_config: tmp_config.close() # close now because of compatibility issues on Windows # use a shim to get ConfigArgParse to pick up tmp_config shim = ( lambda v: copy.deepcopy(constants.CLI_DEFAULTS[v]) if v != "config_files" else [tmp_config.name] ) mock_flag_default.side_effect = shim namespace = self.parse(["certonly"]) self.assertEqual(namespace.domains, []) with open(tmp_config.name, 'w') as file_h: file_h.write("domains = example.com") namespace = self.parse(["certonly"]) self.assertEqual(namespace.domains, ["example.com"]) namespace = self.parse(["renew"]) self.assertEqual(namespace.domains, []) def test_no_args(self): namespace = self.parse([]) for d in ('config_dir', 'logs_dir', 'work_dir'): self.assertEqual(getattr(namespace, d), cli.flag_default(d)) def test_install_abspath(self): cert = 'cert' key = 'key' chain = 'chain' fullchain = 'fullchain' with mock.patch('certbot._internal.main.install'): namespace = self.parse(['install', '--cert-path', cert, '--key-path', 'key', '--chain-path', 'chain', '--fullchain-path', 'fullchain']) self.assertEqual(namespace.cert_path, os.path.abspath(cert)) self.assertEqual(namespace.key_path, os.path.abspath(key)) self.assertEqual(namespace.chain_path, os.path.abspath(chain)) self.assertEqual(namespace.fullchain_path, os.path.abspath(fullchain)) def test_help(self): self._help_output(['--help']) # assert SystemExit is raised here out = self._help_output(['--help', 'all']) self.assertTrue("--configurator" in out) self.assertTrue("how a certificate is deployed" in out) self.assertTrue("--webroot-path" in out) self.assertTrue("--text" not in out) self.assertTrue("%s" not in out) self.assertTrue("{0}" not in out) self.assertTrue("--renew-hook" not in out) out = self._help_output(['-h', 'nginx']) if "nginx" in PLUGINS: # may be false while building distributions without plugins self.assertTrue("--nginx-ctl" in out) self.assertTrue("--webroot-path" not in out) self.assertTrue("--checkpoints" not in out) out = self._help_output(['-h']) self.assertTrue("letsencrypt-auto" not in out) # test cli.cli_command if "nginx" in PLUGINS: self.assertTrue("Use the Nginx plugin" in out) else: self.assertTrue("(the certbot nginx plugin is not" in out) out = self._help_output(['--help', 'plugins']) self.assertTrue("--webroot-path" not in out) self.assertTrue("--prepare" in out) self.assertTrue('"plugins" subcommand' in out) # test multiple topics out = self._help_output(['-h', 'renew']) self.assertTrue("--keep" in out) out = self._help_output(['-h', 'automation']) self.assertTrue("--keep" in out) out = self._help_output(['-h', 'revoke']) self.assertTrue("--keep" not in out) out = self._help_output(['--help', 'install']) self.assertTrue("--cert-path" in out) self.assertTrue("--key-path" in out) out = self._help_output(['--help', 'revoke']) self.assertTrue("--cert-path" in out) self.assertTrue("--key-path" in out) self.assertTrue("--reason" in out) self.assertTrue("--delete-after-revoke" in out) self.assertTrue("--no-delete-after-revoke" in out) out = self._help_output(['-h', 'register']) self.assertTrue("--cert-path" not in out) self.assertTrue("--key-path" not in out) out = self._help_output(['-h']) self.assertTrue(cli.SHORT_USAGE in out) self.assertTrue(cli.COMMAND_OVERVIEW[:100] in out) self.assertTrue("%s" not in out) self.assertTrue("{0}" not in out) def test_help_no_dashes(self): self._help_output(['help']) # assert SystemExit is raised here out = self._help_output(['help', 'all']) self.assertTrue("--configurator" in out) self.assertTrue("how a certificate is deployed" in out) self.assertTrue("--webroot-path" in out) self.assertTrue("--text" not in out) self.assertTrue("%s" not in out) self.assertTrue("{0}" not in out) out = self._help_output(['help', 'install']) self.assertTrue("--cert-path" in out) self.assertTrue("--key-path" in out) out = self._help_output(['help', 'revoke']) self.assertTrue("--cert-path" in out) self.assertTrue("--key-path" in out) def test_parse_domains(self): short_args = ['-d', 'example.com'] namespace = self.parse(short_args) self.assertEqual(namespace.domains, ['example.com']) short_args = ['-d', 'trailing.period.com.'] namespace = self.parse(short_args) self.assertEqual(namespace.domains, ['trailing.period.com']) short_args = ['-d', 'example.com,another.net,third.org,example.com'] namespace = self.parse(short_args) self.assertEqual(namespace.domains, ['example.com', 'another.net', 'third.org']) long_args = ['--domains', 'example.com'] namespace = self.parse(long_args) self.assertEqual(namespace.domains, ['example.com']) long_args = ['--domains', 'trailing.period.com.'] namespace = self.parse(long_args) self.assertEqual(namespace.domains, ['trailing.period.com']) long_args = ['--domains', 'example.com,another.net,example.com'] namespace = self.parse(long_args) self.assertEqual(namespace.domains, ['example.com', 'another.net']) def test_preferred_challenges(self): short_args = ['--preferred-challenges', 'http, dns'] namespace = self.parse(short_args) expected = [challenges.HTTP01.typ, challenges.DNS01.typ] self.assertEqual(namespace.pref_challs, expected) short_args = ['--preferred-challenges', 'jumping-over-the-moon'] # argparse.ArgumentError makes argparse print more information # to stderr and call sys.exit() with mock.patch('sys.stderr'): self.assertRaises(SystemExit, self.parse, short_args) def test_server_flag(self): namespace = self.parse('--server example.com'.split()) self.assertEqual(namespace.server, 'example.com') def test_must_staple_flag(self): short_args = ['--must-staple'] namespace = self.parse(short_args) self.assertTrue(namespace.must_staple) self.assertTrue(namespace.staple) def _check_server_conflict_message(self, parser_args, conflicting_args): try: self.parse(parser_args) self.fail( # pragma: no cover "The following flags didn't conflict with " '--server: {0}'.format(', '.join(conflicting_args))) except errors.Error as error: self.assertTrue('--server' in str(error)) for arg in conflicting_args: self.assertTrue(arg in str(error)) def test_staging_flag(self): short_args = ['--staging'] namespace = self.parse(short_args) self.assertTrue(namespace.staging) self.assertEqual(namespace.server, constants.STAGING_URI) short_args += '--server example.com'.split() self._check_server_conflict_message(short_args, '--staging') def _assert_dry_run_flag_worked(self, namespace, existing_account): self.assertTrue(namespace.dry_run) self.assertTrue(namespace.break_my_certs) self.assertTrue(namespace.staging) self.assertEqual(namespace.server, constants.STAGING_URI) if existing_account: self.assertTrue(namespace.tos) self.assertTrue(namespace.register_unsafely_without_email) else: self.assertFalse(namespace.tos) self.assertFalse(namespace.register_unsafely_without_email) def test_dry_run_flag(self): config_dir = tempfile.mkdtemp() short_args = '--dry-run --config-dir {0}'.format(config_dir).split() self.assertRaises(errors.Error, self.parse, short_args) self._assert_dry_run_flag_worked( self.parse(short_args + ['auth']), False) self._assert_dry_run_flag_worked( self.parse(short_args + ['certonly']), False) self._assert_dry_run_flag_worked( self.parse(short_args + ['renew']), False) account_dir = os.path.join(config_dir, constants.ACCOUNTS_DIR) filesystem.mkdir(account_dir) filesystem.mkdir(os.path.join(account_dir, 'fake_account_dir')) self._assert_dry_run_flag_worked(self.parse(short_args + ['auth']), True) self._assert_dry_run_flag_worked(self.parse(short_args + ['renew']), True) self._assert_dry_run_flag_worked(self.parse(short_args + ['certonly']), True) short_args += ['certonly'] # `--dry-run --server example.com` should emit example.com self.assertEqual(self.parse(short_args + ['--server', 'example.com']).server, 'example.com') # `--dry-run --server STAGING_URI` should emit STAGING_URI self.assertEqual(self.parse(short_args + ['--server', constants.STAGING_URI]).server, constants.STAGING_URI) # `--dry-run --server LIVE` should emit STAGING_URI self.assertEqual(self.parse(short_args + ['--server', cli.flag_default("server")]).server, constants.STAGING_URI) # `--dry-run --server example.com --staging` should emit an error conflicts = ['--staging'] self._check_server_conflict_message(short_args + ['--server', 'example.com', '--staging'], conflicts) def test_option_was_set(self): key_size_option = 'rsa_key_size' key_size_value = cli.flag_default(key_size_option) self.parse('--rsa-key-size {0}'.format(key_size_value).split()) self.assertTrue(cli.option_was_set(key_size_option, key_size_value)) self.assertTrue(cli.option_was_set('no_verify_ssl', True)) config_dir_option = 'config_dir' self.assertFalse(cli.option_was_set( config_dir_option, cli.flag_default(config_dir_option))) self.assertFalse(cli.option_was_set( 'authenticator', cli.flag_default('authenticator'))) def test_encode_revocation_reason(self): for reason, code in constants.REVOCATION_REASONS.items(): namespace = self.parse(['--reason', reason]) self.assertEqual(namespace.reason, code) for reason, code in constants.REVOCATION_REASONS.items(): namespace = self.parse(['--reason', reason.upper()]) self.assertEqual(namespace.reason, code) def test_force_interactive(self): self.assertRaises( errors.Error, self.parse, "renew --force-interactive".split()) self.assertRaises( errors.Error, self.parse, "-n --force-interactive".split()) def test_deploy_hook_conflict(self): with mock.patch("certbot._internal.cli.sys.stderr"): self.assertRaises(SystemExit, self.parse, "--renew-hook foo --deploy-hook bar".split()) def test_deploy_hook_matches_renew_hook(self): value = "foo" namespace = self.parse(["--renew-hook", value, "--deploy-hook", value, "--disable-hook-validation"]) self.assertEqual(namespace.deploy_hook, value) self.assertEqual(namespace.renew_hook, value) def test_deploy_hook_sets_renew_hook(self): value = "foo" namespace = self.parse( ["--deploy-hook", value, "--disable-hook-validation"]) self.assertEqual(namespace.deploy_hook, value) self.assertEqual(namespace.renew_hook, value) def test_renew_hook_conflict(self): with mock.patch("certbot._internal.cli.sys.stderr"): self.assertRaises(SystemExit, self.parse, "--deploy-hook foo --renew-hook bar".split()) def test_renew_hook_matches_deploy_hook(self): value = "foo" namespace = self.parse(["--deploy-hook", value, "--renew-hook", value, "--disable-hook-validation"]) self.assertEqual(namespace.deploy_hook, value) self.assertEqual(namespace.renew_hook, value) def test_renew_hook_does_not_set_renew_hook(self): value = "foo" namespace = self.parse( ["--renew-hook", value, "--disable-hook-validation"]) self.assertEqual(namespace.deploy_hook, None) self.assertEqual(namespace.renew_hook, value) def test_max_log_backups_error(self): with mock.patch('certbot._internal.cli.sys.stderr'): self.assertRaises( SystemExit, self.parse, "--max-log-backups foo".split()) self.assertRaises( SystemExit, self.parse, "--max-log-backups -42".split()) def test_max_log_backups_success(self): value = "42" namespace = self.parse(["--max-log-backups", value]) self.assertEqual(namespace.max_log_backups, int(value)) def test_unchanging_defaults(self): namespace = self.parse([]) self.assertEqual(namespace.domains, []) self.assertEqual(namespace.pref_challs, []) namespace.pref_challs = [challenges.HTTP01.typ] namespace.domains = ['example.com'] namespace = self.parse([]) self.assertEqual(namespace.domains, []) self.assertEqual(namespace.pref_challs, []) def test_no_directory_hooks_set(self): self.assertFalse(self.parse(["--no-directory-hooks"]).directory_hooks) def test_no_directory_hooks_unset(self): self.assertTrue(self.parse([]).directory_hooks) def test_delete_after_revoke(self): namespace = self.parse(["--delete-after-revoke"]) self.assertTrue(namespace.delete_after_revoke) def test_delete_after_revoke_default(self): namespace = self.parse([]) self.assertEqual(namespace.delete_after_revoke, None) def test_no_delete_after_revoke(self): namespace = self.parse(["--no-delete-after-revoke"]) self.assertFalse(namespace.delete_after_revoke) def test_allow_subset_with_wildcard(self): self.assertRaises(errors.Error, self.parse, "--allow-subset-of-names -d *.example.org".split()) def test_route53_no_revert(self): for help_flag in ['-h', '--help']: for topic in ['all', 'plugins', 'dns-route53']: self.assertFalse('certbot-route53:auth' in self._help_output([help_flag, topic])) def test_no_permissions_check_accepted(self): namespace = self.parse(["--no-permissions-check"]) self.assertTrue(namespace.no_permissions_check) class DefaultTest(unittest.TestCase): """Tests for certbot._internal.cli._Default.""" def setUp(self): # pylint: disable=protected-access self.default1 = cli._Default() self.default2 = cli._Default() def test_boolean(self): self.assertFalse(self.default1) self.assertFalse(self.default2) def test_equality(self): self.assertEqual(self.default1, self.default2) def test_hash(self): self.assertEqual(hash(self.default1), hash(self.default2)) class SetByCliTest(unittest.TestCase): """Tests for certbot.set_by_cli and related functions.""" def setUp(self): reload_module(cli) def test_deploy_hook(self): self.assertTrue(_call_set_by_cli( 'renew_hook', '--deploy-hook foo'.split(), 'renew')) def test_webroot_map(self): args = '-w /var/www/html -d example.com'.split() verb = 'renew' self.assertTrue(_call_set_by_cli('webroot_map', args, verb)) def _call_set_by_cli(var, args, verb): with mock.patch('certbot._internal.cli.helpful_parser') as mock_parser: with test_util.patch_get_utility(): mock_parser.args = args mock_parser.verb = verb return cli.set_by_cli(var) if __name__ == '__main__': unittest.main() # pragma: no cover
40.2158
100
0.631708
9b81197edb6e28276e4a870e7026c376843b40a2
273
py
Python
submissions/panasonic2020/c.py
m-star18/atcoder
08e475810516602fa088f87daf1eba590b4e07cc
[ "Unlicense" ]
1
2021-05-10T01:16:28.000Z
2021-05-10T01:16:28.000Z
submissions/panasonic2020/c.py
m-star18/atcoder
08e475810516602fa088f87daf1eba590b4e07cc
[ "Unlicense" ]
3
2021-05-11T06:14:15.000Z
2021-06-19T08:18:36.000Z
submissions/panasonic2020/c.py
m-star18/atcoder
08e475810516602fa088f87daf1eba590b4e07cc
[ "Unlicense" ]
null
null
null
import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines sys.setrecursionlimit(10 ** 7) a, b, c = map(int, readline().split()) if a + b < c and (c - b - a) ** 2 > 4 * a * b: print('Yes') else: print('No')
22.75
46
0.630037
73cf83756f059b68ce1043d95e90f3bf3b635bb8
86
py
Python
receiver/f12020/api.py
f1laps/f1laps-telemetry
0c264f9300d58397fe2f8b3018cd2e9151e28d08
[ "MIT" ]
3
2021-02-23T22:06:13.000Z
2022-02-06T15:05:56.000Z
receiver/f12020/api.py
f1laps/f1laps-telemetry
0c264f9300d58397fe2f8b3018cd2e9151e28d08
[ "MIT" ]
null
null
null
receiver/f12020/api.py
f1laps/f1laps-telemetry
0c264f9300d58397fe2f8b3018cd2e9151e28d08
[ "MIT" ]
null
null
null
from receiver.api_base import F1LapsAPIBase class F1LapsAPI(F1LapsAPIBase): pass
17.2
43
0.813953
32fe8c35a61f3cce13e88847562c3245db4d952d
734
py
Python
tests/integration_tests/mechanics/cashflows/functions.py
worseliz/HERON
fa5f346a0bc9f9d5ea4659618ffeb52bea812cee
[ "Apache-2.0" ]
11
2020-07-28T21:35:26.000Z
2022-01-25T17:31:39.000Z
tests/integration_tests/mechanics/cashflows/functions.py
worseliz/HERON
fa5f346a0bc9f9d5ea4659618ffeb52bea812cee
[ "Apache-2.0" ]
112
2020-07-29T15:25:33.000Z
2022-03-31T19:21:00.000Z
tests/integration_tests/mechanics/cashflows/functions.py
worseliz/HERON
fa5f346a0bc9f9d5ea4659618ffeb52bea812cee
[ "Apache-2.0" ]
22
2020-07-28T20:08:12.000Z
2022-03-08T21:22:03.000Z
# Copyright 2020, Battelle Energy Alliance, LLC # ALL RIGHTS RESERVED """ Implements transfer functions """ def capacity(data, meta): """ return unit capacity @ In, data, dict, data requeset @ In, meta, dict, state information @ Out, data, dict, filled data @ Out, meta, dict, state information """ c = float(meta['HERON']['RAVEN_vars']['source_capacity']) data = {'driver': c} return data, meta def activity(data, meta): """ return usage of resource "a" @ In, data, dict, data requeset @ In, meta, dict, state information @ Out, data, dict, filled data @ Out, meta, dict, state information """ a = meta['HERON']['activity']['a'] data = {'driver': a} return data, meta
23.677419
59
0.628065
b04bfb7d75c07ec32bfa969a3d0c5ca5465509f6
2,741
py
Python
venv/lib/python3.6/site-packages/ansible_collections/f5networks/f5_modules/tests/unit/mock/procenv.py
usegalaxy-no/usegalaxy
75dad095769fe918eb39677f2c887e681a747f3a
[ "MIT" ]
1
2020-01-22T13:11:23.000Z
2020-01-22T13:11:23.000Z
venv/lib/python3.6/site-packages/ansible_collections/f5networks/f5_modules/tests/unit/mock/procenv.py
usegalaxy-no/usegalaxy
75dad095769fe918eb39677f2c887e681a747f3a
[ "MIT" ]
12
2020-02-21T07:24:52.000Z
2020-04-14T09:54:32.000Z
venv/lib/python3.6/site-packages/ansible_collections/f5networks/f5_modules/tests/unit/mock/procenv.py
usegalaxy-no/usegalaxy
75dad095769fe918eb39677f2c887e681a747f3a
[ "MIT" ]
null
null
null
# (c) 2016, Matt Davis <mdavis@ansible.com> # (c) 2016, Toshio Kuratomi <tkuratomi@ansible.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import sys import json from contextlib import contextmanager from io import BytesIO, StringIO from ansible_collections.f5networks.f5_modules.tests.unit.compat import unittest from ansible.module_utils.six import PY3 from ansible.module_utils._text import to_bytes @contextmanager def swap_stdin_and_argv(stdin_data='', argv_data=tuple()): """ context manager that temporarily masks the test runner's values for stdin and argv """ real_stdin = sys.stdin real_argv = sys.argv if PY3: fake_stream = StringIO(stdin_data) fake_stream.buffer = BytesIO(to_bytes(stdin_data)) else: fake_stream = BytesIO(to_bytes(stdin_data)) try: sys.stdin = fake_stream sys.argv = argv_data yield finally: sys.stdin = real_stdin sys.argv = real_argv @contextmanager def swap_stdout(): """ context manager that temporarily replaces stdout for tests that need to verify output """ old_stdout = sys.stdout if PY3: fake_stream = StringIO() else: fake_stream = BytesIO() try: sys.stdout = fake_stream yield fake_stream finally: sys.stdout = old_stdout class ModuleTestCase(unittest.TestCase): def setUp(self, module_args=None): if module_args is None: module_args = {'_ansible_remote_tmp': '/tmp', '_ansible_keep_remote_files': False} args = json.dumps(dict(ANSIBLE_MODULE_ARGS=module_args)) # unittest doesn't have a clean place to use a context manager, so we have to enter/exit manually self.stdin_swap = swap_stdin_and_argv(stdin_data=args) self.stdin_swap.__enter__() def tearDown(self): # unittest doesn't have a clean place to use a context manager, so we have to enter/exit manually self.stdin_swap.__exit__(None, None, None)
30.120879
105
0.711054
fe87cffaf50cff99c146e30983a4cf3a08e8f683
3,434
py
Python
auto_derby/single_mode/item/item_test.py
gentle-knight-13/auto-derby
70593fea2c3d803487e6e0d2ce0c40d60bc6304d
[ "MIT" ]
null
null
null
auto_derby/single_mode/item/item_test.py
gentle-knight-13/auto-derby
70593fea2c3d803487e6e0d2ce0c40d60bc6304d
[ "MIT" ]
null
null
null
auto_derby/single_mode/item/item_test.py
gentle-knight-13/auto-derby
70593fea2c3d803487e6e0d2ce0c40d60bc6304d
[ "MIT" ]
null
null
null
from auto_derby.single_mode.item.effect_summary import EffectSummary from ... import _test from ...constants import Mood, TrainingType from .. import race, training from ..commands import RaceCommand, TrainingCommand from ..context import Context from ..training import Training from . import game_data from . import test_sample def _iterate_item(): for i in game_data.iterate(): i.price = i.original_price yield i def test_property_item(): for name, ctx in test_sample.contexts(): _test.snapshot_match( { i.name: { "exchange": i.exchange_score(ctx), "expectedExchange": i.expected_exchange_score(ctx), "shouldUseDirectly": i.should_use_directly(ctx), } for i in _iterate_item() if any(e for e in i.effects if e.type == e.TYPE_PROPERTY) }, name=name, ) def test_training_buff_item(): for name, ctx in test_sample.contexts(): _test.snapshot_match( { i.name: { "exchange": i.exchange_score(ctx), "expectedExchange": i.expected_exchange_score(ctx), "shouldUseDirectly": i.should_use_directly(ctx), "training": { t_name: { "effect": i.effect_score( ctx, TrainingCommand(t), EffectSummary() ), "expectedEffect": i.expected_effect_score( ctx, TrainingCommand(t) ), } for t_name, t in test_sample.trainings() }, "maxRaceEffect": max( ( i.effect_score(ctx, RaceCommand(r), EffectSummary()) for r in test_sample.races() ) ), } for i in _iterate_item() if any(e for e in i.effects if e.type == e.TYPE_TRAINING_BUFF) }, name=name, ) def test_training_level_item(): def _contexts(): yield from test_sample.contexts() ctx1 = test_sample.simple_context() ctx1.training_levels = {i: 5 for i in TrainingType} yield "max-level", ctx1 for name, ctx in _contexts(): _test.snapshot_match( { i.name: { "exchange": i.exchange_score(ctx), "expectedExchange": i.expected_exchange_score(ctx), "shouldUseDirectly": i.should_use_directly(ctx), } for i in _iterate_item() if any(e for e in i.effects if e.type == e.TYPE_TRAINING_LEVEL) }, name=name, ) def test_race_reward_item(): hammer_1 = game_data.get(51) hammer_1.price = hammer_1.original_price # assert hammer_1.effect_score(ctx, RaceCommand(next(race.game_data.find_by_date((4,0,0))))) >0 for name, ctx in test_sample.contexts(): assert ( hammer_1.effect_score( ctx, TrainingCommand(training.Training.new()), EffectSummary() ) == 0 ) # assert hammer_1.exchange_score(ctx) > 0
33.666667
99
0.510775
285dfc335fa5f6ba96e2b9a3ee60ab822cf43b2c
5,407
py
Python
branch2learn/01b_generate_data_alt.py
Sandbergo/branch2learn
6045c3c01d7e2172bc6672fc3926b4e118ccd0a2
[ "MIT" ]
10
2021-06-01T13:22:19.000Z
2022-03-21T04:15:22.000Z
branch2learn/01b_generate_data_alt.py
Sandbergo/branch2learn
6045c3c01d7e2172bc6672fc3926b4e118ccd0a2
[ "MIT" ]
1
2021-11-06T13:36:51.000Z
2021-11-13T11:12:38.000Z
branch2learn/01b_generate_data_alt.py
Sandbergo/branch2learn
6045c3c01d7e2172bc6672fc3926b4e118ccd0a2
[ "MIT" ]
4
2021-07-16T12:58:44.000Z
2022-03-31T06:12:45.000Z
""" Instance generation script. File adapted from https://github.com/ds4dm/learn2branch by Lars Sandberg @Sandbergo May 2021 """ import os import gzip import pickle import argparse from pathlib import Path from typing import Callable import ecole import numpy as np from utilities.general import Logger class ExploreThenStrongBranch: """ This custom observation function class will randomly return either strong branching scores or pseudocost scores (weak expert for exploration) when called at every node. """ def __init__(self, expert_probability: float): self.expert_probability = expert_probability self.pseudocosts_function = ecole.observation.Pseudocosts() self.strong_branching_function = ecole.observation.StrongBranchingScores() def before_reset(self, model): """ This function will be called at initialization of the environment (before dynamics are reset). """ self.pseudocosts_function.before_reset(model) self.strong_branching_function.before_reset(model) def extract(self, model, done): """ Should we return strong branching or pseudocost scores at time node? """ probabilities = [1 - self.expert_probability, self.expert_probability] expert_chosen = bool(np.random.choice(np.arange(2), p=probabilities)) if expert_chosen: return (self.strong_branching_function.extract(model, done), True) else: return (self.pseudocosts_function.extract(model, done), False) def generate_instances( instance_path: str, sample_path: str, num_samples: int, log: Callable ) -> None: scip_parameters = { "separating/maxrounds": 0, "presolving/maxrestarts": 0, "limits/time": 3600, } env = ecole.environment.Branching( observation_function=( ExploreThenStrongBranch(expert_probability=0.05), ecole.observation.NodeBipartite(), ), scip_params=scip_parameters, ) env.seed(0) instance_files = [str(path) for path in Path(instance_path).glob("instance_*.lp")] log(f"Generating from {len(instance_files)} instances") episode_counter, sample_counter = 0, 0 # We will solve problems (run episodes) until we have saved enough samples while True: for _file in instance_files: episode_counter += 1 observation, action_set, _, done, _ = env.reset(_file) while not done: (scores, scores_are_expert), node_observation = observation action = action_set[scores[action_set].argmax()] # Only save samples if they are coming from the expert (strong branching) if scores_are_expert: sample_counter += 1 if sample_counter > num_samples: return node_observation = ( node_observation.row_features, ( node_observation.edge_features.indices, node_observation.edge_features.values, ), node_observation.column_features, ) data = [node_observation, action, action_set, scores] filename = f"{sample_path}/sample_{sample_counter}.pkl" with gzip.open(filename, "wb") as out_file: pickle.dump(data, out_file) observation, action_set, _, done, _ = env.step(action) if episode_counter % 10 == 0: log(f"Episode {episode_counter}, {sample_counter} samples collected") return if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "-p", "--problem", help="MILP instance type to process.", choices=["setcover", "cauctions", "facilities", "indset"], default="setcover", ) args = parser.parse_args() PROBLEM_TYPE = args.problem Path("branch2learn/log/").mkdir(exist_ok=True) log = Logger(filename="branch2learn/log/01_generate_data") log(f"Problem: {PROBLEM_TYPE}") basedir_samp = f"branch2learn/data/samples/{PROBLEM_TYPE}/" basedir_inst = f"branch2learn/data/instances/{PROBLEM_TYPE}/" train_path_inst = f"{basedir_inst}/train/" valid_path_inst = f"{basedir_inst}/valid/" test_path_inst = f"{basedir_inst}/test/" train_path_samp = f"{basedir_samp}/train/" os.makedirs(Path(train_path_samp), exist_ok=True) valid_path_samp = f"{basedir_samp}/valid/" os.makedirs(Path(valid_path_samp), exist_ok=True) test_path_samp = f"{basedir_samp}/test/" os.makedirs(Path(test_path_samp), exist_ok=True) log("Generating training files") generate_instances( instance_path=train_path_inst, sample_path=train_path_samp, num_samples=50_000, log=log, ) log("Generating valid files") generate_instances( instance_path=valid_path_inst, sample_path=valid_path_samp, num_samples=10_000, log=log, ) log("Generating test files") generate_instances( instance_path=test_path_inst, sample_path=test_path_samp, num_samples=10_000, log=log, ) log("End of data generation.")
31.254335
94
0.635842
ae7b30c027bcfd10da75ec27cd05e2de82530d71
22,593
py
Python
python/radarsat_processing.py
vightel/FloodMapsWorkshop
ebc5246fbca52f2ee181a07663b859b2f6f59532
[ "Apache-2.0" ]
24
2015-02-07T06:34:14.000Z
2021-11-06T08:06:40.000Z
python/radarsat_processing.py
vightel/FloodMapsWorkshop
ebc5246fbca52f2ee181a07663b859b2f6f59532
[ "Apache-2.0" ]
1
2018-07-23T01:54:23.000Z
2018-07-23T01:55:05.000Z
python/radarsat_processing.py
vightel/FloodMapsWorkshop
ebc5246fbca52f2ee181a07663b859b2f6f59532
[ "Apache-2.0" ]
15
2015-03-10T06:39:10.000Z
2020-01-06T19:54:16.000Z
#!/usr/bin/env python # # Created on 3/23/2012 Pat Cappelaere - Vightel Corporation # by getting help from # http://benjamindeschamps.ca/blog/2009/11/12/processing-radarsat-2-imagery-reading-raw-data-and-saving-rgb-composites/ # and sat kumar tomer (http://civil.iisc.ernet.in/~satkumar/) # and https://pypi.python.org/pypi/radarsatlib/1.0.0 # # Requirements: # gdal, numpy, scipy... import os, inspect import argparse import sys, urllib, httplib, subprocess import numpy import math import shutil import zipfile #NoneType = type(None) import scipy.signal from scipy import ndimage import pprint import mapnik from mapnik import DatasourceCache as datasourceCache; from osgeo import gdal from osgeo import osr from osgeo import ogr import config #import ogr2osm from which import * from xml.dom import minidom from datetime import datetime import config BASE_DIR = config.RADARSAT2_DIR; HAND_DIR = config.HANDS_DIR HAND_FILE = config.HANDS_AREA + "_hand_merged_lzw.tif" class Radarsat2: def execute( self, cmd ): if self.verbose: print cmd os.system(cmd) def tolatlon(self,x,y): adfGeoTransform = self.geotransform dfGeoX = adfGeoTransform[0] + adfGeoTransform[1] * x + adfGeoTransform[2] * y dfGeoY = adfGeoTransform[3] + adfGeoTransform[4] * x + adfGeoTransform[5] * y return dfGeoX, dfGeoY def __init__( self, cwd, inpath, verbose ): if verbose: print("Processing: %s" % inpath) self.inpath = inpath self.cwd = cwd # get the scene out of inpath arr = map(str, inpath.split('/')) self.scene = arr[len(arr)-1] input_file = "imagery_HH.tif" output_copy = "outputfile_raw.tif" output_4326 = "outputfile_4326.tif" output_4326_vrt = "outputfile_4326.vrt" output_4326_rgb = "outputfile_4326_rgb.tif" output_4326_hand = "outputfile_4326_hand.tif" output_3857 = "outputfile_3857.tif" output_3857_vrt = "outputfile_3857.vrt" output_3857_rgb = "outputfile_3857_rgb.tif" output_3857_hand = "outputfile_3857_hand.tif" output_4326_shp = "outputfile_4326.shp" hand_3857 = "hand_3857.tif" hand_3857_vrt = "hand_3857_vrt.tif" hand_4326 = "hand_4326.tif" hand_4326_vrt = "hand_4326_vrt.tif" output_basename = "outputfile_sigma.tif" output_merc_basename = "outputfile_sigma_mercator.tif" output_basename_a = "outputfile_sigma_alpha.tif" output_merc_basename_a = "outputfile_sigma_mercator_alpha.tif" output_merc_vrt = "outputfile_sigma_mercator_alpha_vrt.tif" incidence_basename = "outputfile_ia.tif" osm_basename = "outputfile_osm.xml" water_mask = "water_mask.tif" osm_water = "osm_water.png" dem = "dem.tif" hillshaded = "hillshaded.tif" color_relief = "color-relief.tif" flood_elevation_model = "flood-elevation-model.tif" color_composite = "composite.tif" dem = "dem.tif" asterdem_watermask = "asterdem_watermask.tif" dem_merc = "dem_merc.tif" dem_clipped = "dem_clipped.tif" browse_image = "BrowseImage" outputbrowse_image = "surface_water.png" osm_bg_image = "osm_bg_image.png" sw_osm_image = "surface_water_osm.png" coastlines = "osm_coastal.tif" self.coastlines = os.path.join(inpath, coastlines) self.hand_dir = HAND_DIR self.input_file = os.path.join(inpath, input_file) self.output_4326 = os.path.join(inpath, output_4326) self.output_4326_vrt = os.path.join(inpath, output_4326_vrt) self.output_4326_rgb = os.path.join(inpath, output_4326_rgb) self.output_4326_shp = os.path.join(inpath, "shp", output_4326_shp) self.output_4326_hand = os.path.join(inpath, output_4326_hand) self.osm_coastal = os.path.join(inpath, "osm_coastal.tif") self.masked_output_4326_rgb = os.path.join(inpath, "masked_"+output_4326_rgb) self.hand_3857 = os.path.join(inpath, hand_3857) self.hand_3857_vrt = os.path.join(inpath, hand_3857_vrt) self.hand_4326 = os.path.join(inpath, hand_4326) self.hand_4326_vrt = os.path.join(inpath, hand_4326_vrt) self.output_3857 = os.path.join(inpath, output_3857) self.output_3857_vrt = os.path.join(inpath, output_3857_vrt) self.output_3857_rgb = os.path.join(inpath, output_3857_rgb) self.output_3857_hand = os.path.join(inpath, output_3857_hand) self.output_copy = os.path.join(inpath, output_copy) self.output_full_name = os.path.join(inpath, output_basename) self.output_merc_full_name = os.path.join(inpath, output_merc_basename) self.output_full_name_a = os.path.join(inpath, output_basename_a) self.output_merc_full_name_a = os.path.join(inpath, output_merc_basename_a) self.output_merc_vrt = os.path.join(inpath, output_merc_vrt) self.incidence_full_name = os.path.join(inpath, incidence_basename) self.osm_basename = os.path.join(inpath, osm_basename) self.water_mask = os.path.join(inpath, self.scene, water_mask) self.osm_water = os.path.join(inpath, osm_water) self.dem = os.path.join(inpath, "mbtiles", dem) self.asterdem_watermask = os.path.join(inpath, self.scene,dem) self.flood_elevation_model = os.path.join(inpath, self.scene, flood_elevation_model) self.dem_clipped = os.path.join(inpath, "mbtiles", dem_clipped) self.dem_merc = os.path.join(inpath, "mbtiles", dem_merc) self.hillshaded = os.path.join(inpath, "mbtiles", hillshaded) self.color_relief = os.path.join(inpath, "mbtiles", color_relief) self.color_composite = os.path.join(inpath, "mbtiles", color_composite) self.browse_image = os.path.join(inpath,browse_image) self.outputbrowse_image = os.path.join(inpath,outputbrowse_image) self.osm_bg_image = os.path.join(inpath,osm_bg_image) self.sw_osm_image = os.path.join(inpath,sw_osm_image) # # Apply Speckle filter # def speckle_filter(self, filter_name, ws): if app.verbose: print("filter it..") # we need to turn it to float self.data = 1.*self.data if filter_name == 'median': self.data = scipy.signal.medfilt2d(self.data, kernel_size=ws) elif filter_name == 'wiener': self.data = scipy.signal.wiener(self.data,mysize=(ws,ws),noise=None) # # Relative hard thresholding # def threshold( self ): mean = numpy.mean(self.data) if app.verbose: print( "thresholding - mean: %f threshold: %f" % (mean, mean/2)) self.data = ( self.data < mean/2 ) if app.verbose: print( "done.") # # Save processed data back in the file # def save_tiff(self): # save the copy after processing print "saving processed data..." band = self.input_dataset.GetRasterBand(1) band.WriteArray(self.data, 0, 0) band.SetNoDataValue(0) self.data = None self.input_dataset = None # data has been saved back in same file as a bit mask (0..1) # # File was too large to be processed... process by subsets # def process_subsets(self): if app.verbose: print "Process all subsets..." # will need that for thresholding all files the same way mean = numpy.mean(self.data) #print "Mean:", mean divideBy = 2 xmin = 0 ymin = 0 xinc = self.rasterXSize/divideBy yinc = self.rasterYSize/divideBy xmax = xinc ymax = yinc for j in range(0, divideBy): for i in range(0, divideBy): if app.verbose: print "processing subset", ymin,":",ymax,",",xmin,":",xmax # one subset at at time subset = self.data[ymin:ymax,xmin:xmax] # Threshold it if app.verbose: print "Threshold it..." # and save it as float to despeckle it subset = ( subset < mean/2 ) # Despeckle if app.verbose: print "Despeckle it..." subset = 1.0 * subset # there might be a better way to keep it as Int8 but...not sure how to recast it subset = scipy.signal.medfilt2d(subset, kernel_size=3) subset = 1 * subset # there might be a better way to keep it as Int8 but...not sure how to recast it #print "Save it..." #band.WriteArray(self.data, 0, 0) #use numpy slicing self.data[ymin:ymax,xmin:xmax] = subset xmin = xmin + xinc xmax = xmax + xinc ymin = ymin + yinc ymax = ymax + yinc xmin = 0 xmax = xinc subset = None input_dataset = None band = self.input_dataset.GetRasterBand(1) band.WriteArray(self.data, 0, 0) self.data = None self.input_dataset = None # # Process raw data... thresholding, despecking... # def process_raw_data(self): if self.force or not os.path.isfile(self.output_copy): format = "GTiff" driver = gdal.GetDriverByName( format ) #print "Copying ", self.input_file src_ds = gdal.Open( self.input_file ) # will be open as writeable as well self.input_dataset = driver.CreateCopy( self.output_copy, src_ds, 0, [ 'COMPRESS=DEFLATE' ] ) self.rasterXSize = self.input_dataset.RasterXSize self.rasterYSize = self.input_dataset.RasterYSize self.total = self.rasterXSize * self.rasterYSize * 4 self.total /= 1024 #KB self.total /= 1024 #MB if app.verbose: print 'Total Size is: ', self.total, "MB" band = self.input_dataset.GetRasterBand(1) # get sinclair matrix if app.verbose: print "Read data..." self.data = band.ReadAsArray(0, 0, self.rasterXSize, self.rasterYSize ) if self.total < 1024: # from 1500 self.threshold() self.speckle_filter('median', 3) self.save_tiff() else: self.process_subsets() # # Reproject with alpha mask # def reproject( self, epsg, out_file): # remove out_file if it already exists if os.path.isfile(out_file): os.remove(out_file) cmd = "gdalwarp -of GTiff -co COMPRESS=DEFLATE -t_srs "+ epsg +" -multi -dstalpha " + self.output_copy + " " + out_file self.execute(cmd) # # Generate Virtual File # def generate_vrt(self, out_file, out_vrt): # Generate VRT file cmd = "gdal_translate -q -of VRT " + out_file + " " + out_vrt self.execute(cmd) # # Add colortable to colorize file with gdal_translate -expand rgba # def add_colortable_to_vrt( self, out_vrt): # We need to edit the virtual file to add a colortable dom = minidom.parse(out_vrt) cinterp = dom.getElementsByTagName('ColorInterp')[0] if cinterp.firstChild.nodeType != cinterp.TEXT_NODE: raise Exception("node does not contain text") cinterp.firstChild.replaceWholeText("Palette") cinterp.firstChild.replaceWholeText("Palette") xmlTag = dom.getElementsByTagName('VRTRasterBand')[0] ct = dom.createElement("ColorTable") e = dom.createElement("Entry") e.setAttribute('c1', '0') e.setAttribute('c2', '0') e.setAttribute('c3', '0') e.setAttribute('c4', '0') # but does not seem to work ct.appendChild(e) e = dom.createElement("Entry") e.setAttribute('c1', '255') e.setAttribute('c2', '0') e.setAttribute('c3', '0') e.setAttribute('c4', '255') ct.appendChild(e) xmlTag.appendChild(ct) file = open(out_vrt, 'w') file.write(dom.toxml()) file.close() print "vrt updated with color palette" # # Generate Subset HAND file def generate_hand_subset(self, base_img, in_img, out_img): if self.force or not os.path.isfile(out_img): cmd = os.path.join(self.cwd, "subset.py")+" "+ base_img + " " + in_img + " " + out_img self.execute(cmd) # # Height Above Nearest Drainage # def hand(self): base_img = self.output_4326 in_img = os.path.join(self.hand_dir, HAND_FILE) out_img = self.hand_4326 # Get a subset of HAND for particular tile #if self.force or not os.path.isfile(out_img): #print "generate hand subset:"+out_img +" from:"+in_img self.generate_hand_subset(base_img, in_img, out_img) #if not os.path.isfile(self.hand_4326) and not self.force: # cmd = "gdalwarp -of GTIFF "+ out_img + " " + self.hand_4326 # print cmd # err = os.system(cmd) # print "Generating HAND Tif error:", err # #sys.exit(0) if os.path.isfile(self.output_4326_hand) and not self.force: return if verbose: print "Generating ", self.output_4326_hand src_ds = gdal.Open( self.output_4326_rgb ) driver = gdal.GetDriverByName( "GTiff" ) input_dataset = driver.CreateCopy( self.output_4326_hand, src_ds, 0, [ 'COMPRESS=DEFLATE' ] ) input_band = input_dataset.GetRasterBand(1) input_data = input_band.ReadAsArray(0, 0, input_dataset.RasterXSize, input_dataset.RasterYSize ) alpha_band = input_dataset.GetRasterBand(4) alpha_data = alpha_band.ReadAsArray(0, 0, input_dataset.RasterXSize, input_dataset.RasterYSize ) hand_ds = gdal.Open(out_img) hand_band = hand_ds.GetRasterBand(1) hand_data = hand_band.ReadAsArray(0, 0, hand_ds.RasterXSize, hand_ds.RasterYSize ) coastlines_ds = gdal.Open(self.coastlines) coastal_band = coastlines_ds.GetRasterBand(1) coastal_data = coastal_band.ReadAsArray(0, 0, coastlines_ds.RasterXSize, coastlines_ds.RasterYSize ) if app.verbose: print "hand_data:", hand_data.min(), hand_data.max() # HAND Masking mask = hand_data==0 input_data[mask]= 0 mask = hand_data==255 input_data[mask]= 0 mask = coastal_data>0 input_data[mask]= 0 # # Morphing to smooth and filter the data # octagon_2 =[[0, 1, 1, 1, 0], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [0, 1, 1, 1, 0]] morphed = ndimage.grey_opening(input_data, size=(5,5), structure=octagon_2) input_band.WriteArray(morphed, 0, 0) input_band.SetNoDataValue(0) # set transparency alpha_data[morphed<255]=0 alpha_data[morphed>=255]=255 alpha_band.WriteArray(alpha_data, 0, 0) input_data = None morphed = None input_dataset = None hand_band = None hand_ds = None src_ds = None coastlines_ds = None if app.verbose: print "Hand Morphed Done ", self.output_4326_hand # ====================================== # Convert CSA BrowseImage tif to png to use this in browser easily # def convert_browse_image(self): cmd = str.format("convert {0}.tif {0}.png", self.browse_image ); self.execute(cmd) # ====================================== # Reproject to 4326 # def process_to_4326(self): if self.force or not os.path.isfile(self.output_4326): self.reproject("EPSG:4326", self.output_4326) if self.force or not os.path.isfile(self.output_4326_vrt): self.generate_vrt(self.output_4326, self.output_4326_vrt) self.add_colortable_to_vrt(self.output_4326_vrt) # Let's generate the rgb in that projection # generate the RGB file first if self.force or not os.path.isfile(self.output_4326_rgb): cmd = "gdal_translate -q -of GTiff -ot byte -expand rgba -co COMPRESS=DEFLATE " + self.output_4326_vrt + " " + self.output_4326_rgb self.execute(cmd) # Before we go any further, we need our new projected bbox ds = gdal.Open( self.output_4326_rgb ) if ds is None: print("Error opening: "+ self.output_4326_rgb) sys.exit(-1) if app.verbose: print 'Size is ', ds.RasterXSize,'x', ds.RasterYSize, 'x', ds.RasterCount print 'Projection is ', ds.GetProjection() self.metadata = ds.GetDriver().GetMetadata() self.geotransform = ds.GetGeoTransform() self.north = self.geotransform[3] self.west = self.geotransform[0] self.south = self.north - self.geotransform[1]* ds.RasterYSize self.east = self.west + self.geotransform[1]* ds.RasterXSize #print self.geotransform #print ds.RasterYSize, ds.RasterYSize if app.verbose: print("north: %9.5f south:%9.5f west:%9.5f east:%9.5f" % (self.north, self.south, self.west,self.east )) print("bbox: %9.5f,%9.5f,%9.5f,%9.5f" % (self.west, self.south, self.east, self.north )) xorg = self.geotransform[0] yorg = self.geotransform[3] pres = self.geotransform[1] xmax = xorg + self.geotransform[1]* ds.RasterXSize ymax = yorg - self.geotransform[1]* ds.RasterYSize # Create reference water/watershed vectors as well # Needed for refining hand & remove coastal zones cmd = str.format(os.path.join(self.cwd, "geojson_osm.py")+" --dir {0} --bbox {1} {2} {3} {4} --img {5} {6} --res {7}", self.inpath, xorg, ymax, xmax, yorg, ds.RasterXSize, ds.RasterYSize, pres ) self.execute(cmd) # Check Height Above Nearest Drainage to remove noise artifacts self.hand() self.bbox = str.format("BBOX={0},{1},{2},{3}", xorg, ymax, xmax, yorg) # ====================================== # Generate flood vectors # def geojson_4326(self): infile = self.output_4326_hand self.geojson( infile ) def geojson(self, infile): indataset = gdal.Open( infile ) geomatrix = indataset.GetGeoTransform() rasterXSize = indataset.RasterXSize rasterYSize = indataset.RasterYSize xorg = geomatrix[0] yorg = geomatrix[3] pres = geomatrix[1] xmax = xorg + geomatrix[1]* rasterXSize ymax = yorg - geomatrix[1]* rasterYSize #print geomatrix #print rasterXSize, rasterYSize #print "geojson bbox:", xorg, ymax, xmax, yorg file = infile + ".pgm" if app.force or not os.path.exists(file+".topojson"): # subset it, convert red band (band 1) and output to .pgm using PNM driver cmd = "gdal_translate -q -of PNM " + infile + " -b 1 -ot Byte "+file self.execute(cmd) cmd = "rm -f "+file+".aux.xml" self.execute(cmd) # -i invert before processing # -t 2 suppress speckles of up to this many pixels. # -a 1.5 set the corner threshold parameter # -z black specify how to resolve ambiguities in path decomposition. Must be one of black, white, right, left, minority, majority, or random. Default is minority # -x scaling factor # -L left margin # -B bottom margin cmd = str.format("potrace -z black -a 1.5 -t 2 -i -b geojson -o {0} {1} -x {2} -L {3} -B {4} ", file+".geojson", file, pres, xorg, ymax ); self.execute(cmd) cmd = str.format("topojson -o {0} --simplify-proportion 0.5 -- surface_water={1}", file+".topojson", file+".geojson" ); self.execute(cmd) cmd = "rm -f "+file+".geojson" self.execute(cmd) cmd = "rm -f "+file self.execute(cmd) dir = os.path.dirname(file) surface_water_file = os.path.join(dir, "surface_water.json") if app.force or not os.path.exists(surface_water_file): cmd = "topojson-geojson -o %s --precision 5 --id-property surface_water -- %s" %(dir, file+".topojson") self.execute(cmd) cmd = "mv "+file+".topojson "+ os.path.join(dir,"surface_water.topojson") self.execute(cmd) # Transform to KMZ #cmd = os.path.join(self.cwd,"geojson2kmz.py")+" --input %s --scene %s" %(surface_water_file, self.scene) #self.execute(cmd) # Transform to OSM.bz2 surface_water_osm_file = os.path.join(dir, "surface_water.osm") if app.force or not os.path.exists(surface_water_osm_file): data_source = "radarsat-2" cmd = str.format("node geojson2osm {0} {1} ", surface_water_file, data_source) self.execute(cmd) cmd = "bzip2 " + surface_water_osm_file self.execute(cmd) # Compress [geo]json surface_water_json_file = os.path.join(dir, "surface_water.json") surface_water_json_tgz_file = os.path.join(dir, "surface_water.json.gz") if app.force or not os.path.exists(surface_water_json_tgz_file): cmd = str.format("gzip {0} ", surface_water_json_file ); self.execute(cmd) # Compress original json surface_water_topojson_file = os.path.join(dir, "surface_water.topojson") surface_water_topojson_tgz_file = os.path.join(dir, "surface_water.topojson.gz") if app.force or not os.path.exists(surface_water_topojson_tgz_file): cmd = str.format("gzip {0} ", surface_water_topojson_file ); self.execute(cmd) def clear_all_artifacts(self, dir, scene): # Remove older artifacts os.system( "rm -f " + dir + "/output_*") os.system( "rm -f " + dir + "/*outputfile_*") os.system( "rm -rf " + dir + "/mapnik") os.system( "rm -rf " + dir + "/osm") os.system( "rm -rf " + dir + "/osm_tiles") os.system( "rm -rf " + dir + "/mb_tiles") os.system( "rm -rf " + dir + "/" + scene) os.system( "rm -f " + dir + "/" + scene + ".*") os.system( "rm -f " + dir + "/product.kmz") os.system( "rm -f " + dir + "/all.osm.tar.bz2") os.system( "rm -f " + dir + "/*_water*") os.system( "rm -f " + dir + "/osm*") os.system( "rm -f " + dir + "/hand*") os.system( "rm -f " + dir + "/pop_density*") if __name__ == '__main__': version_num = int(gdal.VersionInfo('VERSION_NUM')) if version_num < 1800: # because of GetGeoTransform(can_return_null) print('ERROR: Python bindings of GDAL 1.8.0 or later required') sys.exit(1) err = which("convert") if err == None: print "convert missing... brew install imagemagick --with-libtiff" sys.exit(-1) err = which("bzip2") if err == None: print "bzip2 missing" sys.exit(-1) err = which("potrace") if err == None: print "potrace missing" sys.exit(-1) err = which("topojson") if err == None: print "topojson missing" sys.exit(-1) # make sure that mapnik has the gdal plugin if not 'gdal' in datasourceCache.plugin_names(): print "Missing 'gdal' input plugin in mapnik - brew install mapnik --with-gdal --with-postgresql --with-cairo" sys.exit(-1) cwd = os.path.dirname(sys.argv[0]) #dir = BASE_DIR; parser = argparse.ArgumentParser(description='Process Radarsat2 scene') apg_input = parser.add_argument_group('Input') apg_input.add_argument("-f", "--force", action='store_true', help="Forces new product to be generated") apg_input.add_argument("-v", "--verbose", action='store_true', help="Verbose on/off") apg_input.add_argument("-c", "--clean", action='store_true', help="Clean artifacts") apg_input.add_argument("-s", "--scene", help="radarsat2 scene") options = parser.parse_args() force = options.force verbose = options.verbose scene = options.scene clean = options.clean if verbose: print "** Radarsat Processing start:", str(datetime.now()) inpath = os.path.join(BASE_DIR, scene) app = Radarsat2(cwd, inpath, verbose) app.force = force app.verbose = verbose if clean: app.clear_all_artifacts(inpath, scene) app.process_raw_data() # Just to make sure it is destroyed to save the memory app.input_dataset = None app.data = None # Convert BrowseImage.tif to BrowseImage.png so we can use it in Browser if app.force or not os.path.isfile(app.browse_image+".png"): app.convert_browse_image() app.process_to_4326() app.geojson_4326() cmd = os.path.join(cwd,"browseimage.py %s" % (app.inpath)) if app.force: cmd += " -f " if verbose: print cmd os.system(cmd) if verbose: print "**End:", str(datetime.now()) sys.exit(1)
31.466574
164
0.681096
9acefd1473eec77d9fcd6de29dadc28dc2545f3a
44,178
py
Python
pysparkling/sql/internals.py
ptallada/pysparkling
f0e8e8d039f3313c2693b7c7576cb1b7ba5a6d78
[ "Apache-2.0" ]
260
2015-05-11T18:08:44.000Z
2022-01-15T13:19:43.000Z
pysparkling/sql/internals.py
ptallada/pysparkling
f0e8e8d039f3313c2693b7c7576cb1b7ba5a6d78
[ "Apache-2.0" ]
79
2015-06-02T09:53:25.000Z
2021-09-26T11:18:18.000Z
pysparkling/sql/internals.py
ptallada/pysparkling
f0e8e8d039f3313c2693b7c7576cb1b7ba5a6d78
[ "Apache-2.0" ]
50
2015-06-06T17:00:58.000Z
2022-01-15T13:19:18.000Z
from collections import Counter from copy import deepcopy from functools import partial import itertools import json import math import warnings from ..stat_counter import CovarianceCounter, RowStatHelper from ..storagelevel import StorageLevel from ..utils import ( compute_weighted_percentiles, format_cell, get_keyfunc, merge_rows, merge_rows_joined_on_values, pad_cell, portable_hash, reservoir_sample_and_size, str_half_width ) from .column import parse from .functions import array, collect_set, count, lit, map_from_arrays, rand, struct from .internal_utils.column import resolve_column from .internal_utils.joins import ( CROSS_JOIN, FULL_JOIN, INNER_JOIN, LEFT_ANTI_JOIN, LEFT_JOIN, LEFT_SEMI_JOIN, RIGHT_JOIN ) from .schema_utils import get_schema_from_cols, infer_schema_from_rdd, merge_schemas from .types import create_row, DataType, LongType, Row, row_from_keyed_values, StringType, StructField, StructType from .utils import IllegalArgumentException def _generate_show_layout(char: str, fields): if not fields: return '' txt = char txt += char.join(fields) txt += char + '\n' return txt class FieldIdGenerator: """ This metaclass adds an unique ID to all instances of its classes. This allows to identify that a field was, when created, associated to a DataFrame. Such field can be retrieved with the syntax df.name to build an operation. The id clarifies if it is still associated to a field and which one when the operation is applied. While id() allow the same behaviour in most cases, this one: - Allows deep copies which are needed for aggregation - Support distributed computation, e.g. multiprocessing """ _id = 0 @classmethod def next(cls): cls._id += 1 return cls._id @classmethod def bind_schema(cls, schema): for field in schema.fields: if not hasattr(field, "id"): field.id = cls.next() if isinstance(field, StructType): cls.bind_schema(field) return schema @classmethod def unbind_schema(cls, schema): for field in schema.fields: delattr(field, "id") if isinstance(field, StructType): cls.unbind_schema(field) return schema class DataFrameInternal: def __init__(self, sc, rdd, cols=None, convert_to_row=False, schema=None): """ :type rdd: RDD """ if convert_to_row: if cols is None: cols = [f"_c{i}" for i in range(200)] rdd = rdd.map(partial(create_row, cols)) self._sc = sc self._rdd = rdd if schema is None and convert_to_row is False: raise NotImplementedError( "Schema cannot be None when creating DataFrameInternal from another. " "As a user you should not see this error, feel free to report a bug at " "https://github.com/svenkreiss/pysparkling/issues" ) if schema is not None: self._set_schema(schema) else: self._set_schema(infer_schema_from_rdd(self._rdd)) def _set_schema(self, schema): bound_schema = FieldIdGenerator.bind_schema(deepcopy(schema)) self.bound_schema = bound_schema @property def unbound_schema(self): schema = deepcopy(self.bound_schema) return FieldIdGenerator.unbind_schema(schema) def _with_rdd(self, rdd, schema): return DataFrameInternal( self._sc, rdd, schema=schema ) def rdd(self): return self._rdd @staticmethod def range(sc, start, end=None, step=1, numPartitions=None): if end is None: start, end = 0, start rdd = sc.parallelize( ([i] for i in range(start, end, step)), numSlices=numPartitions ) return DataFrameInternal(sc, rdd, ["id"], True) def count(self): return self._rdd.count() def collect(self): return self._rdd.collect() def toLocalIterator(self): return self._rdd.toLocalIterator() def limit(self, n): jdf = self._sc.parallelize(self._rdd.take(n)) return self._with_rdd(jdf, self.bound_schema) def take(self, n): return self._rdd.take(n) def foreach(self, f): self._rdd.foreach(f) def foreachPartition(self, f): self._rdd.foreachPartition(f) def cache(self): return self._with_rdd(self._rdd.cache(), self.bound_schema) def persist(self, storageLevel=StorageLevel.MEMORY_ONLY): return self._with_rdd(self._rdd.persist(storageLevel), self.bound_schema) def unpersist(self, blocking=False): return self._with_rdd(self._rdd.unpersist(blocking), self.bound_schema) def coalesce(self, numPartitions): return self._with_rdd(self._rdd.coalesce(numPartitions), self.bound_schema) def distinct(self): return self._with_rdd(self._rdd.distinct(), self.bound_schema) def sample(self, withReplacement=None, fraction=None, seed=None): return self._with_rdd( self._rdd.sample( withReplacement=withReplacement, fraction=fraction, seed=seed ), self.bound_schema ) def randomSplit(self, weights, seed): return self._with_rdd( self._rdd.randomSplit(weights=weights, seed=seed), self.bound_schema ) @property def storageLevel(self): return getattr(self._rdd, "storageLevel", StorageLevel(False, False, False, False)) def is_cached(self): return hasattr(self._rdd, "storageLevel") def simple_repartition(self, numPartitions): return self._with_rdd(self._rdd.repartition(numPartitions), self.bound_schema) def repartitionByValues(self, numPartitions, partitioner=None): return self._with_rdd( self._rdd.map(lambda x: (x, x)).partitionBy(numPartitions, partitioner).values(), self.bound_schema ) def repartition(self, numPartitions, cols): def partitioner(row): return sum(hash(c.eval(row, self.bound_schema)) for c in cols) return self.repartitionByValues(numPartitions, partitioner) def repartitionByRange(self, numPartitions, *cols): key = get_keyfunc(cols, self.bound_schema) bounds = self._get_range_bounds(self._rdd, numPartitions, key=key) def get_range_id(value): return sum(1 for bound in bounds if key(bound) < key(value)) return self.repartitionByValues(numPartitions, partitioner=get_range_id) @staticmethod def _get_range_bounds(rdd, numPartitions, key): if numPartitions == 0: return [] # pylint: disable=W0511 # todo: check if sample_size is set in SQLConf.get.rangeExchangeSampleSizePerPartition # sample_size = min( # SQLConf.get.rangeExchangeSampleSizePerPartition * rdd.getNumPartitions(), # 1e6 # ) sample_size = 1e6 sample_size_per_partition = math.ceil(3 * sample_size / numPartitions) sketched_rdd = DataFrameInternal.sketch_rdd(rdd, sample_size_per_partition) rdd_size = sum(partition_size for partition_size, sample in sketched_rdd.values()) if rdd_size == 0: return [] fraction = sample_size / rdd_size candidates, imbalanced_partitions = DataFrameInternal._get_initial_candidates( sketched_rdd, sample_size_per_partition, fraction ) additional_candidates = DataFrameInternal._get_additional_candidates( rdd, imbalanced_partitions, fraction ) candidates += additional_candidates bounds = compute_weighted_percentiles( candidates, min(numPartitions, len(candidates)) + 1, key=key )[1:-1] return bounds @staticmethod def _get_initial_candidates(sketched_rdd, sample_size_per_partition, fraction): candidates = [] imbalanced_partitions = set() for idx, (partition_size, sample) in sketched_rdd.items(): # Partition is bigger than (3 times) average and more than sample_size_per_partition # is needed to get accurate information on its distribution if fraction * partition_size > sample_size_per_partition: imbalanced_partitions.add(idx) else: # The weight is 1 over the sampling probability. weight = partition_size / len(sample) candidates += [(key, weight) for key in sample] return candidates, imbalanced_partitions @staticmethod def _get_additional_candidates(rdd, imbalanced_partitions, fraction): additional_candidates = [] if imbalanced_partitions: # Re-sample imbalanced partitions with the desired sampling probability. def keep_imbalanced_partitions(partition_id, x): return x if partition_id in imbalanced_partitions else [] resampled = (rdd.mapPartitionsWithIndex(keep_imbalanced_partitions) .sample(withReplacement=False, fraction=fraction, seed=rdd.id()) .collect()) weight = (1.0 / fraction).toFloat additional_candidates += [(x, weight) for x in resampled] return additional_candidates @staticmethod def sketch_rdd(rdd, sample_size_per_partition): """ Get a subset per partition of an RDD Sampling algorithm is reservoir sampling. :param rdd: :param sample_size_per_partition: :return: """ def sketch_partition(idx, x): sample, original_size = reservoir_sample_and_size( x, sample_size_per_partition, seed=rdd.id() + idx ) return [(idx, (original_size, sample))] sketched_rdd_content = rdd.mapPartitionsWithIndex(sketch_partition).collect() return dict(sketched_rdd_content) def sampleBy(self, col, fractions, seed): fractions_as_col = map_from_arrays( array(*(map(lit, fractions.keys()))), array(*map(lit, fractions.values())) ) return self._with_rdd( self.filter(rand(seed) < fractions_as_col[col]), self.bound_schema ) def toJSON(self, use_unicode): """ :rtype: RDD """ return self._rdd.map(lambda row: json.dumps(row.asDict(True), ensure_ascii=not use_unicode)) def sortWithinPartitions(self, cols, ascending): key = get_keyfunc([parse(c) for c in cols], self.bound_schema) def partition_sort(data): return sorted(data, key=key, reverse=not ascending) return self._with_rdd( self._rdd.mapPartitions(partition_sort), self.bound_schema ) def sort(self, cols): # Pysparkling implementation of RDD.sortBy is an in-order sort, # calling it multiple times allow sorting # based on multiple criteria and ascending orders # pylint: disable=W0511 # Todo: this could be optimized as it's possible to sort # together columns that are in the same ascending order sorted_rdd = self._rdd for col in cols[::-1]: ascending = col.sort_order in ["ASC NULLS FIRST", "ASC NULLS LAST"] nulls_are_smaller = col.sort_order in ["DESC NULLS LAST", "ASC NULLS FIRST"] key = get_keyfunc([col], self.bound_schema, nulls_are_smaller=nulls_are_smaller) sorted_rdd = sorted_rdd.sortBy(key, ascending=ascending) return self._with_rdd(sorted_rdd, self.bound_schema) def select(self, *exprs): cols = [parse(e) for e in exprs] if any(col.is_an_aggregation for col in cols): df_as_group = InternalGroupedDataFrame(self, []) return df_as_group.agg(exprs) def select_mapper(partition_index, partition): # Initialize non deterministic functions so that they are reproducible initialized_cols = [col.initialize(partition_index) for col in cols] generators = [col for col in initialized_cols if col.may_output_multiple_rows] non_generators = [col for col in initialized_cols if not col.may_output_multiple_rows] number_of_generators = len(generators) if number_of_generators > 1: raise Exception( "Only one generator allowed per select clause" f" but found {number_of_generators}: {', '.join(generators)}" ) return self.get_select_output_field_lists( partition, non_generators, initialized_cols, generators[0] if generators else None ) new_schema = get_schema_from_cols(cols, self.bound_schema) return self._with_rdd( self._rdd.mapPartitionsWithIndex(select_mapper), schema=new_schema ) def get_select_output_field_lists(self, partition, non_generators, initialized_cols, generator): output_rows = [] for row in partition: base_row_fields = [] for col in non_generators: output_cols, output_values = resolve_column(col, row, schema=self.bound_schema) base_row_fields += zip(output_cols, output_values[0]) if generator is not None: generated_row_fields = self.get_generated_row_fields( generator, row, initialized_cols, base_row_fields ) for generated_row in generated_row_fields: output_rows.append( row_from_keyed_values(generated_row, metadata=row.get_metadata()) ) else: output_rows.append( row_from_keyed_values(base_row_fields, metadata=row.get_metadata()) ) return output_rows def get_generated_row_fields(self, generator, row, initialized_cols, base_row): additional_fields = [] generator_position = initialized_cols.index(generator) generated_cols, generated_sub_rows = resolve_column( generator, row, schema=self.bound_schema ) for generated_sub_row in generated_sub_rows: sub_row = list(zip(generated_cols, generated_sub_row)) additional_fields.append( base_row[:generator_position] + sub_row + base_row[generator_position:] ) return additional_fields def selectExpr(self, *cols): raise NotImplementedError("Pysparkling does not currently support DF.selectExpr") def filter(self, condition): condition = parse(condition) def mapper(partition_index, partition): initialized_condition = condition.initialize(partition_index) return (row for row in partition if initialized_condition.eval(row, self.bound_schema)) return self._with_rdd( self._rdd.mapPartitionsWithIndex(mapper), self.bound_schema ) def union(self, other): self_field_names = [field.name for field in self.bound_schema.fields] other_field_names = [field.name for field in other.bound_schema.fields] if len(self_field_names) != len(other_field_names): raise Exception( "Union can only be performed on tables with the same number " f"of columns, but the first table has {len(self_field_names)} columns and the " f"second table has {len(other_field_names)} columns" ) def change_col_names(row): return row_from_keyed_values([ (field.name, value) for field, value in zip(self.bound_schema.fields, row) ]) # This behavior (keeping the columns of self) is the same as in PySpark return self._with_rdd( self._rdd.union(other.rdd().map(change_col_names)), self.bound_schema ) def unionByName(self, other): self_field_names = [field.name for field in self.bound_schema.fields] other_field_names = [field.name for field in other.bound_schema.fields] if len(self_field_names) != len(set(self_field_names)): duplicate_names = [name for name, cnt in Counter(self_field_names).items() if cnt > 1] raise Exception( f"Found duplicate column(s) in the left attributes: {duplicate_names}" ) if len(other_field_names) != len(set(other_field_names)): duplicate_names = [name for name, cnt in Counter(other_field_names).items() if cnt > 1] raise Exception( f"Found duplicate column(s) in the right attributes: {duplicate_names}" ) if len(self_field_names) != len(other_field_names): raise Exception( "Union can only be performed on tables with the same number " f"of columns, but the first table has {len(self_field_names)} columns and the " f"second table has {len(other_field_names)} columns" ) def change_col_order(row): return row_from_keyed_values([ (field.name, row[field.name]) for field in self.bound_schema.fields ]) # This behavior (keeping the columns of self) is the same as in PySpark return self._with_rdd( self._rdd.union(other.rdd().map(change_col_order)), self.bound_schema ) def withColumn(self, colName, col): return self.select(parse("*"), parse(col).alias(colName)) def withColumnRenamed(self, existing, new): def mapper(row): keyed_values = [ (new, row[col]) if col == existing else (col, row[col]) for col in row.__fields__ ] return row_from_keyed_values(keyed_values) new_schema = StructType([ field if field.name != existing else StructField( new, field.dataType, field.nullable ) for field in self.bound_schema.fields ]) return self._with_rdd(self._rdd.map(mapper), schema=new_schema) def toDF(self, new_names): def mapper(row): keyed_values = [ (new_name, row[old]) for new_name, old in zip(new_names, row.__fields__) ] return row_from_keyed_values(keyed_values) new_schema = StructType([ StructField( new_name, field.dataType, field.nullable ) for new_name, field in zip(new_names, self.bound_schema.fields) ]) return self._with_rdd(self._rdd.map(mapper), schema=new_schema) def describe(self, cols): stat_helper = self.get_stat_helper(cols) exprs = [parse(col) for col in cols] return DataFrameInternal( self._sc, self._sc.parallelize(stat_helper.get_as_rows()), schema=self.get_summary_schema(exprs) ) def summary(self, statistics): stat_helper = self.get_stat_helper(["*"]) if not statistics: statistics = ("count", "mean", "stddev", "min", "25%", "50%", "75%", "max") return DataFrameInternal( self._sc, self._sc.parallelize(stat_helper.get_as_rows(statistics)), schema=self.get_summary_schema([parse("*")]) ) def get_summary_schema(self, exprs): return StructType( [ StructField("summary", StringType(), True) ] + [ StructField(field.name, StringType(), True) for field in get_schema_from_cols(exprs, self.bound_schema).fields ] ) def get_stat_helper(self, exprs, percentiles_relative_error=1 / 10000): """ :rtype: RowStatHelper """ return self.aggregate( RowStatHelper(exprs, percentiles_relative_error), lambda counter, row: counter.merge(row, self.bound_schema), lambda counter1, counter2: counter1.mergeStats(counter2) ) def aggregate(self, zeroValue, seqOp, combOp): return self._rdd.aggregate(zeroValue, seqOp, combOp) def showString(self, n, truncate=20, vertical=False): n = max(0, n) if n: sample = self.take(n + 1) rows = sample[:n] contains_more = len(sample) == n + 1 else: rows = self.collect() contains_more = False min_col_width = 3 cols = [field.name for field in self.bound_schema.fields] if not vertical: output = self.horizontal_show(rows, cols, truncate, min_col_width) else: output = self.vertical_show(rows, min_col_width) if not rows[1:] and vertical: output += "(0 rows)\n" elif contains_more: output += f"only showing top {n} row{'s' if len(rows) > 1 else ''}\n" # Last \n will be added by print() return output[:-1] def vertical_show(self, rows, min_col_width): output = "" field_names = [field.name for field in self.bound_schema.fields] field_names_col_width = max( min_col_width, *(str_half_width(field_name) for field_name in field_names) ) data_col_width = max( min_col_width, *(str_half_width(cell) for data_row in rows for cell in data_row) ) for i, row in enumerate(rows): row_header = f"-RECORD {i}".ljust( field_names_col_width + data_col_width + 5, "-" ) output += row_header + "\n" for field_name, cell in zip(field_names, row): formatted_field_name = field_name.ljust( field_names_col_width - str_half_width(field_name) + len(field_name) ) data = format_cell(cell).ljust(data_col_width - str_half_width(cell)) output += f" {formatted_field_name} | {data} \n" return output @staticmethod def horizontal_show(rows, cols, truncate, min_col_width): output = "" col_widths = [max(min_col_width, str_half_width(col)) for col in cols] for row in rows: col_widths = [ max(cur_width, str_half_width(cell)) for cur_width, cell in zip(col_widths, row) ] padded_header = (pad_cell(col, truncate, col_width) for col, col_width in zip(cols, col_widths)) padded_rows = ( [pad_cell(cell, truncate, col_width) for cell, col_width in zip(row, col_widths)] for row in rows ) sep = _generate_show_layout('+', ('-' * col_width for col_width in col_widths)) output += sep output += _generate_show_layout('|', padded_header) output += sep output += '\n'.join(_generate_show_layout('|', row) for row in padded_rows) output += sep return output def approxQuantile(self, exprs, quantiles, relative_error): stat_helper = self.get_stat_helper(exprs, percentiles_relative_error=relative_error) return [ [ stat_helper.get_col_quantile(col, quantile) for quantile in quantiles ] for col in stat_helper.col_names ] def corr(self, col1, col2, method): covariance_helper = self._get_covariance_helper(method, col1, col2) return covariance_helper.pearson_correlation def cov(self, col1, col2): covariance_helper = self._get_covariance_helper("pearson", col1, col2) return covariance_helper.covar_samp def _get_covariance_helper(self, method, col1, col2): """ :rtype: CovarianceCounter """ covariance_helper = self._rdd.treeAggregate( CovarianceCounter(method), seqOp=lambda counter, row: counter.add(row[col1], row[col2]), combOp=lambda baseCounter, other: baseCounter.merge(other) ) return covariance_helper def crosstab(self, df, col1, col2): table_name = "_".join((col1, col2)) counts = df.groupBy(col1, col2).agg(count("*")).take(1e6) if len(counts) == 1e6: warnings.warn("The maximum limit of 1e6 pairs have been collected, " "which may not be all of the pairs. Please try reducing " "the amount of distinct items in your columns.") def clean_element(element): return str(element) if element is not None else "null" distinct_col2 = (counts .map(lambda row: clean_element(row[col2])) .distinct() .sorted() .zipWithIndex() .toMap()) column_size = len(distinct_col2) if column_size < 10_000: raise ValueError( f"The number of distinct values for {col2} can't exceed 10_000." f" Currently {column_size}" ) def create_counts_row(col1Item, rows): counts_row = [None] * (column_size + 1) def parse_row(row): column_index = distinct_col2[clean_element(row[1])] counts_row[int(column_index + 1)] = int(row[2]) rows.foreach(parse_row) # the value of col1 is the first value, the rest are the counts counts_row[0] = clean_element(col1Item) return Row(counts_row) table = counts.groupBy(lambda r: r[col1]).map(create_counts_row).toSeq # Back ticks can't exist in DataFrame column names, # therefore drop them. To be able to accept special keywords and `.`, # wrap the column names in ``. def clean_column_name(name): return name.replace("`", "") # In the map, the column names (._1) are not ordered by the index (._2). # We need to explicitly sort by the column index and assign the column names. header_names = distinct_col2.toSeq.sortBy(lambda r: r[2]).map(lambda r: StructField( clean_column_name(str(r[1])), LongType )) schema = StructType([StructField(table_name, StringType)] + header_names) return schema, table def join(self, other, on, how): if on is None and how == "cross": merged_schema = merge_schemas(self.bound_schema, other.bound_schema, how) output_rdd = self.cross_join(other) elif isinstance(on, list) and all(isinstance(col, str) for col in on): merged_schema = merge_schemas( self.bound_schema, other.bound_schema, how, on=on ) output_rdd = self.join_on_values(other, on, how) elif not isinstance(on, list): merged_schema = merge_schemas(self.bound_schema, other.bound_schema, how) output_rdd = self.join_on_condition(other, on, how, merged_schema) else: raise NotImplementedError( "Pysparkling only supports str, Column and list of str for on" ) return self._with_rdd(output_rdd, schema=merged_schema) def join_on_condition(self, other, on, how, new_schema): """ :type other: DataFrameInternal """ def condition(couple): left, right = couple merged_rows = merge_rows(left, right) condition_value = on.eval(merged_rows, schema=new_schema) return condition_value joined_rdd = self.rdd().cartesian(other.rdd()).filter(condition) def format_output(entry): left, right = entry return merge_rows(left, right) # , self.bound_schema, other.bound_schema, how) output_rdd = joined_rdd.map(format_output) return output_rdd def cross_join(self, other): """ :type other: DataFrameInternal """ joined_rdd = self.rdd().cartesian(other.rdd()) def format_output(entry): left, right = entry return merge_rows(left, right) # , self.bound_schema, other.bound_schema, how) output_rdd = joined_rdd.map(format_output) return output_rdd def join_on_values(self, other, on, how): if how != CROSS_JOIN: def add_key(row): # When joining on value, no check on schema (and lack of duplicated col) is done return tuple(row[on_column] for on_column in on), row else: def add_key(row): return True, row keyed_self = self.rdd().map(add_key) keyed_other = other.rdd().map(add_key) if how == LEFT_JOIN: joined_rdd = keyed_self.leftOuterJoin(keyed_other) elif how == RIGHT_JOIN: joined_rdd = keyed_self.rightOuterJoin(keyed_other) elif how == FULL_JOIN: joined_rdd = keyed_self.fullOuterJoin(keyed_other) elif how in (INNER_JOIN, CROSS_JOIN): joined_rdd = keyed_self.join(keyed_other) elif how == LEFT_ANTI_JOIN: joined_rdd = keyed_self._leftAntiJoin(keyed_other) elif how == LEFT_SEMI_JOIN: joined_rdd = keyed_self._leftSemiJoin(keyed_other) else: raise IllegalArgumentException(f"Invalid how argument in join: {how}") def format_output(entry): _, (left, right) = entry return merge_rows_joined_on_values( left, right, self.bound_schema, other.bound_schema, how, on ) output_rdd = joined_rdd.map(format_output) return output_rdd def crossJoin(self, other): return self.join(other, on=None, how="cross") def exceptAll(self, other): def except_all_within_partition(self_partition, other_partition): min_other = next(other_partition, None) for item in self_partition: if min_other is None or min_other > item: yield item elif min_other < item: while min_other < item or min_other is None: min_other = next(other_partition, None) else: min_other = next(other_partition, None) return self.applyFunctionOnHashPartitionedRdds(other, except_all_within_partition) def intersectAll(self, other): def intersect_all_within_partition(self_partition, other_partition): min_other = next(other_partition, None) for item in self_partition: if min_other is None: return if min_other > item: continue if min_other < item: while min_other < item or min_other is None: min_other = next(other_partition, None) else: yield item min_other = next(other_partition, None) return self.applyFunctionOnHashPartitionedRdds(other, intersect_all_within_partition) def intersect(self, other): def intersect_within_partition(self_partition, other_partition): min_other = next(other_partition, None) for item in self_partition: if min_other is None: return if min_other > item: continue if min_other < item: while min_other < item or min_other is None: min_other = next(other_partition, None) else: yield item while min_other == item: min_other = next(other_partition, None) return self.applyFunctionOnHashPartitionedRdds(other, intersect_within_partition) def dropDuplicates(self, cols): key_column = (struct(*cols) if cols else struct("*")).alias("key") value_column = struct("*").alias("value") self_prepared_rdd = self.select(key_column, value_column).rdd() def drop_duplicate_within_partition(self_partition): def unique_generator(): seen = set() for key, value in self_partition: if key not in seen: seen.add(key) yield value return unique_generator() unique_rdd = (self_prepared_rdd.partitionBy(200) .mapPartitions(drop_duplicate_within_partition)) return self._with_rdd(unique_rdd, self.bound_schema) def applyFunctionOnHashPartitionedRdds(self, other, func): self_prepared_rdd, other_prepared_rdd = self.hash_partition_and_sort(other) def filter_partition(partition_id, self_partition): other_partition = other_prepared_rdd.partitions()[partition_id].x() return func(iter(self_partition), iter(other_partition)) filtered_rdd = self_prepared_rdd.mapPartitionsWithIndex(filter_partition) return self._with_rdd(filtered_rdd, self.bound_schema) def hash_partition_and_sort(self, other): num_partitions = max(self.rdd().getNumPartitions(), 200) def prepare_rdd(rdd): return rdd.partitionBy(num_partitions, portable_hash).mapPartitions(sorted) self_prepared_rdd = prepare_rdd(self.rdd()) other_prepared_rdd = prepare_rdd(other.rdd()) return self_prepared_rdd, other_prepared_rdd def drop(self, cols): positions_to_drop = [] for col in cols: if isinstance(col, str): if col == "*": continue col = parse(col) try: positions_to_drop.append(col.find_position_in_schema(self.bound_schema)) except ValueError: pass new_schema = StructType([ field for i, field in enumerate(self.bound_schema.fields) if i not in positions_to_drop ]) return self._with_rdd( self.rdd().map(lambda row: row_from_keyed_values([ (field, row[i]) for i, field in enumerate(row.__fields__) if i not in positions_to_drop ])), new_schema ) def freqItems(self, cols, support): raise NotImplementedError("pysparkling does not support yet freqItems") def dropna(self, thresh, subset): raise NotImplementedError("pysparkling does not support yet dropna") def fillna(self, value, subset): raise NotImplementedError("pysparkling does not support yet fillna") def replace(self, to_replace, value, subset=None): raise NotImplementedError("pysparkling does not support yet replace") GROUP_BY_TYPE = "GROUP_BY_TYPE" ROLLUP_TYPE = "ROLLUP_TYPE" CUBE_TYPE = "CUBE_TYPE" class SubTotalValue: """ Some grouping type (rollup and cube) compute subtotals on all statistics, This class once instantiated creates a unique value that identify such subtotals """ def __repr__(self): return "SubTotal" GROUPED = SubTotalValue() class InternalGroupedDataFrame: def __init__(self, jdf, grouping_cols, group_type=GROUP_BY_TYPE, pivot_col=None, pivot_values=None): self.jdf = jdf self.grouping_cols = grouping_cols self.group_type = group_type self.pivot_col = pivot_col self.pivot_values = pivot_values def agg(self, stats): grouping_schema = StructType([ field for col in self.grouping_cols for field in col.find_fields_in_schema(self.jdf.bound_schema) ]) aggregated_stats = self.jdf.aggregate( GroupedStats(self.grouping_cols, stats, pivot_col=self.pivot_col, pivot_values=self.pivot_values), lambda grouped_stats, row: grouped_stats.merge( row, self.jdf.bound_schema ), lambda grouped_stats_1, grouped_stats_2: grouped_stats_1.mergeStats( grouped_stats_2, self.jdf.bound_schema ) ) data = [] all_stats = self.add_subtotals(aggregated_stats) for group_key in all_stats.group_keys: key = [(str(key), None if value is GROUPED else value) for key, value in zip(self.grouping_cols, group_key)] grouping = tuple(value is GROUPED for value in group_key) key_as_row = row_from_keyed_values(key).set_grouping(grouping) data.append(row_from_keyed_values( key + [ (str(stat), stat.with_pre_evaluation_schema(self.jdf.bound_schema).eval( key_as_row, grouping_schema) ) for pivot_value in all_stats.pivot_values for stat in get_pivoted_stats( all_stats.groups[group_key][pivot_value], pivot_value ) ] )) if self.pivot_col is not None: if len(stats) == 1: new_schema = StructType( grouping_schema.fields + [ StructField( str(pivot_value), DataType(), True ) for pivot_value in self.pivot_values ] ) else: new_schema = StructType( grouping_schema.fields + [ StructField( f"{pivot_value}_{stat}", DataType(), True ) for pivot_value in self.pivot_values for stat in stats ] ) else: new_schema = StructType( grouping_schema.fields + [ StructField( str(stat), DataType(), True ) for stat in stats ] ) # noinspection PyProtectedMember return self.jdf._with_rdd(self.jdf._sc.parallelize(data), schema=new_schema) def add_subtotals(self, aggregated_stats): """ :type aggregated_stats: GroupedStats """ if self.group_type == GROUP_BY_TYPE: return aggregated_stats grouping_cols = aggregated_stats.grouping_cols nb_cols = len(grouping_cols) all_stats = {} for group_key, group_stats in aggregated_stats.groups.items(): for subtotal_key in self.get_subtotal_keys(group_key, nb_cols): if subtotal_key not in all_stats: all_stats[subtotal_key] = deepcopy(group_stats) else: for pivot_value, pivot_stats in group_stats.items(): for subtotal_stat, group_stat in zip( all_stats[subtotal_key][pivot_value], pivot_stats ): subtotal_stat.mergeStats( group_stat, self.jdf.bound_schema ) return GroupedStats( grouping_cols=grouping_cols, stats=aggregated_stats.stats, pivot_col=self.pivot_col, pivot_values=self.pivot_values, groups=all_stats ) def get_subtotal_keys(self, group_key, nb_cols): """ Returns a list of tuple Each tuple contains: - a subtotal key as a string - a list of boolean corresponding to which groupings where performed """ if self.group_type == GROUP_BY_TYPE: return [group_key] if self.group_type == ROLLUP_TYPE: return [ tuple(itertools.chain(group_key[:i], [GROUPED] * (nb_cols - i))) for i in range(nb_cols + 1) ] if self.group_type == CUBE_TYPE: result = [ tuple( GROUPED if grouping else sub_key for grouping, sub_key in zip(groupings, group_key) ) for groupings in list(itertools.product([True, False], repeat=nb_cols)) ] return result raise NotImplementedError(f"Unknown grouping type: {self.group_type}") def pivot(self, pivot_col, pivot_values): if pivot_values is None: pivot_values = sorted( self.jdf.select(collect_set(pivot_col)).collect()[0][0] ) return InternalGroupedDataFrame( jdf=self.jdf, grouping_cols=self.grouping_cols, group_type=self.group_type, pivot_col=pivot_col, pivot_values=pivot_values ) class GroupedStats: def __init__(self, grouping_cols, stats, pivot_col, pivot_values, groups=None): self.grouping_cols = grouping_cols self.stats = stats self.pivot_col = pivot_col self.pivot_values = pivot_values if pivot_values is not None else [None] if groups is None: self.groups = {} # As python < 3.6 does not guarantee dict ordering # we need to keep track of in which order the columns were self.group_keys = [] else: self.groups = groups # The order is not used when initialized directly self.group_keys = list(groups.keys()) def merge(self, row, schema): group_key = tuple(col.eval(row, schema) for col in self.grouping_cols) if group_key not in self.groups: group_stats = { pivot_value: [deepcopy(stat) for stat in self.stats] for pivot_value in self.pivot_values } self.groups[group_key] = group_stats self.group_keys.append(group_key) else: group_stats = self.groups[group_key] pivot_value = self.pivot_col.eval(row, schema) if self.pivot_col is not None else None if pivot_value in self.pivot_values: for stat in group_stats[pivot_value]: stat.merge(row, schema) return self def mergeStats(self, other, schema): for group_key in other.group_keys: if group_key not in self.group_keys: self.groups[group_key] = other.groups[group_key] self.group_keys.append(group_key) else: group_stats = self.groups[group_key] other_stats = other.groups[group_key] for pivot_value in self.pivot_values: for (stat, other_stat) in zip( group_stats[pivot_value], other_stats[pivot_value] ): stat.mergeStats(other_stat, schema) return self def get_pivoted_stats(stats, pivot_value): if pivot_value is None: return stats if len(stats) == 1: return [stats[0].alias(pivot_value)] return [stat.alias(f"{pivot_value}_{stat}") for stat in stats]
36.815
114
0.593463
828f78e48c841ad35fe522645564e6217585c821
840
py
Python
September 2020/01-Lists-as-Stacks-and-Queues-Lab/Exercises/10-Cups-and-Bottles.py
eclipse-ib/Software-University-Professional-Advanced-Module
636385f9e5521840f680644824d725d074b93c9a
[ "MIT" ]
null
null
null
September 2020/01-Lists-as-Stacks-and-Queues-Lab/Exercises/10-Cups-and-Bottles.py
eclipse-ib/Software-University-Professional-Advanced-Module
636385f9e5521840f680644824d725d074b93c9a
[ "MIT" ]
null
null
null
September 2020/01-Lists-as-Stacks-and-Queues-Lab/Exercises/10-Cups-and-Bottles.py
eclipse-ib/Software-University-Professional-Advanced-Module
636385f9e5521840f680644824d725d074b93c9a
[ "MIT" ]
null
null
null
from collections import deque cups = deque(int(_) for _ in input().split()) bottles = deque(int(_) for _ in input().split()) wasted_water = 0 while True: if len(cups) == 0: print(f"Bottles: {' '.join(str(_) for _ in bottles)}") break if len(bottles) == 0: print(f"Cups: {' '.join(str(_) for _ in cups)}") break current_cup = cups[0] current_bottle = bottles[-1] if current_bottle > current_cup: wasted_water += (current_bottle - current_cup) cups.popleft() bottles.pop() elif current_bottle < current_cup: current_cup -= current_bottle cups[0] = current_cup bottles.pop() continue elif current_bottle == current_cup: cups.popleft() bottles.pop() print(f"Wasted litters of water: {wasted_water}")
21.538462
62
0.59881
849b21e7e41bfa6c098bde06ff97045b258737ef
1,702
py
Python
src-py/Lexer.py
Stepfen-Shawn/rickroll-lang
9ea254a65d27b360b488f85c1b00bd3312af37fe
[ "MIT" ]
700
2021-05-26T18:17:59.000Z
2022-03-31T18:31:12.000Z
src-py/Lexer.py
Stepfen-Shawn/rickroll-lang
9ea254a65d27b360b488f85c1b00bd3312af37fe
[ "MIT" ]
28
2021-06-04T04:08:05.000Z
2022-03-14T20:03:44.000Z
src-py/Lexer.py
Stepfen-Shawn/rickroll-lang
9ea254a65d27b360b488f85c1b00bd3312af37fe
[ "MIT" ]
35
2021-06-03T22:43:29.000Z
2022-03-19T17:02:38.000Z
from PublicVariables import * all_keyword_string = '' for i in keywords: all_keyword_string += i class Lexer: def __init__(self, stmt): self.tokens = [] self.__order_tokens(tokens=self.__basic_tokenize(stmt)) def __basic_tokenize(self, stmt): current_token = '' quote_count = 0 tokens = [] for char in stmt: if char == '"': quote_count += 1 if char == '#': break if char in ignore_tokens and quote_count % 2 == 0: continue if char in separators and quote_count % 2 == 0: if current_token != ' ' and current_token != '\n': tokens.append(current_token) if char != ' ' and char != '\n': tokens.append(char) current_token = '' else: current_token += char return tokens def __order_tokens(self, tokens): """ 如果当前token+kw_in_statement在all keyword string里,kw_in_statement += token 如果当前token+kw_in_statement不在在all keyword string里,将当前kw_in_statement加到final_token里 如果statement结束,将kw_in_statement加到final_token里 """ kw_in_statement = '' temp = False for tok in tokens: if tok in all_keyword_string and kw_in_statement + tok in all_keyword_string: kw_in_statement += tok else: temp = True self.tokens.append(kw_in_statement) kw_in_statement = '' self.tokens.append(tok) if temp == False: self.tokens.append(kw_in_statement)
30.392857
90
0.542891
0c6d6aaa7cf7df1c1e71bf1d77ac4479afa0a7cb
2,596
py
Python
src/build_tools/run_after_chdir.py
hiroyuki-komatsu/mozc
e92f3a2215b95eead9f85b7c0599775d810dcafa
[ "BSD-3-Clause" ]
1,144
2015-04-23T16:18:45.000Z
2022-03-29T19:37:33.000Z
src/build_tools/run_after_chdir.py
kirameister/mozc
18b2b32b4d3fe585d38134606773239781b6be82
[ "BSD-3-Clause" ]
291
2015-05-04T07:53:37.000Z
2022-03-22T00:09:05.000Z
src/build_tools/run_after_chdir.py
kirameister/mozc
18b2b32b4d3fe585d38134606773239781b6be82
[ "BSD-3-Clause" ]
301
2015-05-03T00:07:18.000Z
2022-03-21T10:48:29.000Z
# -*- coding: utf-8 -*- # Copyright 2010-2021, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Script to run an arbitrary program after changing the current directory. % python run_after_chdir.py / ls auto emul home lib media proc srv var ... The example above is to run ls command in / directory. """ from __future__ import absolute_import from __future__ import print_function import os import subprocess import sys def main(): """The main function.""" # Delete the self program name (i.e. run_after_chdir.py). sys.argv.pop(0) # The first parameter is the destination directory. destination_directory_name = sys.argv.pop(0) os.chdir(destination_directory_name) # Rest are the target program name and the parameters, but we special # case if the target program name ends with '.py' if sys.argv[0].endswith('.py'): sys.argv.insert(0, sys.executable) # Inject the python interpreter path. # We don't capture stdout and stderr from Popen. The output will just # be emitted to a terminal or console. print(sys.argv) sys.exit(subprocess.call(sys.argv)) if __name__ == '__main__': main()
39.333333
77
0.759245
64e23ffbd4551270810e76fe08cebe37384fbf2f
3,489
py
Python
color_detector.py
gtstrullo99/Inventory-Classifier-for-Genshin-Impact
a6506f3e144e04fcb2839ca310db2875c2b99138
[ "MIT" ]
null
null
null
color_detector.py
gtstrullo99/Inventory-Classifier-for-Genshin-Impact
a6506f3e144e04fcb2839ca310db2875c2b99138
[ "MIT" ]
null
null
null
color_detector.py
gtstrullo99/Inventory-Classifier-for-Genshin-Impact
a6506f3e144e04fcb2839ca310db2875c2b99138
[ "MIT" ]
null
null
null
import cv2 import os import numpy as np import matplotlib.pyplot as plt ''' Librerías necesarias: · cv2: pip install opencv-python · matplotlib: pip install matplotlib · numpy: pip install numpy · os: para recuperar nombres de archivos ''' ''' Hará una detección de color para identificar: - Naranja: legendario (0) - Morado: épico (1) - Azul: raro (2) - Verde: poco común (3) - Gris: común (4) El color que sea más prometedor, será el resultado que devolverá Input: - image: array de valores en 3D que representará la imagen Output: - rarity: 1 de las 5 clases a las que será más probable que pertenezca ''' def colorDetection(image): # Se inicializa la rareza inicial del item y el contador de coincidencia máxima rarity = -1 maxCount = -1 # Creamos la array de rarezas rarityArray = ['legendary', 'epic', 'rare', 'uncommon', 'common'] # Transformamos la imagen a HSV, ya que así trabaja mejor cv2 imHSV = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) # Se establecen los diferentes lowers y upper limits según la rareza de los objetos: # Legendary = Naranja, Epic = Morado, Rare = Azul, Uncommon = Verde, Common = Gris rarityLower = [ [100, 210, 140], [120, 110, 110], [0, 65, 130], [40, 40, 120], [114, 60, 100] ] rarityUpper = [ [115, 255, 255], [140, 180, 250], [20, 130, 180], [90, 130, 190], [130, 110, 170] ] #plt.figure(figsize=(10, 8)) #plt.imshow(imHSV) for lower, upper, index in zip (rarityLower, rarityUpper, rarityArray): lowerLimit = np.array(lower) upperLimit = np.array(upper) # Se crea una máscara para ver las zonas que ha elegido el algoritmo con los límites maskHSV = cv2.inRange(imHSV, lowerLimit, upperLimit) #plt.figure(figsize=(10, 8)) #plt.imshow(maskHSV) # Se discrimina lo que no haya elegido la máscara res = cv2.bitwise_and(imHSV, imHSV, mask=maskHSV) #plt.figure(figsize=(10, 8)) #plt.imshow(res) counter = cv2.countNonZero(res[:, :, 0]) if counter > maxCount: maxCount = counter rarity = index #plt.close('all') return rarity ''' La función main debería recibir una o varias imágenes de una pantalla de un PC hecha con el móvil (movimiento, desenfoque, diferentes ángulos...) con el inventario de mejora del juego Genshin Impact y el programa debería ser capaz de clasificar los items por nombre, rareza y cantidad. Luego, esta información sería impresa en un archivo .txt en el orden que se encontraba en la imagen para poder subirla más rápidamente a una web que analiza los items para optimizar una ruta de min-maxing de recursos. Dicha web precisa que se copien todos los datos del inventario a mano, por lo que es un trabajo bastante laborioso. https://seelie.inmagi.com/inventory ''' def main(): # Se declara el path del train pathTrain = 'train' # Recibe el set de fotos (cada imagen es una celda con 1 solo item) y las clasifica individualmente según # varios criterios trainList = os.listdir(pathTrain) for item in trainList: curIm = cv2.imread(f'{pathTrain}/{item}') rarity = colorDetection(curIm) if __name__ == '__main__': main()
35.602041
116
0.630553
498cc6288de2c2d45a1de9479f5978d02a5b6184
2,136
py
Python
setup.py
mh-globus/globus-sdk-python
c740ebd85640d5c5fe92fd22e99ec05b1a280f6d
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
setup.py
mh-globus/globus-sdk-python
c740ebd85640d5c5fe92fd22e99ec05b1a280f6d
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
setup.py
mh-globus/globus-sdk-python
c740ebd85640d5c5fe92fd22e99ec05b1a280f6d
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
import os.path import re from setuptools import find_packages, setup MYPY_REQUIREMENTS = [ "mypy==0.902", "types-docutils", "types-jwt", "types-requests", ] LINT_REQUIREMENTS = [ "flake8<4", "isort<6", "black==21.6b0", "flake8-bugbear==21.4.3", ] + MYPY_REQUIREMENTS TEST_REQUIREMENTS = [ "pytest<7", "pytest-cov<3", "pytest-xdist<3", "responses==0.13.3", ] DOC_REQUIREMENTS = [ "sphinx<5", "sphinx-issues<2", "furo==2021.06.18b36", ] DEV_REQUIREMENTS = TEST_REQUIREMENTS + LINT_REQUIREMENTS + DOC_REQUIREMENTS def parse_version(): # single source of truth for package version version_string = "" version_pattern = re.compile(r'__version__ = "([^"]*)"') with open(os.path.join("src", "globus_sdk", "version.py")) as f: for line in f: match = version_pattern.match(line) if match: version_string = match.group(1) break if not version_string: raise RuntimeError("Failed to parse version information") return version_string def read_readme(): with open("README.rst") as fp: return fp.read() setup( name="globus-sdk", version=parse_version(), description="Globus SDK for Python", long_description=read_readme(), author="Globus Team", author_email="support@globus.org", url="https://github.com/globus/globus-sdk-python", packages=find_packages("src"), package_dir={"": "src"}, package_data={"globus_sdk": ["py.typed"]}, python_requires=">=3.6", install_requires=["requests>=2.9.2,<3.0.0", "pyjwt[crypto]>=2.0.0,<3.0.0"], extras_require={"dev": DEV_REQUIREMENTS}, keywords=["globus"], classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", ], )
27.384615
79
0.617509
7856451c409c33513349c4e94dcd4d22b59b4b47
3,069
py
Python
redmail/test/email/test_template.py
kimvanwyk/red-mail
78dc763e5b5f09eed820a11233299dd2c7b0190b
[ "MIT" ]
null
null
null
redmail/test/email/test_template.py
kimvanwyk/red-mail
78dc763e5b5f09eed820a11233299dd2c7b0190b
[ "MIT" ]
null
null
null
redmail/test/email/test_template.py
kimvanwyk/red-mail
78dc763e5b5f09eed820a11233299dd2c7b0190b
[ "MIT" ]
null
null
null
from redmail import EmailSender import pytest from convert import remove_email_extra from getpass import getpass, getuser from platform import node def test_template(tmpdir): html_templates = tmpdir.mkdir("html_tmpl") html_templates.join("example.html").write("""<h1>Hi {{ friend }},</h1><p>have you checked this open source project '{{ project_name }}'?</p><p>- {{ sender.full_name }}</p>""") expected_html = f"<h1>Hi Jack,</h1><p>have you checked this open source project 'RedMail'?</p><p>- Me</p>\n" text_templates = tmpdir.mkdir("text_tmpl") text_templates.join("example.txt").write("""Hi {{ friend }}, \nhave you checked this open source project '{{ project_name }}'? \n- {{ sender.full_name }}""") expected_text = f"Hi Jack, \nhave you checked this open source project 'RedMail'? \n- Me\n" html_tables = tmpdir.mkdir("html_table_tmpl") html_tables.join("modest.html").write("""{{ df.to_html() }}""") text_tables = tmpdir.mkdir("text_table_tmpl") text_tables.join("pandas.txt").write("""{{ df.to_html() }}""") sender = EmailSender(host=None, port=1234) sender.set_template_paths( html=str(html_templates), text=str(text_templates), html_table=str(html_tables), text_table=str(text_tables), ) msg = sender.get_message( sender="me@gmail.com", receivers=["you@gmail.com"], subject="Some news", html_template='example.html', text_template='example.txt', body_params={"friend": "Jack", 'project_name': 'RedMail'} ) assert "multipart/alternative" == msg.get_content_type() #text = remove_extra_lines(msg.get_payload()[0].get_payload()) text = remove_email_extra(msg.get_payload()[0].get_payload()) html = remove_email_extra(msg.get_payload()[1].get_payload()) assert expected_html == html assert expected_text == text def test_body_and_template_error(tmpdir): html_templates = tmpdir.mkdir("html_tmpl") html_templates.join("example.html").write("""<h1>Hi {{ friend }},</h1><p>have you checked this open source project '{{ project_name }}'?</p><p>- {{ sender.full_name }}</p>""") text_templates = tmpdir.mkdir("text_tmpl") text_templates.join("example.txt").write("""Hi {{ friend }}, \nhave you checked this open source project '{{ project_name }}'? \n- {{ sender.full_name }}""") sender = EmailSender(host="localhost", port=0) sender.set_template_paths( html=str(html_templates), text=str(text_templates), ) with pytest.raises(ValueError): msg = sender.get_message( sender="me@gmail.com", receivers="you@gmail.com", subject="Some news", html='This is some body', html_template="example.html" ) with pytest.raises(ValueError): msg = sender.get_message( sender="me@gmail.com", receivers="you@gmail.com", subject="Some news", text='This is some body', text_template="example.txt" )
38.848101
179
0.6406
d1158ff29f054b6a9e4fad7d4bead7e092b783a9
645
py
Python
src/LPB/LPBUtils.py
CptSpookz/LPB
1e3ff95e87b7aa9bc09eb214d2015e866ea9494f
[ "MIT" ]
1
2018-10-24T18:51:12.000Z
2018-10-24T18:51:12.000Z
src/LPB/LPBUtils.py
CptSpookz/LPB
1e3ff95e87b7aa9bc09eb214d2015e866ea9494f
[ "MIT" ]
null
null
null
src/LPB/LPBUtils.py
CptSpookz/LPB
1e3ff95e87b7aa9bc09eb214d2015e866ea9494f
[ "MIT" ]
null
null
null
class OutputParser: def __init__(self): self.conteudo = "" self.modificado = False def isModificado(self): return self.modificado def write(self, texto): if not self.isModificado(): self.modificado = True self.conteudo = "{}{}\n".format(self.conteudo,texto) class SymbolTable: def __init__(self, scope): self.scope = scope self.symbols = {} class Comodo: def __init__(self, ident, tipo, dimensao=1, moveis=None): self.nome = ident self.tipo = tipo self.dimensao = dimensao self.moveis = [] if moveis is None else moveis
24.807692
61
0.60155
a6e5080677494b27bf8cd8d8a29e2d2f9723c343
2,659
py
Python
research/slim/nets/nets_factory_test.py
Dzinushi/models_1_4
d7e72793a68c1667d403b1542c205d1cd9b1d17c
[ "Apache-2.0" ]
9
2018-12-21T15:11:43.000Z
2021-04-28T06:49:30.000Z
research/slim/nets/nets_factory_test.py
Dzinushi/models_1_4
d7e72793a68c1667d403b1542c205d1cd9b1d17c
[ "Apache-2.0" ]
null
null
null
research/slim/nets/nets_factory_test.py
Dzinushi/models_1_4
d7e72793a68c1667d403b1542c205d1cd9b1d17c
[ "Apache-2.0" ]
6
2019-01-25T02:53:39.000Z
2021-04-28T06:49:33.000Z
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for slim.inception.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf from nets import nets_factory class NetworksTest(tf.test.TestCase): def testGetNetworkFnFirstHalf(self): batch_size = 5 num_classes = 1000 for net in nets_factory.networks_map.keys()[:10]: with tf.Graph().as_default() as g, self.test_session(g): net_fn = nets_factory.get_network_fn(net, num_classes) # Most networks use 224 as their default_image_size image_size = getattr(net_fn, 'default_image_size', 224) inputs = tf.random_uniform((batch_size, image_size, image_size, 3)) logits, end_points = net_fn(inputs) self.assertTrue(isinstance(logits, tf.Tensor)) self.assertTrue(isinstance(end_points, dict)) self.assertEqual(logits.get_shape().as_list()[0], batch_size) self.assertEqual(logits.get_shape().as_list()[-1], num_classes) def testGetNetworkFnSecondHalf(self): batch_size = 5 num_classes = 1000 for net in nets_factory.networks_map.keys()[10:]: with tf.Graph().as_default() as g, self.test_session(g): net_fn = nets_factory.get_network_fn(net, num_classes) # Most networks use 224 as their default_image_size image_size = getattr(net_fn, 'default_image_size', 224) inputs = tf.random_uniform((batch_size, image_size, image_size, 3)) logits, end_points = net_fn(inputs) self.assertTrue(isinstance(logits, tf.Tensor)) self.assertTrue(isinstance(end_points, dict)) self.assertEqual(logits.get_shape().as_list()[0], batch_size) self.assertEqual(logits.get_shape().as_list()[-1], num_classes) if __name__ == '__main__': tf.test.main()
42.887097
83
0.649492
2f0a6b6119892a3aeb08dbc3301ea0150b3ee145
384
py
Python
notes/migrations/0007_notesrating_review.py
ArnedyNavi/studymate
55e6a2c6717dd478a311ea8bf839a26ca3ef2b40
[ "MIT" ]
4
2021-12-31T17:25:00.000Z
2022-02-08T17:05:46.000Z
notes/migrations/0007_notesrating_review.py
ArnedyNavi/studymate
55e6a2c6717dd478a311ea8bf839a26ca3ef2b40
[ "MIT" ]
null
null
null
notes/migrations/0007_notesrating_review.py
ArnedyNavi/studymate
55e6a2c6717dd478a311ea8bf839a26ca3ef2b40
[ "MIT" ]
null
null
null
# Generated by Django 3.2.9 on 2022-01-03 06:16 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('notes', '0006_auto_20220102_1238'), ] operations = [ migrations.AddField( model_name='notesrating', name='review', field=models.TextField(blank=True), ), ]
20.210526
47
0.596354
9f8582bb1965ea1ed17d815962100bcbdd0f5631
42,061
py
Python
pip/req/req_install.py
anguslees/pip
6c18ad4492e3ae55ae59c79a0114d03fe7caf19b
[ "MIT" ]
null
null
null
pip/req/req_install.py
anguslees/pip
6c18ad4492e3ae55ae59c79a0114d03fe7caf19b
[ "MIT" ]
1
2021-08-07T12:15:25.000Z
2021-08-07T12:15:25.000Z
pip/req/req_install.py
anguslees/pip
6c18ad4492e3ae55ae59c79a0114d03fe7caf19b
[ "MIT" ]
null
null
null
from __future__ import absolute_import import logging import os import re import shutil import sys import tempfile import warnings import zipfile from distutils.util import change_root from distutils import sysconfig from email.parser import FeedParser from pip._vendor import pkg_resources, six from pip._vendor.distlib.markers import interpret as markers_interpret from pip._vendor.six.moves import configparser from pip._vendor.six.moves.urllib import parse as urllib_parse import pip.wheel from pip.compat import native_str, WINDOWS from pip.download import is_url, url_to_path, path_to_url, is_archive_file from pip.exceptions import ( InstallationError, UninstallationError, UnsupportedWheel, ) from pip.locations import ( bin_py, running_under_virtualenv, PIP_DELETE_MARKER_FILENAME, bin_user, ) from pip.utils import ( display_path, rmtree, ask_path_exists, backup_dir, is_installable_dir, dist_in_usersite, dist_in_site_packages, egg_link_path, make_path_relative, call_subprocess, read_text_file, FakeFile, _make_build_dir, ) from pip.utils.deprecation import RemovedInPip8Warning from pip.utils.logging import indent_log from pip.req.req_uninstall import UninstallPathSet from pip.vcs import vcs from pip.wheel import move_wheel_files, Wheel, wheel_ext from pip._vendor.packaging.version import Version logger = logging.getLogger(__name__) class InstallRequirement(object): def __init__(self, req, comes_from, source_dir=None, editable=False, url=None, as_egg=False, update=True, editable_options=None, pycompile=True, markers=None, isolated=False): self.extras = () if isinstance(req, six.string_types): req = pkg_resources.Requirement.parse(req) self.extras = req.extras self.req = req self.comes_from = comes_from self.source_dir = source_dir self.editable = editable if editable_options is None: editable_options = {} self.editable_options = editable_options self.url = url self.as_egg = as_egg self.markers = markers self._egg_info_path = None # This holds the pkg_resources.Distribution object if this requirement # is already available: self.satisfied_by = None # This hold the pkg_resources.Distribution object if this requirement # conflicts with another installed distribution: self.conflicts_with = None self._temp_build_dir = None # True if the editable should be updated: self.update = update # Set to True after successful installation self.install_succeeded = None # UninstallPathSet of uninstalled distribution (for possible rollback) self.uninstalled = None self.use_user_site = False self.target_dir = None self.pycompile = pycompile self.isolated = isolated @classmethod def from_editable(cls, editable_req, comes_from=None, default_vcs=None, isolated=False): name, url, extras_override, editable_options = parse_editable( editable_req, default_vcs) if url.startswith('file:'): source_dir = url_to_path(url) else: source_dir = None res = cls(name, comes_from, source_dir=source_dir, editable=True, url=url, editable_options=editable_options, isolated=isolated) if extras_override is not None: res.extras = extras_override return res @classmethod def from_line(cls, name, comes_from=None, isolated=False): """Creates an InstallRequirement from a name, which might be a requirement, directory containing 'setup.py', filename, or URL. """ from pip.index import Link url = None if is_url(name): marker_sep = '; ' else: marker_sep = ';' if marker_sep in name: name, markers = name.split(marker_sep, 1) markers = markers.strip() if not markers: markers = None else: markers = None name = name.strip() req = None path = os.path.normpath(os.path.abspath(name)) link = None if is_url(name): link = Link(name) elif (os.path.isdir(path) and (os.path.sep in name or name.startswith('.'))): if not is_installable_dir(path): raise InstallationError( "Directory %r is not installable. File 'setup.py' not " "found." % name ) link = Link(path_to_url(name)) elif is_archive_file(path): if not os.path.isfile(path): logger.warning( 'Requirement %r looks like a filename, but the file does ' 'not exist', name ) link = Link(path_to_url(name)) # it's a local file, dir, or url if link: url = link.url # Handle relative file URLs if link.scheme == 'file' and re.search(r'\.\./', url): url = path_to_url(os.path.normpath(os.path.abspath(link.path))) # wheel file if link.ext == wheel_ext: wheel = Wheel(link.filename) # can raise InvalidWheelFilename if not wheel.supported(): raise UnsupportedWheel( "%s is not a supported wheel on this platform." % wheel.filename ) req = "%s==%s" % (wheel.name, wheel.version) else: # set the req to the egg fragment. when it's not there, this # will become an 'unnamed' requirement req = link.egg_fragment # a requirement specifier else: req = name return cls(req, comes_from, url=url, markers=markers, isolated=isolated) def __str__(self): if self.req: s = str(self.req) if self.url: s += ' from %s' % self.url else: s = self.url if self.satisfied_by is not None: s += ' in %s' % display_path(self.satisfied_by.location) if self.comes_from: if isinstance(self.comes_from, six.string_types): comes_from = self.comes_from else: comes_from = self.comes_from.from_path() if comes_from: s += ' (from %s)' % comes_from return s @property def specifier(self): return self.req.specifier def from_path(self): if self.req is None: return None s = str(self.req) if self.comes_from: if isinstance(self.comes_from, six.string_types): comes_from = self.comes_from else: comes_from = self.comes_from.from_path() if comes_from: s += '->' + comes_from return s def build_location(self, build_dir): if self._temp_build_dir is not None: return self._temp_build_dir if self.req is None: self._temp_build_dir = tempfile.mkdtemp('-build', 'pip-') self._ideal_build_dir = build_dir return self._temp_build_dir if self.editable: name = self.name.lower() else: name = self.name # FIXME: Is there a better place to create the build_dir? (hg and bzr # need this) if not os.path.exists(build_dir): _make_build_dir(build_dir) return os.path.join(build_dir, name) def correct_build_location(self): """If the build location was a temporary directory, this will move it to a new more permanent location""" if self.source_dir is not None: return assert self.req is not None assert self._temp_build_dir old_location = self._temp_build_dir new_build_dir = self._ideal_build_dir del self._ideal_build_dir if self.editable: name = self.name.lower() else: name = self.name new_location = os.path.join(new_build_dir, name) if not os.path.exists(new_build_dir): logger.debug('Creating directory %s', new_build_dir) _make_build_dir(new_build_dir) if os.path.exists(new_location): raise InstallationError( 'A package already exists in %s; please remove it to continue' % display_path(new_location)) logger.debug( 'Moving package %s from %s to new location %s', self, display_path(old_location), display_path(new_location), ) shutil.move(old_location, new_location) self._temp_build_dir = new_location self.source_dir = new_location self._egg_info_path = None @property def name(self): if self.req is None: return None return native_str(self.req.project_name) @property def url_name(self): if self.req is None: return None return urllib_parse.quote(self.req.project_name.lower()) @property def setup_py(self): try: import setuptools # noqa except ImportError: # Setuptools is not available raise InstallationError( "setuptools must be installed to install from a source " "distribution" ) setup_file = 'setup.py' if self.editable_options and 'subdirectory' in self.editable_options: setup_py = os.path.join(self.source_dir, self.editable_options['subdirectory'], setup_file) else: setup_py = os.path.join(self.source_dir, setup_file) # Python2 __file__ should not be unicode if six.PY2 and isinstance(setup_py, six.text_type): setup_py = setup_py.encode(sys.getfilesystemencoding()) return setup_py def run_egg_info(self): assert self.source_dir if self.name: logger.debug( 'Running setup.py (path:%s) egg_info for package %s', self.setup_py, self.name, ) else: logger.debug( 'Running setup.py (path:%s) egg_info for package from %s', self.setup_py, self.url, ) with indent_log(): # if it's distribute>=0.7, it won't contain an importable # setuptools, and having an egg-info dir blocks the ability of # setup.py to find setuptools plugins, so delete the egg-info dir # if no setuptools. it will get recreated by the run of egg_info # NOTE: this self.name check only works when installing from a # specifier (not archive path/urls) # TODO: take this out later if (self.name == 'distribute' and not os.path.isdir( os.path.join(self.source_dir, 'setuptools'))): rmtree(os.path.join(self.source_dir, 'distribute.egg-info')) script = self._run_setup_py script = script.replace('__SETUP_PY__', repr(self.setup_py)) script = script.replace('__PKG_NAME__', repr(self.name)) base_cmd = [sys.executable, '-c', script] if self.isolated: base_cmd += ["--no-user-cfg"] egg_info_cmd = base_cmd + ['egg_info'] # We can't put the .egg-info files at the root, because then the # source code will be mistaken for an installed egg, causing # problems if self.editable: egg_base_option = [] else: egg_info_dir = os.path.join(self.source_dir, 'pip-egg-info') if not os.path.exists(egg_info_dir): os.makedirs(egg_info_dir) egg_base_option = ['--egg-base', 'pip-egg-info'] cwd = self.source_dir if self.editable_options and \ 'subdirectory' in self.editable_options: cwd = os.path.join(cwd, self.editable_options['subdirectory']) call_subprocess( egg_info_cmd + egg_base_option, cwd=cwd, filter_stdout=self._filter_install, show_stdout=False, command_level=logging.DEBUG, command_desc='python setup.py egg_info') if not self.req: if isinstance( pkg_resources.parse_version(self.pkg_info()["Version"]), Version): op = "==" else: op = "===" self.req = pkg_resources.Requirement.parse( "".join([ self.pkg_info()["Name"], op, self.pkg_info()["Version"], ])) self.correct_build_location() # FIXME: This is a lame hack, entirely for PasteScript which has # a self-provided entry point that causes this awkwardness _run_setup_py = """ __file__ = __SETUP_PY__ from setuptools.command import egg_info import pkg_resources import os import tokenize def replacement_run(self): self.mkpath(self.egg_info) installer = self.distribution.fetch_build_egg for ep in pkg_resources.iter_entry_points('egg_info.writers'): # require=False is the change we're making: writer = ep.load(require=False) if writer: writer(self, ep.name, os.path.join(self.egg_info,ep.name)) self.find_sources() egg_info.egg_info.run = replacement_run exec(compile( getattr(tokenize, 'open', open)(__file__).read().replace('\\r\\n', '\\n'), __file__, 'exec' )) """ def egg_info_data(self, filename): if self.satisfied_by is not None: if not self.satisfied_by.has_metadata(filename): return None return self.satisfied_by.get_metadata(filename) assert self.source_dir filename = self.egg_info_path(filename) if not os.path.exists(filename): return None data = read_text_file(filename) return data def egg_info_path(self, filename): if self._egg_info_path is None: if self.editable: base = self.source_dir else: base = os.path.join(self.source_dir, 'pip-egg-info') filenames = os.listdir(base) if self.editable: filenames = [] for root, dirs, files in os.walk(base): for dir in vcs.dirnames: if dir in dirs: dirs.remove(dir) # Iterate over a copy of ``dirs``, since mutating # a list while iterating over it can cause trouble. # (See https://github.com/pypa/pip/pull/462.) for dir in list(dirs): # Don't search in anything that looks like a virtualenv # environment if ( os.path.exists( os.path.join(root, dir, 'bin', 'python') ) or os.path.exists( os.path.join( root, dir, 'Scripts', 'Python.exe' ) )): dirs.remove(dir) # Also don't search through tests elif dir == 'test' or dir == 'tests': dirs.remove(dir) filenames.extend([os.path.join(root, dir) for dir in dirs]) filenames = [f for f in filenames if f.endswith('.egg-info')] if not filenames: raise InstallationError( 'No files/directories in %s (from %s)' % (base, filename) ) assert filenames, \ "No files/directories in %s (from %s)" % (base, filename) # if we have more than one match, we pick the toplevel one. This # can easily be the case if there is a dist folder which contains # an extracted tarball for testing purposes. if len(filenames) > 1: filenames.sort( key=lambda x: x.count(os.path.sep) + (os.path.altsep and x.count(os.path.altsep) or 0) ) self._egg_info_path = os.path.join(base, filenames[0]) return os.path.join(self._egg_info_path, filename) def pkg_info(self): p = FeedParser() data = self.egg_info_data('PKG-INFO') if not data: logger.warning( 'No PKG-INFO file found in %s', display_path(self.egg_info_path('PKG-INFO')), ) p.feed(data or '') return p.close() _requirements_section_re = re.compile(r'\[(.*?)\]') @property def installed_version(self): # Create a requirement that we'll look for inside of setuptools. req = pkg_resources.Requirement.parse(self.name) # We want to avoid having this cached, so we need to construct a new # working set each time. working_set = pkg_resources.WorkingSet() # Get the installed distribution from our working set dist = working_set.find(req) # Check to see if we got an installed distribution or not, if we did # we want to return it's version. if dist: return dist.version def assert_source_matches_version(self): assert self.source_dir version = self.pkg_info()['version'] if version not in self.req: logger.warning( 'Requested %s, but installing version %s', self, self.installed_version, ) else: logger.debug( 'Source in %s has version %s, which satisfies requirement %s', display_path(self.source_dir), version, self, ) def update_editable(self, obtain=True): if not self.url: logger.debug( "Cannot update repository at %s; repository location is " "unknown", self.source_dir, ) return assert self.editable assert self.source_dir if self.url.startswith('file:'): # Static paths don't get updated return assert '+' in self.url, "bad url: %r" % self.url if not self.update: return vc_type, url = self.url.split('+', 1) backend = vcs.get_backend(vc_type) if backend: vcs_backend = backend(self.url) if obtain: vcs_backend.obtain(self.source_dir) else: vcs_backend.export(self.source_dir) else: assert 0, ( 'Unexpected version control type (in %s): %s' % (self.url, vc_type)) def uninstall(self, auto_confirm=False): """ Uninstall the distribution currently satisfying this requirement. Prompts before removing or modifying files unless ``auto_confirm`` is True. Refuses to delete or modify files outside of ``sys.prefix`` - thus uninstallation within a virtual environment can only modify that virtual environment, even if the virtualenv is linked to global site-packages. """ if not self.check_if_exists(): raise UninstallationError( "Cannot uninstall requirement %s, not installed" % (self.name,) ) dist = self.satisfied_by or self.conflicts_with paths_to_remove = UninstallPathSet(dist) develop_egg_link = egg_link_path(dist) egg_info_exists = dist.egg_info and os.path.exists(dist.egg_info) # Special case for distutils installed package distutils_egg_info = getattr(dist._provider, 'path', None) if develop_egg_link: # develop egg with open(develop_egg_link, 'r') as fh: link_pointer = os.path.normcase(fh.readline().strip()) assert (link_pointer == dist.location), ( 'Egg-link %s does not match installed location of %s ' '(at %s)' % (link_pointer, self.name, dist.location) ) paths_to_remove.add(develop_egg_link) easy_install_pth = os.path.join(os.path.dirname(develop_egg_link), 'easy-install.pth') paths_to_remove.add_pth(easy_install_pth, dist.location) elif egg_info_exists and dist.egg_info.endswith('.egg-info'): paths_to_remove.add(dist.egg_info) if dist.has_metadata('installed-files.txt'): for installed_file in dist.get_metadata( 'installed-files.txt').splitlines(): path = os.path.normpath( os.path.join(dist.egg_info, installed_file) ) paths_to_remove.add(path) # FIXME: need a test for this elif block # occurs with --single-version-externally-managed/--record outside # of pip elif dist.has_metadata('top_level.txt'): if dist.has_metadata('namespace_packages.txt'): namespaces = dist.get_metadata('namespace_packages.txt') else: namespaces = [] for top_level_pkg in [ p for p in dist.get_metadata('top_level.txt').splitlines() if p and p not in namespaces]: path = os.path.join(dist.location, top_level_pkg) paths_to_remove.add(path) paths_to_remove.add(path + '.py') paths_to_remove.add(path + '.pyc') elif distutils_egg_info: warnings.warn( "Uninstalling a distutils installed project ({0}) has been " "deprecated and will be removed in a future version. This is " "due to the fact that uninstalling a distutils project will " "only partially uninstall the project.".format(self.name), RemovedInPip8Warning, ) paths_to_remove.add(distutils_egg_info) elif dist.location.endswith('.egg'): # package installed by easy_install # We cannot match on dist.egg_name because it can slightly vary # i.e. setuptools-0.6c11-py2.6.egg vs setuptools-0.6rc11-py2.6.egg paths_to_remove.add(dist.location) easy_install_egg = os.path.split(dist.location)[1] easy_install_pth = os.path.join(os.path.dirname(dist.location), 'easy-install.pth') paths_to_remove.add_pth(easy_install_pth, './' + easy_install_egg) elif egg_info_exists and dist.egg_info.endswith('.dist-info'): for path in pip.wheel.uninstallation_paths(dist): paths_to_remove.add(path) else: logger.debug( 'Not sure how to uninstall: %s - Check: %s', dist, dist.location) # find distutils scripts= scripts if dist.has_metadata('scripts') and dist.metadata_isdir('scripts'): for script in dist.metadata_listdir('scripts'): if dist_in_usersite(dist): bin_dir = bin_user else: bin_dir = bin_py paths_to_remove.add(os.path.join(bin_dir, script)) if WINDOWS: paths_to_remove.add(os.path.join(bin_dir, script) + '.bat') # find console_scripts if dist.has_metadata('entry_points.txt'): config = configparser.SafeConfigParser() config.readfp( FakeFile(dist.get_metadata_lines('entry_points.txt')) ) if config.has_section('console_scripts'): for name, value in config.items('console_scripts'): if dist_in_usersite(dist): bin_dir = bin_user else: bin_dir = bin_py paths_to_remove.add(os.path.join(bin_dir, name)) if WINDOWS: paths_to_remove.add( os.path.join(bin_dir, name) + '.exe' ) paths_to_remove.add( os.path.join(bin_dir, name) + '.exe.manifest' ) paths_to_remove.add( os.path.join(bin_dir, name) + '-script.py' ) paths_to_remove.remove(auto_confirm) self.uninstalled = paths_to_remove def rollback_uninstall(self): if self.uninstalled: self.uninstalled.rollback() else: logger.error( "Can't rollback %s, nothing uninstalled.", self.project_name, ) def commit_uninstall(self): if self.uninstalled: self.uninstalled.commit() else: logger.error( "Can't commit %s, nothing uninstalled.", self.project_name, ) def archive(self, build_dir): assert self.source_dir create_archive = True archive_name = '%s-%s.zip' % (self.name, self.pkg_info()["version"]) archive_path = os.path.join(build_dir, archive_name) if os.path.exists(archive_path): response = ask_path_exists( 'The file %s exists. (i)gnore, (w)ipe, (b)ackup ' % display_path(archive_path), ('i', 'w', 'b')) if response == 'i': create_archive = False elif response == 'w': logger.warning('Deleting %s', display_path(archive_path)) os.remove(archive_path) elif response == 'b': dest_file = backup_dir(archive_path) logger.warning( 'Backing up %s to %s', display_path(archive_path), display_path(dest_file), ) shutil.move(archive_path, dest_file) if create_archive: zip = zipfile.ZipFile( archive_path, 'w', zipfile.ZIP_DEFLATED, allowZip64=True ) dir = os.path.normcase(os.path.abspath(self.source_dir)) for dirpath, dirnames, filenames in os.walk(dir): if 'pip-egg-info' in dirnames: dirnames.remove('pip-egg-info') for dirname in dirnames: dirname = os.path.join(dirpath, dirname) name = self._clean_zip_name(dirname, dir) zipdir = zipfile.ZipInfo(self.name + '/' + name + '/') zipdir.external_attr = 0x1ED << 16 # 0o755 zip.writestr(zipdir, '') for filename in filenames: if filename == PIP_DELETE_MARKER_FILENAME: continue filename = os.path.join(dirpath, filename) name = self._clean_zip_name(filename, dir) zip.write(filename, self.name + '/' + name) zip.close() logger.info('Saved %s', display_path(archive_path)) def _clean_zip_name(self, name, prefix): assert name.startswith(prefix + os.path.sep), ( "name %r doesn't start with prefix %r" % (name, prefix) ) name = name[len(prefix) + 1:] name = name.replace(os.path.sep, '/') return name def match_markers(self): if self.markers is not None: return markers_interpret(self.markers) else: return True def install(self, install_options, global_options=(), root=None): if self.editable: self.install_editable(install_options, global_options) return if self.is_wheel: version = pip.wheel.wheel_version(self.source_dir) pip.wheel.check_compatibility(version, self.name) self.move_wheel_files(self.source_dir, root=root) self.install_succeeded = True return if self.isolated: global_options = list(global_options) + ["--no-user-cfg"] temp_location = tempfile.mkdtemp('-record', 'pip-') record_filename = os.path.join(temp_location, 'install-record.txt') try: install_args = [sys.executable] install_args.append('-c') install_args.append( "import setuptools, tokenize;__file__=%r;" "exec(compile(getattr(tokenize, 'open', open)(__file__).read()" ".replace('\\r\\n', '\\n'), __file__, 'exec'))" % self.setup_py ) install_args += list(global_options) + \ ['install', '--record', record_filename] if not self.as_egg: install_args += ['--single-version-externally-managed'] if root is not None: install_args += ['--root', root] if self.pycompile: install_args += ["--compile"] else: install_args += ["--no-compile"] if running_under_virtualenv(): # FIXME: I'm not sure if this is a reasonable location; # probably not but we can't put it in the default location, as # that is a virtualenv symlink that isn't writable py_ver_str = 'python' + sysconfig.get_python_version() install_args += ['--install-headers', os.path.join(sys.prefix, 'include', 'site', py_ver_str)] logger.info('Running setup.py install for %s', self.name) with indent_log(): call_subprocess( install_args + install_options, cwd=self.source_dir, filter_stdout=self._filter_install, show_stdout=False, ) if not os.path.exists(record_filename): logger.debug('Record file %s not found', record_filename) return self.install_succeeded = True if self.as_egg: # there's no --always-unzip option we can pass to install # command so we unable to save the installed-files.txt return def prepend_root(path): if root is None or not os.path.isabs(path): return path else: return change_root(root, path) with open(record_filename) as f: for line in f: directory = os.path.dirname(line) if directory.endswith('.egg-info'): egg_info_dir = prepend_root(directory) break else: logger.warning( 'Could not find .egg-info directory in install record' ' for %s', self, ) # FIXME: put the record somewhere # FIXME: should this be an error? return new_lines = [] with open(record_filename) as f: for line in f: filename = line.strip() if os.path.isdir(filename): filename += os.path.sep new_lines.append( make_path_relative( prepend_root(filename), egg_info_dir) ) inst_files_path = os.path.join(egg_info_dir, 'installed-files.txt') with open(inst_files_path, 'w') as f: f.write('\n'.join(new_lines) + '\n') finally: if os.path.exists(record_filename): os.remove(record_filename) rmtree(temp_location) def remove_temporary_source(self): """Remove the source files from this requirement, if they are marked for deletion""" if self.source_dir and os.path.exists( os.path.join(self.source_dir, PIP_DELETE_MARKER_FILENAME)): logger.debug('Removing source in %s', self.source_dir) rmtree(self.source_dir) self.source_dir = None if self._temp_build_dir and os.path.exists(self._temp_build_dir): rmtree(self._temp_build_dir) self._temp_build_dir = None def install_editable(self, install_options, global_options=()): logger.info('Running setup.py develop for %s', self.name) if self.isolated: global_options = list(global_options) + ["--no-user-cfg"] with indent_log(): # FIXME: should we do --install-headers here too? cwd = self.source_dir if self.editable_options and \ 'subdirectory' in self.editable_options: cwd = os.path.join(cwd, self.editable_options['subdirectory']) call_subprocess( [ sys.executable, '-c', "import setuptools, tokenize; __file__=%r; exec(compile(" "getattr(tokenize, 'open', open)(__file__).read().replace" "('\\r\\n', '\\n'), __file__, 'exec'))" % self.setup_py ] + list(global_options) + ['develop', '--no-deps'] + list(install_options), cwd=cwd, filter_stdout=self._filter_install, show_stdout=False) self.install_succeeded = True def _filter_install(self, line): level = logging.INFO for regex in [ r'^running .*', r'^writing .*', '^creating .*', '^[Cc]opying .*', r'^reading .*', r"^removing .*\.egg-info' \(and everything under it\)$", r'^byte-compiling ', r'^SyntaxError:', r'^SyntaxWarning:', r'^\s*Skipping implicit fixer: ', r'^\s*(warning: )?no previously-included (files|directories) ', r'^\s*warning: no files found matching \'.*\'', r'^\s*changing mode of', # Not sure what this warning is, but it seems harmless: r"^warning: manifest_maker: standard file '-c' not found$"]: if not line or re.search(regex, line.strip()): level = logging.DEBUG break return (level, line) def check_if_exists(self): """Find an installed distribution that satisfies or conflicts with this requirement, and set self.satisfied_by or self.conflicts_with appropriately.""" if self.req is None: return False try: # DISTRIBUTE TO SETUPTOOLS UPGRADE HACK (1 of 3 parts) # if we've already set distribute as a conflict to setuptools # then this check has already run before. we don't want it to # run again, and return False, since it would block the uninstall # TODO: remove this later if (self.req.project_name == 'setuptools' and self.conflicts_with and self.conflicts_with.project_name == 'distribute'): return True else: self.satisfied_by = pkg_resources.get_distribution(self.req) except pkg_resources.DistributionNotFound: return False except pkg_resources.VersionConflict: existing_dist = pkg_resources.get_distribution( self.req.project_name ) if self.use_user_site: if dist_in_usersite(existing_dist): self.conflicts_with = existing_dist elif (running_under_virtualenv() and dist_in_site_packages(existing_dist)): raise InstallationError( "Will not install to the user site because it will " "lack sys.path precedence to %s in %s" % (existing_dist.project_name, existing_dist.location) ) else: self.conflicts_with = existing_dist return True @property def is_wheel(self): return self.url and '.whl' in self.url def move_wheel_files(self, wheeldir, root=None): move_wheel_files( self.name, self.req, wheeldir, user=self.use_user_site, home=self.target_dir, root=root, pycompile=self.pycompile, isolated=self.isolated, ) def get_dist(self): """Return a pkg_resources.Distribution built from self.egg_info_path""" egg_info = self.egg_info_path('') base_dir = os.path.dirname(egg_info) metadata = pkg_resources.PathMetadata(base_dir, egg_info) dist_name = os.path.splitext(os.path.basename(egg_info))[0] return pkg_resources.Distribution( os.path.dirname(egg_info), project_name=dist_name, metadata=metadata) def _strip_postfix(req): """ Strip req postfix ( -dev, 0.2, etc ) """ # FIXME: use package_to_requirement? match = re.search(r'^(.*?)(?:-dev|-\d.*)$', req) if match: # Strip off -dev, -0.2, etc. req = match.group(1) return req def _build_req_from_url(url): parts = [p for p in url.split('#', 1)[0].split('/') if p] req = None if parts[-2] in ('tags', 'branches', 'tag', 'branch'): req = parts[-3] elif parts[-1] == 'trunk': req = parts[-2] return req def _build_editable_options(req): """ This method generates a dictionary of the query string parameters contained in a given editable URL. """ regexp = re.compile(r"[\?#&](?P<name>[^&=]+)=(?P<value>[^&=]+)") matched = regexp.findall(req) if matched: ret = dict() for option in matched: (name, value) = option if name in ret: raise Exception("%s option already defined" % name) ret[name] = value return ret return None def parse_editable(editable_req, default_vcs=None): """Parses an editable requirement into: - a requirement name - an URL - extras - editable options Accepted requirements: svn+http://blahblah@rev#egg=Foobar[baz]&subdirectory=version_subdir .[some_extra] """ url = editable_req extras = None # If a file path is specified with extras, strip off the extras. m = re.match(r'^(.+)(\[[^\]]+\])$', url) if m: url_no_extras = m.group(1) extras = m.group(2) else: url_no_extras = url if os.path.isdir(url_no_extras): if not os.path.exists(os.path.join(url_no_extras, 'setup.py')): raise InstallationError( "Directory %r is not installable. File 'setup.py' not found." % url_no_extras ) # Treating it as code that has already been checked out url_no_extras = path_to_url(url_no_extras) if url_no_extras.lower().startswith('file:'): if extras: return ( None, url_no_extras, pkg_resources.Requirement.parse( '__placeholder__' + extras ).extras, {}, ) else: return None, url_no_extras, None, {} for version_control in vcs: if url.lower().startswith('%s:' % version_control): url = '%s+%s' % (version_control, url) break if '+' not in url: if default_vcs: url = default_vcs + '+' + url else: raise InstallationError( '%s should either be a path to a local project or a VCS url ' 'beginning with svn+, git+, hg+, or bzr+' % editable_req ) vc_type = url.split('+', 1)[0].lower() if not vcs.get_backend(vc_type): error_message = 'For --editable=%s only ' % editable_req + \ ', '.join([backend.name + '+URL' for backend in vcs.backends]) + \ ' is currently supported' raise InstallationError(error_message) try: options = _build_editable_options(editable_req) except Exception as exc: raise InstallationError( '--editable=%s error in editable options:%s' % (editable_req, exc) ) if not options or 'egg' not in options: req = _build_req_from_url(editable_req) if not req: raise InstallationError( '--editable=%s is not the right format; it must have ' '#egg=Package' % editable_req ) else: req = options['egg'] package = _strip_postfix(req) return package, url, None, options
37.961191
79
0.54654
d433af0220f2f82d5a29c1a049800a2f405e13e3
6,809
py
Python
doc/source/conf.py
scottdangelo/cinderclient-api-microversions
a0df4c76f2959ffed08cf65fd53de03484b1c0bc
[ "CNRI-Python", "Apache-1.1" ]
null
null
null
doc/source/conf.py
scottdangelo/cinderclient-api-microversions
a0df4c76f2959ffed08cf65fd53de03484b1c0bc
[ "CNRI-Python", "Apache-1.1" ]
null
null
null
doc/source/conf.py
scottdangelo/cinderclient-api-microversions
a0df4c76f2959ffed08cf65fd53de03484b1c0bc
[ "CNRI-Python", "Apache-1.1" ]
null
null
null
# -*- coding: utf-8 -*- # # python-cinderclient documentation build configuration file, created by # sphinx-quickstart on Sun Dec 6 14:19:25 2009. # # This file is execfile()d with current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import os import sys import pbr.version # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.append(os.path.abspath('.')) BASE_DIR = os.path.dirname(os.path.abspath(__file__)) ROOT = os.path.abspath(os.path.join(BASE_DIR, "..", "..")) sys.path.insert(0, ROOT) # -- General configuration ---------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'oslosphinx'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8' # The master toctree document. master_doc = 'index' # General information about the project. project = 'python-cinderclient' copyright = 'OpenStack Contributors' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. version_info = pbr.version.VersionInfo('python-cinderclient') # The short X.Y version. version = version_info.version_string() # The full version, including alpha/beta/rc tags. release = version_info.release_string() # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. #unused_docs = [] # List of directories, relative to source directory, that shouldn't be searched # for source files. exclude_trees = [] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] man_pages = [ ('man/cinder', 'cinder', u'Client for OpenStack Block Storage API', [u'OpenStack Contributors'], 1), ] # -- Options for HTML output -------------------------------------------------- # The theme to use for HTML and HTML Help pages. Major themes that come with # Sphinx are currently 'default' and 'sphinxdoc'. #html_theme = 'nature' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_use_modindex = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = '' # Output file base name for HTML help builder. htmlhelp_basename = 'python-cinderclientdoc' # -- Options for LaTeX output ------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]) # . latex_documents = [ ('index', 'python-cinderclient.tex', 'python-cinderclient Documentation', 'Rackspace - based on work by Jacob Kaplan-Moss', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_use_modindex = True
32.89372
79
0.725804
a061357c95680915caecd070a794b43757e569f1
1,100
py
Python
egs/CHiME6/local/get_stats_from_diarization.py
popcornell/OSDC
bb73a305143c74574000e72eab04c13be7c7b9c9
[ "MIT" ]
7
2020-10-28T14:51:15.000Z
2021-10-11T08:47:58.000Z
egs/CHiME6/local/get_stats_from_diarization.py
popcornell/OSDC
bb73a305143c74574000e72eab04c13be7c7b9c9
[ "MIT" ]
2
2020-09-28T11:25:34.000Z
2022-01-10T08:16:24.000Z
egs/CHiME6/local/get_stats_from_diarization.py
popcornell/OSDC
bb73a305143c74574000e72eab04c13be7c7b9c9
[ "MIT" ]
null
null
null
import argparse import json import numpy as np import os parser = argparse.ArgumentParser("get diar stats") parser.add_argument("diar_file") if __name__ == "__main__": args = parser.parse_args() with open(args.diar_file, "r") as f: diarization = json.load(f) stats = [0]*5 for sess in diarization.keys(): maxlen = max([diarization[sess][spk][-1][-1] for spk in diarization[sess].keys()]) dummy = np.zeros(int(np.ceil(maxlen/160)), dtype="uint8") for spk in diarization[sess].keys(): if spk == "garbage": continue for s, e in diarization[sess][spk]: s = int(s/160) e = int(e/160) dummy[s:e] += 1 for i in range(len(stats)): stats[i] += len(np.where(dummy == i)[0]) assert not np.where(dummy > 5)[0].any() print("TOT SILENCE {}".format(stats[0])) print("TOT 1 SPK {}".format(stats[1])) print("TOT 2 SPK {}".format(stats[2])) print("TOT 3 SPK {}".format(stats[3])) print("TOT 4 SPK {}".format(stats[4]))
24.444444
90
0.555455
17c44dd9ca0a89c8e40b07cd7f5a5b35a18cb949
7,290
bzl
Python
bazel/cargo/crates.bzl
gbrail/proxy-wasm-rust-sdk
f1a0ec203c43241587a330a47bd4705a947112de
[ "Apache-2.0" ]
null
null
null
bazel/cargo/crates.bzl
gbrail/proxy-wasm-rust-sdk
f1a0ec203c43241587a330a47bd4705a947112de
[ "Apache-2.0" ]
null
null
null
bazel/cargo/crates.bzl
gbrail/proxy-wasm-rust-sdk
f1a0ec203c43241587a330a47bd4705a947112de
[ "Apache-2.0" ]
null
null
null
""" @generated cargo-raze generated Bazel file. DO NOT EDIT! Replaced on runs of cargo-raze """ load("@bazel_tools//tools/build_defs/repo:git.bzl", "new_git_repository") # buildifier: disable=load load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") # buildifier: disable=load load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") # buildifier: disable=load def raze_fetch_remote_crates(): """This function defines a collection of repos and should be called in a WORKSPACE file""" maybe( http_archive, name = "raze__ahash__0_4_6", url = "https://crates.io/api/v1/crates/ahash/0.4.6/download", type = "tar.gz", sha256 = "f6789e291be47ace86a60303502173d84af8327e3627ecf334356ee0f87a164c", strip_prefix = "ahash-0.4.6", build_file = Label("//bazel/cargo/remote:BUILD.ahash-0.4.6.bazel"), ) maybe( http_archive, name = "raze__autocfg__1_0_1", url = "https://crates.io/api/v1/crates/autocfg/1.0.1/download", type = "tar.gz", sha256 = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a", strip_prefix = "autocfg-1.0.1", build_file = Label("//bazel/cargo/remote:BUILD.autocfg-1.0.1.bazel"), ) maybe( http_archive, name = "raze__cfg_if__0_1_10", url = "https://crates.io/api/v1/crates/cfg-if/0.1.10/download", type = "tar.gz", sha256 = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822", strip_prefix = "cfg-if-0.1.10", build_file = Label("//bazel/cargo/remote:BUILD.cfg-if-0.1.10.bazel"), ) maybe( http_archive, name = "raze__cfg_if__1_0_0", url = "https://crates.io/api/v1/crates/cfg-if/1.0.0/download", type = "tar.gz", sha256 = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd", strip_prefix = "cfg-if-1.0.0", build_file = Label("//bazel/cargo/remote:BUILD.cfg-if-1.0.0.bazel"), ) maybe( http_archive, name = "raze__chrono__0_4_19", url = "https://crates.io/api/v1/crates/chrono/0.4.19/download", type = "tar.gz", sha256 = "670ad68c9088c2a963aaa298cb369688cf3f9465ce5e2d4ca10e6e0098a1ce73", strip_prefix = "chrono-0.4.19", build_file = Label("//bazel/cargo/remote:BUILD.chrono-0.4.19.bazel"), ) maybe( http_archive, name = "raze__getrandom__0_2_0", url = "https://crates.io/api/v1/crates/getrandom/0.2.0/download", type = "tar.gz", sha256 = "ee8025cf36f917e6a52cce185b7c7177689b838b7ec138364e50cc2277a56cf4", strip_prefix = "getrandom-0.2.0", build_file = Label("//bazel/cargo/remote:BUILD.getrandom-0.2.0.bazel"), ) maybe( http_archive, name = "raze__hashbrown__0_9_1", url = "https://crates.io/api/v1/crates/hashbrown/0.9.1/download", type = "tar.gz", sha256 = "d7afe4a420e3fe79967a00898cc1f4db7c8a49a9333a29f8a4bd76a253d5cd04", strip_prefix = "hashbrown-0.9.1", build_file = Label("//bazel/cargo/remote:BUILD.hashbrown-0.9.1.bazel"), ) maybe( http_archive, name = "raze__libc__0_2_81", url = "https://crates.io/api/v1/crates/libc/0.2.81/download", type = "tar.gz", sha256 = "1482821306169ec4d07f6aca392a4681f66c75c9918aa49641a2595db64053cb", strip_prefix = "libc-0.2.81", build_file = Label("//bazel/cargo/remote:BUILD.libc-0.2.81.bazel"), ) maybe( http_archive, name = "raze__log__0_4_11", url = "https://crates.io/api/v1/crates/log/0.4.11/download", type = "tar.gz", sha256 = "4fabed175da42fed1fa0746b0ea71f412aa9d35e76e95e59b192c64b9dc2bf8b", strip_prefix = "log-0.4.11", build_file = Label("//bazel/cargo/remote:BUILD.log-0.4.11.bazel"), ) maybe( http_archive, name = "raze__num_integer__0_1_44", url = "https://crates.io/api/v1/crates/num-integer/0.1.44/download", type = "tar.gz", sha256 = "d2cc698a63b549a70bc047073d2949cce27cd1c7b0a4a862d08a8031bc2801db", strip_prefix = "num-integer-0.1.44", build_file = Label("//bazel/cargo/remote:BUILD.num-integer-0.1.44.bazel"), ) maybe( http_archive, name = "raze__num_traits__0_2_14", url = "https://crates.io/api/v1/crates/num-traits/0.2.14/download", type = "tar.gz", sha256 = "9a64b1ec5cda2586e284722486d802acf1f7dbdc623e2bfc57e65ca1cd099290", strip_prefix = "num-traits-0.2.14", build_file = Label("//bazel/cargo/remote:BUILD.num-traits-0.2.14.bazel"), ) maybe( http_archive, name = "raze__time__0_1_44", url = "https://crates.io/api/v1/crates/time/0.1.44/download", type = "tar.gz", sha256 = "6db9e6914ab8b1ae1c260a4ae7a49b6c5611b40328a735b21862567685e73255", strip_prefix = "time-0.1.44", build_file = Label("//bazel/cargo/remote:BUILD.time-0.1.44.bazel"), ) maybe( http_archive, name = "raze__wasi__0_10_0_wasi_snapshot_preview1", url = "https://crates.io/api/v1/crates/wasi/0.10.0+wasi-snapshot-preview1/download", type = "tar.gz", sha256 = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f", strip_prefix = "wasi-0.10.0+wasi-snapshot-preview1", build_file = Label("//bazel/cargo/remote:BUILD.wasi-0.10.0+wasi-snapshot-preview1.bazel"), ) maybe( http_archive, name = "raze__wasi__0_9_0_wasi_snapshot_preview1", url = "https://crates.io/api/v1/crates/wasi/0.9.0+wasi-snapshot-preview1/download", type = "tar.gz", sha256 = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519", strip_prefix = "wasi-0.9.0+wasi-snapshot-preview1", build_file = Label("//bazel/cargo/remote:BUILD.wasi-0.9.0+wasi-snapshot-preview1.bazel"), ) maybe( http_archive, name = "raze__winapi__0_3_9", url = "https://crates.io/api/v1/crates/winapi/0.3.9/download", type = "tar.gz", sha256 = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419", strip_prefix = "winapi-0.3.9", build_file = Label("//bazel/cargo/remote:BUILD.winapi-0.3.9.bazel"), ) maybe( http_archive, name = "raze__winapi_i686_pc_windows_gnu__0_4_0", url = "https://crates.io/api/v1/crates/winapi-i686-pc-windows-gnu/0.4.0/download", type = "tar.gz", sha256 = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6", strip_prefix = "winapi-i686-pc-windows-gnu-0.4.0", build_file = Label("//bazel/cargo/remote:BUILD.winapi-i686-pc-windows-gnu-0.4.0.bazel"), ) maybe( http_archive, name = "raze__winapi_x86_64_pc_windows_gnu__0_4_0", url = "https://crates.io/api/v1/crates/winapi-x86_64-pc-windows-gnu/0.4.0/download", type = "tar.gz", sha256 = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f", strip_prefix = "winapi-x86_64-pc-windows-gnu-0.4.0", build_file = Label("//bazel/cargo/remote:BUILD.winapi-x86_64-pc-windows-gnu-0.4.0.bazel"), )
39.836066
101
0.646365
b783cc4ba6808e42d386e05bb6ee2c8e339975ae
4,006
py
Python
bayes.py
cvlabmiet/bayesian-classifier
302da1e261f6b0d455e356a940dd121436881613
[ "MIT" ]
null
null
null
bayes.py
cvlabmiet/bayesian-classifier
302da1e261f6b0d455e356a940dd121436881613
[ "MIT" ]
null
null
null
bayes.py
cvlabmiet/bayesian-classifier
302da1e261f6b0d455e356a940dd121436881613
[ "MIT" ]
null
null
null
#coding=utf-8 import cv2 import numpy as np import matplotlib.pyplot as plt import mpl_toolkits.mplot3d.axes3d as p3 from data import getTrainingSetYCrCb, getTestSetYCrCb """ Вычисление ячейки гистограммы, к которой относится заданная точка. Args: bins: массив левых границ ячеек разбиения по каждой из компонент. pixel: точка изображения. Returns: Позиция ячейки, соответствующей точки изображения. """ def getPosition(bins, pixel): ndims = len(bins) position = np.empty(ndims, dtype = int) for dim in np.arange(ndims): current_bins = bins[dim] last_bin = current_bins[-1] if pixel[dim] >= last_bin: position[dim] = len(current_bins) - 1 else: res = current_bins[:] > pixel[dim] position[dim] = np.argmax(res) - 1 position = tuple(position) return position """ Построение гистограммы данных с заданными параметрами ячеек. Args: bins: массив границ ячеек разбиения по каждой из компонент. data: данные, по которым строится гистограмма. Returns: Массив, соответствующий гистограмме. """ def getHistogram(bins, data): ndims = len(bins) data_length = data.shape[0] dims = np.empty(ndims, dtype = int) for i in np.arange(ndims): dims[i] = bins[i].size hist = np.zeros(dims) for i in np.arange(data_length): current = data[i,:] position = getPosition(bins, current) if min(position) < 0: return -1 hist[position] += 1 if hist.sum() != 0: hist = hist / hist.sum() return hist """ Алгоритм выделения кожи на изображении на основе классификатора Байеса. Attributes: model_path: каталог, содержащий натренированные модели классификатора. bins: массив границ ячеек разбиения по каждой из компонент. skin_histogram: гистограмма, соответствующая точкам кожи. non_skin_histogram: гистограмма, соответствующая точкам фона. """ class Bayes(object): model_path = "bayes_models\\" bins = None skin_histogram = None non_skin_histogram = None """Инициализация модели алгоритма.""" def __init__(self, bins, skin, non_skin): self.bins = bins ndims = len(bins) steps = np.empty(ndims, dtype = int) for i in np.arange(ndims): steps[i] = bins[i][1] - bins[i][0] postfix = "" for i in np.arange(ndims): postfix += "_" + str(steps[i]) skin_model_name = self.model_path + "bayes_skin_model" + postfix + ".npy" non_skin_model_name = self.model_path + "bayes_non_skin_model" + postfix + ".npy" try: # Загрузка сохранённой модели. self.skin_histogram = np.load(skin_model_name) self.non_skin_histogram = np.load(non_skin_model_name) except Exception: # Обучение новой модели. self.skin_histogram = getHistogram(bins, skin) self.non_skin_histogram = getHistogram(bins, non_skin) np.save(skin_model_name, self.skin_histogram) np.save(non_skin_model_name, self.non_skin_histogram) """ Построение карты кожи изображения.""" def apply(self, image): rows, cols, _ = image.shape skin_map = np.empty([rows, cols]) for y in range(rows): for x in range(cols): current = image[y,x,:] position = getPosition(self.bins, current) skin = self.skin_histogram[position] non_skin = self.non_skin_histogram[position] if non_skin == 0: skin_map[y,x] = skin else: skin_map[y,x] = skin / non_skin return skin_map """Построение бинарной маски сегментации кожи.""" def classify(self, image, threshold): skin_map = self.apply(image) skin_map[skin_map <= threshold] = 0 skin_map[skin_map > threshold] = 255 skin_map = np.uint8(skin_map) return skin_map
29.028986
89
0.626311
579a7693778b25ede794f78a2053a179cb5593f1
1,646
py
Python
DQM/Integration/python/clients/gem_dqm_sourceclient-live_cfg.py
pwrobel5/cmssw
856711bff1da14a7022e9138e9ec519bc1f01732
[ "Apache-2.0" ]
null
null
null
DQM/Integration/python/clients/gem_dqm_sourceclient-live_cfg.py
pwrobel5/cmssw
856711bff1da14a7022e9138e9ec519bc1f01732
[ "Apache-2.0" ]
null
null
null
DQM/Integration/python/clients/gem_dqm_sourceclient-live_cfg.py
pwrobel5/cmssw
856711bff1da14a7022e9138e9ec519bc1f01732
[ "Apache-2.0" ]
null
null
null
import FWCore.ParameterSet.Config as cms import sys process = cms.Process('GEMDQM') unitTest = False if 'unitTest=True' in sys.argv: unitTest=True process.load('Configuration.StandardSequences.GeometryRecoDB_cff') process.load("DQM.Integration.config.FrontierCondition_GT_cfi") if unitTest: process.load("DQM.Integration.config.unittestinputsource_cfi") from DQM.Integration.config.unittestinputsource_cfi import options else: process.load("DQM.Integration.config.inputsource_cfi") from DQM.Integration.config.inputsource_cfi import options process.load("DQM.Integration.config.environment_cfi") process.dqmEnv.subSystemFolder = "GEM" process.dqmSaver.tag = "GEM" process.dqmSaver.runNumber = options.runNumber process.dqmSaverPB.tag = "GEM" process.dqmSaverPB.runNumber = options.runNumber process.load("DQMServices.Components.DQMProvInfo_cfi") process.load("EventFilter.GEMRawToDigi.muonGEMDigis_cfi") process.load('RecoLocalMuon.GEMRecHit.gemRecHits_cfi') process.load("DQM.GEM.GEMDQM_cff") if (process.runType.getRunType() == process.runType.hi_run): process.muonGEMDigis.InputLabel = cms.InputTag("rawDataRepacker") process.muonGEMDigis.useDBEMap = True process.muonGEMDigis.unPackStatusDigis = True process.path = cms.Path( process.muonGEMDigis * process.gemRecHits * process.GEMDQM ) process.end_path = cms.EndPath( process.dqmEnv + process.dqmSaver + process.dqmSaverPB ) process.schedule = cms.Schedule( process.path, process.end_path ) process.dqmProvInfo.runType = process.runType.getRunTypeName() from DQM.Integration.config.online_customizations_cfi import * process = customise(process)
26.983607
68
0.803159
6a75fc8dd198c84ba8dfeb7668ceeecb8261deaa
1,561
py
Python
tests/test_FileManager.py
anitavincent/simple_crawler
0e84bb9009e81c96ecff24621c3d3d3286c94f6d
[ "MIT" ]
null
null
null
tests/test_FileManager.py
anitavincent/simple_crawler
0e84bb9009e81c96ecff24621c3d3d3286c94f6d
[ "MIT" ]
null
null
null
tests/test_FileManager.py
anitavincent/simple_crawler
0e84bb9009e81c96ecff24621c3d3d3286c94f6d
[ "MIT" ]
null
null
null
from unittest import TestCase from filemanager import FileManager class FileManagerTest(TestCase): def setUp(self): self.manager = FileManager("products.csv", "urls.db") def test_change_products_result(self): self.manager.clear_result() products = self.manager.get_product_names_set() self.assertEqual(set(), products) self.manager.add_to_results("epoca.com", "Blush", "Blush - Epoca") self.manager.add_to_results("epoca.com", "Batom", "Batom") products = self.manager.get_product_names_set() self.assertEqual({"Blush", "Batom"}, products) self.manager.clear_result() products = self.manager.get_product_names_set() self.assertEqual(set(), products) def test_change_saved_urls(self): self.manager.cleanup_database() self.manager.setup_database() self.manager.add_found_url("epoca.com") self.manager.add_found_url("google.com") self.manager.add_found_url("wow.com") self.manager.add_found_url("fb.com") self.manager.change_url_to_parsed("wow.com") self.manager.change_url_to_parsed("fb.com") saved_urls = self.manager.get_saved_urls_set() self.assertEqual( {"epoca.com", "google.com", "wow.com", "fb.com"}, saved_urls) parsed_urls = self.manager.get_unparsed_urls_set() self.assertEqual( {"epoca.com", "google.com"}, parsed_urls) self.manager.cleanup_database() self.assertTrue(self.manager.database_is_empty())
32.520833
74
0.664958
7d07e1f9a1cc3846346c77ea4a0637dda8021911
361
py
Python
rplugin/python3/denite/source/lsp_docment_symbol.py
statiolake/denite-vim-lsp
77ac576ba447149633bbfb829c5ef243561001c2
[ "MIT" ]
null
null
null
rplugin/python3/denite/source/lsp_docment_symbol.py
statiolake/denite-vim-lsp
77ac576ba447149633bbfb829c5ef243561001c2
[ "MIT" ]
null
null
null
rplugin/python3/denite/source/lsp_docment_symbol.py
statiolake/denite-vim-lsp
77ac576ba447149633bbfb829c5ef243561001c2
[ "MIT" ]
null
null
null
import sys from pathlib import Path sys.path.append(str(Path(__file__).parent.parent.parent.resolve())) from denite_lsp_symbol.symbol_base import SymbolBase class Source(SymbolBase): def __init__(self, vim): super().__init__(vim, 'lsp_document_symbol') def start_lookup(self, _query): self.vim.call('denite_vim_lsp#document_symbol')
25.785714
67
0.747922
cb5f9575b39247b4317b29234a26ec5b34755325
30,241
py
Python
rudolf.py
iknite/rudolf
4a33a26a3aff867846db46c6fb82dc5b3f04aace
[ "ZPL-2.1" ]
1
2019-05-01T05:57:10.000Z
2019-05-01T05:57:10.000Z
rudolf.py
iknite/rudolf
4a33a26a3aff867846db46c6fb82dc5b3f04aace
[ "ZPL-2.1" ]
null
null
null
rudolf.py
iknite/rudolf
4a33a26a3aff867846db46c6fb82dc5b3f04aace
[ "ZPL-2.1" ]
null
null
null
"""Color output plugin for the nose testing framework. Use ``nosetests --with-color`` (no "u"!) to turn it on. http://en.wikipedia.org/wiki/Rudolph_the_Red-Nosed_Reindeer "Rudolph the Red-Nosed Reindeer" is a popular Christmas story about Santa Claus' ninth and lead reindeer who possesses an unusually red colored nose that gives off its own light that is powerful enough to illuminate the team's path through inclement weather. Copyright 2007 John J. Lee <jjl@pobox.com> This code is derived from zope.testing version 3.5.0, which carries the following copyright and licensing notice: ############################################################################## # # Copyright (c) 2004-2006 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """ from __future__ import division, print_function import binascii import doctest import os import re import sys import time import traceback import unittest import warnings import nose.config import nose.core import nose.plugins import nose.util # TODO # syntax-highlight traceback Python source lines __version__ = "0.4" # some of this ANSI/xterm colour stuff is based on public domain code by Ian # Ward # don't use the basic 16 colours, we can't be sure what their RGB values are CUBE_START = 16 # first index of colour cube CUBE_SIZE = 6 # one side of the colour cube GRAY_START = CUBE_SIZE ** 3 + CUBE_START # values copied from xterm 256colres.h: CUBE_STEPS = 0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff GRAY_STEPS = (0x08, 0x12, 0x1c, 0x26, 0x30, 0x3a, 0x44, 0x4e, 0x58, 0x62, 0x6c, 0x76, 0x80, 0x84, 0x94, 0x9e, 0xa8, 0xb2, 0xbc, 0xc6, 0xd0, 0xda, 0xe4, 0xee) TABLE_START = CUBE_START TABLE_END = 256 def xterm_from_rgb_string(rgb_text): try: bytes = binascii.unhexlify(rgb_text) except (TypeError, binascii.Error): raise ValueError(rgb_text) if len(bytes) < 3: raise ValueError(rgb_text) rgb = [x if isinstance(x, int) else ord(x) for x in bytes] return xterm_from_rgb(rgb) def cube_vals(n): """Return the cube coordinates for colour-number n.""" assert n >= CUBE_START and n < GRAY_START val = n - CUBE_START c = val % CUBE_SIZE val = int(val / CUBE_SIZE) b = val % CUBE_SIZE a = int(val / CUBE_SIZE) return a, b, c def rgb_from_xterm(n): """Return the red, green and blue components of colour-number n. Components are between 0 and 255.""" # we don't handle the basic 16 colours, since we can't be sure what their # RGB values are assert n >= CUBE_START and n < TABLE_END if n < GRAY_START: return tuple([CUBE_STEPS[v] for v in cube_vals(n)]) return (GRAY_STEPS[n - GRAY_START],) * 3 RGB_FROM_XTERM_COLOR = [ rgb_from_xterm(xi) for xi in range(TABLE_START, TABLE_END)] def xterm_from_rgb(rgb): smallest_distance = sys.maxsize for index in range(0, TABLE_END - TABLE_START): rc = RGB_FROM_XTERM_COLOR[index] dist = ((rc[0] - rgb[0]) ** 2 + (rc[1] - rgb[1]) ** 2 + (rc[2] - rgb[2]) ** 2) if dist < smallest_distance: smallest_distance = dist best_match = index return best_match + TABLE_START class Xterm256Color(object): def __init__(self, xterm_color_code): self._code = xterm_color_code def terminal_code(self): return "\033[38;5;%dm" % self._code class Ansi16Color(object): def __init__(self, foreground_color, bright): self._fg_color = foreground_color self._bright = bright def terminal_code(self): if self._fg_color is None: fg_code = 0 else: fg_code = self._fg_color + 30 if self._bright is None: prefix_code = "" elif self._bright: prefix_code = "1;" else: prefix_code = "0;" return "\033[%s%sm" % (prefix_code, fg_code) def parse_color(color_text): assert color_text # RGB if color_text.startswith("rgb(") and color_text.endswith(")"): try: xc = xterm_from_rgb_string(color_text[4:-1]) except ValueError: raise ValueError("Bad RGB colour: %r" % color_text) else: return Xterm256Color(xc) # xterm 256 colour code try: xc = int(color_text) except ValueError: pass else: if 0 <= xc < 256: return Xterm256Color(xc) else: raise ValueError("Bad xterm colour: %r" % color_text) # named ANSI 16 colour colorcodes = {"default": None, "normal": None, "black": 0, "red": 1, "green": 2, "brown": 3, "yellow": 3, "blue": 4, "magenta": 5, "cyan": 6, "grey": 7, "gray": 7, "white": 7} prefixes = [("dark", False), ("light", True), ("bright", True), ("bold", True)] is_bright = None remaining = color_text for prefix, bright in prefixes: if remaining.startswith(prefix): remaining = color_text[len(prefix):] is_bright = bright break try: foreground = colorcodes[remaining] except KeyError: raise ValueError("Bad named colour: %r" % color_text) return Ansi16Color(foreground, is_bright) def parse_colorscheme(colorscheme): if not colorscheme: return {} colors = {} specs = colorscheme.split(",") for spec in specs: try: name, color_text = spec.split("=", 1) except ValueError: raise ValueError("Missing equals (name=colour): %r" % spec) if color_text == "": raise ValueError("Missing colour (name=colour): %r" % spec) colors[name] = parse_color(color_text) return colors def normalize_path(pathname): if hasattr(os.path, "realpath"): pathname = os.path.realpath(pathname) return os.path.normcase(os.path.abspath(pathname)) def relative_location(basedir, target, posix_result=True): # based on a function by Robin Becker import os.path import posixpath basedir = normalize_path(basedir) target = normalize_path(target) baseparts = basedir.split(os.sep) targetparts = target.split(os.sep) nr_base = len(baseparts) nr_target = len(targetparts) nr_common = min(nr_base, nr_target) ii = 0 while ii < nr_common and baseparts[ii] == targetparts[ii]: ii += 1 relative_parts = (nr_base - ii) * ['..'] + targetparts[ii:] if posix_result: return posixpath.join(*relative_parts) else: return os.path.join(*relative_parts) def elide_foreign_path_and_line_nr(base_dir, path, line_nr): relpath = relative_location(base_dir, path) if ".." in relpath: filename = os.path.basename(relpath) return os.path.join("...", filename), "..." else: return relpath, line_nr class DocTestFailureException(AssertionError): """Custom exception for doctest unit test failures.""" # colour output code taken from zope.testing, and hacked class ColorfulOutputFormatter(object): """Output formatter that uses ANSI color codes. Like syntax highlighting in your text editor, colorizing test failures helps the developer. """ separator1 = "=" * 70 separator2 = "-" * 70 doctest_template = """ File "%s", line %s, in %s %s Want: %s Got: %s """ # Map prefix character to color in diff output. This handles ndiff and # udiff correctly, but not cdiff. diff_color = {"-": "expected-output", "+": "actual-output", "?": "character-diffs", "@": "diff-chunk", "*": "diff-chunk", "!": "actual-output"} def __init__(self, verbosity, descriptions, colorscheme, stream=sys.stdout, clean_tracebacks=False, base_dir=False): self._stream = stream self._verbose = bool(verbosity) self._show_all = verbosity > 1 self._dots = verbosity == 1 self._descriptions = descriptions self._clean_tracebacks = clean_tracebacks self._base_dir = base_dir self._colorscheme = colorscheme def color(self, what): """Pick a named color from the color scheme""" return self._colorscheme[what].terminal_code() def colorize(self, what, message, normal="normal"): """Wrap message in color.""" return u'' + self.color(what) + message + self.color(normal) def get_description(self, test): if self._descriptions: return test.shortDescription() or str(test) else: return str(test) def start_test(self, test): if self._show_all: self._stream.write(self.colorize("normal", self.get_description(test))) self._stream.write(self.colorize("normal", " ... ")) self._stream.flush() def test_success(self, test): if self._show_all: self._stream.writeln(self.colorize("pass", "ok")) elif self._dots: self._stream.write(self.colorize("pass", ".")) def test_error(self, test, exc_info, label): if self._show_all: self._stream.writeln(self.colorize("error", label)) elif self._dots: self._stream.write(self.colorize("error", label[:1])) def test_skip(self, label): if self._show_all: self._stream.writeln(self.colorize("skip", label)) elif self._dots: self._stream.write(self.colorize("skip", label[:1])) def test_failure(self, test, exc_info): if self._show_all: self._stream.writeln(self.colorize("failure", "FAIL")) elif self._dots: self._stream.write(self.colorize("failure", "F")) def print_error_list(self, flavour, errors): problem_color = { "FAIL": "failure", "SKIP": "skip" }.get(flavour, "error") for tup in errors: test, err = tup[:2] try: err_type = tup[2] except IndexError: err_type = None # Handle skip message skip_msg = "" if flavour == "SKIP": reason = getattr(err, "message", None) if reason: skip_msg = " (%s)" % self.colorize("skip", reason) self._stream.writeln(self.separator1) self._stream.writeln("%s: %s%s" % ( self.colorize(problem_color, flavour), self.colorize("testname", self.get_description(test)), skip_msg )) if flavour != "SKIP": self._stream.writeln(self.separator2) self.print_traceback(err, err_type) def print_summary(self, success, summary, tests_run, start, stop): write = self._stream.write writeln = self._stream.writeln writelines = self._stream.writelines taken = float(stop - start) plural = tests_run != 1 and "s" or "" count_color = success and "ok-number" or "error-number" writeln(self.separator2) writelines([ "Ran ", self.colorize(count_color, "%s " % tests_run), "test%s in " % plural, self._format_seconds(taken)]) writeln() if not success: write(self.colorize("failure", "FAILED")) write(" (") any = False for label, count in summary.items(): if not count: continue if any: write(", ") write("%s=" % label) problem_color = (label == "failures") and "failure" or "error" write(self.colorize(problem_color, str(count))) any = True writeln(")") else: writeln(self.colorize("pass", "OK")) def _format_seconds(self, n_seconds, normal="normal"): """Format a time in seconds.""" if n_seconds >= 60: n_minutes, n_seconds = divmod(n_seconds, 60) return "%s minutes %s seconds" % ( self.colorize("number", "%d" % n_minutes, normal), self.colorize("number", "%.3f" % n_seconds, normal)) else: return "%s seconds" % ( self.colorize("number", "%.3f" % n_seconds, normal)) def format_traceback(self, exc_info): """Format the traceback.""" v = exc_info[1] if isinstance(v, DocTestFailureException): tb = v.args[0] if isinstance(v, doctest.DocTestFailure): tb = self.doctest_template % ( v.test.filename, v.test.lineno + v.example.lineno + 1, v.test.name, v.example.source, v.example.want, v.got, ) else: tb = "".join(traceback.format_exception(*exc_info)) return tb def print_traceback(self, formatted_traceback, err_type): """Report an error with a traceback.""" if issubclass(err_type, DocTestFailureException): self.print_doctest_failure(formatted_traceback) else: self.print_colorized_traceback(formatted_traceback) print(file=self._stream) def print_doctest_failure(self, formatted_failure): """Report a doctest failure. ``formatted_failure`` is a string -- that's what DocTestSuite/DocFileSuite gives us. """ color_of_indented_text = 'normal' colorize_diff = False colorize_exception = False lines = formatted_failure.splitlines() # this first traceback in a doctest failure report is rarely # interesting, but it looks funny non-colourized so let's colourize it # anyway exc_lines = [] while True: line = lines.pop(0) if line == self.separator2: break exc_lines.append(line) self.print_colorized_traceback("\n".join(exc_lines)) print(file=self._stream) print(self.separator2, file=self._stream) exc_lines = [] for line in lines: if line.startswith('File '): m = re.match(r'File "(.*)", line (\d*), in (.*)$', line) if m: filename, lineno, test = m.groups() if self._clean_tracebacks: filename, lineno = elide_foreign_path_and_line_nr( self._base_dir, filename, lineno) self._stream.writelines([ self.color('normal'), 'File "', self.color('filename'), filename, self.color('normal'), '", line ', self.color('lineno'), lineno, self.color('normal'), ', in ', self.color('testname'), test, self.color('normal'), '\n']) else: print(line, file=self._stream) elif line.startswith(' '): if colorize_diff and len(line) > 4: color = self.diff_color.get(line[4], color_of_indented_text) print(self.colorize(color, line), file=self._stream) elif colorize_exception: exc_lines.append(line[4:]) else: print(self.colorize(color_of_indented_text, line), file=self._stream) else: colorize_diff = False if colorize_exception: self.print_colorized_traceback("\n".join(exc_lines), indent_level=1) colorize_exception = False exc_lines = [] if line.startswith('Failed example'): color_of_indented_text = 'failed-example' elif line.startswith('Expected:'): color_of_indented_text = 'expected-output' elif line.startswith('Got:'): color_of_indented_text = 'actual-output' elif line.startswith('Exception raised:'): color_of_indented_text = 'exception' colorize_exception = True elif line.startswith('Differences '): if line in [ "Differences (ndiff with -expected +actual):", "Differences (unified diff with -expected +actual):" ]: line = "".join([ "Differences (ndiff with ", self.color("expected-output"), "-expected ", self.color("actual-output"), "+actual", self.color("normal"), "):", ]) color_of_indented_text = 'normal' colorize_diff = True else: color_of_indented_text = 'normal' print(line, file=self._stream) print(file=self._stream) def print_colorized_traceback(self, formatted_traceback, indent_level=0): """Report a test failure. ``formatted_traceback`` is a string. """ indentation = " " * indent_level for line in formatted_traceback.splitlines(): if line.startswith(" File"): m = re.match(r' File "(.*)", line (\d*)(?:, in (.*))?$', line) if m: filename, lineno, test = m.groups() if self._clean_tracebacks: filename, lineno = elide_foreign_path_and_line_nr( self._base_dir, filename, lineno) tb_lines = [ self.color("normal"), ' File "', self.color("filename"), filename, self.color("normal"), '", line ', self.color("lineno"), lineno, ] if test: # this is missing for the first traceback in doctest # failure report tb_lines.extend([ self.color("normal"), ", in ", self.color("testname"), test, ]) tb_lines.extend([ self.color("normal"), "\n", ]) self._stream.write(indentation) self._stream.writelines(tb_lines) else: print(indentation + line, file=self._stream) elif line.startswith(" "): print(self.colorize("failed-example", indentation + line), file=self._stream) elif line.startswith("Traceback (most recent call last)"): print(indentation + line, file=self._stream) else: print(self.colorize("exception", indentation + line), file=self._stream) def stop_test(self, test): if self._verbose > 1: print(file=self._stream) self._stream.flush() def stop_tests(self): if self._verbose == 1: self._stream.write("\n") self._stream.flush() class ColorOutputPlugin(nose.plugins.Plugin): """Output test results in colour to terminal.""" name = "color" formatter_class = ColorfulOutputFormatter clean_tracebacks = False base_dir = None # These colors are carefully chosen to have enough contrast # on terminals with both black and white background. default_colorscheme = {"normal": "normal", "pass": "green", "failure": "magenta", "error": "brightred", "number": "green", "ok-number": "green", "error-number": "brightred", "filename": "lightblue", "lineno": "lightred", "testname": "lightcyan", "failed-example": "cyan", "expected-output": "green", "actual-output": "red", "character-diffs": "magenta", "diff-chunk": "magenta", "exception": "red", "skip": "yellow"} default_colorscheme = dict((name, parse_color(color)) for name, color in default_colorscheme.items()) # Lower than default plugin level, since the output we're # printing is replacing non-plugin core nose output, which # usually happens after plugin output. If this were >= default # score, then e.g. core plugin testid output would come out in # the wrong place. score = 50 def __init__(self): nose.plugins.Plugin.__init__(self) self._result = None # for debugging # self.base_dir = os.path.dirname(__file__) # clean_tracebacks = True def options(self, parser, env=os.environ): nose.plugins.Plugin.options(self, parser, env) parser.add_option("--no-color", action="store_false", dest="enable_plugin_color", help="Don't output in color") # XXX This might be wrong when running tests in a subprocess (since I # guess sys.stdout will be a pipe, but colour output should be turned # on). Depends on how the running-in-a-subprocess is done (it's not a # core nose feature as of version 0.10.0). # XXX should be able to specify auto-color in environment action = sys.stdout.isatty() and "store_true" or "store_false" parser.add_option("--auto-color", action=action, dest="enable_plugin_color", help="Output in color only if stdout is a terminal") env_opt = "NOSE_COLORS" parser.add_option("--colors", action="store", type="string", dest="colors", default=env.get(env_opt, ""), help="Colour scheme for --with-color terminal " "output, listing colours to be used for each " "named part of the output. Format is " "name1=color1,name2=color2 . " "Colours can be specified as xterm 256 colour " "codes (e.g. '45'), RGB colours (e.g. " "'rgb(00ff00)'), ANSI 16 colour names (e.g. " "'red' or 'brightred'), and the special " "colour 'normal'. Example: " "--colors='fail=red,pass=rgb(00ff00),error=45' " + "[%s]" % env_opt) def configure(self, options, conf): nose.plugins.Plugin.configure(self, options, conf) if not self.enabled: return self._verbosity = conf.verbosity cs = dict(self.default_colorscheme) try: user_colorscheme = parse_colorscheme(options.colors) except ValueError as exc: filenames = list(conf.files) if options.files: filenames.extend(options.files) warnings.warn("Bad colorscheme string " "(from --colors or one of %s): %s" % (", ".join(filenames), exc), RuntimeWarning) user_colorscheme = {} unknown_names = set(user_colorscheme.keys()) - set(cs.keys()) if unknown_names: warnings.warn("Invalid colorscheme names: %s" % (", ".join(unknown_names))) cs.update(user_colorscheme) self._colorscheme = cs self._show_all = self._verbosity > 1 self._dots = self._verbosity == 1 def begin(self): self._old_failure_exception = doctest.DocTestCase.failureException # monkeypatch! doctest.DocTestCase.failureException = DocTestFailureException def setOutputStream(self, stream): self._stream = stream self._formatter = self.formatter_class( self._verbosity, True, self._colorscheme, self._stream, clean_tracebacks=self.clean_tracebacks, base_dir=self.base_dir) def prepareTestResult(self, result): result.__failures = [] result.__errors = [] result.__tests_run = 0 result.__start_time = time.time() # Python <= 2.6 has _WritelnDecorator at top level try: writeln_decorator = unittest._WritelnDecorator # Python >= 2.7 has it in the runner module except AttributeError: writeln_decorator = unittest.runner._WritelnDecorator # This neuters any default or plugin defined output streams, # effectively forcing all output through Rudolf. result.stream = writeln_decorator(open(os.devnull, 'w')) # So we need to monkeypatch core addSkip, which appears to be the only # code called on skips (our own addSkip, if defined, is ignored.) # Gross, but works. old_addSkip = result.addSkip def new_addSkip(test, reason): old_addSkip(test, reason) label = result.errorClasses[nose.plugins.skip.SkipTest][1] self._formatter.test_skip(label) result.addSkip = new_addSkip self._result = result def startTest(self, test): self._result.__tests_run = self._result.__tests_run + 1 self._formatter.start_test(test) def addSuccess(self, test): self._formatter.test_success(test) def addFailure(self, test, err): formatted_failure = self._exc_info_to_string(err, test) self._result.__failures.append((test, formatted_failure, err[0])) self._formatter.test_failure(test, err) def addError(self, test, err): # If the exception is a registered class, the error will be added to # the list for that class, not errors. formatted_err = self._formatter.format_traceback(err) for cls, (storage, label, isfail) in self._result.errorClasses.items(): if issubclass(err[0], cls): storage.append((test, formatted_err, err[0])) self._formatter.test_error(test, err, label) return self._result.__errors.append((test, formatted_err, err[0])) self._formatter.test_error(test, err, "ERROR") def stopTest(self, test): self._formatter.stop_test(test) def report(self, stream): self._print_errors() self._print_summary(self._result.__start_time, time.time()) self._result = None def finalize(self, result): self._formatter.stop_tests() # remove monkeypatch doctest.DocTestCase.failureException = self._old_failure_exception def _print_errors(self): if self._dots or self._show_all: self._stream.writeln() self._formatter.print_error_list("ERROR", self._result.__errors) self._formatter.print_error_list("FAIL", self._result.__failures) for cls in self._result.errorClasses.keys(): storage, label, isfail = self._result.errorClasses[cls] self._formatter.print_error_list(label, storage) def _print_summary(self, start, stop): success = self._result.wasSuccessful() summary = nose.util.odict() if not success: summary["failures"], summary["errors"] = \ [len(x) for x in (self._result.__failures, self._result.__errors)] for cls in self._result.errorClasses.keys(): storage, label, isfail = self._result.errorClasses[cls] if not isfail: continue summary[label] = len(storage) self._formatter.print_summary(success, summary, self._result.__tests_run, start, stop) def _exc_info_to_string(self, err, test): exctype, value, tb = err # Skip test runner traceback levels while tb and self._is_relevant_tb_level(tb): tb = tb.tb_next if exctype is test.failureException: # Skip assert*() traceback levels length = self._count_relevant_tb_levels(tb) return ''.join(traceback.format_exception(exctype, value, tb, length)) return ''.join(traceback.format_exception(exctype, value, tb)) def _is_relevant_tb_level(self, tb): return '__unittest' in tb.tb_frame.f_globals def _count_relevant_tb_levels(self, tb): length = 0 while tb and not self._is_relevant_tb_level(tb): length += 1 tb = tb.tb_next # printing is replacing non-plugin core nose output, which # usually happens after plugin output. If this were >= default # score, then e.g. core plugin testid output would come out in return length
37.105521
82
0.555207