code stringlengths 114 1.05M | path stringlengths 3 312 | quality_prob float64 0.5 0.99 | learning_prob float64 0.2 1 | filename stringlengths 3 168 | kind stringclasses 1
value |
|---|---|---|---|---|---|
from datetime import datetime
from py4j.compat import long
from pyspark.sql import SparkSession
from pyspark.sql.dataframe import DataFrame
class ConfKeys:
DATASOURCE_INIT = "druid.datasource.init"
# Segment config
DATA_SOURCE = "druid.datasource"
TIME_COLUMN = "druid.time_column"
DIMENSIONS_SPEC = "druid.dimensions_spec"
METRICS_SPEC = "druid.metrics_spec"
TRANSFORM_SPEC = "druid.transform_spec"
SEGMENT_GRANULARITY = "druid.segment_granularity"
QUERY_GRANULARITY = "druid.query_granularity"
BITMAP_FACTORY = "druid.bitmap_factory"
EXCLUDED_DIMENSIONS = "druid.exclude_dimensions"
SEGMENT_MAX_ROWS = "druid.segment.max_rows"
SEGMENT_ROLLUP = "druid.segment.rollup"
USE_DEFAULT_VALUES_FOR_NULL = "druid.use_default_values_for_null"
# Metadata config
METADATA_DB_TYPE = "druid.metastore.db.type"
METADATA_DB_URI = "druid.metastore.db.uri"
METADATA_DB_USERNAME = "druid.metastore.db.username"
METADATA_DB_PASSWORD = "druid.metastore.db.password"
METADATA_DB_TABLE_BASE = "druid.metastore.db.table.base"
# Deep Storage config
DEEP_STORAGE_TYPE = "druid.segment_storage.type"
# S3 config
DEEP_STORAGE_S3_BUCKET = "druid.segment_storage.s3.bucket"
DEEP_STORAGE_S3_BASE_KEY = "druid.segment_storage.s3.basekey"
# Local config (only for testing)
DEEP_STORAGE_LOCAL_DIRECTORY = "druid.segment_storage.local.dir"
def repartition_by_druid_segment_size(self, time_col_name, segment_granularity='DAY', rows_per_segment=5000000,
exclude_columns_with_unknown_types=False):
_jdf = self.sql_ctx._sc._jvm.com.rovio.ingest.extensions.java.DruidDatasetExtensions \
.repartitionByDruidSegmentSize(self._jdf, time_col_name, segment_granularity, rows_per_segment,
exclude_columns_with_unknown_types)
return DataFrame(_jdf, self.sql_ctx)
def normalize_date(spark: SparkSession, value: datetime, granularity: str) -> datetime:
instant: long = long(value.timestamp() * 1000)
normalized: long = spark.sparkContext._jvm.com.rovio.ingest.util \
.NormalizeTimeColumnUDF.normalize(instant, granularity)
return datetime.fromtimestamp(normalized / 1000)
def add_dataframe_druid_extension():
DataFrame.repartition_by_druid_segment_size = repartition_by_druid_segment_size | /rovio_ingest-1.0.5-py3-none-any.whl/rovio_ingest/extensions/dataframe_extension.py | 0.501465 | 0.199756 | dataframe_extension.py | pypi |
#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 importlib import resources # Python 3.7+
import sys
import logging
import argparse
from threading import Thread, Event
from row_estimator_for_apache_cassandra.estimator import Estimator
def main():
def add_helper(n):
return columns_in_bytes+n
logging.getLogger('cassandra').setLevel(logging.ERROR)
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO)
# Event object used to send signals from one thread to another
stop_event = Event()
# Configure app args
parser = argparse.ArgumentParser(description='The tool helps to gather Cassandra rows stats')
requiredNamed = parser.add_argument_group('required named arguments')
requiredNamed.add_argument('--hostname', help='Cassandra endpoint', default='127.0.0.1', required=True)
requiredNamed.add_argument('--port', help='Cassandra native transport port', required=True)
parser.add_argument('--ssl', help='Use SSL.', default=None)
parser.add_argument('--path-cert', help='Path to the TLS certificate', default=None)
parser.add_argument('--username', help='Authenticate as user')
parser.add_argument('--password',help='Authenticate using password')
requiredNamed.add_argument('--keyspace',help='Gather stats against provided keyspace', required=True)
requiredNamed.add_argument('--table',help='Gather stats against provided table', required=True)
parser.add_argument('--execution-timeout', help='Set execution timeout in seconds', type=int, default=360)
parser.add_argument('--token-step', help='Set token step, for example, 2, 4, 8, 16, 32, ..., 255',type=int, default=4)
parser.add_argument('--rows-per-request', help='How many rows per token',type=int, default=1000)
parser.add_argument('--pagination', help='Turn on pagination mechanism',type=int, default=200)
parser.add_argument('--dc', help='Define Cassandra datacenter for routing policy', default='datacenter1')
parser.add_argument('--json', help='Estimata size of Cassandra rows as JSON', default=None)
if (len(sys.argv)<2):
parser.print_help()
sys.exit()
args = parser.parse_args()
p_hostname = args.hostname
p_port = args.port
p_username = args.username
p_password = args.password
p_ssl = args.ssl
p_path_cert = args.path_cert
p_json = args.json
p_dc = args.dc
p_keyspace = args.keyspace
p_table = args.table
p_execution_timeout = args.execution_timeout
p_token_step = args.token_step
p_rows_per_request = args.rows_per_request
p_pagination = args.pagination
estimator = Estimator(p_hostname, p_port, p_username, p_password, p_ssl, p_dc, p_keyspace, p_table,
p_execution_timeout, p_token_step, p_rows_per_request, p_pagination, p_path_cert)
logging.info("Endpoint: %s %s", p_hostname, p_port)
logging.info("Keyspace name: %s", estimator.keyspace)
logging.info("Table name: %s", estimator.table)
logging.info("Client SSL: %s", estimator.ssl)
logging.info("Token step: %s", estimator.token_step)
logging.info("Limit of rows per token step: %s", estimator.rows_per_request)
logging.info("Pagination: %s", estimator.pagination)
logging.info("Execution-timeout: %s", estimator.execution_timeout)
if p_json == None:
action_thread = Thread(target=estimator.row_sampler(json=False))
action_thread.start()
action_thread.join(timeout=estimator.execution_timeout)
stop_event.set()
columns_in_bytes = estimator.get_total_column_size()
rows_in_bytes = estimator.rows_in_bytes
rows_columns_in_bytes = map(add_helper, rows_in_bytes)
val = list(rows_columns_in_bytes)
logging.info("Number of sampled rows: %s", len(rows_in_bytes))
logging.info("Estimated size of column names and values in a row:")
logging.info(" Mean: %s", '{:06.2f}'.format(estimator.mean(val)))
logging.info(" Weighted_mean: %s", '{:06.2f}'.format(estimator.weighted_mean(val)))
logging.info(" Median: %s", '{:06.2f}'.format(estimator.median(val)))
logging.info(" Min: %s",min(val))
logging.info(" P10: %s",'{:06.2f}'.format(estimator.quartiles(val, 0.1)))
logging.info(" P50: %s",'{:06.2f}'.format(estimator.quartiles(val, 0.5)))
logging.info(" P90: %s",'{:06.2f}'.format(estimator.quartiles(val, 0.9)))
logging.info(" Max: %s",max(val))
logging.info(" Average: %s",'{:06.2f}'.format(sum(val)/len(val)))
logging.info("Estimated size of values in a row")
logging.info(" Mean: %s", '{:06.2f}'.format(estimator.mean(rows_in_bytes)))
logging.info(" Weighted_mean: %s", '{:06.2f}'.format(estimator.weighted_mean(rows_in_bytes)))
logging.info(" Median: %s", '{:06.2f}'.format(estimator.median(rows_in_bytes)))
logging.info(" Min: %s",min(rows_in_bytes))
logging.info(" P10: %s",'{:06.2f}'.format(estimator.quartiles(rows_in_bytes, 0.1)))
logging.info(" P50: %s",'{:06.2f}'.format(estimator.quartiles(rows_in_bytes, 0.5)))
logging.info(" P90: %s",'{:06.2f}'.format(estimator.quartiles(rows_in_bytes, 0.9)))
logging.info(" Max: %s",max(rows_in_bytes))
logging.info(" Average: %s",'{:06.2f}'.format(sum(rows_in_bytes)/len(rows_in_bytes)))
logging.info("Total column name size in a row: %s",columns_in_bytes)
logging.info("Columns in a row: %s", estimator.get_columns().count(',')+1)
else:
action_thread = Thread(target=estimator.row_sampler(json=True))
action_thread.start()
action_thread.join(timeout=estimator.execution_timeout)
stop_event.set()
rows_in_bytes = estimator.rows_in_bytes
logging.info("Number of sampled rows: %s", len(rows_in_bytes))
logging.info("Estimated size of a Cassandra JSON row")
logging.info("Mean: %s", '{:06.2f}'.format(estimator.mean(rows_in_bytes)))
logging.info("Weighted_mean: %s", '{:06.2f}'.format(estimator.weighted_mean(rows_in_bytes)))
logging.info("Median: %s", '{:06.2f}'.format(estimator.median(rows_in_bytes)))
logging.info("Min: %s",min(rows_in_bytes))
logging.info("Max: %s",max(rows_in_bytes))
logging.info("Average: %s",'{:06.2f}'.format(sum(rows_in_bytes)/len(rows_in_bytes)))
if __name__ == "__main__":
main() | /row_estimator_for_apache_cassandra-0.0.3-py3-none-any.whl/row_estimator_for_apache_cassandra/__main__.py | 0.487795 | 0.190272 | __main__.py | pypi |
#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 sys import getsizeof, stderr
import sys
from ssl import SSLContext, PROTOCOL_TLSv1_2, CERT_REQUIRED
from cassandra.cluster import Cluster
from cassandra.auth import PlainTextAuthProvider
from cassandra import ConsistencyLevel
from cassandra.cluster import ExecutionProfile
from cassandra.policies import WhiteListRoundRobinPolicy
import math
from functools import reduce
import optparse
import time
import os
from datetime import datetime
from sortedcontainers import SortedDict
from threading import Thread, Event
from collections import deque
stop_event = Event()
class Estimator(object):
""" The estimator class containes connetion, stats methods """
def __init__(self, endpoint_name, port, username=None, password=None, ssl=None, dc=None, keyspace=None,
table=None, execution_timeout=None, token_step=None, rows_per_request=None, pagination=5000, path_cert=None):
self.endpoint_name = endpoint_name
self.port = port
self.username = username
self.password = password
self.ssl = ssl
self.path_cert = path_cert
self.keyspace = keyspace
self.table = table
self.execution_timeout = execution_timeout
self.token_step = token_step
self.rows_per_request = rows_per_request
self.pagination = pagination
self.dc = dc
self.rows_in_bytes = []
def get_connection(self):
""" Returns Cassandra session """
auth_provider = None
if self.ssl:
ssl_context = SSLContext(PROTOCOL_TLSv1)
ssl_context.load_verify_locations(path_cert)
ssl_context.verify_mode = CERT_REQUIRED
#ssl_options = {
# 'ca_certs' : self.ssl,
# 'ssl_version' : PROTOCOL_TLSv1_2
#}
else:
ssl_context=None
if (self.username and self.password):
auth_provider = PlainTextAuthProvider(self.username, self.password)
node1_profile = ExecutionProfile(load_balancing_policy=WhiteListRoundRobinPolicy([self.endpoint_name]))
profiles = {'node1': node1_profile}
cluster = Cluster([self.endpoint_name], port=self.port ,auth_provider=auth_provider, ssl_context=ssl_context, control_connection_timeout=360, execution_profiles=profiles)
session = cluster.connect()
return session
def mean(self, lst):
""" Calculate the mean of list of Cassandra values """
final_mean = 0.0
for n in lst:
final_mean += n
final_mean = final_mean / float(len(lst))
return final_mean
def weighted_mean(self, lst):
""" Calculates the weighted mean of a list of Cassandra values """
total = 0
total_weight = 0
normalized_weights = []
# Set up some lists for our weighted values, and weighted means
weights = [1 + n for n in range(len(lst))]
normalized_weights = [0 for n in range(len(lst))]
# Calculate a total of all weights
total_weight = reduce(lambda y,x: x+y, weights)
# Divide each weight by the sum of all weights
for q,r in enumerate(weights):
normalized_weights[q] = r / float(total_weight)
# Add values of original List multipled by weighted values
for q,r in enumerate(lst):
total +=r * normalized_weights[q]
return total
def median(self, lst):
""" Calculate the median of Cassandra values """
""" The middle value in the set """
tmp_lst = sorted(lst)
index = (len(lst) - 1) // 2
# If the set has an even number of entries, combine the middle two
# Otherwise print the middle value
if len(lst) % 2 == 0:
return ((tmp_lst[index] + tmp_lst[index + 1]) / 2.0)
else:
return tmp_lst[index]
def quartiles(self, lst, q):
""" Quartiles in stats are values that devide your data into quarters """
lst.sort()
cnt = len(lst)
ith = int(math.floor(q*(cnt)))
return lst[ith]
def total_size(self, obj, handlers={}, verbose=False):
"""
Gets ~ memory footprint an object and all of its contents.
Finds the contents of the following builtin containers and
their subclasses: tuple, list, deque, dict, set and frozenset.
To search other containers, add handlers to iterate over their contents:
handlers = {SomeContainerClass: iter, OtherContainerClass: OtherContainerClass.get_elements}
"""
dict_handler = lambda d: chain.from_iterable(d.items())
all_handlers = {tuple: iter,
list: iter,
deque: iter,
dict: dict_handler,
set: iter,
frozenset: iter,
}
all_handlers.update(handlers)
seen = set()
default_size = getsizeof(0)
obj_empty_size = getsizeof('')
def sizeof(obj):
if id(obj) in seen:
return 0
seen.add(id(obj))
s = getsizeof(obj, default_size)
if verbose:
print(s, type(obj), repr(obj), file=stderr)
for typ, handler in all_handlers.items():
if isinstance(obj, typ):
# Recursively call the function sizeof for each object handler to estimate the sum of bytes
s += sum(map(sizeof, handler(obj)))
break
return s
return sizeof(obj)-obj_empty_size
def get_total_column_size(self):
""" The method returns total size of field names in ResultSets """
session = self.get_connection()
columns_results_stmt = session.prepare("select column_name from system_schema.columns where keyspace_name=? and table_name=?")
columns_results_stmt.consistency_level = ConsistencyLevel.LOCAL_ONE
columns_results = session.execute(columns_results_stmt, [self.keyspace, self.table])
clmsum=0
for col in columns_results:
clmsum += self.total_size(col.column_name, verbose=False)
return clmsum
def get_partition_key(self):
""" The method returns parition key """
session = self.get_connection()
pk_results_stmt = session.prepare("select column_name, position from system_schema.columns where keyspace_name=? and table_name=? and kind='partition_key' ALLOW FILTERING")
pk_results_stmt.consistency_level = ConsistencyLevel.LOCAL_ONE
pk_results = session.execute(pk_results_stmt, [self.keyspace, self.table])
sd = SortedDict()
for p in pk_results:
sd[p.position]=p.column_name
if len(sd)>1:
pk_string = ','.join(sd.values())
else:
pk_string = sd.values()[0]
return pk_string
def get_columns(self):
""" The method returns all columns """
session = self.get_connection()
columns_results_stmt = session.prepare("select column_name from system_schema.columns where keyspace_name=? and table_name=?")
columns_results_stmt.consistency_level = ConsistencyLevel.LOCAL_ONE
columns_results = session.execute(columns_results_stmt, [self.keyspace, self.table])
clms=[]
for c in columns_results:
clms.append(c.column_name)
if len(clms)>1:
cl_string = ','.join(clms)
else:
cl_string = clms[0]
return cl_string
def row_sampler(self, json=False):
a=0
session = self.get_connection()
cl = self.get_columns()
pk = self.get_partition_key()
if (json == True):
tbl_lookup_stmt = session.prepare("SELECT json "+cl+" FROM "+self.keyspace+"."+self.table+" WHERE token("+pk+")>? AND token("+pk+")<? LIMIT "+str(self.rows_per_request))
else:
tbl_lookup_stmt = session.prepare("SELECT * FROM "+self.keyspace+"."+self.table+" WHERE token("+pk+")>? AND token("+pk+")<? LIMIT "+str(self.rows_per_request))
tbl_lookup_stmt.consistency_level = ConsistencyLevel.LOCAL_ONE
tbl_lookup_stmt.fetch_size=int(self.pagination)
ring=[]
ring_values_by_step=[]
rows_bytes=[]
for r in session.cluster.metadata.token_map.ring:
ring.append(r.value)
for i in ring[::self.token_step]:
ring_values_by_step.append(i)
it = iter(ring_values_by_step)
for val in it:
try:
results = session.execute(tbl_lookup_stmt, [val, next(it)])
for row in results:
if (json == True):
s1 = str(row.json).replace('null','""')
rows_bytes.append(self.total_size(s1, verbose=False))
else:
for value in row:
s1 = str(value)
a +=self.total_size(s1, verbose=False)
rows_bytes.append(a)
a = 0
if stop_event.is_set():
break
except StopIteration:
logger.info("no more token pairs")
self.rows_in_bytes = rows_bytes | /row_estimator_for_apache_cassandra-0.0.3-py3-none-any.whl/row_estimator_for_apache_cassandra/estimator.py | 0.493164 | 0.210381 | estimator.py | pypi |
import os
import re
from os.path import exists
from google.cloud import storage
# Need to save service account JSON under root_repo_name directory
class GCP:
def __init__(
self,
service_account_name="omd-emea-daimler-a8c6772fb5f7.json",
):
"""
Args:
service_account_name (str, optional): file name of the Service account JSON file which is stored directly in the root_repo directory eg. 'omd-emea-daimler-a8c6772fb5f7.json'
"""
self.json_path = service_account_name
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = service_account_name
def download_file_from_bucket(self, GCP_path, destination_file_name):
"""Downloads file from bucket
Args:
GCP_path (str): The path to the file in GCP
destination_file_name (str): relative path where to download file into
"""
bucket_name, source_blob_name = GCP_path.split("/", 1)
storage_client = storage.Client.from_service_account_json(self.json_path)
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(source_blob_name)
blob.download_to_filename(destination_file_name)
print(
"Downloaded storage object {} from bucket {} to local file {}.".format(
source_blob_name, bucket_name, destination_file_name
)
)
def __check_variable_names_have_been_set__(self, varible_names, varible_values):
d = dict(zip(varible_names, varible_values))
for var_name in d:
if d[var_name] == None:
raise ValueError(f"GCP: {var_name} not defined")
def upload_to_bucket(self, GCP_path, relative_path_to_file):
"""Uploads Data to Bucket
Args:
GCP_path (str): The path to the file in GCP
relative_path_to_file (str): Relative path to locally stored file
Returns
str: Location of stored file in GCP bucket
"""
bucket_name, blob_name = GCP_path.split("/", 1)
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(blob_name)
blob.upload_from_filename(relative_path_to_file)
# returns a public url
return blob.public_url
def search_for_file_name(self, gcp_bucket, file):
"""Searches a GCP bucket for a file, and returns path in GCP bucket if it exists
Args:
gcp_bucket (str): Bucket to search in
file (str): file to look for
"""
list_of_matching_files = (
os.popen('gsutil ls "gs://' + gcp_bucket + '/**" | grep ' + file)
.read()
.split("\n")[:-1]
)
return list_of_matching_files
def download_multiple_files(self, GCP_path, regex_pattern, relative_path_to_folder):
"""Downloads multiple files under a path in GCP according to a regex match, and stores them all in one folder
Args:
GCP_path (str): Folder in GCP you wish to search for multiple files
regex_pattern (str): regex pattern matching criteria
relative_path_to_folder (str): path to local folder to store all downloaded files into, if you are installing directly in root repo dir then put ''
"""
# add check if files are called same thing
files_to_download = self.search_for_file_name(GCP_path, regex_pattern)
try:
bucket_name, _ = GCP_path.split("/", 1)
except:
# TODO make this more granular
# If we are looking directly in root of the bucket
bucket_name = GCP_path
storage_client = storage.Client.from_service_account_json(self.json_path)
bucket = storage_client.bucket(bucket_name)
for file in files_to_download:
file = file.replace("gs://" + bucket_name + "/", "")
file_name = file.split("/")[-1]
blob = bucket.blob(file)
blob.download_to_filename(os.path.join(relative_path_to_folder, file_name))
def read_in_data(
self, download_from_GCP, relative_path_to_file, file_reader, GCP_path=None
):
"""Reads in data from existing local file or downloads from GCP to path_to_file and reads it in
Args:
download_from_GCP (bool): Whether or not to download file from GCP or use locally stored file to read
relative_path_to_file (str): relative path to locally stored file / where to download file into
file_reader (str): method to read file
GCP_path (str): The path to the file in GCP
Returns:
data: The data eg. pandas df
"""
# TODO add **kwargs for file_reader
if download_from_GCP:
try:
self.__check_variable_names_have_been_set__(["GCP_path"], [GCP_path])
except Exception as e:
return e
self.download_file_from_bucket(GCP_path, relative_path_to_file)
else:
if not exists(local_path_to_file):
print(
"Missing data, please read in from GCP or enter correct data location"
)
return file_reader(relative_path_to_file) | /rowan_ds_tools-0.14.tar.gz/rowan_ds_tools-0.14/rowan_ds_tools/io/GCP_bucket.py | 0.575827 | 0.245752 | GCP_bucket.py | pypi |
import functools
import time
import pandas as pd
import sqlalchemy as sqa
from ..utils._param_validation import validate_params
def _db_connector_decorator(func):
"""Decorator which
1. sets up connections to the db
2. peforms decorated function
3. closes connections to the DB
Args:
func (function): function to interact with the DB
Returns:
_type_: _description_
"""
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
# ---------- Sets up DB connection ----------
try:
engine = sqa.create_engine(self.connstring)
conn = engine.connect()
except:
# Sometimes it doesn't connect on first try
time.sleep(4)
engine = sqa.create_engine(self.connstring)
conn = engine.connect()
# ---------- DB interaction ----------
try:
out = func(self, *args, **kwargs, conn=conn)
except Exception as e:
raise (e)
# ---------- Terminate db connection ----------
finally:
conn.close()
engine.dispose()
return out
return wrapper
def strip_column_wrappers(df):
return [x.replace('"', "") for x in df.columns]
def add_column_wrappers(df):
return ['"' + x + '"' for x in df.columns]
class PostgressHelper:
@validate_params({"conn_string": [str]})
def __init__(self, conn_string):
self.connstring = conn_string
def get_db_engine(self):
engine = sqa.create_engine(self.connstring)
return engine
@_db_connector_decorator
@validate_params({"dequote": ["boolean"], "query": [str]})
def query(self, query, dequote=True, **kwargs):
"""Queries the postgress DB and return the quieried result
Args:
query (str): query string
dequote (bool, optional): option to dequote columns or not. Defaults to True.
Returns:
_type_: _description_
"""
df = pd.read_sql(query, con=kwargs["conn"])
if dequote:
df.columns = strip_column_wrappers(df)
return df
@_db_connector_decorator
@validate_params({"query": [str]})
def alter_db(self, query, **kwargs):
"""Peforms query to alter the postgress DB, such as drop drop table or rows
Args:
query (str): query to alter db
"""
kwargs["conn"].execute(query)
print("query executed")
return
@_db_connector_decorator
@validate_params({"df": [pd.core.frame.DataFrame], "table_name": [str]})
def upload_to_db(
self,
df,
table_name,
if_exists,
index=False,
index_label=None,
chunksize=None,
dtype=None,
method=None,
add_quotes=True,
**kwargs,
):
"""Uploads data to the database
Args:
df (pd.core.frame.DataFrame): dataframe to upload
table_name (str): name of table to upload into
if_exists (str): .to_sql arg
index (bool): .to_sql arg
index_label (str): .to_sql arg
chunksize (int): .to_sql arg
dtype (): .to_sql arg
method (): .to_sql arg
add_quotes (bool): whether to add quotes to df in ordder to insert into pandas df
Raises:
ValueError: _description_
Returns:
_type_: _description_
"""
# TODO add if statements on if_exists to add this in
# self.check_columns_align(df, table_name, dequote=add_quotes)
if add_quotes:
df.columns = add_column_wrappers(df)
df.to_sql(
table_name,
con=kwargs["conn"],
if_exists=if_exists,
index=index,
index_label=index_label,
chunksize=chunksize,
dtype=dtype,
method=method,
)
print("upload completed")
return
@validate_params({"table_name": [str]})
def query_column_names(self, table_name, dequote=True):
"""queries postgress DB to get the column names from a specified table
Args:
table_name (str): name of table to query
Returns:
(list): list of column names in table
"""
column_name_query = (
"SELECT column_name FROM information_schema.columns where table_name = '"
+ table_name
+ "' order by column_name"
)
if dequote:
column_names = (
self.query(column_name_query)["column_name"]
.apply(lambda x: x.replace('"', ""))
.values
)
else:
column_names = self.query(column_name_query)["column_name"].values
return column_names
@validate_params({"df": [pd.core.frame.DataFrame], "table_name": [str]})
def check_columns_align(self, df, table_name, dequote=True):
"""Checks names in local df matches names in postgres table
Args:
df (pd.core.frame.DataFrame): local df
table_name (str): name of table in pandas df
"""
db_cols = set(self.query_column_names(table_name, dequote=dequote))
df_cols = set(df.columns)
db_cols_not_in_df = db_cols.difference(df_cols)
df_cols_not_in_db = df_cols.difference(db_cols)
if len(db_cols_not_in_df) + len(df_cols_not_in_db) != 0:
raise ValueError(
f"The following columns {db_cols_not_in_df} are in the db but not in the df \n The following columns {df_cols_not_in_db} are in the df but not in the db"
)
else:
print("All columns align!")
return | /rowan_ds_tools-0.14.tar.gz/rowan_ds_tools-0.14/rowan_ds_tools/io/db_helper.py | 0.636692 | 0.278407 | db_helper.py | pypi |
from abc import ABC
from abc import abstractmethod
from collections.abc import Iterable
import functools
import math
from inspect import signature
from numbers import Integral
from numbers import Real
import operator
import warnings
import numpy as np
from scipy.sparse import issparse
from scipy.sparse import csr_matrix
"""Parameter validation library taken from sklearn
"""
def validate_parameter_constraints(parameter_constraints, params, caller_name):
"""Validate types and values of given parameters.
Parameters
----------
parameter_constraints : dict or {"no_validation"}
If "no_validation", validation is skipped for this parameter.
If a dict, it must be a dictionary `param_name: list of constraints`.
A parameter is valid if it satisfies one of the constraints from the list.
Constraints can be:
- an Interval object, representing a continuous or discrete range of numbers
- the string "array-like"
- the string "sparse matrix"
- the string "random_state"
- callable
- None, meaning that None is a valid value for the parameter
- any type, meaning that any instance of this type is valid
- a StrOptions object, representing a set of strings
- the string "boolean"
- the string "verbose"
- the string "cv_object"
- the string "missing_values"
- a HasMethods object, representing method(s) an object must have
- a Hidden object, representing a constraint not meant to be exposed to the user
params : dict
A dictionary `param_name: param_value`. The parameters to validate against the
constraints.
caller_name : str
The name of the estimator or function or method that called this function.
"""
if len(set(parameter_constraints) - set(params)) != 0:
raise ValueError(
f"The parameter constraints {list(parameter_constraints)}"
" contain unexpected parameters"
f" {set(parameter_constraints) - set(params)}"
)
for param_name, param_val in params.items():
# We allow parameters to not have a constraint so that third party estimators
# can inherit from sklearn estimators without having to necessarily use the
# validation tools.
if param_name not in parameter_constraints:
continue
constraints = parameter_constraints[param_name]
if constraints == "no_validation":
continue
constraints = [make_constraint(constraint) for constraint in constraints]
for constraint in constraints:
if constraint.is_satisfied_by(param_val):
# this constraint is satisfied, no need to check further.
break
else:
# No constraint is satisfied, raise with an informative message.
# Ignore constraints that we don't want to expose in the error message,
# i.e. options that are for internal purpose or not officially supported.
constraints = [
constraint for constraint in constraints if not constraint.hidden
]
if len(constraints) == 1:
constraints_str = f"{constraints[0]}"
else:
constraints_str = (
f"{', '.join([str(c) for c in constraints[:-1]])} or"
f" {constraints[-1]}"
)
raise ValueError(
f"The {param_name!r} parameter of {caller_name} must be"
f" {constraints_str}. Got {param_val!r} instead."
)
def make_constraint(constraint):
"""Convert the constraint into the appropriate Constraint object.
Parameters
----------
constraint : object
The constraint to convert.
Returns
-------
constraint : instance of _Constraint
The converted constraint.
"""
if isinstance(constraint, str) and constraint == "array-like":
return _ArrayLikes()
if isinstance(constraint, str) and constraint == "sparse matrix":
return _SparseMatrices()
if isinstance(constraint, str) and constraint == "random_state":
return _RandomStates()
if constraint is callable:
return _Callables()
if constraint is None:
return _NoneConstraint()
if isinstance(constraint, type):
return _InstancesOf(constraint)
if isinstance(constraint, (Interval, StrOptions, HasMethods)):
return constraint
if isinstance(constraint, str) and constraint == "boolean":
return _Booleans()
if isinstance(constraint, str) and constraint == "verbose":
return _VerboseHelper()
if isinstance(constraint, str) and constraint == "missing_values":
return _MissingValues()
if isinstance(constraint, str) and constraint == "cv_object":
return _CVObjects()
if isinstance(constraint, Hidden):
constraint = make_constraint(constraint.constraint)
constraint.hidden = True
return constraint
raise ValueError(f"Unknown constraint type: {constraint}")
def validate_params(parameter_constraints):
"""Decorator to validate types and values of functions and methods.
Parameters
----------
parameter_constraints : dict
A dictionary `param_name: list of constraints`. See the docstring of
`validate_parameter_constraints` for a description of the accepted constraints.
Note that the *args and **kwargs parameters are not validated and must not be
present in the parameter_constraints dictionary.
Returns
-------
decorated_function : function or method
The decorated function.
"""
def decorator(func):
# The dict of parameter constraints is set as an attribute of the function
# to make it possible to dynamically introspect the constraints for
# automatic testing.
setattr(func, "_skl_parameter_constraints", parameter_constraints)
@functools.wraps(func)
def wrapper(*args, **kwargs):
func_sig = signature(func)
# Map *args/**kwargs to the function signature
params = func_sig.bind(*args, **kwargs)
params.apply_defaults()
# ignore self/cls and positional/keyword markers
to_ignore = [
p.name
for p in func_sig.parameters.values()
if p.kind in (p.VAR_POSITIONAL, p.VAR_KEYWORD)
]
to_ignore += ["self", "cls"]
params = {k: v for k, v in params.arguments.items() if k not in to_ignore}
validate_parameter_constraints(
parameter_constraints, params, caller_name=func.__qualname__
)
return func(*args, **kwargs)
return wrapper
return decorator
class _Constraint(ABC):
"""Base class for the constraint objects."""
def __init__(self):
self.hidden = False
@abstractmethod
def is_satisfied_by(self, val):
"""Whether or not a value satisfies the constraint.
Parameters
----------
val : object
The value to check.
Returns
-------
is_satisfied : bool
Whether or not the constraint is satisfied by this value.
"""
@abstractmethod
def __str__(self):
"""A human readable representational string of the constraint."""
class _InstancesOf(_Constraint):
"""Constraint representing instances of a given type.
Parameters
----------
type : type
The valid type.
"""
def __init__(self, type):
super().__init__()
self.type = type
def _type_name(self, t):
"""Convert type into human readable string."""
module = t.__module__
qualname = t.__qualname__
if module == "builtins":
return qualname
elif t == Real:
return "float"
elif t == Integral:
return "int"
return f"{module}.{qualname}"
def is_satisfied_by(self, val):
return isinstance(val, self.type)
def __str__(self):
return f"an instance of {self._type_name(self.type)!r}"
class _NoneConstraint(_Constraint):
"""Constraint representing the None singleton."""
def is_satisfied_by(self, val):
return val is None
def __str__(self):
return "None"
class _NanConstraint(_Constraint):
"""Constraint representing the indicator `np.nan`."""
def is_satisfied_by(self, val):
return isinstance(val, Real) and math.isnan(val)
def __str__(self):
return "numpy.nan"
class _PandasNAConstraint(_Constraint):
"""Constraint representing the indicator `pd.NA`."""
def is_satisfied_by(self, val):
try:
import pandas as pd
return isinstance(val, type(pd.NA)) and pd.isna(val)
except ImportError:
return False
def __str__(self):
return "pandas.NA"
class StrOptions(_Constraint):
"""Constraint representing a set of strings.
Parameters
----------
options : set of str
The set of valid strings.
deprecated : set of str or None, default=None
A subset of the `options` to mark as deprecated in the repr of the constraint.
"""
@validate_params({"options": [set], "deprecated": [set, None]})
def __init__(self, options, deprecated=None):
super().__init__()
self.options = options
self.deprecated = deprecated or set()
if self.deprecated - self.options:
raise ValueError("The deprecated options must be a subset of the options.")
def is_satisfied_by(self, val):
return isinstance(val, str) and val in self.options
def _mark_if_deprecated(self, option):
"""Add a deprecated mark to an option if needed."""
option_str = f"{option!r}"
if option in self.deprecated:
option_str = f"{option_str} (deprecated)"
return option_str
def __str__(self):
options_str = (
f"{', '.join([self._mark_if_deprecated(o) for o in self.options])}"
)
return f"a str among {{{options_str}}}"
class Interval(_Constraint):
"""Constraint representing a typed interval.
Parameters
----------
type : {numbers.Integral, numbers.Real}
The set of numbers in which to set the interval.
left : float or int or None
The left bound of the interval. None means left bound is -∞.
right : float, int or None
The right bound of the interval. None means right bound is +∞.
closed : {"left", "right", "both", "neither"}
Whether the interval is open or closed. Possible choices are:
- `"left"`: the interval is closed on the left and open on the right.
It is equivalent to the interval `[ left, right )`.
- `"right"`: the interval is closed on the right and open on the left.
It is equivalent to the interval `( left, right ]`.
- `"both"`: the interval is closed.
It is equivalent to the interval `[ left, right ]`.
- `"neither"`: the interval is open.
It is equivalent to the interval `( left, right )`.
Notes
-----
Setting a bound to `None` and setting the interval closed is valid. For instance,
strictly speaking, `Interval(Real, 0, None, closed="both")` corresponds to
`[0, +∞) U {+∞}`.
"""
@validate_params(
{
"type": [type],
"left": [Integral, Real, None],
"right": [Integral, Real, None],
"closed": [StrOptions({"left", "right", "both", "neither"})],
}
)
def __init__(self, type, left, right, *, closed):
super().__init__()
self.type = type
self.left = left
self.right = right
self.closed = closed
self._check_params()
def _check_params(self):
if self.type is Integral:
suffix = "for an interval over the integers."
if self.left is not None and not isinstance(self.left, Integral):
raise TypeError(f"Expecting left to be an int {suffix}")
if self.right is not None and not isinstance(self.right, Integral):
raise TypeError(f"Expecting right to be an int {suffix}")
if self.left is None and self.closed in ("left", "both"):
raise ValueError(
f"left can't be None when closed == {self.closed} {suffix}"
)
if self.right is None and self.closed in ("right", "both"):
raise ValueError(
f"right can't be None when closed == {self.closed} {suffix}"
)
if self.right is not None and self.left is not None and self.right <= self.left:
raise ValueError(
f"right can't be less than left. Got left={self.left} and "
f"right={self.right}"
)
def __contains__(self, val):
if np.isnan(val):
return False
left_cmp = operator.lt if self.closed in ("left", "both") else operator.le
right_cmp = operator.gt if self.closed in ("right", "both") else operator.ge
left = -np.inf if self.left is None else self.left
right = np.inf if self.right is None else self.right
if left_cmp(val, left):
return False
if right_cmp(val, right):
return False
return True
def is_satisfied_by(self, val):
if not isinstance(val, self.type):
return False
return val in self
def __str__(self):
type_str = "an int" if self.type is Integral else "a float"
left_bracket = "[" if self.closed in ("left", "both") else "("
left_bound = "-inf" if self.left is None else self.left
right_bound = "inf" if self.right is None else self.right
right_bracket = "]" if self.closed in ("right", "both") else ")"
return (
f"{type_str} in the range "
f"{left_bracket}{left_bound}, {right_bound}{right_bracket}"
)
class _ArrayLikes(_Constraint):
"""Constraint representing array-likes"""
def is_satisfied_by(self, val):
return _is_arraylike_not_scalar(val)
def __str__(self):
return "an array-like"
class _SparseMatrices(_Constraint):
"""Constraint representing sparse matrices."""
def is_satisfied_by(self, val):
return issparse(val)
def __str__(self):
return "a sparse matrix"
class _Callables(_Constraint):
"""Constraint representing callables."""
def is_satisfied_by(self, val):
return callable(val)
def __str__(self):
return "a callable"
class _RandomStates(_Constraint):
"""Constraint representing random states.
Convenience class for
[Interval(Integral, 0, 2**32 - 1, closed="both"), np.random.RandomState, None]
"""
def __init__(self):
super().__init__()
self._constraints = [
Interval(Integral, 0, 2**32 - 1, closed="both"),
_InstancesOf(np.random.RandomState),
_NoneConstraint(),
]
def is_satisfied_by(self, val):
return any(c.is_satisfied_by(val) for c in self._constraints)
def __str__(self):
return (
f"{', '.join([str(c) for c in self._constraints[:-1]])} or"
f" {self._constraints[-1]}"
)
class _Booleans(_Constraint):
"""Constraint representing boolean likes.
Convenience class for
[bool, np.bool_, Integral (deprecated)]
"""
def __init__(self):
super().__init__()
self._constraints = [
_InstancesOf(bool),
_InstancesOf(np.bool_),
_InstancesOf(Integral),
]
def is_satisfied_by(self, val):
# TODO(1.4) remove support for Integral.
if isinstance(val, Integral) and not isinstance(val, bool):
warnings.warn(
"Passing an int for a boolean parameter is deprecated in version 1.2 "
"and won't be supported anymore in version 1.4.",
FutureWarning,
)
return any(c.is_satisfied_by(val) for c in self._constraints)
def __str__(self):
return (
f"{', '.join([str(c) for c in self._constraints[:-1]])} or"
f" {self._constraints[-1]}"
)
class _VerboseHelper(_Constraint):
"""Helper constraint for the verbose parameter.
Convenience class for
[Interval(Integral, 0, None, closed="left"), bool, numpy.bool_]
"""
def __init__(self):
super().__init__()
self._constraints = [
Interval(Integral, 0, None, closed="left"),
_InstancesOf(bool),
_InstancesOf(np.bool_),
]
def is_satisfied_by(self, val):
return any(c.is_satisfied_by(val) for c in self._constraints)
def __str__(self):
return (
f"{', '.join([str(c) for c in self._constraints[:-1]])} or"
f" {self._constraints[-1]}"
)
class _MissingValues(_Constraint):
"""Helper constraint for the `missing_values` parameters.
Convenience for
[
Integral,
Interval(Real, None, None, closed="both"),
str,
None,
_NanConstraint(),
_PandasNAConstraint(),
]
"""
def __init__(self):
super().__init__()
self._constraints = [
_InstancesOf(Integral),
# we use an interval of Real to ignore np.nan that has its own constraint
Interval(Real, None, None, closed="both"),
_InstancesOf(str),
_NoneConstraint(),
_NanConstraint(),
_PandasNAConstraint(),
]
def is_satisfied_by(self, val):
return any(c.is_satisfied_by(val) for c in self._constraints)
def __str__(self):
return (
f"{', '.join([str(c) for c in self._constraints[:-1]])} or"
f" {self._constraints[-1]}"
)
class HasMethods(_Constraint):
"""Constraint representing objects that expose specific methods.
It is useful for parameters following a protocol and where we don't want to impose
an affiliation to a specific module or class.
Parameters
----------
methods : str or list of str
The method(s) that the object is expected to expose.
"""
@validate_params({"methods": [str, list]})
def __init__(self, methods):
super().__init__()
if isinstance(methods, str):
methods = [methods]
self.methods = methods
def is_satisfied_by(self, val):
return all(callable(getattr(val, method, None)) for method in self.methods)
def __str__(self):
if len(self.methods) == 1:
methods = f"{self.methods[0]!r}"
else:
methods = (
f"{', '.join([repr(m) for m in self.methods[:-1]])} and"
f" {self.methods[-1]!r}"
)
return f"an object implementing {methods}"
class _IterablesNotString(_Constraint):
"""Constraint representing iterables that are not strings."""
def is_satisfied_by(self, val):
return isinstance(val, Iterable) and not isinstance(val, str)
def __str__(self):
return "an iterable"
class _CVObjects(_Constraint):
"""Constraint representing cv objects.
Convenient class for
[
Interval(Integral, 2, None, closed="left"),
HasMethods(["split", "get_n_splits"]),
_IterablesNotString(),
None,
]
"""
def __init__(self):
super().__init__()
self._constraints = [
Interval(Integral, 2, None, closed="left"),
HasMethods(["split", "get_n_splits"]),
_IterablesNotString(),
_NoneConstraint(),
]
def is_satisfied_by(self, val):
return any(c.is_satisfied_by(val) for c in self._constraints)
def __str__(self):
return (
f"{', '.join([str(c) for c in self._constraints[:-1]])} or"
f" {self._constraints[-1]}"
)
class Hidden:
"""Class encapsulating a constraint not meant to be exposed to the user.
Parameters
----------
constraint : str or _Constraint instance
The constraint to be used internally.
"""
def __init__(self, constraint):
self.constraint = constraint
def generate_invalid_param_val(constraint, constraints=None):
"""Return a value that does not satisfy the constraint.
Raises a NotImplementedError if there exists no invalid value for this constraint.
This is only useful for testing purpose.
Parameters
----------
constraint : _Constraint instance
The constraint to generate a value for.
constraints : list of _Constraint instances or None, default=None
The list of all constraints for this parameter. If None, the list only
containing `constraint` is used.
Returns
-------
val : object
A value that does not satisfy the constraint.
"""
if isinstance(constraint, StrOptions):
return f"not {' or '.join(constraint.options)}"
if isinstance(constraint, _MissingValues):
return np.array([1, 2, 3])
if isinstance(constraint, _VerboseHelper):
return -1
if isinstance(constraint, HasMethods):
return type("HasNotMethods", (), {})()
if isinstance(constraint, _IterablesNotString):
return "a string"
if isinstance(constraint, _CVObjects):
return "not a cv object"
if not isinstance(constraint, Interval):
raise NotImplementedError
# constraint is an interval
constraints = [constraint] if constraints is None else constraints
return _generate_invalid_param_val_interval(constraint, constraints)
def _generate_invalid_param_val_interval(interval, constraints):
"""Return a value that does not satisfy an interval constraint.
Generating an invalid value for an integer interval depends on the other constraints
since an int is a real, meaning that it can be valid for a real interval.
Assumes that there can be at most 2 interval constraints: one integer interval
and/or one real interval.
This is only useful for testing purpose.
Parameters
----------
interval : Interval instance
The interval to generate a value for.
constraints : list of _Constraint instances
The list of all constraints for this parameter.
Returns
-------
val : object
A value that does not satisfy the interval constraint.
"""
if interval.type is Real:
# generate a non-integer value such that it can't be valid even if there's also
# an integer interval constraint.
if interval.left is None and interval.right is None:
if interval.closed in ("left", "neither"):
return np.inf
elif interval.closed in ("right", "neither"):
return -np.inf
else:
raise NotImplementedError
if interval.left is not None:
return np.floor(interval.left) - 0.5
else: # right is not None
return np.ceil(interval.right) + 0.5
else: # interval.type is Integral
if interval.left is None and interval.right is None:
raise NotImplementedError
# We need to check if there's also a real interval constraint to generate a
# value that is not valid for any of the 2 interval constraints.
real_intervals = [
i for i in constraints if isinstance(i, Interval) and i.type is Real
]
real_interval = real_intervals[0] if real_intervals else None
if real_interval is None:
# Only the integer interval constraint -> easy
if interval.left is not None:
return interval.left - 1
else: # interval.right is not None
return interval.right + 1
# There's also a real interval constraint. Try to find a value left to both or
# right to both or in between them.
# redefine left and right bounds to be smallest and largest valid integers in
# both intervals.
int_left = interval.left
if int_left is not None and interval.closed in ("right", "neither"):
int_left = int_left + 1
int_right = interval.right
if int_right is not None and interval.closed in ("left", "neither"):
int_right = int_right - 1
real_left = real_interval.left
if real_interval.left is not None:
real_left = int(np.ceil(real_interval.left))
if real_interval.closed in ("right", "neither"):
real_left = real_left + 1
real_right = real_interval.right
if real_interval.right is not None:
real_right = int(np.floor(real_interval.right))
if real_interval.closed in ("left", "neither"):
real_right = real_right - 1
if int_left is not None and real_left is not None:
# there exists an int left to both intervals
return min(int_left, real_left) - 1
if int_right is not None and real_right is not None:
# there exists an int right to both intervals
return max(int_right, real_right) + 1
if int_left is not None:
if real_right is not None and int_left - real_right >= 2:
# there exists an int between the 2 intervals
return int_left - 1
else:
raise NotImplementedError
else: # int_right is not None
if real_left is not None and real_left - int_right >= 2:
# there exists an int between the 2 intervals
return int_right + 1
else:
raise NotImplementedError
def generate_valid_param(constraint):
"""Return a value that does satisfy a constraint.
This is only useful for testing purpose.
Parameters
----------
constraint : Constraint instance
The constraint to generate a value for.
Returns
-------
val : object
A value that does satisfy the constraint.
"""
if isinstance(constraint, _ArrayLikes):
return np.array([1, 2, 3])
if isinstance(constraint, _SparseMatrices):
return csr_matrix([[0, 1], [1, 0]])
if isinstance(constraint, _RandomStates):
return np.random.RandomState(42)
if isinstance(constraint, _Callables):
return lambda x: x
if isinstance(constraint, _NoneConstraint):
return None
if isinstance(constraint, _InstancesOf):
return constraint.type()
if isinstance(constraint, _Booleans):
return True
if isinstance(constraint, _VerboseHelper):
return 1
if isinstance(constraint, _MissingValues):
return np.nan
if isinstance(constraint, HasMethods):
return type(
"ValidHasMethods", (), {m: lambda self: None for m in constraint.methods}
)()
if isinstance(constraint, _IterablesNotString):
return [1, 2, 3]
if isinstance(constraint, _CVObjects):
return 5
if isinstance(constraint, StrOptions):
for option in constraint.options:
return option
if isinstance(constraint, Interval):
interval = constraint
if interval.left is None and interval.right is None:
return 0
elif interval.left is None:
return interval.right - 1
elif interval.right is None:
return interval.left + 1
else:
if interval.type is Real:
return (interval.left + interval.right) / 2
else:
return interval.left + 1
raise ValueError(f"Unknown constraint type: {constraint}")
def _is_arraylike_not_scalar(array):
"""Return True if array is array-like and not a scalar"""
return _is_arraylike(array) and not np.isscalar(array)
def _is_arraylike(x):
"""Returns whether the input is array-like."""
return hasattr(x, "__len__") or hasattr(x, "shape") or hasattr(x, "__array__") | /rowan_ds_tools-0.14.tar.gz/rowan_ds_tools-0.14/rowan_ds_tools/utils/_param_validation.py | 0.912165 | 0.450722 | _param_validation.py | pypi |
import logging
import socket
from typing import Optional, Tuple
import mysql.connector
from mysql.connector import errorcode
from mysql.connector.pooling import MySQLConnectionPool, PooledMySQLConnection
from starlette import status
from starlette.exceptions import HTTPException
from rowantree.auth.sdk import User
from rowantree.contracts import BaseModel
from ...contracts.duplicate_key_error import DuplicateKeyError
from .incorrect_row_count_error import IncorrectRowCountError
class DBDAO(BaseModel):
"""
Database DAO
Attributes
----------
cnxpool: Any
MySQL Connection Pool
"""
cnxpool: MySQLConnectionPool
# pylint: disable=duplicate-code
def _call_proc(self, name: str, args: list, debug: bool = False) -> Optional[list[Tuple]]:
"""
Perform a stored procedure call.
Parameters
----------
name: str
The name of the stored procedure to call.
args: list
The arguments to pass to the stored procedure.
debug: bool
Whether to log debug details about the call.
Returns
-------
results: Optional[list[Tuple]]
An optional list of tuples (rows) from the call.
"""
if debug:
logging.debug("[DAO] [Stored Proc Call Details] Name: {%s}, Arguments: {%s}", name, args)
rows: Optional[list[Tuple]] = None
cnx: Optional[PooledMySQLConnection] = None
try:
cnx = self.cnxpool.get_connection()
cursor = cnx.cursor()
cursor.callproc(name, args)
for result in cursor.stored_results():
rows = result.fetchall()
cursor.close()
cnx.close()
except socket.error as error:
logging.error("socket.error")
logging.error(error)
if cnx:
cnx.close()
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Internal Server Error"
) from error
except mysql.connector.Error as error:
logging.error("mysql.connector.Error: {%i}", error.errno)
logging.error(str(error))
if cnx:
cnx.close()
if error.errno == errorcode.ER_ACCESS_DENIED_ERROR:
logging.error("Something is wrong with your user name or password")
elif error.errno == errorcode.ER_BAD_DB_ERROR:
logging.error("Database does not exist")
elif error.errno == errorcode.ER_DUP_ENTRY:
logging.error("Duplicate key")
raise DuplicateKeyError(str(error)) from error
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Internal Server Error"
) from error
except Exception as error:
logging.error("error")
# All other uncaught exception types
logging.error(str(error))
if cnx:
cnx.close()
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Internal Server Error"
) from error
if debug:
logging.debug("[DAO] [Stored Proc Call Details] Returning:")
logging.debug(rows)
return rows
def get_user(self, username: Optional[str] = None, guid: Optional[str] = None) -> User:
"""
Get User (From Database) Using `username` first, else `guid`. At least one must be supplied.
Parameters
----------
username: Optional[str]
username
guid: Optional[str]
user guid
Returns
-------
user: User
User (from database)
"""
if username is None and guid is None:
logging.debug("get_user called without username or a guid, one is required")
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR)
args: list[str] = [username]
proc_name: str = "getUserByUsername"
if username is None:
args = [guid]
proc_name: str = "getUserByGUID"
rows: Optional[list[Tuple]] = self._call_proc(proc_name, args, True)
if rows is None or len(rows) != 1:
raise IncorrectRowCountError(f"Result count was not exactly one. Received: {rows}")
user: tuple = rows[0]
is_disabled: bool = True
if user[6] == 0:
is_disabled = False
is_admin: bool = False
if user[7] == 1:
is_admin = True
return User(
username=user[2], guid=user[1], email=user[3], hashed_password=user[4], disabled=is_disabled, admin=is_admin
)
def create_user(self, user: User) -> User:
"""
Creates a new user within the database.
Parameters
----------
user: User
User object to create.
Returns
-------
user: User
The requested `User` but with the guid assigned.
"""
# The inbound User will be missing a guid.
# This is auto assigned on the database side and returned by the call.
args: list[str] = [user.username, user.email, user.hashed_password, user.disabled, user.admin]
proc_name: str = "createUser"
rows: Optional[list[Tuple]] = self._call_proc(proc_name, args, True)
if rows is None or len(rows) != 1:
raise IncorrectRowCountError(f"Result count was not exactly one. Received: {rows}")
user_guid: str = rows[0][0]
user.guid = user_guid
return user | /rowantree.auth.service-0.13.0-py3-none-any.whl/rowantree/auth/service/services/db/dao.py | 0.86056 | 0.157396 | dao.py | pypi |
import os
from typing import Optional
from .environment_variable_not_found_error import EnvironmentVariableNotFoundError
def demand_env_var(name: str) -> str:
"""
Returns an environment variable as a string, or throws an exception.
Parameters
----------
name: str
The name of the environment variable.
Returns
-------
The environment variables value as a string.
"""
if name not in os.environ:
raise EnvironmentVariableNotFoundError(f"Environment variable ({name}) not found")
return os.environ[name]
def get_env_var(name: str) -> Optional[str]:
"""
Returns an environment variable as a string, otherwise `None` if it does not exist.
Parameters
----------
name: str
The name of the environment variable.
Returns
-------
The environment variables value as a string, or `None` if it does not exist.
"""
if name not in os.environ:
return None
return os.environ[name]
def demand_env_var_as_int(name: str) -> int:
"""
Returns an environment variable as an int, or throws an exception.
Parameters
----------
name: str
The name of the environment variable.
Returns
-------
The environment variables value as an int.
"""
return int(demand_env_var(name=name))
def demand_env_var_as_float(name: str) -> float:
"""
Returns an environment variable as a float, or throws an exception.
Parameters
----------
name: str
The name of the environment variable.
Returns
-------
The environment variables value as a float.
"""
return float(demand_env_var(name=name))
def demand_env_var_as_bool(name: str) -> bool:
"""
Returns an environment variable as a bool, or throws an exception.
Parameters
----------
name: str
The name of the environment variable.
Returns
-------
The environment variables value as a bool.
"""
value_str: str = demand_env_var(name=name).lower()
if value_str in ("true", "1"):
return True
if value_str in ("false", "0"):
return False
raise EnvironmentVariableNotFoundError(f"Environment variable ({name}) not boolean and can not be loaded") | /rowantree.common.sdk-1.0.0.tar.gz/rowantree.common.sdk-1.0.0/src/rowantree/common/sdk/config/environment.py | 0.921816 | 0.504211 | environment.py | pypi |
import json
import random
from pathlib import Path
from typing import Any, Optional
from pydantic import ValidationError
from rowantree.contracts import StoreType, UserEvent, UserStore
from ..abstract.abstract_loremaster import AbstractLoremaster
class WorldStoryTeller(AbstractLoremaster):
"""
The Story Teller
This class handles world encounters.
"""
MAX_ENCOUNTER_TRIES = 10
events: list[UserEvent] = []
def __init__(self, **data: Any):
super().__init__(**data)
with open(file=(Path(__file__).parent / "events.json").resolve(), mode="r", encoding="utf-8") as file:
global_events_dict = json.load(file)
for event_dict in global_events_dict["events"]:
try:
event: UserEvent = UserEvent.parse_obj(event_dict)
self.events.append(event)
except ValidationError as error:
print(event_dict)
raise error
def generate_event(self, user_population: int, user_stores: dict[StoreType, UserStore]) -> Optional[UserEvent]:
"""
Generates a world event (encounter).
Parameters
----------
user_population: UserPopulation
The target user population.
user_stores: UserStores
The target user stores.
Returns
-------
outbound_event: Optional[UserEvent]
An optional encounter for the target user.
"""
num_events: int = len(self.events)
requirement_check: bool = False
counter: int = 0
new_event: Optional[UserEvent] = None
while requirement_check is False:
counter += 1
event_index = random.randint(1, num_events) - 1
new_event = self.events[event_index].copy()
# check requirements
for requirement in new_event.requirements:
if requirement == "population":
min_required_pop = new_event.requirements[requirement]
# logging.debug('reported user population: ' + str(user_population))
if user_population >= min_required_pop:
requirement_check = True
else:
# assume it is a store - get the current amount of the store for the user
min_required_store = new_event.requirements[requirement]
if requirement in user_stores:
if user_stores[requirement].amount >= min_required_store:
requirement_check = True
# bail out if we've reached the max, no encounters this time
if counter >= self.MAX_ENCOUNTER_TRIES:
new_event = None
requirement_check = True
if new_event is None:
return None
# remove the requirements stanza before we send to over to the client
new_event.requirements = {}
return new_event | /rowantree.content.service-0.20.0.tar.gz/rowantree.content.service-0.20.0/src/rowantree/content/service/common/world/storyteller.py | 0.770896 | 0.194196 | storyteller.py | pypi |
from starlette import status
from starlette.exceptions import HTTPException
from rowantree.contracts import (
FeatureType,
IncomeSourceType,
StoreType,
UserFeatureState,
UserIncome,
UserNotification,
UserState,
UserStore,
)
from ..services.db.incorrect_row_count_error import IncorrectRowCountError
from .abstract_controller import AbstractController
class UserStateGetController(AbstractController):
"""
User State Get Controller
Gets the user game state.
Methods
-------
execute(self, user_guid: str) -> UserState
Executes the command.
"""
def execute(self, user_guid: str) -> UserState:
"""
Gets the user game state.
Parameters
----------
user_guid: str
The target user guid.
Returns
-------
user_state: UserState
The user state object.
"""
try:
# User Game State
active: int = self.dao.user_active_state_get(user_guid=user_guid)
# User Stores (Inventory)
stores: dict[StoreType, UserStore] = self.dao.user_stores_get(user_guid=user_guid)
# User Income
incomes: dict[IncomeSourceType, UserIncome] = self.dao.user_income_get(user_guid=user_guid)
# Features
features: set[FeatureType] = self.dao.user_features_get(user_guid=user_guid)
# Population
population: int = self.dao.user_population_by_guid_get(user_guid=user_guid)
# Active Feature Details and name
active_feature_state: UserFeatureState = self.dao.user_active_feature_state_details_get(user_guid=user_guid)
active_feature_state.name = self.dao.user_active_feature_get(user_guid=user_guid)
# Merchants
merchants: set[StoreType] = self.dao.user_merchant_transforms_get(user_guid=user_guid)
# Notifications
notifications: list[UserNotification] = self.dao.user_notifications_get(user_guid=user_guid)
except IncorrectRowCountError as error:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found") from error
user_state: UserState = UserState(
active=active,
stores=stores,
incomes=incomes,
features=features,
active_feature_state=active_feature_state,
population=population,
merchants=merchants,
notifications=notifications,
)
return user_state | /rowantree.game.service-0.23.0-py3-none-any.whl/rowantree/game/service/controllers/user_state_get.py | 0.74826 | 0.192103 | user_state_get.py | pypi |
import logging
import socket
from datetime import datetime
from typing import Optional, Tuple
import mysql.connector
from mysql.connector import IntegrityError, errorcode
from mysql.connector.pooling import MySQLConnectionPool, PooledMySQLConnection
from starlette import status
from starlette.exceptions import HTTPException
from rowantree.contracts import (
ActionQueue,
BaseModel,
FeatureDetailType,
FeatureType,
IncomeSourceType,
StoreType,
User,
UserEvent,
UserFeatureState,
UserIncome,
UserNotification,
UserStore,
)
from rowantree.game.service.sdk import UserIncomeSetRequest
from ...contracts.duplicate_key_error import DuplicateKeyError
from ...contracts.sql_exception_error import SqlExceptionError
from .incorrect_row_count_error import IncorrectRowCountError
class DBDAO(BaseModel):
"""
Database DAO
Attributes
----------
cnxpool: MySQLConnectionPool
MySQL Connection Pool
"""
cnxpool: MySQLConnectionPool
def merchant_transform_perform(self, user_guid: str, store_name: str) -> None:
"""
Perform a merchant transform.
Parameters
----------
user_guid: str
The target user guid.
store_name: str
The name of the store to perform the transform on.
"""
args: list = [user_guid, store_name]
self._call_proc("peformMerchantTransformByGUID", args)
def user_active_feature_get(self, user_guid: str) -> FeatureType:
"""
Gets user's active feature/location.
Parameters
----------
user_guid: str
The target user guid.
Returns
-------
user_feature: FeatureType
The active user feature.
"""
args: list = [
user_guid,
]
rows: list[Tuple[str]] = self._call_proc("getUserActiveFeatureByGUID", args)
if len(rows) != 1:
# User did not exist (received an empty tuple)
message: str = f"Result count was not exactly one. Received: {rows}"
logging.debug(message)
raise IncorrectRowCountError(message)
return FeatureType(rows[0][0])
def user_active_feature_state_details_get(self, user_guid: str) -> UserFeatureState:
"""
Get User Active Feature/Location Including Details.
Parameters
----------
user_guid: str
The target user guid.
Returns
-------
user_feature: UserFeatureState
The active user feature/location with details.
"""
args: list = [
user_guid,
]
rows: list[Tuple[str, Optional[str]]] = self._call_proc("getUserActiveFeatureStateDetailsByGUID", args)
if len(rows) != 1:
# User did not exist (received an empty tuple)
message: str = f"Result count was not exactly one. Received: {rows}"
logging.debug(message)
raise IncorrectRowCountError(message)
return UserFeatureState(details=FeatureDetailType(rows[0][0]), description=rows[0][1])
def users_active_get(self) -> set[str]:
"""
Get Active Users.
Returns
-------
active_user_guids: set[str]
A (unique) set of user guids which are active.
"""
active_user_guids: set[str] = set()
rows: list[Tuple] = self._call_proc("getActiveUsers", [])
for response_tuple in rows:
active_user_guids.add(response_tuple[0])
return active_user_guids
def user_active_state_get(self, user_guid: str) -> bool:
"""
Get user active state.
Parameters
----------
user_guid: str
The target user guid.
Returns
-------
user_active: UserActive
The user active state.
"""
args: list[str, int] = [
user_guid,
]
rows: list[Tuple[int]] = self._call_proc("getUserActivityStateByGUID", args)
if len(rows) != 1:
raise IncorrectRowCountError(f"Result count was not exactly one. Received: {rows}")
if rows[0][0] == 1:
return True
return False
def user_active_state_set(self, user_guid: str, active: bool) -> None:
"""
Set user's active state.
# TODO: the underlying calls need to provide more context on status of this call.
Parameters
----------
user_guid: str
The target user guid.
active: bool
The active state to set.
"""
args: list = [
user_guid,
]
if active:
proc = "setUserActiveByGUID"
else:
proc = "setUserInactiveByGUID"
self._call_proc(name=proc, args=args)
def user_create_by_guid(self, user_guid: str) -> User:
"""
Create a user.
TODO this returns nothing, needs more detail from the db.
Returns
-------
user: User
The created user.
"""
args = [user_guid]
try:
self._call_proc("createUserByGUID", args)
except (IntegrityError, DuplicateKeyError) as error:
message: str = f"User already exists: {user_guid}, {str(error)}"
logging.debug(message)
raise IncorrectRowCountError(message) from error
return User(guid=user_guid)
def user_delete(self, user_guid: str) -> None:
"""
Delete user.
TODO: the underlying calls need to provide more context on status of this call.
Parameters
----------
user_guid: str
The target user guid.
"""
args: list = [
user_guid,
]
self._call_proc("deleteUserByGUID", args)
def user_features_get(self, user_guid: str) -> set[FeatureType]:
"""
Get user features.
Parameters
----------
user_guid: str
The target user guid.
Returns
-------
user_features: UserFeatures
User features object.
"""
features: set[FeatureType] = set()
args: list = [
user_guid,
]
rows: list[Tuple[str]] = self._call_proc("getUserFeaturesByGUID", args)
if rows is None or len(rows) == 0:
# User does not exist ot had no features. However, it should not be
# possible to exist in the game world with without a feature state.
# Users are given a feature state on creation (the process is atomic).
# This should always be do to a non-existent user.
message: str = f"Result count was not exactly one. Received: {rows}"
logging.debug(message)
raise IncorrectRowCountError(message)
for row in rows:
name: str = row[0]
features.add(FeatureType(name))
return features
def user_income_get(self, user_guid: str) -> dict[IncomeSourceType, UserIncome]:
"""
Get user income sources
# TODO: This can not tell if there are no stores, or if the user just doesn't exist.
Parameters
----------
user_guid: str
The target user guid.
Returns
-------
user_incomes: dict[IncomeSourceType, UserIncome]
"""
income_sources: dict[IncomeSourceType, UserIncome] = {}
args: list[str] = [
user_guid,
]
rows: list[Tuple[int, str, Optional[str]]] = self._call_proc("getUserIncomeByGUID", args)
for row in rows:
income_sources[IncomeSourceType(row[1])] = UserIncome(
amount=row[0], name=IncomeSourceType(row[1]), description=row[2]
)
return income_sources
def user_income_set(self, user_guid: str, transaction: UserIncomeSetRequest) -> None:
"""
Set user income source.
TODO: This needs to return more detail on success / failure.
Parameters
----------
user_guid: str
The target user guid.
transaction: UserIncomeSetRequest
The user income set request.
"""
args = [user_guid, transaction.income_source_name, transaction.amount]
self._call_proc("deltaUserIncomeByNameAndGUID", args)
def user_merchant_transforms_get(self, user_guid: str) -> set[StoreType]:
"""
Get User merchant transforms [currently available].
Parameters
----------
user_guid: str
The target user guid.
Returns
-------
user_merchants: set[StoreType]
User merchants object.
"""
merchants: set[StoreType] = set()
args: list = [
user_guid,
]
rows: list[Tuple[str]] = self._call_proc("getUserMerchantTransformsByGUID", args)
for row in rows:
merchants.add(StoreType(row[0]))
return merchants
def user_notifications_get(self, user_guid: str) -> list[UserNotification]:
"""
Get User notifications.
Returns the most recent (new) user notifications.
Parameters
----------
user_guid: str
The target user guid.
Returns
-------
user_notifications: UserNotifications
New user notifications.
"""
notifications: list[UserNotification] = []
args: list = [
user_guid,
]
rows: list[Tuple[int, datetime, str]] = self._call_proc("getUserNotificationByGUID", args)
for row in rows:
notification: UserNotification = UserNotification(
index=row[0], timestamp=row[1], event=UserEvent.parse_raw(row[2])
)
notifications.append(notification)
return notifications
def user_population_by_guid_get(self, user_guid: str) -> int:
"""
Get user population (by GUID)
Parameters
----------
user_guid: str
The target user guid.
Returns
-------
user_population: int
User population size.
"""
rows: list[Tuple[int]] = self._call_proc(
"getUserPopulationByGUID",
[
user_guid,
],
)
if rows is None or len(rows) != 1:
message: str = f"Result count was not exactly one. Received: {rows}"
logging.debug(message)
raise IncorrectRowCountError(message)
return rows[0][0]
def user_stores_get(self, user_guid: str) -> dict[StoreType, UserStore]:
"""
Get user stores.
Parameters
----------
user_guid: str
The target user guid.
Returns
-------
user_stores: dict[StoreType, UserStore]
User Stores Object
"""
stores: dict[StoreType, UserStore] = {}
args: list[str, int] = [
user_guid,
]
rows: list[Tuple[str, Optional[str], int]] = self._call_proc("getUserStoresByGUID", args)
for row in rows:
stores[StoreType(row[0])] = UserStore(name=StoreType(row[0]), description=row[1], amount=row[2])
return stores
def user_transport(self, user_guid: str, location: str) -> UserFeatureState:
"""
Perform User Transport.
Parameters
----------
user_guid: str
The target user guid.
location: str
The name of the feature/location to transport the user to.
Returns
-------
user_feature: UserFeatureState
The active user feature state.
"""
args: list = [user_guid, location]
rows: list[Tuple[str, Optional[str]]] = self._call_proc("transportUserByGUID", args, True)
if len(rows) != 1:
# User did not exist (received an empty tuple)
message: str = f"Result count was not exactly one. Received: {rows}"
logging.debug(message)
raise IncorrectRowCountError(message)
return UserFeatureState(details=rows[0][0], description=rows[0][1])
# Utility functions
def process_action_queue(self, action_queue: ActionQueue) -> None:
"""
Process the provided action queue.
Parameters
----------
action_queue: ActionQueue
The action queue to process.
"""
for action in action_queue.queue:
self._call_proc(action.name, action.arguments)
# pylint: disable=duplicate-code
def _call_proc(self, name: str, args: list, debug: bool = False) -> Optional[list[Tuple]]:
"""
Perform a stored procedure call.
Parameters
----------
name: str
The name of the stored procedure to call.
args: list
The arguments to pass to the stored procedure.
debug: bool
Whether to log debug details about the call.
Returns
-------
results: Optional[list[Tuple]]
An optional list of tuples (rows) from the call.
"""
if debug:
logging.debug("[DAO] [Stored Proc Call Details] Name: {%s}, Arguments: {%s}", name, args)
rows: Optional[list[Tuple]] = None
cnx: Optional[PooledMySQLConnection] = None
try:
cnx = self.cnxpool.get_connection()
cursor = cnx.cursor()
cursor.callproc(name, args)
for result in cursor.stored_results():
rows = result.fetchall()
cursor.close()
cnx.close()
except socket.error as error:
logging.error("socket.error")
logging.error(error)
if cnx:
cnx.close()
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Internal Server Error"
) from error
except mysql.connector.Error as error:
logging.error("mysql.connector.Error: {%i}", error.errno)
logging.error(str(error))
if cnx:
cnx.close()
# pylint: disable=no-else-raise
if error.errno == errorcode.ER_ACCESS_DENIED_ERROR:
logging.error("Something is wrong with your user name or password")
raise SqlExceptionError("Bad username or password") from error
elif error.errno == errorcode.ER_BAD_DB_ERROR:
logging.error("Database does not exist")
raise SqlExceptionError("Database does not exist") from error
elif error.errno == errorcode.ER_DUP_ENTRY:
logging.error("Duplicate key")
raise DuplicateKeyError(str(error)) from error
raise SqlExceptionError(f"Unhandled SQL Exception: {str(error)}") from error
except Exception as error:
logging.error("error")
# All other uncaught exception types
logging.error(str(error))
if cnx:
cnx.close()
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Internal Server Error"
) from error
if debug:
logging.debug("[DAO] [Stored Proc Call Details] Returning:")
logging.debug(rows)
return rows | /rowantree.game.service-0.23.0-py3-none-any.whl/rowantree/game/service/services/db/dao.py | 0.762203 | 0.185947 | dao.py | pypi |
import copy
import random
from typing import Optional
from rowantree.contracts import UserPopulation, UserStore, UserStores
class StoryTeller:
MAX_ENCOUNTER_TRIES = 10
# pylint: disable=line-too-long
events = {
"global": [
{
"title": "a stranger arrives in the night",
"requirements": {"population": 0},
"reward": {"population": 1},
},
{
"title": "a weathered family takes up in one of the huts",
"requirements": {"population": 1},
"reward": {"population": 3},
},
{
"title": "a small group arrives, all dust and bones",
"requirements": {"population": 1},
"reward": {"population": 5},
},
{
"title": "a convoy lurches in, equal parts worry and hope",
"requirements": {"population": 1},
"reward": {"population": 6},
},
{
"title": "a half-feral and malnourished child is discovered huddled by the great tree",
"requirements": {"population": 1},
"reward": {"population": 1},
},
{
"title": "another lone wanderer comes into town, in tears to have found a place of sanctuary against the world",
"requirements": {"population": 1},
"reward": {"population": 1},
},
{
"title": "a fire rampages through one of the huts, destroying it.",
"requirements": {"population": 15},
"text": ["all residents in the hut perished in the fire."],
"curse": {"population": 10},
},
{
"title": "a terrible plague is fast spreading through the village.",
"requirements": {"population": 20},
"text": ["the nights are rent with screams.", "the only hope is a quick death."],
"curse": {"population": 15},
},
{
"title": "a sickness is spreading through the village.",
"requirements": {"population": 15},
"text": ["only a few die.", "the rest bury them."],
"curse": {"population": 10},
},
{"title": "some villagers are ill", "requirements": {"population": 6}, "curse": {"population": 3}},
{
"title": "A Beast Attack",
"requirements": {"population": 15},
"text": [
"a pack of snarling beasts pours out of the trees.",
"the fight is short and bloody, but the beasts are repelled.",
"the villagers retreat to mourn the dead.",
],
"notification": "wild beasts attack the villagers",
"reward": {"fur": 100, "meat": 100, "teeth": 10},
"curse": {"population": 10},
},
{
"title": "A Robot Attack",
"requirements": {"population": 5},
"text": [
"a dented and rattling robot rolls into view, sparks falling from lose wires as they arc against its frame.",
"a remnant from some ancient war.",
],
"notification": "a robot opens fire on the villagers",
"reward": {"gems": 1, "coins": 10},
"curse": {"population": 1},
},
{
"title": "A Ghoul Attack",
"requirements": {"population": 10},
"text": [
"the groans could be heard a few hours before they dragged themselves through the main part of the settlement",
"the awful smell, even worse those eyes",
"some of our own dead rose again, and had to be put to rest one final time.",
],
"notification": "a heard of ghouls wanders through the settlement",
"reward": {"gems": 1, "coins": 10, "fur": 100, "meat": 10, "teeth": 10},
"curse": {"population": 5},
},
{
"title": "The Forest Has Legs",
"requirements": {"population": 20},
"text": [
"maybe it was their time to swarm, or just the presence of the settlement",
"the forest came alive as they blanketed everything, assaulting and cocooning all those who fell to them",
"moarn not those who died, but those the spiders took away",
],
"notification": "the skittering as the spiders retreated back into the forest haunts the dreams of even the bravest of those who survived",
"reward": {"gems": 1, "coins": 10, "fur": 100, "meat": 10, "teeth": 10},
"curse": {"population": 10},
},
{
"title": "Raccoon Attack",
"requirements": {"population": 5},
"text": [
"Hissing and screaming the raccoon attacks",
"Wielding a pike, it attacked from atop its",
"majestic human mount.",
],
"notification": "",
"reward": {
"sulphur": 1,
"bait": 1,
"wood": 1,
"stone": 1,
"fur": 10,
"teeth": 10,
"meat": 10,
"cloth": 5,
"coins": 5,
"torch": 5,
"bone spear": 1,
},
"curse": {
"population": 2,
},
},
{
"title": "The Shock Wave",
"requirements": {"population": 1},
"text": [
"A great shock wave rolled over the town, breaking everything of questionable assembly.",
"A short time later, that awful sound followed, so loud some of us never fully recovered",
"our hearing.",
"Days later some refugees from that far off disaster arrived. Blisted, and burned.",
],
"notification": "hello? hello! I still cant hear anything, ugh.",
"reward": {"population": 20, "sulphur": 3, "coins": 20, "gems": 10, "medicine": 5},
"curse": {
"population": 5,
"sulphur": 2,
"bait": 5,
"wood": 5,
"stone": 5,
"fur": 3,
"teeth": 2,
"meat": 5,
"meatpie": 5,
"cured meat": 5,
"leather": 1,
"iron": 1,
"steel": 1,
"coal": 5,
"scales": 1,
"cloth": 3,
"coins": 5,
"gems": 1,
"charm": 1,
"torch": 5,
"medicine": 5,
"seed": 5,
"crops": 10,
"bone spear": 5,
"bayonet": 2,
"bolas": 5,
"bullets": 5,
"iron sword": 1,
"steel sword": 1,
"leather armour": 1,
"iron armour": 1,
"steel armour": 1,
"rifle": 1,
"grenade": 2,
},
},
{
"title": "A Quiet Death",
"requirements": {"population": 5},
"text": ["All trails lead to the meadow at the end of the forest."],
"curse": {"population": 1},
},
{
"title": "Bait Rot",
"requirements": {"bait": 10000},
"text": ["the bait has gone bad."],
"curse": {"bait": 10000},
},
{
"title": "Wet Store Houses",
"requirements": {"population": 200},
"text": ["some of the store houses had leaky roofs"],
"curse": {"meat": 10000, "meatpie": 10000, "cured meat": 10000, "seed": 10000, "crops": 10000},
},
{
"title": "Kidnapping",
"requirements": {"population": 1},
"text": ["a local street urchin has been reported missing."],
"curse": {"population": 1},
},
{
"title": "Kidnapping of Two",
"requirements": {"population": 2},
"text": ["a local family looses children"],
"curse": {"population": 2},
},
{
"title": "Slaver Attack",
"requirements": {"population": 30},
"text": ["a group of slavers attack early in the morning."],
"curse": {"population": 30},
},
{
"title": "Slaver Raid",
"requirements": {"population": 100},
"text": ["a group of slavers raid in the middle of the night."],
"curse": {"population": 100},
},
{
"title": "Raccon Spy",
"requirements": {"population": 100},
"text": [
"it was on the outskirts for days, it kept coming back",
"after being chased off. we knew it was trouble.",
],
"curse": {
"bait": 5000,
"meat": 10000,
"meatpie": 5000,
"cured meat": 50000,
"cloth": 1000,
"coins": 1000,
"gems": 200,
"charm": 10,
"seed": 1000,
"crops": 10000,
"bone spear": 5000,
},
},
{
"title": "Fire At The Lumber Yard",
"requirements": {"wood": 10000},
"text": ["it burned with terrible bright light that night"],
"curse": {"population": 10, "wood": 10000},
},
{
"title": "Radioactive Artifact",
"requirements": {"population": 100},
"text": ["such a small thing.", "so innocent looking and beautiful.", "warm even, to the touch."],
"reward": {"charm": 2},
"curse": {"population": 100},
},
{
"title": "dazed and confused, a ragged women emerges from the dark forest",
"requirements": {"population": 1},
"reward": {"population": 1},
},
]
}
def generate_event(self, user_population: UserPopulation, user_stores: UserStores) -> Optional[dict]:
num_events: int = len(self.events["global"])
requirement_check: bool = False
counter: int = 0
new_event: Optional[dict] = None
# convert to dictionary
user_stores_dict: dict[str, UserStore] = {}
for store in user_stores.stores:
user_stores_dict[store.name] = store
while requirement_check is False:
counter += 1
event_index = random.randint(1, num_events) - 1
new_event = self.events["global"][event_index]
# check requirements
for requirement in new_event["requirements"]:
if requirement == "population":
min_required_pop = new_event["requirements"][requirement]
# logging.debug('reported user population: ' + str(user_population))
if user_population.population >= min_required_pop:
requirement_check = True
else:
# assume it is a store - get the current amount of the store for the user
min_required_store = new_event["requirements"][requirement]
if requirement in user_stores_dict:
if user_stores_dict[requirement].amount >= min_required_store:
requirement_check = True
# bail out if we've reached the max, no encounters this time
if counter >= self.MAX_ENCOUNTER_TRIES:
new_event = None
requirement_check = True
if new_event is None:
return None
# remove the requirements stanza before we send to over to the client
outbound_event = copy.deepcopy(new_event)
del outbound_event["requirements"]
return outbound_event | /rowantree.server-0.3.0-py3-none-any.whl/rowantree/server/common/storyteller.py | 0.527073 | 0.629604 | storyteller.py | pypi |
from starlette import status
from starlette.exceptions import HTTPException
from rowantree.contracts import (
FeatureType,
IncomeSourceType,
StoreType,
UserFeatureState,
UserIncome,
UserNotification,
UserState,
UserStore,
)
from ..services.db.incorrect_row_count_error import IncorrectRowCountError
from .abstract_controller import AbstractController
class UserStateGetController(AbstractController):
"""
User State Get Controller
Gets the user game state.
Methods
-------
execute(self, user_guid: str) -> UserState
Executes the command.
"""
def execute(self, user_guid: str) -> UserState:
"""
Gets the user game state.
Parameters
----------
user_guid: str
The target user guid.
Returns
-------
user_state: UserState
The user state object.
"""
try:
# User Game State
active: int = self.dao.user_active_state_get(user_guid=user_guid)
# User Stores (Inventory)
stores: dict[StoreType, UserStore] = self.dao.user_stores_get(user_guid=user_guid)
# User Income
incomes: dict[IncomeSourceType, UserIncome] = self.dao.user_income_get(user_guid=user_guid)
# Features
features: set[FeatureType] = self.dao.user_features_get(user_guid=user_guid)
# Population
population: int = self.dao.user_population_by_guid_get(user_guid=user_guid)
# Active Feature Details and name
active_feature_state: UserFeatureState = self.dao.user_active_feature_state_details_get(user_guid=user_guid)
active_feature_state.name = self.dao.user_active_feature_get(user_guid=user_guid)
# Merchants
merchants: set[StoreType] = self.dao.user_merchant_transforms_get(user_guid=user_guid)
# Notifications
notifications: list[UserNotification] = self.dao.user_notifications_get(user_guid=user_guid)
except IncorrectRowCountError as error:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found") from error
user_state: UserState = UserState(
active=active,
stores=stores,
incomes=incomes,
features=features,
active_feature_state=active_feature_state,
population=population,
merchants=merchants,
notifications=notifications,
)
return user_state | /rowantree.service-0.22.0.tar.gz/rowantree.service-0.22.0/src/rowantree/service/controllers/user_state_get.py | 0.74826 | 0.192103 | user_state_get.py | pypi |
import logging
import socket
from datetime import datetime
from typing import Optional, Tuple
import mysql.connector
from mysql.connector import IntegrityError, errorcode
from mysql.connector.pooling import MySQLConnectionPool, PooledMySQLConnection
from starlette import status
from starlette.exceptions import HTTPException
from rowantree.contracts import (
ActionQueue,
BaseModel,
FeatureDetailType,
FeatureType,
IncomeSourceType,
StoreType,
User,
UserEvent,
UserFeatureState,
UserIncome,
UserNotification,
UserStore,
)
from rowantree.service.sdk import UserIncomeSetRequest
from ...contracts.duplicate_key_error import DuplicateKeyError
from ...contracts.sql_exception_error import SqlExceptionError
from .incorrect_row_count_error import IncorrectRowCountError
class DBDAO(BaseModel):
"""
Database DAO
Attributes
----------
cnxpool: MySQLConnectionPool
MySQL Connection Pool
"""
cnxpool: MySQLConnectionPool
def merchant_transform_perform(self, user_guid: str, store_name: str) -> None:
"""
Perform a merchant transform.
Parameters
----------
user_guid: str
The target user guid.
store_name: str
The name of the store to perform the transform on.
"""
args: list = [user_guid, store_name]
self._call_proc("peformMerchantTransformByGUID", args)
def user_active_feature_get(self, user_guid: str) -> FeatureType:
"""
Gets user's active feature/location.
Parameters
----------
user_guid: str
The target user guid.
Returns
-------
user_feature: FeatureType
The active user feature.
"""
args: list = [
user_guid,
]
rows: list[Tuple[str]] = self._call_proc("getUserActiveFeatureByGUID", args)
if len(rows) != 1:
# User did not exist (received an empty tuple)
message: str = f"Result count was not exactly one. Received: {rows}"
logging.debug(message)
raise IncorrectRowCountError(message)
return FeatureType(rows[0][0])
def user_active_feature_state_details_get(self, user_guid: str) -> UserFeatureState:
"""
Get User Active Feature/Location Including Details.
Parameters
----------
user_guid: str
The target user guid.
Returns
-------
user_feature: UserFeatureState
The active user feature/location with details.
"""
args: list = [
user_guid,
]
rows: list[Tuple[str, Optional[str]]] = self._call_proc("getUserActiveFeatureStateDetailsByGUID", args)
if len(rows) != 1:
# User did not exist (received an empty tuple)
message: str = f"Result count was not exactly one. Received: {rows}"
logging.debug(message)
raise IncorrectRowCountError(message)
return UserFeatureState(details=FeatureDetailType(rows[0][0]), description=rows[0][1])
def users_active_get(self) -> set[str]:
"""
Get Active Users.
Returns
-------
active_user_guids: set[str]
A (unique) set of user guids which are active.
"""
active_user_guids: set[str] = set()
rows: list[Tuple] = self._call_proc("getActiveUsers", [])
for response_tuple in rows:
active_user_guids.add(response_tuple[0])
return active_user_guids
def user_active_state_get(self, user_guid: str) -> bool:
"""
Get user active state.
Parameters
----------
user_guid: str
The target user guid.
Returns
-------
user_active: UserActive
The user active state.
"""
args: list[str, int] = [
user_guid,
]
rows: list[Tuple[int]] = self._call_proc("getUserActivityStateByGUID", args)
if len(rows) != 1:
raise IncorrectRowCountError(f"Result count was not exactly one. Received: {rows}")
if rows[0][0] == 1:
return True
return False
def user_active_state_set(self, user_guid: str, active: bool) -> None:
"""
Set user's active state.
# TODO: the underlying calls need to provide more context on status of this call.
Parameters
----------
user_guid: str
The target user guid.
active: bool
The active state to set.
"""
args: list = [
user_guid,
]
if active:
proc = "setUserActiveByGUID"
else:
proc = "setUserInactiveByGUID"
self._call_proc(name=proc, args=args)
def user_create_by_guid(self, user_guid: str) -> User:
"""
Create a user.
TODO this returns nothing, needs more detail from the db.
Returns
-------
user: User
The created user.
"""
args = [user_guid]
try:
self._call_proc("createUserByGUID", args)
except (IntegrityError, DuplicateKeyError) as error:
message: str = f"User already exists: {user_guid}, {str(error)}"
logging.debug(message)
raise IncorrectRowCountError(message) from error
return User(guid=user_guid)
def user_delete(self, user_guid: str) -> None:
"""
Delete user.
TODO: the underlying calls need to provide more context on status of this call.
Parameters
----------
user_guid: str
The target user guid.
"""
args: list = [
user_guid,
]
self._call_proc("deleteUserByGUID", args)
def user_features_get(self, user_guid: str) -> set[FeatureType]:
"""
Get user features.
Parameters
----------
user_guid: str
The target user guid.
Returns
-------
user_features: UserFeatures
User features object.
"""
features: set[FeatureType] = set()
args: list = [
user_guid,
]
rows: list[Tuple[str]] = self._call_proc("getUserFeaturesByGUID", args)
if rows is None or len(rows) == 0:
# User does not exist ot had no features. However, it should not be
# possible to exist in the game world with without a feature state.
# Users are given a feature state on creation (the process is atomic).
# This should always be do to a non-existent user.
message: str = f"Result count was not exactly one. Received: {rows}"
logging.debug(message)
raise IncorrectRowCountError(message)
for row in rows:
name: str = row[0]
features.add(FeatureType(name))
return features
def user_income_get(self, user_guid: str) -> dict[IncomeSourceType, UserIncome]:
"""
Get user income sources
# TODO: This can not tell if there are no stores, or if the user just doesn't exist.
Parameters
----------
user_guid: str
The target user guid.
Returns
-------
user_incomes: dict[IncomeSourceType, UserIncome]
"""
income_sources: dict[IncomeSourceType, UserIncome] = {}
args: list[str] = [
user_guid,
]
rows: list[Tuple[int, str, Optional[str]]] = self._call_proc("getUserIncomeByGUID", args)
for row in rows:
income_sources[IncomeSourceType(row[1])] = UserIncome(
amount=row[0], name=IncomeSourceType(row[1]), description=row[2]
)
return income_sources
def user_income_set(self, user_guid: str, transaction: UserIncomeSetRequest) -> None:
"""
Set user income source.
TODO: This needs to return more detail on success / failure.
Parameters
----------
user_guid: str
The target user guid.
transaction: UserIncomeSetRequest
The user income set request.
"""
args = [user_guid, transaction.income_source_name, transaction.amount]
self._call_proc("deltaUserIncomeByNameAndGUID", args)
def user_merchant_transforms_get(self, user_guid: str) -> set[StoreType]:
"""
Get User merchant transforms [currently available].
Parameters
----------
user_guid: str
The target user guid.
Returns
-------
user_merchants: set[StoreType]
User merchants object.
"""
merchants: set[StoreType] = set()
args: list = [
user_guid,
]
rows: list[Tuple[str]] = self._call_proc("getUserMerchantTransformsByGUID", args)
for row in rows:
merchants.add(StoreType(row[0]))
return merchants
def user_notifications_get(self, user_guid: str) -> list[UserNotification]:
"""
Get User notifications.
Returns the most recent (new) user notifications.
Parameters
----------
user_guid: str
The target user guid.
Returns
-------
user_notifications: UserNotifications
New user notifications.
"""
notifications: list[UserNotification] = []
args: list = [
user_guid,
]
rows: list[Tuple[int, datetime, str]] = self._call_proc("getUserNotificationByGUID", args)
for row in rows:
notification: UserNotification = UserNotification(
index=row[0], timestamp=row[1], event=UserEvent.parse_raw(row[2])
)
notifications.append(notification)
return notifications
def user_population_by_guid_get(self, user_guid: str) -> int:
"""
Get user population (by GUID)
Parameters
----------
user_guid: str
The target user guid.
Returns
-------
user_population: int
User population size.
"""
rows: list[Tuple[int]] = self._call_proc(
"getUserPopulationByGUID",
[
user_guid,
],
)
if rows is None or len(rows) != 1:
message: str = f"Result count was not exactly one. Received: {rows}"
logging.debug(message)
raise IncorrectRowCountError(message)
return rows[0][0]
def user_stores_get(self, user_guid: str) -> dict[StoreType, UserStore]:
"""
Get user stores.
Parameters
----------
user_guid: str
The target user guid.
Returns
-------
user_stores: dict[StoreType, UserStore]
User Stores Object
"""
stores: dict[StoreType, UserStore] = {}
args: list[str, int] = [
user_guid,
]
rows: list[Tuple[str, Optional[str], int]] = self._call_proc("getUserStoresByGUID", args)
for row in rows:
stores[StoreType(row[0])] = UserStore(name=StoreType(row[0]), description=row[1], amount=row[2])
return stores
def user_transport(self, user_guid: str, location: str) -> UserFeatureState:
"""
Perform User Transport.
Parameters
----------
user_guid: str
The target user guid.
location: str
The name of the feature/location to transport the user to.
Returns
-------
user_feature: UserFeatureState
The active user feature state.
"""
args: list = [user_guid, location]
rows: list[Tuple[str, Optional[str]]] = self._call_proc("transportUserByGUID", args, True)
if len(rows) != 1:
# User did not exist (received an empty tuple)
message: str = f"Result count was not exactly one. Received: {rows}"
logging.debug(message)
raise IncorrectRowCountError(message)
return UserFeatureState(details=rows[0][0], description=rows[0][1])
# Utility functions
def process_action_queue(self, action_queue: ActionQueue) -> None:
"""
Process the provided action queue.
Parameters
----------
action_queue: ActionQueue
The action queue to process.
"""
for action in action_queue.queue:
self._call_proc(action.name, action.arguments)
# pylint: disable=duplicate-code
def _call_proc(self, name: str, args: list, debug: bool = False) -> Optional[list[Tuple]]:
"""
Perform a stored procedure call.
Parameters
----------
name: str
The name of the stored procedure to call.
args: list
The arguments to pass to the stored procedure.
debug: bool
Whether to log debug details about the call.
Returns
-------
results: Optional[list[Tuple]]
An optional list of tuples (rows) from the call.
"""
if debug:
logging.debug("[DAO] [Stored Proc Call Details] Name: {%s}, Arguments: {%s}", name, args)
rows: Optional[list[Tuple]] = None
cnx: Optional[PooledMySQLConnection] = None
try:
cnx = self.cnxpool.get_connection()
cursor = cnx.cursor()
cursor.callproc(name, args)
for result in cursor.stored_results():
rows = result.fetchall()
cursor.close()
cnx.close()
except socket.error as error:
logging.error("socket.error")
logging.error(error)
if cnx:
cnx.close()
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Internal Server Error"
) from error
except mysql.connector.Error as error:
logging.error("mysql.connector.Error: {%i}", error.errno)
logging.error(str(error))
if cnx:
cnx.close()
# pylint: disable=no-else-raise
if error.errno == errorcode.ER_ACCESS_DENIED_ERROR:
logging.error("Something is wrong with your user name or password")
raise SqlExceptionError("Bad username or password") from error
elif error.errno == errorcode.ER_BAD_DB_ERROR:
logging.error("Database does not exist")
raise SqlExceptionError("Database does not exist") from error
elif error.errno == errorcode.ER_DUP_ENTRY:
logging.error("Duplicate key")
raise DuplicateKeyError(str(error)) from error
raise SqlExceptionError(f"Unhandled SQL Exception: {str(error)}") from error
except Exception as error:
logging.error("error")
# All other uncaught exception types
logging.error(str(error))
if cnx:
cnx.close()
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Internal Server Error"
) from error
if debug:
logging.debug("[DAO] [Stored Proc Call Details] Returning:")
logging.debug(rows)
return rows | /rowantree.service-0.22.0.tar.gz/rowantree.service-0.22.0/src/rowantree/service/services/db/dao.py | 0.771327 | 0.17614 | dao.py | pypi |
Transforms
==========
Transforms are series of functions that can be applied to columns, to perform manipulations on the columns values while a table is
being iterated. The transforms are usually simple functions, with some special argument names defined; when iterating, values are
automatically injected according to the argument names. Also, there are a few objects available as transforms, such as the entire
current row.
Each transform specification consists of names of functions or simple python expressions, which may include:
* Zero or one initializers, prefixed with a carat, '^'.
* Zero or more stages, with no prefix, each of which can contain one or more segments.
* Zero or one exceptions handlers, prefixed with a bang, '!'.
For instance, this transform specification:
.. code-block::
^empty_is_null; lower; !handle_exception
Might initialize a column in a table with the value from the empty_is_null() function ( defined elsewhere ) , then call str.lower() on the result, and, if there is an exception, handle the exception with the handle_exception() function.
Each of the segments of a transform can be an expression or a function. Functions can be among those defined in `rowgenerators.valuetype`, or a function that is added to the environment passed into the RowGenerator object when it is constructed
In this example, we have a source data that consists of the columns `a` and `b`, each of which is the first 10 integers. This data is fed into the table `foobar`, which has four columns defined. The first, names `id` will automatically get the row number. The second, `int_val_1` will be initialized form the `a` column of the dataset. The second `int_val_2` is initialized from the `b` column of the input, and then, in a second step, it is doubled.
.. code-block:: python
from rowgenerators.rowpipe import Table
from rowgenerators.rowpipe import RowProcessor
# Define a transform function
def doubleit(v):
return int(v) * 2
# Construct a table, with transforms defined on some columns.
t = Table('foobar')
t.add_column('id', datatype='int')
t.add_column('val_1', datatype='int', transform='^row.a')
t.add_column('val_2', datatype='int', transform='^row.b;doubleit')
t.add_column('val_3', datatype='str', transform='^str(row.val_2)')
# Add the function to the environment.
env = {
'doubleit': doubleit
}
# Iterate over some data.
class Source(object):
headers = 'a b'.split()
def __iter__(self):
for i in range(10):
yield i, i
rp = RowProcessor(Source(), t, env=env)
for row in rp:
print(row)
In the output data:
* `id` will be the row number; this is due to special handling of columns named `id`
* `val_1` will be initialized to the same value as the `a` column of the input data
* `val_2` will be initialized to the value of the `b` column of the input, then doubled
# `val_3` will be set to a string version of `val_2`
When running a RowProcessor, the transforms are re-organized into "stages", with a number of stages equal to the number of stages of the longest transform on a column in the table. The first stage is the initializers ( '^' ); if an initializer is not specified, a default one is used. The result is a new row. In the next stage, all of the second stages of each column transform are run, transforming the output row from the first stage into a new output row. This process continues for all of the output rows.
The source data that is passed into the RowProcess may have a different structure than the output table of the RowProcess. The first stage -- the initializer stage -- will also transform the structure of the data, by assigning source columns to dest columns based on name, or using None for destination columns if there is no associated source column.
For instance, the transform spec `^init; stage1; stage2; !ehandler` would set the final value in a similar fashion to this code:
.. code-block:: python
try:
v = init()
v = stage1(v)
v = stage2(v)
except Exception as e:
ehandler(e)
The function values `init`, `stage1`, `stage2` and `ehandler` must either be from the `rowgenerator` package, or be added to the row processors, environment, as with the `env` dict in the first example.
The conceptual process for processing each row is:
# Take a row from the source data
# Assign values from the source row into the destination table by matching names. Assign None to any destination column without an associated source column. If the first column is named 'id' and there is no associated source column, assign the row number.
# Call the initializers for each column, and cast each column to a ValueType object with a type based on the datatype of the column.
# For each remaining stage, start with the row from the previous stage and apply all of the transforms for this stage
# Repeat until all of the stages are run.
Initializers
------------
The first stage of processing a row initializes the row from the source data.
Transforms
----------
Exceptions
----------
How It Works
------------
Consider this table definition:
.. code-block:: python
t = Table('extable')
t.add_column('id', datatype='int')
t.add_column('b', datatype='int')
t.add_column('v1', datatype='int', transform='^row.a')
t.add_column('v2', datatype='int', transform='row.v1;doubleit')
t.add_column('v3', datatype='int', transform='^row.a;doubleit')
This defintion will result in three stages, with the transformation for each column, at each stage, shown in the table below.
======= ========== ========== ================ ========== ================
stage id b v1 v2 v3
======= ========== ========== ================ ========== ================
0 IntMeasure IntMeasure row.a|IntMeasure IntMeasure row.a|IntMeasure
1 v v v row.v1 doubleit
2 v v v doubleit v
======= ========== ========== ================ ========== ================
The value 'v' in a cell indicates that the value from the previous stage is passed through. The value `IntMeasure` is a valuetype
object, which holds an integer.
The RowProcessor generates code for this table, with a function for each of the stages. Here is the first stage row function:
.. code-block:: python
def row_extable_0(row, row_n, errors, scratch, accumulator, pipe, manager, source):
return [
extable_id_0(row_n, None, 0, None, 'id', row, row_n, errors, scratch, accumulator, pipe, manager, source), # column id
extable_b_0(row[1], 1, 1, 'b', 'b', row, row_n, errors, scratch, accumulator, pipe, manager, source), # column b
extable_v1_0(None, None, 2, None, 'v1', row, row_n, errors, scratch, accumulator, pipe, manager, source), # column v1
extable_v2_0(None, None, 3, None, 'v2', row, row_n, errors, scratch, accumulator, pipe, manager, source), # column v2
extable_v3_0(None, None, 4, None, 'v3', row, row_n, errors, scratch, accumulator, pipe, manager, source), # column v3
]
The function takes an input row, along with some other management objects, and returns a row. The returned list has one entry for
each of the columns in the destination table. The first argument to each function is the value being passed in from the source
data. In this case, the source data only has two columns, 'a' and 'b'. The first entry, for the `id` column, is given a specialq
value, the row number. The second column is named `b`, the same name as in the source data, so it is given a value of the `b`
column in the source data. The remainder of the columns in the destination table have no counterpart in source table, so they have
values of `None`
This is the column function for the `id` column:
.. code-block:: python
def extable_id_0(v, i_s, i_d, header_s, header_d, row, row_n, errors, scratch, accumulator, pipe, manager, source):
try:
v = IntMeasure(v) # .../rowgenerators/rowpipe/codegen.py:345
except Exception as exc:
raise CasterExceptionError("extable_id_0",header_d, v, exc, sys.exc_info())
return v
It just takes the input value, which was `row_n`, and casts it to an `IntMeasure`
The `v1` column has an initializer, so it is a bit different; it will take the `a` value from the source row and assign it to the `v1` column, then casts to IntMeasure
.. code-block:: python
def extable_v1_0(v, i_s, i_d, header_s, header_d, row, row_n, errors, scratch, accumulator, pipe, manager, source):
try:
v = row.a # .../rowgenerators/rowpipe/codegen.py:548
v = IntMeasure(v) # .../rowgenerators/rowpipe/codegen.py:348
except Exception as exc:
raise CasterExceptionError("extable_v1_0",header_d, v, exc, sys.exc_info())
return v
| /rowgenerators-0.9.24.tar.gz/rowgenerators-0.9.24/docs/transforms/index.rst | 0.942546 | 0.973869 | index.rst | pypi |
# world_rowing
Collection of code to load, process and analyse rowing data from [World Rowing](https://worldrowing.com/).
Can view the world rowing data by running `streamlit run world_rowing_app/home.py` or visiting https://matthewghgriffiths-worldrowing.streamlit.app/
# rowing.analysis
A python library for analysing gps data, there are two main programs, `gpx` and `garmin`. `gpx` directly processes gpx files, calculating fastest times/splits over distances and timings/splits between specified rowing landmarks. See `Garmin.ipynb` for a more direct example of how to use the library.
## Example usage
```
$ gpx --help
usage: gpx [-h] [-o [OUT_FILE]] [-l-log LOG] [gpx_file [gpx_file ...]]
Analyse gpx data files
positional arguments:
gpx_file gpx files to process, accepts globs, e.g. activity_*.gpx, default='*.gpx'
optional arguments:
-h, --help show this help message and exit
-o [OUT_FILE], --out-file [OUT_FILE]
path to excel spreadsheet to save results, default='gpx_data.xlsx'
-l-log LOG, --log LOG
Provide logging level. Example --log debug', default='warning'
$ garmin --help
usage: garmin [-h] [--start [START]] [-u [USER]] [-p [PASSWORD]] [-c [CREDENTIALS]]
[--actions {excel,heartrate,download} [{excel,heartrate,download} ...]]
[--excel-file [EXCEL_FILE]] [--folder [FOLDER]] [-a [ACTIVITY]]
[--min-distance [MIN_DISTANCE]] [--max-distance [MAX_DISTANCE]]
[--start-date START_DATE] [--end-date END_DATE] [--min-hr [MIN_HR]]
[--max-hr [MAX_HR]] [--hr-to-plot HR_TO_PLOT [HR_TO_PLOT ...]]
[--cmap {gist_ncar,inferno,hot,hot_r}] [--dpi DPI] [--hr-file HR_FILE]
[--hr-plot HR_PLOT] [-l-log LOG]
[n]
Analyse recent gps data
positional arguments:
n maximum number of activities to load
optional arguments:
-h, --help show this help message and exit
--start [START] if loading large number of activities, sets when to start
loading the activities from
-u [USER], --user [USER], --email [USER]
Email address to use
-p [PASSWORD], --password [PASSWORD]
Password
-c [CREDENTIALS], --credentials [CREDENTIALS]
path to json file containing credentials (email and password)
--actions {excel,heartrate,download} [{excel,heartrate,download} ...]
specify action will happen
--excel-file [EXCEL_FILE]
path of output excel spreadsheet
--folder [FOLDER] folder path to download fit files
-a [ACTIVITY], --activity [ACTIVITY]
activity type, options: rowing, cycling, running
--min-distance [MIN_DISTANCE]
minimum distance of activity (in km)
--max-distance [MAX_DISTANCE]
maximum distance of activity (in km)
--start-date START_DATE
start date to search for activities from in YYYY-MM-DD format
--end-date END_DATE start date to search for activities from in YYYY-MM-DD format
--min-hr [MIN_HR] min heart rate to plot
--max-hr [MAX_HR] max heart rate to plot
--hr-to-plot HR_TO_PLOT [HR_TO_PLOT ...]
which heart rates to plot lines for
--cmap {gist_ncar,inferno,hot,hot_r}
The cmap to plot the heart rates for
--dpi DPI
--hr-file HR_FILE file to save heart rate to
--hr-plot HR_PLOT file to save heart rate to
-l-log LOG, --log LOG, --logging LOG
Provide logging level. Example --log debug', default='warning'
```
Example running `garmin`,
```
$ garmin --credentials garmin-credentials.json
best times:
time split heart_rate cadence bearing
activity_id startTime totalDistance length distance
8864358195 2022-05-21 09:45:21 11.98812 250m 0.191 1:25.50 2:51.01 97.9 8.1 76.3
0.452 1:20.04 2:40.08 107.7 20.1 48.5
0.803 1:24.81 2:49.62 106.8 18.4 29.0
1.054 1:13.89 2:27.78 118.7 17.9 19.6
1.376 1:15.38 2:30.77 121.1 18.1 16.0
... ... ... ... ... ...
8888463424 2022-05-25 05:35:52 16.04431 5km 2.943 22:35.28 2:15.52 153.4 20.0 11.4
8.142 25:10.40 2:31.04 151.9 20.1 -136.1
7km 1.064 32:48.65 2:20.61 145.3 18.4 13.7
8.129 38:47.62 2:46.25 150.9 19.9 -141.6
10km 1.757 47:57.81 2:23.89 150.0 19.7 -41.3
```
```
$ garmin --start-date 2021-09-01 --end-date 2022-05-25 --action heartrate --hr-plot hr.png
saved heart rate data to heart_rate.xlsx
saved heart rate plot to hr.png
Press enter to finish
```
`hr.png` is shown below,
 | /rowing-0.3.1.tar.gz/rowing-0.3.1/README.md | 0.461259 | 0.841891 | README.md | pypi |
# Rownd bindings for Django
Easily add Rownd instant accounts to your Django-backed apps.
## Installation
Begin by adding the `rownd_django` package to your dependencies. In `requirements.txt`, this would look like:
```
rownd_django>=1.0.0
```
> NOTE: This plugin only works with Django v3 and above. We strongly recommend upgrading if you're
> using something older. If you can't for some reason, please [get in touch](mailto:support@rownd.io?subject=Django%soSDK:%20Request%20for%20older%20version%20support).
Next, add the Rownd app and authentication backend to your Django `settings.py` file.
```python
INSTALLED_APPS = [
...
'rownd_django',
]
AUTHENTICATION_BACKENDS = [
'rownd_django.auth.backend.RowndAuthenticationBackend',
'django.contrib.auth.backends.ModelBackend'
]
```
If you're using Django REST Framework, then add the Rownd authentication class to your `REST_FRAMEWORK` settings.
```python
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rownd_django.auth.backend.RowndApiAuthentication',
]
}
```
Finally, add your Rownd app credentials to your Django `settings.py` file. You can obtain these from the [Rownd dashboard](https://app.rownd.io).
These credentials enable the Rownd authentication backend to communicate with the Rownd API.
```python
ROWND = {
'APP_KEY': '<your app key>',
'APP_SECRET': '<your app secret>',
}
```
### Configure the Rownd Hub (required)
Rownd authentication requires a small code snippet to be embedded within your app, present on all HTML pages.
Setup for the Hub/snippet itself is outside the scope of this document, but you can find the relevant setup
guides for either [single page apps](https://docs.rownd.io/rownd/sdk-reference/web/react-next.js)
or [traditional web apps via vanilla js](https://docs.rownd.io/rownd/sdk-reference/web/javascript-browser).
Use our SDKs to embed the Hub/snippet in your SPA or use the vanilla JS SDK to add the snippet in your main Django template HTML.
Now that everything is set up, you can add Rownd authentication to your APIs or views.
## Usage
The Rownd Django SDK provides support for both "traditional" Django apps where you have an authentication
session that follows a user across page loads, as well as "single-page" (SPA) Django apps using frameworks
like React, Vue, etc.
### Single-page apps (SPA) / API-based
When using an SPA framework like React, Vue, or similar, you'll likely want to leverage the specific Rownd SDK
for those frameworks. You can find a list of supported frameworks in [our documentation](https://docs.rownd.io/rownd/sdk-reference/web).
Typically, an SPA will use an API-driven request/response flow which makes typical sessions unnecessary (though Rownd supports them if you
need them). We highly recommend the [Django REST framework](https://www.django-rest-framework.org/) for this purpose. Rownd provides plug-and-play
support for the REST framework's authentication API.
Here's an example of how you might configure an API to leverage Rownd's authenticator, given the installation instructions above:
```python
from rownd_django.auth.backend import RowndApiAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
class ExampleView(APIView):
authentication_classes = [RowndApiAuthentication]
permission_classes = [IsAuthenticated]
def get(self, request, format=None):
content = {
'user': str(request.user), # `django.contrib.auth.User` instance.
'auth': str(request.auth), # None
}
return Response(content)
```
### Traditional (non-SPA) apps / session-based
In this flow, once a user has been authenticated with the Rownd Hub, the Hub will make a request to your
app's backend to set up a session for the user.
First, ensure your project has session middleware enabled.
```python
MIDDLEWARE = [
...
'django.contrib.sessions.middleware.SessionMiddleware',
...
]
```
Next, include the Rownd `session_authenticator` in your `urls.py` file.
```python
urlpatterns = [
...
path('rownd/', include('rownd_django.auth.urls', namespace='rownd')),
...
]
```
Finally, update your Rownd Hub code snippet to fire a post-authenticate API request to the session authenticator we just enabled.
```html
<script type="text/javascript">
(function () {
// Rownd Hub snippet
})();
</script>
<script type="text/javascript">
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
_rphConfig.push(['setAppKey', '<rownd app key>']);
_rphConfig.push(['setPostAuthenticationApi', {
method: 'post',
url: '/rownd/session_authenticate',
extra_headers: {
'X-CSRFToken': getCookie('csrftoken')
}
}]);
</script>
```
The session authenticator will establish an authenticated session if one doesn't already exist and will return a response
indicating that the Rownd Hub should trigger a page refresh. This is usually necessary for your app views to display
the desired authenticated context. In the event that an authenticated session already exists, the Hub will not trigger
further page refreshes.
| /rownd_django-1.0.1.tar.gz/rownd_django-1.0.1/README.md | 0.499756 | 0.823293 | README.md | pypi |
[](https://travis-ci.org/dumitrescustefan/RoWordNet)
[](https://www.python.org/downloads/)
[]()
# RoWordNet
**RoWordNet stand for Romanian WordNet, a semantic network for the Romanian language**. RoWordNet mimics Princeton WordNet, a large lexical database of English.
The building block of a WordNet is the **synset** that expresses a unique concept. The synset (a synonym set) contains, as the name implies, a number of synonym words known as literals. The synset has more properties like a definition and links to other synsets. They also have a part-of-speech (pos) that groups them in four categories: nouns, verbs, adverbs and adjectives. Synsets are interlinked by **semantic relations** like hypernymy ("is-a"), meronymy ("is-part"), antonymy, and others.
#### New version release : 1.1
* Fixed a bug that when searching the results would give back synsets that contained incorrectly split multi-word literals. We have now added the ``strict = True`` option to obtain only entire word (or multi-word) literals. (Issue [#23](https://github.com/dumitrescustefan/RoWordNet/issues/23))
* Optimized the three similarity algorithms: ``path``, ``wup`` and ``lch``. Similarity is now significantly faster by orders of magnitute by separately computing a hypernym tree and running sim over it instead of the entire word net. (Issue [#27](https://github.com/dumitrescustefan/RoWordNet/issues/27))
## Install
Simple, use python's pip:
```sh
pip install rowordnet
```
RoWordNet has two dependencies: _networkx_ and _lxml_ which are automatically installed by pip.
## Intro
RoWordNet is, at its core, a directed graph (powered by networkx) with synset IDs as nodes and relations as edges. Synsets (objects) are kept as an ID:object indexed dictionary for O(1) access.
A **synset** has the following data, accessed as properties (others are present, but the following are most important):
* id : the id(string) of this synset
* literals : a list of words(strings) representing a unique concept. These words are synonyms.
* definition : a longer description(string) of this synset
* pos : the part of speech of this synset (enum: Synset.Pos.NOUN, VERB, ADVERB, ADJECTIVE)
* sentiwn : a three-valued list indicating the SentiWN PNO (Positive, Negative, Objective) of this synset.
**Relations** are edges between synsets. Examples on how to list inbound/outbound relations given a synset and other graph operations are given in examples below.
____
* Demo on basic ops available as a [Jupyter notebook here](jupyter/basic_operations_wordnet.ipynb).
* Demo on more advanced ops available as a [Jupyter notebook here](jupyter/create_edit_synsets.ipynb).
* Demo on save/load ops available as a [Jupyter notebook here](jupyter/load_save_wordnet.ipynb).
* Demo on synset/relation creation and editing available as a [Jupyter notebook here](jupyter/synonym_antonym.ipynb).
* Demo on similiarity metrics available as a [Jupyter notebook here](jupyter/similarity_metrics.ipynb).
____
## Basic Usage
```python
import rowordnet as rwn
wn = rwn.RoWordNet()
```
And you're good to go. We present a few basic usage examples here:
### Search for a word
As words are polysemous, searching for a word will likely yield more than one synset. A word is known as a literal in RoWordNet, and every synset has one or more literals that are synonyms.
```python
word = 'arbore'
synset_ids = wn.synsets(literal=word)
```
Eash synset has a unique ID, and most operations work with IDs. Here, ``wn.synsets(word)`` returns a list of synsets that contain word 'arbore' or an empty list if the word is not found.
Please note that the Romanian WordNet also contains words (literals) that are actually expressions like "tren\_de\_marfă", and searching for "tren" will also find this synset.
### Get a synset
Calling ``wn.print_synset(id)`` prints all available info of a particular synset.
```python
wn.print_synset(synset_id)
```
To get the actual Synset object, we simply call ``wn.synset(id)``, or ``wn(id)`` directly.
```python
synset_object = wn.synset(synset_id)
synset_object = wn(synset_id) # equivalent, shorter form
```
To print any individual information, like its literals, definiton or ID, we directly call the synset object's properties:
```python
print("Print its literals (synonym words): {}".format(synset_object.literals))
print("Print its definition: {}".format(synset_object.definition))
print("Print its ID: {}".format(synset_object.id))
```
### Synsets access
The ``wn.synsets()`` function has two (optional) parameters, ``literal`` and ``pos``. If we specify a literal it will return all synset IDs that contain that literal. If we don't specify a literal, we will obtain a list of all existing synsets. The pos parameter filters by part of speech: NOUN, VERB, ADVERB or ADJECTIVE. The function returns a list of synset IDs.
```python
synset_ids_all = wn.synsets() # get all synset IDs in RoWordNet
synset_ids_verbs = wn.synsets(pos=Synset.Pos.VERB) # get all verb synset IDs
synset_ids = wn.synsets(literal="cal", pos=Synset.Pos.NOUN) # get all synset IDs that contain word "cal" and are nouns
```
For example we want to list all synsets containing word "cal":
```python
word = 'cal'
print("Search for all noun synsets that contain word/literal '{}'".format(word))
synset_ids = wn.synsets(literal=word, pos=Synset.Pos.NOUN)
for synset_id in synset_ids:
print(wn.synset(synset_id))
```
will output:
```
Search for all noun synsets that contain word/literal 'cal'
Synset(id='ENG30-03624767-n', literals=['cal'], definition='piesă la jocul de șah de forma unui cap de cal')
Synset(id='ENG30-03538037-n', literals=['cal'], definition='Nume dat unor aparate sau piese asemănătoare cu un cal :')
Synset(id='ENG30-02376918-n', literals=['cal'], definition='Masculul speciei Equus caballus')
````
### Relations access
Synsets are linked by relations (encoded as directed edges in a graph). A synset usually has outbound as well as inbound relation, To obtain the outbound relations of a synset use ``wn.outbound_relations()`` with the synset id as parameter. The result is a list of tuples like ``(synset_id, relation)`` encoding the target synset and the relation that starts from the current synset (given as parameter) to the target synset.
```python
synset_id = wn.synsets("tren")[2] # select the third synset from all synsets containing word "tren"
print("\nPrint all outbound relations of {}".format(wn.synset(synset_id)))
outbound_relations = wn.outbound_relations(synset_id)
for outbound_relation in outbound_relations:
target_synset_id = outbound_relation[0]
relation = outbound_relation[1]
print("\tRelation [{}] to synset {}".format(relation,wn.synset(target_synset_id)))
```
Will output (amongst other relations):
```
Print all outbound relations of Synset(id='ENG30-04468005-n', literals=['tren'], definition='Convoi de vagoane de cale ferată legate între și puse în mișcare de o locomotivă.')
Relation [hypernym] to synset Synset(id='ENG30-04019101-n', literals=['transport_public'], definition='transportarea pasagerilor sau postei')
Relation [hyponym] to synset Synset(id='ENG30-03394480-n', literals=['marfar', 'tren_de_marfă'], definition='tren format din vagoane de marfă')
Relation [member_meronym] to synset Synset(id='ENG30-03684823-n', literals=['locomotivă', 'mașină'], definition='Vehicul motor de cale ferată, cu sursă de energie proprie sau străină, folosind pentru a remorca și a deplasa vagoanele.')
````
This means that from the current synset there are three relations pointing to other synsets: the first relation means that "tren" is-a (hypernym) "transport\_public"; the second relation is a hyponym, meaning that "marfar" is-a "tren"; the third member_meronym relation meaning that "locomotiva" is a part-of "tren".
The ``wn.inbound_relations()`` works identically but provides a list of _incoming_ relations to the synset provided as the function parameter, while ``wn.relations()`` provides allboth inbound and outbound relations to/from a synset (note: usually wn.relations() is provided as a convenience and is used for information/printing purposes as the returned tuple list looses directionality)
## Credits
Please consider citing the following paper as a thank you to the authors of the actual Romanian WordNet data:
```
Dan Tufiş, Verginica Barbu Mititelu, The Lexical Ontology for Romanian, in Nuria Gala, Reinhard Rapp, Nuria Bel-Enguix (Ed.), Language Production, Cognition, and the Lexicon, series Text, Speech and Language Technology, vol. 48, Springer, 2014, p. 491-504.
```
or in .bib format:
```
@InBook{DTVBMzock,
title = "The Lexical Ontology for Romanian",
author = "Tufiș, Dan and Barbu Mititelu, Verginica",booktitle = "Language Production, Cognition, and the Lexicon",
editor = "Nuria Gala, Reinhard Rapp, Nuria Bel-Enguix",
series = "Text, Speech and Language Technology",
volume = "48",
year = "2014",
publisher = "Springer",
pages = "491-504"}
```
.. and also to the autors of this [API](https://ieeexplore.ieee.org/abstract/document/8679089):
```
S. D. Dumitrescu, A. M. Avram, L. Morogan and S. Toma, "RoWordNet – A Python API for the Romanian WordNet," 2018 10th International Conference on Electronics, Computers and Artificial Intelligence (ECAI), Iasi, Romania, 2018, pp. 1-6.
```
or in .bib format:
```
@inproceedings{dumitrescu2018rowordnet,
title={RoWordNet--A Python API for the Romanian WordNet},
author={Dumitrescu, Stefan Daniel and Avram, Andrei Marius and Morogan, Luciana and Toma, Stefan-Adrian},
booktitle={2018 10th International Conference on Electronics, Computers and Artificial Intelligence (ECAI)},
pages={1--6},
year={2018},
organization={IEEE}
}
```
## Online query/visualizer for RoWordNet
Because there are many visitors that just want an **online interface to query RoWordNet**, please go to:
[http://dcl.bas.bg/bulnet/](http://dcl.bas.bg/bulnet/)
and choose in the upper right corner **PWN \& RoWN**. This interface provides pretty much the whole data available in this repo (after all it's a visualization interface) and it also includes mappings to Princeton's WordNet. Please note that this link is not associated with us in any way - we just use the same basic data and package it in an API for programatic use. By providing this link we're trying to help out people that just want to browse RoWordNet without having to code anything.
| /rowordnet-1.1.0.tar.gz/rowordnet-1.1.0/README.md | 0.720172 | 0.938576 | README.md | pypi |
import math
import matplotlib.pyplot as plt
from .Generaldistribution import Distribution
class Gaussian(Distribution):
""" Gaussian distribution class for calculating and
visualizing a Gaussian distribution.
Attributes:
mean (float) representing the mean value of the distribution
stdev (float) representing the standard deviation of the distribution
data_list (list of floats) a list of floats extracted from the data file
"""
def __init__(self, mu=0, sigma=1):
Distribution.__init__(self, mu, sigma)
def calculate_mean(self):
"""Function to calculate the mean of the data set.
Args:
None
Returns:
float: mean of the data set
"""
avg = 1.0 * sum(self.data) / len(self.data)
self.mean = avg
return self.mean
def calculate_stdev(self, sample=True):
"""Function to calculate the standard deviation of the data set.
Args:
sample (bool): whether the data represents a sample or population
Returns:
float: standard deviation of the data set
"""
if sample:
n = len(self.data) - 1
else:
n = len(self.data)
mean = self.calculate_mean()
sigma = 0
for d in self.data:
sigma += (d - mean) ** 2
sigma = math.sqrt(sigma / n)
self.stdev = sigma
return self.stdev
def plot_histogram(self):
"""Function to output a histogram of the instance variable data using
matplotlib pyplot library.
Args:
None
Returns:
None
"""
plt.hist(self.data)
plt.title('Histogram of Data')
plt.xlabel('data')
plt.ylabel('count')
def pdf(self, x):
"""Probability density function calculator for the gaussian distribution.
Args:
x (float): point for calculating the probability density function
Returns:
float: probability density function output
"""
return (1.0 / (self.stdev * math.sqrt(2*math.pi))) * math.exp(-0.5*((x - self.mean) / self.stdev) ** 2)
def plot_histogram_pdf(self, n_spaces = 50):
"""Function to plot the normalized histogram of the data and a plot of the
probability density function along the same range
Args:
n_spaces (int): number of data points
Returns:
list: x values for the pdf plot
list: y values for the pdf plot
"""
mu = self.mean
sigma = self.stdev
min_range = min(self.data)
max_range = max(self.data)
# calculates the interval between x values
interval = 1.0 * (max_range - min_range) / n_spaces
x = []
y = []
# calculate the x values to visualize
for i in range(n_spaces):
tmp = min_range + interval*i
x.append(tmp)
y.append(self.pdf(tmp))
# make the plots
fig, axes = plt.subplots(2,sharex=True)
fig.subplots_adjust(hspace=.5)
axes[0].hist(self.data, density=True)
axes[0].set_title('Normed Histogram of Data')
axes[0].set_ylabel('Density')
axes[1].plot(x, y)
axes[1].set_title('Normal Distribution for \n Sample Mean and Sample Standard Deviation')
axes[0].set_ylabel('Density')
plt.show()
return x, y
def __add__(self, other):
"""Function to add together two Gaussian distributions
Args:
other (Gaussian): Gaussian instance
Returns:
Gaussian: Gaussian distribution
"""
result = Gaussian()
result.mean = self.mean + other.mean
result.stdev = math.sqrt(self.stdev ** 2 + other.stdev ** 2)
return result
def __repr__(self):
"""Function to output the characteristics of the Gaussian instance
Args:
None
Returns:
string: characteristics of the Gaussian
"""
return "mean {}, standard deviation {}".format(self.mean, self.stdev) | /rox_distributions-0.1.tar.gz/rox_distributions-0.1/rox_distributions/Gaussiandistribution.py | 0.688364 | 0.853058 | Gaussiandistribution.py | pypi |
import operator
from typing import Any
import matplotlib # type: ignore
import numpy as np
import pandas as pd
import plotly.express as px # type: ignore
import plotly.graph_objects as go # type: ignore
import pyvista as pv
import vtk # type: ignore
from roxieapi.xml_api import X_COORDINATE, Y_COORDINATE
ROXIE_COLOR_MAP_RGB = [
(17, 0, 181),
(11, 42, 238),
(0, 104, 236),
(0, 154, 235),
(0, 208, 226),
(0, 246, 244),
(0, 255, 0),
(116, 255, 0),
(191, 255, 0),
(252, 255, 0),
(255, 199, 0),
(255, 146, 0),
(255, 86, 0),
(255, 0, 0),
(246, 0, 0),
(232, 0, 0),
(197, 0, 50),
(168, 0, 159),
]
ROXIE_COLOR_MAP_RGB_PLOTLY = [
f"rgb{color_code_rgb}" for color_code_rgb in ROXIE_COLOR_MAP_RGB
]
def rgb_to_hex(rgb):
return "#%02x%02x%02x" % rgb
ROXIE_COLOR_MAP_HEX = [rgb_to_hex(rgb) for rgb in ROXIE_COLOR_MAP_RGB]
ROXIE_COLOR_MAP_RGB_MATPLOTLIB = matplotlib.colors.ListedColormap(
ROXIE_COLOR_MAP_HEX, name="ROXIE_COLORMAP"
)
def plotly_results(
strand_data: pd.DataFrame,
column: str,
figsize=(750, 600),
xlim=(0, 80),
ylim=(0, 80),
) -> None:
"""Function plotting results with plotly package
:param strand_data: a dataframe with strand positions and field values
:param xlim: limits in x-direction
:param ylim: limits in y-direction
"""
fig = px.scatter(
strand_data,
x="x, [mm]",
y="y, [mm]",
color=column,
hover_data=[column],
color_continuous_scale=ROXIE_COLOR_MAP_RGB_PLOTLY,
)
fig.update_layout(
autosize=False,
width=figsize[0],
height=figsize[1],
xaxis_range=xlim,
yaxis_range=ylim,
plot_bgcolor="rgba(0,0,0,0)",
images=[
dict(
source="https://i.ibb.co/kcc2mbw/ROXIE.png",
xref="paper",
yref="paper",
x=1.16,
y=-0.05,
sizex=0.2,
sizey=0.2,
xanchor="right",
yanchor="bottom",
)
],
)
fig.show()
def plotly_mesh(
x_values, y_values, elements, figsize=(750, 750), xlim=(-80, 80), ylim=(-80, 80)
):
"""Method plotting blocks with plotly library
:param figsize: size of the figure on a display
:param xlim: limits in x-direction
:param ylim: limits in y-direction
"""
go_scatters = _create_plotly_scatters(x_values, y_values, elements)
fig = go.Figure(go_scatters)
fig.update_layout(
autosize=False,
width=figsize[0],
height=figsize[1],
yaxis_range=ylim,
xaxis_range=xlim,
showlegend=False,
plot_bgcolor="rgba(0,0,0,0)",
)
fig.add_trace(px.scatter(x=[0], y=[0]).data[0])
fig.update_xaxes(title=dict(text="x, [mm]"))
fig.update_yaxes(title=dict(text="y, [mm]"))
fig.show()
def _create_plotly_scatters(x_values, y_values, elements):
"""Static method creating a list of plotly scatter instances
:param blocks: list of blocks to convert to plotly scatter
:return: a list of plotly scatter instances
"""
go_scatter = []
index = 1
for element in elements:
x = list(operator.itemgetter(*element)(x_values))
y = list(operator.itemgetter(*element)(y_values))
x.append(x[0])
y.append(y[0])
go_scatter.append(
go.Scatter(
x=x,
y=y,
fill="toself",
fillcolor="white",
marker=dict(size=1),
name="element" + str(index),
line=go.scatter.Line(color="blue"),
)
)
index += 1
return go_scatter
def plot_strand_mesh_data(
strand_data_df: pd.DataFrame,
mesh_data_df: pd.DataFrame,
elements: list,
field_name_strand: str,
field_name_mesh: str,
show_bar_strand=False,
show_bar_mesh=True,
point_size_strand=2.5,
) -> None:
"""
Function plotting mesh data along with strand data
:param strand_data_df: a dataframe with x y coordinates of strands and at least one column with strand data to plot
:param mesh_data_df: a dataframe with x y coordinates of mesh nodes and at least one column with mesh data to plot
:param elements: a list of lists with mesh elements definition. The outer list goes from 1 to number of mesh
elements. The inner list goes from 1 to m nodes of a mesh element. The inner loop contains mesh indices
:param field_name_strand: name of a column with strand data to plot
:param field_name_mesh: name of a column with mesh data to plot
:param show_bar_strand: if True a bar legend for mesh data is shown, otherwise hidden
:param show_bar_mesh: if True a bar legend for mesh data is shown, otherwise hidden
:param point_size_strand: size of a strand point with data
"""
vtk_grid_strand = _initialize_vtk_grid_with_points(
strand_data_df[[X_COORDINATE, Y_COORDINATE]].values
)
vtk_grid_mesh = _initialize_vtk_grid_with_points(
mesh_data_df[[X_COORDINATE, Y_COORDINATE]].values
)
for element in elements:
vtk_grid_mesh.InsertNextCell(vtk.VTK_POLYGON, len(element), element)
field_mesh = mesh_data_df[field_name_mesh].values
field_strand = strand_data_df[field_name_strand].values
pv_grid_strand = _initialize_pyvista_grid_with_vtk_grid_and_point_data(
vtk_grid_strand, field_strand, field_name=field_name_strand
)
pv_grid_mesh = _initialize_pyvista_grid_with_vtk_grid_and_point_data(
vtk_grid_mesh, field_mesh, field_name=field_name_mesh
)
pl = pv.Plotter()
pl.add_points(
pv_grid_strand.points,
scalars=field_strand,
cmap=ROXIE_COLOR_MAP_RGB_MATPLOTLIB,
show_scalar_bar=show_bar_strand,
point_size=point_size_strand,
)
pl.add_mesh(
pv_grid_mesh, cmap=ROXIE_COLOR_MAP_RGB_MATPLOTLIB, show_scalar_bar=show_bar_mesh
)
pl.view_xy()
pl.enable_joystick_style()
pl.show()
def _initialize_vtk_grid_with_points(xy_points: np.ndarray) -> vtk.vtkUnstructuredGrid:
vtk_grid = vtk.vtkUnstructuredGrid()
vtk_points = vtk.vtkPoints()
for i, (x, y) in enumerate(xy_points):
vtk_points.InsertPoint(i, x, y, 0.0)
vtk_grid.SetPoints(vtk_points)
return vtk_grid
def _initialize_pyvista_grid_with_vtk_grid_and_point_data(
vtk_grid: vtk.vtkUnstructuredGrid,
point_data: np.ndarray[float, Any],
field_name="field",
) -> pv.UnstructuredGrid:
pv_grid = pv.UnstructuredGrid(vtk_grid)
pv_grid.point_data[field_name] = point_data
return pv_grid | /roxie_api-0.0.15-py3-none-any.whl/roxieapi/plot_api.py | 0.88993 | 0.342049 | plot_api.py | pypi |
import re
from io import StringIO
from typing import Dict, List, Tuple, Union
import pandas as pd
from pymbse.commons import text_file
def extract_objective_table(
output_lines: List[str],
index_start_objective_table: int,
n_objectives: int,
) -> pd.DataFrame:
"""Function extracting an objective table from ROXIE output file and converting it into a dataframe.
:param output_lines: a list of lines from the output text file
:param index_start_objective_table: a start index of the objective table
:param n_objectives: the length of the objective table
:return: dataframe with objective table
"""
objectives_table = output_lines[
index_start_objective_table : index_start_objective_table + n_objectives + 1
]
objectives_table_lines = [
"\t".join(objective_table.split()) for objective_table in objectives_table
]
TESTDATA = StringIO("\n".join(objectives_table_lines))
objective_table_df = pd.read_csv(TESTDATA, sep="\t", index_col=0)
objective_table_df.rename(columns={"WEIGHTED": "WEIGHTED OBJ"}, inplace=True)
objective_table_df.drop(columns="OBJ", inplace=True)
return objective_table_df
def find_index_start_and_length_objective_table(
output_lines: List[str], table_keyword: str
) -> Tuple[int, int]:
"""Function finding a start index and length of an objective table in output lines from a .output ROXIE file
:param output_lines: list of output lines
:param table_keyword: a keyword of the objective table
:return: a tuple with objective table start index and its length
"""
index_objective_table = None
n_objectives = None
for index_line, output_line in enumerate(output_lines):
if "OBJECTIVE" in output_line and "S1" in output_line:
index_objective_table = index_line
if table_keyword in output_line:
matches = re.findall(r"\d+", output_line)
if matches:
n_objectives = int(matches[0])
if index_objective_table is None or n_objectives is None:
raise IndexError("Objective table not found in the output")
return index_objective_table, n_objectives
def convert_bottom_header_table_to_str(
block_df: pd.DataFrame, keyword: str, line_suffix="", header_suffix=""
) -> str:
"""Function converting a dataframe with a keyword and suffix to string. The string is used to create a ROXIE .data
input file.
:param block_df: a dataframe with content to be converted into a bottom header table string
:param keyword: a keyword for the table
:param line_suffix: a string added at the end of each of line to match the ROXIE formatting
:return: a string representation of a bottom header table
"""
if header_suffix:
keyword_and_length_str = "%s %s" % (keyword, header_suffix)
else:
keyword_and_length_str = "%s %d" % (keyword, len(block_df))
if block_df.empty:
return keyword_and_length_str
else:
block_str: str = block_df.to_string(index=False)
block_str_lines = block_str.split("\n")
block_str_lines = block_str_lines[1:] + [block_str_lines[0]]
block_str = (line_suffix + "\n").join(block_str_lines)
return "%s\n%s" % (keyword_and_length_str, block_str)
def convert_table_to_str(block_df: pd.DataFrame, keyword: str, header_suffix="") -> str:
"""Function converting a dataframe with a keyword and suffix to string without bottom header columns.
The string is used to create a ROXIE .datainput file.
:param block_df: a dataframe with content to be converted into a bottom header table string
:param keyword: a keyword for the table
:param line_suffix: a string added at the end of each of line to match the ROXIE formatting
:return: a string representation of a bottom header table
"""
if header_suffix:
keyword_and_length_str = "%s %s" % (keyword, header_suffix)
else:
keyword_and_length_str = "%s %d" % (keyword, len(block_df))
block_str: str = block_df.to_string(index=False)
block_str_lines = block_str.split("\n")
# header at the first index is skipped
block_str = "\n".join(block_str_lines[1:])
return "%s\n%s" % (keyword_and_length_str, block_str)
def read_bottom_header_table(roxie_file_path: str, keyword="CABLE") -> pd.DataFrame:
"""Function reading a bottom header table from ROXIE .data, .cadata, .output files
:param roxie_file_path: a path to a roxie file
:param keyword: a table keyword
:return: a dataframe with content of a table given by a keyword
"""
with open(roxie_file_path, "r") as text_file:
text_file_lines = text_file.read().split("\n")
index_start, n_lines = find_index_start_and_length_bottom_header_table(
text_file_lines, keyword
)
return extract_bottom_header_table(text_file_lines, index_start, n_lines)
def find_index_start_and_length_bottom_header_table(
output_lines: List[str], table_keyword: str
) -> Tuple[int, int]:
"""Function finding the start and length of a table in ROXIE .output or .cadata or .data file.
If a table keyword can't be found, the an IndexError is thrown.
:param output_lines: a list of lines read from a ROXIE file
:param table_keyword: a keyword for the objective table
:return: a tuple with an index of the start of bottom header table and its length
"""
len_keyword = len(table_keyword)
for index_line, output_line in enumerate(output_lines):
if (len(output_line) >= len_keyword) and (
output_line[0:len_keyword] == table_keyword
):
index_table_start = index_line
matches = re.findall(r"\d+", output_line)
if matches:
n_lines_table = int(matches[0])
return index_table_start, n_lines_table
raise IndexError("Not found start index and length for keyword %s" % table_keyword)
def extract_bottom_header_table(
text_file_lines: List[str], index_start: int, n_lines: int
) -> pd.DataFrame:
"""Function extracting a bottom header template from ROXIE .data and .cadata files. The method requires a start index
in the table as well as the number of lines the table occupies.
:param text_file_lines: an input list of lines from a ROXIE .data or .cadata file
:param index_start: an index where the table starts
:param n_lines: the number of lines occupied by the table
:return: a dataframe with the table
"""
value_rows = text_file_lines[index_start + 1 : index_start + n_lines + 1]
header = text_file_lines[index_start + n_lines + 1]
if "Comment" in header:
columns = ",".join(header.split()[:-1])
else:
columns = ",".join(header.split())
# Replace comment
values_comma_separated = []
comments = []
for value_row in value_rows:
if "'" in value_row:
quotation_split = value_row.split("'")
values_without_comment = ",".join(quotation_split[0].split())
values_comma_separated.append(values_without_comment)
comments.append(quotation_split[1])
else:
values_comma_separated.append(",".join(value_row.split()))
TESTDATA = StringIO("\n".join([columns] + values_comma_separated))
objective_table_df = pd.read_csv(TESTDATA, sep=",")
if comments:
objective_table_df["Comment"] = comments
return objective_table_df
def read_nested_bottom_header_table(
roxie_file_path: str, keyword="LAYER"
) -> pd.DataFrame:
"""Function reading a bottom header table from ROXIE .data, .cadata, .output files
:param roxie_file_path: a path to a roxie file
:param keyword: a table keyword
:return: a nested dataframe with content of a table given by a keyword
"""
with open(roxie_file_path, "r") as text_file:
text_file_lines = text_file.read().split("\n")
index_start, n_lines = find_index_start_and_length_bottom_header_table(
text_file_lines, keyword
)
return extract_nested_bottom_header_table(text_file_lines, index_start, n_lines)
def extract_nested_bottom_header_table(
text_file_lines: List[str], index_start: int, n_lines: int
):
"""Function extracting a bottom header template from ROXIE .data and .cadata files. The method requires a start index
in the table as well as the number of lines the table occupies.
:param text_file_lines: an input list of lines from a ROXIE .data or .cadata file
:param index_start: an index where the table starts
:param n_lines: the number of lines occupied by the table
:return: a dataframe with the table
"""
value_rows = text_file_lines[index_start + 1 : index_start + n_lines + 1]
headers = text_file_lines[index_start + n_lines + 1].split()
header_values = []
for value_row in value_rows:
header_value: Dict[str, Union[int, List[int]]] = {}
values = value_row.split()
for index, header in enumerate(headers[:-1]):
header_value[header] = int(values[index])
# It is assumed that the remaining values for a list assigned to the last column
# Thus it starts from len(headers) - 1 until the last but one element (the last one is \ character)
remaining_values = values[len(headers) - 1 : -1]
header_value[headers[-1]] = [int(value) for value in remaining_values]
header_values.append(header_value)
return pd.DataFrame(header_values)
def read_block_coordinates_from_cnc_file(cnc_file_path: str) -> List[pd.DataFrame]:
with open(cnc_file_path, "r") as file:
cnc_lines = file.readlines()
wedge_indices = [index for index, line in enumerate(cnc_lines) if "WEDGE" in line]
wedge_indices += [len(cnc_lines) + 1]
position_header_indices = [
index for index, line in enumerate(cnc_lines) if "X(mm)" in line
]
pattern = r"([+-]?\d+(?:\.\d+)?)"
prog = re.compile(pattern)
block_coordinates = []
for index in range(len(position_header_indices)):
index_start = position_header_indices[index] + 1
index_stop = wedge_indices[index + 1] - 1
coordinates = cnc_lines[index_start:index_stop]
coordinates_df = pd.DataFrame(
[prog.findall(coordinate) for coordinate in coordinates],
columns=["X(mm)", "Y(mm)", "Z(mm)"],
)
coordinates_df[coordinates_df.columns] = coordinates_df[
coordinates_df.columns
].apply(pd.to_numeric, errors="coerce")
block_coordinates.append(coordinates_df)
return block_coordinates
def convert_figures_of_merit_to_dict(fom_df: pd.DataFrame) -> dict:
fom_dct = {}
for index, row in fom_df.iterrows():
key = "%s_%d_%d" % (index, row["S1"], row["S2"])
fom_dct[key] = row["OBJECTIVE.1"]
return fom_dct
def read_figures_of_merit_table_from_output(output_file_path: str) -> pd.DataFrame:
"""
Returns:
object:
"""
N_OBJECTIVES_KEYWORD = "NUMBER OF OBJECTIVES AND CONSTRAINTS"
output_file = open(output_file_path, "r")
output_lines = output_file.read().split("\n")
output_file.close()
(
idx_start_obj_table,
n_objectives,
) = find_index_start_and_length_objective_table(output_lines, N_OBJECTIVES_KEYWORD)
objective_table_df = extract_objective_table(
output_lines, idx_start_obj_table, n_objectives
)
return objective_table_df
def update_force2d_with_field_scaling(
roxie_force_input_path: str,
roxie_force_output_path: str,
field: float,
target_field: float,
) -> None:
"""Static method scaling ROXIE force with actual and target field
:param roxie_force_input_path: input path with ROXIE Lorentz force
:param roxie_force_output_path: output path with ROXIE Lorentz force
:param field: actual field in tesla
:param target_field: target field in tesla
"""
roxie_force_txt = text_file.readlines(roxie_force_input_path)
# # convert text input to a list of floats
scaling = (target_field / field) ** 2
roxie_force = []
for roxie_force_txt_el in roxie_force_txt:
row_float = [
float(el)
for el in roxie_force_txt_el.replace("\n", "").split(" ")
if el != ""
]
row_float[2] *= scaling
row_float[3] *= scaling
roxie_force.append(row_float)
with open(roxie_force_output_path, "w") as file_write:
for roxie_force_el in roxie_force:
row_str = [str(roxie_force_el_el) for roxie_force_el_el in roxie_force_el]
file_write.write(" ".join(row_str) + "\n")
def convert_roxie_force_file_to_ansys(
input_force_file_path: str, output_force_file_path: str
) -> None:
"""Function preparing a force file for ANSYS from a ROXIE Lorentz force file, .force2d
:param input_force_file_path: a name of a ROXIE Lorentz force file
:param output_force_file_path: a name of an output file for ANSYS
"""
force_txt = text_file.readlines(input_force_file_path)
ansys_force = []
for force_txt_el in force_txt:
row_float = [
float(el) for el in force_txt_el.replace("\n", "").split(" ") if el != ""
]
ansys_force.append("nodeNum = NODE(%f, %f, 0.0)" % tuple(row_float[:2]))
ansys_force.append("F,nodeNum,FX, %f" % row_float[2])
ansys_force.append("F,nodeNum,FY, %f" % row_float[3])
text_file.writelines(output_force_file_path, ansys_force) | /roxie_api-0.0.15-py3-none-any.whl/roxieapi/api.py | 0.836087 | 0.450662 | api.py | pypi |
import os
import xml.etree.ElementTree as ET
from pathlib import Path
from typing import List
import numpy as np
import pandas as pd
from pymbse.commons import text_file # type: ignore
Y_COORDINATE = "y, [mm]"
X_COORDINATE = "x, [mm]"
def correct_xml_file(input_xml_path: str, output_xml_path: str) -> None:
"""Static method for correcting an XML file by removing the first empty line and a first space in the second
line. The corrected XML file is valid and can be automatically parsed.
:param input_xml_path: path of an input XML file
:param output_xml_path: path of an output, corrected XML file
"""
xml_lines = text_file.read(input_xml_path)
# get rid of an extra first line and a starting empty space in the second line
if xml_lines[:2] == "\n ":
xml_lines = xml_lines[2:]
text_file.write(output_xml_path, xml_lines)
def parse_xml_element(element: ET.Element) -> list:
data_str = str(element.text).replace(";", "").split("\n")
data = []
for data_el in data_str:
if "," in data_el:
data.append(float(data_el.split(",")[1]))
return data
def read_index_to_variable_xml_output(
index_to_variable_xml_output_path: str,
) -> dict:
path = Path(os.path.dirname(__file__))
full_path = os.path.join(path, index_to_variable_xml_output_path)
index_to_variable_xml_output_df = pd.read_csv(full_path, index_col=0)
return {
index: row["variable"]
for index, row in index_to_variable_xml_output_df.iterrows()
}
def parse_roxie_xml(file_path: str) -> pd.DataFrame:
"""Function parsing a ROXIE XML file and returning a dataframe with strand positions and field values given by id
:param file_path: a path to a file
:return: output dataframe with strand positions and field values
"""
mytree = ET.parse(file_path)
mytree.getroot().get("x")
x_values, y_values = _read_x_y_values_from_xml(
mytree, xml_tree_location="loop/step/loop/step/loop/coilGeom/strands/p"
)
x_strands = []
y_strands = []
for i in range(0, len(x_values), 4):
x_strands.append(np.mean(x_values[i : i + 4]))
y_strands.append(np.mean(y_values[i : i + 4]))
if not mytree.getroot().findall("loop/step/loop/step/loop/step/coilData"):
raise IndexError(
"The XML file does not contain coilData with results. "
"Please enable plotting in the ROXIE data file"
)
data_dct = {X_COORDINATE: x_strands, Y_COORDINATE: y_strands}
index_to_variable = read_index_to_variable_xml_output(
"index_to_variable_xml_output.csv"
)
for data_element in mytree.getroot().findall(
"loop/step/loop/step/loop/step/coilData"
):
data = parse_xml_element(data_element)
index = int(data_element.attrib["id"])
data_dct[index_to_variable[index]] = data
return pd.DataFrame(data_dct)
def _read_x_y_values_from_xml(mytree, xml_tree_location=""):
x_values = []
y_values = []
for type_tag in mytree.getroot().findall(xml_tree_location):
x_value = float(str(type_tag.get("x")))
y_value = float(str(type_tag.get("y")))
x_values.append(x_value)
y_values.append(y_value)
return x_values, y_values
def read_graph_dfs(
xml_file_path: str, graph_table_df: pd.DataFrame
) -> List[pd.DataFrame]:
graphs = read_graphs_as_xy_from_xml(xml_file_path)
graph_dfs = []
for index, graph in enumerate(graphs):
xy = convert_graph_from_text_to_float(graph)
index_name = concat_name(graph_table_df, index, ["xvalue", "s1x", "s2x"])
col_name = concat_name(graph_table_df, index, ["yvalue", "s1y", "s2y"])
graph_df = pd.DataFrame(
index=pd.Index([xy_el[0] for xy_el in xy], name=index_name),
data=[xy_el[1] for xy_el in xy],
columns=[col_name],
)
graph_dfs.append(graph_df)
return graph_dfs
def read_graphs_as_xy_from_xml(file_path):
mytree = ET.parse(file_path)
mytree.getroot().get("x")
return mytree.getroot().findall("loop/step/loop/step/loop/step/graph")
def convert_graph_from_text_to_float(graph):
xy_lines = graph.text.split(";\n")
xy_str = [xy_line.strip().split(",") for xy_line in xy_lines[:-1]]
return [(float(x), float(y)) for x, y in xy_str]
def concat_name(df, index, columns):
name_segments = df.loc[index, columns].values
return "_".join([str(name_segment) for name_segment in name_segments])
def read_mesh_data_and_elements(roxie_data_xml_path: str) -> tuple:
mytree = ET.parse(roxie_data_xml_path)
mytree.getroot().get("x")
x_values, y_values = _read_x_y_values_from_xml(
mytree, "loop/step/loop/step/loop/meshGeom/nodes/p"
)
elements = _read_mesh_elements_from_xml(
mytree, "loop/step/loop/step/loop/meshGeom/elements/fe"
)
mesh_data = _read_mesh_data(mytree)
return (
pd.concat(
[pd.DataFrame({X_COORDINATE: x_values, Y_COORDINATE: y_values}), mesh_data],
axis=1,
),
elements,
)
def _read_mesh_elements_from_xml(mytree, xml_tree_location):
elements = []
for type_tag in mytree.getroot().findall(xml_tree_location):
element = [int(item[1]) - 1 for item in type_tag.items()]
elements.append(element)
return elements
def _read_mesh_data(mytree) -> pd.DataFrame:
mesh_plot_infos = mytree.getroot().findall("loop/step/loop/step/loop/meshPlotInfo")
mesh_plot_label_to_id = {
mesh_plot_info.attrib["id"]: mesh_plot_info.attrib["label"]
for mesh_plot_info in mesh_plot_infos
}
data_values_dct = {}
for data_element in mytree.getroot().findall(
"loop/step/loop/step/loop/step/meshData"
):
data_id = data_element.get("id")
data_values = [float(value.attrib["v"]) for value in data_element.findall("d")]
data_values_dct[mesh_plot_label_to_id[data_id]] = data_values
return pd.DataFrame(data_values_dct) | /roxie_api-0.0.15-py3-none-any.whl/roxieapi/xml_api.py | 0.647575 | 0.406685 | xml_api.py | pypi |
import json
from typing import List, Union, TypeVar
import pandas as pd
from roxieapi.cadata.CableDefinition import CableDefinition
from roxieapi.cadata.ConductorDefinition import ConductorDefinition
from roxieapi.cadata.Definition import Definition
from roxieapi.cadata.FilamentDefinition import FilamentDefinition
from roxieapi.cadata.InsulationDefinition import InsulationDefinition
from roxieapi.cadata.QuenchDefinition import QuenchDefinition
from roxieapi.cadata.RemFitDefinition import RemFitDefinition
from roxieapi.cadata.StrandDefinition import StrandDefinition
from roxieapi.cadata.TransientDefinition import TransientDefinition
import roxieapi.api as RoxieAPI
import pymbse.commons.json_file as json_file
import pymbse.commons.text_file as text_file
from pymbse.commons.directory_manager import check_if_file_exists
definition_type = Union[
CableDefinition,
ConductorDefinition,
FilamentDefinition,
InsulationDefinition,
QuenchDefinition,
RemFitDefinition,
StrandDefinition,
TransientDefinition,
]
TDefinition = TypeVar("TDefinition", bound=Definition)
class CableDatabase:
"""Class providing an interface to read, write, and access cable database definitions."""
keyword_to_class = {
"INSUL": InsulationDefinition,
"REMFIT": RemFitDefinition,
"FILAMENT": FilamentDefinition,
"STRAND": StrandDefinition,
"TRANSIENT": TransientDefinition,
"QUENCH": QuenchDefinition,
"CABLE": CableDefinition,
"CONDUCTOR": ConductorDefinition,
}
def __init__(
self,
insul_defs: List[InsulationDefinition],
remfit_defs: List[RemFitDefinition],
filament_defs: List[FilamentDefinition],
strand_defs: List[StrandDefinition],
transient_defs: List[TransientDefinition],
quench_defs: List[QuenchDefinition],
cable_defs: List[CableDefinition],
conductor_defs: List[ConductorDefinition],
) -> None:
self.insul_defs = insul_defs
self.remfit_defs = remfit_defs
self.filament_defs = filament_defs
self.strand_defs = strand_defs
self.transient_defs = transient_defs
self.quench_defs = quench_defs
self.cable_defs = cable_defs
self.conductor_defs = conductor_defs
@classmethod
def initialize_definitions(
cls, cadata_file_path: str, keyword: str
) -> List[TDefinition]:
"""Method initializing a list of definitions of a given type from a given cadata file. Method reads a cadata
file and returns a dictionary, which is converted into a list of dictionaries. The list of dictionaries is
converted into a list of definitions.
:param cadata_file_path: a path to a cadata file
:param keyword: a cadata table name
:return: a list of cadata definitions for a given table name
"""
ClassDefinition = cls.keyword_to_class[keyword.upper()]
try:
df = RoxieAPI.read_bottom_header_table(cadata_file_path, keyword=keyword)
df = df.drop(columns=["No"])
df = df.rename(columns=ClassDefinition.get_roxie_to_magnum_dct())
df_dicts = df.to_dict("records")
defs: List[TDefinition] = []
for df_dict in df_dicts:
defs.append(ClassDefinition(**df_dict)) # type: ignore
return defs
except IndexError:
return [ClassDefinition()] # type: ignore
def get_insul_definition(self, condname: str) -> InsulationDefinition:
"""Method returning an insulation definition for a given conductor name
:param condname: conductor name
:return: insulation definition if match, otherwise a KeyError is thrown
"""
insul_name = self.get_conductor_definition(condname).insulation
return _find_matching_definition(self.insul_defs, insul_name, "insulation")
def get_remfit_definition(self, condname: str) -> RemFitDefinition:
"""Method returning a remfit definition for a given conductor name
:param condname: conductor name
:return: remfit definition if match, otherwise a KeyError is thrown
"""
remfit_name = self.get_filament_definition(condname).fit_perp
return _find_matching_definition(self.remfit_defs, remfit_name, "rem_fit")
def get_filament_definition(self, condname: str) -> FilamentDefinition:
"""Method returning a filament definition for a given conductor name
:param condname: conductor name
:return: filament definition if match, otherwise a KeyError is thrown
"""
filament_name = self.get_conductor_definition(condname).filament
return _find_matching_definition(self.filament_defs, filament_name, "filament")
def get_strand_definition(self, condname: str) -> StrandDefinition:
"""Method returning a strand definition for a given conductor name
:param condname: conductor name
:return: strand definition if match, otherwise a KeyError is thrown
"""
strand_name = self.get_conductor_definition(condname).strand
return _find_matching_definition(self.strand_defs, strand_name, "strand")
def get_transient_definition(self, condname: str) -> TransientDefinition:
"""Method returning a transient definition for a given conductor name. If there is no transient definition for
a given condname, then an empty transient definition is returned.
:param condname: conductor name
:return: transient definition if match, otherwise a KeyError is thrown
"""
trans_name = self.get_conductor_definition(condname).transient
if trans_name == "NONE":
return TransientDefinition()
return _find_matching_definition(self.transient_defs, trans_name, "transient")
def get_quench_definition(self, condname: str) -> QuenchDefinition:
"""Method returning a quench definition for a given conductor name. If there is no quench definition for
a given condname, then an empty quench definition is returned.
:param condname: conductor name
:return: quench definition if match, otherwise a KeyError is thrown
"""
quench_name = self.get_conductor_definition(condname).quench_mat
if quench_name == "NONE":
return QuenchDefinition()
return _find_matching_definition(self.quench_defs, quench_name, "quench")
def get_cable_definition(self, condname: str) -> CableDefinition:
"""Method returning an insulation definition for a given conductor name
:param condname: conductor name
:return: insulation definition if match, otherwise a KeyError is thrown
"""
geometry_name = self.get_conductor_definition(condname).cable_geom
return _find_matching_definition(self.cable_defs, geometry_name, "cable")
def get_conductor_definition(self, condname: str) -> ConductorDefinition:
"""Method returning an insulation definition for a given conductor name
:param condname: conductor name
:return: insulation definition if match, otherwise a KeyError is thrown
"""
return _find_matching_definition(self.conductor_defs, condname, "conductor")
@classmethod
def read_json(cls, json_file_path: str) -> "CableDatabase":
"""Method reading a json file and returning an initialized CableDatabase instance. Some definitions are
optional. In this case, the
:param json_file_path: a path
:return: a CableDatabase instance with initialized lists of definitions
"""
data = json_file.read(json_file_path)
# Optional definitions
if "remfit" in data:
remfit_defs = [
RemFitDefinition(**remfit_def) for remfit_def in data["remfit"]
]
else:
remfit_defs = [RemFitDefinition()]
if "transient" in data:
transient_defs = [
TransientDefinition(**transient_def)
for transient_def in data["transient"]
]
else:
transient_defs = [TransientDefinition()]
if "quench" in data:
quench_defs = [
QuenchDefinition(**quench_def) for quench_def in data["quench"]
]
else:
quench_defs = [QuenchDefinition()]
# Mandatory definitions
insul_defs = [
InsulationDefinition(**insulation_def)
for insulation_def in data["insulation"]
]
filament_defs = [
FilamentDefinition(**filament_def) for filament_def in data["filament"]
]
strand_defs = [StrandDefinition(**strand_def) for strand_def in data["strand"]]
cable_defs = [CableDefinition(**cable_def) for cable_def in data["cable"]]
conductor_defs = [
ConductorDefinition(**conductor_def) for conductor_def in data["conductor"]
]
return CableDatabase(
insul_defs=insul_defs,
remfit_defs=remfit_defs,
filament_defs=filament_defs,
strand_defs=strand_defs,
transient_defs=transient_defs,
quench_defs=quench_defs,
cable_defs=cable_defs,
conductor_defs=conductor_defs,
)
def write_json(self, json_output_path: str) -> None:
"""Method writing a CableDatabase instance into a json file.
:param json_output_path: a path to an output json file
"""
json_cadata = {
"insulation": self._get_insulation_definitions_as_list_of_dict(),
"remfit": self._get_remfit_definitions_as_list_of_dict(),
"filament": self._get_filament_definitions_as_list_of_dict(),
"strand": self._get_strand_definitions_as_list_of_dict(),
"transient": self._get_transient_definitions_as_list_of_dict(),
"quench": self._get_quench_definitions_as_list_of_dict(),
"cable": self._get_cable_definitions_as_list_of_dict(),
"conductor": self._get_conductor_definitions_as_list_of_dict(),
}
with open(json_output_path, "w", encoding="utf-8") as f:
json.dump(json_cadata, f, ensure_ascii=False, indent=4)
def _get_conductor_definitions_as_list_of_dict(self):
"""Method returning a list of conductor definitions as a list of dictionaries sorted with ROXIE order.
:return: a list of dictionaries with conductor definitions sorted with ROXIE order
"""
return [
ConductorDefinition.reorder_dct(conductor_def.__dict__)
for conductor_def in self.conductor_defs
]
def _get_cable_definitions_as_list_of_dict(self):
"""Method returning a list of cable definitions as a list of dictionaries sorted with ROXIE order.
:return: a list of dictionaries with cable definitions sorted with ROXIE order
"""
return [
CableDefinition.reorder_dct(cable_def.__dict__)
for cable_def in self.cable_defs
]
def _get_quench_definitions_as_list_of_dict(self):
"""Method returning a list of quench definitions as a list of dictionaries sorted with ROXIE order.
:return: a list of dictionaries with quench definitions sorted with ROXIE order
"""
return [
QuenchDefinition.reorder_dct(quench_def.__dict__)
for quench_def in self.quench_defs
]
def _get_transient_definitions_as_list_of_dict(self):
"""Method returning a list of transient definitions as a list of dictionaries sorted with ROXIE order.
:return: a list of dictionaries with transient definitions sorted with ROXIE order
"""
return [
TransientDefinition.reorder_dct(transient_def.__dict__)
for transient_def in self.transient_defs
]
def _get_strand_definitions_as_list_of_dict(self):
"""Method returning a list of strand definitions as a list of dictionaries sorted with ROXIE order.
:return: a list of dictionaries with strand definitions sorted with ROXIE order
"""
return [
StrandDefinition.reorder_dct(strand_def.__dict__)
for strand_def in self.strand_defs
]
def _get_filament_definitions_as_list_of_dict(self):
"""Method returning a list of filament definitions as a list of dictionaries sorted with ROXIE order.
:return: a list of dictionaries with filament definitions sorted with ROXIE order
"""
return [
FilamentDefinition.reorder_dct(filament_def.__dict__)
for filament_def in self.filament_defs
]
def _get_remfit_definitions_as_list_of_dict(self):
"""Method returning a list of remfit definitions as a list of dictionaries sorted with ROXIE order.
:return: a list of dictionaries with remfit definitions sorted with ROXIE order
"""
return [
RemFitDefinition.reorder_dct(remfit_def.__dict__)
for remfit_def in self.remfit_defs
]
def _get_insulation_definitions_as_list_of_dict(self):
"""Method returning a list of insulation definitions as a list of dictionaries sorted with ROXIE order.
:return: a list of dictionaries with insulation definitions sorted with ROXIE order
"""
return [
InsulationDefinition.reorder_dct(insul_def.__dict__)
for insul_def in self.insul_defs
]
@classmethod
def read_cadata(cls, cadata_file_path: str) -> "CableDatabase":
"""Method reading a cadata file and returns an initialized CableDatabase instance with a list of definitions.
:param cadata_file_path: a path to a cadata file
:return: a CableDatabase instance with initialized lists of definitions
"""
check_if_file_exists(cadata_file_path)
return CableDatabase(
insul_defs=cls.initialize_definitions(cadata_file_path, keyword="INSUL"),
remfit_defs=cls.initialize_definitions(cadata_file_path, keyword="REMFIT"),
filament_defs=cls.initialize_definitions(
cadata_file_path, keyword="FILAMENT"
),
strand_defs=cls.initialize_definitions(cadata_file_path, keyword="STRAND"),
transient_defs=cls.initialize_definitions(
cadata_file_path, keyword="TRANSIENT"
),
quench_defs=cls.initialize_definitions(cadata_file_path, keyword="QUENCH"),
cable_defs=cls.initialize_definitions(cadata_file_path, keyword="CABLE"),
conductor_defs=cls.initialize_definitions(
cadata_file_path, keyword="CONDUCTOR"
),
)
def write_cadata(self, cadata_output_path: str) -> None:
"""Method writing a CableDatabase instance into a cadata file.
:param cadata_output_path: a path to an output cadata file
"""
output = [
"VERSION 11",
self._convert_definition_df_to_bottom_header_str(
self.get_insul_df(), "INSUL"
),
self._convert_definition_df_to_bottom_header_str(
self.get_remfit_df(), "REMFIT"
),
self._convert_definition_df_to_bottom_header_str(
self.get_filament_df(), "FILAMENT"
),
self._convert_definition_df_to_bottom_header_str(
self.get_strand_df(), "STRAND"
),
self._convert_definition_df_to_bottom_header_str(
self.get_transient_df(), "TRANSIENT"
),
self._convert_definition_df_to_bottom_header_str(
self.get_quench_df(), "QUENCH"
),
self._convert_definition_df_to_bottom_header_str(
self.get_cable_df(), "CABLE"
),
self._convert_definition_df_to_bottom_header_str(
self.get_conductor_df(), "CONDUCTOR"
),
]
# Write to a text file
text_file.writelines(cadata_output_path, output, endline="\n\n")
@classmethod
def _convert_definition_df_to_bottom_header_str(
cls, df: pd.DataFrame, keyword: str
) -> str:
"""Method converting a definition dataframe to a string representation as a bottom header table for ROXIE.
:param df: input dataframe with definitions
:param keyword: name of a table
:return: a string formatted as a bottom header table of ROXIE
"""
# Get the definition class
ClassDefinition = cls.keyword_to_class[keyword.upper()]
# Convert to a dataframe
df = df.rename(columns=ClassDefinition.get_magnum_to_roxie_dct())
# Take only those columns that are needed for ROXIE
df = df[ClassDefinition.get_roxie_to_magnum_dct().keys()]
# Add apostrophes around comment column
df["Comment"] = "'" + df["Comment"] + "'"
# Add No column (1-based)
columns = df.columns
df["No"] = df.index + 1
df = df[["No"] + list(columns)]
df = df.astype({"No": "int32"})
# Convert a dataframe to a bottom header table
return RoxieAPI.convert_bottom_header_table_to_str(df, keyword=keyword)
def get_insul_df(self) -> pd.DataFrame:
"""Method returning a dataframe table with insulation definitions.
:return: a dataframe table with insulation definitions.
"""
insulation_definitions = self._get_insulation_definitions_as_list_of_dict()
return pd.DataFrame(insulation_definitions)
def get_remfit_df(self) -> pd.DataFrame:
"""Method returning a dataframe table with remfit definitions.
:return: a dataframe table with remfit definitions.
"""
remfit_definitions = self._get_remfit_definitions_as_list_of_dict()
return pd.DataFrame(remfit_definitions)
def get_filament_df(self) -> pd.DataFrame:
"""Method returning a dataframe table with filament definitions.
:return: a dataframe table with filament definitions.
"""
filament_definitions = self._get_filament_definitions_as_list_of_dict()
return pd.DataFrame(filament_definitions)
def get_strand_df(self) -> pd.DataFrame:
"""Method returning a dataframe table with strand definitions.
:return: a dataframe table with strand definitions.
"""
strand_definitions = self._get_strand_definitions_as_list_of_dict()
return pd.DataFrame(strand_definitions)
def get_transient_df(self) -> pd.DataFrame:
"""Method returning a dataframe table with transient definitions.
:return: a dataframe table with transient definitions.
"""
transient_definitions = self._get_transient_definitions_as_list_of_dict()
return pd.DataFrame(transient_definitions)
def get_quench_df(self) -> pd.DataFrame:
"""Method returning a dataframe table with quench definitions.
:return: a dataframe table with quench definitions.
"""
quench_definitions = self._get_quench_definitions_as_list_of_dict()
return pd.DataFrame(quench_definitions)
def get_cable_df(self) -> pd.DataFrame:
"""Method returning a dataframe table with cable definitions.
:return: a dataframe table with cable definitions.
"""
cable_definitions = self._get_cable_definitions_as_list_of_dict()
return pd.DataFrame(cable_definitions)
def get_conductor_df(self) -> pd.DataFrame:
"""Method returning a dataframe table with conductor definitions.
:return: a dataframe table with conductor definitions.
"""
conductor_definitions = self._get_conductor_definitions_as_list_of_dict()
return pd.DataFrame(conductor_definitions)
def _find_matching_definition(
defs: List[TDefinition], name_def: str, desc_def: str
) -> TDefinition:
"""Function finding a definition with a matching name in a list of input definitions. If there is a match, then
the definition is returned, otherwise a KeyError is thrown.
:param defs: list of input definitions over which a search is performed.
:param name_def: name of a definition to find.
:param desc_def: name of a key storing the definition name.
:return: If there is a match, then the definition is returned, otherwise a KeyError is thrown.
"""
matches = list(filter(lambda x: x.name == name_def, defs))
if matches:
return matches[0]
else:
raise KeyError(
"%s name %s not present in %s definitions."
% (desc_def.capitalize(), name_def, desc_def)
) | /roxie_api-0.0.15-py3-none-any.whl/roxieapi/cadata/CableDatabase.py | 0.837354 | 0.2838 | CableDatabase.py | pypi |
from typing import Optional
from pydantic.dataclasses import dataclass
from roxieapi.cadata.Definition import Definition
@dataclass
class QuenchDefinition(Definition):
"""Class for quench definition.
Attributes:
cp_sc (str): The fit function for the specific heat of the superconductor.
See also: http://cern.ch/roxie > Documentation > Materials.pdf
cp_cu (str): The fit function for the specific heat of copper.
See also: http://cern.ch/roxie > Documentation > Materials.pdf
k_cu (str): The fit function for the thermal conductivity of copper.
See also: http://cern.ch/roxie > Documentation > Materials.pdf
res_cu (str): The fit function for the electrical resistitvity of copper.
See also: http://cern.ch/roxie > Documentation > Materials.pdf
cp_ins (str): The fit function for the heat capacity of the cable insulation.
See also: http://cern.ch/roxie > Documentation > Materials.pdf
k_ins (str): The fit function for the thermal conductivity of the cable insulation.
See also: http://cern.ch/roxie > Documentation > Materials.pdf
cp_fill (str): The fit function for the heat capacity of the material filling the cable voids.
See also: http://cern.ch/roxie > Documentation > Materials.pdf
perc_he (float): The percentage of the cable voids that is filled by helium.
"""
cp_sc: Optional[int] = None
cp_cu: Optional[int] = None
k_cu: Optional[int] = None
res_cu: Optional[int] = None
cp_ins: Optional[int] = None
k_ins: Optional[int] = None
cp_fill: Optional[int] = None
perc_he: Optional[float] = None
@staticmethod
def get_magnum_to_roxie_dct() -> dict:
return {
"name": "Name",
"cp_sc": "SCHeatCapa",
"cp_cu": "CuHeatCapa",
"k_cu": "CuThermCond",
"res_cu": "CuElecRes",
"cp_ins": "InsHeatCapa",
"k_ins": "InsThermCond",
"cp_fill": "FillHeatCapa",
"perc_he": "He%",
"comment": "Comment",
} | /roxie_api-0.0.15-py3-none-any.whl/roxieapi/cadata/QuenchDefinition.py | 0.900757 | 0.459501 | QuenchDefinition.py | pypi |
import math
from pydantic.dataclasses import dataclass
from roxieapi.cadata.Definition import Definition
@dataclass
class StrandDefinition(Definition):
"""Class for strand definition.
Attributes:
d_strand (float): The strand diameter (mm).
f_cu_nocu (float): The Copper to superconductor ratio.
rrr (float): The Residual Resistivity ratio.
temp_ref (float): The Reference Temperature (K) for Bref. This value is never used in the code and serves
only for reference for Bref and Jc@BrTr.
b_ref (float): The Reference Field for the definition of a linear approximation of the Jc curve.
j_c_at_b_ref_t_ref (float): The Critical current density at Bref for the definition of a linear approximation
of the Jc curve. (LINMARG)
dj_c_over_db (float): dJc/dB at Bref and Tref for the definition of a linear approximation of the Jc curve.
(LINMARG)
"""
d_strand: float = 0.0
f_cu_nocu: float = 0.0
rrr: float = 0.0
temp_ref: float = 0.0
b_ref: float = 0.0
j_c_at_b_ref_t_ref: float = 0.0
dj_c_over_db: float = 0.0
@staticmethod
def get_magnum_to_roxie_dct() -> dict:
return {
"name": "Name",
"d_strand": "diam.",
"f_cu_nocu": "cu/sc",
"rrr": "RRR",
"temp_ref": "Tref",
"b_ref": "Bref",
"j_c_at_b_ref_t_ref": "Jc@BrTr",
"dj_c_over_db": "dJc/dB",
"comment": "Comment",
}
def compute_surface_cu(self):
"""Method computing copper surface of a strand as S = f_co * pi * d_strand^2 / 4
:return: a copper surface of a strand in mm^2
"""
return self.compute_f_cu() * self.compute_surface()
def compute_surface_nocu(self):
"""Method computing non-copper surface of a strand as S = f_nocu * pi * d_strand^2 / 4
:return: a non-copper surface of a strand in mm^2
"""
return self.compute_f_nocu() * self.compute_surface()
def compute_f_nocu(self):
"""Method fraction of non-copper in a strand
:return: a fraction of non-copper in a strand (no unit)
"""
return 1 / (1 + self.f_cu_nocu)
def compute_f_cu(self):
"""Method fraction of copper in a strand
:return: a fraction of copper in a strand (no unit)
"""
return self.f_cu_nocu / (1 + self.f_cu_nocu)
def compute_surface(self):
"""Method computing surface of a strand as S = pi * d_strand^2 / 4
:return: a surface of a strand in mm^2
"""
return math.pi * self.d_strand**2 / 4 | /roxie_api-0.0.15-py3-none-any.whl/roxieapi/cadata/StrandDefinition.py | 0.845656 | 0.72059 | StrandDefinition.py | pypi |
import os
from pathlib import Path
import jinja2
import pandas as pd
from roxieapi.api import convert_bottom_header_table_to_str, convert_table_to_str
class RoxieInputBuilder:
"""Class RoxieInputBuilder builds a ROXIE input"""
comment = ""
bhdata_path = ""
cadata_path = ""
iron_path = ""
flags = {
"LEND": False,
"LWEDG": False,
"LPERS": False,
"LQUENCH": False,
"LALGO": False,
"LQUENCH0D": False,
"LMIRIRON": False,
"LBEMFEM": False,
"LPSI": False,
"LSOLV": False,
"LIRON": False,
"LMORPH": False,
"LHARD": False,
"LPOSTP": False,
"LPEAK": False,
"LINMARG": False,
"LMARG": False,
"LSELF": False,
"LMQE": False,
"LINDU": False,
"LEDDY": False,
"LSOLE": False,
"LFLUX": False,
"LFIELD3": False,
"LFISTR": False,
"LSELF3": False,
"LBRICK": False,
"LLEAD": False,
"LVRML": False,
"LOPERA": False,
"LOPER20": False,
"LANSYS": False,
"LRX2ANS": False,
"LANS2RX": False,
"LDXF": False,
"LMAP2D": False,
"LMAP3D": False,
"LEXPR": False,
"LFIL3D": False,
"LFIL2D": False,
"LCNC": False,
"LANSYSCN": False,
"LWEIRON": False,
"LCATIA": False,
"LEXEL": False,
"LQVOLT": False,
"LFORCE2D": False,
"LAXIS": False,
"LIMAGX": False,
"LIMAGY": False,
"LRAEND": False,
"LMARKER": False,
"LROLER2": False,
"LROLERP": False,
"LIMAGZZ": False,
"LSUPP": False,
"LSTEP": False,
"LIFF": False,
"LICCA": False,
"LICC": False,
"LICCIND": False,
"LITERNL": False,
"LTOPO": False,
"LQUEN3": False,
"LAYER": False,
"LEULER": False,
"LHEAD": False,
"LPLOT": False,
"LVERS52": False,
"LHARM": False,
"LMATRF": False,
"LF3LIN": False,
"LKVAL": False,
}
global2doption = pd.DataFrame()
global3d = pd.DataFrame()
block = pd.DataFrame()
blockoption = pd.DataFrame()
block3d = pd.DataFrame()
lead = pd.DataFrame()
brick = pd.DataFrame()
ironyokeoptions = pd.DataFrame()
ironyoke = pd.DataFrame()
extrusion = pd.DataFrame()
permanentmag2 = pd.DataFrame()
permanentmag1 = pd.DataFrame()
layer = pd.DataFrame()
algo = pd.DataFrame()
design = pd.DataFrame()
euler = pd.DataFrame()
peak = pd.DataFrame()
timetable2 = pd.DataFrame()
timetable1 = pd.DataFrame()
eddy = pd.DataFrame()
eddyoptions = pd.DataFrame()
quenchg = pd.DataFrame()
quenchen = pd.DataFrame()
quenchtm = pd.DataFrame()
quenchp = pd.DataFrame()
quenchs = pd.DataFrame()
quench0d = pd.DataFrame()
harmonictable = pd.DataFrame()
matrf = pd.DataFrame()
linefield = pd.DataFrame()
kvalues = pd.DataFrame()
harmonicoption = pd.DataFrame()
graph = pd.DataFrame()
graphoption = pd.DataFrame()
plot2d = pd.DataFrame()
plot2doption = pd.DataFrame()
plot3d = pd.DataFrame()
plot3doption = pd.DataFrame()
ansysoptions = pd.DataFrame()
objective = pd.DataFrame()
def set_flag(self, flag_name: str, flag_value: bool) -> "RoxieInputBuilder":
"""Method setting a flag in a ROXIE input file. An error is thrown if a flag does not exist
:param flag_name: name of a flag
:param flag_value: value of a flag
:return: an updated RoxieInputBuilder instance
"""
if flag_name in self.flags.keys():
self.flags[flag_name] = flag_value
else:
raise KeyError("Key")
return self
def build(self, output_path: str) -> None:
"""Method building a ROXIE input based on a template file
:param output_path: an output path for the input .data file
"""
output_str = self.prepare_data_file_str_from_template()
with open(output_path, "wb") as input_file:
input_file.write(bytes(output_str, "utf-8").replace(b"\r\n", b"\n"))
def prepare_data_file_str_from_template(self) -> str:
path = Path(os.path.dirname(__file__))
template_loader = jinja2.FileSystemLoader(searchpath=path)
template_env = jinja2.Environment(loader=template_loader)
template_env.globals[
"convert_bottom_header_table_to_str"
] = convert_bottom_header_table_to_str
template_env.globals["convert_table_to_str"] = convert_table_to_str
template_env.globals[
"convert_flag_dct_to_str"
] = RoxieInputBuilder.convert_flag_dct_to_str
template_env.globals["str"] = str
TEMPLATE_FILE = "roxie_template.data"
template = template_env.get_template(TEMPLATE_FILE)
return template.render(input=self)
@staticmethod
def convert_flag_dct_to_str(flags: dict) -> str:
"""Static method converting a dictionary with flags into a formatted string
:param flags: a dictionary with flags
:return: a formatted string representation of the dictionary with flags
"""
COLUMN_WIDTH = 11
flag_per_line_count = 1
flag_str = " "
for key, value in flags.items():
temp = "%s=%s" % (key, "T" if value else "F")
temp += (COLUMN_WIDTH - len(temp)) * " "
if flag_per_line_count < 6:
flag_str += temp
flag_per_line_count += 1
else:
flag_str += temp + "\n "
flag_per_line_count = 1
flag_str += "\n /"
return flag_str
@staticmethod
def append_to_outputs(
outputs, keyword, df, line_suffix="", header_suffix=""
) -> None:
"""Static method appending to the output list (in place) a dataframe with a keyword
:param outputs: a list of outputs for an input file
:param keyword: a table keyword
:param df: a dataframe
"""
outputs.append("")
outputs.append(
convert_bottom_header_table_to_str(df, keyword, line_suffix, header_suffix)
) | /roxie_api-0.0.15-py3-none-any.whl/roxieapi/input_builder/RoxieInputBuilder.py | 0.451568 | 0.182062 | RoxieInputBuilder.py | pypi |
from __future__ import annotations
from typing import Union
from pathlib import Path
from logging import getLogger
from os import environ, getpid
from mmap import mmap, ACCESS_READ, ACCESS_WRITE
from shutil import rmtree
log = getLogger(__name__)
class _RingBufferSet():
def __init__(self):
""" リング式バッファセット
"""
self.list: list[InspectBuffer] = []
self.index: int = 0
def get_next(self) -> InspectBuffer:
""" 次のバッファを取得
"""
self.index = (self.index + 1) % len(self.list)
return self.list[self.index]
@property
def buffer(self) -> InspectBuffer:
""" 現在のバッファを取得
"""
return self.list[self.index]
class InspectBuffer():
_root_path = Path(environ.get('TEMP')) / 'roxyai_api_buffer' / str(getpid())
# バッファ名に対応するリングバッファ辞書
_name_dict: dict[str, _RingBufferSet] = {}
@classmethod
def clean(cls):
""" Roxy AI のメモリマップドファイルを全て削除する
Note:
ロックされているファイルは無視
起動時に1度だけ実行する想定
"""
if cls._root_path.parent.exists():
for path in cls._root_path.parent.iterdir():
try:
if path.is_dir():
rmtree(str(path))
else:
path.unlink()
except Exception as e:
log.info(
f'{cls.__name__}: failed to clear {path}: {e}'
)
@classmethod
def release_all(cls):
""" 管理しているバッファを全て開放する
"""
for name, lst in cls._name_dict.items():
for i, buf in enumerate(lst.list):
try:
buf._release()
except Exception as e:
log.warning(
f'{cls.__name__}: failed to release buffer '
f'"{name}:{i}"\n{e}'
)
cls._name_dict.clear()
@classmethod
def alloc_set(cls, set_name: str, set_size: int, buffer_size: int) -> InspectBuffer:
""" バッファセットをメモリマップ上に取得する
Args:
set_name: バッファセット名
set_size: セットで作成するバッファ数
buffer_size: バッファサイズ[bytes]
Returns:
InspectBuffer: 作成した先頭のバッファインスタンス
None: バッファの作成失敗
"""
buf = None
if set_size < 1:
ValueError(f'{cls.__name__}: number must be greater than 0')
buf_set = cls._name_dict.get(set_name)
if buf_set:
# 既に同名のバッファセットを生成済み
if (buf_set.buffer.size != buffer_size):
log.warning(
f'{cls.__name__}: {set_name}:{buf.id} size is different from {buffer_size}'
)
buf = buf_set.get_next()
else:
try:
buf_set = _RingBufferSet()
for index in range(set_size):
# バッファの確保
file_name = f'{set_name}_{index:03d}'
path = cls._create_temp_file(file_name, buffer_size)
# 書き込み可能でバッファを取得
buff = cls(path, read_only=False)
buf_set.list.append(buff)
# バッファセットを登録
cls._name_dict[set_name] = buf_set
buf = buf_set.buffer
except Exception as e:
log.warning(
f'{cls.__name__}: falied to allocate buffer, '
f'name: "{set_name}", nubmer: {set_size}, '
f'size: {buffer_size:,d}\n{e}'
)
return buf
@classmethod
def get_next_buffer(cls, set_name) -> mmap:
""" 次のバッファを取得する
Args:
set_name: バッファ名
Returns:
InspectBuffer: 次のバッファインスタンス
None: バッファがない
"""
ret = None
if cls._name_dict.get(set_name):
lst = cls._name_dict[set_name]
cls._name_index[set_name] = 0
if len(lst) > 0:
ret = lst.pop(0)
return ret
@classmethod
def _create_temp_file(cls, name: str, size: int) -> Path:
""" メモリマップドファイル用のファイルを生成する
Args:
name: ファイル名
size: ファイルサイズ[bytes]
Returns:
Path: ファイルパス
"""
try:
# 格納ディレクトリ作成
cls._root_path.mkdir(parents=True, exist_ok=True)
path = cls._root_path / name
if path.exists():
log.warning(f'{cls.__name__}: file already exists: {path}')
# Windowsは空のファイルを利用できないので適当なファイルを作成
with open(path, 'wb') as fd:
fd.write(b'\0' * size)
fd.flush()
except Exception as e:
log.warning(
f'{cls.__name__}: failed to allocate buffer, '
f'name: "{name}", size: {size:,d}\n{e}'
)
raise
return path
def __init__(self, path: Union[str, Path], read_only: bool = True):
""" 検査用のバッファ管理
Args:
path: メモリマップドファイルパス
read_only: 読み取り専用か
Notes:
メモリマップドファイル上にバッファを確保する
"""
self._path = Path(path).resolve()
self._name = self._path.name[:-4]
self._id = int(self._path.name[-3])
self._fd = None
self._mm = None
self._size = None
self._read_only = read_only
# インスタンス生成時にバッファ獲得
self._mmap()
def _mmap(self) -> bool:
""" バッファをメモリマップ上に取得する
Returns:
True: 獲得成功
False: 獲得失敗
"""
try:
# ファイルオープン
self._fd = open(self._path, 'r+b')
if self._read_only:
access = ACCESS_READ
else:
access = ACCESS_WRITE
# メモリマップ割り当て(確保メモリサイズはファイルサイズ)
self._mm = mmap(self._fd.fileno(), 0, access=access)
self._size = self._mm.size()
except Exception:
log.warning(f'{self}: failed to allocate buffer')
raise
log.debug(f'{self}: allocated buffer')
def _release(self):
""" バッファを開放する
"""
# メモリマップ開放
try:
if self._mm.closed:
self._mm.close()
except Exception as e:
log.warning(f'{self}: failed to close mmap: {e}')
self._mm = None
# ファイルクローズ
try:
if self._fd and (not self._fd.closed):
self._fd.close()
except Exception as e:
log.warning(f'{self}: failed to close mmap: {e}')
self._fd = None
def get_next(self) -> InspectBuffer:
""" 次のバッファを取得する
Returns:
InspectBuffer: 次のバッファインスタンス
None: 次のバッファがない
Note:
リングバッファのセットで確保した場合のみ利用可能
"""
buf = None
buf_set = self._name_dict.get(self._name)
if buf_set:
buf = buf_set.get_next()
else:
log.warning(f'{self}: not found buffer set {self._name}')
return buf
@property
def closed(self) -> bool:
""" メモリマップドファイル開放済みか
"""
return (not self._mm)
@property
def mmap(self) -> mmap:
""" メモリマップドファイル
"""
return self._mm
@property
def size(self) -> int:
""" バッファサイズ
"""
return self._size
@property
def path(self) -> Path:
""" メモリマップのファイルパス
"""
return self._path
def __str__(self) -> str:
text = f'<{self.__class__.__name__} '
text += f'{self._name}:{self._id} '
text += 'RO> ' if self._read_only else 'RW> '
text += f'({self._size:,d} bytes)'
return text
# 起動時に過去のバッファ用のファイルを削除
InspectBuffer.clean()
if __name__ == '__main__':
import numpy as np
from timeit import timeit
from shutil import copyfileobj
InspectBuffer.clean()
mm = InspectBuffer.alloc_set('test', 2, 512 * 1024)
print(mm)
dt = np.dtype('uint8')
dt = dt.newbyteorder('<')
dst_np = np.frombuffer(mm.mmap, dtype=dt, offset=0)
src_np = dst_np.copy()
m2 = mm.get_next()
# コピースピードの確認
def test_func1():
# データサイズが小さい時(~500KBくらい)には最速
dummy_np = dst_np.copy()
def test_func2():
# test_func3より若干遅い
mm.mmap[:] = dst_np.data[:]
def test_func3():
# データサイズが大きい時(1MB~)には最速
copyfileobj(mm.mmap, m2.mmap)
def test_func4():
m2.mmap[:] = mm.mmap[:]
result1 = timeit(test_func1, number=10)
print(f'np.copy(): {result1}')
result2 = timeit(test_func2, number=10)
print(f'np.copy(): {result2}')
result3 = timeit(test_func3, number=10)
print(f'np.copy(): {result3}')
result4 = timeit(test_func4, number=10)
print(f'np.copy(): {result4}')
pass | /roxyai-api-1.13.6.tar.gz/roxyai-api-1.13.6/roxyai_api/inspect_buffer.py | 0.525856 | 0.154376 | inspect_buffer.py | pypi |
from __future__ import annotations
import struct
from .connection import Connection
from .com_definition import (
Probability,
LabeledProbability,
CommandCode,
ProbabilityType,
)
from .com_base import BaseCommand
class GetProbabilitiesCommand(BaseCommand):
_CODE = CommandCode.GET_PROBABILITIES
PROB_SIZE = 13
LABELED_PROB_SIZE = 14
PROB_OFFSET = 3
# ログの詳細出力
verbose = False
def __init__(
self,
inspect_id: int,
connection: Connection = None,
logging: bool = True,
):
""" GetProbabilities コマンド制御
Args:
inspect_id: 取得対象の検査番号
connection: 通信対象のTCP接続
logging: 送受信時のログ出力フラグ
"""
super().__init__(connection=connection, logging=logging)
self.inspect_id = inspect_id
self.data = struct.pack(f'< Q', inspect_id)
def _decode_reply(self, reply: bytes):
""" Inspect コマンドの応答内容確認
Args:
reply (bytes): 受信応答データ(ヘッダ以外)
"""
prob_type, prob_len = struct.unpack(
'< B H',
reply[:self.PROB_OFFSET]
)
prob_data = reply[self.PROB_OFFSET:]
# 受信データの格納
self.prob_type = ProbabilityType(prob_type)
self.prob_size = prob_len
self.prob_list = []
if prob_type == ProbabilityType.LABELED:
prob_size = self.LABELED_PROB_SIZE
else:
prob_size = self.PROB_SIZE
for offset in range(0, prob_len * prob_size, prob_size):
if prob_type == ProbabilityType.LABELED:
x1, y1, x2, y2, typ, label, prob = struct.unpack(
'< H H H H B B f',
prob_data[offset:offset + prob_size]
)
prob = LabeledProbability(x1, y1, x2, y2, typ, label, prob)
else:
x1, y1, x2, y2, typ, prob = struct.unpack(
'< H H H H B f',
prob_data[offset:offset + prob_size]
)
prob = Probability(x1, y1, x2, y2, typ, prob)
self.prob_list.append(prob)
def __str__(self):
string = (
f'{super().__str__()} '
f'InspectID: {self.inspect_id}(=0x{self.inspect_id:#016X}) -> '
)
if self.is_received_ack:
string += (
f'ProbabilityList: {self.prob_size} items '
f'({self.process_time} ms)'
)
if self.verbose:
for prob in self.prob_list:
string += '\n ' + str(prob)
return string | /roxyai-api-1.13.6.tar.gz/roxyai-api-1.13.6/roxyai_api/com_get_probabilities.py | 0.486088 | 0.275161 | com_get_probabilities.py | pypi |
from __future__ import annotations
from typing import Callable, Any
from logging import getLogger
from time import perf_counter_ns
from .com_definition import CommandStatus
log = getLogger(__name__)
class ServerBaseHandler():
code = None
name = None
# コマンド送受信ログ出力用
last_command = None
repeat_count = 0
def __init__(
self,
reply_func: Callable[[CommandStatus, bytes, bytes], None],
context: Any = None,
):
""" 基底ハンドラクラス
Args:
reply_func: 応答処理関数
context: コマンド処理に必要な情報
"""
# # ログ出力に手続き名を設定
self._status = CommandStatus.STS_REQUEST
self._reply_func = reply_func
self.__start_time = None
self.__end_time = None
self._context = context
def proceed(self):
""" コマンドの処理呼び出し
"""
try:
# コマンド処理開始時刻の記録
self.__start_time = perf_counter_ns()
self.__end_time = None
# 具象クラスの処理を呼び出し
self.status = self.run()
if self._status.is_ack:
# 正常応答ならば具象クラスのデータ構築を呼び出し
send_data = self.encode()
else:
send_data = b''
# コマンド処理完了時間の記録
self.__end_time = perf_counter_ns()
except Exception:
# コマンド処理中に例外が発生(TBD)
self.status = CommandStatus.ERR_UNKNOWN_EXCEPTION
send_data = b''
log.exception(
f"{self.__class__.__name__}: "
f"Exception on command {self.code:02X}x procedure"
)
finally:
# 応答処理
self._reply_func(self._status, send_data)
log.debug(f'command {self.__class__.__name__} replies {repr(self._status)}\n')
def decode(self, payload: bytes):
""" コマンド要求の受信データ解釈
Note:
要求パラメータのデコードを各具象クラスでオーバーライドする
"""
# 処理するパラメータが無い場合は何も実施しない。
pass
def run(self):
""" コマンドの処理実行
Note:
各具象クラスでオーバーライドする
"""
raise NotImplementedError
def encode(self):
""" コマンド応答の送信データ構築
Note:
応答パラメータのデコードを各具象クラスでオーバーライドする
"""
return b''
@property
def process_time(self) -> float:
""" ハンドラの処理時間 [ms]
"""
time_ms = None
if self.__end_time and self.__start_time:
time_ms = (self.__end_time - self.__start_time) / 1000000
return time_ms
def com_info(self):
""" コマンドの情報文字列取得
Note:
各ハンドラの __str__ での利用を想定。
"""
string = f"0x{self.code:02X}({self.code:d})"
if self._status.is_reply:
# コマンド応答時
string += (
f' [{str(self._status)}]'
)
if self._status.is_ack:
# 正常応答時
string += f'({self.process_time:,.2f} ms)'
return string
@property
def status(self) -> CommandStatus:
return CommandStatus(self._status)
@status.setter
def status(self, val: int):
""" コマンドの送信/返信状態の設定
"""
self._status = CommandStatus(val) | /roxyai-api-1.13.6.tar.gz/roxyai-api-1.13.6/roxyai_api/svr_base_handler.py | 0.601242 | 0.168994 | svr_base_handler.py | pypi |
from __future__ import annotations
from pathlib import Path
import json5 as json
from logging import getLogger
from dataclasses import dataclass
log = getLogger(__name__)
# 共通のラベル情報定義
OK_LABEL_NAME = 'OK'
OK_LABEL_COLOR = 'R=256,G=256,B=256'
OTHER_LABEL_NAME = 'Other'
OTHER_LABEL_COLOR = 'R=127,G=127,B=127'
def _color2bgr(color: str) -> tuple[int, int, int]:
""" カラー定義文字列からRGB値への変換
Args:
color: RGB値定義文字列
例) R=256,G=256,B=256
Return:
tuple[R, G, B] 変換値
None: 変換失敗
"""
try:
rs, gs, bs = color.split(',')
ri = int(rs.replace('R=', ''))
gi = int(gs.replace('G=', ''))
bi = int(bs.replace('B=', ''))
ret = (bi, gi, ri)
except Exception:
ret = None
return ret
@dataclass
class ModelLabelInfo():
""" モデル毎のラベル情報
"""
id: int
name: str
color: str
def __post_init__(self):
self.bgr = _color2bgr(self.color)
def __str__(self) -> str:
text = f'label ({self.id}): "{self.name}" {self.color}'
return text
@classmethod
def OK(cls) -> ModelLabelInfo:
return ModelLabelInfo(0, OK_LABEL_NAME, OK_LABEL_COLOR)
class ProductLabelInfo():
""" 製品全体の統合ラベル情報
"""
# ラベル情報(0番は利用しない)
_label_list = []
LABEL_ID_OK = 0
# 違和感検知(その他の不良)用のラベル
_other_label = None
_ok_label = None
@classmethod
def clear(cls):
cls._label_list = []
cls._other_label = None
# 正常ラベルはデフォルトで登録しておく
cls._ok_label = ProductLabelInfo(
cls.LABEL_ID_OK, OK_LABEL_NAME, OK_LABEL_COLOR
)
cls._label_list.append(cls._ok_label)
@classmethod
def set_info(
cls, model_name: str, index: int, label_name: str, color: str
) -> int:
""" ラベルを設定してIDを取得
Args:
model_name: モデル名
index: モデルにおけるラベルのインデックス番号
label_name: ラベル名
color: 色情報
Returns:
ラベルの統一番号
"""
info = ProductLabelInfo(index, label_name, color)
if info in cls._label_list:
# 既に同じラベルがあればそれに差替え
i = cls._label_list.index(info)
info = cls._label_list[i]
label_id = info._label_id
else:
# 新規なら追加登録
label_id = len(cls._label_list)
info._label_id = label_id
cls._label_list.append(info)
# モデル名を登録
info._model_name.append(model_name)
if cls._other_label:
# OTHERラベルがある場合は最後のラベルとして設定
cls._other_label._label_id = len(cls._label_list)
return label_id
@classmethod
def set_other(cls, model_name: str, index: int):
""" 違和感検知用に「その他の不良」のラベルを設定する
Args:
model_name: モデル名
index: モデルにおけるOTHERラベルのインデックス番号
Note:
その他の不良ラベルは常にラベルリストの最後に設定
"""
if not cls._other_label:
# ラベルが未登録ならば新規作成
cls._other_label = ProductLabelInfo(
index, OTHER_LABEL_NAME, OTHER_LABEL_COLOR
)
# モデル名を登録
cls._other_label._model_name.append(model_name)
# 最後のラベルとしてIDを設定
cls._other_label._label_id = len(cls._label_list)
@classmethod
def get(cls, label_id: int):
""" ラベルIDから情報を取得
Args:
label_id: ProductLabelInfoのラベルの統一番号
"""
if (label_id < 0) or (len(cls._label_list) <= label_id):
ret = cls._other_label
else:
ret = cls._label_list[label_id]
return ret
@classmethod
def get_list(cls, include_ok: bool = False) -> list:
""" その他の不良を含めた全てのリストを返す
"""
if include_ok:
# 正常ラベルを含める場合
all_list = cls._label_list.copy()
else:
# 正常ラベルを含めない場合
all_list = cls._label_list[1:].copy()
if cls._other_label:
# 違和感検知用に「その他の不良」ラベルがあれば追加
all_list.append(cls._other_label)
return all_list
@classmethod
def get_other_id(self) -> int:
""" 違和感検知用のOTHERラベルの統一番号を取得
Note:
常に全モデルのラベルの最後に追加される
"""
return len(self._label_list)
def __init__(self, index: int, name: str, color: str):
""" ラベル情報
Args:
index: ラベル番号(モデル内の番号)
name: ラベル名
color: 色情報
"""
# 統合ラベル番号
self._index = index
self._name = name
self._color = color
# 統合ラベル番号
self._label_id = 0
# このラベルを含むモデル名
self._model_name = []
def __eq__(self, o: ProductLabelInfo) -> bool:
return (
(self._index == o._index)
and (self._name == o._name)
and (self._color == o._color)
)
@property
def id(self) -> int:
return self._label_id
@property
def model_name(self) -> int:
return self._model_name
@property
def index(self) -> int:
return self._index
@property
def name(self) -> str:
return self._name
@property
def color(self) -> str:
return self._color
@property
def bgr(self) -> tuple[int, int, int]:
return _color2bgr(self._color)
def __str__(self) -> str:
text = f'label ({self._label_id}): "{self._model_name}" '
text += f'{self._index:2d}) {self._name} {self._color}'
return text
class LabelManager():
""" ラベルとモデルの関連を管理する
"""
_LABELS_FILE = 'labels.txt'
_MODEL_CONFIG_FILE = 'config.json'
_INSPECT_CONFIG_FILE = 'inspect_config.json'
@classmethod
def get(cls, product_folder: str, model_list: list[str] = None) -> LabelManager:
""" 製品全体のラベル情報を取得する
Args:
product_folder: 製品情報フォルダ
model_list: 使用モデル名のリスト
Return:
LabelManager
"""
try:
ProductLabelInfo.clear()
label_info = cls(product_folder, model_list)
except Exception as e:
log.exception(f'{cls.__name__}: failed to load label info\n{e}')
label_info = None
return label_info
def __init__(self, product_folder: str, model_list: list[str] = None):
""" モデル毎のラベル情報を管理するクラス
Args:
product_folder (str or Path): 製品フォルダ
model_list: 使用モデル名のリスト
Note:
製品名フォルダ配下のinspect_config.jsonからモデル名を取得し、
"""
self._product_path = Path(product_folder)
self._label_set = set()
self._model_list = model_list
# モデル毎の統合ラベル番号辞書
self._product_label_dict: dict[str, dict[int, ProductLabelInfo]] = {}
# モデル毎のラベル番号辞書
self._model_label_dict: dict[str, ModelLabelInfo] = {}
if not self._product_path.exists():
# ファイルが存在しない
log.error(f'Not found inspect_config.json. {self._product_path}')
raise RuntimeError
self._load_all_model_label()
def _load_all_model_label(self):
""" 製品フォルダ配下の全てのモデルのラベル情報を読込
"""
model_path_list = list(
path for path in self._product_path.iterdir()
if path.is_dir()
)
labels_path_list = list(
md / self._LABELS_FILE for md in model_path_list
)
# 違和感検知用のOTHERラベルのインデックス(全てのモデルで共通化のため別管理)
other_label = {}
for label_path in labels_path_list:
if not label_path.exists():
# ラベルファイルが無ければ無効フォルダとしてスキップ
continue
model_name = label_path.parent.name
if self._model_list and (model_name not in self._model_list):
# 未使用のモデルならスキップ
continue
# モデルラベル情報の生成または取得
model_dict = self._model_label_dict.get(
model_name, {0: ModelLabelInfo.OK()}
)
# モデル毎のラベル情報の読み出し
try:
data = label_path.read_text(encoding='utf_8_sig', errors='ignore')
labels = {}
# OKがラベルID=0となるため不良ラベルは1開始
index = 1
for line in data.rstrip('\n').split('\n'):
# ラベル定義の行から値を取得
parts = line.rstrip('\n').split('\t')
# ラベル定義のindexは無視
# index = int(parts[0])
name = parts[1]
color = parts[2]
used = parts[3]
if used == 'unused':
# 未使用ラベルはindexの対象外
continue
# 読み込んだ情報を登録
label_info = ProductLabelInfo.set_info(
model_name, index, name, color
)
labels[index] = label_info
model_dict[index] = ModelLabelInfo(index, name, color)
index += 1
except Exception as e:
log.warning(f'Failed to load: {label_path}, {e}')
# 失敗したファイルは無視して処理継続
# 違和感検知の有効/無効読み出し
cfg_path = label_path.parent / self._MODEL_CONFIG_FILE
try:
if cfg_path.exists():
# モデル設定から Anomal の有効/無効を取得
data = cfg_path.read_text(encoding='utf_8_sig ', errors='ignore')
dic: dict = json.loads(data)
if dic.get('anormal_param', {}).get('enable_anormal', False):
# 違和感検知が有効ならばOTHERラベルを登録
ProductLabelInfo.set_other(model_name, index)
other_label[model_name] = index
model_dict[index] = ModelLabelInfo(
index, OTHER_LABEL_NAME, OTHER_LABEL_COLOR
)
except Exception as e:
log.warning(f'Failed to load model config: {cfg_path}, {e}')
# モデル毎の辞書に登録
self._product_label_dict[model_name] = labels
self._model_label_dict[model_name] = model_dict
log.debug(f'Loaded {len(labels)} labels for model "{model_name}".')
# 違和感検知用のラベル番号を各モデルに登録
for model_name, index in other_label.items():
self._product_label_dict[model_name][index] = ProductLabelInfo.get_other_id()
log.debug(f'loaded total {len(ProductLabelInfo.get_list())} labels.')
def get_info_json(self) -> str:
""" 統合ラベルの情報取得
Returns:
全モデルの統合ラベル情報を表すJSONデータ
"""
# モニター設定情報の取得
conf_path = (self._product_path / self._INSPECT_CONFIG_FILE).resolve().absolute()
try:
data = conf_path.read_text(encoding='utf-8', errors='ignore')
dic: dict = json.loads(data)
monitor_conf = dic.get('monitor', {})
except Exception as e:
log.warning(f'failed to load monitor config: {conf_path}\n{repr(e)}')
# モニター情報の読込
title_list = []
screen_list = monitor_conf.get('screen', [])
for screen in screen_list:
sc_id = screen.get('screen_id')
sc_title = screen.get('title')
if sc_title:
title_list.append(sc_title)
else:
log.debug(f'{self}: screen {sc_id} does not have "title"')
# 全ラベルの情報リスト
label_list = []
for label in ProductLabelInfo.get_list():
label_list.append({
'label_id': label.id,
'label_name': label.name,
'color': label.color,
})
all_label_info = {
'label': label_list
}
label_json = json.dumps(all_label_info, ensure_ascii=False)
return label_json
def get_id(self, model_name: str, label_index: int) -> int:
""" モデル名とモデル定義のラベル番号から統合のラベル番号取得
Args:
model_name: モデル名
label_index: モデルデータ内に定義されたラベル番号
Returns:
全モデルで統一化されたラベル番号
"""
labels = self._product_label_dict.get(model_name, {})
label_id = labels.get(label_index)
return label_id
def get_model_label(self, model_name: str) -> dict[int, ModelLabelInfo]:
""" モデル名からモデル毎のラベル情報辞書を取得する
Args:
model_name: モデル名
Returns:
モデル毎のラベル情報辞書
"""
return self._model_label_dict.get(model_name, {})
@property
def label_list(self) -> list[ProductLabelInfo]:
return ProductLabelInfo.get_list() | /roxyai-api-1.13.6.tar.gz/roxyai-api-1.13.6/roxyai_api/label_info.py | 0.533397 | 0.194444 | label_info.py | pypi |
from __future__ import annotations
from typing import Union
import json
from .connection import Connection
from .com_definition import CommandCode
from .com_base import BaseCommand
class InitializeCommand(BaseCommand):
_CODE = CommandCode.INITIALIZE
send_json = ''
def __init__(
self,
send_json: str = None,
product: str = None,
model_list: Union[list[str], tuple[str, str]] = [],
connection: Connection = None,
logging: bool = True,
):
""" Initialize コマンド制御
Args:
send_json: 初期設定をJSONデータで定義
product: 初期設定のproduct名(設定パス)
model_list: 初期設定のモデル名リスト
connection: 通信対象のTCP接続
logging: 送受信時のログ出力フラグ
Note:
JSONデータか、product, model_list指定の何れかを選択する。
Example:
code-block:: markdown
```python
from roxyai-api import InitializeCommand
com = InitializeCommand(product='ProductName', model_list=['ModelName'])
com.run()
if com.status.is_error_reply:
```
"""
super().__init__(connection=connection, logging=logging)
# 要求データの設定
if send_json:
self.product = None
self.model_list = []
self.send_json = send_json
else:
self.product = product
self.model_list = model_list
self.__encode_json()
self.data = self.send_json.encode('utf-8')
def append_model(self, model_name: str, group_name: str = None):
""" モデルを追加する(オプションで画像グループ指定を行う)
"""
if self.product is None:
# jsonコードの未解釈の場合は一度解釈する
dic = json.loads(self.send_json, encoding='utf-8')
self.product = dic['Product']
self.model_list = dic['ModelList']
if group_name:
self.model_list.append((str(model_name), str(group_name)))
else:
self.model_list.append(str(model_name))
self.__encode_json()
def __encode_json(self) -> str:
model_list = []
for model in self.model_list:
if type(model) in (list, tuple):
if len(model) >= 2:
model = [str(model[0]), str(model[1])]
else:
model = str(model[0])
else:
model = str(model)
model_list.append(model)
dic = {
'Product': str(self.product),
'ModelList': model_list
}
self.send_json = json.dumps(dic, ensure_ascii=False)
def __str__(self):
string = (
f'{super().__str__()} '
f'SendJson: {self.send_json} '
f'{len(self.send_json)} bytes ->'
)
return string | /roxyai-api-1.13.6.tar.gz/roxyai-api-1.13.6/roxyai_api/com_initialize.py | 0.669961 | 0.297795 | com_initialize.py | pypi |
from __future__ import annotations
from typing import List, Union
import struct
from datetime import datetime
from .connection import Connection
from .com_definition import (
Probability,
LabeledProbability,
CommandCode,
Judgment,
ProbabilityType,
)
from .com_base import (
BaseCommand,
HEADER_SIZE,
CommandError,
)
from .inspect_image import ImageFormat, InspectImage
class InspectCommand(BaseCommand):
_CODE = CommandCode.INSPECT
PROB_SIZE = 13
LABELED_PROB_SIZE = 14
PROB_OFFSET = 20 - HEADER_SIZE
# Requestパラメータ
_inspect_id = None
_model_id = None
_data_format = None
_image_data = b''
# Replayパラメータ
_result = Judgment.FAILED
_prob_size = 0
_prob_list: list[Probability] = []
# ログの詳細出力
verbose = False
def __init__(
self,
inspect_id: int,
model_id: int,
data_format: ImageFormat = None,
image_data: Union[bytes, InspectImage] = b'',
connection: Connection = None,
logging: bool = True,
):
""" Inspect コマンド制御
Args:
inspect_id: 検査番号
model_id: モデル番号
data_format: 送信する検査画像フォーマット
None: image_data のフォーマット利用
ImageFormat: 送信フォーマットを指定
image_data: 検査画像データ
connection: 通信対象のTCP接続
logging: 送受信時のログ出力フラグ
Raises:
TypeError: data_format が None で image_data が bytes
ValueError: data_format が NDARRAY
"""
super().__init__(connection=connection, logging=logging)
# データの格納フォーマットチェック
if (data_format is None) and not issubclass(type(image_data), InspectImage):
raise TypeError('image data_format is not specified')
# 要求データの設定
if inspect_id is None:
self._inspect_id = self.get_datetime_id()
else:
self._inspect_id = inspect_id
self._model_id = model_id
self._data_format = data_format or image_data.format
if self._data_format == ImageFormat.NDARRAY:
raise ValueError('ImageFromat NDARRAY is not supported')
self._image_data = image_data
self._extension = self._image_data
self.encode_data()
# 応答の変数定義はクラス定義を引き継ぎ
# self._result = Judgment.FAILED
# self._prob_size = 0
# self._prob_list = []
self._prob_type = None
def encode_data(self):
""" Inspect コマンドの送信データ生成
"""
send_params = (
self._inspect_id,
self._model_id,
self._data_format,
)
self.data = struct.pack('< Q B B', *send_params)
def send(self, timeout: float = None):
""" Inspect コマンドの要求を送信
Args:
timeout:
(None, default): None はタイムアウト無し
(float, option): タイムアウト時間[sec]
Raises:
送信タイムアウト(socket.timeout)を含む通信例外を送出
"""
super().send(extension=self.extension, timeout=timeout)
def recv(self, timeout: float = None):
""" Inspect コマンドの応答を受信
Args:
timeout:
(None, default): None はタイムアウト無し
(float, option): タイムアウト時間[sec]
Raises:
送信タイムアウト(socket.timeout)を含む通信例外を送出
CommandError 不正な応答受信
"""
super().recv(timeout=timeout)
def _decode_reply(self, reply: bytes):
""" Inspect コマンドの応答内容確認
Args:
reply (bytes): 受信応答データ(ヘッダ以外)
"""
if not reply:
self._result = Judgment.FAILED
self._prob_size = 0
self._prob_list = []
return
inspect_id, result, prob_type, prob_size = struct.unpack(
'< Q B B H',
reply[:self.PROB_OFFSET]
)
prob_data = reply[self.PROB_OFFSET:]
# 受信データのチェック
if self._inspect_id != inspect_id:
raise CommandError(
f'mismatched inspect_id '
f'recv:{inspect_id}(=0x{inspect_id:#016X}) != '
f'send:{self._inspect_id}(=0x{self._inspect_id:#016X})')
# 受信データの格納
self._result = Judgment(result)
self._prob_type = prob_type
self._prob_size = prob_size
self._prob_list = []
if prob_type == ProbabilityType.LABELED:
for offset in range(
0, prob_size * self.LABELED_PROB_SIZE, self.LABELED_PROB_SIZE
):
x1, y1, x2, y2, typ, label, prob = struct.unpack(
'< H H H H B B f',
prob_data[offset:offset + self.LABELED_PROB_SIZE]
)
prob = LabeledProbability(x1, y1, x2, y2, typ, label, prob)
self._prob_list .append(prob)
else:
for offset in range(0, prob_size * self.PROB_SIZE, self.PROB_SIZE):
x1, y1, x2, y2, typ, prob = struct.unpack(
'< H H H H B f',
prob_data[offset:offset + self.PROB_SIZE]
)
prob = Probability(x1, y1, x2, y2, typ, prob)
self._prob_list .append(prob)
@staticmethod
def get_datetime_id() -> int:
""" デフォルトで利用する日時算出の検査ID取得
Returns:
int: 日時から算出した検査ID
"""
dt = datetime.now()
dtid = int(dt.strftime('%Y%m%d%H%M%S%f')) // 1000
return dtid
def __str__(self) -> str:
image_size = self._extension.get_size(self._data_format)
string = (
f'{super().__str__()} '
f'InspectID: {self._inspect_id}(=0x{self._inspect_id:016X}), '
f'ModelID: {self._model_id}, '
f'DataFormat: 0x{self._data_format:02X}, '
f'ImageData: {image_size:,d} bytes -> '
)
if self.is_received_ack:
string += (
f'Result: {str(self._result)}, '
f'ProbabilityType: {self._prob_type}, '
f'ProbabilitySize: {self._prob_size}, '
f'ProbabilityList: {self._prob_size} items '
)
if self.verbose:
for prob in self._prob_list:
string += '\n ' + str(prob)
return string
# 読み取り専用変数の定義
@property
def inspect_id(self) -> int:
return self._inspect_id
@property
def model_id(self) -> int:
return self._model_id
@property
def data_format(self) -> ImageFormat:
return self._data_format
@property
def image_data(self) -> InspectImage:
return self._image_data
@property
def extension(self) -> bytes:
return self._extension.get_image(self._data_format)
@property
def result(self) -> Judgment:
return self._result
@property
def prob_size(self) -> int:
return self._prob_size
@property
def prob_list(self) -> List[Probability]:
return self._prob_list | /roxyai-api-1.13.6.tar.gz/roxyai-api-1.13.6/roxyai_api/com_inspect.py | 0.723212 | 0.268923 | com_inspect.py | pypi |
from __future__ import annotations
import time
from struct import pack, unpack
from io import BytesIO
from .connection import Connection
from .com_definition import (
SIGN_CODE,
HEADER_SIZE,
CommandStatus,
CommandCode,
)
from logging import getLogger
log = getLogger(__name__)
class CommandError(RuntimeError):
""" Roxy AI コマンドエラー
"""
pass
class BaseCommand():
# デフォルトの検査サーバの定義
HOST = "127.0.0.1"
""" デフォルトの接続先IPアドレス """
PORT = 6945
""" デフォルトの接続先ポート番号 """
_REPLAY_NONE = False
_CODE = None
_connection = None
_last_connection = Connection(HOST, PORT)
data = b""
_logging = True
def __init__(self, connection: Connection = None, logging: bool = True):
""" 基底コマンドクラス
Args:
connection: 通信対象のTCP接続
logging: 送受信時のログ出力フラグ
"""
self._connection = connection or self._connection or BaseCommand._last_connection
if connection:
# 接続設定をクラス変数に記録
BaseCommand._last_connection = connection
self.status = CommandStatus.NONE
self.__send_time = None
self.__recv_time = None
self.__rest_size = None
self._logging = logging
def send(self, extension: bytes = b'', timeout: float = None):
""" コマンドの送信
Args:
extension
(bytes, option): 拡張送信データ
timeout
(None, default): None はタイムアウト無し
(float, option): タイムアウト時間[sec]
Raises:
送信タイムアウト(socket.timeout)を含む通信例外を送出
Note:
extension はコマンドの最後に、メモリコピーを伴わずに送信する
拡張データを指定できます。
"""
data = self.data
sock = self._connection.sock
code = self._CODE
size = len(data) + len(extension)
status = CommandStatus.STS_REQUEST
buffer = pack(f"< H L B B {len(data)}s", SIGN_CODE, size, code, status, data)
if self._logging:
log.debug(f"Send [{size:3,d} bytes]: {self}")
try:
self.__send_time = time.time()
self.__recv_time = None
sock.settimeout(timeout)
sock.sendall(buffer)
if extension:
# 残りのタイムアウト時間を再計算してブロッキングモードの範囲で設定
if timeout is not None:
timeout = max(0.000001, timeout - (time.time() - self.__send_time))
sock.settimeout(timeout)
# 拡張データの送信
sock.sendall(extension)
except Exception:
if (sock is None) or (sock._closed):
# ソケットが閉じられている
raise ConnectionError("Connection is closed.")
raise
def recv(self, recv_size: int = None, timeout: float = None):
""" コマンドの受信
Args:
recv_size
(None, default): 応答コマンド全体を受信
(int, option): 指定されたデータBytesまで受信
timeout
(None, default): None はタイムアウト無し
(float, option): タイムアウト時間[sec]
Raises:
送信タイムアウト(socket.timeout)を含む通信例外を送出
Note:
下記の属性を設定
status (int): 返信コマンドステータス
code (int): 返信コマンド番号
rest_size (int): フレームの未受信データサイズ
"""
sock = self._connection.sock
try:
# タイムアウト設定
pre_time = time.time()
sock.settimeout(timeout)
# ヘッダの読み込み
buf = sock.recv(HEADER_SIZE)
except Exception:
if (sock is None) or (sock._closed):
# ソケットが閉じられている
raise ConnectionError("Connection is closed.")
raise
self.__recv_time = time.time()
if len(buf) == 0:
# サーバによる切断
raise ConnectionResetError
if len(buf) < HEADER_SIZE:
# ゴミ受信のため破棄
self.status = CommandStatus.ERR_INVALID_DATA_SIZE
dat = ' '.join(f'{b:02x}' for b in buf)
raise CommandError(f"{self} Receive invalid header size data: {len(buf)} bytes\nData: {dat} {buf}")
sign, size, code, status = unpack("< H L B B", buf[0:HEADER_SIZE])
if sign != SIGN_CODE:
# パケット種別チェック
self.status = CommandStatus.ERR_INVALID_SIGNATURE
dat = f'sign: {sign:04x}, size: {size:,d}, code: {code:02x}, status: {status:02x}'
raise CommandError(f"{self} Receive invalid signe code: 0x{sign:04x}\n{dat}")
# 受信ヘッダデータの検証
if code and (code != self._CODE):
self.status = CommandStatus.ERR_INVALID_COMMAND
dat = f'sign: {sign:04x}, size: {size:,d}, code: {code:02x}, status: {status:02x}'
raise CommandError(f"{self} Received command code:0x{code:02X} is mismatched 0x{self._CODE:02X}\n{dat}")
try:
self.status = status
except ValueError:
self.status = CommandStatus.ERR_UNKNOWN_EXCEPTION
dat = f'sign: {sign:04x}, size: {size:,}, code: {code:02x}, status: {status:02x}'
raise CommandError(f"{self} Receive invalid status: 0x{status:02x}\n{dat}")
if recv_size and (recv_size < size):
# フレームサイズが指定受信サイズ以上の場合は途中までを受信
self.__rest_size = size - recv_size
size = recv_size
log.warning(f'{self} Received larger size packet: {size:,} > expectation: {recv_size:,} bytes')
else:
self.__rest_size = 0
# コマンドデータの読み込み
reply_data = b''
if size > 0:
# データ受信開始の時間を記録
rcv_dat_start = time.time()
with BytesIO(b'\0' * size) as buffer:
while buffer.tell() < size:
# 残りのタイムアウト時間を再計算してブロッキングモードの範囲で設定
if timeout is not None:
now = time.time()
timeout = max(0.000001, timeout - (now - pre_time))
pre_time = now
try:
sock.settimeout(timeout)
fragment = sock.recv(size - buffer.tell())
except Exception:
if (sock is None) or (sock._closed):
# ソケットが閉じられている
raise ConnectionError("Connection is closed.")
raise
# データ受信開始の時間を記録
rcv_dat_time = (time.time() - rcv_dat_start) * 1000
received_size = buffer.tell() + len(fragment)
if rcv_dat_time >= 500:
# 500ms 以上掛かっている場合は警告ログを出力
log.warning(
f'{self}\n Long receiving time: {rcv_dat_time:,} ms ({received_size:,} / {size:,} bytes) '
)
if received_size > size:
# バッファで最初に確保したサイズ以上のデータを受信した場合
log.warning(
f'{self}\n Received larger size data: {received_size:,} / {size:,} bytes'
)
if len(fragment) == 0:
# サーバによる切断
raise ConnectionResetError
buffer.write(fragment)
reply_data = buffer.getvalue()
# 受信コマンドデータのデコード
try:
self._decode_reply(reply_data)
except Exception:
self.status = CommandStatus.ERR_FIALED_PARSE_DATA
log.exception('received invalid data')
if self._logging:
log.debug(f"Recv [{size:3,d} bytes]: {self}")
if self._status.is_error_reply:
reply_data = b''
def _decode_reply(self, reply: bytes):
if reply:
# データが存在する場合は各コマンドでオーバライドする
raise NotImplementedError
def run(self, timeout: float = None):
""" コマンドの送受信
Args:
timeout
(None, default): None はタイムアウト無し
(float, option): タイムアウト時間[sec]
Raises:
送信タイムアウト(socket.timeout)を含む通信例外を送出
"""
pre_time = time.time()
# コマンドの送信&受信
self.send(timeout=timeout)
if self._REPLAY_NONE:
# 応答不要コマンドは受信完了を設定する
self.__recv_time = time.time()
self.status = CommandStatus.STS_REPLY_ACK
return b''
if timeout is not None:
# 残りのタイムアウト時間を再計算してブロッキングモードの範囲で設定
now = time.time()
timeout = max(0.000001, timeout - (now - pre_time))
pre_time = now
self.recv(timeout=timeout)
@property
def is_received(self) -> bool:
""" 応答を受信しているかのフラグ
"""
return (self.__recv_time is not None)
@property
def is_received_ack(self) -> bool:
""" 正常応答を受信しているかのフラグ
"""
return (self._status and self._status.is_ack)
@property
def process_time(self) -> float:
""" コマンドの要求~応答の処理時間 [ms]
"""
proc_time = None
if self.is_received:
proc_time = (self.__recv_time - self.__send_time) * 1000
proc_time = round(proc_time, 3)
return proc_time
def __str__(self) -> str:
string = f"{str(self.code)} "
if not self.is_received:
string += "<REQUEST>"
else:
string += "<REPLY"
if self._status.is_error_reply:
string += f"-{str(self.status)}"
string += ">"
if self.is_received:
string += f" ({self.process_time} ms)"
return string
# 読み出し専用変数のアクセス定義
@property
def code(self) -> CommandCode:
""" コマンドのコード番号
"""
return CommandCode(self._CODE)
@property
def last_connection(self) -> Connection:
""" 前回接続に利用した Connection
"""
return self._last_connection
@property
def connection(self) -> Connection:
""" 接続中の Connection
"""
return self._connection
@property
def status(self) -> CommandStatus:
""" コマンドの送信/返信状態
"""
return CommandStatus(self._status)
@status.setter
def status(self, val: int):
""" コマンドの送信/返信状態の設定
"""
self._status = CommandStatus(val)
@property
def rest_size(self) -> int:
""" 応答コマンドの未受信データの残りサイズ
"""
self.__rest_size | /roxyai-api-1.13.6.tar.gz/roxyai-api-1.13.6/roxyai_api/com_base.py | 0.441553 | 0.167627 | com_base.py | pypi |
import click
import os
class ProjectCreator():
def __init__(self, project_name: str):
self.project_name = project_name
self.package_name = project_name.replace('-', '_').replace(' ', '_')
def create_readme(self) -> None:
with open(f'{self.project_name}/README.md', 'w') as f:
f.write(
f'''# {self.project_name}
> description
## Installation
```
pip install {self.package_name}
```
or from Github:
```
git clone https://github.com/roymanigley/{self.package_name}.git
cd {self.package_name}
python setup.py install
'''
)
def create_license(self) -> None:
with open(f'{self.project_name}/LICENSE', 'w') as f:
f.write(
'''MIT License
Copyright (c) 2022 roymanigley
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'''
)
def create_gitignore(self) -> None:
with open(f'{self.project_name}/.gitignore', 'w') as f:
f.write(
f'''{self.package_name}.egg-info
build
dist
__pycache__
.env
.venv
env
venv
.idea
'''
)
def create_setup_file(self) -> None:
with open(f'{self.project_name}/setup.py', 'w') as f:
f.write(
f'''from setuptools import setup, find_packages
long_description = open('README.md', "rt").read()
setup(
name='{self.package_name}',
version='0.0.1',
description='generated project',
long_description=long_description,
long_description_content_type='text/markdown',
url='https://github.com/roymanigley/{self.package_name}',
author='Roy Manigley',
author_email='roy.manigley@gmail.com',
license='MIT',
packages=['{self.package_name}'],
install_requires=[
'requests>=2.28.1',
'click>=8.1.3',
],
# entry_points = {{
# 'console_scripts': [
# 'your-command = {self.package_name}.your_module:main',
# ],
# }},
classifiers=[
'Development Status :: 1 - Planning',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python :: 3.10',
],
)
'''
)
def create_publish_script(self) -> None:
with open(f'{self.project_name}/publish.sh', 'w') as f:
f.write(
''' #!/bin/bash
rm ./dist/*.whl
python setup.py sdist bdist_wheel
twine upload dist/*.whl
''')
def create_requirements(self) -> None:
with open(f'{self.project_name}/requirements.txt', 'w') as f:
f.write(
'''
wheel
twine==4.0.2
'''
)
def create_sources(self) -> None:
source_dir = f'{self.project_name}/{self.package_name}'
os.mkdir(source_dir)
with open(f'{source_dir}/__init__.py', 'w') as f:
f.write('# __init__.py')
def generate(self) -> None:
try:
print(f'[+] create project:\n\t{self.project_name}')
os.mkdir(self.project_name)
print(f'[+] create readme:\n\t{self.project_name}/README.md')
self.create_readme()
print(f'[+] create locense:\n\t{self.project_name}/LICENSE')
self.create_license()
print(f'[+] create gitignore:\n\t{self.project_name}/.gitignore')
self.create_gitignore()
print(f'[+] create requirements:\n\t{self.project_name}/requirements.txt')
self.create_requirements()
print(f'[+] create setup.py:\n\t{self.project_name}/setup.py')
self.create_setup_file()
print(f'[+] create sources:\n\t{self.project_name}/{self.package_name}')
self.create_sources()
print(f'[+] completed')
except Exception as e:
print(f'[!] an error occurred:\n\t{e}')
@click.command()
@click.option(
'--project-name',
prompt='Enter the project name',
help='the project you want to create',
type=str
)
def main(project_name: str) -> None:
ProjectCreator(project_name).generate()
if __name__ == '__main__':
main() | /royman_tools-0.0.3-py3-none-any.whl/royman_tools/project_creator.py | 0.70202 | 0.436262 | project_creator.py | pypi |
import bz2
import csv
import gzip
import io
import lzma
import sys
import time
from bz2 import BZ2File
from collections import OrderedDict
from gzip import GzipFile
from math import floor, log10
from pathlib import Path
from typing import Optional, Callable, TextIO, Union, BinaryIO, TypeVar, Iterable, Dict, Any, Generator, Iterator
from pydantic import validate_arguments
from pyxtension import PydanticValidated
_K = TypeVar('_K')
__author__ = 'andrei.suiu@gmail.com'
@validate_arguments
def openByExtension(filename: Union[Path, str], mode: str = 'r', buffering: int = -1,
compresslevel: int = 9, **kwargs) -> Union[TextIO, BinaryIO, GzipFile, BZ2File]:
"""
:return: Returns an opened file-like object, decompressing/compressing data depending on file extension
"""
if filename.endswith('.gz'):
return gzip.open(filename, mode, compresslevel=compresslevel, **kwargs)
elif filename.endswith('.bz2'):
return bz2.open(filename, mode, compresslevel=compresslevel, **kwargs)
elif filename.endswith('.xz'):
my_filters = [
{"id": lzma.FILTER_LZMA2, "preset": compresslevel | lzma.PRESET_EXTREME}
]
return lzma.open(filename, mode=mode, filters=my_filters, **kwargs)
else:
return open(filename, mode, buffering=buffering, **kwargs)
open_by_ext = openByExtension
smart_open = openByExtension
class Progbar(object):
"""Displays a progress bar.
# Arguments
target: Total number of steps expected, None if unknown.
width: Progress bar width on screen.
verbose: Verbosity mode, 0 (silent), 1 (verbose), 2 (semi-verbose)
interval: Minimum visual progress update interval (in seconds).
This class was inspired from keras.utils.Progbar
"""
def __init__(self, target: Optional[int],
width: int = 30,
verbose: bool = False,
interval: float = 0.5,
stdout: TextIO = sys.stdout,
timer: Callable[[], float] = time.time,
dynamic_display: Optional[bool] = None):
self.target = target
self.width = width
self.verbose = verbose
self.interval = interval
self.stdout = stdout
if dynamic_display is None:
self._dynamic_display = ((hasattr(self.stdout, 'isatty') and self.stdout.isatty())
or 'ipykernel' in sys.modules
or (hasattr(self.stdout, 'name')
and self.stdout.name in ('<stdout>', '<stderr>'))
)
else:
self._dynamic_display = dynamic_display
self._total_width = 0
self._seen_so_far = 0
self._values = OrderedDict()
self._timer = timer
self._start = self._timer()
self._last_update = 0
def update(self, current, values=None):
"""Updates the progress bar.
# Arguments
current: Index of current step.
values: List of tuples:
`(name, value_for_last_step)`.
"""
values = values or []
for k, v in values:
if k not in self._values:
self._values[k] = [v * (current - self._seen_so_far),
current - self._seen_so_far]
else:
self._values[k][0] += v * (current - self._seen_so_far)
self._values[k][1] += (current - self._seen_so_far)
self._seen_so_far = current
now = self._timer()
info = ' - %.0fs' % (now - self._start)
if (now - self._last_update < self.interval and
self.target is not None and current < self.target):
return
prev_total_width = self._total_width
if self.target is not None:
numdigits = int(floor(log10(self.target))) + 1
barstr = '%%%dd/%d [' % (numdigits, self.target)
bar = barstr % current
prog = float(current) / self.target
prog_width = int(self.width * prog)
if prog_width > 0:
bar += ('=' * (prog_width - 1))
if current < self.target:
bar += '>'
else:
bar += '='
bar += ('.' * (self.width - prog_width))
bar += ']'
else:
bar = '%7d/Unknown' % current
if current:
time_per_unit = (now - self._start) / current
else:
time_per_unit = 0
if self.target is not None and current < self.target:
eta = time_per_unit * (self.target - current)
if eta > 3600:
eta_format = ('%d:%02d:%02d' %
(eta // 3600, (eta % 3600) // 60, eta % 60))
elif eta > 60:
eta_format = '%d:%02d' % (eta // 60, eta % 60)
else:
eta_format = '%ds' % eta
info = ' - ETA: %s' % eta_format
else:
if time_per_unit >= 1:
info += ' %.0fs/step' % time_per_unit
elif time_per_unit >= 1e-3:
info += ' %.0fms/step' % (time_per_unit * 1e3)
else:
info += ' %.0fus/step' % (time_per_unit * 1e6)
for k in self._values:
info += ' - %s:' % k
if isinstance(self._values[k], list):
avg = self._values[k][0] / max(1, self._values[k][1])
# avg = mean( )
if abs(avg) > 1e-3:
info += ' %.3f' % avg
else:
info += ' %.3e' % avg
else:
info += ' %s' % self._values[k]
self._total_width += len(info)
if prev_total_width > self._total_width:
info += (' ' * (prev_total_width - self._total_width))
display_str = bar + info
if self._dynamic_display:
prev_total_width = self._total_width
self._total_width = len(display_str)
# ASU: if \r doesn't work, use \b - to move cursor one char back
display_str = '\r' + display_str + ' ' * max(0, prev_total_width - len(display_str))
else:
display_str = display_str + '\n'
if self.target is not None and current >= self.target:
display_str += '\n'
self.stdout.write(display_str)
self.stdout.flush()
if self.verbose:
if self.target is None or current >= self.target:
for k in self._values:
info += ' - %s:' % k
avg = self._values[k][0] / max(1, self._values[k][1])
# avg = mean()
if avg > 1e-3:
info += ' %.3f' % avg
else:
info += ' %.3e' % avg
display_str = info
if self._dynamic_display:
prev_total_width = self._total_width
self._total_width = len(display_str)
# ASU: if \r doesn't work, use \b - to move cursor one char back
display_str = '\r' + display_str + ' ' * max(0, prev_total_width - len(display_str))
else:
display_str = display_str + '\n'
self.stdout.write(display_str)
self.stdout.flush()
self._last_update = now
def add(self, n, values=None):
self.update(self._seen_so_far + n, values)
def __call__(self, el: _K) -> _K:
"""
It's intended to be used from a mapper over a stream of values.
It returns the same el
# Example:
>>> from pyxtension.fileutils import Progbar
>>> stream(range(3)).map(Progbar(3)).size()
1/3 [=========>....................] - ETA: 0s
2/3 [===================>..........] - ETA: 0s
3/3 [==============================] - 0s 100ms/step
"""
self.add(1, None)
return el
class ReversedCSVReader(Iterable[Dict[str, Any]], PydanticValidated):
def __init__(self, fpath: Path, buf_size: int = 4 * 1024, opener: Any = gzip.open):
"""
:param opener: Callable[..., IO] should accept next parameters ([filename],mode:str, newline:str)
The filename argument can be an actual filename (a str or bytes object),
or an existing file object to read from or write to.
"""
self._fpath = fpath
self._opener = opener
self._buf_size = buf_size
self._fh = None
def _itr(self) -> Generator[Dict[str, Any], None, None]:
with self._opener(self._fpath, mode="rt", newline='') as in_csv_file:
self._fh = in_csv_file
reader = csv.reader(in_csv_file, delimiter=',', quotechar='"')
input_stream = iter(reader)
columns = next(input_stream)
nr_columns = len(columns)
for row in input_stream:
yield {columns[i]: row[i] for i in range(nr_columns)}
self._fh = None
def __iter__(self) -> Iterator[_K]:
return iter(self._itr())
def __reversed__(self):
return self._reversed_itr()
def _reversed_byte_reader(self):
with self._opener(self._fpath, "rb") as in_csv_file:
self._fh = in_csv_file
in_csv_file.seek(0, io.SEEK_END)
f_size = in_csv_file.tell()
cur_pos = f_size
while cur_pos > 0:
new_cur_pos = max(0, cur_pos - self._buf_size)
read_sz = cur_pos - new_cur_pos
cur_pos = new_cur_pos
if read_sz:
in_csv_file.seek(new_cur_pos, io.SEEK_SET)
buf = in_csv_file.read(read_sz)
for b in reversed(buf):
yield b
self._fh = None
def _split_stream_to_unicode_strings(self, s: Iterable):
buf = []
for b in s:
if b == ord(b'\n'):
if buf:
yield bytes(reversed(buf)).decode('utf-8').strip()
buf = []
else:
buf.append(b)
if buf:
yield bytes(reversed(buf)).decode('utf-8').strip()
def _reversed_itr(self) -> Generator[Dict[str, Any], None, None]:
with self._opener(self._fpath, "rt", newline='') as in_csv_file:
reader = csv.reader(in_csv_file, delimiter=',', quotechar='"')
input_stream = iter(reader)
columns = next(input_stream)
nr_columns = len(columns)
reversed_bytes_itr = self._reversed_byte_reader()
prev_row = None # we return only prev row to avoid returning first row that contains column definitions
for unicode_string in self._split_stream_to_unicode_strings(reversed_bytes_itr):
row = unicode_string.split(",")
if prev_row is not None:
yield {columns[i]: prev_row[i] for i in range(nr_columns)}
prev_row = row
def close(self):
"""
Attention! This will forcefully close the file and the already started generators won't work anymore.
"""
if self._fh is not None:
self._fh.close() | /roys_pyxtension-1.0.2-py3-none-any.whl/pyxtension/fileutils.py | 0.499023 | 0.163045 | fileutils.py | pypi |
from typing import Any, Callable, cast, Optional
from json_composite_encoder import JSONCompositeEncoder
from pydantic import BaseModel, Extra
class ExtModel(BaseModel):
"""
Extended Model with custom JSON encoder.
Extends the standard Pydantic model functionality by allowing arbitrary types and providing custom encoding.
"""
def json(
self,
*,
include=None,
exclude=None,
by_alias: bool = False,
skip_defaults: bool = None,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
encoder: Optional[Callable[[Any], Any]] = None,
**dumps_kwargs: Any,
) -> str:
"""
Note: we don't override the dict() method since it doesn't need custom encoder, so only here we can apply custom encoders;
Generate a JSON representation of the model, `include` and `exclude` arguments as per `dict()`.
`encoder` is an optional function to supply as `default` to json.dumps(), other arguments as per `json.dumps()`.
"""
if skip_defaults is not None:
exclude_unset = skip_defaults
encoder = cast(Callable[[Any], Any], encoder or self.__json_encoder__)
data = self.dict(
include=include,
exclude=exclude,
by_alias=by_alias,
exclude_unset=exclude_unset,
exclude_defaults=exclude_defaults,
exclude_none=exclude_none,
)
if self.__custom_root_type__:
# below is a hardcoding workaround instead of original utils.ROOT_KEY as Pydantic doesn't have it on Unix
data = data["__root__"]
composite_encoder_builder = JSONCompositeEncoder.Builder(encoders=self.__config__.json_encoders)
# Note: using a default arg instead of cls would not call encoder for elements that derive from base types like str or float;
return self.__config__.json_dumps(data, default=encoder, cls=composite_encoder_builder, **dumps_kwargs)
class Config:
arbitrary_types_allowed = True
class ImmutableExtModel(ExtModel):
class Config:
allow_mutation = False
arbitrary_types_allowed = True
extra = Extra.forbid
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls] | /roys_pyxtension-1.0.2-py3-none-any.whl/pyxtension/models.py | 0.921415 | 0.226142 | models.py | pypi |
import copy
import json
from typing import MutableMapping
from pyxtension.streams import *
__author__ = 'andrei.suiu@gmail.com'
supermethod = lambda self: super(self.__class__, self)
class JsonList(slist):
@classmethod
def __decide(cls, j):
if isinstance(j, dict):
return Json(j)
elif isinstance(j, (list, tuple)) and not isinstance(j, JsonList):
return JsonList(list(map(Json._toJ, j)))
elif isinstance(j, stream):
return JsonList(j.map(Json._toJ).toList())
else:
return j
def __init__(self, *args):
slist.__init__(self, stream(*args).map(lambda j: JsonList.__decide(j)))
def toOrig(self):
return [isinstance(t, (Json, JsonList)) and t.toOrig() or t for t in self]
def toString(self):
return json.dumps(self)
K = TypeVar('K')
V = TypeVar('V')
class Json(sdict, dict, MutableMapping[K, V]):
FORBIDEN_METHODS = ('__methods__', '__members__') # Introduced due to PyCharm debugging accessing these methods
@classmethod
def __myAttrs(cls):
return set(dir(cls))
@staticmethod
def load(fp, *args, **kwargs):
"""Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
a JSON document) to a Python object.
If the contents of ``fp`` is encoded with an ASCII based encoding other
than utf-8 (e.g. latin-1), then an appropriate ``encoding`` name must
be specified. Encodings that are not ASCII based (such as UCS-2) are
not allowed, and should be wrapped with
``codecs.getreader(fp)(encoding)``, or simply decoded to a ``unicode``
object and passed to ``loads()``
``object_hook`` is an optional function that will be called with the
result of any object literal decode (a ``dict``). The return value of
``object_hook`` will be used instead of the ``dict``. This feature
can be used to implement custom decoders (e.g. JSON-RPC class hinting).
``object_pairs_hook`` is an optional function that will be called with the
result of any object literal decoded with an ordered list of pairs. The
return value of ``object_pairs_hook`` will be used instead of the ``dict``.
This feature can be used to implement custom decoders that rely on the
order that the key and value pairs are decoded (for example,
collections.OrderedDict will remember the order of insertion). If
``object_hook`` is also defined, the ``object_pairs_hook`` takes priority.
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
kwarg; otherwise ``JSONDecoder`` is used.
"""
return Json.loads(fp.read(), *args, **kwargs)
@staticmethod
def loads(*args, **kwargs):
"""Deserialize ``s`` (a ``str`` or ``unicode`` instance containing a JSON
document) to a Python object.
If ``s`` is a ``str`` instance and is encoded with an ASCII based encoding
other than utf-8 (e.g. latin-1) then an appropriate ``encoding`` name
must be specified. Encodings that are not ASCII based (such as UCS-2)
are not allowed and should be decoded to ``unicode`` first.
``object_hook`` is an optional function that will be called with the
result of any object literal decode (a ``dict``). The return value of
``object_hook`` will be used instead of the ``dict``. This feature
can be used to implement custom decoders (e.g. JSON-RPC class hinting).
``object_pairs_hook`` is an optional function that will be called with the
result of any object literal decoded with an ordered list of pairs. The
return value of ``object_pairs_hook`` will be used instead of the ``dict``.
This feature can be used to implement custom decoders that rely on the
order that the key and value pairs are decoded (for example,
collections.OrderedDict will remember the order of insertion). If
``object_hook`` is also defined, the ``object_pairs_hook`` takes priority.
``parse_float``, if specified, will be called with the string
of every JSON float to be decoded. By default this is equivalent to
float(num_str). This can be used to use another datatype or parser
for JSON floats (e.g. decimal.Decimal).
``parse_int``, if specified, will be called with the string
of every JSON int to be decoded. By default this is equivalent to
int(num_str). This can be used to use another datatype or parser
for JSON integers (e.g. float).
``parse_constant``, if specified, will be called with one of the
following strings: -Infinity, Infinity, NaN, null, true, false.
This can be used to raise an exception if invalid JSON numbers
are encountered.
To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
kwarg; otherwise ``JSONDecoder`` is used.
"""
d = json.loads(*args, **kwargs)
if isinstance(d, dict):
return Json(d)
elif isinstance(d, list):
return JsonList(d)
else:
raise NotImplementedError("Unknown JSON format: {}".format(d.__class__))
@staticmethod
def fromString(s, *args, **kwargs):
return Json.loads(s, *args, **kwargs)
__decide = lambda self, j: isinstance(j, dict) and Json(j) or (isinstance(j, list) and slist(j) or j)
@classmethod
def _toJ(cls, j):
if isinstance(j, Json):
return j
elif isinstance(j, dict):
return Json(j)
elif isinstance(j, JsonList):
return j
elif isinstance(j, list):
return JsonList(j)
else:
return j
def __init__(self, *args, **kwargs):
if not kwargs and len(args) == 1 and isinstance(args[0], (str, bytes)):
d = json.loads(args[0])
assert isinstance(d, dict)
sdict.__init__(self, d)
elif len(args) >= 2 and isinstance(args[0], (tuple, list)):
sdict.__init__(self, args)
else:
sdict.__init__(self, *args, **kwargs)
def __getitem__(self, name):
"""
This is called when the Dict is accessed by []. E.g.
some_instance_of_Dict['a'];
If the name is in the dict, we return it. Otherwise we set both
the attr and item to a new instance of Dict.
"""
if name in self:
d = sdict.__getitem__(self, name)
if isinstance(d, dict) and not isinstance(d, Json):
j = Json(d)
sdict.__setitem__(self, name, j)
return j
elif isinstance(d, list) and not isinstance(d, JsonList):
j = JsonList(d)
sdict.__setitem__(self, name, j)
return j
elif isinstance(d, set) and not isinstance(d, sset):
j = sset(d)
sdict.__setitem__(self, name, j)
return j
else:
return d
else:
j = Json()
sdict.__setitem__(self, name, j)
return j
def __getattr__(self, item):
if item in self.FORBIDEN_METHODS:
raise AttributeError("Forbidden methods access to %s. Introduced due to PyCharm debugging problem." % str(
self.FORBIDEN_METHODS))
return self.__getitem__(item)
def __setattr__(self, key, value):
if key not in self.__myAttrs():
self[key] = value
else:
raise AttributeError("'%s' object attribute '%s' is read-only" % (str(self.__class__), key))
def __iter__(self):
return super(Json, self).__iter__()
def items(self):
return stream(dict.items(self)).map(lambda kv: (kv[0], Json._toJ(kv[1])))
def keys(self):
return stream(dict.keys(self))
def values(self):
return stream(dict.values(self)).map(Json._toJ)
def __str__(self):
return json.dumps(self.toOrig(), separators=(',', ':'), default=lambda k: str(k))
def dump(self, *args, **kwargs):
"""Serialize ``obj`` as a JSON formatted stream to ``fp`` (a
``.write()``-supporting file-like object).
If ``skipkeys`` is true then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``.
If ``ensure_ascii`` is true (the default), all non-ASCII characters in the
output are escaped with ``\\uXXXX`` sequences, and the result is a ``str``
instance consisting of ASCII characters only. If ``ensure_ascii`` is
``False``, some chunks written to ``fp`` may be ``unicode`` instances.
This usually happens because the input contains unicode strings or the
``encoding`` parameter is used. Unless ``fp.write()`` explicitly
understands ``unicode`` (as in ``codecs.getwriter``) this is likely to
cause an error.
If ``check_circular`` is false, then the circular reference check
for container types will be skipped and a circular reference will
result in an ``OverflowError`` (or worse).
If ``allow_nan`` is false, then it will be a ``ValueError`` to
serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``)
in strict compliance of the JSON specification, instead of using the
JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
If ``indent`` is a non-negative integer, then JSON array elements and
object members will be pretty-printed with that indent level. An indent
level of 0 will only insert newlines. ``None`` is the most compact
representation. Since the default item separator is ``', '``, the
output might include trailing whitespace when ``indent`` is specified.
You can use ``separators=(',', ': ')`` to avoid this.
If ``separators`` is an ``(item_separator, dict_separator)`` tuple
then it will be used instead of the default ``(', ', ': ')`` separators.
``(',', ':')`` is the most compact JSON representation.
``encoding`` is the character encoding for str instances, default is UTF-8.
``default(obj)`` is a function that should return a serializable version
of obj or raise TypeError. The default simply raises TypeError.
If *sort_keys* is ``True`` (default: ``False``), then the output of
dictionaries will be sorted by key.
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with
the ``cls`` kwarg; otherwise ``JSONEncoder`` is used.
"""
return json.dump(self.toOrig(), *args, **kwargs)
def dumps(self, *args, **kwargs):
"""Serialize ``self`` to a JSON formatted ``str``.
If ``skipkeys`` is false then ``dict`` keys that are not basic types
(``str``, ``unicode``, ``int``, ``long``, ``float``, ``bool``, ``None``)
will be skipped instead of raising a ``TypeError``.
If ``ensure_ascii`` is false, all non-ASCII characters are not escaped, and
the return value may be a ``unicode`` instance. See ``dump`` for details.
If ``check_circular`` is false, then the circular reference check
for container types will be skipped and a circular reference will
result in an ``OverflowError`` (or worse).
If ``allow_nan`` is false, then it will be a ``ValueError`` to
serialize out of range ``float`` values (``nan``, ``inf``, ``-inf``) in
strict compliance of the JSON specification, instead of using the
JavaScript equivalents (``NaN``, ``Infinity``, ``-Infinity``).
If ``indent`` is a non-negative integer, then JSON array elements and
object members will be pretty-printed with that indent level. An indent
level of 0 will only insert newlines. ``None`` is the most compact
representation. Since the default item separator is ``', '``, the
output might include trailing whitespace when ``indent`` is specified.
You can use ``separators=(',', ': ')`` to avoid this.
If ``separators`` is an ``(item_separator, dict_separator)`` tuple
then it will be used instead of the default ``(', ', ': ')`` separators.
``(',', ':')`` is the most compact JSON representation.
``encoding`` is the character encoding for str instances, default is UTF-8.
``default(obj)`` is a function that should return a serializable version
of obj or raise TypeError. The default simply raises TypeError.
If *sort_keys* is ``True`` (default: ``False``), then the output of
dictionaries will be sorted by key.
To use a custom ``JSONEncoder`` subclass (e.g. one that overrides the
``.default()`` method to serialize additional types), specify it with
the ``cls`` kwarg; otherwise ``JSONEncoder`` is used.
"""
return json.dumps(self.toOrig(), *args, **kwargs)
def toString(self):
"""
:return: deterministic sorted output string, that can be compared
:rtype: str
"""
return str(self)
"""To be removed and make Json serializable"""
def __eq__(self, y):
return super(Json, self).__eq__(y)
def __reduce__(self):
return self.__reduce_ex__(2)
def __reduce_ex__(self, protocol):
return str(self)
def copy(self):
return Json(super(Json, self).copy())
def __deepcopy__(self, memo):
return Json(copy.deepcopy(self.toOrig(), memo))
def __delattr__(self, name):
if name in self:
return supermethod(self).__delitem__(name)
else:
raise AttributeError("%s instance has no attribute %s" % (str(self.__class__), name))
def toOrig(self):
"""
Converts Json to a native dict
:return: stream dictionary
:rtype: sdict
"""
return sdict(
self.items()
.map(lambda kv: (kv[0], isinstance(kv[1], (Json, JsonList)) and kv[1].toOrig() or kv[1]))
)
class FrozenJson(Json):
def __init__(self, *args, **kwargs):
super(FrozenJson, self).__init__(*args, **kwargs)
def __setattr__(self, key, value):
raise TypeError("Can not update a FrozenJson instance by (key,value): ({},{})".format(key, value))
def __hash__(self):
return hash(self.toString()) | /roys_pyxtension-1.0.2-py3-none-any.whl/pyxtension/Json.py | 0.815306 | 0.384825 | Json.py | pypi |
# Royston
An end-to-end machine learning library for detect trending stories and content in real time. An open source Python framework that currently works in memory on a single node and can comfortably perform with around 500k-1m articles. Parallelisation is very much on the near term road map (next 6 months).
Trends are identified by detecting phrases that start occurring much more frequently than those that don't typically occur. Various natural language processing and data science techniques are used to ensure similar words are modelled together (i.e. "cycle", "cycling" and "cyclist" all reduce down to a common word form, such as "cycle").
Documents can be grouped by a subject, so it is possible to detect "localised" trends. It is often the case that a trending story has a number of related phrases (for example, "doping scandal" and "Tour de France"), so this is handled using hierachical clustering and doc2vec to handle this.
Based on [`ramekin`](https://github.com/readikus/ramekin), but going to take it further to do real time detection and maintaining models rather than creating them each time.
## Installation and basic usage
We are going to create a royston to contain a set of news articles, and then find the trends.
First we will install the package via `pip` by typing the following into the command line:
```
pip3 install royston
```
The following script creates some simple documents and adds them to a `royston` (also shipped in the `examples` directory):
```
from royston import Royston
from datetime import datetime as dt
roy = Royston()
# ingest a few documents
roy.ingest({ 'id': '123', 'body': 'Random text string', 'date': dt.now() })
roy.ingest({ 'id': '456', 'body': 'Antoher random string', 'date': dt.now() })
# find the trends - with this example, it won't find anything, as it's
# only got two stories!
trends = roy.trending()
print(trends)
```
## Configuration Options
### Constructor:
This package is heavily configurable to allow us to tune how we look for emerging trends. The default options have been set for the most common use case that looks at new trends that have emerged over the last 24 hours.
Currently, the main way of tuning these parameters is controlled by passing the Royston constructor an `options` dict with the following attributes:
| Attribute | Type | Default | Description |
|----------------|--------|---------|----------------------------------|
| `min_trend_freq` | `int` | 4 | A threshold for the minimum number of times a phrase has to occur in a single day before it can even be considered a trend for a given subject. |
| `history_days` | `int` | 90 | The context of the number of days to consider for the history. This means we look at how often a phrase has occured over this period, and get an idea of typical use. |
| `trend_days` | `int` | 1 | The period of time in which we want to look for trends. With the default of 1, we are looking at documents from the last day to see if new trends have emerged during that time compared with the typical use period defined by `history_days` |
| `max_n` | `int` | 6 | The maximum size of the n-gram window (i.e. the window size of each phrase) |
| `history_frequency_tolerance` | `float` | 1.6 | Factor the history count by this amount to handle words that just didn't get mentioned in the history period. This usefulness of this is in review, and it is likely to be removed in future (or at least set to 1 by default). |
| `trends_top_n` | `int` | 8 | The maximum number of trends to return |
Disclaimer: the following options are currently supported but expected to change significantly in future releases:
| Attribute | Type | Default | Description |
|-----------------|------------|---------|----------------------------------|
| `start` | `datetime` | now - trend_days | The start of the "trend" period (i.e. a day ago) |
| `end` | `datetime` | now | The end of the "trend" period |
| `history_start` | `datetime` | `start` | Start of the trend period (i.e. `history_days` before `end`) |
| `history_end` | `datetime` | `end` - history_days | Start of the trend period (i.e. `history_days` before `end`) |
Currently they are calculate in the constructor only, which is stupid, as we want this to run in realtime and adapt each time the `trend` method is called.
## Running tests
```
poetry run test
```
Run coverage reports:
```
poetry run coverage
```
## Distribute
This now uses poetry for package management, which can be done with the following command:
```
poetry build && poetry publish
```
## Contribute?
This is still in the early stages of being ported over from JavaScript, and any help would be appreciated. The issues contain a lot of features that are needed. Please get in touch via [LinkedIn](https://www.linkedin.com/in/ianreadnorwich/) and I can talk you thought anything.
Main concerns are:
* 100% test coverage.
* Retain the document format
* Code formatted using black/flake8
| /royston-0.0.19.tar.gz/royston-0.0.19/README.md | 0.425725 | 0.98104 | README.md | pypi |
import os
from typing import List, Tuple, Optional
import json
import pathlib
import tarfile
from contextlib import closing
from requests import Response, get
from autocorrect import Speller
from sentry_sdk import capture_exception
from rozental_as_a_service.common_types import TypoInfo
from rozental_as_a_service.config import YA_SPELLER_REQUEST_TIMEOUTS, YA_SPELLER_RETRIES_COUNT
from rozental_as_a_service.db_utils import save_ya_speller_results_to_db, get_ya_speller_cache_from_db
PATH = os.path.abspath(os.path.dirname(__file__))
def process_with_vocabulary(
words: List[str],
vocabulary_path: Optional[str],
) -> Tuple[List[str], List[TypoInfo], List[str]]:
if vocabulary_path is None or not os.path.exists(vocabulary_path):
return [], [], words
with open(vocabulary_path, encoding='utf8') as file_handler:
raw_vocabulary = file_handler.readlines()
vocabulary = {w.strip().lower() for w in raw_vocabulary if not w.strip().startswith('#')}
correct_words = {w for w in words if w in vocabulary}
return list(correct_words), [], [w for w in words if w not in correct_words]
class YaSpellerBackend:
def __init__(self, db_path: Optional[str]):
self.db_path = db_path
def __call__(self, words: List[str]) -> Tuple[List[str], List[TypoInfo], List[str]]:
sure_correct_words, incorrect_typos_info, unknown = self._process_with_db_cache(
words,
)
(
sure_correct_words_from_ya,
incorrect_typos_info_from_ya,
unknown,
) = self._process_with_ya_speller(unknown)
return (
sure_correct_words + sure_correct_words_from_ya,
incorrect_typos_info + incorrect_typos_info_from_ya,
unknown,
)
def _process_with_db_cache(
self,
words: List[str],
) -> Tuple[List[str], List[TypoInfo], List[str]]:
if self.db_path is None:
return [], [], words
words_cache = get_ya_speller_cache_from_db(words, self.db_path)
sure_correct_words: List[str] = []
incorrect_typos_info: List[TypoInfo] = []
for word in words:
if word not in words_cache:
continue
cached_value = words_cache[word]
if cached_value is None:
sure_correct_words.append(word)
else:
incorrect_typos_info.append(
{
'original': word,
'possible_options': cached_value,
},
)
known_words = set(
sure_correct_words + [t['original'] for t in incorrect_typos_info],
)
return sure_correct_words, incorrect_typos_info, list(set(words) - known_words)
def _process_with_ya_speller(
self,
words: List[str],
) -> Tuple[List[str], List[TypoInfo], List[str]]:
if not words:
return [], [], words
for _ in range(YA_SPELLER_RETRIES_COUNT):
try:
response = get(
'https://speller.yandex.net/services/spellservice.json/checkTexts',
params={'text': words},
timeout=YA_SPELLER_REQUEST_TIMEOUTS,
)
except TimeoutError as e:
capture_exception(e)
else:
break
return ([], *_process_ya_speller_response(response, words, self.db_path))
def _process_ya_speller_response(
response: Response,
words: List[str],
db_path: Optional[str],
) -> Tuple[List[TypoInfo], List[str]]:
typos_info: List[TypoInfo] = []
speller_result = response.json()
if speller_result:
for word_info in speller_result:
if word_info and word_info[0]['s']:
typos_info.append({
'original': word_info[0]['word'],
'possible_options': word_info[0]['s'],
})
if db_path is not None:
save_ya_speller_results_to_db(speller_result, words, db_path)
typo_words = {t['original'] for t in typos_info}
return typos_info, [w for w in words if w not in typo_words]
class AutocorrectCheckerBackend:
def __init__(self) -> None:
archive_path = pathlib.Path(PATH, 'data', 'ru.tar.gz')
with closing(tarfile.open(archive_path, 'r:gz')) as tarf, closing(tarf.extractfile('word_count.json')) as file:
nlp_data = json.load(file) # type: ignore
self.checker = Speller('ru', fast=True, nlp_data=nlp_data)
def __call__(self, words: List[str]) -> Tuple[List[str], List[TypoInfo], List[str]]:
incorrect_typos_info: List[TypoInfo] = []
known: List[str] = []
unknown: List[str] = []
for word in words:
if self.checker.existing([word]):
known.append(word)
continue
candidates = [
candidate[1] for candidate in sorted(
self.checker.get_candidates(word), key=lambda item: item[0],
)
]
if word == candidates[0]:
known.append(word)
continue
incorrect_typos_info.append(
{
'original': word,
'possible_options': candidates,
},
)
return known, incorrect_typos_info, unknown | /rozental_as_a_service-1.2.2.tar.gz/rozental_as_a_service-1.2.2/rozental_as_a_service/typos_backends.py | 0.664431 | 0.203075 | typos_backends.py | pypi |
import json
import os
import sqlite3
from typing import List, Mapping, Any, Tuple, Optional, Dict, Set
from rozental_as_a_service.config import OBSCENE_BASE_TABLE_NAME
from rozental_as_a_service.list_utils import flat
def save_ya_speller_results_to_db(
speller_result: List[List[Mapping[str, Any]]],
words: List[str],
db_path: str,
) -> None:
if not os.path.exists(db_path):
create_db(db_path)
connection = sqlite3.connect(db_path)
existing_words = get_existing_words_in_db(words, connection)
new_results = [(w, r[0] if r else None) for w, r in zip(words, speller_result) if w not in existing_words]
insert_db_words_info(new_results, connection)
def get_ya_speller_cache_from_db(
words: List[str],
db_path: str,
) -> Dict[str, Optional[List[str]]]:
if not os.path.exists(db_path):
return {}
connection = sqlite3.connect(db_path)
return fetch_words_info_from_db(words, connection)
def create_db(db_path: str) -> None:
connection = sqlite3.connect(db_path)
cursor = connection.cursor()
cursor.execute('CREATE TABLE words (word text, ya_speller_hints_json text)')
cursor.execute(f'CREATE TABLE {OBSCENE_BASE_TABLE_NAME} (word text)')
connection.commit()
def get_existing_words_in_db(words: List[str], connection: sqlite3.Connection) -> List[str]:
cursor = connection.cursor()
raw_result = cursor.execute(
'SELECT word FROM words WHERE word IN ({0})'.format(','.join('?' * len(words))),
words,
).fetchall()
return [r[0] for r in raw_result]
def fetch_words_info_from_db(words: List[str], connection: sqlite3.Connection) -> Dict[str, Optional[List[str]]]:
cursor = connection.cursor()
raw_result = cursor.execute(
'SELECT word, ya_speller_hints_json FROM words WHERE word IN ({0})'.format(','.join('?' * len(words))),
words,
).fetchall()
return {r: json.loads(info) for r, info in raw_result}
def insert_db_words_info(data: List[Tuple[str, Optional[Mapping]]], connection: sqlite3.Connection) -> None:
cursor = connection.cursor()
cursor.executemany(
'INSERT INTO words (word, ya_speller_hints_json) VALUES (?, ?)',
[(d[0], json.dumps(d[1]['s'] if d[1] else None)) for d in data], # type: ignore
)
connection.commit()
def is_table_exists(db_path: str, table_name: str) -> bool:
connection = sqlite3.connect(db_path)
cursor = connection.cursor()
raw_result = cursor.execute(
f"SELECT name FROM sqlite_master WHERE type='table' AND name='{table_name}';",
).fetchall()
return bool(raw_result)
def is_obscene_table_has_data(db_path: str) -> bool:
connection = sqlite3.connect(db_path)
cursor = connection.cursor()
raw_result = cursor.execute(
f'SELECT count(*) FROM {OBSCENE_BASE_TABLE_NAME}',
).fetchall()
return bool(raw_result[0][0])
def create_obscene_base_table(db_path: str) -> None:
connection = sqlite3.connect(db_path)
cursor = connection.cursor()
cursor.execute(f'CREATE TABLE {OBSCENE_BASE_TABLE_NAME} (word text)')
connection.commit()
def save_obscene_words_to_db(db_path: str, obscene_words: List[str]) -> None:
connection = sqlite3.connect(db_path)
cursor = connection.cursor()
cursor.executemany(
f'INSERT INTO {OBSCENE_BASE_TABLE_NAME} (word) VALUES (?)',
[[w] for w in obscene_words],
)
connection.commit()
def load_obscene_words(db_path: str) -> Set[str]:
connection = sqlite3.connect(db_path)
cursor = connection.cursor()
return set(flat(cursor.execute(
f'SELECT word FROM {OBSCENE_BASE_TABLE_NAME}',
).fetchall())) | /rozental_as_a_service-1.2.2.tar.gz/rozental_as_a_service-1.2.2/rozental_as_a_service/db_utils.py | 0.60743 | 0.164584 | db_utils.py | pypi |
import re
from typing import List, Tuple
from rozental_as_a_service.text_utils import split_camel_case_words, is_camel_case_word
def extract_words(
raw_constants: List[str],
min_word_length: int = 3,
only_russian: bool = True,
strip_urls: bool = True,
) -> List[str]:
common_replacements = [
# remove diacritic symbols manually
('\u0306', ''),
('\u0301', ''),
('\u0300', ''),
]
url_regexp = r'(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)'
processed_words: List[str] = []
raw_camelcase_words: List[str] = []
for constant in raw_constants:
if strip_urls:
constant = re.sub(url_regexp, ' ', constant)
for replace_from, replace_to in common_replacements:
constant = constant.replace(replace_from, replace_to)
new_processed_words, new_camelcase_words = process_raw_constant(constant, min_word_length)
processed_words += new_processed_words
raw_camelcase_words += new_camelcase_words
processed_words += process_camelcased_words(raw_camelcase_words)
processed_words = list(set(processed_words))
word_regexp = r'[а-яё-]+' if only_russian else r'[а-яёa-z-]+'
filtered_words = []
for word in processed_words:
match = re.match(word_regexp, word)
if match:
word = match.group()
if 'а-я' not in word and 'a-z' not in word: # most likely regexp
filtered_words.append(word)
processed_words = filtered_words
return processed_words
def process_raw_constant(constant: str, min_word_length: int) -> Tuple[List[str], List[str]]:
processed_words: List[str] = []
raw_camelcase_words: List[str] = []
for raw_word in re.findall(r'[\w-]+', constant):
word = raw_word.strip()
if (
len(word) >= min_word_length
and not (word.startswith('-') or word.endswith('-'))
):
if is_camel_case_word(word):
raw_camelcase_words.append(word)
else:
processed_words.append(word.lower())
return processed_words, raw_camelcase_words
def process_camelcased_words(raw_camelcase_words: List[str]) -> List[str]:
processed_words: List[str] = []
for camel_case_words in raw_camelcase_words:
splitted_words = split_camel_case_words(camel_case_words)
if splitted_words:
processed_words += splitted_words
return processed_words | /rozental_as_a_service-1.2.2.tar.gz/rozental_as_a_service-1.2.2/rozental_as_a_service/extractors_utils.py | 0.446253 | 0.26583 | extractors_utils.py | pypi |
# Python ZipInfo processing for RISC OS archives
This repository contains a pair of modules for handling the Zip archives with RISC OS information present.
The `rozipinfo` module provides a subclass of ZipInfo which is able to both parse the extra field used by RISC OS Zip archives, and generate these extra fields. This allows RISC OS archives to be worked with on non-RISC OS systems (or on RISC OS, if needed).
The `rozipfile` module builds on the `rozipinfo` module to allow the files to be extracted or created as a simple operation. It provide both a programatic and command line interface.
## Installing
The modules may be installed by copying them to where you need them, or through the package
manager:
pip install rozipinfo
## `rozipinfo`
The `rozipinfo` module provides decoding for the RISC OS specific extra fields in the Zip Archives.
It can be used standalone as a module to convert the standard `zipfile.ZipInfo` objects into objects that have RISC OS properties extracted from the Zip file's extra field.
### Features
* Supports reading RISC OS style file properties, synthesised if necessary:
* `riscos_filename`: RISC OS format filename, a `bytes` object in the configured encoding
* `riscos_date_time`: tuple like `date_time`, but with centiseconds on the end
* `riscos_objtype`: File or directory object type
* `riscos_loadaddr`: Load address
* `riscos_execaddr`: Exec address
* `riscos_filetype`: RISC OS filetype number
* `riscos_attr`: RISC OS attributes value
* Forces the `filename` to be unicode, having been decoded using the archive's encoding.
* All properties are mutable, and cause the extra field to be regenerated, updating the base properties as needed.
* Supports reading and writing the extra field, or using the NFS filename encoding format for transfer to other platforms.
* Configurable (by subclassing) encoding used for RISC OS filenames.
* Configurable (by subclassing) filetype inferrence rules, using extension, and parent directory name.
* Configurable (by subclassing) use of MimeMap module on RISC OS (not currently implemented, but the stub is there for overriding).
### Examples
The example code `showzip.py` demonstrates the use of the `ZipInfoRISCOS` module for reading zip archives.
For reading, it is expected that users will either enumerate objects in a zipfile and create a list of `ZipInfo` objects with `ZipFile.infolist()`, which they can then pass to `ZipInfoRISCOS` to handle the RISC OS specific extensions.
For writing, it is expected that users will create new `ZipInfoRISCOS` objects and pass these directly to the `ZipFile.writestr()` method.
## `rozipfile`
The rozipfile module builds upon the `rozipinfo` and works in a similar way to the regular `zipfile`.
### Listing files in the archive
The module allows the files to be listed as they might be in RISC OS:
with RISCOSZipFile('ro-app.zip, 'r') as zh:
zh.printdir()
The filenames can can be manually enumerated:
with RISCOSZipFile('ro-app.zip, 'r') as zh:
for zi in zh.infolist():
print(zi.riscos_filename)
### Creating archives
The module allows the creation of archives of files on unix systems which are extractable on RISC OS with filetypes.
Creating a new zip archive containing an application directory and some files from the filesystem:
with RISCOSZipFile('newzip.zip', 'w', base_dir='.') as rzh:
rzh.add_dir('!MyApp')
rzh.add_file('!MyApp/!Run,feb')
rzh.add_file('!MyApp/!Sprites,ff9')
rzh.add_file('!MyApp/!RunImage,ffb')
Or the files can be automatically traversed:
with RISCOSZipFile('newzip.zip', 'w', base_dir='.') as rzh:
rzh.add_to_zipfile('!MyApp')
### Extracting files from an archive
The module allows extracting the files from the RISC OS format archive, using the NFS filename
encoding.
with RISCOSZipFile('ro-app.zip, 'r') as zh:
zh.extractall(path='new-directory')
Individual files can alco be extracted, but filenames are in RISC OS format:
with RISCOSZipFile('ro-app.zip, 'r') as zh:
zh.extractall(path='!MyApp')
## Command line usage
The `rozipfile` module can be used to extract and create archives from the command line.
Listing an archive:
python -m rozipfile --list <archive>
Creating an archive:
python -m rozipfile [--chdir <dir>] --create <archive> <files>*
Extracting an archive:
python -m rozipfile [--chdir <dir>] --extract <archive> <files>*
Producing a list of *SetType commands to restore filetypes from a badly extracted file:
python -m rozipfile [--chdir <dir>] --settypes <archive>
### Default filetype
The default filetype for files that don't have any RISC OS extension information present (either as NFS-encoding or RISC OS extensions) is &FFD (Data). However, the switch `--default-filetype` can be used to default to a different type. Most commonly you may wish to set the default filetype to Text with `--default-filetype text`.
## Tests
Tests exist to show that the module is working properly, intended for use on GitLab.
Code coverage is about 84% at present; feature coverage is a bit lower, as not all the intended functionality is exercised by the tests.
| /rozipinfo-1.0.43.tar.gz/rozipinfo-1.0.43/README.md | 0.91855 | 0.788705 | README.md | pypi |
import keyword
from attrs import define
from bs4.element import Tag
reserved_names = keyword.kwlist
@define
class BaseClass:
"""Provides common base for descendants"""
def __init__(self, *args, **kwargs):
"""Mock to allow using __init__ with args and kwargs (see Parser class)"""
def get_as_str(self):
"""Returns __dict__ in a string format"""
return str(self.__dict__)
def get_class_as_str(self):
"""Returns __class__ in a string formt"""
return str(self.__class__)
def __repr__(self) -> str:
return str(self.to_dict())
# pylint: disable=C0301
# Copied from https://github.com/MarshalX/yandex-music-api/blob/a30082f4929e56381c870cb03103777ae29bcc6b/yandex_music/base.py
# Thanks to MarshalX for this amazing serializer
# *Added pylint disable!
def to_dict(self, for_request=False) -> dict:
# pylint: disable=R1705, C0103, C0301
"""Рекурсивная сериализация объекта.
Args:
for_request (:obj:`bool`): Перевести ли обратно все поля в camelCase и игнорировать зарезервированные слова.
Note:
Исключает из сериализации `client` и `_id_attrs` необходимые в `__eq__`.
К зарезервированным словам добавляет "_" в конец.
Returns:
:obj:`dict`: Сериализованный в dict объект.
"""
def parse(val):
# Added by Me - bs4 objects have any attr
if hasattr(val, 'to_dict') and val.to_dict:
return val.to_dict(for_request)
elif isinstance(val, list):
return [parse(it) for it in val]
elif isinstance(val, dict):
return {key: parse(value) for key, value in val.items()}
elif isinstance(val, Tag):
return {val.__class__: val.name}
else:
return val
data = self.__dict__.copy()
# Removed nonexistent pops
# data.pop('client', None)
# data.pop('_id_attrs', None)
if for_request:
for k, v in data.copy().items():
camel_case = ''.join(word.title() for word in k.split('_'))
camel_case = camel_case[0].lower() + camel_case[1:]
data.pop(k)
data.update({camel_case: v})
else:
for k, v in data.copy().items():
if k.lower() in reserved_names:
data.pop(k)
data.update({f'{k}_': v})
return parse(data) | /rozklad_ontu_parser_makisukurisu-0.0.4.1.tar.gz/rozklad_ontu_parser_makisukurisu-0.0.4.1/ontu_parser/classes/base.py | 0.696784 | 0.21564 | base.py | pypi |
import functools
from datetime import datetime
from sqlalchemy.orm import declarative_base, relationship
from sqlalchemy import Column, Table
from sqlalchemy import create_engine
from sqlalchemy import (
Boolean,
DateTime,
Integer,
Float,
String,
Text,
ForeignKey
)
from rp_tagger.conf import settings
Base = declarative_base()
tag_relationship = Table(
"assoc_tagged_image",
Base.metadata,
Column("image_id", Integer, ForeignKey("image.id"), nullable=False),
Column("tag_id", Integer, ForeignKey("tag.id"), nullable=False),
)
class Tag(Base):
"""
Tags that describe the image content
"""
__tablename__ = "tag"
id = Column(Integer, primary_key=True, nullable=False)
name = Column(String, index=True, nullable=False)
hits = Column(Integer, index=True, nullable=False, default=0)
def __str__(self):
return self.name
def as_dict(self):
return {
"id": self.id,
"name": self.name,
"hits": self.hits
}
class Image(Base):
"""
Saves the image metadata
"""
__tablename__ = "image"
id = Column(Integer, primary_key=True, nullable=False)
name = Column(String, nullable=False, unique=True)
path = Column(String, nullable=False)
hits = Column(Integer, nullable=False, default=0)
last_used = Column(DateTime, default=None, index=True)
tags = relationship("Tag", secondary=tag_relationship, backref="images")
date_created = Column(DateTime, default=datetime.now(), index=True, nullable=False)
def as_dict(self):
return {
"id": self.id,
"name": self.name,
"path": self.path,
"hits": self.hits,
"last_used": self.last_used,
"tags": [tag.as_dict() for tag in self.tags],
"date_created": self.date_created,
}
def create_db(name="sqlite:///./db.sqlite"):
engine = create_engine(name)
Base.metadata.create_all(engine)
return engine
def drop_db(name="sqlite:///./db.sqlite"):
engine = create_engine(name)
Base.metadata.drop_all(engine) | /rp_tagger-1.1.0-py3-none-any.whl/rp_tagger/db.py | 0.453504 | 0.20003 | db.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.application import Application
from prompt_toolkit.buffer import Buffer, AcceptAction
from prompt_toolkit.buffer_mapping import BufferMapping
from prompt_toolkit.document import Document
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import Condition, HasFocus, InFocusStack
from prompt_toolkit.key_binding.defaults import load_key_bindings
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.containers import HSplit, VSplit, Window, FloatContainer, Float, ConditionalContainer, Container, ScrollOffsets
from prompt_toolkit.layout.controls import BufferControl, FillControl
from prompt_toolkit.layout.dimension import LayoutDimension as D
from prompt_toolkit.layout.lexers import PygmentsLexer
from prompt_toolkit.layout.margins import Margin, ScrollbarMargin
from prompt_toolkit.layout.processors import Processor, Transformation, HighlightSearchProcessor, HighlightSelectionProcessor
from prompt_toolkit.layout.screen import Char
from prompt_toolkit.layout.toolbars import ArgToolbar, SearchToolbar
from prompt_toolkit.layout.toolbars import TokenListToolbar
from prompt_toolkit.layout.utils import token_list_to_text
from pygments.lexers import RstLexer
from pygments.token import Token
from .utils import if_mousedown
from rp.rp_ptpython.layout import get_inputmode_tokens
from functools import partial
import six
if six.PY2:
from pygments.lexers import PythonLexer
else:
from pygments.lexers import Python3Lexer as PythonLexer
HISTORY_BUFFER = 'HISTORY_BUFFER'
HELP_BUFFER = 'HELP_BUFFER'
HISTORY_COUNT = 2000
__all__ = (
'create_history_application',
)
HELP_TEXT = """
This interface is meant to select multiple lines from the
history and execute them together.
Typical usage
-------------
1. Move the ``cursor up`` in the history pane, until the
cursor is on the first desired line.
2. Hold down the ``space bar``, or press it multiple
times. Each time it will select one line and move to
the next one. Each selected line will appear on the
right side.
3. When all the required lines are displayed on the right
side, press ``Enter``. This will go back to the Python
REPL and show these lines as the current input. They
can still be edited from there.
Key bindings
------------
Many Emacs and Vi navigation key bindings should work.
Press ``F4`` to switch between Emacs and Vi mode.
Additional bindings:
- ``Space``: Select or delect a line.
- ``Tab``: Move the focus between the history and input
pane. (Alternative: ``Ctrl-W``)
- ``Ctrl-C``: Cancel. Ignore the result and go back to
the REPL. (Alternatives: ``q`` and ``Control-G``.)
- ``Enter``: Accept the result and go back to the REPL.
- ``F1``: Show/hide help. Press ``Enter`` to quit this
help message.
Further, remember that searching works like in Emacs
(using ``Ctrl-R``) or Vi (using ``/``).
"""
class BORDER:
" Box drawing characters. "
HORIZONTAL = '\u2501'
VERTICAL = '\u2503'
TOP_LEFT = '\u250f'
TOP_RIGHT = '\u2513'
BOTTOM_LEFT = '\u2517'
BOTTOM_RIGHT = '\u251b'
LIGHT_VERTICAL = '\u2502'
def create_popup_window(title, body):
"""
Return the layout for a pop-up window. It consists of a title bar showing
the `title` text, and a body layout. The window is surrounded by borders.
"""
assert isinstance(title, six.text_type)
assert isinstance(body, Container)
return HSplit([
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_LEFT, token=Token.Window.Border)),
TokenListToolbar(
get_tokens=lambda cli: [(Token.Window.Title, ' %s ' % title)],
align_center=True,
default_char=Char(BORDER.HORIZONTAL, Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_RIGHT, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
body,
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_LEFT, token=Token.Window.Border)),
Window(height=D.exact(1),
content=FillControl(BORDER.HORIZONTAL, token=Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_RIGHT, token=Token.Window.Border)),
]),
])
def create_layout(python_input, history_mapping):
"""
Create and return a `Container` instance for the history
application.
"""
processors = [
HighlightSearchProcessor(preview_search=True),
HighlightSelectionProcessor()]
help_window = create_popup_window(
title='History Help',
body=Window(
content=BufferControl(
buffer_name=HELP_BUFFER,
default_char=Char(token=Token),
lexer=PygmentsLexer(RstLexer),
input_processors=processors),
right_margins=[ScrollbarMargin()],
scroll_offsets=ScrollOffsets(top=2, bottom=2)))
return HSplit([
# Top title bar.
TokenListToolbar(
get_tokens=_get_top_toolbar_tokens,
align_center=True,
default_char=Char(' ', Token.Toolbar.Status)),
FloatContainer(
content=VSplit([
# Left side: history.
Window(
content=BufferControl(
buffer_name=HISTORY_BUFFER,
lexer=PygmentsLexer(PythonLexer),
input_processors=processors),
wrap_lines=False,
left_margins=[HistoryMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
# Separator.
Window(width=D.exact(1),
content=FillControl(BORDER.LIGHT_VERTICAL, token=Token.Separator)),
# Right side: result.
Window(
content=BufferControl(
buffer_name=DEFAULT_BUFFER,
input_processors=processors + [GrayExistingText(history_mapping)],
lexer=PygmentsLexer(PythonLexer)),
wrap_lines=False,
left_margins=[ResultMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
]),
floats=[
# Help text as a float.
Float(width=60, top=3, bottom=2,
content=ConditionalContainer(
# (We use InFocusStack, because it's possible to search
# through the help text as well, and at that point the search
# buffer has the focus.)
content=help_window, filter=InFocusStack(HELP_BUFFER))),
]
),
# Bottom toolbars.
ArgToolbar(),
SearchToolbar(),
TokenListToolbar(
get_tokens=partial(_get_bottom_toolbar_tokens, python_input=python_input),
default_char=Char(' ', Token.Toolbar.Status)),
])
def _get_top_toolbar_tokens(cli):
return [(Token.Toolbar.Status.Title, 'History browser - Insert from history')]
def _get_bottom_toolbar_tokens(cli, python_input):
@if_mousedown
def f1(cli, mouse_event):
_toggle_help(cli)
@if_mousedown
def tab(cli, mouse_event):
_select_other_window(cli)
return [
(Token.Toolbar.Status, ' ')
] + get_inputmode_tokens(cli, python_input) + [
(Token.Toolbar.Status, ' '),
(Token.Toolbar.Status.Key, '[Space]'),
(Token.Toolbar.Status, ' Toggle '),
(Token.Toolbar.Status.Key, '[Tab]', tab),
(Token.Toolbar.Status, ' Focus ', tab),
(Token.Toolbar.Status.Key, '[Enter]'),
(Token.Toolbar.Status, ' Accept '),
(Token.Toolbar.Status.Key, '[F1]', f1),
(Token.Toolbar.Status, ' Help ', f1),
]
class HistoryMargin(Margin):
"""
Margin for the history buffer.
This displays a green bar for the selected entries.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[HISTORY_BUFFER].document
lines_starting_new_entries = self.history_mapping.lines_starting_new_entries
selected_lines = self.history_mapping.selected_lines
current_lineno = document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
# Show stars at the start of each entry.
# (Visualises multiline entries.)
if line_number in lines_starting_new_entries:
char = '*'
else:
char = ' '
if line_number in selected_lines:
t = Token.History.Line.Selected
else:
t = Token.History.Line
if line_number == current_lineno:
t = t.Current
result.append((t, char))
result.append((Token, '\n'))
return result
class ResultMargin(Margin):
"""
The margin to be shown in the result pane.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[DEFAULT_BUFFER].document
current_lineno = document.cursor_position_row
offset = self.history_mapping.result_line_offset #original_document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
if (line_number is None or line_number < offset or
line_number >= offset + len(self.history_mapping.selected_lines)):
t = Token
elif line_number == current_lineno:
t = Token.History.Line.Selected.Current
else:
t = Token.History.Line.Selected
result.append((t, ' '))
result.append((Token, '\n'))
return result
def invalidation_hash(self, cli, document):
return document.cursor_position_row
class GrayExistingText(Processor):
"""
Turn the existing input, before and after the inserted code gray.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
self._lines_before = len(history_mapping.original_document.text_before_cursor.splitlines())
def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
if (lineno < self._lines_before or
lineno >= self._lines_before + len(self.history_mapping.selected_lines)):
text = token_list_to_text(tokens)
return Transformation(tokens=[(Token.History.ExistingInput, text)])
else:
return Transformation(tokens=tokens)
class HistoryMapping(object):
"""
Keep a list of all the lines from the history and the selected lines.
"""
def __init__(self, python_history, original_document):
self.python_history = python_history
self.original_document = original_document
self.lines_starting_new_entries = set()
self.selected_lines = set()
# Process history.
history_lines = []
for entry_nr, entry in list(enumerate(python_history))[-HISTORY_COUNT:]:
self.lines_starting_new_entries.add(len(history_lines))
for line in entry.splitlines():
history_lines.append(line)
if len(python_history) > HISTORY_COUNT:
history_lines[0] = '# *** History has been truncated to %s lines ***' % HISTORY_COUNT
self.history_lines = history_lines
self.concatenated_history = '\n'.join(history_lines)
# Line offset.
if self.original_document.text_before_cursor:
self.result_line_offset = self.original_document.cursor_position_row + 1
else:
self.result_line_offset = 0
def get_new_document(self, cursor_pos=None):
"""
Create a `Document` instance that contains the resulting text.
"""
lines = []
# Original text, before cursor.
if self.original_document.text_before_cursor:
lines.append(self.original_document.text_before_cursor)
# Selected entries from the history.
for line_no in sorted(self.selected_lines):
lines.append(self.history_lines[line_no])
# Original text, after cursor.
if self.original_document.text_after_cursor:
lines.append(self.original_document.text_after_cursor)
# Create `Document` with cursor at the right position.
text = '\n'.join(lines)
if cursor_pos is not None and cursor_pos > len(text):
cursor_pos = len(text)
return Document(text, cursor_pos)
def update_default_buffer(self, cli):
b = cli.buffers[DEFAULT_BUFFER]
b.set_document(
self.get_new_document(b.cursor_position), bypass_readonly=True)
def _toggle_help(cli):
" Display/hide help. "
if cli.current_buffer_name == HELP_BUFFER:
cli.pop_focus()
else:
cli.push_focus(HELP_BUFFER)
def _select_other_window(cli):
" Toggle focus between left/right window. "
if cli.current_buffer_name == HISTORY_BUFFER:
cli.focus(DEFAULT_BUFFER)
elif cli.current_buffer_name == DEFAULT_BUFFER:
cli.focus(HISTORY_BUFFER)
def create_key_bindings(python_input, history_mapping):
"""
Key bindings.
"""
registry = load_key_bindings(
enable_search=True,
enable_extra_page_navigation=True)
handle = registry.add_binding
@handle(' ', filter=HasFocus(HISTORY_BUFFER))
def _(event):
"""
Space: select/deselect line from history pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row
if line_no in history_mapping.selected_lines:
# Remove line.
history_mapping.selected_lines.remove(line_no)
history_mapping.update_default_buffer(event.cli)
else:
# Add line.
history_mapping.selected_lines.add(line_no)
history_mapping.update_default_buffer(event.cli)
# Update cursor position
default_buffer = event.cli.buffers[DEFAULT_BUFFER]
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
# Also move the cursor to the next line. (This way they can hold
# space to select a region.)
b.cursor_position = b.document.translate_row_col_to_index(line_no + 1, 0)
@handle(' ', filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.Delete, filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.ControlH, filter=HasFocus(DEFAULT_BUFFER))
def _(event):
"""
Space: remove line from default pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row - history_mapping.result_line_offset
if line_no >= 0:
try:
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass # When `selected_lines` is an empty set.
else:
history_mapping.selected_lines.remove(history_lineno)
history_mapping.update_default_buffer(event.cli)
help_focussed = HasFocus(HELP_BUFFER)
main_buffer_focussed = HasFocus(HISTORY_BUFFER) | HasFocus(DEFAULT_BUFFER)
@handle(Keys.Tab, filter=main_buffer_focussed)
@handle(Keys.ControlX, filter=main_buffer_focussed, eager=True)
# Eager: ignore the Emacs [Ctrl-X Ctrl-X] binding.
@handle(Keys.ControlW, filter=main_buffer_focussed)
def _(event):
" Select other window. "
_select_other_window(event.cli)
@handle(Keys.F4)
def _(event):
" Switch between Emacs/Vi mode. "
python_input.vi_mode = not python_input.vi_mode
@handle(Keys.F1)
def _(event):
" Display/hide help. "
_toggle_help(event.cli)
@handle(Keys.ControlJ, filter=help_focussed)
@handle(Keys.ControlC, filter=help_focussed)
@handle(Keys.ControlG, filter=help_focussed)
@handle(Keys.Escape, filter=help_focussed)
def _(event):
" Leave help. "
event.cli.pop_focus()
@handle('q', filter=main_buffer_focussed)
@handle(Keys.F3, filter=main_buffer_focussed)
@handle(Keys.ControlC, filter=main_buffer_focussed)
@handle(Keys.ControlG, filter=main_buffer_focussed)
def _(event):
" Cancel and go back. "
event.cli.set_return_value(None)
enable_system_bindings = Condition(lambda cli: python_input.enable_system_bindings)
@handle(Keys.ControlZ, filter=enable_system_bindings)
def _(event):
" Suspend to background. "
event.cli.suspend_to_background()
return registry
def create_history_application(python_input, original_document):
"""
Create an `Application` for the history screen.
This has to be run as a sub application of `python_input`.
When this application runs and returns, it retuns the selected lines.
"""
history_mapping = HistoryMapping(python_input.history, original_document)
def default_buffer_pos_changed(_):
""" When the cursor changes in the default buffer. Synchronize with
history buffer. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == DEFAULT_BUFFER:
try:
line_no = default_buffer.document.cursor_position_row - \
history_mapping.result_line_offset
if line_no < 0: # When the cursor is above the inserted region.
raise IndexError
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass
else:
history_buffer.cursor_position = \
history_buffer.document.translate_row_col_to_index(history_lineno, 0)
def history_buffer_pos_changed(_):
""" When the cursor changes in the history buffer. Synchronize. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == HISTORY_BUFFER:
line_no = history_buffer.document.cursor_position_row
if line_no in history_mapping.selected_lines:
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
history_buffer = Buffer(
initial_document=Document(history_mapping.concatenated_history),
on_cursor_position_changed=history_buffer_pos_changed,
accept_action=AcceptAction(
lambda cli, buffer: cli.set_return_value(default_buffer.document)),
read_only=True)
default_buffer = Buffer(
initial_document=history_mapping.get_new_document(),
on_cursor_position_changed=default_buffer_pos_changed,
read_only=True)
help_buffer = Buffer(
initial_document=Document(HELP_TEXT, 0),
accept_action=AcceptAction.IGNORE,
read_only=True
)
buffer_mapping = BufferMapping({
HISTORY_BUFFER: history_buffer,
DEFAULT_BUFFER: default_buffer,
HELP_BUFFER: help_buffer,
}, initial=HISTORY_BUFFER)
application = Application(
layout=create_layout(python_input, history_mapping),
use_alternate_screen=True,
buffers=buffer_mapping,
style=python_input._current_style,
mouse_support=Condition(lambda cli: python_input.enable_mouse_support),
key_bindings_registry=create_key_bindings(python_input, history_mapping)
)
return application | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.254/Olde/rp 11.48.10 PM/rp_ptpython/history_browser.py | 0.754101 | 0.161982 | history_browser.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.mouse_events import MouseEventTypes
import re
__all__ = (
'has_unclosed_brackets',
'get_jedi_script_from_document',
'document_is_multiline_python',
)
def has_unclosed_brackets(text):
"""
Starting at the end of the string. If we find an opening bracket
for which we didn't had a closing one yet, return True.
"""
stack = []
# Ignore braces inside strings
text = re.sub(r'''('[^']*'|"[^"]*")''', '', text) # XXX: handle escaped quotes.!
for c in reversed(text):
if c in '])}':
stack.append(c)
elif c in '[({':
if stack:
if ((c == '[' and stack[-1] == ']') or
(c == '{' and stack[-1] == '}') or
(c == '(' and stack[-1] == ')')):
stack.pop()
else:
# Opening bracket for which we didn't had a closing one.
return True
return False
def get_jedi_script_from_document(document, locals, globals):
import jedi # We keep this import in-line, to improve start-up time.
# Importing Jedi is 'slow'.
try:
return jedi.Interpreter(
document.text,
column=document.cursor_position_col,
line=document.cursor_position_row + 1,
path='input-text',
namespaces=[locals, globals])
except ValueError:
# Invalid cursor position.
# ValueError('`column` parameter is not in a valid range.')
return None
except AttributeError:
# Workaround for #65: https://github.com/jonathanslenders/python-prompt-toolkit/issues/65
# See also: https://github.com/davidhalter/jedi/issues/508
return None
except IndexError:
# Workaround Jedi issue #514: for https://github.com/davidhalter/jedi/issues/514
return None
except KeyError:
# Workaroud for a crash when the input is "u'", the start of a unicode string.
return None
except Exception:
# Workaround for: https://github.com/jonathanslenders/ptpython/issues/91
return None
_multiline_string_delims = re.compile('''[']{3}|["]{3}''')
def document_is_multiline_python(document):
"""
Determine whether this is a multiline Python document.
"""
def ends_in_multiline_string():
"""
``True`` if we're inside a multiline string at the end of the text.
"""
delims = _multiline_string_delims.findall(document.text)
opening = None
for delim in delims:
if opening is None:
opening = delim
elif delim == opening:
opening = None
return bool(opening)
if '\n' in document.text or ends_in_multiline_string():
return True
def line_ends_with_colon():
return document.current_line.rstrip()[-1:] == ':'
# If we just typed a colon, or still have open brackets, always insert a real newline.
if line_ends_with_colon() or \
(document.is_cursor_at_the_end and
has_unclosed_brackets(document.text_before_cursor)) or \
document.text.startswith('@'):
return True
# If the character before the cursor is a backslash (line continuation
# char), insert a new line.
elif document.text_before_cursor[-1:] == '\\':
return True
return False
def if_mousedown(handler):
"""
Decorator for mouse handlers.
Only handle event when the user pressed mouse down.
(When applied to a token list. Scroll events will bubble up and are handled
by the Window.)
"""
def handle_if_mouse_down(cli, mouse_event):
if mouse_event.event_type == MouseEventTypes.MOUSE_DOWN:
return handler(cli, mouse_event)
else:
return NotImplemented
return handle_if_mouse_down | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.254/Olde/rp 11.48.10 PM/rp_ptpython/utils.py | 0.516839 | 0.157234 | utils.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.application import Application
from prompt_toolkit.buffer import Buffer, AcceptAction
from prompt_toolkit.buffer_mapping import BufferMapping
from prompt_toolkit.document import Document
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import Condition, HasFocus, InFocusStack
from prompt_toolkit.key_binding.defaults import load_key_bindings
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.containers import HSplit, VSplit, Window, FloatContainer, Float, ConditionalContainer, Container, ScrollOffsets
from prompt_toolkit.layout.controls import BufferControl, FillControl
from prompt_toolkit.layout.dimension import LayoutDimension as D
from prompt_toolkit.layout.lexers import PygmentsLexer
from prompt_toolkit.layout.margins import Margin, ScrollbarMargin
from prompt_toolkit.layout.processors import Processor, Transformation, HighlightSearchProcessor, HighlightSelectionProcessor
from prompt_toolkit.layout.screen import Char
from prompt_toolkit.layout.toolbars import ArgToolbar, SearchToolbar
from prompt_toolkit.layout.toolbars import TokenListToolbar
from prompt_toolkit.layout.utils import token_list_to_text
from pygments.lexers import RstLexer
from pygments.token import Token
from .utils import if_mousedown
from rp.rp_ptpython.layout import get_inputmode_tokens
from functools import partial
import six
if six.PY2:
from pygments.lexers import PythonLexer
else:
from pygments.lexers import Python3Lexer as PythonLexer
HISTORY_BUFFER = 'HISTORY_BUFFER'
HELP_BUFFER = 'HELP_BUFFER'
HISTORY_COUNT = 2000
__all__ = (
'create_history_application',
)
HELP_TEXT = """
This interface is meant to select multiple lines from the
history and execute them together.
Typical usage
-------------
1. Move the ``cursor up`` in the history pane, until the
cursor is on the first desired line.
2. Hold down the ``space bar``, or press it multiple
times. Each time it will select one line and move to
the next one. Each selected line will appear on the
right side.
3. When all the required lines are displayed on the right
side, press ``Enter``. This will go back to the Python
REPL and show these lines as the current input. They
can still be edited from there.
Key bindings
------------
Many Emacs and Vi navigation key bindings should work.
Press ``F4`` to switch between Emacs and Vi mode.
Additional bindings:
- ``Space``: Select or delect a line.
- ``Tab``: Move the focus between the history and input
pane. (Alternative: ``Ctrl-W``)
- ``Ctrl-C``: Cancel. Ignore the result and go back to
the REPL. (Alternatives: ``q`` and ``Control-G``.)
- ``Enter``: Accept the result and go back to the REPL.
- ``F1``: Show/hide help. Press ``Enter`` to quit this
help message.
Further, remember that searching works like in Emacs
(using ``Ctrl-R``) or Vi (using ``/``).
"""
class BORDER:
" Box drawing characters. "
HORIZONTAL = '\u2501'
VERTICAL = '\u2503'
TOP_LEFT = '\u250f'
TOP_RIGHT = '\u2513'
BOTTOM_LEFT = '\u2517'
BOTTOM_RIGHT = '\u251b'
LIGHT_VERTICAL = '\u2502'
def create_popup_window(title, body):
"""
Return the layout for a pop-up window. It consists of a title bar showing
the `title` text, and a body layout. The window is surrounded by borders.
"""
assert isinstance(title, six.text_type)
assert isinstance(body, Container)
return HSplit([
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_LEFT, token=Token.Window.Border)),
TokenListToolbar(
get_tokens=lambda cli: [(Token.Window.Title, ' %s ' % title)],
align_center=True,
default_char=Char(BORDER.HORIZONTAL, Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_RIGHT, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
body,
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_LEFT, token=Token.Window.Border)),
Window(height=D.exact(1),
content=FillControl(BORDER.HORIZONTAL, token=Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_RIGHT, token=Token.Window.Border)),
]),
])
def create_layout(python_input, history_mapping):
"""
Create and return a `Container` instance for the history
application.
"""
processors = [
HighlightSearchProcessor(preview_search=True),
HighlightSelectionProcessor()]
help_window = create_popup_window(
title='History Help',
body=Window(
content=BufferControl(
buffer_name=HELP_BUFFER,
default_char=Char(token=Token),
lexer=PygmentsLexer(RstLexer),
input_processors=processors),
right_margins=[ScrollbarMargin()],
scroll_offsets=ScrollOffsets(top=2, bottom=2)))
return HSplit([
# Top title bar.
TokenListToolbar(
get_tokens=_get_top_toolbar_tokens,
align_center=True,
default_char=Char(' ', Token.Toolbar.Status)),
FloatContainer(
content=VSplit([
# Left side: history.
Window(
content=BufferControl(
buffer_name=HISTORY_BUFFER,
lexer=PygmentsLexer(PythonLexer),
input_processors=processors),
wrap_lines=False,
left_margins=[HistoryMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
# Separator.
Window(width=D.exact(1),
content=FillControl(BORDER.LIGHT_VERTICAL, token=Token.Separator)),
# Right side: result.
Window(
content=BufferControl(
buffer_name=DEFAULT_BUFFER,
input_processors=processors + [GrayExistingText(history_mapping)],
lexer=PygmentsLexer(PythonLexer)),
wrap_lines=False,
left_margins=[ResultMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
]),
floats=[
# Help text as a float.
Float(width=60, top=3, bottom=2,
content=ConditionalContainer(
# (We use InFocusStack, because it's possible to search
# through the help text as well, and at that point the search
# buffer has the focus.)
content=help_window, filter=InFocusStack(HELP_BUFFER))),
]
),
# Bottom toolbars.
ArgToolbar(),
SearchToolbar(),
TokenListToolbar(
get_tokens=partial(_get_bottom_toolbar_tokens, python_input=python_input),
default_char=Char(' ', Token.Toolbar.Status)),
])
def _get_top_toolbar_tokens(cli):
return [(Token.Toolbar.Status.Title, 'History browser - Insert from history')]
def _get_bottom_toolbar_tokens(cli, python_input):
@if_mousedown
def f1(cli, mouse_event):
_toggle_help(cli)
@if_mousedown
def tab(cli, mouse_event):
_select_other_window(cli)
return [
(Token.Toolbar.Status, ' ')
] + get_inputmode_tokens(cli, python_input) + [
(Token.Toolbar.Status, ' '),
(Token.Toolbar.Status.Key, '[Space]'),
(Token.Toolbar.Status, ' Toggle '),
(Token.Toolbar.Status.Key, '[Tab]', tab),
(Token.Toolbar.Status, ' Focus ', tab),
(Token.Toolbar.Status.Key, '[Enter]'),
(Token.Toolbar.Status, ' Accept '),
(Token.Toolbar.Status.Key, '[F1]', f1),
(Token.Toolbar.Status, ' Help ', f1),
]
class HistoryMargin(Margin):
"""
Margin for the history buffer.
This displays a green bar for the selected entries.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[HISTORY_BUFFER].document
lines_starting_new_entries = self.history_mapping.lines_starting_new_entries
selected_lines = self.history_mapping.selected_lines
current_lineno = document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
# Show stars at the start of each entry.
# (Visualises multiline entries.)
if line_number in lines_starting_new_entries:
char = '*'
else:
char = ' '
if line_number in selected_lines:
t = Token.History.Line.Selected
else:
t = Token.History.Line
if line_number == current_lineno:
t = t.Current
result.append((t, char))
result.append((Token, '\n'))
return result
class ResultMargin(Margin):
"""
The margin to be shown in the result pane.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[DEFAULT_BUFFER].document
current_lineno = document.cursor_position_row
offset = self.history_mapping.result_line_offset #original_document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
if (line_number is None or line_number < offset or
line_number >= offset + len(self.history_mapping.selected_lines)):
t = Token
elif line_number == current_lineno:
t = Token.History.Line.Selected.Current
else:
t = Token.History.Line.Selected
result.append((t, ' '))
result.append((Token, '\n'))
return result
def invalidation_hash(self, cli, document):
return document.cursor_position_row
class GrayExistingText(Processor):
"""
Turn the existing input, before and after the inserted code gray.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
self._lines_before = len(history_mapping.original_document.text_before_cursor.splitlines())
def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
if (lineno < self._lines_before or
lineno >= self._lines_before + len(self.history_mapping.selected_lines)):
text = token_list_to_text(tokens)
return Transformation(tokens=[(Token.History.ExistingInput, text)])
else:
return Transformation(tokens=tokens)
class HistoryMapping(object):
"""
Keep a list of all the lines from the history and the selected lines.
"""
def __init__(self, python_history, original_document):
self.python_history = python_history
self.original_document = original_document
self.lines_starting_new_entries = set()
self.selected_lines = set()
# Process history.
history_lines = []
for entry_nr, entry in list(enumerate(python_history))[-HISTORY_COUNT:]:
self.lines_starting_new_entries.add(len(history_lines))
for line in entry.splitlines():
history_lines.append(line)
if len(python_history) > HISTORY_COUNT:
history_lines[0] = '# *** History has been truncated to %s lines ***' % HISTORY_COUNT
self.history_lines = history_lines
self.concatenated_history = '\n'.join(history_lines)
# Line offset.
if self.original_document.text_before_cursor:
self.result_line_offset = self.original_document.cursor_position_row + 1
else:
self.result_line_offset = 0
def get_new_document(self, cursor_pos=None):
"""
Create a `Document` instance that contains the resulting text.
"""
lines = []
# Original text, before cursor.
if self.original_document.text_before_cursor:
lines.append(self.original_document.text_before_cursor)
# Selected entries from the history.
for line_no in sorted(self.selected_lines):
lines.append(self.history_lines[line_no])
# Original text, after cursor.
if self.original_document.text_after_cursor:
lines.append(self.original_document.text_after_cursor)
# Create `Document` with cursor at the right position.
text = '\n'.join(lines)
if cursor_pos is not None and cursor_pos > len(text):
cursor_pos = len(text)
return Document(text, cursor_pos)
def update_default_buffer(self, cli):
b = cli.buffers[DEFAULT_BUFFER]
b.set_document(
self.get_new_document(b.cursor_position), bypass_readonly=True)
def _toggle_help(cli):
" Display/hide help. "
if cli.current_buffer_name == HELP_BUFFER:
cli.pop_focus()
else:
cli.push_focus(HELP_BUFFER)
def _select_other_window(cli):
" Toggle focus between left/right window. "
if cli.current_buffer_name == HISTORY_BUFFER:
cli.focus(DEFAULT_BUFFER)
elif cli.current_buffer_name == DEFAULT_BUFFER:
cli.focus(HISTORY_BUFFER)
def create_key_bindings(python_input, history_mapping):
"""
Key bindings.
"""
registry = load_key_bindings(
enable_search=True,
enable_extra_page_navigation=True)
handle = registry.add_binding
@handle(' ', filter=HasFocus(HISTORY_BUFFER))
def _(event):
"""
Space: select/deselect line from history pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row
if line_no in history_mapping.selected_lines:
# Remove line.
history_mapping.selected_lines.remove(line_no)
history_mapping.update_default_buffer(event.cli)
else:
# Add line.
history_mapping.selected_lines.add(line_no)
history_mapping.update_default_buffer(event.cli)
# Update cursor position
default_buffer = event.cli.buffers[DEFAULT_BUFFER]
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
# Also move the cursor to the next line. (This way they can hold
# space to select a region.)
b.cursor_position = b.document.translate_row_col_to_index(line_no + 1, 0)
@handle(' ', filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.Delete, filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.ControlH, filter=HasFocus(DEFAULT_BUFFER))
def _(event):
"""
Space: remove line from default pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row - history_mapping.result_line_offset
if line_no >= 0:
try:
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass # When `selected_lines` is an empty set.
else:
history_mapping.selected_lines.remove(history_lineno)
history_mapping.update_default_buffer(event.cli)
help_focussed = HasFocus(HELP_BUFFER)
main_buffer_focussed = HasFocus(HISTORY_BUFFER) | HasFocus(DEFAULT_BUFFER)
@handle(Keys.Tab, filter=main_buffer_focussed)
@handle(Keys.ControlX, filter=main_buffer_focussed, eager=True)
# Eager: ignore the Emacs [Ctrl-X Ctrl-X] binding.
@handle(Keys.ControlW, filter=main_buffer_focussed)
def _(event):
" Select other window. "
_select_other_window(event.cli)
@handle(Keys.F4)
def _(event):
" Switch between Emacs/Vi mode. "
python_input.vi_mode = not python_input.vi_mode
@handle(Keys.F1)
def _(event):
" Display/hide help. "
_toggle_help(event.cli)
@handle(Keys.ControlJ, filter=help_focussed)
@handle(Keys.ControlC, filter=help_focussed)
@handle(Keys.ControlG, filter=help_focussed)
@handle(Keys.Escape, filter=help_focussed)
def _(event):
" Leave help. "
event.cli.pop_focus()
@handle('q', filter=main_buffer_focussed)
@handle(Keys.F3, filter=main_buffer_focussed)
@handle(Keys.ControlC, filter=main_buffer_focussed)
@handle(Keys.ControlG, filter=main_buffer_focussed)
def _(event):
" Cancel and go back. "
event.cli.set_return_value(None)
enable_system_bindings = Condition(lambda cli: python_input.enable_system_bindings)
@handle(Keys.ControlZ, filter=enable_system_bindings)
def _(event):
" Suspend to background. "
event.cli.suspend_to_background()
return registry
def create_history_application(python_input, original_document):
"""
Create an `Application` for the history screen.
This has to be run as a sub application of `python_input`.
When this application runs and returns, it retuns the selected lines.
"""
history_mapping = HistoryMapping(python_input.history, original_document)
def default_buffer_pos_changed(_):
""" When the cursor changes in the default buffer. Synchronize with
history buffer. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == DEFAULT_BUFFER:
try:
line_no = default_buffer.document.cursor_position_row - \
history_mapping.result_line_offset
if line_no < 0: # When the cursor is above the inserted region.
raise IndexError
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass
else:
history_buffer.cursor_position = \
history_buffer.document.translate_row_col_to_index(history_lineno, 0)
def history_buffer_pos_changed(_):
""" When the cursor changes in the history buffer. Synchronize. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == HISTORY_BUFFER:
line_no = history_buffer.document.cursor_position_row
if line_no in history_mapping.selected_lines:
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
history_buffer = Buffer(
initial_document=Document(history_mapping.concatenated_history),
on_cursor_position_changed=history_buffer_pos_changed,
accept_action=AcceptAction(
lambda cli, buffer: cli.set_return_value(default_buffer.document)),
read_only=True)
default_buffer = Buffer(
initial_document=history_mapping.get_new_document(),
on_cursor_position_changed=default_buffer_pos_changed,
read_only=True)
help_buffer = Buffer(
initial_document=Document(HELP_TEXT, 0),
accept_action=AcceptAction.IGNORE,
read_only=True
)
buffer_mapping = BufferMapping({
HISTORY_BUFFER: history_buffer,
DEFAULT_BUFFER: default_buffer,
HELP_BUFFER: help_buffer,
}, initial=HISTORY_BUFFER)
application = Application(
layout=create_layout(python_input, history_mapping),
use_alternate_screen=True,
buffers=buffer_mapping,
style=python_input._current_style,
mouse_support=Condition(lambda cli: python_input.enable_mouse_support),
key_bindings_registry=create_key_bindings(python_input, history_mapping)
)
return application | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.254/Olde/rp 5.45.01 PM/rp_ptpython/history_browser.py | 0.754101 | 0.161982 | history_browser.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.mouse_events import MouseEventTypes
import re
__all__ = (
'has_unclosed_brackets',
'get_jedi_script_from_document',
'document_is_multiline_python',
)
def has_unclosed_brackets(text):
"""
Starting at the end of the string. If we find an opening bracket
for which we didn't had a closing one yet, return True.
"""
stack = []
# Ignore braces inside strings
text = re.sub(r'''('[^']*'|"[^"]*")''', '', text) # XXX: handle escaped quotes.!
for c in reversed(text):
if c in '])}':
stack.append(c)
elif c in '[({':
if stack:
if ((c == '[' and stack[-1] == ']') or
(c == '{' and stack[-1] == '}') or
(c == '(' and stack[-1] == ')')):
stack.pop()
else:
# Opening bracket for which we didn't had a closing one.
return True
return False
def get_jedi_script_from_document(document, locals, globals):
import jedi # We keep this import in-line, to improve start-up time.
# Importing Jedi is 'slow'.
try:
return jedi.Interpreter(
document.text,
column=document.cursor_position_col,
line=document.cursor_position_row + 1,
path='input-text',
namespaces=[locals, globals])
except ValueError:
# Invalid cursor position.
# ValueError('`column` parameter is not in a valid range.')
return None
except AttributeError:
# Workaround for #65: https://github.com/jonathanslenders/python-prompt-toolkit/issues/65
# See also: https://github.com/davidhalter/jedi/issues/508
return None
except IndexError:
# Workaround Jedi issue #514: for https://github.com/davidhalter/jedi/issues/514
return None
except KeyError:
# Workaroud for a crash when the input is "u'", the start of a unicode string.
return None
except Exception:
# Workaround for: https://github.com/jonathanslenders/ptpython/issues/91
return None
_multiline_string_delims = re.compile('''[']{3}|["]{3}''')
def document_is_multiline_python(document):
"""
Determine whether this is a multiline Python document.
"""
def ends_in_multiline_string():
"""
``True`` if we're inside a multiline string at the end of the text.
"""
delims = _multiline_string_delims.findall(document.text)
opening = None
for delim in delims:
if opening is None:
opening = delim
elif delim == opening:
opening = None
return bool(opening)
if '\n' in document.text or ends_in_multiline_string():
return True
def line_ends_with_colon():
return document.current_line.rstrip()[-1:] == ':'
# If we just typed a colon, or still have open brackets, always insert a real newline.
if line_ends_with_colon() or \
(document.is_cursor_at_the_end and
has_unclosed_brackets(document.text_before_cursor)) or \
document.text.startswith('@'):
return True
# If the character before the cursor is a backslash (line continuation
# char), insert a new line.
elif document.text_before_cursor[-1:] == '\\':
return True
return False
def if_mousedown(handler):
"""
Decorator for mouse handlers.
Only handle event when the user pressed mouse down.
(When applied to a token list. Scroll events will bubble up and are handled
by the Window.)
"""
def handle_if_mouse_down(cli, mouse_event):
if mouse_event.event_type == MouseEventTypes.MOUSE_DOWN:
return handler(cli, mouse_event)
else:
return NotImplemented
return handle_if_mouse_down | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.254/Olde/rp 5.45.01 PM/rp_ptpython/utils.py | 0.516839 | 0.157234 | utils.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.application import Application
from prompt_toolkit.buffer import Buffer, AcceptAction
from prompt_toolkit.buffer_mapping import BufferMapping
from prompt_toolkit.document import Document
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import Condition, HasFocus, InFocusStack
from prompt_toolkit.key_binding.defaults import load_key_bindings
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.containers import HSplit, VSplit, Window, FloatContainer, Float, ConditionalContainer, Container, ScrollOffsets
from prompt_toolkit.layout.controls import BufferControl, FillControl
from prompt_toolkit.layout.dimension import LayoutDimension as D
from prompt_toolkit.layout.lexers import PygmentsLexer
from prompt_toolkit.layout.margins import Margin, ScrollbarMargin
from prompt_toolkit.layout.processors import Processor, Transformation, HighlightSearchProcessor, HighlightSelectionProcessor
from prompt_toolkit.layout.screen import Char
from prompt_toolkit.layout.toolbars import ArgToolbar, SearchToolbar
from prompt_toolkit.layout.toolbars import TokenListToolbar
from prompt_toolkit.layout.utils import token_list_to_text
from pygments.lexers import RstLexer
from pygments.token import Token
from .utils import if_mousedown
from rp.rp_ptpython.layout import get_inputmode_tokens
from functools import partial
import six
if six.PY2:
from pygments.lexers import PythonLexer
else:
from pygments.lexers import Python3Lexer as PythonLexer
HISTORY_BUFFER = 'HISTORY_BUFFER'
HELP_BUFFER = 'HELP_BUFFER'
HISTORY_COUNT = 2000
__all__ = (
'create_history_application',
)
HELP_TEXT = """
This interface is meant to select multiple lines from the
history and execute them together.
Typical usage
-------------
1. Move the ``cursor up`` in the history pane, until the
cursor is on the first desired line.
2. Hold down the ``space bar``, or press it multiple
times. Each time it will select one line and move to
the next one. Each selected line will appear on the
right side.
3. When all the required lines are displayed on the right
side, press ``Enter``. This will go back to the Python
REPL and show these lines as the current input. They
can still be edited from there.
Key bindings
------------
Many Emacs and Vi navigation key bindings should work.
Press ``F4`` to switch between Emacs and Vi mode.
Additional bindings:
- ``Space``: Select or delect a line.
- ``Tab``: Move the focus between the history and input
pane. (Alternative: ``Ctrl-W``)
- ``Ctrl-C``: Cancel. Ignore the result and go back to
the REPL. (Alternatives: ``q`` and ``Control-G``.)
- ``Enter``: Accept the result and go back to the REPL.
- ``F1``: Show/hide help. Press ``Enter`` to quit this
help message.
Further, remember that searching works like in Emacs
(using ``Ctrl-R``) or Vi (using ``/``).
"""
class BORDER:
" Box drawing characters. "
HORIZONTAL = '\u2501'
VERTICAL = '\u2503'
TOP_LEFT = '\u250f'
TOP_RIGHT = '\u2513'
BOTTOM_LEFT = '\u2517'
BOTTOM_RIGHT = '\u251b'
LIGHT_VERTICAL = '\u2502'
def create_popup_window(title, body):
"""
Return the layout for a pop-up window. It consists of a title bar showing
the `title` text, and a body layout. The window is surrounded by borders.
"""
assert isinstance(title, six.text_type)
assert isinstance(body, Container)
return HSplit([
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_LEFT, token=Token.Window.Border)),
TokenListToolbar(
get_tokens=lambda cli: [(Token.Window.Title, ' %s ' % title)],
align_center=True,
default_char=Char(BORDER.HORIZONTAL, Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_RIGHT, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
body,
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_LEFT, token=Token.Window.Border)),
Window(height=D.exact(1),
content=FillControl(BORDER.HORIZONTAL, token=Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_RIGHT, token=Token.Window.Border)),
]),
])
def create_layout(python_input, history_mapping):
"""
Create and return a `Container` instance for the history
application.
"""
processors = [
HighlightSearchProcessor(preview_search=True),
HighlightSelectionProcessor()]
help_window = create_popup_window(
title='History Help',
body=Window(
content=BufferControl(
buffer_name=HELP_BUFFER,
default_char=Char(token=Token),
lexer=PygmentsLexer(RstLexer),
input_processors=processors),
right_margins=[ScrollbarMargin()],
scroll_offsets=ScrollOffsets(top=2, bottom=2)))
return HSplit([
# Top title bar.
TokenListToolbar(
get_tokens=_get_top_toolbar_tokens,
align_center=True,
default_char=Char(' ', Token.Toolbar.Status)),
FloatContainer(
content=VSplit([
# Left side: history.
Window(
content=BufferControl(
buffer_name=HISTORY_BUFFER,
lexer=PygmentsLexer(PythonLexer),
input_processors=processors),
wrap_lines=False,
left_margins=[HistoryMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
# Separator.
Window(width=D.exact(1),
content=FillControl(BORDER.LIGHT_VERTICAL, token=Token.Separator)),
# Right side: result.
Window(
content=BufferControl(
buffer_name=DEFAULT_BUFFER,
input_processors=processors + [GrayExistingText(history_mapping)],
lexer=PygmentsLexer(PythonLexer)),
wrap_lines=False,
left_margins=[ResultMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
]),
floats=[
# Help text as a float.
Float(width=60, top=3, bottom=2,
content=ConditionalContainer(
# (We use InFocusStack, because it's possible to search
# through the help text as well, and at that point the search
# buffer has the focus.)
content=help_window, filter=InFocusStack(HELP_BUFFER))),
]
),
# Bottom toolbars.
ArgToolbar(),
SearchToolbar(),
TokenListToolbar(
get_tokens=partial(_get_bottom_toolbar_tokens, python_input=python_input),
default_char=Char(' ', Token.Toolbar.Status)),
])
def _get_top_toolbar_tokens(cli):
return [(Token.Toolbar.Status.Title, 'History browser - Insert from history')]
def _get_bottom_toolbar_tokens(cli, python_input):
@if_mousedown
def f1(cli, mouse_event):
_toggle_help(cli)
@if_mousedown
def tab(cli, mouse_event):
_select_other_window(cli)
return [
(Token.Toolbar.Status, ' ')
] + get_inputmode_tokens(cli, python_input) + [
(Token.Toolbar.Status, ' '),
(Token.Toolbar.Status.Key, '[Space]'),
(Token.Toolbar.Status, ' Toggle '),
(Token.Toolbar.Status.Key, '[Tab]', tab),
(Token.Toolbar.Status, ' Focus ', tab),
(Token.Toolbar.Status.Key, '[Enter]'),
(Token.Toolbar.Status, ' Accept '),
(Token.Toolbar.Status.Key, '[F1]', f1),
(Token.Toolbar.Status, ' Help ', f1),
]
class HistoryMargin(Margin):
"""
Margin for the history buffer.
This displays a green bar for the selected entries.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[HISTORY_BUFFER].document
lines_starting_new_entries = self.history_mapping.lines_starting_new_entries
selected_lines = self.history_mapping.selected_lines
current_lineno = document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
# Show stars at the start of each entry.
# (Visualises multiline entries.)
if line_number in lines_starting_new_entries:
char = '*'
else:
char = ' '
if line_number in selected_lines:
t = Token.History.Line.Selected
else:
t = Token.History.Line
if line_number == current_lineno:
t = t.Current
result.append((t, char))
result.append((Token, '\n'))
return result
class ResultMargin(Margin):
"""
The margin to be shown in the result pane.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[DEFAULT_BUFFER].document
current_lineno = document.cursor_position_row
offset = self.history_mapping.result_line_offset #original_document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
if (line_number is None or line_number < offset or
line_number >= offset + len(self.history_mapping.selected_lines)):
t = Token
elif line_number == current_lineno:
t = Token.History.Line.Selected.Current
else:
t = Token.History.Line.Selected
result.append((t, ' '))
result.append((Token, '\n'))
return result
def invalidation_hash(self, cli, document):
return document.cursor_position_row
class GrayExistingText(Processor):
"""
Turn the existing input, before and after the inserted code gray.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
self._lines_before = len(history_mapping.original_document.text_before_cursor.splitlines())
def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
if (lineno < self._lines_before or
lineno >= self._lines_before + len(self.history_mapping.selected_lines)):
text = token_list_to_text(tokens)
return Transformation(tokens=[(Token.History.ExistingInput, text)])
else:
return Transformation(tokens=tokens)
class HistoryMapping(object):
"""
Keep a list of all the lines from the history and the selected lines.
"""
def __init__(self, python_history, original_document):
self.python_history = python_history
self.original_document = original_document
self.lines_starting_new_entries = set()
self.selected_lines = set()
# Process history.
history_lines = []
for entry_nr, entry in list(enumerate(python_history))[-HISTORY_COUNT:]:
self.lines_starting_new_entries.add(len(history_lines))
for line in entry.splitlines():
history_lines.append(line)
if len(python_history) > HISTORY_COUNT:
history_lines[0] = '# *** History has been truncated to %s lines ***' % HISTORY_COUNT
self.history_lines = history_lines
self.concatenated_history = '\n'.join(history_lines)
# Line offset.
if self.original_document.text_before_cursor:
self.result_line_offset = self.original_document.cursor_position_row + 1
else:
self.result_line_offset = 0
def get_new_document(self, cursor_pos=None):
"""
Create a `Document` instance that contains the resulting text.
"""
lines = []
# Original text, before cursor.
if self.original_document.text_before_cursor:
lines.append(self.original_document.text_before_cursor)
# Selected entries from the history.
for line_no in sorted(self.selected_lines):
lines.append(self.history_lines[line_no])
# Original text, after cursor.
if self.original_document.text_after_cursor:
lines.append(self.original_document.text_after_cursor)
# Create `Document` with cursor at the right position.
text = '\n'.join(lines)
if cursor_pos is not None and cursor_pos > len(text):
cursor_pos = len(text)
return Document(text, cursor_pos)
def update_default_buffer(self, cli):
b = cli.buffers[DEFAULT_BUFFER]
b.set_document(
self.get_new_document(b.cursor_position), bypass_readonly=True)
def _toggle_help(cli):
" Display/hide help. "
if cli.current_buffer_name == HELP_BUFFER:
cli.pop_focus()
else:
cli.push_focus(HELP_BUFFER)
def _select_other_window(cli):
" Toggle focus between left/right window. "
if cli.current_buffer_name == HISTORY_BUFFER:
cli.focus(DEFAULT_BUFFER)
elif cli.current_buffer_name == DEFAULT_BUFFER:
cli.focus(HISTORY_BUFFER)
def create_key_bindings(python_input, history_mapping):
"""
Key bindings.
"""
registry = load_key_bindings(
enable_search=True,
enable_extra_page_navigation=True)
handle = registry.add_binding
@handle(' ', filter=HasFocus(HISTORY_BUFFER))
def _(event):
"""
Space: select/deselect line from history pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row
if line_no in history_mapping.selected_lines:
# Remove line.
history_mapping.selected_lines.remove(line_no)
history_mapping.update_default_buffer(event.cli)
else:
# Add line.
history_mapping.selected_lines.add(line_no)
history_mapping.update_default_buffer(event.cli)
# Update cursor position
default_buffer = event.cli.buffers[DEFAULT_BUFFER]
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
# Also move the cursor to the next line. (This way they can hold
# space to select a region.)
b.cursor_position = b.document.translate_row_col_to_index(line_no + 1, 0)
@handle(' ', filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.Delete, filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.ControlH, filter=HasFocus(DEFAULT_BUFFER))
def _(event):
"""
Space: remove line from default pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row - history_mapping.result_line_offset
if line_no >= 0:
try:
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass # When `selected_lines` is an empty set.
else:
history_mapping.selected_lines.remove(history_lineno)
history_mapping.update_default_buffer(event.cli)
help_focussed = HasFocus(HELP_BUFFER)
main_buffer_focussed = HasFocus(HISTORY_BUFFER) | HasFocus(DEFAULT_BUFFER)
@handle(Keys.Tab, filter=main_buffer_focussed)
@handle(Keys.ControlX, filter=main_buffer_focussed, eager=True)
# Eager: ignore the Emacs [Ctrl-X Ctrl-X] binding.
@handle(Keys.ControlW, filter=main_buffer_focussed)
def _(event):
" Select other window. "
_select_other_window(event.cli)
@handle(Keys.F4)
def _(event):
" Switch between Emacs/Vi mode. "
python_input.vi_mode = not python_input.vi_mode
@handle(Keys.F1)
def _(event):
" Display/hide help. "
_toggle_help(event.cli)
@handle(Keys.ControlJ, filter=help_focussed)
@handle(Keys.ControlC, filter=help_focussed)
@handle(Keys.ControlG, filter=help_focussed)
@handle(Keys.Escape, filter=help_focussed)
def _(event):
" Leave help. "
event.cli.pop_focus()
@handle('q', filter=main_buffer_focussed)
@handle(Keys.F3, filter=main_buffer_focussed)
@handle(Keys.ControlC, filter=main_buffer_focussed)
@handle(Keys.ControlG, filter=main_buffer_focussed)
def _(event):
" Cancel and go back. "
event.cli.set_return_value(None)
enable_system_bindings = Condition(lambda cli: python_input.enable_system_bindings)
@handle(Keys.ControlZ, filter=enable_system_bindings)
def _(event):
" Suspend to background. "
event.cli.suspend_to_background()
return registry
def create_history_application(python_input, original_document):
"""
Create an `Application` for the history screen.
This has to be run as a sub application of `python_input`.
When this application runs and returns, it retuns the selected lines.
"""
history_mapping = HistoryMapping(python_input.history, original_document)
def default_buffer_pos_changed(_):
""" When the cursor changes in the default buffer. Synchronize with
history buffer. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == DEFAULT_BUFFER:
try:
line_no = default_buffer.document.cursor_position_row - \
history_mapping.result_line_offset
if line_no < 0: # When the cursor is above the inserted region.
raise IndexError
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass
else:
history_buffer.cursor_position = \
history_buffer.document.translate_row_col_to_index(history_lineno, 0)
def history_buffer_pos_changed(_):
""" When the cursor changes in the history buffer. Synchronize. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == HISTORY_BUFFER:
line_no = history_buffer.document.cursor_position_row
if line_no in history_mapping.selected_lines:
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
history_buffer = Buffer(
initial_document=Document(history_mapping.concatenated_history),
on_cursor_position_changed=history_buffer_pos_changed,
accept_action=AcceptAction(
lambda cli, buffer: cli.set_return_value(default_buffer.document)),
read_only=True)
default_buffer = Buffer(
initial_document=history_mapping.get_new_document(),
on_cursor_position_changed=default_buffer_pos_changed,
read_only=True)
help_buffer = Buffer(
initial_document=Document(HELP_TEXT, 0),
accept_action=AcceptAction.IGNORE,
read_only=True
)
buffer_mapping = BufferMapping({
HISTORY_BUFFER: history_buffer,
DEFAULT_BUFFER: default_buffer,
HELP_BUFFER: help_buffer,
}, initial=HISTORY_BUFFER)
application = Application(
layout=create_layout(python_input, history_mapping),
use_alternate_screen=True,
buffers=buffer_mapping,
style=python_input._current_style,
mouse_support=Condition(lambda cli: python_input.enable_mouse_support),
key_bindings_registry=create_key_bindings(python_input, history_mapping)
)
return application | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.254/Olde/rp 7.24.17 AM/rp_ptpython/history_browser.py | 0.754101 | 0.161982 | history_browser.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.mouse_events import MouseEventTypes
import re
__all__ = (
'has_unclosed_brackets',
'get_jedi_script_from_document',
'document_is_multiline_python',
)
def has_unclosed_brackets(text):
"""
Starting at the end of the string. If we find an opening bracket
for which we didn't had a closing one yet, return True.
"""
stack = []
# Ignore braces inside strings
text = re.sub(r'''('[^']*'|"[^"]*")''', '', text) # XXX: handle escaped quotes.!
for c in reversed(text):
if c in '])}':
stack.append(c)
elif c in '[({':
if stack:
if ((c == '[' and stack[-1] == ']') or
(c == '{' and stack[-1] == '}') or
(c == '(' and stack[-1] == ')')):
stack.pop()
else:
# Opening bracket for which we didn't had a closing one.
return True
return False
def get_jedi_script_from_document(document, locals, globals):
import jedi # We keep this import in-line, to improve start-up time.
# Importing Jedi is 'slow'.
try:
return jedi.Interpreter(
document.text,
column=document.cursor_position_col,
line=document.cursor_position_row + 1,
path='input-text',
namespaces=[locals, globals])
except ValueError:
# Invalid cursor position.
# ValueError('`column` parameter is not in a valid range.')
return None
except AttributeError:
# Workaround for #65: https://github.com/jonathanslenders/python-prompt-toolkit/issues/65
# See also: https://github.com/davidhalter/jedi/issues/508
return None
except IndexError:
# Workaround Jedi issue #514: for https://github.com/davidhalter/jedi/issues/514
return None
except KeyError:
# Workaroud for a crash when the input is "u'", the start of a unicode string.
return None
except Exception:
# Workaround for: https://github.com/jonathanslenders/ptpython/issues/91
return None
_multiline_string_delims = re.compile('''[']{3}|["]{3}''')
def document_is_multiline_python(document):
"""
Determine whether this is a multiline Python document.
"""
def ends_in_multiline_string():
"""
``True`` if we're inside a multiline string at the end of the text.
"""
delims = _multiline_string_delims.findall(document.text)
opening = None
for delim in delims:
if opening is None:
opening = delim
elif delim == opening:
opening = None
return bool(opening)
if '\n' in document.text or ends_in_multiline_string():
return True
def line_ends_with_colon():
return document.current_line.rstrip()[-1:] == ':'
# If we just typed a colon, or still have open brackets, always insert a real newline.
if line_ends_with_colon() or \
(document.is_cursor_at_the_end and
has_unclosed_brackets(document.text_before_cursor)) or \
document.text.startswith('@'):
return True
# If the character before the cursor is a backslash (line continuation
# char), insert a new line.
elif document.text_before_cursor[-1:] == '\\':
return True
return False
def if_mousedown(handler):
"""
Decorator for mouse handlers.
Only handle event when the user pressed mouse down.
(When applied to a token list. Scroll events will bubble up and are handled
by the Window.)
"""
def handle_if_mouse_down(cli, mouse_event):
if mouse_event.event_type == MouseEventTypes.MOUSE_DOWN:
return handler(cli, mouse_event)
else:
return NotImplemented
return handle_if_mouse_down | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.254/Olde/rp 7.24.17 AM/rp_ptpython/utils.py | 0.516839 | 0.157234 | utils.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.application import Application
from prompt_toolkit.buffer import Buffer, AcceptAction
from prompt_toolkit.buffer_mapping import BufferMapping
from prompt_toolkit.document import Document
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import Condition, HasFocus, InFocusStack
from prompt_toolkit.key_binding.defaults import load_key_bindings
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.containers import HSplit, VSplit, Window, FloatContainer, Float, ConditionalContainer, Container, ScrollOffsets
from prompt_toolkit.layout.controls import BufferControl, FillControl
from prompt_toolkit.layout.dimension import LayoutDimension as D
from prompt_toolkit.layout.lexers import PygmentsLexer
from prompt_toolkit.layout.margins import Margin, ScrollbarMargin
from prompt_toolkit.layout.processors import Processor, Transformation, HighlightSearchProcessor, HighlightSelectionProcessor
from prompt_toolkit.layout.screen import Char
from prompt_toolkit.layout.toolbars import ArgToolbar, SearchToolbar
from prompt_toolkit.layout.toolbars import TokenListToolbar
from prompt_toolkit.layout.utils import token_list_to_text
from pygments.lexers import RstLexer
from pygments.token import Token
from .utils import if_mousedown
from rp.rp_ptpython.layout import get_inputmode_tokens
from functools import partial
import six
if six.PY2:
from pygments.lexers import PythonLexer
else:
from pygments.lexers import Python3Lexer as PythonLexer
HISTORY_BUFFER = 'HISTORY_BUFFER'
HELP_BUFFER = 'HELP_BUFFER'
HISTORY_COUNT = 2000
__all__ = (
'create_history_application',
)
HELP_TEXT = """
This interface is meant to select multiple lines from the
history and execute them together.
Typical usage
-------------
1. Move the ``cursor up`` in the history pane, until the
cursor is on the first desired line.
2. Hold down the ``space bar``, or press it multiple
times. Each time it will select one line and move to
the next one. Each selected line will appear on the
right side.
3. When all the required lines are displayed on the right
side, press ``Enter``. This will go back to the Python
REPL and show these lines as the current input. They
can still be edited from there.
Key bindings
------------
Many Emacs and Vi navigation key bindings should work.
Press ``F4`` to switch between Emacs and Vi mode.
Additional bindings:
- ``Space``: Select or delect a line.
- ``Tab``: Move the focus between the history and input
pane. (Alternative: ``Ctrl-W``)
- ``Ctrl-C``: Cancel. Ignore the result and go back to
the REPL. (Alternatives: ``q`` and ``Control-G``.)
- ``Enter``: Accept the result and go back to the REPL.
- ``F1``: Show/hide help. Press ``Enter`` to quit this
help message.
Further, remember that searching works like in Emacs
(using ``Ctrl-R``) or Vi (using ``/``).
"""
class BORDER:
" Box drawing characters. "
HORIZONTAL = '\u2501'
VERTICAL = '\u2503'
TOP_LEFT = '\u250f'
TOP_RIGHT = '\u2513'
BOTTOM_LEFT = '\u2517'
BOTTOM_RIGHT = '\u251b'
LIGHT_VERTICAL = '\u2502'
def create_popup_window(title, body):
"""
Return the layout for a pop-up window. It consists of a title bar showing
the `title` text, and a body layout. The window is surrounded by borders.
"""
assert isinstance(title, six.text_type)
assert isinstance(body, Container)
return HSplit([
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_LEFT, token=Token.Window.Border)),
TokenListToolbar(
get_tokens=lambda cli: [(Token.Window.Title, ' %s ' % title)],
align_center=True,
default_char=Char(BORDER.HORIZONTAL, Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_RIGHT, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
body,
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_LEFT, token=Token.Window.Border)),
Window(height=D.exact(1),
content=FillControl(BORDER.HORIZONTAL, token=Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_RIGHT, token=Token.Window.Border)),
]),
])
def create_layout(python_input, history_mapping):
"""
Create and return a `Container` instance for the history
application.
"""
processors = [
HighlightSearchProcessor(preview_search=True),
HighlightSelectionProcessor()]
help_window = create_popup_window(
title='History Help',
body=Window(
content=BufferControl(
buffer_name=HELP_BUFFER,
default_char=Char(token=Token),
lexer=PygmentsLexer(RstLexer),
input_processors=processors),
right_margins=[ScrollbarMargin()],
scroll_offsets=ScrollOffsets(top=2, bottom=2)))
return HSplit([
# Top title bar.
TokenListToolbar(
get_tokens=_get_top_toolbar_tokens,
align_center=True,
default_char=Char(' ', Token.Toolbar.Status)),
FloatContainer(
content=VSplit([
# Left side: history.
Window(
content=BufferControl(
buffer_name=HISTORY_BUFFER,
lexer=PygmentsLexer(PythonLexer),
input_processors=processors),
wrap_lines=False,
left_margins=[HistoryMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
# Separator.
Window(width=D.exact(1),
content=FillControl(BORDER.LIGHT_VERTICAL, token=Token.Separator)),
# Right side: result.
Window(
content=BufferControl(
buffer_name=DEFAULT_BUFFER,
input_processors=processors + [GrayExistingText(history_mapping)],
lexer=PygmentsLexer(PythonLexer)),
wrap_lines=False,
left_margins=[ResultMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
]),
floats=[
# Help text as a float.
Float(width=60, top=3, bottom=2,
content=ConditionalContainer(
# (We use InFocusStack, because it's possible to search
# through the help text as well, and at that point the search
# buffer has the focus.)
content=help_window, filter=InFocusStack(HELP_BUFFER))),
]
),
# Bottom toolbars.
ArgToolbar(),
SearchToolbar(),
TokenListToolbar(
get_tokens=partial(_get_bottom_toolbar_tokens, python_input=python_input),
default_char=Char(' ', Token.Toolbar.Status)),
])
def _get_top_toolbar_tokens(cli):
return [(Token.Toolbar.Status.Title, 'History browser - Insert from history')]
def _get_bottom_toolbar_tokens(cli, python_input):
@if_mousedown
def f1(cli, mouse_event):
_toggle_help(cli)
@if_mousedown
def tab(cli, mouse_event):
_select_other_window(cli)
return [
(Token.Toolbar.Status, ' ')
] + get_inputmode_tokens(cli, python_input) + [
(Token.Toolbar.Status, ' '),
(Token.Toolbar.Status.Key, '[Space]'),
(Token.Toolbar.Status, ' Toggle '),
(Token.Toolbar.Status.Key, '[Tab]', tab),
(Token.Toolbar.Status, ' Focus ', tab),
(Token.Toolbar.Status.Key, '[Enter]'),
(Token.Toolbar.Status, ' Accept '),
(Token.Toolbar.Status.Key, '[F1]', f1),
(Token.Toolbar.Status, ' Help ', f1),
]
class HistoryMargin(Margin):
"""
Margin for the history buffer.
This displays a green bar for the selected entries.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[HISTORY_BUFFER].document
lines_starting_new_entries = self.history_mapping.lines_starting_new_entries
selected_lines = self.history_mapping.selected_lines
current_lineno = document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
# Show stars at the start of each entry.
# (Visualises multiline entries.)
if line_number in lines_starting_new_entries:
char = '*'
else:
char = ' '
if line_number in selected_lines:
t = Token.History.Line.Selected
else:
t = Token.History.Line
if line_number == current_lineno:
t = t.Current
result.append((t, char))
result.append((Token, '\n'))
return result
class ResultMargin(Margin):
"""
The margin to be shown in the result pane.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[DEFAULT_BUFFER].document
current_lineno = document.cursor_position_row
offset = self.history_mapping.result_line_offset #original_document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
if (line_number is None or line_number < offset or
line_number >= offset + len(self.history_mapping.selected_lines)):
t = Token
elif line_number == current_lineno:
t = Token.History.Line.Selected.Current
else:
t = Token.History.Line.Selected
result.append((t, ' '))
result.append((Token, '\n'))
return result
def invalidation_hash(self, cli, document):
return document.cursor_position_row
class GrayExistingText(Processor):
"""
Turn the existing input, before and after the inserted code gray.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
self._lines_before = len(history_mapping.original_document.text_before_cursor.splitlines())
def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
if (lineno < self._lines_before or
lineno >= self._lines_before + len(self.history_mapping.selected_lines)):
text = token_list_to_text(tokens)
return Transformation(tokens=[(Token.History.ExistingInput, text)])
else:
return Transformation(tokens=tokens)
class HistoryMapping(object):
"""
Keep a list of all the lines from the history and the selected lines.
"""
def __init__(self, python_history, original_document):
self.python_history = python_history
self.original_document = original_document
self.lines_starting_new_entries = set()
self.selected_lines = set()
# Process history.
history_lines = []
for entry_nr, entry in list(enumerate(python_history))[-HISTORY_COUNT:]:
self.lines_starting_new_entries.add(len(history_lines))
for line in entry.splitlines():
history_lines.append(line)
if len(python_history) > HISTORY_COUNT:
history_lines[0] = '# *** History has been truncated to %s lines ***' % HISTORY_COUNT
self.history_lines = history_lines
self.concatenated_history = '\n'.join(history_lines)
# Line offset.
if self.original_document.text_before_cursor:
self.result_line_offset = self.original_document.cursor_position_row + 1
else:
self.result_line_offset = 0
def get_new_document(self, cursor_pos=None):
"""
Create a `Document` instance that contains the resulting text.
"""
lines = []
# Original text, before cursor.
if self.original_document.text_before_cursor:
lines.append(self.original_document.text_before_cursor)
# Selected entries from the history.
for line_no in sorted(self.selected_lines):
lines.append(self.history_lines[line_no])
# Original text, after cursor.
if self.original_document.text_after_cursor:
lines.append(self.original_document.text_after_cursor)
# Create `Document` with cursor at the right position.
text = '\n'.join(lines)
if cursor_pos is not None and cursor_pos > len(text):
cursor_pos = len(text)
return Document(text, cursor_pos)
def update_default_buffer(self, cli):
b = cli.buffers[DEFAULT_BUFFER]
b.set_document(
self.get_new_document(b.cursor_position), bypass_readonly=True)
def _toggle_help(cli):
" Display/hide help. "
if cli.current_buffer_name == HELP_BUFFER:
cli.pop_focus()
else:
cli.push_focus(HELP_BUFFER)
def _select_other_window(cli):
" Toggle focus between left/right window. "
if cli.current_buffer_name == HISTORY_BUFFER:
cli.focus(DEFAULT_BUFFER)
elif cli.current_buffer_name == DEFAULT_BUFFER:
cli.focus(HISTORY_BUFFER)
def create_key_bindings(python_input, history_mapping):
"""
Key bindings.
"""
registry = load_key_bindings(
enable_search=True,
enable_extra_page_navigation=True)
handle = registry.add_binding
@handle(' ', filter=HasFocus(HISTORY_BUFFER))
def _(event):
"""
Space: select/deselect line from history pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row
if line_no in history_mapping.selected_lines:
# Remove line.
history_mapping.selected_lines.remove(line_no)
history_mapping.update_default_buffer(event.cli)
else:
# Add line.
history_mapping.selected_lines.add(line_no)
history_mapping.update_default_buffer(event.cli)
# Update cursor position
default_buffer = event.cli.buffers[DEFAULT_BUFFER]
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
# Also move the cursor to the next line. (This way they can hold
# space to select a region.)
b.cursor_position = b.document.translate_row_col_to_index(line_no + 1, 0)
@handle(' ', filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.Delete, filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.ControlH, filter=HasFocus(DEFAULT_BUFFER))
def _(event):
"""
Space: remove line from default pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row - history_mapping.result_line_offset
if line_no >= 0:
try:
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass # When `selected_lines` is an empty set.
else:
history_mapping.selected_lines.remove(history_lineno)
history_mapping.update_default_buffer(event.cli)
help_focussed = HasFocus(HELP_BUFFER)
main_buffer_focussed = HasFocus(HISTORY_BUFFER) | HasFocus(DEFAULT_BUFFER)
@handle(Keys.Tab, filter=main_buffer_focussed)
@handle(Keys.ControlX, filter=main_buffer_focussed, eager=True)
# Eager: ignore the Emacs [Ctrl-X Ctrl-X] binding.
@handle(Keys.ControlW, filter=main_buffer_focussed)
def _(event):
" Select other window. "
_select_other_window(event.cli)
@handle(Keys.F4)
def _(event):
" Switch between Emacs/Vi mode. "
python_input.vi_mode = not python_input.vi_mode
@handle(Keys.F1)
def _(event):
" Display/hide help. "
_toggle_help(event.cli)
@handle(Keys.ControlJ, filter=help_focussed)
@handle(Keys.ControlC, filter=help_focussed)
@handle(Keys.ControlG, filter=help_focussed)
@handle(Keys.Escape, filter=help_focussed)
def _(event):
" Leave help. "
event.cli.pop_focus()
@handle('q', filter=main_buffer_focussed)
@handle(Keys.F3, filter=main_buffer_focussed)
@handle(Keys.ControlC, filter=main_buffer_focussed)
@handle(Keys.ControlG, filter=main_buffer_focussed)
def _(event):
" Cancel and go back. "
event.cli.set_return_value(None)
enable_system_bindings = Condition(lambda cli: python_input.enable_system_bindings)
@handle(Keys.ControlZ, filter=enable_system_bindings)
def _(event):
" Suspend to background. "
event.cli.suspend_to_background()
return registry
def create_history_application(python_input, original_document):
"""
Create an `Application` for the history screen.
This has to be run as a sub application of `python_input`.
When this application runs and returns, it retuns the selected lines.
"""
history_mapping = HistoryMapping(python_input.history, original_document)
def default_buffer_pos_changed(_):
""" When the cursor changes in the default buffer. Synchronize with
history buffer. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == DEFAULT_BUFFER:
try:
line_no = default_buffer.document.cursor_position_row - \
history_mapping.result_line_offset
if line_no < 0: # When the cursor is above the inserted region.
raise IndexError
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass
else:
history_buffer.cursor_position = \
history_buffer.document.translate_row_col_to_index(history_lineno, 0)
def history_buffer_pos_changed(_):
""" When the cursor changes in the history buffer. Synchronize. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == HISTORY_BUFFER:
line_no = history_buffer.document.cursor_position_row
if line_no in history_mapping.selected_lines:
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
history_buffer = Buffer(
initial_document=Document(history_mapping.concatenated_history),
on_cursor_position_changed=history_buffer_pos_changed,
accept_action=AcceptAction(
lambda cli, buffer: cli.set_return_value(default_buffer.document)),
read_only=True)
default_buffer = Buffer(
initial_document=history_mapping.get_new_document(),
on_cursor_position_changed=default_buffer_pos_changed,
read_only=True)
help_buffer = Buffer(
initial_document=Document(HELP_TEXT, 0),
accept_action=AcceptAction.IGNORE,
read_only=True
)
buffer_mapping = BufferMapping({
HISTORY_BUFFER: history_buffer,
DEFAULT_BUFFER: default_buffer,
HELP_BUFFER: help_buffer,
}, initial=HISTORY_BUFFER)
application = Application(
layout=create_layout(python_input, history_mapping),
use_alternate_screen=True,
buffers=buffer_mapping,
style=python_input._current_style,
mouse_support=Condition(lambda cli: python_input.enable_mouse_support),
key_bindings_registry=create_key_bindings(python_input, history_mapping)
)
return application | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.254/Olde/rp 5.38.10 PM/rp_ptpython/history_browser.py | 0.754101 | 0.161982 | history_browser.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.mouse_events import MouseEventTypes
import re
__all__ = (
'has_unclosed_brackets',
'get_jedi_script_from_document',
'document_is_multiline_python',
)
def has_unclosed_brackets(text):
"""
Starting at the end of the string. If we find an opening bracket
for which we didn't had a closing one yet, return True.
"""
stack = []
# Ignore braces inside strings
text = re.sub(r'''('[^']*'|"[^"]*")''', '', text) # XXX: handle escaped quotes.!
for c in reversed(text):
if c in '])}':
stack.append(c)
elif c in '[({':
if stack:
if ((c == '[' and stack[-1] == ']') or
(c == '{' and stack[-1] == '}') or
(c == '(' and stack[-1] == ')')):
stack.pop()
else:
# Opening bracket for which we didn't had a closing one.
return True
return False
def get_jedi_script_from_document(document, locals, globals):
import jedi # We keep this import in-line, to improve start-up time.
# Importing Jedi is 'slow'.
try:
return jedi.Interpreter(
document.text,
column=document.cursor_position_col,
line=document.cursor_position_row + 1,
path='input-text',
namespaces=[locals, globals])
except ValueError:
# Invalid cursor position.
# ValueError('`column` parameter is not in a valid range.')
return None
except AttributeError:
# Workaround for #65: https://github.com/jonathanslenders/python-prompt-toolkit/issues/65
# See also: https://github.com/davidhalter/jedi/issues/508
return None
except IndexError:
# Workaround Jedi issue #514: for https://github.com/davidhalter/jedi/issues/514
return None
except KeyError:
# Workaroud for a crash when the input is "u'", the start of a unicode string.
return None
except Exception:
# Workaround for: https://github.com/jonathanslenders/ptpython/issues/91
return None
_multiline_string_delims = re.compile('''[']{3}|["]{3}''')
def document_is_multiline_python(document):
"""
Determine whether this is a multiline Python document.
"""
def ends_in_multiline_string():
"""
``True`` if we're inside a multiline string at the end of the text.
"""
delims = _multiline_string_delims.findall(document.text)
opening = None
for delim in delims:
if opening is None:
opening = delim
elif delim == opening:
opening = None
return bool(opening)
if '\n' in document.text or ends_in_multiline_string():
return True
def line_ends_with_colon():
return document.current_line.rstrip()[-1:] == ':'
# If we just typed a colon, or still have open brackets, always insert a real newline.
if line_ends_with_colon() or \
(document.is_cursor_at_the_end and
has_unclosed_brackets(document.text_before_cursor)) or \
document.text.startswith('@'):
return True
# If the character before the cursor is a backslash (line continuation
# char), insert a new line.
elif document.text_before_cursor[-1:] == '\\':
return True
return False
def if_mousedown(handler):
"""
Decorator for mouse handlers.
Only handle event when the user pressed mouse down.
(When applied to a token list. Scroll events will bubble up and are handled
by the Window.)
"""
def handle_if_mouse_down(cli, mouse_event):
if mouse_event.event_type == MouseEventTypes.MOUSE_DOWN:
return handler(cli, mouse_event)
else:
return NotImplemented
return handle_if_mouse_down | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.254/Olde/rp 5.38.10 PM/rp_ptpython/utils.py | 0.516839 | 0.157234 | utils.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.application import Application
from prompt_toolkit.buffer import Buffer, AcceptAction
from prompt_toolkit.buffer_mapping import BufferMapping
from prompt_toolkit.document import Document
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import Condition, HasFocus, InFocusStack
from prompt_toolkit.key_binding.defaults import load_key_bindings
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.containers import HSplit, VSplit, Window, FloatContainer, Float, ConditionalContainer, Container, ScrollOffsets
from prompt_toolkit.layout.controls import BufferControl, FillControl
from prompt_toolkit.layout.dimension import LayoutDimension as D
from prompt_toolkit.layout.lexers import PygmentsLexer
from prompt_toolkit.layout.margins import Margin, ScrollbarMargin
from prompt_toolkit.layout.processors import Processor, Transformation, HighlightSearchProcessor, HighlightSelectionProcessor
from prompt_toolkit.layout.screen import Char
from prompt_toolkit.layout.toolbars import ArgToolbar, SearchToolbar
from prompt_toolkit.layout.toolbars import TokenListToolbar
from prompt_toolkit.layout.utils import token_list_to_text
from pygments.lexers import RstLexer
from pygments.token import Token
from .utils import if_mousedown
from rp.rp_ptpython.layout import get_inputmode_tokens
from functools import partial
import six
if six.PY2:
from pygments.lexers import PythonLexer
else:
from pygments.lexers import Python3Lexer as PythonLexer
HISTORY_BUFFER = 'HISTORY_BUFFER'
HELP_BUFFER = 'HELP_BUFFER'
HISTORY_COUNT = 2000
__all__ = (
'create_history_application',
)
HELP_TEXT = """
This interface is meant to select multiple lines from the
history and execute them together.
Typical usage
-------------
1. Move the ``cursor up`` in the history pane, until the
cursor is on the first desired line.
2. Hold down the ``space bar``, or press it multiple
times. Each time it will select one line and move to
the next one. Each selected line will appear on the
right side.
3. When all the required lines are displayed on the right
side, press ``Enter``. This will go back to the Python
REPL and show these lines as the current input. They
can still be edited from there.
Key bindings
------------
Many Emacs and Vi navigation key bindings should work.
Press ``F4`` to switch between Emacs and Vi mode.
Additional bindings:
- ``Space``: Select or delect a line.
- ``Tab``: Move the focus between the history and input
pane. (Alternative: ``Ctrl-W``)
- ``Ctrl-C``: Cancel. Ignore the result and go back to
the REPL. (Alternatives: ``q`` and ``Control-G``.)
- ``Enter``: Accept the result and go back to the REPL.
- ``F1``: Show/hide help. Press ``Enter`` to quit this
help message.
Further, remember that searching works like in Emacs
(using ``Ctrl-R``) or Vi (using ``/``).
"""
class BORDER:
" Box drawing characters. "
HORIZONTAL = '\u2501'
VERTICAL = '\u2503'
TOP_LEFT = '\u250f'
TOP_RIGHT = '\u2513'
BOTTOM_LEFT = '\u2517'
BOTTOM_RIGHT = '\u251b'
LIGHT_VERTICAL = '\u2502'
def create_popup_window(title, body):
"""
Return the layout for a pop-up window. It consists of a title bar showing
the `title` text, and a body layout. The window is surrounded by borders.
"""
assert isinstance(title, six.text_type)
assert isinstance(body, Container)
return HSplit([
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_LEFT, token=Token.Window.Border)),
TokenListToolbar(
get_tokens=lambda cli: [(Token.Window.Title, ' %s ' % title)],
align_center=True,
default_char=Char(BORDER.HORIZONTAL, Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_RIGHT, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
body,
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_LEFT, token=Token.Window.Border)),
Window(height=D.exact(1),
content=FillControl(BORDER.HORIZONTAL, token=Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_RIGHT, token=Token.Window.Border)),
]),
])
def create_layout(python_input, history_mapping):
"""
Create and return a `Container` instance for the history
application.
"""
processors = [
HighlightSearchProcessor(preview_search=True),
HighlightSelectionProcessor()]
help_window = create_popup_window(
title='History Help',
body=Window(
content=BufferControl(
buffer_name=HELP_BUFFER,
default_char=Char(token=Token),
lexer=PygmentsLexer(RstLexer),
input_processors=processors),
right_margins=[ScrollbarMargin()],
scroll_offsets=ScrollOffsets(top=2, bottom=2)))
return HSplit([
# Top title bar.
TokenListToolbar(
get_tokens=_get_top_toolbar_tokens,
align_center=True,
default_char=Char(' ', Token.Toolbar.Status)),
FloatContainer(
content=VSplit([
# Left side: history.
Window(
content=BufferControl(
buffer_name=HISTORY_BUFFER,
lexer=PygmentsLexer(PythonLexer),
input_processors=processors),
wrap_lines=False,
left_margins=[HistoryMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
# Separator.
Window(width=D.exact(1),
content=FillControl(BORDER.LIGHT_VERTICAL, token=Token.Separator)),
# Right side: result.
Window(
content=BufferControl(
buffer_name=DEFAULT_BUFFER,
input_processors=processors + [GrayExistingText(history_mapping)],
lexer=PygmentsLexer(PythonLexer)),
wrap_lines=False,
left_margins=[ResultMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
]),
floats=[
# Help text as a float.
Float(width=60, top=3, bottom=2,
content=ConditionalContainer(
# (We use InFocusStack, because it's possible to search
# through the help text as well, and at that point the search
# buffer has the focus.)
content=help_window, filter=InFocusStack(HELP_BUFFER))),
]
),
# Bottom toolbars.
ArgToolbar(),
SearchToolbar(),
TokenListToolbar(
get_tokens=partial(_get_bottom_toolbar_tokens, python_input=python_input),
default_char=Char(' ', Token.Toolbar.Status)),
])
def _get_top_toolbar_tokens(cli):
return [(Token.Toolbar.Status.Title, 'History browser - Insert from history')]
def _get_bottom_toolbar_tokens(cli, python_input):
@if_mousedown
def f1(cli, mouse_event):
_toggle_help(cli)
@if_mousedown
def tab(cli, mouse_event):
_select_other_window(cli)
return [
(Token.Toolbar.Status, ' ')
] + get_inputmode_tokens(cli, python_input) + [
(Token.Toolbar.Status, ' '),
(Token.Toolbar.Status.Key, '[Space]'),
(Token.Toolbar.Status, ' Toggle '),
(Token.Toolbar.Status.Key, '[Tab]', tab),
(Token.Toolbar.Status, ' Focus ', tab),
(Token.Toolbar.Status.Key, '[Enter]'),
(Token.Toolbar.Status, ' Accept '),
(Token.Toolbar.Status.Key, '[F1]', f1),
(Token.Toolbar.Status, ' Help ', f1),
]
class HistoryMargin(Margin):
"""
Margin for the history buffer.
This displays a green bar for the selected entries.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[HISTORY_BUFFER].document
lines_starting_new_entries = self.history_mapping.lines_starting_new_entries
selected_lines = self.history_mapping.selected_lines
current_lineno = document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
# Show stars at the start of each entry.
# (Visualises multiline entries.)
if line_number in lines_starting_new_entries:
char = '*'
else:
char = ' '
if line_number in selected_lines:
t = Token.History.Line.Selected
else:
t = Token.History.Line
if line_number == current_lineno:
t = t.Current
result.append((t, char))
result.append((Token, '\n'))
return result
class ResultMargin(Margin):
"""
The margin to be shown in the result pane.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[DEFAULT_BUFFER].document
current_lineno = document.cursor_position_row
offset = self.history_mapping.result_line_offset #original_document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
if (line_number is None or line_number < offset or
line_number >= offset + len(self.history_mapping.selected_lines)):
t = Token
elif line_number == current_lineno:
t = Token.History.Line.Selected.Current
else:
t = Token.History.Line.Selected
result.append((t, ' '))
result.append((Token, '\n'))
return result
def invalidation_hash(self, cli, document):
return document.cursor_position_row
class GrayExistingText(Processor):
"""
Turn the existing input, before and after the inserted code gray.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
self._lines_before = len(history_mapping.original_document.text_before_cursor.splitlines())
def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
if (lineno < self._lines_before or
lineno >= self._lines_before + len(self.history_mapping.selected_lines)):
text = token_list_to_text(tokens)
return Transformation(tokens=[(Token.History.ExistingInput, text)])
else:
return Transformation(tokens=tokens)
class HistoryMapping(object):
"""
Keep a list of all the lines from the history and the selected lines.
"""
def __init__(self, python_history, original_document):
self.python_history = python_history
self.original_document = original_document
self.lines_starting_new_entries = set()
self.selected_lines = set()
# Process history.
history_lines = []
for entry_nr, entry in list(enumerate(python_history))[-HISTORY_COUNT:]:
self.lines_starting_new_entries.add(len(history_lines))
for line in entry.splitlines():
history_lines.append(line)
if len(python_history) > HISTORY_COUNT:
history_lines[0] = '# *** History has been truncated to %s lines ***' % HISTORY_COUNT
self.history_lines = history_lines
self.concatenated_history = '\n'.join(history_lines)
# Line offset.
if self.original_document.text_before_cursor:
self.result_line_offset = self.original_document.cursor_position_row + 1
else:
self.result_line_offset = 0
def get_new_document(self, cursor_pos=None):
"""
Create a `Document` instance that contains the resulting text.
"""
lines = []
# Original text, before cursor.
if self.original_document.text_before_cursor:
lines.append(self.original_document.text_before_cursor)
# Selected entries from the history.
for line_no in sorted(self.selected_lines):
lines.append(self.history_lines[line_no])
# Original text, after cursor.
if self.original_document.text_after_cursor:
lines.append(self.original_document.text_after_cursor)
# Create `Document` with cursor at the right position.
text = '\n'.join(lines)
if cursor_pos is not None and cursor_pos > len(text):
cursor_pos = len(text)
return Document(text, cursor_pos)
def update_default_buffer(self, cli):
b = cli.buffers[DEFAULT_BUFFER]
b.set_document(
self.get_new_document(b.cursor_position), bypass_readonly=True)
def _toggle_help(cli):
" Display/hide help. "
if cli.current_buffer_name == HELP_BUFFER:
cli.pop_focus()
else:
cli.push_focus(HELP_BUFFER)
def _select_other_window(cli):
" Toggle focus between left/right window. "
if cli.current_buffer_name == HISTORY_BUFFER:
cli.focus(DEFAULT_BUFFER)
elif cli.current_buffer_name == DEFAULT_BUFFER:
cli.focus(HISTORY_BUFFER)
def create_key_bindings(python_input, history_mapping):
"""
Key bindings.
"""
registry = load_key_bindings(
enable_search=True,
enable_extra_page_navigation=True)
handle = registry.add_binding
@handle(' ', filter=HasFocus(HISTORY_BUFFER))
def _(event):
"""
Space: select/deselect line from history pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row
if line_no in history_mapping.selected_lines:
# Remove line.
history_mapping.selected_lines.remove(line_no)
history_mapping.update_default_buffer(event.cli)
else:
# Add line.
history_mapping.selected_lines.add(line_no)
history_mapping.update_default_buffer(event.cli)
# Update cursor position
default_buffer = event.cli.buffers[DEFAULT_BUFFER]
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
# Also move the cursor to the next line. (This way they can hold
# space to select a region.)
b.cursor_position = b.document.translate_row_col_to_index(line_no + 1, 0)
@handle(' ', filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.Delete, filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.ControlH, filter=HasFocus(DEFAULT_BUFFER))
def _(event):
"""
Space: remove line from default pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row - history_mapping.result_line_offset
if line_no >= 0:
try:
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass # When `selected_lines` is an empty set.
else:
history_mapping.selected_lines.remove(history_lineno)
history_mapping.update_default_buffer(event.cli)
help_focussed = HasFocus(HELP_BUFFER)
main_buffer_focussed = HasFocus(HISTORY_BUFFER) | HasFocus(DEFAULT_BUFFER)
@handle(Keys.Tab, filter=main_buffer_focussed)
@handle(Keys.ControlX, filter=main_buffer_focussed, eager=True)
# Eager: ignore the Emacs [Ctrl-X Ctrl-X] binding.
@handle(Keys.ControlW, filter=main_buffer_focussed)
def _(event):
" Select other window. "
_select_other_window(event.cli)
@handle(Keys.F4)
def _(event):
" Switch between Emacs/Vi mode. "
python_input.vi_mode = not python_input.vi_mode
@handle(Keys.F1)
def _(event):
" Display/hide help. "
_toggle_help(event.cli)
@handle(Keys.ControlJ, filter=help_focussed)
@handle(Keys.ControlC, filter=help_focussed)
@handle(Keys.ControlG, filter=help_focussed)
@handle(Keys.Escape, filter=help_focussed)
def _(event):
" Leave help. "
event.cli.pop_focus()
@handle('q', filter=main_buffer_focussed)
@handle(Keys.F3, filter=main_buffer_focussed)
@handle(Keys.ControlC, filter=main_buffer_focussed)
@handle(Keys.ControlG, filter=main_buffer_focussed)
def _(event):
" Cancel and go back. "
event.cli.set_return_value(None)
enable_system_bindings = Condition(lambda cli: python_input.enable_system_bindings)
@handle(Keys.ControlZ, filter=enable_system_bindings)
def _(event):
" Suspend to background. "
event.cli.suspend_to_background()
return registry
def create_history_application(python_input, original_document):
"""
Create an `Application` for the history screen.
This has to be run as a sub application of `python_input`.
When this application runs and returns, it retuns the selected lines.
"""
history_mapping = HistoryMapping(python_input.history, original_document)
def default_buffer_pos_changed(_):
""" When the cursor changes in the default buffer. Synchronize with
history buffer. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == DEFAULT_BUFFER:
try:
line_no = default_buffer.document.cursor_position_row - \
history_mapping.result_line_offset
if line_no < 0: # When the cursor is above the inserted region.
raise IndexError
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass
else:
history_buffer.cursor_position = \
history_buffer.document.translate_row_col_to_index(history_lineno, 0)
def history_buffer_pos_changed(_):
""" When the cursor changes in the history buffer. Synchronize. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == HISTORY_BUFFER:
line_no = history_buffer.document.cursor_position_row
if line_no in history_mapping.selected_lines:
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
history_buffer = Buffer(
initial_document=Document(history_mapping.concatenated_history),
on_cursor_position_changed=history_buffer_pos_changed,
accept_action=AcceptAction(
lambda cli, buffer: cli.set_return_value(default_buffer.document)),
read_only=True)
default_buffer = Buffer(
initial_document=history_mapping.get_new_document(),
on_cursor_position_changed=default_buffer_pos_changed,
read_only=True)
help_buffer = Buffer(
initial_document=Document(HELP_TEXT, 0),
accept_action=AcceptAction.IGNORE,
read_only=True
)
buffer_mapping = BufferMapping({
HISTORY_BUFFER: history_buffer,
DEFAULT_BUFFER: default_buffer,
HELP_BUFFER: help_buffer,
}, initial=HISTORY_BUFFER)
application = Application(
layout=create_layout(python_input, history_mapping),
use_alternate_screen=True,
buffers=buffer_mapping,
style=python_input._current_style,
mouse_support=Condition(lambda cli: python_input.enable_mouse_support),
key_bindings_registry=create_key_bindings(python_input, history_mapping)
)
return application | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.673/Olde/rp 11.48.10 PM/rp_ptpython/history_browser.py | 0.754101 | 0.161982 | history_browser.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.mouse_events import MouseEventTypes
import re
__all__ = (
'has_unclosed_brackets',
'get_jedi_script_from_document',
'document_is_multiline_python',
)
def has_unclosed_brackets(text):
"""
Starting at the end of the string. If we find an opening bracket
for which we didn't had a closing one yet, return True.
"""
stack = []
# Ignore braces inside strings
text = re.sub(r'''('[^']*'|"[^"]*")''', '', text) # XXX: handle escaped quotes.!
for c in reversed(text):
if c in '])}':
stack.append(c)
elif c in '[({':
if stack:
if ((c == '[' and stack[-1] == ']') or
(c == '{' and stack[-1] == '}') or
(c == '(' and stack[-1] == ')')):
stack.pop()
else:
# Opening bracket for which we didn't had a closing one.
return True
return False
def get_jedi_script_from_document(document, locals, globals):
import jedi # We keep this import in-line, to improve start-up time.
# Importing Jedi is 'slow'.
try:
return jedi.Interpreter(
document.text,
column=document.cursor_position_col,
line=document.cursor_position_row + 1,
path='input-text',
namespaces=[locals, globals])
except ValueError:
# Invalid cursor position.
# ValueError('`column` parameter is not in a valid range.')
return None
except AttributeError:
# Workaround for #65: https://github.com/jonathanslenders/python-prompt-toolkit/issues/65
# See also: https://github.com/davidhalter/jedi/issues/508
return None
except IndexError:
# Workaround Jedi issue #514: for https://github.com/davidhalter/jedi/issues/514
return None
except KeyError:
# Workaroud for a crash when the input is "u'", the start of a unicode string.
return None
except Exception:
# Workaround for: https://github.com/jonathanslenders/ptpython/issues/91
return None
_multiline_string_delims = re.compile('''[']{3}|["]{3}''')
def document_is_multiline_python(document):
"""
Determine whether this is a multiline Python document.
"""
def ends_in_multiline_string():
"""
``True`` if we're inside a multiline string at the end of the text.
"""
delims = _multiline_string_delims.findall(document.text)
opening = None
for delim in delims:
if opening is None:
opening = delim
elif delim == opening:
opening = None
return bool(opening)
if '\n' in document.text or ends_in_multiline_string():
return True
def line_ends_with_colon():
return document.current_line.rstrip()[-1:] == ':'
# If we just typed a colon, or still have open brackets, always insert a real newline.
if line_ends_with_colon() or \
(document.is_cursor_at_the_end and
has_unclosed_brackets(document.text_before_cursor)) or \
document.text.startswith('@'):
return True
# If the character before the cursor is a backslash (line continuation
# char), insert a new line.
elif document.text_before_cursor[-1:] == '\\':
return True
return False
def if_mousedown(handler):
"""
Decorator for mouse handlers.
Only handle event when the user pressed mouse down.
(When applied to a token list. Scroll events will bubble up and are handled
by the Window.)
"""
def handle_if_mouse_down(cli, mouse_event):
if mouse_event.event_type == MouseEventTypes.MOUSE_DOWN:
return handler(cli, mouse_event)
else:
return NotImplemented
return handle_if_mouse_down | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.673/Olde/rp 11.48.10 PM/rp_ptpython/utils.py | 0.516839 | 0.157234 | utils.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.application import Application
from prompt_toolkit.buffer import Buffer, AcceptAction
from prompt_toolkit.buffer_mapping import BufferMapping
from prompt_toolkit.document import Document
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import Condition, HasFocus, InFocusStack
from prompt_toolkit.key_binding.defaults import load_key_bindings
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.containers import HSplit, VSplit, Window, FloatContainer, Float, ConditionalContainer, Container, ScrollOffsets
from prompt_toolkit.layout.controls import BufferControl, FillControl
from prompt_toolkit.layout.dimension import LayoutDimension as D
from prompt_toolkit.layout.lexers import PygmentsLexer
from prompt_toolkit.layout.margins import Margin, ScrollbarMargin
from prompt_toolkit.layout.processors import Processor, Transformation, HighlightSearchProcessor, HighlightSelectionProcessor
from prompt_toolkit.layout.screen import Char
from prompt_toolkit.layout.toolbars import ArgToolbar, SearchToolbar
from prompt_toolkit.layout.toolbars import TokenListToolbar
from prompt_toolkit.layout.utils import token_list_to_text
from pygments.lexers import RstLexer
from pygments.token import Token
from .utils import if_mousedown
from rp.rp_ptpython.layout import get_inputmode_tokens
from functools import partial
import six
if six.PY2:
from pygments.lexers import PythonLexer
else:
from pygments.lexers import Python3Lexer as PythonLexer
HISTORY_BUFFER = 'HISTORY_BUFFER'
HELP_BUFFER = 'HELP_BUFFER'
HISTORY_COUNT = 2000
__all__ = (
'create_history_application',
)
HELP_TEXT = """
This interface is meant to select multiple lines from the
history and execute them together.
Typical usage
-------------
1. Move the ``cursor up`` in the history pane, until the
cursor is on the first desired line.
2. Hold down the ``space bar``, or press it multiple
times. Each time it will select one line and move to
the next one. Each selected line will appear on the
right side.
3. When all the required lines are displayed on the right
side, press ``Enter``. This will go back to the Python
REPL and show these lines as the current input. They
can still be edited from there.
Key bindings
------------
Many Emacs and Vi navigation key bindings should work.
Press ``F4`` to switch between Emacs and Vi mode.
Additional bindings:
- ``Space``: Select or delect a line.
- ``Tab``: Move the focus between the history and input
pane. (Alternative: ``Ctrl-W``)
- ``Ctrl-C``: Cancel. Ignore the result and go back to
the REPL. (Alternatives: ``q`` and ``Control-G``.)
- ``Enter``: Accept the result and go back to the REPL.
- ``F1``: Show/hide help. Press ``Enter`` to quit this
help message.
Further, remember that searching works like in Emacs
(using ``Ctrl-R``) or Vi (using ``/``).
"""
class BORDER:
" Box drawing characters. "
HORIZONTAL = '\u2501'
VERTICAL = '\u2503'
TOP_LEFT = '\u250f'
TOP_RIGHT = '\u2513'
BOTTOM_LEFT = '\u2517'
BOTTOM_RIGHT = '\u251b'
LIGHT_VERTICAL = '\u2502'
def create_popup_window(title, body):
"""
Return the layout for a pop-up window. It consists of a title bar showing
the `title` text, and a body layout. The window is surrounded by borders.
"""
assert isinstance(title, six.text_type)
assert isinstance(body, Container)
return HSplit([
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_LEFT, token=Token.Window.Border)),
TokenListToolbar(
get_tokens=lambda cli: [(Token.Window.Title, ' %s ' % title)],
align_center=True,
default_char=Char(BORDER.HORIZONTAL, Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_RIGHT, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
body,
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_LEFT, token=Token.Window.Border)),
Window(height=D.exact(1),
content=FillControl(BORDER.HORIZONTAL, token=Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_RIGHT, token=Token.Window.Border)),
]),
])
def create_layout(python_input, history_mapping):
"""
Create and return a `Container` instance for the history
application.
"""
processors = [
HighlightSearchProcessor(preview_search=True),
HighlightSelectionProcessor()]
help_window = create_popup_window(
title='History Help',
body=Window(
content=BufferControl(
buffer_name=HELP_BUFFER,
default_char=Char(token=Token),
lexer=PygmentsLexer(RstLexer),
input_processors=processors),
right_margins=[ScrollbarMargin()],
scroll_offsets=ScrollOffsets(top=2, bottom=2)))
return HSplit([
# Top title bar.
TokenListToolbar(
get_tokens=_get_top_toolbar_tokens,
align_center=True,
default_char=Char(' ', Token.Toolbar.Status)),
FloatContainer(
content=VSplit([
# Left side: history.
Window(
content=BufferControl(
buffer_name=HISTORY_BUFFER,
lexer=PygmentsLexer(PythonLexer),
input_processors=processors),
wrap_lines=False,
left_margins=[HistoryMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
# Separator.
Window(width=D.exact(1),
content=FillControl(BORDER.LIGHT_VERTICAL, token=Token.Separator)),
# Right side: result.
Window(
content=BufferControl(
buffer_name=DEFAULT_BUFFER,
input_processors=processors + [GrayExistingText(history_mapping)],
lexer=PygmentsLexer(PythonLexer)),
wrap_lines=False,
left_margins=[ResultMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
]),
floats=[
# Help text as a float.
Float(width=60, top=3, bottom=2,
content=ConditionalContainer(
# (We use InFocusStack, because it's possible to search
# through the help text as well, and at that point the search
# buffer has the focus.)
content=help_window, filter=InFocusStack(HELP_BUFFER))),
]
),
# Bottom toolbars.
ArgToolbar(),
SearchToolbar(),
TokenListToolbar(
get_tokens=partial(_get_bottom_toolbar_tokens, python_input=python_input),
default_char=Char(' ', Token.Toolbar.Status)),
])
def _get_top_toolbar_tokens(cli):
return [(Token.Toolbar.Status.Title, 'History browser - Insert from history')]
def _get_bottom_toolbar_tokens(cli, python_input):
@if_mousedown
def f1(cli, mouse_event):
_toggle_help(cli)
@if_mousedown
def tab(cli, mouse_event):
_select_other_window(cli)
return [
(Token.Toolbar.Status, ' ')
] + get_inputmode_tokens(cli, python_input) + [
(Token.Toolbar.Status, ' '),
(Token.Toolbar.Status.Key, '[Space]'),
(Token.Toolbar.Status, ' Toggle '),
(Token.Toolbar.Status.Key, '[Tab]', tab),
(Token.Toolbar.Status, ' Focus ', tab),
(Token.Toolbar.Status.Key, '[Enter]'),
(Token.Toolbar.Status, ' Accept '),
(Token.Toolbar.Status.Key, '[F1]', f1),
(Token.Toolbar.Status, ' Help ', f1),
]
class HistoryMargin(Margin):
"""
Margin for the history buffer.
This displays a green bar for the selected entries.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[HISTORY_BUFFER].document
lines_starting_new_entries = self.history_mapping.lines_starting_new_entries
selected_lines = self.history_mapping.selected_lines
current_lineno = document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
# Show stars at the start of each entry.
# (Visualises multiline entries.)
if line_number in lines_starting_new_entries:
char = '*'
else:
char = ' '
if line_number in selected_lines:
t = Token.History.Line.Selected
else:
t = Token.History.Line
if line_number == current_lineno:
t = t.Current
result.append((t, char))
result.append((Token, '\n'))
return result
class ResultMargin(Margin):
"""
The margin to be shown in the result pane.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[DEFAULT_BUFFER].document
current_lineno = document.cursor_position_row
offset = self.history_mapping.result_line_offset #original_document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
if (line_number is None or line_number < offset or
line_number >= offset + len(self.history_mapping.selected_lines)):
t = Token
elif line_number == current_lineno:
t = Token.History.Line.Selected.Current
else:
t = Token.History.Line.Selected
result.append((t, ' '))
result.append((Token, '\n'))
return result
def invalidation_hash(self, cli, document):
return document.cursor_position_row
class GrayExistingText(Processor):
"""
Turn the existing input, before and after the inserted code gray.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
self._lines_before = len(history_mapping.original_document.text_before_cursor.splitlines())
def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
if (lineno < self._lines_before or
lineno >= self._lines_before + len(self.history_mapping.selected_lines)):
text = token_list_to_text(tokens)
return Transformation(tokens=[(Token.History.ExistingInput, text)])
else:
return Transformation(tokens=tokens)
class HistoryMapping(object):
"""
Keep a list of all the lines from the history and the selected lines.
"""
def __init__(self, python_history, original_document):
self.python_history = python_history
self.original_document = original_document
self.lines_starting_new_entries = set()
self.selected_lines = set()
# Process history.
history_lines = []
for entry_nr, entry in list(enumerate(python_history))[-HISTORY_COUNT:]:
self.lines_starting_new_entries.add(len(history_lines))
for line in entry.splitlines():
history_lines.append(line)
if len(python_history) > HISTORY_COUNT:
history_lines[0] = '# *** History has been truncated to %s lines ***' % HISTORY_COUNT
self.history_lines = history_lines
self.concatenated_history = '\n'.join(history_lines)
# Line offset.
if self.original_document.text_before_cursor:
self.result_line_offset = self.original_document.cursor_position_row + 1
else:
self.result_line_offset = 0
def get_new_document(self, cursor_pos=None):
"""
Create a `Document` instance that contains the resulting text.
"""
lines = []
# Original text, before cursor.
if self.original_document.text_before_cursor:
lines.append(self.original_document.text_before_cursor)
# Selected entries from the history.
for line_no in sorted(self.selected_lines):
lines.append(self.history_lines[line_no])
# Original text, after cursor.
if self.original_document.text_after_cursor:
lines.append(self.original_document.text_after_cursor)
# Create `Document` with cursor at the right position.
text = '\n'.join(lines)
if cursor_pos is not None and cursor_pos > len(text):
cursor_pos = len(text)
return Document(text, cursor_pos)
def update_default_buffer(self, cli):
b = cli.buffers[DEFAULT_BUFFER]
b.set_document(
self.get_new_document(b.cursor_position), bypass_readonly=True)
def _toggle_help(cli):
" Display/hide help. "
if cli.current_buffer_name == HELP_BUFFER:
cli.pop_focus()
else:
cli.push_focus(HELP_BUFFER)
def _select_other_window(cli):
" Toggle focus between left/right window. "
if cli.current_buffer_name == HISTORY_BUFFER:
cli.focus(DEFAULT_BUFFER)
elif cli.current_buffer_name == DEFAULT_BUFFER:
cli.focus(HISTORY_BUFFER)
def create_key_bindings(python_input, history_mapping):
"""
Key bindings.
"""
registry = load_key_bindings(
enable_search=True,
enable_extra_page_navigation=True)
handle = registry.add_binding
@handle(' ', filter=HasFocus(HISTORY_BUFFER))
def _(event):
"""
Space: select/deselect line from history pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row
if line_no in history_mapping.selected_lines:
# Remove line.
history_mapping.selected_lines.remove(line_no)
history_mapping.update_default_buffer(event.cli)
else:
# Add line.
history_mapping.selected_lines.add(line_no)
history_mapping.update_default_buffer(event.cli)
# Update cursor position
default_buffer = event.cli.buffers[DEFAULT_BUFFER]
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
# Also move the cursor to the next line. (This way they can hold
# space to select a region.)
b.cursor_position = b.document.translate_row_col_to_index(line_no + 1, 0)
@handle(' ', filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.Delete, filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.ControlH, filter=HasFocus(DEFAULT_BUFFER))
def _(event):
"""
Space: remove line from default pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row - history_mapping.result_line_offset
if line_no >= 0:
try:
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass # When `selected_lines` is an empty set.
else:
history_mapping.selected_lines.remove(history_lineno)
history_mapping.update_default_buffer(event.cli)
help_focussed = HasFocus(HELP_BUFFER)
main_buffer_focussed = HasFocus(HISTORY_BUFFER) | HasFocus(DEFAULT_BUFFER)
@handle(Keys.Tab, filter=main_buffer_focussed)
@handle(Keys.ControlX, filter=main_buffer_focussed, eager=True)
# Eager: ignore the Emacs [Ctrl-X Ctrl-X] binding.
@handle(Keys.ControlW, filter=main_buffer_focussed)
def _(event):
" Select other window. "
_select_other_window(event.cli)
@handle(Keys.F4)
def _(event):
" Switch between Emacs/Vi mode. "
python_input.vi_mode = not python_input.vi_mode
@handle(Keys.F1)
def _(event):
" Display/hide help. "
_toggle_help(event.cli)
@handle(Keys.ControlJ, filter=help_focussed)
@handle(Keys.ControlC, filter=help_focussed)
@handle(Keys.ControlG, filter=help_focussed)
@handle(Keys.Escape, filter=help_focussed)
def _(event):
" Leave help. "
event.cli.pop_focus()
@handle('q', filter=main_buffer_focussed)
@handle(Keys.F3, filter=main_buffer_focussed)
@handle(Keys.ControlC, filter=main_buffer_focussed)
@handle(Keys.ControlG, filter=main_buffer_focussed)
def _(event):
" Cancel and go back. "
event.cli.set_return_value(None)
enable_system_bindings = Condition(lambda cli: python_input.enable_system_bindings)
@handle(Keys.ControlZ, filter=enable_system_bindings)
def _(event):
" Suspend to background. "
event.cli.suspend_to_background()
return registry
def create_history_application(python_input, original_document):
"""
Create an `Application` for the history screen.
This has to be run as a sub application of `python_input`.
When this application runs and returns, it retuns the selected lines.
"""
history_mapping = HistoryMapping(python_input.history, original_document)
def default_buffer_pos_changed(_):
""" When the cursor changes in the default buffer. Synchronize with
history buffer. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == DEFAULT_BUFFER:
try:
line_no = default_buffer.document.cursor_position_row - \
history_mapping.result_line_offset
if line_no < 0: # When the cursor is above the inserted region.
raise IndexError
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass
else:
history_buffer.cursor_position = \
history_buffer.document.translate_row_col_to_index(history_lineno, 0)
def history_buffer_pos_changed(_):
""" When the cursor changes in the history buffer. Synchronize. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == HISTORY_BUFFER:
line_no = history_buffer.document.cursor_position_row
if line_no in history_mapping.selected_lines:
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
history_buffer = Buffer(
initial_document=Document(history_mapping.concatenated_history),
on_cursor_position_changed=history_buffer_pos_changed,
accept_action=AcceptAction(
lambda cli, buffer: cli.set_return_value(default_buffer.document)),
read_only=True)
default_buffer = Buffer(
initial_document=history_mapping.get_new_document(),
on_cursor_position_changed=default_buffer_pos_changed,
read_only=True)
help_buffer = Buffer(
initial_document=Document(HELP_TEXT, 0),
accept_action=AcceptAction.IGNORE,
read_only=True
)
buffer_mapping = BufferMapping({
HISTORY_BUFFER: history_buffer,
DEFAULT_BUFFER: default_buffer,
HELP_BUFFER: help_buffer,
}, initial=HISTORY_BUFFER)
application = Application(
layout=create_layout(python_input, history_mapping),
use_alternate_screen=True,
buffers=buffer_mapping,
style=python_input._current_style,
mouse_support=Condition(lambda cli: python_input.enable_mouse_support),
key_bindings_registry=create_key_bindings(python_input, history_mapping)
)
return application | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.673/Olde/rp 5.45.01 PM/rp_ptpython/history_browser.py | 0.754101 | 0.161982 | history_browser.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.mouse_events import MouseEventTypes
import re
__all__ = (
'has_unclosed_brackets',
'get_jedi_script_from_document',
'document_is_multiline_python',
)
def has_unclosed_brackets(text):
"""
Starting at the end of the string. If we find an opening bracket
for which we didn't had a closing one yet, return True.
"""
stack = []
# Ignore braces inside strings
text = re.sub(r'''('[^']*'|"[^"]*")''', '', text) # XXX: handle escaped quotes.!
for c in reversed(text):
if c in '])}':
stack.append(c)
elif c in '[({':
if stack:
if ((c == '[' and stack[-1] == ']') or
(c == '{' and stack[-1] == '}') or
(c == '(' and stack[-1] == ')')):
stack.pop()
else:
# Opening bracket for which we didn't had a closing one.
return True
return False
def get_jedi_script_from_document(document, locals, globals):
import jedi # We keep this import in-line, to improve start-up time.
# Importing Jedi is 'slow'.
try:
return jedi.Interpreter(
document.text,
column=document.cursor_position_col,
line=document.cursor_position_row + 1,
path='input-text',
namespaces=[locals, globals])
except ValueError:
# Invalid cursor position.
# ValueError('`column` parameter is not in a valid range.')
return None
except AttributeError:
# Workaround for #65: https://github.com/jonathanslenders/python-prompt-toolkit/issues/65
# See also: https://github.com/davidhalter/jedi/issues/508
return None
except IndexError:
# Workaround Jedi issue #514: for https://github.com/davidhalter/jedi/issues/514
return None
except KeyError:
# Workaroud for a crash when the input is "u'", the start of a unicode string.
return None
except Exception:
# Workaround for: https://github.com/jonathanslenders/ptpython/issues/91
return None
_multiline_string_delims = re.compile('''[']{3}|["]{3}''')
def document_is_multiline_python(document):
"""
Determine whether this is a multiline Python document.
"""
def ends_in_multiline_string():
"""
``True`` if we're inside a multiline string at the end of the text.
"""
delims = _multiline_string_delims.findall(document.text)
opening = None
for delim in delims:
if opening is None:
opening = delim
elif delim == opening:
opening = None
return bool(opening)
if '\n' in document.text or ends_in_multiline_string():
return True
def line_ends_with_colon():
return document.current_line.rstrip()[-1:] == ':'
# If we just typed a colon, or still have open brackets, always insert a real newline.
if line_ends_with_colon() or \
(document.is_cursor_at_the_end and
has_unclosed_brackets(document.text_before_cursor)) or \
document.text.startswith('@'):
return True
# If the character before the cursor is a backslash (line continuation
# char), insert a new line.
elif document.text_before_cursor[-1:] == '\\':
return True
return False
def if_mousedown(handler):
"""
Decorator for mouse handlers.
Only handle event when the user pressed mouse down.
(When applied to a token list. Scroll events will bubble up and are handled
by the Window.)
"""
def handle_if_mouse_down(cli, mouse_event):
if mouse_event.event_type == MouseEventTypes.MOUSE_DOWN:
return handler(cli, mouse_event)
else:
return NotImplemented
return handle_if_mouse_down | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.673/Olde/rp 5.45.01 PM/rp_ptpython/utils.py | 0.516839 | 0.157234 | utils.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.application import Application
from prompt_toolkit.buffer import Buffer, AcceptAction
from prompt_toolkit.buffer_mapping import BufferMapping
from prompt_toolkit.document import Document
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import Condition, HasFocus, InFocusStack
from prompt_toolkit.key_binding.defaults import load_key_bindings
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.containers import HSplit, VSplit, Window, FloatContainer, Float, ConditionalContainer, Container, ScrollOffsets
from prompt_toolkit.layout.controls import BufferControl, FillControl
from prompt_toolkit.layout.dimension import LayoutDimension as D
from prompt_toolkit.layout.lexers import PygmentsLexer
from prompt_toolkit.layout.margins import Margin, ScrollbarMargin
from prompt_toolkit.layout.processors import Processor, Transformation, HighlightSearchProcessor, HighlightSelectionProcessor
from prompt_toolkit.layout.screen import Char
from prompt_toolkit.layout.toolbars import ArgToolbar, SearchToolbar
from prompt_toolkit.layout.toolbars import TokenListToolbar
from prompt_toolkit.layout.utils import token_list_to_text
from pygments.lexers import RstLexer
from pygments.token import Token
from .utils import if_mousedown
from rp.rp_ptpython.layout import get_inputmode_tokens
from functools import partial
import six
if six.PY2:
from pygments.lexers import PythonLexer
else:
from pygments.lexers import Python3Lexer as PythonLexer
HISTORY_BUFFER = 'HISTORY_BUFFER'
HELP_BUFFER = 'HELP_BUFFER'
HISTORY_COUNT = 2000
__all__ = (
'create_history_application',
)
HELP_TEXT = """
This interface is meant to select multiple lines from the
history and execute them together.
Typical usage
-------------
1. Move the ``cursor up`` in the history pane, until the
cursor is on the first desired line.
2. Hold down the ``space bar``, or press it multiple
times. Each time it will select one line and move to
the next one. Each selected line will appear on the
right side.
3. When all the required lines are displayed on the right
side, press ``Enter``. This will go back to the Python
REPL and show these lines as the current input. They
can still be edited from there.
Key bindings
------------
Many Emacs and Vi navigation key bindings should work.
Press ``F4`` to switch between Emacs and Vi mode.
Additional bindings:
- ``Space``: Select or delect a line.
- ``Tab``: Move the focus between the history and input
pane. (Alternative: ``Ctrl-W``)
- ``Ctrl-C``: Cancel. Ignore the result and go back to
the REPL. (Alternatives: ``q`` and ``Control-G``.)
- ``Enter``: Accept the result and go back to the REPL.
- ``F1``: Show/hide help. Press ``Enter`` to quit this
help message.
Further, remember that searching works like in Emacs
(using ``Ctrl-R``) or Vi (using ``/``).
"""
class BORDER:
" Box drawing characters. "
HORIZONTAL = '\u2501'
VERTICAL = '\u2503'
TOP_LEFT = '\u250f'
TOP_RIGHT = '\u2513'
BOTTOM_LEFT = '\u2517'
BOTTOM_RIGHT = '\u251b'
LIGHT_VERTICAL = '\u2502'
def create_popup_window(title, body):
"""
Return the layout for a pop-up window. It consists of a title bar showing
the `title` text, and a body layout. The window is surrounded by borders.
"""
assert isinstance(title, six.text_type)
assert isinstance(body, Container)
return HSplit([
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_LEFT, token=Token.Window.Border)),
TokenListToolbar(
get_tokens=lambda cli: [(Token.Window.Title, ' %s ' % title)],
align_center=True,
default_char=Char(BORDER.HORIZONTAL, Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_RIGHT, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
body,
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_LEFT, token=Token.Window.Border)),
Window(height=D.exact(1),
content=FillControl(BORDER.HORIZONTAL, token=Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_RIGHT, token=Token.Window.Border)),
]),
])
def create_layout(python_input, history_mapping):
"""
Create and return a `Container` instance for the history
application.
"""
processors = [
HighlightSearchProcessor(preview_search=True),
HighlightSelectionProcessor()]
help_window = create_popup_window(
title='History Help',
body=Window(
content=BufferControl(
buffer_name=HELP_BUFFER,
default_char=Char(token=Token),
lexer=PygmentsLexer(RstLexer),
input_processors=processors),
right_margins=[ScrollbarMargin()],
scroll_offsets=ScrollOffsets(top=2, bottom=2)))
return HSplit([
# Top title bar.
TokenListToolbar(
get_tokens=_get_top_toolbar_tokens,
align_center=True,
default_char=Char(' ', Token.Toolbar.Status)),
FloatContainer(
content=VSplit([
# Left side: history.
Window(
content=BufferControl(
buffer_name=HISTORY_BUFFER,
lexer=PygmentsLexer(PythonLexer),
input_processors=processors),
wrap_lines=False,
left_margins=[HistoryMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
# Separator.
Window(width=D.exact(1),
content=FillControl(BORDER.LIGHT_VERTICAL, token=Token.Separator)),
# Right side: result.
Window(
content=BufferControl(
buffer_name=DEFAULT_BUFFER,
input_processors=processors + [GrayExistingText(history_mapping)],
lexer=PygmentsLexer(PythonLexer)),
wrap_lines=False,
left_margins=[ResultMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
]),
floats=[
# Help text as a float.
Float(width=60, top=3, bottom=2,
content=ConditionalContainer(
# (We use InFocusStack, because it's possible to search
# through the help text as well, and at that point the search
# buffer has the focus.)
content=help_window, filter=InFocusStack(HELP_BUFFER))),
]
),
# Bottom toolbars.
ArgToolbar(),
SearchToolbar(),
TokenListToolbar(
get_tokens=partial(_get_bottom_toolbar_tokens, python_input=python_input),
default_char=Char(' ', Token.Toolbar.Status)),
])
def _get_top_toolbar_tokens(cli):
return [(Token.Toolbar.Status.Title, 'History browser - Insert from history')]
def _get_bottom_toolbar_tokens(cli, python_input):
@if_mousedown
def f1(cli, mouse_event):
_toggle_help(cli)
@if_mousedown
def tab(cli, mouse_event):
_select_other_window(cli)
return [
(Token.Toolbar.Status, ' ')
] + get_inputmode_tokens(cli, python_input) + [
(Token.Toolbar.Status, ' '),
(Token.Toolbar.Status.Key, '[Space]'),
(Token.Toolbar.Status, ' Toggle '),
(Token.Toolbar.Status.Key, '[Tab]', tab),
(Token.Toolbar.Status, ' Focus ', tab),
(Token.Toolbar.Status.Key, '[Enter]'),
(Token.Toolbar.Status, ' Accept '),
(Token.Toolbar.Status.Key, '[F1]', f1),
(Token.Toolbar.Status, ' Help ', f1),
]
class HistoryMargin(Margin):
"""
Margin for the history buffer.
This displays a green bar for the selected entries.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[HISTORY_BUFFER].document
lines_starting_new_entries = self.history_mapping.lines_starting_new_entries
selected_lines = self.history_mapping.selected_lines
current_lineno = document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
# Show stars at the start of each entry.
# (Visualises multiline entries.)
if line_number in lines_starting_new_entries:
char = '*'
else:
char = ' '
if line_number in selected_lines:
t = Token.History.Line.Selected
else:
t = Token.History.Line
if line_number == current_lineno:
t = t.Current
result.append((t, char))
result.append((Token, '\n'))
return result
class ResultMargin(Margin):
"""
The margin to be shown in the result pane.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[DEFAULT_BUFFER].document
current_lineno = document.cursor_position_row
offset = self.history_mapping.result_line_offset #original_document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
if (line_number is None or line_number < offset or
line_number >= offset + len(self.history_mapping.selected_lines)):
t = Token
elif line_number == current_lineno:
t = Token.History.Line.Selected.Current
else:
t = Token.History.Line.Selected
result.append((t, ' '))
result.append((Token, '\n'))
return result
def invalidation_hash(self, cli, document):
return document.cursor_position_row
class GrayExistingText(Processor):
"""
Turn the existing input, before and after the inserted code gray.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
self._lines_before = len(history_mapping.original_document.text_before_cursor.splitlines())
def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
if (lineno < self._lines_before or
lineno >= self._lines_before + len(self.history_mapping.selected_lines)):
text = token_list_to_text(tokens)
return Transformation(tokens=[(Token.History.ExistingInput, text)])
else:
return Transformation(tokens=tokens)
class HistoryMapping(object):
"""
Keep a list of all the lines from the history and the selected lines.
"""
def __init__(self, python_history, original_document):
self.python_history = python_history
self.original_document = original_document
self.lines_starting_new_entries = set()
self.selected_lines = set()
# Process history.
history_lines = []
for entry_nr, entry in list(enumerate(python_history))[-HISTORY_COUNT:]:
self.lines_starting_new_entries.add(len(history_lines))
for line in entry.splitlines():
history_lines.append(line)
if len(python_history) > HISTORY_COUNT:
history_lines[0] = '# *** History has been truncated to %s lines ***' % HISTORY_COUNT
self.history_lines = history_lines
self.concatenated_history = '\n'.join(history_lines)
# Line offset.
if self.original_document.text_before_cursor:
self.result_line_offset = self.original_document.cursor_position_row + 1
else:
self.result_line_offset = 0
def get_new_document(self, cursor_pos=None):
"""
Create a `Document` instance that contains the resulting text.
"""
lines = []
# Original text, before cursor.
if self.original_document.text_before_cursor:
lines.append(self.original_document.text_before_cursor)
# Selected entries from the history.
for line_no in sorted(self.selected_lines):
lines.append(self.history_lines[line_no])
# Original text, after cursor.
if self.original_document.text_after_cursor:
lines.append(self.original_document.text_after_cursor)
# Create `Document` with cursor at the right position.
text = '\n'.join(lines)
if cursor_pos is not None and cursor_pos > len(text):
cursor_pos = len(text)
return Document(text, cursor_pos)
def update_default_buffer(self, cli):
b = cli.buffers[DEFAULT_BUFFER]
b.set_document(
self.get_new_document(b.cursor_position), bypass_readonly=True)
def _toggle_help(cli):
" Display/hide help. "
if cli.current_buffer_name == HELP_BUFFER:
cli.pop_focus()
else:
cli.push_focus(HELP_BUFFER)
def _select_other_window(cli):
" Toggle focus between left/right window. "
if cli.current_buffer_name == HISTORY_BUFFER:
cli.focus(DEFAULT_BUFFER)
elif cli.current_buffer_name == DEFAULT_BUFFER:
cli.focus(HISTORY_BUFFER)
def create_key_bindings(python_input, history_mapping):
"""
Key bindings.
"""
registry = load_key_bindings(
enable_search=True,
enable_extra_page_navigation=True)
handle = registry.add_binding
@handle(' ', filter=HasFocus(HISTORY_BUFFER))
def _(event):
"""
Space: select/deselect line from history pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row
if line_no in history_mapping.selected_lines:
# Remove line.
history_mapping.selected_lines.remove(line_no)
history_mapping.update_default_buffer(event.cli)
else:
# Add line.
history_mapping.selected_lines.add(line_no)
history_mapping.update_default_buffer(event.cli)
# Update cursor position
default_buffer = event.cli.buffers[DEFAULT_BUFFER]
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
# Also move the cursor to the next line. (This way they can hold
# space to select a region.)
b.cursor_position = b.document.translate_row_col_to_index(line_no + 1, 0)
@handle(' ', filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.Delete, filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.ControlH, filter=HasFocus(DEFAULT_BUFFER))
def _(event):
"""
Space: remove line from default pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row - history_mapping.result_line_offset
if line_no >= 0:
try:
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass # When `selected_lines` is an empty set.
else:
history_mapping.selected_lines.remove(history_lineno)
history_mapping.update_default_buffer(event.cli)
help_focussed = HasFocus(HELP_BUFFER)
main_buffer_focussed = HasFocus(HISTORY_BUFFER) | HasFocus(DEFAULT_BUFFER)
@handle(Keys.Tab, filter=main_buffer_focussed)
@handle(Keys.ControlX, filter=main_buffer_focussed, eager=True)
# Eager: ignore the Emacs [Ctrl-X Ctrl-X] binding.
@handle(Keys.ControlW, filter=main_buffer_focussed)
def _(event):
" Select other window. "
_select_other_window(event.cli)
@handle(Keys.F4)
def _(event):
" Switch between Emacs/Vi mode. "
python_input.vi_mode = not python_input.vi_mode
@handle(Keys.F1)
def _(event):
" Display/hide help. "
_toggle_help(event.cli)
@handle(Keys.ControlJ, filter=help_focussed)
@handle(Keys.ControlC, filter=help_focussed)
@handle(Keys.ControlG, filter=help_focussed)
@handle(Keys.Escape, filter=help_focussed)
def _(event):
" Leave help. "
event.cli.pop_focus()
@handle('q', filter=main_buffer_focussed)
@handle(Keys.F3, filter=main_buffer_focussed)
@handle(Keys.ControlC, filter=main_buffer_focussed)
@handle(Keys.ControlG, filter=main_buffer_focussed)
def _(event):
" Cancel and go back. "
event.cli.set_return_value(None)
enable_system_bindings = Condition(lambda cli: python_input.enable_system_bindings)
@handle(Keys.ControlZ, filter=enable_system_bindings)
def _(event):
" Suspend to background. "
event.cli.suspend_to_background()
return registry
def create_history_application(python_input, original_document):
"""
Create an `Application` for the history screen.
This has to be run as a sub application of `python_input`.
When this application runs and returns, it retuns the selected lines.
"""
history_mapping = HistoryMapping(python_input.history, original_document)
def default_buffer_pos_changed(_):
""" When the cursor changes in the default buffer. Synchronize with
history buffer. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == DEFAULT_BUFFER:
try:
line_no = default_buffer.document.cursor_position_row - \
history_mapping.result_line_offset
if line_no < 0: # When the cursor is above the inserted region.
raise IndexError
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass
else:
history_buffer.cursor_position = \
history_buffer.document.translate_row_col_to_index(history_lineno, 0)
def history_buffer_pos_changed(_):
""" When the cursor changes in the history buffer. Synchronize. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == HISTORY_BUFFER:
line_no = history_buffer.document.cursor_position_row
if line_no in history_mapping.selected_lines:
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
history_buffer = Buffer(
initial_document=Document(history_mapping.concatenated_history),
on_cursor_position_changed=history_buffer_pos_changed,
accept_action=AcceptAction(
lambda cli, buffer: cli.set_return_value(default_buffer.document)),
read_only=True)
default_buffer = Buffer(
initial_document=history_mapping.get_new_document(),
on_cursor_position_changed=default_buffer_pos_changed,
read_only=True)
help_buffer = Buffer(
initial_document=Document(HELP_TEXT, 0),
accept_action=AcceptAction.IGNORE,
read_only=True
)
buffer_mapping = BufferMapping({
HISTORY_BUFFER: history_buffer,
DEFAULT_BUFFER: default_buffer,
HELP_BUFFER: help_buffer,
}, initial=HISTORY_BUFFER)
application = Application(
layout=create_layout(python_input, history_mapping),
use_alternate_screen=True,
buffers=buffer_mapping,
style=python_input._current_style,
mouse_support=Condition(lambda cli: python_input.enable_mouse_support),
key_bindings_registry=create_key_bindings(python_input, history_mapping)
)
return application | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.673/Olde/rp 7.24.17 AM/rp_ptpython/history_browser.py | 0.754101 | 0.161982 | history_browser.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.mouse_events import MouseEventTypes
import re
__all__ = (
'has_unclosed_brackets',
'get_jedi_script_from_document',
'document_is_multiline_python',
)
def has_unclosed_brackets(text):
"""
Starting at the end of the string. If we find an opening bracket
for which we didn't had a closing one yet, return True.
"""
stack = []
# Ignore braces inside strings
text = re.sub(r'''('[^']*'|"[^"]*")''', '', text) # XXX: handle escaped quotes.!
for c in reversed(text):
if c in '])}':
stack.append(c)
elif c in '[({':
if stack:
if ((c == '[' and stack[-1] == ']') or
(c == '{' and stack[-1] == '}') or
(c == '(' and stack[-1] == ')')):
stack.pop()
else:
# Opening bracket for which we didn't had a closing one.
return True
return False
def get_jedi_script_from_document(document, locals, globals):
import jedi # We keep this import in-line, to improve start-up time.
# Importing Jedi is 'slow'.
try:
return jedi.Interpreter(
document.text,
column=document.cursor_position_col,
line=document.cursor_position_row + 1,
path='input-text',
namespaces=[locals, globals])
except ValueError:
# Invalid cursor position.
# ValueError('`column` parameter is not in a valid range.')
return None
except AttributeError:
# Workaround for #65: https://github.com/jonathanslenders/python-prompt-toolkit/issues/65
# See also: https://github.com/davidhalter/jedi/issues/508
return None
except IndexError:
# Workaround Jedi issue #514: for https://github.com/davidhalter/jedi/issues/514
return None
except KeyError:
# Workaroud for a crash when the input is "u'", the start of a unicode string.
return None
except Exception:
# Workaround for: https://github.com/jonathanslenders/ptpython/issues/91
return None
_multiline_string_delims = re.compile('''[']{3}|["]{3}''')
def document_is_multiline_python(document):
"""
Determine whether this is a multiline Python document.
"""
def ends_in_multiline_string():
"""
``True`` if we're inside a multiline string at the end of the text.
"""
delims = _multiline_string_delims.findall(document.text)
opening = None
for delim in delims:
if opening is None:
opening = delim
elif delim == opening:
opening = None
return bool(opening)
if '\n' in document.text or ends_in_multiline_string():
return True
def line_ends_with_colon():
return document.current_line.rstrip()[-1:] == ':'
# If we just typed a colon, or still have open brackets, always insert a real newline.
if line_ends_with_colon() or \
(document.is_cursor_at_the_end and
has_unclosed_brackets(document.text_before_cursor)) or \
document.text.startswith('@'):
return True
# If the character before the cursor is a backslash (line continuation
# char), insert a new line.
elif document.text_before_cursor[-1:] == '\\':
return True
return False
def if_mousedown(handler):
"""
Decorator for mouse handlers.
Only handle event when the user pressed mouse down.
(When applied to a token list. Scroll events will bubble up and are handled
by the Window.)
"""
def handle_if_mouse_down(cli, mouse_event):
if mouse_event.event_type == MouseEventTypes.MOUSE_DOWN:
return handler(cli, mouse_event)
else:
return NotImplemented
return handle_if_mouse_down | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.673/Olde/rp 7.24.17 AM/rp_ptpython/utils.py | 0.516839 | 0.157234 | utils.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.application import Application
from prompt_toolkit.buffer import Buffer, AcceptAction
from prompt_toolkit.buffer_mapping import BufferMapping
from prompt_toolkit.document import Document
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import Condition, HasFocus, InFocusStack
from prompt_toolkit.key_binding.defaults import load_key_bindings
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.containers import HSplit, VSplit, Window, FloatContainer, Float, ConditionalContainer, Container, ScrollOffsets
from prompt_toolkit.layout.controls import BufferControl, FillControl
from prompt_toolkit.layout.dimension import LayoutDimension as D
from prompt_toolkit.layout.lexers import PygmentsLexer
from prompt_toolkit.layout.margins import Margin, ScrollbarMargin
from prompt_toolkit.layout.processors import Processor, Transformation, HighlightSearchProcessor, HighlightSelectionProcessor
from prompt_toolkit.layout.screen import Char
from prompt_toolkit.layout.toolbars import ArgToolbar, SearchToolbar
from prompt_toolkit.layout.toolbars import TokenListToolbar
from prompt_toolkit.layout.utils import token_list_to_text
from pygments.lexers import RstLexer
from pygments.token import Token
from .utils import if_mousedown
from rp.rp_ptpython.layout import get_inputmode_tokens
from functools import partial
import six
if six.PY2:
from pygments.lexers import PythonLexer
else:
from pygments.lexers import Python3Lexer as PythonLexer
HISTORY_BUFFER = 'HISTORY_BUFFER'
HELP_BUFFER = 'HELP_BUFFER'
HISTORY_COUNT = 2000
__all__ = (
'create_history_application',
)
HELP_TEXT = """
This interface is meant to select multiple lines from the
history and execute them together.
Typical usage
-------------
1. Move the ``cursor up`` in the history pane, until the
cursor is on the first desired line.
2. Hold down the ``space bar``, or press it multiple
times. Each time it will select one line and move to
the next one. Each selected line will appear on the
right side.
3. When all the required lines are displayed on the right
side, press ``Enter``. This will go back to the Python
REPL and show these lines as the current input. They
can still be edited from there.
Key bindings
------------
Many Emacs and Vi navigation key bindings should work.
Press ``F4`` to switch between Emacs and Vi mode.
Additional bindings:
- ``Space``: Select or delect a line.
- ``Tab``: Move the focus between the history and input
pane. (Alternative: ``Ctrl-W``)
- ``Ctrl-C``: Cancel. Ignore the result and go back to
the REPL. (Alternatives: ``q`` and ``Control-G``.)
- ``Enter``: Accept the result and go back to the REPL.
- ``F1``: Show/hide help. Press ``Enter`` to quit this
help message.
Further, remember that searching works like in Emacs
(using ``Ctrl-R``) or Vi (using ``/``).
"""
class BORDER:
" Box drawing characters. "
HORIZONTAL = '\u2501'
VERTICAL = '\u2503'
TOP_LEFT = '\u250f'
TOP_RIGHT = '\u2513'
BOTTOM_LEFT = '\u2517'
BOTTOM_RIGHT = '\u251b'
LIGHT_VERTICAL = '\u2502'
def create_popup_window(title, body):
"""
Return the layout for a pop-up window. It consists of a title bar showing
the `title` text, and a body layout. The window is surrounded by borders.
"""
assert isinstance(title, six.text_type)
assert isinstance(body, Container)
return HSplit([
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_LEFT, token=Token.Window.Border)),
TokenListToolbar(
get_tokens=lambda cli: [(Token.Window.Title, ' %s ' % title)],
align_center=True,
default_char=Char(BORDER.HORIZONTAL, Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_RIGHT, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
body,
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_LEFT, token=Token.Window.Border)),
Window(height=D.exact(1),
content=FillControl(BORDER.HORIZONTAL, token=Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_RIGHT, token=Token.Window.Border)),
]),
])
def create_layout(python_input, history_mapping):
"""
Create and return a `Container` instance for the history
application.
"""
processors = [
HighlightSearchProcessor(preview_search=True),
HighlightSelectionProcessor()]
help_window = create_popup_window(
title='History Help',
body=Window(
content=BufferControl(
buffer_name=HELP_BUFFER,
default_char=Char(token=Token),
lexer=PygmentsLexer(RstLexer),
input_processors=processors),
right_margins=[ScrollbarMargin()],
scroll_offsets=ScrollOffsets(top=2, bottom=2)))
return HSplit([
# Top title bar.
TokenListToolbar(
get_tokens=_get_top_toolbar_tokens,
align_center=True,
default_char=Char(' ', Token.Toolbar.Status)),
FloatContainer(
content=VSplit([
# Left side: history.
Window(
content=BufferControl(
buffer_name=HISTORY_BUFFER,
lexer=PygmentsLexer(PythonLexer),
input_processors=processors),
wrap_lines=False,
left_margins=[HistoryMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
# Separator.
Window(width=D.exact(1),
content=FillControl(BORDER.LIGHT_VERTICAL, token=Token.Separator)),
# Right side: result.
Window(
content=BufferControl(
buffer_name=DEFAULT_BUFFER,
input_processors=processors + [GrayExistingText(history_mapping)],
lexer=PygmentsLexer(PythonLexer)),
wrap_lines=False,
left_margins=[ResultMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
]),
floats=[
# Help text as a float.
Float(width=60, top=3, bottom=2,
content=ConditionalContainer(
# (We use InFocusStack, because it's possible to search
# through the help text as well, and at that point the search
# buffer has the focus.)
content=help_window, filter=InFocusStack(HELP_BUFFER))),
]
),
# Bottom toolbars.
ArgToolbar(),
SearchToolbar(),
TokenListToolbar(
get_tokens=partial(_get_bottom_toolbar_tokens, python_input=python_input),
default_char=Char(' ', Token.Toolbar.Status)),
])
def _get_top_toolbar_tokens(cli):
return [(Token.Toolbar.Status.Title, 'History browser - Insert from history')]
def _get_bottom_toolbar_tokens(cli, python_input):
@if_mousedown
def f1(cli, mouse_event):
_toggle_help(cli)
@if_mousedown
def tab(cli, mouse_event):
_select_other_window(cli)
return [
(Token.Toolbar.Status, ' ')
] + get_inputmode_tokens(cli, python_input) + [
(Token.Toolbar.Status, ' '),
(Token.Toolbar.Status.Key, '[Space]'),
(Token.Toolbar.Status, ' Toggle '),
(Token.Toolbar.Status.Key, '[Tab]', tab),
(Token.Toolbar.Status, ' Focus ', tab),
(Token.Toolbar.Status.Key, '[Enter]'),
(Token.Toolbar.Status, ' Accept '),
(Token.Toolbar.Status.Key, '[F1]', f1),
(Token.Toolbar.Status, ' Help ', f1),
]
class HistoryMargin(Margin):
"""
Margin for the history buffer.
This displays a green bar for the selected entries.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[HISTORY_BUFFER].document
lines_starting_new_entries = self.history_mapping.lines_starting_new_entries
selected_lines = self.history_mapping.selected_lines
current_lineno = document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
# Show stars at the start of each entry.
# (Visualises multiline entries.)
if line_number in lines_starting_new_entries:
char = '*'
else:
char = ' '
if line_number in selected_lines:
t = Token.History.Line.Selected
else:
t = Token.History.Line
if line_number == current_lineno:
t = t.Current
result.append((t, char))
result.append((Token, '\n'))
return result
class ResultMargin(Margin):
"""
The margin to be shown in the result pane.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[DEFAULT_BUFFER].document
current_lineno = document.cursor_position_row
offset = self.history_mapping.result_line_offset #original_document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
if (line_number is None or line_number < offset or
line_number >= offset + len(self.history_mapping.selected_lines)):
t = Token
elif line_number == current_lineno:
t = Token.History.Line.Selected.Current
else:
t = Token.History.Line.Selected
result.append((t, ' '))
result.append((Token, '\n'))
return result
def invalidation_hash(self, cli, document):
return document.cursor_position_row
class GrayExistingText(Processor):
"""
Turn the existing input, before and after the inserted code gray.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
self._lines_before = len(history_mapping.original_document.text_before_cursor.splitlines())
def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
if (lineno < self._lines_before or
lineno >= self._lines_before + len(self.history_mapping.selected_lines)):
text = token_list_to_text(tokens)
return Transformation(tokens=[(Token.History.ExistingInput, text)])
else:
return Transformation(tokens=tokens)
class HistoryMapping(object):
"""
Keep a list of all the lines from the history and the selected lines.
"""
def __init__(self, python_history, original_document):
self.python_history = python_history
self.original_document = original_document
self.lines_starting_new_entries = set()
self.selected_lines = set()
# Process history.
history_lines = []
for entry_nr, entry in list(enumerate(python_history))[-HISTORY_COUNT:]:
self.lines_starting_new_entries.add(len(history_lines))
for line in entry.splitlines():
history_lines.append(line)
if len(python_history) > HISTORY_COUNT:
history_lines[0] = '# *** History has been truncated to %s lines ***' % HISTORY_COUNT
self.history_lines = history_lines
self.concatenated_history = '\n'.join(history_lines)
# Line offset.
if self.original_document.text_before_cursor:
self.result_line_offset = self.original_document.cursor_position_row + 1
else:
self.result_line_offset = 0
def get_new_document(self, cursor_pos=None):
"""
Create a `Document` instance that contains the resulting text.
"""
lines = []
# Original text, before cursor.
if self.original_document.text_before_cursor:
lines.append(self.original_document.text_before_cursor)
# Selected entries from the history.
for line_no in sorted(self.selected_lines):
lines.append(self.history_lines[line_no])
# Original text, after cursor.
if self.original_document.text_after_cursor:
lines.append(self.original_document.text_after_cursor)
# Create `Document` with cursor at the right position.
text = '\n'.join(lines)
if cursor_pos is not None and cursor_pos > len(text):
cursor_pos = len(text)
return Document(text, cursor_pos)
def update_default_buffer(self, cli):
b = cli.buffers[DEFAULT_BUFFER]
b.set_document(
self.get_new_document(b.cursor_position), bypass_readonly=True)
def _toggle_help(cli):
" Display/hide help. "
if cli.current_buffer_name == HELP_BUFFER:
cli.pop_focus()
else:
cli.push_focus(HELP_BUFFER)
def _select_other_window(cli):
" Toggle focus between left/right window. "
if cli.current_buffer_name == HISTORY_BUFFER:
cli.focus(DEFAULT_BUFFER)
elif cli.current_buffer_name == DEFAULT_BUFFER:
cli.focus(HISTORY_BUFFER)
def create_key_bindings(python_input, history_mapping):
"""
Key bindings.
"""
registry = load_key_bindings(
enable_search=True,
enable_extra_page_navigation=True)
handle = registry.add_binding
@handle(' ', filter=HasFocus(HISTORY_BUFFER))
def _(event):
"""
Space: select/deselect line from history pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row
if line_no in history_mapping.selected_lines:
# Remove line.
history_mapping.selected_lines.remove(line_no)
history_mapping.update_default_buffer(event.cli)
else:
# Add line.
history_mapping.selected_lines.add(line_no)
history_mapping.update_default_buffer(event.cli)
# Update cursor position
default_buffer = event.cli.buffers[DEFAULT_BUFFER]
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
# Also move the cursor to the next line. (This way they can hold
# space to select a region.)
b.cursor_position = b.document.translate_row_col_to_index(line_no + 1, 0)
@handle(' ', filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.Delete, filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.ControlH, filter=HasFocus(DEFAULT_BUFFER))
def _(event):
"""
Space: remove line from default pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row - history_mapping.result_line_offset
if line_no >= 0:
try:
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass # When `selected_lines` is an empty set.
else:
history_mapping.selected_lines.remove(history_lineno)
history_mapping.update_default_buffer(event.cli)
help_focussed = HasFocus(HELP_BUFFER)
main_buffer_focussed = HasFocus(HISTORY_BUFFER) | HasFocus(DEFAULT_BUFFER)
@handle(Keys.Tab, filter=main_buffer_focussed)
@handle(Keys.ControlX, filter=main_buffer_focussed, eager=True)
# Eager: ignore the Emacs [Ctrl-X Ctrl-X] binding.
@handle(Keys.ControlW, filter=main_buffer_focussed)
def _(event):
" Select other window. "
_select_other_window(event.cli)
@handle(Keys.F4)
def _(event):
" Switch between Emacs/Vi mode. "
python_input.vi_mode = not python_input.vi_mode
@handle(Keys.F1)
def _(event):
" Display/hide help. "
_toggle_help(event.cli)
@handle(Keys.ControlJ, filter=help_focussed)
@handle(Keys.ControlC, filter=help_focussed)
@handle(Keys.ControlG, filter=help_focussed)
@handle(Keys.Escape, filter=help_focussed)
def _(event):
" Leave help. "
event.cli.pop_focus()
@handle('q', filter=main_buffer_focussed)
@handle(Keys.F3, filter=main_buffer_focussed)
@handle(Keys.ControlC, filter=main_buffer_focussed)
@handle(Keys.ControlG, filter=main_buffer_focussed)
def _(event):
" Cancel and go back. "
event.cli.set_return_value(None)
enable_system_bindings = Condition(lambda cli: python_input.enable_system_bindings)
@handle(Keys.ControlZ, filter=enable_system_bindings)
def _(event):
" Suspend to background. "
event.cli.suspend_to_background()
return registry
def create_history_application(python_input, original_document):
"""
Create an `Application` for the history screen.
This has to be run as a sub application of `python_input`.
When this application runs and returns, it retuns the selected lines.
"""
history_mapping = HistoryMapping(python_input.history, original_document)
def default_buffer_pos_changed(_):
""" When the cursor changes in the default buffer. Synchronize with
history buffer. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == DEFAULT_BUFFER:
try:
line_no = default_buffer.document.cursor_position_row - \
history_mapping.result_line_offset
if line_no < 0: # When the cursor is above the inserted region.
raise IndexError
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass
else:
history_buffer.cursor_position = \
history_buffer.document.translate_row_col_to_index(history_lineno, 0)
def history_buffer_pos_changed(_):
""" When the cursor changes in the history buffer. Synchronize. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == HISTORY_BUFFER:
line_no = history_buffer.document.cursor_position_row
if line_no in history_mapping.selected_lines:
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
history_buffer = Buffer(
initial_document=Document(history_mapping.concatenated_history),
on_cursor_position_changed=history_buffer_pos_changed,
accept_action=AcceptAction(
lambda cli, buffer: cli.set_return_value(default_buffer.document)),
read_only=True)
default_buffer = Buffer(
initial_document=history_mapping.get_new_document(),
on_cursor_position_changed=default_buffer_pos_changed,
read_only=True)
help_buffer = Buffer(
initial_document=Document(HELP_TEXT, 0),
accept_action=AcceptAction.IGNORE,
read_only=True
)
buffer_mapping = BufferMapping({
HISTORY_BUFFER: history_buffer,
DEFAULT_BUFFER: default_buffer,
HELP_BUFFER: help_buffer,
}, initial=HISTORY_BUFFER)
application = Application(
layout=create_layout(python_input, history_mapping),
use_alternate_screen=True,
buffers=buffer_mapping,
style=python_input._current_style,
mouse_support=Condition(lambda cli: python_input.enable_mouse_support),
key_bindings_registry=create_key_bindings(python_input, history_mapping)
)
return application | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.673/Olde/rp 5.38.10 PM/rp_ptpython/history_browser.py | 0.754101 | 0.161982 | history_browser.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.mouse_events import MouseEventTypes
import re
__all__ = (
'has_unclosed_brackets',
'get_jedi_script_from_document',
'document_is_multiline_python',
)
def has_unclosed_brackets(text):
"""
Starting at the end of the string. If we find an opening bracket
for which we didn't had a closing one yet, return True.
"""
stack = []
# Ignore braces inside strings
text = re.sub(r'''('[^']*'|"[^"]*")''', '', text) # XXX: handle escaped quotes.!
for c in reversed(text):
if c in '])}':
stack.append(c)
elif c in '[({':
if stack:
if ((c == '[' and stack[-1] == ']') or
(c == '{' and stack[-1] == '}') or
(c == '(' and stack[-1] == ')')):
stack.pop()
else:
# Opening bracket for which we didn't had a closing one.
return True
return False
def get_jedi_script_from_document(document, locals, globals):
import jedi # We keep this import in-line, to improve start-up time.
# Importing Jedi is 'slow'.
try:
return jedi.Interpreter(
document.text,
column=document.cursor_position_col,
line=document.cursor_position_row + 1,
path='input-text',
namespaces=[locals, globals])
except ValueError:
# Invalid cursor position.
# ValueError('`column` parameter is not in a valid range.')
return None
except AttributeError:
# Workaround for #65: https://github.com/jonathanslenders/python-prompt-toolkit/issues/65
# See also: https://github.com/davidhalter/jedi/issues/508
return None
except IndexError:
# Workaround Jedi issue #514: for https://github.com/davidhalter/jedi/issues/514
return None
except KeyError:
# Workaroud for a crash when the input is "u'", the start of a unicode string.
return None
except Exception:
# Workaround for: https://github.com/jonathanslenders/ptpython/issues/91
return None
_multiline_string_delims = re.compile('''[']{3}|["]{3}''')
def document_is_multiline_python(document):
"""
Determine whether this is a multiline Python document.
"""
def ends_in_multiline_string():
"""
``True`` if we're inside a multiline string at the end of the text.
"""
delims = _multiline_string_delims.findall(document.text)
opening = None
for delim in delims:
if opening is None:
opening = delim
elif delim == opening:
opening = None
return bool(opening)
if '\n' in document.text or ends_in_multiline_string():
return True
def line_ends_with_colon():
return document.current_line.rstrip()[-1:] == ':'
# If we just typed a colon, or still have open brackets, always insert a real newline.
if line_ends_with_colon() or \
(document.is_cursor_at_the_end and
has_unclosed_brackets(document.text_before_cursor)) or \
document.text.startswith('@'):
return True
# If the character before the cursor is a backslash (line continuation
# char), insert a new line.
elif document.text_before_cursor[-1:] == '\\':
return True
return False
def if_mousedown(handler):
"""
Decorator for mouse handlers.
Only handle event when the user pressed mouse down.
(When applied to a token list. Scroll events will bubble up and are handled
by the Window.)
"""
def handle_if_mouse_down(cli, mouse_event):
if mouse_event.event_type == MouseEventTypes.MOUSE_DOWN:
return handler(cli, mouse_event)
else:
return NotImplemented
return handle_if_mouse_down | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.673/Olde/rp 5.38.10 PM/rp_ptpython/utils.py | 0.516839 | 0.157234 | utils.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.application import Application
from prompt_toolkit.buffer import Buffer, AcceptAction
from prompt_toolkit.buffer_mapping import BufferMapping
from prompt_toolkit.document import Document
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import Condition, HasFocus, InFocusStack
from prompt_toolkit.key_binding.defaults import load_key_bindings
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.containers import HSplit, VSplit, Window, FloatContainer, Float, ConditionalContainer, Container, ScrollOffsets
from prompt_toolkit.layout.controls import BufferControl, FillControl
from prompt_toolkit.layout.dimension import LayoutDimension as D
from prompt_toolkit.layout.lexers import PygmentsLexer
from prompt_toolkit.layout.margins import Margin, ScrollbarMargin
from prompt_toolkit.layout.processors import Processor, Transformation, HighlightSearchProcessor, HighlightSelectionProcessor
from prompt_toolkit.layout.screen import Char
from prompt_toolkit.layout.toolbars import ArgToolbar, SearchToolbar
from prompt_toolkit.layout.toolbars import TokenListToolbar
from prompt_toolkit.layout.utils import token_list_to_text
from pygments.lexers import RstLexer
from pygments.token import Token
from .utils import if_mousedown
from rp.rp_ptpython.layout import get_inputmode_tokens
from functools import partial
import six
if six.PY2:
from pygments.lexers import PythonLexer
else:
from pygments.lexers import Python3Lexer as PythonLexer
HISTORY_BUFFER = 'HISTORY_BUFFER'
HELP_BUFFER = 'HELP_BUFFER'
HISTORY_COUNT = 2000
__all__ = (
'create_history_application',
)
HELP_TEXT = """
This interface is meant to select multiple lines from the
history and execute them together.
Typical usage
-------------
1. Move the ``cursor up`` in the history pane, until the
cursor is on the first desired line.
2. Hold down the ``space bar``, or press it multiple
times. Each time it will select one line and move to
the next one. Each selected line will appear on the
right side.
3. When all the required lines are displayed on the right
side, press ``Enter``. This will go back to the Python
REPL and show these lines as the current input. They
can still be edited from there.
Key bindings
------------
Many Emacs and Vi navigation key bindings should work.
Press ``F4`` to switch between Emacs and Vi mode.
Additional bindings:
- ``Space``: Select or delect a line.
- ``Tab``: Move the focus between the history and input
pane. (Alternative: ``Ctrl-W``)
- ``Ctrl-C``: Cancel. Ignore the result and go back to
the REPL. (Alternatives: ``q`` and ``Control-G``.)
- ``Enter``: Accept the result and go back to the REPL.
- ``F1``: Show/hide help. Press ``Enter`` to quit this
help message.
Further, remember that searching works like in Emacs
(using ``Ctrl-R``) or Vi (using ``/``).
"""
class BORDER:
" Box drawing characters. "
HORIZONTAL = '\u2501'
VERTICAL = '\u2503'
TOP_LEFT = '\u250f'
TOP_RIGHT = '\u2513'
BOTTOM_LEFT = '\u2517'
BOTTOM_RIGHT = '\u251b'
LIGHT_VERTICAL = '\u2502'
def create_popup_window(title, body):
"""
Return the layout for a pop-up window. It consists of a title bar showing
the `title` text, and a body layout. The window is surrounded by borders.
"""
assert isinstance(title, six.text_type)
assert isinstance(body, Container)
return HSplit([
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_LEFT, token=Token.Window.Border)),
TokenListToolbar(
get_tokens=lambda cli: [(Token.Window.Title, ' %s ' % title)],
align_center=True,
default_char=Char(BORDER.HORIZONTAL, Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_RIGHT, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
body,
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_LEFT, token=Token.Window.Border)),
Window(height=D.exact(1),
content=FillControl(BORDER.HORIZONTAL, token=Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_RIGHT, token=Token.Window.Border)),
]),
])
def create_layout(python_input, history_mapping):
"""
Create and return a `Container` instance for the history
application.
"""
processors = [
HighlightSearchProcessor(preview_search=True),
HighlightSelectionProcessor()]
help_window = create_popup_window(
title='History Help',
body=Window(
content=BufferControl(
buffer_name=HELP_BUFFER,
default_char=Char(token=Token),
lexer=PygmentsLexer(RstLexer),
input_processors=processors),
right_margins=[ScrollbarMargin()],
scroll_offsets=ScrollOffsets(top=2, bottom=2)))
return HSplit([
# Top title bar.
TokenListToolbar(
get_tokens=_get_top_toolbar_tokens,
align_center=True,
default_char=Char(' ', Token.Toolbar.Status)),
FloatContainer(
content=VSplit([
# Left side: history.
Window(
content=BufferControl(
buffer_name=HISTORY_BUFFER,
lexer=PygmentsLexer(PythonLexer),
input_processors=processors),
wrap_lines=False,
left_margins=[HistoryMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
# Separator.
Window(width=D.exact(1),
content=FillControl(BORDER.LIGHT_VERTICAL, token=Token.Separator)),
# Right side: result.
Window(
content=BufferControl(
buffer_name=DEFAULT_BUFFER,
input_processors=processors + [GrayExistingText(history_mapping)],
lexer=PygmentsLexer(PythonLexer)),
wrap_lines=False,
left_margins=[ResultMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
]),
floats=[
# Help text as a float.
Float(width=60, top=3, bottom=2,
content=ConditionalContainer(
# (We use InFocusStack, because it's possible to search
# through the help text as well, and at that point the search
# buffer has the focus.)
content=help_window, filter=InFocusStack(HELP_BUFFER))),
]
),
# Bottom toolbars.
ArgToolbar(),
SearchToolbar(),
TokenListToolbar(
get_tokens=partial(_get_bottom_toolbar_tokens, python_input=python_input),
default_char=Char(' ', Token.Toolbar.Status)),
])
def _get_top_toolbar_tokens(cli):
return [(Token.Toolbar.Status.Title, 'History browser - Insert from history')]
def _get_bottom_toolbar_tokens(cli, python_input):
@if_mousedown
def f1(cli, mouse_event):
_toggle_help(cli)
@if_mousedown
def tab(cli, mouse_event):
_select_other_window(cli)
return [
(Token.Toolbar.Status, ' ')
] + get_inputmode_tokens(cli, python_input) + [
(Token.Toolbar.Status, ' '),
(Token.Toolbar.Status.Key, '[Space]'),
(Token.Toolbar.Status, ' Toggle '),
(Token.Toolbar.Status.Key, '[Tab]', tab),
(Token.Toolbar.Status, ' Focus ', tab),
(Token.Toolbar.Status.Key, '[Enter]'),
(Token.Toolbar.Status, ' Accept '),
(Token.Toolbar.Status.Key, '[F1]', f1),
(Token.Toolbar.Status, ' Help ', f1),
]
class HistoryMargin(Margin):
"""
Margin for the history buffer.
This displays a green bar for the selected entries.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[HISTORY_BUFFER].document
lines_starting_new_entries = self.history_mapping.lines_starting_new_entries
selected_lines = self.history_mapping.selected_lines
current_lineno = document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
# Show stars at the start of each entry.
# (Visualises multiline entries.)
if line_number in lines_starting_new_entries:
char = '*'
else:
char = ' '
if line_number in selected_lines:
t = Token.History.Line.Selected
else:
t = Token.History.Line
if line_number == current_lineno:
t = t.Current
result.append((t, char))
result.append((Token, '\n'))
return result
class ResultMargin(Margin):
"""
The margin to be shown in the result pane.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[DEFAULT_BUFFER].document
current_lineno = document.cursor_position_row
offset = self.history_mapping.result_line_offset #original_document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
if (line_number is None or line_number < offset or
line_number >= offset + len(self.history_mapping.selected_lines)):
t = Token
elif line_number == current_lineno:
t = Token.History.Line.Selected.Current
else:
t = Token.History.Line.Selected
result.append((t, ' '))
result.append((Token, '\n'))
return result
def invalidation_hash(self, cli, document):
return document.cursor_position_row
class GrayExistingText(Processor):
"""
Turn the existing input, before and after the inserted code gray.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
self._lines_before = len(history_mapping.original_document.text_before_cursor.splitlines())
def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
if (lineno < self._lines_before or
lineno >= self._lines_before + len(self.history_mapping.selected_lines)):
text = token_list_to_text(tokens)
return Transformation(tokens=[(Token.History.ExistingInput, text)])
else:
return Transformation(tokens=tokens)
class HistoryMapping(object):
"""
Keep a list of all the lines from the history and the selected lines.
"""
def __init__(self, python_history, original_document):
self.python_history = python_history
self.original_document = original_document
self.lines_starting_new_entries = set()
self.selected_lines = set()
# Process history.
history_lines = []
for entry_nr, entry in list(enumerate(python_history))[-HISTORY_COUNT:]:
self.lines_starting_new_entries.add(len(history_lines))
for line in entry.splitlines():
history_lines.append(line)
if len(python_history) > HISTORY_COUNT:
history_lines[0] = '# *** History has been truncated to %s lines ***' % HISTORY_COUNT
self.history_lines = history_lines
self.concatenated_history = '\n'.join(history_lines)
# Line offset.
if self.original_document.text_before_cursor:
self.result_line_offset = self.original_document.cursor_position_row + 1
else:
self.result_line_offset = 0
def get_new_document(self, cursor_pos=None):
"""
Create a `Document` instance that contains the resulting text.
"""
lines = []
# Original text, before cursor.
if self.original_document.text_before_cursor:
lines.append(self.original_document.text_before_cursor)
# Selected entries from the history.
for line_no in sorted(self.selected_lines):
lines.append(self.history_lines[line_no])
# Original text, after cursor.
if self.original_document.text_after_cursor:
lines.append(self.original_document.text_after_cursor)
# Create `Document` with cursor at the right position.
text = '\n'.join(lines)
if cursor_pos is not None and cursor_pos > len(text):
cursor_pos = len(text)
return Document(text, cursor_pos)
def update_default_buffer(self, cli):
b = cli.buffers[DEFAULT_BUFFER]
b.set_document(
self.get_new_document(b.cursor_position), bypass_readonly=True)
def _toggle_help(cli):
" Display/hide help. "
if cli.current_buffer_name == HELP_BUFFER:
cli.pop_focus()
else:
cli.push_focus(HELP_BUFFER)
def _select_other_window(cli):
" Toggle focus between left/right window. "
if cli.current_buffer_name == HISTORY_BUFFER:
cli.focus(DEFAULT_BUFFER)
elif cli.current_buffer_name == DEFAULT_BUFFER:
cli.focus(HISTORY_BUFFER)
def create_key_bindings(python_input, history_mapping):
"""
Key bindings.
"""
registry = load_key_bindings(
enable_search=True,
enable_extra_page_navigation=True)
handle = registry.add_binding
@handle(' ', filter=HasFocus(HISTORY_BUFFER))
def _(event):
"""
Space: select/deselect line from history pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row
if line_no in history_mapping.selected_lines:
# Remove line.
history_mapping.selected_lines.remove(line_no)
history_mapping.update_default_buffer(event.cli)
else:
# Add line.
history_mapping.selected_lines.add(line_no)
history_mapping.update_default_buffer(event.cli)
# Update cursor position
default_buffer = event.cli.buffers[DEFAULT_BUFFER]
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
# Also move the cursor to the next line. (This way they can hold
# space to select a region.)
b.cursor_position = b.document.translate_row_col_to_index(line_no + 1, 0)
@handle(' ', filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.Delete, filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.ControlH, filter=HasFocus(DEFAULT_BUFFER))
def _(event):
"""
Space: remove line from default pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row - history_mapping.result_line_offset
if line_no >= 0:
try:
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass # When `selected_lines` is an empty set.
else:
history_mapping.selected_lines.remove(history_lineno)
history_mapping.update_default_buffer(event.cli)
help_focussed = HasFocus(HELP_BUFFER)
main_buffer_focussed = HasFocus(HISTORY_BUFFER) | HasFocus(DEFAULT_BUFFER)
@handle(Keys.Tab, filter=main_buffer_focussed)
@handle(Keys.ControlX, filter=main_buffer_focussed, eager=True)
# Eager: ignore the Emacs [Ctrl-X Ctrl-X] binding.
@handle(Keys.ControlW, filter=main_buffer_focussed)
def _(event):
" Select other window. "
_select_other_window(event.cli)
@handle(Keys.F4)
def _(event):
" Switch between Emacs/Vi mode. "
python_input.vi_mode = not python_input.vi_mode
@handle(Keys.F1)
def _(event):
" Display/hide help. "
_toggle_help(event.cli)
@handle(Keys.ControlJ, filter=help_focussed)
@handle(Keys.ControlC, filter=help_focussed)
@handle(Keys.ControlG, filter=help_focussed)
@handle(Keys.Escape, filter=help_focussed)
def _(event):
" Leave help. "
event.cli.pop_focus()
@handle('q', filter=main_buffer_focussed)
@handle(Keys.F3, filter=main_buffer_focussed)
@handle(Keys.ControlC, filter=main_buffer_focussed)
@handle(Keys.ControlG, filter=main_buffer_focussed)
def _(event):
" Cancel and go back. "
event.cli.set_return_value(None)
enable_system_bindings = Condition(lambda cli: python_input.enable_system_bindings)
@handle(Keys.ControlZ, filter=enable_system_bindings)
def _(event):
" Suspend to background. "
event.cli.suspend_to_background()
return registry
def create_history_application(python_input, original_document):
"""
Create an `Application` for the history screen.
This has to be run as a sub application of `python_input`.
When this application runs and returns, it retuns the selected lines.
"""
history_mapping = HistoryMapping(python_input.history, original_document)
def default_buffer_pos_changed(_):
""" When the cursor changes in the default buffer. Synchronize with
history buffer. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == DEFAULT_BUFFER:
try:
line_no = default_buffer.document.cursor_position_row - \
history_mapping.result_line_offset
if line_no < 0: # When the cursor is above the inserted region.
raise IndexError
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass
else:
history_buffer.cursor_position = \
history_buffer.document.translate_row_col_to_index(history_lineno, 0)
def history_buffer_pos_changed(_):
""" When the cursor changes in the history buffer. Synchronize. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == HISTORY_BUFFER:
line_no = history_buffer.document.cursor_position_row
if line_no in history_mapping.selected_lines:
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
history_buffer = Buffer(
initial_document=Document(history_mapping.concatenated_history),
on_cursor_position_changed=history_buffer_pos_changed,
accept_action=AcceptAction(
lambda cli, buffer: cli.set_return_value(default_buffer.document)),
read_only=True)
default_buffer = Buffer(
initial_document=history_mapping.get_new_document(),
on_cursor_position_changed=default_buffer_pos_changed,
read_only=True)
help_buffer = Buffer(
initial_document=Document(HELP_TEXT, 0),
accept_action=AcceptAction.IGNORE,
read_only=True
)
buffer_mapping = BufferMapping({
HISTORY_BUFFER: history_buffer,
DEFAULT_BUFFER: default_buffer,
HELP_BUFFER: help_buffer,
}, initial=HISTORY_BUFFER)
application = Application(
layout=create_layout(python_input, history_mapping),
use_alternate_screen=True,
buffers=buffer_mapping,
style=python_input._current_style,
mouse_support=Condition(lambda cli: python_input.enable_mouse_support),
key_bindings_registry=create_key_bindings(python_input, history_mapping)
)
return application | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.676/Olde/rp 11.48.10 PM/rp_ptpython/history_browser.py | 0.754101 | 0.161982 | history_browser.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.mouse_events import MouseEventTypes
import re
__all__ = (
'has_unclosed_brackets',
'get_jedi_script_from_document',
'document_is_multiline_python',
)
def has_unclosed_brackets(text):
"""
Starting at the end of the string. If we find an opening bracket
for which we didn't had a closing one yet, return True.
"""
stack = []
# Ignore braces inside strings
text = re.sub(r'''('[^']*'|"[^"]*")''', '', text) # XXX: handle escaped quotes.!
for c in reversed(text):
if c in '])}':
stack.append(c)
elif c in '[({':
if stack:
if ((c == '[' and stack[-1] == ']') or
(c == '{' and stack[-1] == '}') or
(c == '(' and stack[-1] == ')')):
stack.pop()
else:
# Opening bracket for which we didn't had a closing one.
return True
return False
def get_jedi_script_from_document(document, locals, globals):
import jedi # We keep this import in-line, to improve start-up time.
# Importing Jedi is 'slow'.
try:
return jedi.Interpreter(
document.text,
column=document.cursor_position_col,
line=document.cursor_position_row + 1,
path='input-text',
namespaces=[locals, globals])
except ValueError:
# Invalid cursor position.
# ValueError('`column` parameter is not in a valid range.')
return None
except AttributeError:
# Workaround for #65: https://github.com/jonathanslenders/python-prompt-toolkit/issues/65
# See also: https://github.com/davidhalter/jedi/issues/508
return None
except IndexError:
# Workaround Jedi issue #514: for https://github.com/davidhalter/jedi/issues/514
return None
except KeyError:
# Workaroud for a crash when the input is "u'", the start of a unicode string.
return None
except Exception:
# Workaround for: https://github.com/jonathanslenders/ptpython/issues/91
return None
_multiline_string_delims = re.compile('''[']{3}|["]{3}''')
def document_is_multiline_python(document):
"""
Determine whether this is a multiline Python document.
"""
def ends_in_multiline_string():
"""
``True`` if we're inside a multiline string at the end of the text.
"""
delims = _multiline_string_delims.findall(document.text)
opening = None
for delim in delims:
if opening is None:
opening = delim
elif delim == opening:
opening = None
return bool(opening)
if '\n' in document.text or ends_in_multiline_string():
return True
def line_ends_with_colon():
return document.current_line.rstrip()[-1:] == ':'
# If we just typed a colon, or still have open brackets, always insert a real newline.
if line_ends_with_colon() or \
(document.is_cursor_at_the_end and
has_unclosed_brackets(document.text_before_cursor)) or \
document.text.startswith('@'):
return True
# If the character before the cursor is a backslash (line continuation
# char), insert a new line.
elif document.text_before_cursor[-1:] == '\\':
return True
return False
def if_mousedown(handler):
"""
Decorator for mouse handlers.
Only handle event when the user pressed mouse down.
(When applied to a token list. Scroll events will bubble up and are handled
by the Window.)
"""
def handle_if_mouse_down(cli, mouse_event):
if mouse_event.event_type == MouseEventTypes.MOUSE_DOWN:
return handler(cli, mouse_event)
else:
return NotImplemented
return handle_if_mouse_down | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.676/Olde/rp 11.48.10 PM/rp_ptpython/utils.py | 0.516839 | 0.157234 | utils.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.application import Application
from prompt_toolkit.buffer import Buffer, AcceptAction
from prompt_toolkit.buffer_mapping import BufferMapping
from prompt_toolkit.document import Document
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import Condition, HasFocus, InFocusStack
from prompt_toolkit.key_binding.defaults import load_key_bindings
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.containers import HSplit, VSplit, Window, FloatContainer, Float, ConditionalContainer, Container, ScrollOffsets
from prompt_toolkit.layout.controls import BufferControl, FillControl
from prompt_toolkit.layout.dimension import LayoutDimension as D
from prompt_toolkit.layout.lexers import PygmentsLexer
from prompt_toolkit.layout.margins import Margin, ScrollbarMargin
from prompt_toolkit.layout.processors import Processor, Transformation, HighlightSearchProcessor, HighlightSelectionProcessor
from prompt_toolkit.layout.screen import Char
from prompt_toolkit.layout.toolbars import ArgToolbar, SearchToolbar
from prompt_toolkit.layout.toolbars import TokenListToolbar
from prompt_toolkit.layout.utils import token_list_to_text
from pygments.lexers import RstLexer
from pygments.token import Token
from .utils import if_mousedown
from rp.rp_ptpython.layout import get_inputmode_tokens
from functools import partial
import six
if six.PY2:
from pygments.lexers import PythonLexer
else:
from pygments.lexers import Python3Lexer as PythonLexer
HISTORY_BUFFER = 'HISTORY_BUFFER'
HELP_BUFFER = 'HELP_BUFFER'
HISTORY_COUNT = 2000
__all__ = (
'create_history_application',
)
HELP_TEXT = """
This interface is meant to select multiple lines from the
history and execute them together.
Typical usage
-------------
1. Move the ``cursor up`` in the history pane, until the
cursor is on the first desired line.
2. Hold down the ``space bar``, or press it multiple
times. Each time it will select one line and move to
the next one. Each selected line will appear on the
right side.
3. When all the required lines are displayed on the right
side, press ``Enter``. This will go back to the Python
REPL and show these lines as the current input. They
can still be edited from there.
Key bindings
------------
Many Emacs and Vi navigation key bindings should work.
Press ``F4`` to switch between Emacs and Vi mode.
Additional bindings:
- ``Space``: Select or delect a line.
- ``Tab``: Move the focus between the history and input
pane. (Alternative: ``Ctrl-W``)
- ``Ctrl-C``: Cancel. Ignore the result and go back to
the REPL. (Alternatives: ``q`` and ``Control-G``.)
- ``Enter``: Accept the result and go back to the REPL.
- ``F1``: Show/hide help. Press ``Enter`` to quit this
help message.
Further, remember that searching works like in Emacs
(using ``Ctrl-R``) or Vi (using ``/``).
"""
class BORDER:
" Box drawing characters. "
HORIZONTAL = '\u2501'
VERTICAL = '\u2503'
TOP_LEFT = '\u250f'
TOP_RIGHT = '\u2513'
BOTTOM_LEFT = '\u2517'
BOTTOM_RIGHT = '\u251b'
LIGHT_VERTICAL = '\u2502'
def create_popup_window(title, body):
"""
Return the layout for a pop-up window. It consists of a title bar showing
the `title` text, and a body layout. The window is surrounded by borders.
"""
assert isinstance(title, six.text_type)
assert isinstance(body, Container)
return HSplit([
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_LEFT, token=Token.Window.Border)),
TokenListToolbar(
get_tokens=lambda cli: [(Token.Window.Title, ' %s ' % title)],
align_center=True,
default_char=Char(BORDER.HORIZONTAL, Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_RIGHT, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
body,
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_LEFT, token=Token.Window.Border)),
Window(height=D.exact(1),
content=FillControl(BORDER.HORIZONTAL, token=Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_RIGHT, token=Token.Window.Border)),
]),
])
def create_layout(python_input, history_mapping):
"""
Create and return a `Container` instance for the history
application.
"""
processors = [
HighlightSearchProcessor(preview_search=True),
HighlightSelectionProcessor()]
help_window = create_popup_window(
title='History Help',
body=Window(
content=BufferControl(
buffer_name=HELP_BUFFER,
default_char=Char(token=Token),
lexer=PygmentsLexer(RstLexer),
input_processors=processors),
right_margins=[ScrollbarMargin()],
scroll_offsets=ScrollOffsets(top=2, bottom=2)))
return HSplit([
# Top title bar.
TokenListToolbar(
get_tokens=_get_top_toolbar_tokens,
align_center=True,
default_char=Char(' ', Token.Toolbar.Status)),
FloatContainer(
content=VSplit([
# Left side: history.
Window(
content=BufferControl(
buffer_name=HISTORY_BUFFER,
lexer=PygmentsLexer(PythonLexer),
input_processors=processors),
wrap_lines=False,
left_margins=[HistoryMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
# Separator.
Window(width=D.exact(1),
content=FillControl(BORDER.LIGHT_VERTICAL, token=Token.Separator)),
# Right side: result.
Window(
content=BufferControl(
buffer_name=DEFAULT_BUFFER,
input_processors=processors + [GrayExistingText(history_mapping)],
lexer=PygmentsLexer(PythonLexer)),
wrap_lines=False,
left_margins=[ResultMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
]),
floats=[
# Help text as a float.
Float(width=60, top=3, bottom=2,
content=ConditionalContainer(
# (We use InFocusStack, because it's possible to search
# through the help text as well, and at that point the search
# buffer has the focus.)
content=help_window, filter=InFocusStack(HELP_BUFFER))),
]
),
# Bottom toolbars.
ArgToolbar(),
SearchToolbar(),
TokenListToolbar(
get_tokens=partial(_get_bottom_toolbar_tokens, python_input=python_input),
default_char=Char(' ', Token.Toolbar.Status)),
])
def _get_top_toolbar_tokens(cli):
return [(Token.Toolbar.Status.Title, 'History browser - Insert from history')]
def _get_bottom_toolbar_tokens(cli, python_input):
@if_mousedown
def f1(cli, mouse_event):
_toggle_help(cli)
@if_mousedown
def tab(cli, mouse_event):
_select_other_window(cli)
return [
(Token.Toolbar.Status, ' ')
] + get_inputmode_tokens(cli, python_input) + [
(Token.Toolbar.Status, ' '),
(Token.Toolbar.Status.Key, '[Space]'),
(Token.Toolbar.Status, ' Toggle '),
(Token.Toolbar.Status.Key, '[Tab]', tab),
(Token.Toolbar.Status, ' Focus ', tab),
(Token.Toolbar.Status.Key, '[Enter]'),
(Token.Toolbar.Status, ' Accept '),
(Token.Toolbar.Status.Key, '[F1]', f1),
(Token.Toolbar.Status, ' Help ', f1),
]
class HistoryMargin(Margin):
"""
Margin for the history buffer.
This displays a green bar for the selected entries.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[HISTORY_BUFFER].document
lines_starting_new_entries = self.history_mapping.lines_starting_new_entries
selected_lines = self.history_mapping.selected_lines
current_lineno = document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
# Show stars at the start of each entry.
# (Visualises multiline entries.)
if line_number in lines_starting_new_entries:
char = '*'
else:
char = ' '
if line_number in selected_lines:
t = Token.History.Line.Selected
else:
t = Token.History.Line
if line_number == current_lineno:
t = t.Current
result.append((t, char))
result.append((Token, '\n'))
return result
class ResultMargin(Margin):
"""
The margin to be shown in the result pane.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[DEFAULT_BUFFER].document
current_lineno = document.cursor_position_row
offset = self.history_mapping.result_line_offset #original_document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
if (line_number is None or line_number < offset or
line_number >= offset + len(self.history_mapping.selected_lines)):
t = Token
elif line_number == current_lineno:
t = Token.History.Line.Selected.Current
else:
t = Token.History.Line.Selected
result.append((t, ' '))
result.append((Token, '\n'))
return result
def invalidation_hash(self, cli, document):
return document.cursor_position_row
class GrayExistingText(Processor):
"""
Turn the existing input, before and after the inserted code gray.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
self._lines_before = len(history_mapping.original_document.text_before_cursor.splitlines())
def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
if (lineno < self._lines_before or
lineno >= self._lines_before + len(self.history_mapping.selected_lines)):
text = token_list_to_text(tokens)
return Transformation(tokens=[(Token.History.ExistingInput, text)])
else:
return Transformation(tokens=tokens)
class HistoryMapping(object):
"""
Keep a list of all the lines from the history and the selected lines.
"""
def __init__(self, python_history, original_document):
self.python_history = python_history
self.original_document = original_document
self.lines_starting_new_entries = set()
self.selected_lines = set()
# Process history.
history_lines = []
for entry_nr, entry in list(enumerate(python_history))[-HISTORY_COUNT:]:
self.lines_starting_new_entries.add(len(history_lines))
for line in entry.splitlines():
history_lines.append(line)
if len(python_history) > HISTORY_COUNT:
history_lines[0] = '# *** History has been truncated to %s lines ***' % HISTORY_COUNT
self.history_lines = history_lines
self.concatenated_history = '\n'.join(history_lines)
# Line offset.
if self.original_document.text_before_cursor:
self.result_line_offset = self.original_document.cursor_position_row + 1
else:
self.result_line_offset = 0
def get_new_document(self, cursor_pos=None):
"""
Create a `Document` instance that contains the resulting text.
"""
lines = []
# Original text, before cursor.
if self.original_document.text_before_cursor:
lines.append(self.original_document.text_before_cursor)
# Selected entries from the history.
for line_no in sorted(self.selected_lines):
lines.append(self.history_lines[line_no])
# Original text, after cursor.
if self.original_document.text_after_cursor:
lines.append(self.original_document.text_after_cursor)
# Create `Document` with cursor at the right position.
text = '\n'.join(lines)
if cursor_pos is not None and cursor_pos > len(text):
cursor_pos = len(text)
return Document(text, cursor_pos)
def update_default_buffer(self, cli):
b = cli.buffers[DEFAULT_BUFFER]
b.set_document(
self.get_new_document(b.cursor_position), bypass_readonly=True)
def _toggle_help(cli):
" Display/hide help. "
if cli.current_buffer_name == HELP_BUFFER:
cli.pop_focus()
else:
cli.push_focus(HELP_BUFFER)
def _select_other_window(cli):
" Toggle focus between left/right window. "
if cli.current_buffer_name == HISTORY_BUFFER:
cli.focus(DEFAULT_BUFFER)
elif cli.current_buffer_name == DEFAULT_BUFFER:
cli.focus(HISTORY_BUFFER)
def create_key_bindings(python_input, history_mapping):
"""
Key bindings.
"""
registry = load_key_bindings(
enable_search=True,
enable_extra_page_navigation=True)
handle = registry.add_binding
@handle(' ', filter=HasFocus(HISTORY_BUFFER))
def _(event):
"""
Space: select/deselect line from history pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row
if line_no in history_mapping.selected_lines:
# Remove line.
history_mapping.selected_lines.remove(line_no)
history_mapping.update_default_buffer(event.cli)
else:
# Add line.
history_mapping.selected_lines.add(line_no)
history_mapping.update_default_buffer(event.cli)
# Update cursor position
default_buffer = event.cli.buffers[DEFAULT_BUFFER]
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
# Also move the cursor to the next line. (This way they can hold
# space to select a region.)
b.cursor_position = b.document.translate_row_col_to_index(line_no + 1, 0)
@handle(' ', filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.Delete, filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.ControlH, filter=HasFocus(DEFAULT_BUFFER))
def _(event):
"""
Space: remove line from default pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row - history_mapping.result_line_offset
if line_no >= 0:
try:
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass # When `selected_lines` is an empty set.
else:
history_mapping.selected_lines.remove(history_lineno)
history_mapping.update_default_buffer(event.cli)
help_focussed = HasFocus(HELP_BUFFER)
main_buffer_focussed = HasFocus(HISTORY_BUFFER) | HasFocus(DEFAULT_BUFFER)
@handle(Keys.Tab, filter=main_buffer_focussed)
@handle(Keys.ControlX, filter=main_buffer_focussed, eager=True)
# Eager: ignore the Emacs [Ctrl-X Ctrl-X] binding.
@handle(Keys.ControlW, filter=main_buffer_focussed)
def _(event):
" Select other window. "
_select_other_window(event.cli)
@handle(Keys.F4)
def _(event):
" Switch between Emacs/Vi mode. "
python_input.vi_mode = not python_input.vi_mode
@handle(Keys.F1)
def _(event):
" Display/hide help. "
_toggle_help(event.cli)
@handle(Keys.ControlJ, filter=help_focussed)
@handle(Keys.ControlC, filter=help_focussed)
@handle(Keys.ControlG, filter=help_focussed)
@handle(Keys.Escape, filter=help_focussed)
def _(event):
" Leave help. "
event.cli.pop_focus()
@handle('q', filter=main_buffer_focussed)
@handle(Keys.F3, filter=main_buffer_focussed)
@handle(Keys.ControlC, filter=main_buffer_focussed)
@handle(Keys.ControlG, filter=main_buffer_focussed)
def _(event):
" Cancel and go back. "
event.cli.set_return_value(None)
enable_system_bindings = Condition(lambda cli: python_input.enable_system_bindings)
@handle(Keys.ControlZ, filter=enable_system_bindings)
def _(event):
" Suspend to background. "
event.cli.suspend_to_background()
return registry
def create_history_application(python_input, original_document):
"""
Create an `Application` for the history screen.
This has to be run as a sub application of `python_input`.
When this application runs and returns, it retuns the selected lines.
"""
history_mapping = HistoryMapping(python_input.history, original_document)
def default_buffer_pos_changed(_):
""" When the cursor changes in the default buffer. Synchronize with
history buffer. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == DEFAULT_BUFFER:
try:
line_no = default_buffer.document.cursor_position_row - \
history_mapping.result_line_offset
if line_no < 0: # When the cursor is above the inserted region.
raise IndexError
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass
else:
history_buffer.cursor_position = \
history_buffer.document.translate_row_col_to_index(history_lineno, 0)
def history_buffer_pos_changed(_):
""" When the cursor changes in the history buffer. Synchronize. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == HISTORY_BUFFER:
line_no = history_buffer.document.cursor_position_row
if line_no in history_mapping.selected_lines:
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
history_buffer = Buffer(
initial_document=Document(history_mapping.concatenated_history),
on_cursor_position_changed=history_buffer_pos_changed,
accept_action=AcceptAction(
lambda cli, buffer: cli.set_return_value(default_buffer.document)),
read_only=True)
default_buffer = Buffer(
initial_document=history_mapping.get_new_document(),
on_cursor_position_changed=default_buffer_pos_changed,
read_only=True)
help_buffer = Buffer(
initial_document=Document(HELP_TEXT, 0),
accept_action=AcceptAction.IGNORE,
read_only=True
)
buffer_mapping = BufferMapping({
HISTORY_BUFFER: history_buffer,
DEFAULT_BUFFER: default_buffer,
HELP_BUFFER: help_buffer,
}, initial=HISTORY_BUFFER)
application = Application(
layout=create_layout(python_input, history_mapping),
use_alternate_screen=True,
buffers=buffer_mapping,
style=python_input._current_style,
mouse_support=Condition(lambda cli: python_input.enable_mouse_support),
key_bindings_registry=create_key_bindings(python_input, history_mapping)
)
return application | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.676/Olde/rp 5.45.01 PM/rp_ptpython/history_browser.py | 0.754101 | 0.161982 | history_browser.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.mouse_events import MouseEventTypes
import re
__all__ = (
'has_unclosed_brackets',
'get_jedi_script_from_document',
'document_is_multiline_python',
)
def has_unclosed_brackets(text):
"""
Starting at the end of the string. If we find an opening bracket
for which we didn't had a closing one yet, return True.
"""
stack = []
# Ignore braces inside strings
text = re.sub(r'''('[^']*'|"[^"]*")''', '', text) # XXX: handle escaped quotes.!
for c in reversed(text):
if c in '])}':
stack.append(c)
elif c in '[({':
if stack:
if ((c == '[' and stack[-1] == ']') or
(c == '{' and stack[-1] == '}') or
(c == '(' and stack[-1] == ')')):
stack.pop()
else:
# Opening bracket for which we didn't had a closing one.
return True
return False
def get_jedi_script_from_document(document, locals, globals):
import jedi # We keep this import in-line, to improve start-up time.
# Importing Jedi is 'slow'.
try:
return jedi.Interpreter(
document.text,
column=document.cursor_position_col,
line=document.cursor_position_row + 1,
path='input-text',
namespaces=[locals, globals])
except ValueError:
# Invalid cursor position.
# ValueError('`column` parameter is not in a valid range.')
return None
except AttributeError:
# Workaround for #65: https://github.com/jonathanslenders/python-prompt-toolkit/issues/65
# See also: https://github.com/davidhalter/jedi/issues/508
return None
except IndexError:
# Workaround Jedi issue #514: for https://github.com/davidhalter/jedi/issues/514
return None
except KeyError:
# Workaroud for a crash when the input is "u'", the start of a unicode string.
return None
except Exception:
# Workaround for: https://github.com/jonathanslenders/ptpython/issues/91
return None
_multiline_string_delims = re.compile('''[']{3}|["]{3}''')
def document_is_multiline_python(document):
"""
Determine whether this is a multiline Python document.
"""
def ends_in_multiline_string():
"""
``True`` if we're inside a multiline string at the end of the text.
"""
delims = _multiline_string_delims.findall(document.text)
opening = None
for delim in delims:
if opening is None:
opening = delim
elif delim == opening:
opening = None
return bool(opening)
if '\n' in document.text or ends_in_multiline_string():
return True
def line_ends_with_colon():
return document.current_line.rstrip()[-1:] == ':'
# If we just typed a colon, or still have open brackets, always insert a real newline.
if line_ends_with_colon() or \
(document.is_cursor_at_the_end and
has_unclosed_brackets(document.text_before_cursor)) or \
document.text.startswith('@'):
return True
# If the character before the cursor is a backslash (line continuation
# char), insert a new line.
elif document.text_before_cursor[-1:] == '\\':
return True
return False
def if_mousedown(handler):
"""
Decorator for mouse handlers.
Only handle event when the user pressed mouse down.
(When applied to a token list. Scroll events will bubble up and are handled
by the Window.)
"""
def handle_if_mouse_down(cli, mouse_event):
if mouse_event.event_type == MouseEventTypes.MOUSE_DOWN:
return handler(cli, mouse_event)
else:
return NotImplemented
return handle_if_mouse_down | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.676/Olde/rp 5.45.01 PM/rp_ptpython/utils.py | 0.516839 | 0.157234 | utils.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.application import Application
from prompt_toolkit.buffer import Buffer, AcceptAction
from prompt_toolkit.buffer_mapping import BufferMapping
from prompt_toolkit.document import Document
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import Condition, HasFocus, InFocusStack
from prompt_toolkit.key_binding.defaults import load_key_bindings
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.containers import HSplit, VSplit, Window, FloatContainer, Float, ConditionalContainer, Container, ScrollOffsets
from prompt_toolkit.layout.controls import BufferControl, FillControl
from prompt_toolkit.layout.dimension import LayoutDimension as D
from prompt_toolkit.layout.lexers import PygmentsLexer
from prompt_toolkit.layout.margins import Margin, ScrollbarMargin
from prompt_toolkit.layout.processors import Processor, Transformation, HighlightSearchProcessor, HighlightSelectionProcessor
from prompt_toolkit.layout.screen import Char
from prompt_toolkit.layout.toolbars import ArgToolbar, SearchToolbar
from prompt_toolkit.layout.toolbars import TokenListToolbar
from prompt_toolkit.layout.utils import token_list_to_text
from pygments.lexers import RstLexer
from pygments.token import Token
from .utils import if_mousedown
from rp.rp_ptpython.layout import get_inputmode_tokens
from functools import partial
import six
if six.PY2:
from pygments.lexers import PythonLexer
else:
from pygments.lexers import Python3Lexer as PythonLexer
HISTORY_BUFFER = 'HISTORY_BUFFER'
HELP_BUFFER = 'HELP_BUFFER'
HISTORY_COUNT = 2000
__all__ = (
'create_history_application',
)
HELP_TEXT = """
This interface is meant to select multiple lines from the
history and execute them together.
Typical usage
-------------
1. Move the ``cursor up`` in the history pane, until the
cursor is on the first desired line.
2. Hold down the ``space bar``, or press it multiple
times. Each time it will select one line and move to
the next one. Each selected line will appear on the
right side.
3. When all the required lines are displayed on the right
side, press ``Enter``. This will go back to the Python
REPL and show these lines as the current input. They
can still be edited from there.
Key bindings
------------
Many Emacs and Vi navigation key bindings should work.
Press ``F4`` to switch between Emacs and Vi mode.
Additional bindings:
- ``Space``: Select or delect a line.
- ``Tab``: Move the focus between the history and input
pane. (Alternative: ``Ctrl-W``)
- ``Ctrl-C``: Cancel. Ignore the result and go back to
the REPL. (Alternatives: ``q`` and ``Control-G``.)
- ``Enter``: Accept the result and go back to the REPL.
- ``F1``: Show/hide help. Press ``Enter`` to quit this
help message.
Further, remember that searching works like in Emacs
(using ``Ctrl-R``) or Vi (using ``/``).
"""
class BORDER:
" Box drawing characters. "
HORIZONTAL = '\u2501'
VERTICAL = '\u2503'
TOP_LEFT = '\u250f'
TOP_RIGHT = '\u2513'
BOTTOM_LEFT = '\u2517'
BOTTOM_RIGHT = '\u251b'
LIGHT_VERTICAL = '\u2502'
def create_popup_window(title, body):
"""
Return the layout for a pop-up window. It consists of a title bar showing
the `title` text, and a body layout. The window is surrounded by borders.
"""
assert isinstance(title, six.text_type)
assert isinstance(body, Container)
return HSplit([
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_LEFT, token=Token.Window.Border)),
TokenListToolbar(
get_tokens=lambda cli: [(Token.Window.Title, ' %s ' % title)],
align_center=True,
default_char=Char(BORDER.HORIZONTAL, Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_RIGHT, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
body,
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_LEFT, token=Token.Window.Border)),
Window(height=D.exact(1),
content=FillControl(BORDER.HORIZONTAL, token=Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_RIGHT, token=Token.Window.Border)),
]),
])
def create_layout(python_input, history_mapping):
"""
Create and return a `Container` instance for the history
application.
"""
processors = [
HighlightSearchProcessor(preview_search=True),
HighlightSelectionProcessor()]
help_window = create_popup_window(
title='History Help',
body=Window(
content=BufferControl(
buffer_name=HELP_BUFFER,
default_char=Char(token=Token),
lexer=PygmentsLexer(RstLexer),
input_processors=processors),
right_margins=[ScrollbarMargin()],
scroll_offsets=ScrollOffsets(top=2, bottom=2)))
return HSplit([
# Top title bar.
TokenListToolbar(
get_tokens=_get_top_toolbar_tokens,
align_center=True,
default_char=Char(' ', Token.Toolbar.Status)),
FloatContainer(
content=VSplit([
# Left side: history.
Window(
content=BufferControl(
buffer_name=HISTORY_BUFFER,
lexer=PygmentsLexer(PythonLexer),
input_processors=processors),
wrap_lines=False,
left_margins=[HistoryMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
# Separator.
Window(width=D.exact(1),
content=FillControl(BORDER.LIGHT_VERTICAL, token=Token.Separator)),
# Right side: result.
Window(
content=BufferControl(
buffer_name=DEFAULT_BUFFER,
input_processors=processors + [GrayExistingText(history_mapping)],
lexer=PygmentsLexer(PythonLexer)),
wrap_lines=False,
left_margins=[ResultMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
]),
floats=[
# Help text as a float.
Float(width=60, top=3, bottom=2,
content=ConditionalContainer(
# (We use InFocusStack, because it's possible to search
# through the help text as well, and at that point the search
# buffer has the focus.)
content=help_window, filter=InFocusStack(HELP_BUFFER))),
]
),
# Bottom toolbars.
ArgToolbar(),
SearchToolbar(),
TokenListToolbar(
get_tokens=partial(_get_bottom_toolbar_tokens, python_input=python_input),
default_char=Char(' ', Token.Toolbar.Status)),
])
def _get_top_toolbar_tokens(cli):
return [(Token.Toolbar.Status.Title, 'History browser - Insert from history')]
def _get_bottom_toolbar_tokens(cli, python_input):
@if_mousedown
def f1(cli, mouse_event):
_toggle_help(cli)
@if_mousedown
def tab(cli, mouse_event):
_select_other_window(cli)
return [
(Token.Toolbar.Status, ' ')
] + get_inputmode_tokens(cli, python_input) + [
(Token.Toolbar.Status, ' '),
(Token.Toolbar.Status.Key, '[Space]'),
(Token.Toolbar.Status, ' Toggle '),
(Token.Toolbar.Status.Key, '[Tab]', tab),
(Token.Toolbar.Status, ' Focus ', tab),
(Token.Toolbar.Status.Key, '[Enter]'),
(Token.Toolbar.Status, ' Accept '),
(Token.Toolbar.Status.Key, '[F1]', f1),
(Token.Toolbar.Status, ' Help ', f1),
]
class HistoryMargin(Margin):
"""
Margin for the history buffer.
This displays a green bar for the selected entries.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[HISTORY_BUFFER].document
lines_starting_new_entries = self.history_mapping.lines_starting_new_entries
selected_lines = self.history_mapping.selected_lines
current_lineno = document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
# Show stars at the start of each entry.
# (Visualises multiline entries.)
if line_number in lines_starting_new_entries:
char = '*'
else:
char = ' '
if line_number in selected_lines:
t = Token.History.Line.Selected
else:
t = Token.History.Line
if line_number == current_lineno:
t = t.Current
result.append((t, char))
result.append((Token, '\n'))
return result
class ResultMargin(Margin):
"""
The margin to be shown in the result pane.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[DEFAULT_BUFFER].document
current_lineno = document.cursor_position_row
offset = self.history_mapping.result_line_offset #original_document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
if (line_number is None or line_number < offset or
line_number >= offset + len(self.history_mapping.selected_lines)):
t = Token
elif line_number == current_lineno:
t = Token.History.Line.Selected.Current
else:
t = Token.History.Line.Selected
result.append((t, ' '))
result.append((Token, '\n'))
return result
def invalidation_hash(self, cli, document):
return document.cursor_position_row
class GrayExistingText(Processor):
"""
Turn the existing input, before and after the inserted code gray.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
self._lines_before = len(history_mapping.original_document.text_before_cursor.splitlines())
def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
if (lineno < self._lines_before or
lineno >= self._lines_before + len(self.history_mapping.selected_lines)):
text = token_list_to_text(tokens)
return Transformation(tokens=[(Token.History.ExistingInput, text)])
else:
return Transformation(tokens=tokens)
class HistoryMapping(object):
"""
Keep a list of all the lines from the history and the selected lines.
"""
def __init__(self, python_history, original_document):
self.python_history = python_history
self.original_document = original_document
self.lines_starting_new_entries = set()
self.selected_lines = set()
# Process history.
history_lines = []
for entry_nr, entry in list(enumerate(python_history))[-HISTORY_COUNT:]:
self.lines_starting_new_entries.add(len(history_lines))
for line in entry.splitlines():
history_lines.append(line)
if len(python_history) > HISTORY_COUNT:
history_lines[0] = '# *** History has been truncated to %s lines ***' % HISTORY_COUNT
self.history_lines = history_lines
self.concatenated_history = '\n'.join(history_lines)
# Line offset.
if self.original_document.text_before_cursor:
self.result_line_offset = self.original_document.cursor_position_row + 1
else:
self.result_line_offset = 0
def get_new_document(self, cursor_pos=None):
"""
Create a `Document` instance that contains the resulting text.
"""
lines = []
# Original text, before cursor.
if self.original_document.text_before_cursor:
lines.append(self.original_document.text_before_cursor)
# Selected entries from the history.
for line_no in sorted(self.selected_lines):
lines.append(self.history_lines[line_no])
# Original text, after cursor.
if self.original_document.text_after_cursor:
lines.append(self.original_document.text_after_cursor)
# Create `Document` with cursor at the right position.
text = '\n'.join(lines)
if cursor_pos is not None and cursor_pos > len(text):
cursor_pos = len(text)
return Document(text, cursor_pos)
def update_default_buffer(self, cli):
b = cli.buffers[DEFAULT_BUFFER]
b.set_document(
self.get_new_document(b.cursor_position), bypass_readonly=True)
def _toggle_help(cli):
" Display/hide help. "
if cli.current_buffer_name == HELP_BUFFER:
cli.pop_focus()
else:
cli.push_focus(HELP_BUFFER)
def _select_other_window(cli):
" Toggle focus between left/right window. "
if cli.current_buffer_name == HISTORY_BUFFER:
cli.focus(DEFAULT_BUFFER)
elif cli.current_buffer_name == DEFAULT_BUFFER:
cli.focus(HISTORY_BUFFER)
def create_key_bindings(python_input, history_mapping):
"""
Key bindings.
"""
registry = load_key_bindings(
enable_search=True,
enable_extra_page_navigation=True)
handle = registry.add_binding
@handle(' ', filter=HasFocus(HISTORY_BUFFER))
def _(event):
"""
Space: select/deselect line from history pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row
if line_no in history_mapping.selected_lines:
# Remove line.
history_mapping.selected_lines.remove(line_no)
history_mapping.update_default_buffer(event.cli)
else:
# Add line.
history_mapping.selected_lines.add(line_no)
history_mapping.update_default_buffer(event.cli)
# Update cursor position
default_buffer = event.cli.buffers[DEFAULT_BUFFER]
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
# Also move the cursor to the next line. (This way they can hold
# space to select a region.)
b.cursor_position = b.document.translate_row_col_to_index(line_no + 1, 0)
@handle(' ', filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.Delete, filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.ControlH, filter=HasFocus(DEFAULT_BUFFER))
def _(event):
"""
Space: remove line from default pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row - history_mapping.result_line_offset
if line_no >= 0:
try:
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass # When `selected_lines` is an empty set.
else:
history_mapping.selected_lines.remove(history_lineno)
history_mapping.update_default_buffer(event.cli)
help_focussed = HasFocus(HELP_BUFFER)
main_buffer_focussed = HasFocus(HISTORY_BUFFER) | HasFocus(DEFAULT_BUFFER)
@handle(Keys.Tab, filter=main_buffer_focussed)
@handle(Keys.ControlX, filter=main_buffer_focussed, eager=True)
# Eager: ignore the Emacs [Ctrl-X Ctrl-X] binding.
@handle(Keys.ControlW, filter=main_buffer_focussed)
def _(event):
" Select other window. "
_select_other_window(event.cli)
@handle(Keys.F4)
def _(event):
" Switch between Emacs/Vi mode. "
python_input.vi_mode = not python_input.vi_mode
@handle(Keys.F1)
def _(event):
" Display/hide help. "
_toggle_help(event.cli)
@handle(Keys.ControlJ, filter=help_focussed)
@handle(Keys.ControlC, filter=help_focussed)
@handle(Keys.ControlG, filter=help_focussed)
@handle(Keys.Escape, filter=help_focussed)
def _(event):
" Leave help. "
event.cli.pop_focus()
@handle('q', filter=main_buffer_focussed)
@handle(Keys.F3, filter=main_buffer_focussed)
@handle(Keys.ControlC, filter=main_buffer_focussed)
@handle(Keys.ControlG, filter=main_buffer_focussed)
def _(event):
" Cancel and go back. "
event.cli.set_return_value(None)
enable_system_bindings = Condition(lambda cli: python_input.enable_system_bindings)
@handle(Keys.ControlZ, filter=enable_system_bindings)
def _(event):
" Suspend to background. "
event.cli.suspend_to_background()
return registry
def create_history_application(python_input, original_document):
"""
Create an `Application` for the history screen.
This has to be run as a sub application of `python_input`.
When this application runs and returns, it retuns the selected lines.
"""
history_mapping = HistoryMapping(python_input.history, original_document)
def default_buffer_pos_changed(_):
""" When the cursor changes in the default buffer. Synchronize with
history buffer. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == DEFAULT_BUFFER:
try:
line_no = default_buffer.document.cursor_position_row - \
history_mapping.result_line_offset
if line_no < 0: # When the cursor is above the inserted region.
raise IndexError
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass
else:
history_buffer.cursor_position = \
history_buffer.document.translate_row_col_to_index(history_lineno, 0)
def history_buffer_pos_changed(_):
""" When the cursor changes in the history buffer. Synchronize. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == HISTORY_BUFFER:
line_no = history_buffer.document.cursor_position_row
if line_no in history_mapping.selected_lines:
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
history_buffer = Buffer(
initial_document=Document(history_mapping.concatenated_history),
on_cursor_position_changed=history_buffer_pos_changed,
accept_action=AcceptAction(
lambda cli, buffer: cli.set_return_value(default_buffer.document)),
read_only=True)
default_buffer = Buffer(
initial_document=history_mapping.get_new_document(),
on_cursor_position_changed=default_buffer_pos_changed,
read_only=True)
help_buffer = Buffer(
initial_document=Document(HELP_TEXT, 0),
accept_action=AcceptAction.IGNORE,
read_only=True
)
buffer_mapping = BufferMapping({
HISTORY_BUFFER: history_buffer,
DEFAULT_BUFFER: default_buffer,
HELP_BUFFER: help_buffer,
}, initial=HISTORY_BUFFER)
application = Application(
layout=create_layout(python_input, history_mapping),
use_alternate_screen=True,
buffers=buffer_mapping,
style=python_input._current_style,
mouse_support=Condition(lambda cli: python_input.enable_mouse_support),
key_bindings_registry=create_key_bindings(python_input, history_mapping)
)
return application | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.676/Olde/rp 7.24.17 AM/rp_ptpython/history_browser.py | 0.754101 | 0.161982 | history_browser.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.mouse_events import MouseEventTypes
import re
__all__ = (
'has_unclosed_brackets',
'get_jedi_script_from_document',
'document_is_multiline_python',
)
def has_unclosed_brackets(text):
"""
Starting at the end of the string. If we find an opening bracket
for which we didn't had a closing one yet, return True.
"""
stack = []
# Ignore braces inside strings
text = re.sub(r'''('[^']*'|"[^"]*")''', '', text) # XXX: handle escaped quotes.!
for c in reversed(text):
if c in '])}':
stack.append(c)
elif c in '[({':
if stack:
if ((c == '[' and stack[-1] == ']') or
(c == '{' and stack[-1] == '}') or
(c == '(' and stack[-1] == ')')):
stack.pop()
else:
# Opening bracket for which we didn't had a closing one.
return True
return False
def get_jedi_script_from_document(document, locals, globals):
import jedi # We keep this import in-line, to improve start-up time.
# Importing Jedi is 'slow'.
try:
return jedi.Interpreter(
document.text,
column=document.cursor_position_col,
line=document.cursor_position_row + 1,
path='input-text',
namespaces=[locals, globals])
except ValueError:
# Invalid cursor position.
# ValueError('`column` parameter is not in a valid range.')
return None
except AttributeError:
# Workaround for #65: https://github.com/jonathanslenders/python-prompt-toolkit/issues/65
# See also: https://github.com/davidhalter/jedi/issues/508
return None
except IndexError:
# Workaround Jedi issue #514: for https://github.com/davidhalter/jedi/issues/514
return None
except KeyError:
# Workaroud for a crash when the input is "u'", the start of a unicode string.
return None
except Exception:
# Workaround for: https://github.com/jonathanslenders/ptpython/issues/91
return None
_multiline_string_delims = re.compile('''[']{3}|["]{3}''')
def document_is_multiline_python(document):
"""
Determine whether this is a multiline Python document.
"""
def ends_in_multiline_string():
"""
``True`` if we're inside a multiline string at the end of the text.
"""
delims = _multiline_string_delims.findall(document.text)
opening = None
for delim in delims:
if opening is None:
opening = delim
elif delim == opening:
opening = None
return bool(opening)
if '\n' in document.text or ends_in_multiline_string():
return True
def line_ends_with_colon():
return document.current_line.rstrip()[-1:] == ':'
# If we just typed a colon, or still have open brackets, always insert a real newline.
if line_ends_with_colon() or \
(document.is_cursor_at_the_end and
has_unclosed_brackets(document.text_before_cursor)) or \
document.text.startswith('@'):
return True
# If the character before the cursor is a backslash (line continuation
# char), insert a new line.
elif document.text_before_cursor[-1:] == '\\':
return True
return False
def if_mousedown(handler):
"""
Decorator for mouse handlers.
Only handle event when the user pressed mouse down.
(When applied to a token list. Scroll events will bubble up and are handled
by the Window.)
"""
def handle_if_mouse_down(cli, mouse_event):
if mouse_event.event_type == MouseEventTypes.MOUSE_DOWN:
return handler(cli, mouse_event)
else:
return NotImplemented
return handle_if_mouse_down | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.676/Olde/rp 7.24.17 AM/rp_ptpython/utils.py | 0.516839 | 0.157234 | utils.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.application import Application
from prompt_toolkit.buffer import Buffer, AcceptAction
from prompt_toolkit.buffer_mapping import BufferMapping
from prompt_toolkit.document import Document
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import Condition, HasFocus, InFocusStack
from prompt_toolkit.key_binding.defaults import load_key_bindings
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.containers import HSplit, VSplit, Window, FloatContainer, Float, ConditionalContainer, Container, ScrollOffsets
from prompt_toolkit.layout.controls import BufferControl, FillControl
from prompt_toolkit.layout.dimension import LayoutDimension as D
from prompt_toolkit.layout.lexers import PygmentsLexer
from prompt_toolkit.layout.margins import Margin, ScrollbarMargin
from prompt_toolkit.layout.processors import Processor, Transformation, HighlightSearchProcessor, HighlightSelectionProcessor
from prompt_toolkit.layout.screen import Char
from prompt_toolkit.layout.toolbars import ArgToolbar, SearchToolbar
from prompt_toolkit.layout.toolbars import TokenListToolbar
from prompt_toolkit.layout.utils import token_list_to_text
from pygments.lexers import RstLexer
from pygments.token import Token
from .utils import if_mousedown
from rp.rp_ptpython.layout import get_inputmode_tokens
from functools import partial
import six
if six.PY2:
from pygments.lexers import PythonLexer
else:
from pygments.lexers import Python3Lexer as PythonLexer
HISTORY_BUFFER = 'HISTORY_BUFFER'
HELP_BUFFER = 'HELP_BUFFER'
HISTORY_COUNT = 2000
__all__ = (
'create_history_application',
)
HELP_TEXT = """
This interface is meant to select multiple lines from the
history and execute them together.
Typical usage
-------------
1. Move the ``cursor up`` in the history pane, until the
cursor is on the first desired line.
2. Hold down the ``space bar``, or press it multiple
times. Each time it will select one line and move to
the next one. Each selected line will appear on the
right side.
3. When all the required lines are displayed on the right
side, press ``Enter``. This will go back to the Python
REPL and show these lines as the current input. They
can still be edited from there.
Key bindings
------------
Many Emacs and Vi navigation key bindings should work.
Press ``F4`` to switch between Emacs and Vi mode.
Additional bindings:
- ``Space``: Select or delect a line.
- ``Tab``: Move the focus between the history and input
pane. (Alternative: ``Ctrl-W``)
- ``Ctrl-C``: Cancel. Ignore the result and go back to
the REPL. (Alternatives: ``q`` and ``Control-G``.)
- ``Enter``: Accept the result and go back to the REPL.
- ``F1``: Show/hide help. Press ``Enter`` to quit this
help message.
Further, remember that searching works like in Emacs
(using ``Ctrl-R``) or Vi (using ``/``).
"""
class BORDER:
" Box drawing characters. "
HORIZONTAL = '\u2501'
VERTICAL = '\u2503'
TOP_LEFT = '\u250f'
TOP_RIGHT = '\u2513'
BOTTOM_LEFT = '\u2517'
BOTTOM_RIGHT = '\u251b'
LIGHT_VERTICAL = '\u2502'
def create_popup_window(title, body):
"""
Return the layout for a pop-up window. It consists of a title bar showing
the `title` text, and a body layout. The window is surrounded by borders.
"""
assert isinstance(title, six.text_type)
assert isinstance(body, Container)
return HSplit([
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_LEFT, token=Token.Window.Border)),
TokenListToolbar(
get_tokens=lambda cli: [(Token.Window.Title, ' %s ' % title)],
align_center=True,
default_char=Char(BORDER.HORIZONTAL, Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_RIGHT, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
body,
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_LEFT, token=Token.Window.Border)),
Window(height=D.exact(1),
content=FillControl(BORDER.HORIZONTAL, token=Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_RIGHT, token=Token.Window.Border)),
]),
])
def create_layout(python_input, history_mapping):
"""
Create and return a `Container` instance for the history
application.
"""
processors = [
HighlightSearchProcessor(preview_search=True),
HighlightSelectionProcessor()]
help_window = create_popup_window(
title='History Help',
body=Window(
content=BufferControl(
buffer_name=HELP_BUFFER,
default_char=Char(token=Token),
lexer=PygmentsLexer(RstLexer),
input_processors=processors),
right_margins=[ScrollbarMargin()],
scroll_offsets=ScrollOffsets(top=2, bottom=2)))
return HSplit([
# Top title bar.
TokenListToolbar(
get_tokens=_get_top_toolbar_tokens,
align_center=True,
default_char=Char(' ', Token.Toolbar.Status)),
FloatContainer(
content=VSplit([
# Left side: history.
Window(
content=BufferControl(
buffer_name=HISTORY_BUFFER,
lexer=PygmentsLexer(PythonLexer),
input_processors=processors),
wrap_lines=False,
left_margins=[HistoryMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
# Separator.
Window(width=D.exact(1),
content=FillControl(BORDER.LIGHT_VERTICAL, token=Token.Separator)),
# Right side: result.
Window(
content=BufferControl(
buffer_name=DEFAULT_BUFFER,
input_processors=processors + [GrayExistingText(history_mapping)],
lexer=PygmentsLexer(PythonLexer)),
wrap_lines=False,
left_margins=[ResultMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
]),
floats=[
# Help text as a float.
Float(width=60, top=3, bottom=2,
content=ConditionalContainer(
# (We use InFocusStack, because it's possible to search
# through the help text as well, and at that point the search
# buffer has the focus.)
content=help_window, filter=InFocusStack(HELP_BUFFER))),
]
),
# Bottom toolbars.
ArgToolbar(),
SearchToolbar(),
TokenListToolbar(
get_tokens=partial(_get_bottom_toolbar_tokens, python_input=python_input),
default_char=Char(' ', Token.Toolbar.Status)),
])
def _get_top_toolbar_tokens(cli):
return [(Token.Toolbar.Status.Title, 'History browser - Insert from history')]
def _get_bottom_toolbar_tokens(cli, python_input):
@if_mousedown
def f1(cli, mouse_event):
_toggle_help(cli)
@if_mousedown
def tab(cli, mouse_event):
_select_other_window(cli)
return [
(Token.Toolbar.Status, ' ')
] + get_inputmode_tokens(cli, python_input) + [
(Token.Toolbar.Status, ' '),
(Token.Toolbar.Status.Key, '[Space]'),
(Token.Toolbar.Status, ' Toggle '),
(Token.Toolbar.Status.Key, '[Tab]', tab),
(Token.Toolbar.Status, ' Focus ', tab),
(Token.Toolbar.Status.Key, '[Enter]'),
(Token.Toolbar.Status, ' Accept '),
(Token.Toolbar.Status.Key, '[F1]', f1),
(Token.Toolbar.Status, ' Help ', f1),
]
class HistoryMargin(Margin):
"""
Margin for the history buffer.
This displays a green bar for the selected entries.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[HISTORY_BUFFER].document
lines_starting_new_entries = self.history_mapping.lines_starting_new_entries
selected_lines = self.history_mapping.selected_lines
current_lineno = document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
# Show stars at the start of each entry.
# (Visualises multiline entries.)
if line_number in lines_starting_new_entries:
char = '*'
else:
char = ' '
if line_number in selected_lines:
t = Token.History.Line.Selected
else:
t = Token.History.Line
if line_number == current_lineno:
t = t.Current
result.append((t, char))
result.append((Token, '\n'))
return result
class ResultMargin(Margin):
"""
The margin to be shown in the result pane.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[DEFAULT_BUFFER].document
current_lineno = document.cursor_position_row
offset = self.history_mapping.result_line_offset #original_document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
if (line_number is None or line_number < offset or
line_number >= offset + len(self.history_mapping.selected_lines)):
t = Token
elif line_number == current_lineno:
t = Token.History.Line.Selected.Current
else:
t = Token.History.Line.Selected
result.append((t, ' '))
result.append((Token, '\n'))
return result
def invalidation_hash(self, cli, document):
return document.cursor_position_row
class GrayExistingText(Processor):
"""
Turn the existing input, before and after the inserted code gray.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
self._lines_before = len(history_mapping.original_document.text_before_cursor.splitlines())
def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
if (lineno < self._lines_before or
lineno >= self._lines_before + len(self.history_mapping.selected_lines)):
text = token_list_to_text(tokens)
return Transformation(tokens=[(Token.History.ExistingInput, text)])
else:
return Transformation(tokens=tokens)
class HistoryMapping(object):
"""
Keep a list of all the lines from the history and the selected lines.
"""
def __init__(self, python_history, original_document):
self.python_history = python_history
self.original_document = original_document
self.lines_starting_new_entries = set()
self.selected_lines = set()
# Process history.
history_lines = []
for entry_nr, entry in list(enumerate(python_history))[-HISTORY_COUNT:]:
self.lines_starting_new_entries.add(len(history_lines))
for line in entry.splitlines():
history_lines.append(line)
if len(python_history) > HISTORY_COUNT:
history_lines[0] = '# *** History has been truncated to %s lines ***' % HISTORY_COUNT
self.history_lines = history_lines
self.concatenated_history = '\n'.join(history_lines)
# Line offset.
if self.original_document.text_before_cursor:
self.result_line_offset = self.original_document.cursor_position_row + 1
else:
self.result_line_offset = 0
def get_new_document(self, cursor_pos=None):
"""
Create a `Document` instance that contains the resulting text.
"""
lines = []
# Original text, before cursor.
if self.original_document.text_before_cursor:
lines.append(self.original_document.text_before_cursor)
# Selected entries from the history.
for line_no in sorted(self.selected_lines):
lines.append(self.history_lines[line_no])
# Original text, after cursor.
if self.original_document.text_after_cursor:
lines.append(self.original_document.text_after_cursor)
# Create `Document` with cursor at the right position.
text = '\n'.join(lines)
if cursor_pos is not None and cursor_pos > len(text):
cursor_pos = len(text)
return Document(text, cursor_pos)
def update_default_buffer(self, cli):
b = cli.buffers[DEFAULT_BUFFER]
b.set_document(
self.get_new_document(b.cursor_position), bypass_readonly=True)
def _toggle_help(cli):
" Display/hide help. "
if cli.current_buffer_name == HELP_BUFFER:
cli.pop_focus()
else:
cli.push_focus(HELP_BUFFER)
def _select_other_window(cli):
" Toggle focus between left/right window. "
if cli.current_buffer_name == HISTORY_BUFFER:
cli.focus(DEFAULT_BUFFER)
elif cli.current_buffer_name == DEFAULT_BUFFER:
cli.focus(HISTORY_BUFFER)
def create_key_bindings(python_input, history_mapping):
"""
Key bindings.
"""
registry = load_key_bindings(
enable_search=True,
enable_extra_page_navigation=True)
handle = registry.add_binding
@handle(' ', filter=HasFocus(HISTORY_BUFFER))
def _(event):
"""
Space: select/deselect line from history pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row
if line_no in history_mapping.selected_lines:
# Remove line.
history_mapping.selected_lines.remove(line_no)
history_mapping.update_default_buffer(event.cli)
else:
# Add line.
history_mapping.selected_lines.add(line_no)
history_mapping.update_default_buffer(event.cli)
# Update cursor position
default_buffer = event.cli.buffers[DEFAULT_BUFFER]
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
# Also move the cursor to the next line. (This way they can hold
# space to select a region.)
b.cursor_position = b.document.translate_row_col_to_index(line_no + 1, 0)
@handle(' ', filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.Delete, filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.ControlH, filter=HasFocus(DEFAULT_BUFFER))
def _(event):
"""
Space: remove line from default pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row - history_mapping.result_line_offset
if line_no >= 0:
try:
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass # When `selected_lines` is an empty set.
else:
history_mapping.selected_lines.remove(history_lineno)
history_mapping.update_default_buffer(event.cli)
help_focussed = HasFocus(HELP_BUFFER)
main_buffer_focussed = HasFocus(HISTORY_BUFFER) | HasFocus(DEFAULT_BUFFER)
@handle(Keys.Tab, filter=main_buffer_focussed)
@handle(Keys.ControlX, filter=main_buffer_focussed, eager=True)
# Eager: ignore the Emacs [Ctrl-X Ctrl-X] binding.
@handle(Keys.ControlW, filter=main_buffer_focussed)
def _(event):
" Select other window. "
_select_other_window(event.cli)
@handle(Keys.F4)
def _(event):
" Switch between Emacs/Vi mode. "
python_input.vi_mode = not python_input.vi_mode
@handle(Keys.F1)
def _(event):
" Display/hide help. "
_toggle_help(event.cli)
@handle(Keys.ControlJ, filter=help_focussed)
@handle(Keys.ControlC, filter=help_focussed)
@handle(Keys.ControlG, filter=help_focussed)
@handle(Keys.Escape, filter=help_focussed)
def _(event):
" Leave help. "
event.cli.pop_focus()
@handle('q', filter=main_buffer_focussed)
@handle(Keys.F3, filter=main_buffer_focussed)
@handle(Keys.ControlC, filter=main_buffer_focussed)
@handle(Keys.ControlG, filter=main_buffer_focussed)
def _(event):
" Cancel and go back. "
event.cli.set_return_value(None)
enable_system_bindings = Condition(lambda cli: python_input.enable_system_bindings)
@handle(Keys.ControlZ, filter=enable_system_bindings)
def _(event):
" Suspend to background. "
event.cli.suspend_to_background()
return registry
def create_history_application(python_input, original_document):
"""
Create an `Application` for the history screen.
This has to be run as a sub application of `python_input`.
When this application runs and returns, it retuns the selected lines.
"""
history_mapping = HistoryMapping(python_input.history, original_document)
def default_buffer_pos_changed(_):
""" When the cursor changes in the default buffer. Synchronize with
history buffer. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == DEFAULT_BUFFER:
try:
line_no = default_buffer.document.cursor_position_row - \
history_mapping.result_line_offset
if line_no < 0: # When the cursor is above the inserted region.
raise IndexError
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass
else:
history_buffer.cursor_position = \
history_buffer.document.translate_row_col_to_index(history_lineno, 0)
def history_buffer_pos_changed(_):
""" When the cursor changes in the history buffer. Synchronize. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == HISTORY_BUFFER:
line_no = history_buffer.document.cursor_position_row
if line_no in history_mapping.selected_lines:
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
history_buffer = Buffer(
initial_document=Document(history_mapping.concatenated_history),
on_cursor_position_changed=history_buffer_pos_changed,
accept_action=AcceptAction(
lambda cli, buffer: cli.set_return_value(default_buffer.document)),
read_only=True)
default_buffer = Buffer(
initial_document=history_mapping.get_new_document(),
on_cursor_position_changed=default_buffer_pos_changed,
read_only=True)
help_buffer = Buffer(
initial_document=Document(HELP_TEXT, 0),
accept_action=AcceptAction.IGNORE,
read_only=True
)
buffer_mapping = BufferMapping({
HISTORY_BUFFER: history_buffer,
DEFAULT_BUFFER: default_buffer,
HELP_BUFFER: help_buffer,
}, initial=HISTORY_BUFFER)
application = Application(
layout=create_layout(python_input, history_mapping),
use_alternate_screen=True,
buffers=buffer_mapping,
style=python_input._current_style,
mouse_support=Condition(lambda cli: python_input.enable_mouse_support),
key_bindings_registry=create_key_bindings(python_input, history_mapping)
)
return application | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.676/Olde/rp 5.38.10 PM/rp_ptpython/history_browser.py | 0.754101 | 0.161982 | history_browser.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.mouse_events import MouseEventTypes
import re
__all__ = (
'has_unclosed_brackets',
'get_jedi_script_from_document',
'document_is_multiline_python',
)
def has_unclosed_brackets(text):
"""
Starting at the end of the string. If we find an opening bracket
for which we didn't had a closing one yet, return True.
"""
stack = []
# Ignore braces inside strings
text = re.sub(r'''('[^']*'|"[^"]*")''', '', text) # XXX: handle escaped quotes.!
for c in reversed(text):
if c in '])}':
stack.append(c)
elif c in '[({':
if stack:
if ((c == '[' and stack[-1] == ']') or
(c == '{' and stack[-1] == '}') or
(c == '(' and stack[-1] == ')')):
stack.pop()
else:
# Opening bracket for which we didn't had a closing one.
return True
return False
def get_jedi_script_from_document(document, locals, globals):
import jedi # We keep this import in-line, to improve start-up time.
# Importing Jedi is 'slow'.
try:
return jedi.Interpreter(
document.text,
column=document.cursor_position_col,
line=document.cursor_position_row + 1,
path='input-text',
namespaces=[locals, globals])
except ValueError:
# Invalid cursor position.
# ValueError('`column` parameter is not in a valid range.')
return None
except AttributeError:
# Workaround for #65: https://github.com/jonathanslenders/python-prompt-toolkit/issues/65
# See also: https://github.com/davidhalter/jedi/issues/508
return None
except IndexError:
# Workaround Jedi issue #514: for https://github.com/davidhalter/jedi/issues/514
return None
except KeyError:
# Workaroud for a crash when the input is "u'", the start of a unicode string.
return None
except Exception:
# Workaround for: https://github.com/jonathanslenders/ptpython/issues/91
return None
_multiline_string_delims = re.compile('''[']{3}|["]{3}''')
def document_is_multiline_python(document):
"""
Determine whether this is a multiline Python document.
"""
def ends_in_multiline_string():
"""
``True`` if we're inside a multiline string at the end of the text.
"""
delims = _multiline_string_delims.findall(document.text)
opening = None
for delim in delims:
if opening is None:
opening = delim
elif delim == opening:
opening = None
return bool(opening)
if '\n' in document.text or ends_in_multiline_string():
return True
def line_ends_with_colon():
return document.current_line.rstrip()[-1:] == ':'
# If we just typed a colon, or still have open brackets, always insert a real newline.
if line_ends_with_colon() or \
(document.is_cursor_at_the_end and
has_unclosed_brackets(document.text_before_cursor)) or \
document.text.startswith('@'):
return True
# If the character before the cursor is a backslash (line continuation
# char), insert a new line.
elif document.text_before_cursor[-1:] == '\\':
return True
return False
def if_mousedown(handler):
"""
Decorator for mouse handlers.
Only handle event when the user pressed mouse down.
(When applied to a token list. Scroll events will bubble up and are handled
by the Window.)
"""
def handle_if_mouse_down(cli, mouse_event):
if mouse_event.event_type == MouseEventTypes.MOUSE_DOWN:
return handler(cli, mouse_event)
else:
return NotImplemented
return handle_if_mouse_down | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.676/Olde/rp 5.38.10 PM/rp_ptpython/utils.py | 0.516839 | 0.157234 | utils.py | pypi |
from __future__ import print_function, unicode_literals
import os
import re
import warnings
from .utils import trace
DEFAULT_TAG_REGEX = r"^(?:[\w-]+-)?(?P<version>[vV]?\d+(?:\.\d+){0,2}[^\+]*)(?:\+.*)?$"
DEFAULT_VERSION_SCHEME = "guess-next-dev"
DEFAULT_LOCAL_SCHEME = "node-and-date"
def _check_tag_regex(value):
if not value:
value = DEFAULT_TAG_REGEX
regex = re.compile(value)
group_names = regex.groupindex.keys()
if regex.groups == 0 or (regex.groups > 1 and "version" not in group_names):
warnings.warn(
"Expected tag_regex to contain a single match group or a group named"
" 'version' to identify the version part of any tag."
)
return regex
def _check_absolute_root(root, relative_to):
if relative_to:
if os.path.isabs(root) and not root.startswith(relative_to):
warnings.warn(
"absolute root path '%s' overrides relative_to '%s'"
% (root, relative_to)
)
root = os.path.join(os.path.dirname(relative_to), root)
return os.path.abspath(root)
class Configuration(object):
""" Global configuration model """
def __init__(
self,
relative_to=None,
root=".",
version_scheme=DEFAULT_VERSION_SCHEME,
local_scheme=DEFAULT_LOCAL_SCHEME,
write_to=None,
write_to_template=None,
tag_regex=DEFAULT_TAG_REGEX,
parentdir_prefix_version=None,
fallback_version=None,
fallback_root=".",
parse=None,
git_describe_command=None,
):
# TODO:
self._relative_to = relative_to
self._root = "."
self.root = root
self.version_scheme = version_scheme
self.local_scheme = local_scheme
self.write_to = write_to
self.write_to_template = write_to_template
self.parentdir_prefix_version = parentdir_prefix_version
self.fallback_version = fallback_version
self.fallback_root = fallback_root
self.parse = parse
self.tag_regex = tag_regex
self.git_describe_command = git_describe_command
@property
def fallback_root(self):
return self._fallback_root
@fallback_root.setter
def fallback_root(self, value):
self._fallback_root = os.path.abspath(value)
@property
def absolute_root(self):
return self._absolute_root
@property
def relative_to(self):
return self._relative_to
@relative_to.setter
def relative_to(self, value):
self._absolute_root = _check_absolute_root(self._root, value)
self._relative_to = value
trace("root", repr(self._absolute_root))
@property
def root(self):
return self._root
@root.setter
def root(self, value):
self._absolute_root = _check_absolute_root(value, self._relative_to)
self._root = value
trace("root", repr(self._absolute_root))
@property
def tag_regex(self):
return self._tag_regex
@tag_regex.setter
def tag_regex(self, value):
self._tag_regex = _check_tag_regex(value)
@classmethod
def from_file(cls, name="pyproject.toml"):
"""
Read Configuration from pyproject.toml (or similar).
Raises exceptions when file is not found or toml is
not installed or the file has invalid format or does
not contain the [tool.setuptools_scm] section.
"""
with open(name) as strm:
defn = __import__("toml").load(strm)
section = defn.get("tool", {})["setuptools_scm"]
return cls(**section) | /rp-0.1.923.tar.gz/rp-0.1.923/.eggs/setuptools_scm-4.1.2-py3.7.egg/setuptools_scm/config.py | 0.441914 | 0.20093 | config.py | pypi |
from __future__ import print_function
import datetime
import warnings
import re
from .config import Configuration
from .utils import trace, string_types, utc
from pkg_resources import iter_entry_points
from pkg_resources import parse_version as pkg_parse_version
SEMVER_MINOR = 2
SEMVER_PATCH = 3
SEMVER_LEN = 3
def _parse_version_tag(tag, config):
tagstring = tag if not isinstance(tag, string_types) else str(tag)
match = config.tag_regex.match(tagstring)
result = None
if match:
if len(match.groups()) == 1:
key = 1
else:
key = "version"
result = {
"version": match.group(key),
"prefix": match.group(0)[: match.start(key)],
"suffix": match.group(0)[match.end(key) :],
}
trace("tag '{}' parsed to {}".format(tag, result))
return result
def _get_version_class():
modern_version = pkg_parse_version("1.0")
if isinstance(modern_version, tuple):
return None
else:
return type(modern_version)
VERSION_CLASS = _get_version_class()
class SetuptoolsOutdatedWarning(Warning):
pass
# append so integrators can disable the warning
warnings.simplefilter("error", SetuptoolsOutdatedWarning, append=True)
def _warn_if_setuptools_outdated():
if VERSION_CLASS is None:
warnings.warn("your setuptools is too old (<12)", SetuptoolsOutdatedWarning)
def callable_or_entrypoint(group, callable_or_name):
trace("ep", (group, callable_or_name))
if callable(callable_or_name):
return callable_or_name
for ep in iter_entry_points(group, callable_or_name):
trace("ep found:", ep.name)
return ep.load()
def tag_to_version(tag, config=None):
"""
take a tag that might be prefixed with a keyword and return only the version part
:param config: optional configuration object
"""
trace("tag", tag)
if not config:
config = Configuration()
tagdict = _parse_version_tag(tag, config)
if not isinstance(tagdict, dict) or not tagdict.get("version", None):
warnings.warn("tag {!r} no version found".format(tag))
return None
version = tagdict["version"]
trace("version pre parse", version)
if tagdict.get("suffix", ""):
warnings.warn(
"tag {!r} will be stripped of its suffix '{}'".format(
tag, tagdict["suffix"]
)
)
if VERSION_CLASS is not None:
version = pkg_parse_version(version)
trace("version", repr(version))
return version
def tags_to_versions(tags, config=None):
"""
take tags that might be prefixed with a keyword and return only the version part
:param tags: an iterable of tags
:param config: optional configuration object
"""
result = []
for tag in tags:
tag = tag_to_version(tag, config=config)
if tag:
result.append(tag)
return result
class ScmVersion(object):
def __init__(
self,
tag_version,
distance=None,
node=None,
dirty=False,
preformatted=False,
branch=None,
config=None,
**kw
):
if kw:
trace("unknown args", kw)
self.tag = tag_version
if dirty and distance is None:
distance = 0
self.distance = distance
self.node = node
self.time = datetime.datetime.now(utc)
self._extra = kw
self.dirty = dirty
self.preformatted = preformatted
self.branch = branch
self.config = config
@property
def extra(self):
warnings.warn(
"ScmVersion.extra is deprecated and will be removed in future",
category=DeprecationWarning,
stacklevel=2,
)
return self._extra
@property
def exact(self):
return self.distance is None
def __repr__(self):
return self.format_with(
"<ScmVersion {tag} d={distance} n={node} d={dirty} b={branch}>"
)
def format_with(self, fmt, **kw):
return fmt.format(
time=self.time,
tag=self.tag,
distance=self.distance,
node=self.node,
dirty=self.dirty,
branch=self.branch,
**kw
)
def format_choice(self, clean_format, dirty_format, **kw):
return self.format_with(dirty_format if self.dirty else clean_format, **kw)
def format_next_version(self, guess_next, fmt="{guessed}.dev{distance}", **kw):
guessed = guess_next(self.tag, **kw)
return self.format_with(fmt, guessed=guessed)
def _parse_tag(tag, preformatted, config):
if preformatted:
return tag
if VERSION_CLASS is None or not isinstance(tag, VERSION_CLASS):
tag = tag_to_version(tag, config)
return tag
def meta(
tag,
distance=None,
dirty=False,
node=None,
preformatted=False,
branch=None,
config=None,
**kw
):
if not config:
warnings.warn(
"meta invoked without explicit configuration,"
" will use defaults where required."
)
parsed_version = _parse_tag(tag, preformatted, config)
trace("version", tag, "->", parsed_version)
assert parsed_version is not None, "cant parse version %s" % tag
return ScmVersion(
parsed_version, distance, node, dirty, preformatted, branch, config, **kw
)
def guess_next_version(tag_version):
version = _strip_local(str(tag_version))
return _bump_dev(version) or _bump_regex(version)
def _strip_local(version_string):
public, sep, local = version_string.partition("+")
return public
def _bump_dev(version):
if ".dev" not in version:
return
prefix, tail = version.rsplit(".dev", 1)
assert tail == "0", "own dev numbers are unsupported"
return prefix
def _bump_regex(version):
prefix, tail = re.match(r"(.*?)(\d+)$", version).groups()
return "%s%d" % (prefix, int(tail) + 1)
def guess_next_dev_version(version):
if version.exact:
return version.format_with("{tag}")
else:
return version.format_next_version(guess_next_version)
def guess_next_simple_semver(version, retain, increment=True):
parts = [int(i) for i in str(version).split(".")[:retain]]
while len(parts) < retain:
parts.append(0)
if increment:
parts[-1] += 1
while len(parts) < SEMVER_LEN:
parts.append(0)
return ".".join(str(i) for i in parts)
def simplified_semver_version(version):
if version.exact:
return guess_next_simple_semver(version.tag, retain=SEMVER_LEN, increment=False)
else:
if version.branch is not None and "feature" in version.branch:
return version.format_next_version(
guess_next_simple_semver, retain=SEMVER_MINOR
)
else:
return version.format_next_version(
guess_next_simple_semver, retain=SEMVER_PATCH
)
def release_branch_semver_version(version):
if version.exact:
return version.format_with("{tag}")
if version.branch is not None:
# Does the branch name (stripped of namespace) parse as a version?
branch_ver = _parse_version_tag(version.branch.split("/")[-1], version.config)
if branch_ver is not None:
# Does the branch version up to the minor part match the tag? If not it
# might be like, an issue number or something and not a version number, so
# we only want to use it if it matches.
tag_ver_up_to_minor = str(version.tag).split(".")[:SEMVER_MINOR]
branch_ver_up_to_minor = branch_ver["version"].split(".")[:SEMVER_MINOR]
if branch_ver_up_to_minor == tag_ver_up_to_minor:
# We're in a release/maintenance branch, next is a patch/rc/beta bump:
return version.format_next_version(guess_next_version)
# We're in a development branch, next is a minor bump:
return version.format_next_version(guess_next_simple_semver, retain=SEMVER_MINOR)
def release_branch_semver(version):
warnings.warn(
"release_branch_semver is deprecated and will be removed in future. "
+ "Use release_branch_semver_version instead",
category=DeprecationWarning,
stacklevel=2,
)
return release_branch_semver_version(version)
def _format_local_with_time(version, time_format):
if version.exact or version.node is None:
return version.format_choice(
"", "+d{time:{time_format}}", time_format=time_format
)
else:
return version.format_choice(
"+{node}", "+{node}.d{time:{time_format}}", time_format=time_format
)
def get_local_node_and_date(version):
return _format_local_with_time(version, time_format="%Y%m%d")
def get_local_node_and_timestamp(version, fmt="%Y%m%d%H%M%S"):
return _format_local_with_time(version, time_format=fmt)
def get_local_dirty_tag(version):
return version.format_choice("", "+dirty")
def get_no_local_node(_):
return ""
def postrelease_version(version):
if version.exact:
return version.format_with("{tag}")
else:
return version.format_with("{tag}.post{distance}")
def format_version(version, **config):
trace("scm version", version)
trace("config", config)
if version.preformatted:
return version.tag
version_scheme = callable_or_entrypoint(
"setuptools_scm.version_scheme", config["version_scheme"]
)
local_scheme = callable_or_entrypoint(
"setuptools_scm.local_scheme", config["local_scheme"]
)
main_version = version_scheme(version)
trace("version", main_version)
local_version = local_scheme(version)
trace("local_version", local_version)
return version_scheme(version) + local_scheme(version) | /rp-0.1.923.tar.gz/rp-0.1.923/.eggs/setuptools_scm-4.1.2-py3.7.egg/setuptools_scm/version.py | 0.593845 | 0.183191 | version.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.application import Application
from prompt_toolkit.buffer import Buffer, AcceptAction
from prompt_toolkit.buffer_mapping import BufferMapping
from prompt_toolkit.document import Document
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import Condition, HasFocus, InFocusStack
from prompt_toolkit.key_binding.defaults import load_key_bindings
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.containers import HSplit, VSplit, Window, FloatContainer, Float, ConditionalContainer, Container, ScrollOffsets
from prompt_toolkit.layout.controls import BufferControl, FillControl
from prompt_toolkit.layout.dimension import LayoutDimension as D
from prompt_toolkit.layout.lexers import PygmentsLexer
from prompt_toolkit.layout.margins import Margin, ScrollbarMargin
from prompt_toolkit.layout.processors import Processor, Transformation, HighlightSearchProcessor, HighlightSelectionProcessor
from prompt_toolkit.layout.screen import Char
from prompt_toolkit.layout.toolbars import ArgToolbar, SearchToolbar
from prompt_toolkit.layout.toolbars import TokenListToolbar
from prompt_toolkit.layout.utils import token_list_to_text
from pygments.lexers import RstLexer
from pygments.token import Token
from .utils import if_mousedown
from rp.rp_ptpython.layout import get_inputmode_tokens
from functools import partial
import six
if six.PY2:
from pygments.lexers import PythonLexer
else:
from pygments.lexers import Python3Lexer as PythonLexer
HISTORY_BUFFER = 'HISTORY_BUFFER'
HELP_BUFFER = 'HELP_BUFFER'
HISTORY_COUNT = 2000
__all__ = (
'create_history_application',
)
HELP_TEXT = """
This interface is meant to select multiple lines from the
history and execute them together.
Typical usage
-------------
1. Move the ``cursor up`` in the history pane, until the
cursor is on the first desired line.
2. Hold down the ``space bar``, or press it multiple
times. Each time it will select one line and move to
the next one. Each selected line will appear on the
right side.
3. When all the required lines are displayed on the right
side, press ``Enter``. This will go back to the Python
REPL and show these lines as the current input. They
can still be edited from there.
Key bindings
------------
Many Emacs and Vi navigation key bindings should work.
Press ``F4`` to switch between Emacs and Vi mode.
Additional bindings:
- ``Space``: Select or delect a line.
- ``Tab``: Move the focus between the history and input
pane. (Alternative: ``Ctrl-W``)
- ``Ctrl-C``: Cancel. Ignore the result and go back to
the REPL. (Alternatives: ``q`` and ``Control-G``.)
- ``Enter``: Accept the result and go back to the REPL.
- ``F1``: Show/hide help. Press ``Enter`` to quit this
help message.
Further, remember that searching works like in Emacs
(using ``Ctrl-R``) or Vi (using ``/``).
"""
class BORDER:
" Box drawing characters. "
HORIZONTAL = '\u2501'
VERTICAL = '\u2503'
TOP_LEFT = '\u250f'
TOP_RIGHT = '\u2513'
BOTTOM_LEFT = '\u2517'
BOTTOM_RIGHT = '\u251b'
LIGHT_VERTICAL = '\u2502'
def create_popup_window(title, body):
"""
Return the layout for a pop-up window. It consists of a title bar showing
the `title` text, and a body layout. The window is surrounded by borders.
"""
assert isinstance(title, six.text_type)
assert isinstance(body, Container)
return HSplit([
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_LEFT, token=Token.Window.Border)),
TokenListToolbar(
get_tokens=lambda cli: [(Token.Window.Title, ' %s ' % title)],
align_center=True,
default_char=Char(BORDER.HORIZONTAL, Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_RIGHT, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
body,
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_LEFT, token=Token.Window.Border)),
Window(height=D.exact(1),
content=FillControl(BORDER.HORIZONTAL, token=Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_RIGHT, token=Token.Window.Border)),
]),
])
def create_layout(python_input, history_mapping):
"""
Create and return a `Container` instance for the history
application.
"""
processors = [
HighlightSearchProcessor(preview_search=True),
HighlightSelectionProcessor()]
help_window = create_popup_window(
title='History Help',
body=Window(
content=BufferControl(
buffer_name=HELP_BUFFER,
default_char=Char(token=Token),
lexer=PygmentsLexer(RstLexer),
input_processors=processors),
right_margins=[ScrollbarMargin()],
scroll_offsets=ScrollOffsets(top=2, bottom=2)))
return HSplit([
# Top title bar.
TokenListToolbar(
get_tokens=_get_top_toolbar_tokens,
align_center=True,
default_char=Char(' ', Token.Toolbar.Status)),
FloatContainer(
content=VSplit([
# Left side: history.
Window(
content=BufferControl(
buffer_name=HISTORY_BUFFER,
lexer=PygmentsLexer(PythonLexer),
input_processors=processors),
wrap_lines=False,
left_margins=[HistoryMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
# Separator.
Window(width=D.exact(1),
content=FillControl(BORDER.LIGHT_VERTICAL, token=Token.Separator)),
# Right side: result.
Window(
content=BufferControl(
buffer_name=DEFAULT_BUFFER,
input_processors=processors + [GrayExistingText(history_mapping)],
lexer=PygmentsLexer(PythonLexer)),
wrap_lines=False,
left_margins=[ResultMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
]),
floats=[
# Help text as a float.
Float(width=60, top=3, bottom=2,
content=ConditionalContainer(
# (We use InFocusStack, because it's possible to search
# through the help text as well, and at that point the search
# buffer has the focus.)
content=help_window, filter=InFocusStack(HELP_BUFFER))),
]
),
# Bottom toolbars.
ArgToolbar(),
SearchToolbar(),
TokenListToolbar(
get_tokens=partial(_get_bottom_toolbar_tokens, python_input=python_input),
default_char=Char(' ', Token.Toolbar.Status)),
])
def _get_top_toolbar_tokens(cli):
return [(Token.Toolbar.Status.Title, 'History browser - Insert from history')]
def _get_bottom_toolbar_tokens(cli, python_input):
@if_mousedown
def f1(cli, mouse_event):
_toggle_help(cli)
@if_mousedown
def tab(cli, mouse_event):
_select_other_window(cli)
return [
(Token.Toolbar.Status, ' ')
] + get_inputmode_tokens(cli, python_input) + [
(Token.Toolbar.Status, ' '),
(Token.Toolbar.Status.Key, '[Space]'),
(Token.Toolbar.Status, ' Toggle '),
(Token.Toolbar.Status.Key, '[Tab]', tab),
(Token.Toolbar.Status, ' Focus ', tab),
(Token.Toolbar.Status.Key, '[Enter]'),
(Token.Toolbar.Status, ' Accept '),
(Token.Toolbar.Status.Key, '[F1]', f1),
(Token.Toolbar.Status, ' Help ', f1),
]
class HistoryMargin(Margin):
"""
Margin for the history buffer.
This displays a green bar for the selected entries.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[HISTORY_BUFFER].document
lines_starting_new_entries = self.history_mapping.lines_starting_new_entries
selected_lines = self.history_mapping.selected_lines
current_lineno = document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
# Show stars at the start of each entry.
# (Visualises multiline entries.)
if line_number in lines_starting_new_entries:
char = '*'
else:
char = ' '
if line_number in selected_lines:
t = Token.History.Line.Selected
else:
t = Token.History.Line
if line_number == current_lineno:
t = t.Current
result.append((t, char))
result.append((Token, '\n'))
return result
class ResultMargin(Margin):
"""
The margin to be shown in the result pane.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[DEFAULT_BUFFER].document
current_lineno = document.cursor_position_row
offset = self.history_mapping.result_line_offset #original_document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
if (line_number is None or line_number < offset or
line_number >= offset + len(self.history_mapping.selected_lines)):
t = Token
elif line_number == current_lineno:
t = Token.History.Line.Selected.Current
else:
t = Token.History.Line.Selected
result.append((t, ' '))
result.append((Token, '\n'))
return result
def invalidation_hash(self, cli, document):
return document.cursor_position_row
class GrayExistingText(Processor):
"""
Turn the existing input, before and after the inserted code gray.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
self._lines_before = len(history_mapping.original_document.text_before_cursor.splitlines())
def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
if (lineno < self._lines_before or
lineno >= self._lines_before + len(self.history_mapping.selected_lines)):
text = token_list_to_text(tokens)
return Transformation(tokens=[(Token.History.ExistingInput, text)])
else:
return Transformation(tokens=tokens)
class HistoryMapping(object):
"""
Keep a list of all the lines from the history and the selected lines.
"""
def __init__(self, python_history, original_document):
self.python_history = python_history
self.original_document = original_document
self.lines_starting_new_entries = set()
self.selected_lines = set()
# Process history.
history_lines = []
for entry_nr, entry in list(enumerate(python_history))[-HISTORY_COUNT:]:
self.lines_starting_new_entries.add(len(history_lines))
for line in entry.splitlines():
history_lines.append(line)
if len(python_history) > HISTORY_COUNT:
history_lines[0] = '# *** History has been truncated to %s lines ***' % HISTORY_COUNT
self.history_lines = history_lines
self.concatenated_history = '\n'.join(history_lines)
# Line offset.
if self.original_document.text_before_cursor:
self.result_line_offset = self.original_document.cursor_position_row + 1
else:
self.result_line_offset = 0
def get_new_document(self, cursor_pos=None):
"""
Create a `Document` instance that contains the resulting text.
"""
lines = []
# Original text, before cursor.
if self.original_document.text_before_cursor:
lines.append(self.original_document.text_before_cursor)
# Selected entries from the history.
for line_no in sorted(self.selected_lines):
lines.append(self.history_lines[line_no])
# Original text, after cursor.
if self.original_document.text_after_cursor:
lines.append(self.original_document.text_after_cursor)
# Create `Document` with cursor at the right position.
text = '\n'.join(lines)
if cursor_pos is not None and cursor_pos > len(text):
cursor_pos = len(text)
return Document(text, cursor_pos)
def update_default_buffer(self, cli):
b = cli.buffers[DEFAULT_BUFFER]
b.set_document(
self.get_new_document(b.cursor_position), bypass_readonly=True)
def _toggle_help(cli):
" Display/hide help. "
if cli.current_buffer_name == HELP_BUFFER:
cli.pop_focus()
else:
cli.push_focus(HELP_BUFFER)
def _select_other_window(cli):
" Toggle focus between left/right window. "
if cli.current_buffer_name == HISTORY_BUFFER:
cli.focus(DEFAULT_BUFFER)
elif cli.current_buffer_name == DEFAULT_BUFFER:
cli.focus(HISTORY_BUFFER)
def create_key_bindings(python_input, history_mapping):
"""
Key bindings.
"""
registry = load_key_bindings(
enable_search=True,
enable_extra_page_navigation=True)
handle = registry.add_binding
@handle(' ', filter=HasFocus(HISTORY_BUFFER))
def _(event):
"""
Space: select/deselect line from history pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row
if line_no in history_mapping.selected_lines:
# Remove line.
history_mapping.selected_lines.remove(line_no)
history_mapping.update_default_buffer(event.cli)
else:
# Add line.
history_mapping.selected_lines.add(line_no)
history_mapping.update_default_buffer(event.cli)
# Update cursor position
default_buffer = event.cli.buffers[DEFAULT_BUFFER]
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
# Also move the cursor to the next line. (This way they can hold
# space to select a region.)
b.cursor_position = b.document.translate_row_col_to_index(line_no + 1, 0)
@handle(' ', filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.Delete, filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.ControlH, filter=HasFocus(DEFAULT_BUFFER))
def _(event):
"""
Space: remove line from default pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row - history_mapping.result_line_offset
if line_no >= 0:
try:
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass # When `selected_lines` is an empty set.
else:
history_mapping.selected_lines.remove(history_lineno)
history_mapping.update_default_buffer(event.cli)
help_focussed = HasFocus(HELP_BUFFER)
main_buffer_focussed = HasFocus(HISTORY_BUFFER) | HasFocus(DEFAULT_BUFFER)
@handle(Keys.Tab, filter=main_buffer_focussed)
@handle(Keys.ControlX, filter=main_buffer_focussed, eager=True)
# Eager: ignore the Emacs [Ctrl-X Ctrl-X] binding.
@handle(Keys.ControlW, filter=main_buffer_focussed)
def _(event):
" Select other window. "
_select_other_window(event.cli)
@handle(Keys.F4)
def _(event):
" Switch between Emacs/Vi mode. "
python_input.vi_mode = not python_input.vi_mode
@handle(Keys.F1)
def _(event):
" Display/hide help. "
_toggle_help(event.cli)
@handle(Keys.ControlJ, filter=help_focussed)
@handle(Keys.ControlC, filter=help_focussed)
@handle(Keys.ControlG, filter=help_focussed)
@handle(Keys.Escape, filter=help_focussed)
def _(event):
" Leave help. "
event.cli.pop_focus()
@handle('q', filter=main_buffer_focussed)
@handle(Keys.F3, filter=main_buffer_focussed)
@handle(Keys.ControlC, filter=main_buffer_focussed)
@handle(Keys.ControlG, filter=main_buffer_focussed)
def _(event):
" Cancel and go back. "
event.cli.set_return_value(None)
enable_system_bindings = Condition(lambda cli: python_input.enable_system_bindings)
@handle(Keys.ControlZ, filter=enable_system_bindings)
def _(event):
" Suspend to background. "
event.cli.suspend_to_background()
return registry
def create_history_application(python_input, original_document):
"""
Create an `Application` for the history screen.
This has to be run as a sub application of `python_input`.
When this application runs and returns, it retuns the selected lines.
"""
history_mapping = HistoryMapping(python_input.history, original_document)
def default_buffer_pos_changed(_):
""" When the cursor changes in the default buffer. Synchronize with
history buffer. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == DEFAULT_BUFFER:
try:
line_no = default_buffer.document.cursor_position_row - \
history_mapping.result_line_offset
if line_no < 0: # When the cursor is above the inserted region.
raise IndexError
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass
else:
history_buffer.cursor_position = \
history_buffer.document.translate_row_col_to_index(history_lineno, 0)
def history_buffer_pos_changed(_):
""" When the cursor changes in the history buffer. Synchronize. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == HISTORY_BUFFER:
line_no = history_buffer.document.cursor_position_row
if line_no in history_mapping.selected_lines:
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
history_buffer = Buffer(
initial_document=Document(history_mapping.concatenated_history),
on_cursor_position_changed=history_buffer_pos_changed,
accept_action=AcceptAction(
lambda cli, buffer: cli.set_return_value(default_buffer.document)),
read_only=True)
default_buffer = Buffer(
initial_document=history_mapping.get_new_document(),
on_cursor_position_changed=default_buffer_pos_changed,
read_only=True)
help_buffer = Buffer(
initial_document=Document(HELP_TEXT, 0),
accept_action=AcceptAction.IGNORE,
read_only=True
)
buffer_mapping = BufferMapping({
HISTORY_BUFFER: history_buffer,
DEFAULT_BUFFER: default_buffer,
HELP_BUFFER: help_buffer,
}, initial=HISTORY_BUFFER)
application = Application(
layout=create_layout(python_input, history_mapping),
use_alternate_screen=True,
buffers=buffer_mapping,
style=python_input._current_style,
mouse_support=Condition(lambda cli: python_input.enable_mouse_support),
key_bindings_registry=create_key_bindings(python_input, history_mapping)
)
return application | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.259/Olde/rp 11.48.10 PM/rp_ptpython/history_browser.py | 0.754101 | 0.161982 | history_browser.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.mouse_events import MouseEventTypes
import re
__all__ = (
'has_unclosed_brackets',
'get_jedi_script_from_document',
'document_is_multiline_python',
)
def has_unclosed_brackets(text):
"""
Starting at the end of the string. If we find an opening bracket
for which we didn't had a closing one yet, return True.
"""
stack = []
# Ignore braces inside strings
text = re.sub(r'''('[^']*'|"[^"]*")''', '', text) # XXX: handle escaped quotes.!
for c in reversed(text):
if c in '])}':
stack.append(c)
elif c in '[({':
if stack:
if ((c == '[' and stack[-1] == ']') or
(c == '{' and stack[-1] == '}') or
(c == '(' and stack[-1] == ')')):
stack.pop()
else:
# Opening bracket for which we didn't had a closing one.
return True
return False
def get_jedi_script_from_document(document, locals, globals):
import jedi # We keep this import in-line, to improve start-up time.
# Importing Jedi is 'slow'.
try:
return jedi.Interpreter(
document.text,
column=document.cursor_position_col,
line=document.cursor_position_row + 1,
path='input-text',
namespaces=[locals, globals])
except ValueError:
# Invalid cursor position.
# ValueError('`column` parameter is not in a valid range.')
return None
except AttributeError:
# Workaround for #65: https://github.com/jonathanslenders/python-prompt-toolkit/issues/65
# See also: https://github.com/davidhalter/jedi/issues/508
return None
except IndexError:
# Workaround Jedi issue #514: for https://github.com/davidhalter/jedi/issues/514
return None
except KeyError:
# Workaroud for a crash when the input is "u'", the start of a unicode string.
return None
except Exception:
# Workaround for: https://github.com/jonathanslenders/ptpython/issues/91
return None
_multiline_string_delims = re.compile('''[']{3}|["]{3}''')
def document_is_multiline_python(document):
"""
Determine whether this is a multiline Python document.
"""
def ends_in_multiline_string():
"""
``True`` if we're inside a multiline string at the end of the text.
"""
delims = _multiline_string_delims.findall(document.text)
opening = None
for delim in delims:
if opening is None:
opening = delim
elif delim == opening:
opening = None
return bool(opening)
if '\n' in document.text or ends_in_multiline_string():
return True
def line_ends_with_colon():
return document.current_line.rstrip()[-1:] == ':'
# If we just typed a colon, or still have open brackets, always insert a real newline.
if line_ends_with_colon() or \
(document.is_cursor_at_the_end and
has_unclosed_brackets(document.text_before_cursor)) or \
document.text.startswith('@'):
return True
# If the character before the cursor is a backslash (line continuation
# char), insert a new line.
elif document.text_before_cursor[-1:] == '\\':
return True
return False
def if_mousedown(handler):
"""
Decorator for mouse handlers.
Only handle event when the user pressed mouse down.
(When applied to a token list. Scroll events will bubble up and are handled
by the Window.)
"""
def handle_if_mouse_down(cli, mouse_event):
if mouse_event.event_type == MouseEventTypes.MOUSE_DOWN:
return handler(cli, mouse_event)
else:
return NotImplemented
return handle_if_mouse_down | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.259/Olde/rp 11.48.10 PM/rp_ptpython/utils.py | 0.516839 | 0.157234 | utils.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.application import Application
from prompt_toolkit.buffer import Buffer, AcceptAction
from prompt_toolkit.buffer_mapping import BufferMapping
from prompt_toolkit.document import Document
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import Condition, HasFocus, InFocusStack
from prompt_toolkit.key_binding.defaults import load_key_bindings
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.containers import HSplit, VSplit, Window, FloatContainer, Float, ConditionalContainer, Container, ScrollOffsets
from prompt_toolkit.layout.controls import BufferControl, FillControl
from prompt_toolkit.layout.dimension import LayoutDimension as D
from prompt_toolkit.layout.lexers import PygmentsLexer
from prompt_toolkit.layout.margins import Margin, ScrollbarMargin
from prompt_toolkit.layout.processors import Processor, Transformation, HighlightSearchProcessor, HighlightSelectionProcessor
from prompt_toolkit.layout.screen import Char
from prompt_toolkit.layout.toolbars import ArgToolbar, SearchToolbar
from prompt_toolkit.layout.toolbars import TokenListToolbar
from prompt_toolkit.layout.utils import token_list_to_text
from pygments.lexers import RstLexer
from pygments.token import Token
from .utils import if_mousedown
from rp.rp_ptpython.layout import get_inputmode_tokens
from functools import partial
import six
if six.PY2:
from pygments.lexers import PythonLexer
else:
from pygments.lexers import Python3Lexer as PythonLexer
HISTORY_BUFFER = 'HISTORY_BUFFER'
HELP_BUFFER = 'HELP_BUFFER'
HISTORY_COUNT = 2000
__all__ = (
'create_history_application',
)
HELP_TEXT = """
This interface is meant to select multiple lines from the
history and execute them together.
Typical usage
-------------
1. Move the ``cursor up`` in the history pane, until the
cursor is on the first desired line.
2. Hold down the ``space bar``, or press it multiple
times. Each time it will select one line and move to
the next one. Each selected line will appear on the
right side.
3. When all the required lines are displayed on the right
side, press ``Enter``. This will go back to the Python
REPL and show these lines as the current input. They
can still be edited from there.
Key bindings
------------
Many Emacs and Vi navigation key bindings should work.
Press ``F4`` to switch between Emacs and Vi mode.
Additional bindings:
- ``Space``: Select or delect a line.
- ``Tab``: Move the focus between the history and input
pane. (Alternative: ``Ctrl-W``)
- ``Ctrl-C``: Cancel. Ignore the result and go back to
the REPL. (Alternatives: ``q`` and ``Control-G``.)
- ``Enter``: Accept the result and go back to the REPL.
- ``F1``: Show/hide help. Press ``Enter`` to quit this
help message.
Further, remember that searching works like in Emacs
(using ``Ctrl-R``) or Vi (using ``/``).
"""
class BORDER:
" Box drawing characters. "
HORIZONTAL = '\u2501'
VERTICAL = '\u2503'
TOP_LEFT = '\u250f'
TOP_RIGHT = '\u2513'
BOTTOM_LEFT = '\u2517'
BOTTOM_RIGHT = '\u251b'
LIGHT_VERTICAL = '\u2502'
def create_popup_window(title, body):
"""
Return the layout for a pop-up window. It consists of a title bar showing
the `title` text, and a body layout. The window is surrounded by borders.
"""
assert isinstance(title, six.text_type)
assert isinstance(body, Container)
return HSplit([
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_LEFT, token=Token.Window.Border)),
TokenListToolbar(
get_tokens=lambda cli: [(Token.Window.Title, ' %s ' % title)],
align_center=True,
default_char=Char(BORDER.HORIZONTAL, Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_RIGHT, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
body,
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_LEFT, token=Token.Window.Border)),
Window(height=D.exact(1),
content=FillControl(BORDER.HORIZONTAL, token=Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_RIGHT, token=Token.Window.Border)),
]),
])
def create_layout(python_input, history_mapping):
"""
Create and return a `Container` instance for the history
application.
"""
processors = [
HighlightSearchProcessor(preview_search=True),
HighlightSelectionProcessor()]
help_window = create_popup_window(
title='History Help',
body=Window(
content=BufferControl(
buffer_name=HELP_BUFFER,
default_char=Char(token=Token),
lexer=PygmentsLexer(RstLexer),
input_processors=processors),
right_margins=[ScrollbarMargin()],
scroll_offsets=ScrollOffsets(top=2, bottom=2)))
return HSplit([
# Top title bar.
TokenListToolbar(
get_tokens=_get_top_toolbar_tokens,
align_center=True,
default_char=Char(' ', Token.Toolbar.Status)),
FloatContainer(
content=VSplit([
# Left side: history.
Window(
content=BufferControl(
buffer_name=HISTORY_BUFFER,
lexer=PygmentsLexer(PythonLexer),
input_processors=processors),
wrap_lines=False,
left_margins=[HistoryMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
# Separator.
Window(width=D.exact(1),
content=FillControl(BORDER.LIGHT_VERTICAL, token=Token.Separator)),
# Right side: result.
Window(
content=BufferControl(
buffer_name=DEFAULT_BUFFER,
input_processors=processors + [GrayExistingText(history_mapping)],
lexer=PygmentsLexer(PythonLexer)),
wrap_lines=False,
left_margins=[ResultMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
]),
floats=[
# Help text as a float.
Float(width=60, top=3, bottom=2,
content=ConditionalContainer(
# (We use InFocusStack, because it's possible to search
# through the help text as well, and at that point the search
# buffer has the focus.)
content=help_window, filter=InFocusStack(HELP_BUFFER))),
]
),
# Bottom toolbars.
ArgToolbar(),
SearchToolbar(),
TokenListToolbar(
get_tokens=partial(_get_bottom_toolbar_tokens, python_input=python_input),
default_char=Char(' ', Token.Toolbar.Status)),
])
def _get_top_toolbar_tokens(cli):
return [(Token.Toolbar.Status.Title, 'History browser - Insert from history')]
def _get_bottom_toolbar_tokens(cli, python_input):
@if_mousedown
def f1(cli, mouse_event):
_toggle_help(cli)
@if_mousedown
def tab(cli, mouse_event):
_select_other_window(cli)
return [
(Token.Toolbar.Status, ' ')
] + get_inputmode_tokens(cli, python_input) + [
(Token.Toolbar.Status, ' '),
(Token.Toolbar.Status.Key, '[Space]'),
(Token.Toolbar.Status, ' Toggle '),
(Token.Toolbar.Status.Key, '[Tab]', tab),
(Token.Toolbar.Status, ' Focus ', tab),
(Token.Toolbar.Status.Key, '[Enter]'),
(Token.Toolbar.Status, ' Accept '),
(Token.Toolbar.Status.Key, '[F1]', f1),
(Token.Toolbar.Status, ' Help ', f1),
]
class HistoryMargin(Margin):
"""
Margin for the history buffer.
This displays a green bar for the selected entries.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[HISTORY_BUFFER].document
lines_starting_new_entries = self.history_mapping.lines_starting_new_entries
selected_lines = self.history_mapping.selected_lines
current_lineno = document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
# Show stars at the start of each entry.
# (Visualises multiline entries.)
if line_number in lines_starting_new_entries:
char = '*'
else:
char = ' '
if line_number in selected_lines:
t = Token.History.Line.Selected
else:
t = Token.History.Line
if line_number == current_lineno:
t = t.Current
result.append((t, char))
result.append((Token, '\n'))
return result
class ResultMargin(Margin):
"""
The margin to be shown in the result pane.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[DEFAULT_BUFFER].document
current_lineno = document.cursor_position_row
offset = self.history_mapping.result_line_offset #original_document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
if (line_number is None or line_number < offset or
line_number >= offset + len(self.history_mapping.selected_lines)):
t = Token
elif line_number == current_lineno:
t = Token.History.Line.Selected.Current
else:
t = Token.History.Line.Selected
result.append((t, ' '))
result.append((Token, '\n'))
return result
def invalidation_hash(self, cli, document):
return document.cursor_position_row
class GrayExistingText(Processor):
"""
Turn the existing input, before and after the inserted code gray.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
self._lines_before = len(history_mapping.original_document.text_before_cursor.splitlines())
def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
if (lineno < self._lines_before or
lineno >= self._lines_before + len(self.history_mapping.selected_lines)):
text = token_list_to_text(tokens)
return Transformation(tokens=[(Token.History.ExistingInput, text)])
else:
return Transformation(tokens=tokens)
class HistoryMapping(object):
"""
Keep a list of all the lines from the history and the selected lines.
"""
def __init__(self, python_history, original_document):
self.python_history = python_history
self.original_document = original_document
self.lines_starting_new_entries = set()
self.selected_lines = set()
# Process history.
history_lines = []
for entry_nr, entry in list(enumerate(python_history))[-HISTORY_COUNT:]:
self.lines_starting_new_entries.add(len(history_lines))
for line in entry.splitlines():
history_lines.append(line)
if len(python_history) > HISTORY_COUNT:
history_lines[0] = '# *** History has been truncated to %s lines ***' % HISTORY_COUNT
self.history_lines = history_lines
self.concatenated_history = '\n'.join(history_lines)
# Line offset.
if self.original_document.text_before_cursor:
self.result_line_offset = self.original_document.cursor_position_row + 1
else:
self.result_line_offset = 0
def get_new_document(self, cursor_pos=None):
"""
Create a `Document` instance that contains the resulting text.
"""
lines = []
# Original text, before cursor.
if self.original_document.text_before_cursor:
lines.append(self.original_document.text_before_cursor)
# Selected entries from the history.
for line_no in sorted(self.selected_lines):
lines.append(self.history_lines[line_no])
# Original text, after cursor.
if self.original_document.text_after_cursor:
lines.append(self.original_document.text_after_cursor)
# Create `Document` with cursor at the right position.
text = '\n'.join(lines)
if cursor_pos is not None and cursor_pos > len(text):
cursor_pos = len(text)
return Document(text, cursor_pos)
def update_default_buffer(self, cli):
b = cli.buffers[DEFAULT_BUFFER]
b.set_document(
self.get_new_document(b.cursor_position), bypass_readonly=True)
def _toggle_help(cli):
" Display/hide help. "
if cli.current_buffer_name == HELP_BUFFER:
cli.pop_focus()
else:
cli.push_focus(HELP_BUFFER)
def _select_other_window(cli):
" Toggle focus between left/right window. "
if cli.current_buffer_name == HISTORY_BUFFER:
cli.focus(DEFAULT_BUFFER)
elif cli.current_buffer_name == DEFAULT_BUFFER:
cli.focus(HISTORY_BUFFER)
def create_key_bindings(python_input, history_mapping):
"""
Key bindings.
"""
registry = load_key_bindings(
enable_search=True,
enable_extra_page_navigation=True)
handle = registry.add_binding
@handle(' ', filter=HasFocus(HISTORY_BUFFER))
def _(event):
"""
Space: select/deselect line from history pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row
if line_no in history_mapping.selected_lines:
# Remove line.
history_mapping.selected_lines.remove(line_no)
history_mapping.update_default_buffer(event.cli)
else:
# Add line.
history_mapping.selected_lines.add(line_no)
history_mapping.update_default_buffer(event.cli)
# Update cursor position
default_buffer = event.cli.buffers[DEFAULT_BUFFER]
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
# Also move the cursor to the next line. (This way they can hold
# space to select a region.)
b.cursor_position = b.document.translate_row_col_to_index(line_no + 1, 0)
@handle(' ', filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.Delete, filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.ControlH, filter=HasFocus(DEFAULT_BUFFER))
def _(event):
"""
Space: remove line from default pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row - history_mapping.result_line_offset
if line_no >= 0:
try:
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass # When `selected_lines` is an empty set.
else:
history_mapping.selected_lines.remove(history_lineno)
history_mapping.update_default_buffer(event.cli)
help_focussed = HasFocus(HELP_BUFFER)
main_buffer_focussed = HasFocus(HISTORY_BUFFER) | HasFocus(DEFAULT_BUFFER)
@handle(Keys.Tab, filter=main_buffer_focussed)
@handle(Keys.ControlX, filter=main_buffer_focussed, eager=True)
# Eager: ignore the Emacs [Ctrl-X Ctrl-X] binding.
@handle(Keys.ControlW, filter=main_buffer_focussed)
def _(event):
" Select other window. "
_select_other_window(event.cli)
@handle(Keys.F4)
def _(event):
" Switch between Emacs/Vi mode. "
python_input.vi_mode = not python_input.vi_mode
@handle(Keys.F1)
def _(event):
" Display/hide help. "
_toggle_help(event.cli)
@handle(Keys.ControlJ, filter=help_focussed)
@handle(Keys.ControlC, filter=help_focussed)
@handle(Keys.ControlG, filter=help_focussed)
@handle(Keys.Escape, filter=help_focussed)
def _(event):
" Leave help. "
event.cli.pop_focus()
@handle('q', filter=main_buffer_focussed)
@handle(Keys.F3, filter=main_buffer_focussed)
@handle(Keys.ControlC, filter=main_buffer_focussed)
@handle(Keys.ControlG, filter=main_buffer_focussed)
def _(event):
" Cancel and go back. "
event.cli.set_return_value(None)
enable_system_bindings = Condition(lambda cli: python_input.enable_system_bindings)
@handle(Keys.ControlZ, filter=enable_system_bindings)
def _(event):
" Suspend to background. "
event.cli.suspend_to_background()
return registry
def create_history_application(python_input, original_document):
"""
Create an `Application` for the history screen.
This has to be run as a sub application of `python_input`.
When this application runs and returns, it retuns the selected lines.
"""
history_mapping = HistoryMapping(python_input.history, original_document)
def default_buffer_pos_changed(_):
""" When the cursor changes in the default buffer. Synchronize with
history buffer. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == DEFAULT_BUFFER:
try:
line_no = default_buffer.document.cursor_position_row - \
history_mapping.result_line_offset
if line_no < 0: # When the cursor is above the inserted region.
raise IndexError
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass
else:
history_buffer.cursor_position = \
history_buffer.document.translate_row_col_to_index(history_lineno, 0)
def history_buffer_pos_changed(_):
""" When the cursor changes in the history buffer. Synchronize. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == HISTORY_BUFFER:
line_no = history_buffer.document.cursor_position_row
if line_no in history_mapping.selected_lines:
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
history_buffer = Buffer(
initial_document=Document(history_mapping.concatenated_history),
on_cursor_position_changed=history_buffer_pos_changed,
accept_action=AcceptAction(
lambda cli, buffer: cli.set_return_value(default_buffer.document)),
read_only=True)
default_buffer = Buffer(
initial_document=history_mapping.get_new_document(),
on_cursor_position_changed=default_buffer_pos_changed,
read_only=True)
help_buffer = Buffer(
initial_document=Document(HELP_TEXT, 0),
accept_action=AcceptAction.IGNORE,
read_only=True
)
buffer_mapping = BufferMapping({
HISTORY_BUFFER: history_buffer,
DEFAULT_BUFFER: default_buffer,
HELP_BUFFER: help_buffer,
}, initial=HISTORY_BUFFER)
application = Application(
layout=create_layout(python_input, history_mapping),
use_alternate_screen=True,
buffers=buffer_mapping,
style=python_input._current_style,
mouse_support=Condition(lambda cli: python_input.enable_mouse_support),
key_bindings_registry=create_key_bindings(python_input, history_mapping)
)
return application | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.259/Olde/rp 5.45.01 PM/rp_ptpython/history_browser.py | 0.754101 | 0.161982 | history_browser.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.application import Application
from prompt_toolkit.buffer import Buffer, AcceptAction
from prompt_toolkit.buffer_mapping import BufferMapping
from prompt_toolkit.document import Document
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import Condition, HasFocus, InFocusStack
from prompt_toolkit.key_binding.defaults import load_key_bindings
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.containers import HSplit, VSplit, Window, FloatContainer, Float, ConditionalContainer, Container, ScrollOffsets
from prompt_toolkit.layout.controls import BufferControl, FillControl
from prompt_toolkit.layout.dimension import LayoutDimension as D
from prompt_toolkit.layout.lexers import PygmentsLexer
from prompt_toolkit.layout.margins import Margin, ScrollbarMargin
from prompt_toolkit.layout.processors import Processor, Transformation, HighlightSearchProcessor, HighlightSelectionProcessor
from prompt_toolkit.layout.screen import Char
from prompt_toolkit.layout.toolbars import ArgToolbar, SearchToolbar
from prompt_toolkit.layout.toolbars import TokenListToolbar
from prompt_toolkit.layout.utils import token_list_to_text
from pygments.lexers import RstLexer
from pygments.token import Token
from .utils import if_mousedown
from rp.rp_ptpython.layout import get_inputmode_tokens
from functools import partial
import six
if six.PY2:
from pygments.lexers import PythonLexer
else:
from pygments.lexers import Python3Lexer as PythonLexer
HISTORY_BUFFER = 'HISTORY_BUFFER'
HELP_BUFFER = 'HELP_BUFFER'
HISTORY_COUNT = 2000
__all__ = (
'create_history_application',
)
HELP_TEXT = """
This interface is meant to select multiple lines from the
history and execute them together.
Typical usage
-------------
1. Move the ``cursor up`` in the history pane, until the
cursor is on the first desired line.
2. Hold down the ``space bar``, or press it multiple
times. Each time it will select one line and move to
the next one. Each selected line will appear on the
right side.
3. When all the required lines are displayed on the right
side, press ``Enter``. This will go back to the Python
REPL and show these lines as the current input. They
can still be edited from there.
Key bindings
------------
Many Emacs and Vi navigation key bindings should work.
Press ``F4`` to switch between Emacs and Vi mode.
Additional bindings:
- ``Space``: Select or delect a line.
- ``Tab``: Move the focus between the history and input
pane. (Alternative: ``Ctrl-W``)
- ``Ctrl-C``: Cancel. Ignore the result and go back to
the REPL. (Alternatives: ``q`` and ``Control-G``.)
- ``Enter``: Accept the result and go back to the REPL.
- ``F1``: Show/hide help. Press ``Enter`` to quit this
help message.
Further, remember that searching works like in Emacs
(using ``Ctrl-R``) or Vi (using ``/``).
"""
class BORDER:
" Box drawing characters. "
HORIZONTAL = '\u2501'
VERTICAL = '\u2503'
TOP_LEFT = '\u250f'
TOP_RIGHT = '\u2513'
BOTTOM_LEFT = '\u2517'
BOTTOM_RIGHT = '\u251b'
LIGHT_VERTICAL = '\u2502'
def create_popup_window(title, body):
"""
Return the layout for a pop-up window. It consists of a title bar showing
the `title` text, and a body layout. The window is surrounded by borders.
"""
assert isinstance(title, six.text_type)
assert isinstance(body, Container)
return HSplit([
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_LEFT, token=Token.Window.Border)),
TokenListToolbar(
get_tokens=lambda cli: [(Token.Window.Title, ' %s ' % title)],
align_center=True,
default_char=Char(BORDER.HORIZONTAL, Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_RIGHT, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
body,
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_LEFT, token=Token.Window.Border)),
Window(height=D.exact(1),
content=FillControl(BORDER.HORIZONTAL, token=Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_RIGHT, token=Token.Window.Border)),
]),
])
def create_layout(python_input, history_mapping):
"""
Create and return a `Container` instance for the history
application.
"""
processors = [
HighlightSearchProcessor(preview_search=True),
HighlightSelectionProcessor()]
help_window = create_popup_window(
title='History Help',
body=Window(
content=BufferControl(
buffer_name=HELP_BUFFER,
default_char=Char(token=Token),
lexer=PygmentsLexer(RstLexer),
input_processors=processors),
right_margins=[ScrollbarMargin()],
scroll_offsets=ScrollOffsets(top=2, bottom=2)))
return HSplit([
# Top title bar.
TokenListToolbar(
get_tokens=_get_top_toolbar_tokens,
align_center=True,
default_char=Char(' ', Token.Toolbar.Status)),
FloatContainer(
content=VSplit([
# Left side: history.
Window(
content=BufferControl(
buffer_name=HISTORY_BUFFER,
lexer=PygmentsLexer(PythonLexer),
input_processors=processors),
wrap_lines=False,
left_margins=[HistoryMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
# Separator.
Window(width=D.exact(1),
content=FillControl(BORDER.LIGHT_VERTICAL, token=Token.Separator)),
# Right side: result.
Window(
content=BufferControl(
buffer_name=DEFAULT_BUFFER,
input_processors=processors + [GrayExistingText(history_mapping)],
lexer=PygmentsLexer(PythonLexer)),
wrap_lines=False,
left_margins=[ResultMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
]),
floats=[
# Help text as a float.
Float(width=60, top=3, bottom=2,
content=ConditionalContainer(
# (We use InFocusStack, because it's possible to search
# through the help text as well, and at that point the search
# buffer has the focus.)
content=help_window, filter=InFocusStack(HELP_BUFFER))),
]
),
# Bottom toolbars.
ArgToolbar(),
SearchToolbar(),
TokenListToolbar(
get_tokens=partial(_get_bottom_toolbar_tokens, python_input=python_input),
default_char=Char(' ', Token.Toolbar.Status)),
])
def _get_top_toolbar_tokens(cli):
return [(Token.Toolbar.Status.Title, 'History browser - Insert from history')]
def _get_bottom_toolbar_tokens(cli, python_input):
@if_mousedown
def f1(cli, mouse_event):
_toggle_help(cli)
@if_mousedown
def tab(cli, mouse_event):
_select_other_window(cli)
return [
(Token.Toolbar.Status, ' ')
] + get_inputmode_tokens(cli, python_input) + [
(Token.Toolbar.Status, ' '),
(Token.Toolbar.Status.Key, '[Space]'),
(Token.Toolbar.Status, ' Toggle '),
(Token.Toolbar.Status.Key, '[Tab]', tab),
(Token.Toolbar.Status, ' Focus ', tab),
(Token.Toolbar.Status.Key, '[Enter]'),
(Token.Toolbar.Status, ' Accept '),
(Token.Toolbar.Status.Key, '[F1]', f1),
(Token.Toolbar.Status, ' Help ', f1),
]
class HistoryMargin(Margin):
"""
Margin for the history buffer.
This displays a green bar for the selected entries.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[HISTORY_BUFFER].document
lines_starting_new_entries = self.history_mapping.lines_starting_new_entries
selected_lines = self.history_mapping.selected_lines
current_lineno = document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
# Show stars at the start of each entry.
# (Visualises multiline entries.)
if line_number in lines_starting_new_entries:
char = '*'
else:
char = ' '
if line_number in selected_lines:
t = Token.History.Line.Selected
else:
t = Token.History.Line
if line_number == current_lineno:
t = t.Current
result.append((t, char))
result.append((Token, '\n'))
return result
class ResultMargin(Margin):
"""
The margin to be shown in the result pane.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[DEFAULT_BUFFER].document
current_lineno = document.cursor_position_row
offset = self.history_mapping.result_line_offset #original_document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
if (line_number is None or line_number < offset or
line_number >= offset + len(self.history_mapping.selected_lines)):
t = Token
elif line_number == current_lineno:
t = Token.History.Line.Selected.Current
else:
t = Token.History.Line.Selected
result.append((t, ' '))
result.append((Token, '\n'))
return result
def invalidation_hash(self, cli, document):
return document.cursor_position_row
class GrayExistingText(Processor):
"""
Turn the existing input, before and after the inserted code gray.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
self._lines_before = len(history_mapping.original_document.text_before_cursor.splitlines())
def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
if (lineno < self._lines_before or
lineno >= self._lines_before + len(self.history_mapping.selected_lines)):
text = token_list_to_text(tokens)
return Transformation(tokens=[(Token.History.ExistingInput, text)])
else:
return Transformation(tokens=tokens)
class HistoryMapping(object):
"""
Keep a list of all the lines from the history and the selected lines.
"""
def __init__(self, python_history, original_document):
self.python_history = python_history
self.original_document = original_document
self.lines_starting_new_entries = set()
self.selected_lines = set()
# Process history.
history_lines = []
for entry_nr, entry in list(enumerate(python_history))[-HISTORY_COUNT:]:
self.lines_starting_new_entries.add(len(history_lines))
for line in entry.splitlines():
history_lines.append(line)
if len(python_history) > HISTORY_COUNT:
history_lines[0] = '# *** History has been truncated to %s lines ***' % HISTORY_COUNT
self.history_lines = history_lines
self.concatenated_history = '\n'.join(history_lines)
# Line offset.
if self.original_document.text_before_cursor:
self.result_line_offset = self.original_document.cursor_position_row + 1
else:
self.result_line_offset = 0
def get_new_document(self, cursor_pos=None):
"""
Create a `Document` instance that contains the resulting text.
"""
lines = []
# Original text, before cursor.
if self.original_document.text_before_cursor:
lines.append(self.original_document.text_before_cursor)
# Selected entries from the history.
for line_no in sorted(self.selected_lines):
lines.append(self.history_lines[line_no])
# Original text, after cursor.
if self.original_document.text_after_cursor:
lines.append(self.original_document.text_after_cursor)
# Create `Document` with cursor at the right position.
text = '\n'.join(lines)
if cursor_pos is not None and cursor_pos > len(text):
cursor_pos = len(text)
return Document(text, cursor_pos)
def update_default_buffer(self, cli):
b = cli.buffers[DEFAULT_BUFFER]
b.set_document(
self.get_new_document(b.cursor_position), bypass_readonly=True)
def _toggle_help(cli):
" Display/hide help. "
if cli.current_buffer_name == HELP_BUFFER:
cli.pop_focus()
else:
cli.push_focus(HELP_BUFFER)
def _select_other_window(cli):
" Toggle focus between left/right window. "
if cli.current_buffer_name == HISTORY_BUFFER:
cli.focus(DEFAULT_BUFFER)
elif cli.current_buffer_name == DEFAULT_BUFFER:
cli.focus(HISTORY_BUFFER)
def create_key_bindings(python_input, history_mapping):
"""
Key bindings.
"""
registry = load_key_bindings(
enable_search=True,
enable_extra_page_navigation=True)
handle = registry.add_binding
@handle(' ', filter=HasFocus(HISTORY_BUFFER))
def _(event):
"""
Space: select/deselect line from history pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row
if line_no in history_mapping.selected_lines:
# Remove line.
history_mapping.selected_lines.remove(line_no)
history_mapping.update_default_buffer(event.cli)
else:
# Add line.
history_mapping.selected_lines.add(line_no)
history_mapping.update_default_buffer(event.cli)
# Update cursor position
default_buffer = event.cli.buffers[DEFAULT_BUFFER]
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
# Also move the cursor to the next line. (This way they can hold
# space to select a region.)
b.cursor_position = b.document.translate_row_col_to_index(line_no + 1, 0)
@handle(' ', filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.Delete, filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.ControlH, filter=HasFocus(DEFAULT_BUFFER))
def _(event):
"""
Space: remove line from default pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row - history_mapping.result_line_offset
if line_no >= 0:
try:
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass # When `selected_lines` is an empty set.
else:
history_mapping.selected_lines.remove(history_lineno)
history_mapping.update_default_buffer(event.cli)
help_focussed = HasFocus(HELP_BUFFER)
main_buffer_focussed = HasFocus(HISTORY_BUFFER) | HasFocus(DEFAULT_BUFFER)
@handle(Keys.Tab, filter=main_buffer_focussed)
@handle(Keys.ControlX, filter=main_buffer_focussed, eager=True)
# Eager: ignore the Emacs [Ctrl-X Ctrl-X] binding.
@handle(Keys.ControlW, filter=main_buffer_focussed)
def _(event):
" Select other window. "
_select_other_window(event.cli)
@handle(Keys.F4)
def _(event):
" Switch between Emacs/Vi mode. "
python_input.vi_mode = not python_input.vi_mode
@handle(Keys.F1)
def _(event):
" Display/hide help. "
_toggle_help(event.cli)
@handle(Keys.ControlJ, filter=help_focussed)
@handle(Keys.ControlC, filter=help_focussed)
@handle(Keys.ControlG, filter=help_focussed)
@handle(Keys.Escape, filter=help_focussed)
def _(event):
" Leave help. "
event.cli.pop_focus()
@handle('q', filter=main_buffer_focussed)
@handle(Keys.F3, filter=main_buffer_focussed)
@handle(Keys.ControlC, filter=main_buffer_focussed)
@handle(Keys.ControlG, filter=main_buffer_focussed)
def _(event):
" Cancel and go back. "
event.cli.set_return_value(None)
enable_system_bindings = Condition(lambda cli: python_input.enable_system_bindings)
@handle(Keys.ControlZ, filter=enable_system_bindings)
def _(event):
" Suspend to background. "
event.cli.suspend_to_background()
return registry
def create_history_application(python_input, original_document):
"""
Create an `Application` for the history screen.
This has to be run as a sub application of `python_input`.
When this application runs and returns, it retuns the selected lines.
"""
history_mapping = HistoryMapping(python_input.history, original_document)
def default_buffer_pos_changed(_):
""" When the cursor changes in the default buffer. Synchronize with
history buffer. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == DEFAULT_BUFFER:
try:
line_no = default_buffer.document.cursor_position_row - \
history_mapping.result_line_offset
if line_no < 0: # When the cursor is above the inserted region.
raise IndexError
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass
else:
history_buffer.cursor_position = \
history_buffer.document.translate_row_col_to_index(history_lineno, 0)
def history_buffer_pos_changed(_):
""" When the cursor changes in the history buffer. Synchronize. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == HISTORY_BUFFER:
line_no = history_buffer.document.cursor_position_row
if line_no in history_mapping.selected_lines:
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
history_buffer = Buffer(
initial_document=Document(history_mapping.concatenated_history),
on_cursor_position_changed=history_buffer_pos_changed,
accept_action=AcceptAction(
lambda cli, buffer: cli.set_return_value(default_buffer.document)),
read_only=True)
default_buffer = Buffer(
initial_document=history_mapping.get_new_document(),
on_cursor_position_changed=default_buffer_pos_changed,
read_only=True)
help_buffer = Buffer(
initial_document=Document(HELP_TEXT, 0),
accept_action=AcceptAction.IGNORE,
read_only=True
)
buffer_mapping = BufferMapping({
HISTORY_BUFFER: history_buffer,
DEFAULT_BUFFER: default_buffer,
HELP_BUFFER: help_buffer,
}, initial=HISTORY_BUFFER)
application = Application(
layout=create_layout(python_input, history_mapping),
use_alternate_screen=True,
buffers=buffer_mapping,
style=python_input._current_style,
mouse_support=Condition(lambda cli: python_input.enable_mouse_support),
key_bindings_registry=create_key_bindings(python_input, history_mapping)
)
return application | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.259/Olde/rp 5.38.10 PM/rp_ptpython/history_browser.py | 0.754101 | 0.161982 | history_browser.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.mouse_events import MouseEventTypes
import re
__all__ = (
'has_unclosed_brackets',
'get_jedi_script_from_document',
'document_is_multiline_python',
)
def has_unclosed_brackets(text):
"""
Starting at the end of the string. If we find an opening bracket
for which we didn't had a closing one yet, return True.
"""
stack = []
# Ignore braces inside strings
text = re.sub(r'''('[^']*'|"[^"]*")''', '', text) # XXX: handle escaped quotes.!
for c in reversed(text):
if c in '])}':
stack.append(c)
elif c in '[({':
if stack:
if ((c == '[' and stack[-1] == ']') or
(c == '{' and stack[-1] == '}') or
(c == '(' and stack[-1] == ')')):
stack.pop()
else:
# Opening bracket for which we didn't had a closing one.
return True
return False
def get_jedi_script_from_document(document, locals, globals):
import jedi # We keep this import in-line, to improve start-up time.
# Importing Jedi is 'slow'.
try:
return jedi.Interpreter(
document.text,
column=document.cursor_position_col,
line=document.cursor_position_row + 1,
path='input-text',
namespaces=[locals, globals])
except ValueError:
# Invalid cursor position.
# ValueError('`column` parameter is not in a valid range.')
return None
except AttributeError:
# Workaround for #65: https://github.com/jonathanslenders/python-prompt-toolkit/issues/65
# See also: https://github.com/davidhalter/jedi/issues/508
return None
except IndexError:
# Workaround Jedi issue #514: for https://github.com/davidhalter/jedi/issues/514
return None
except KeyError:
# Workaroud for a crash when the input is "u'", the start of a unicode string.
return None
except Exception:
# Workaround for: https://github.com/jonathanslenders/ptpython/issues/91
return None
_multiline_string_delims = re.compile('''[']{3}|["]{3}''')
def document_is_multiline_python(document):
"""
Determine whether this is a multiline Python document.
"""
def ends_in_multiline_string():
"""
``True`` if we're inside a multiline string at the end of the text.
"""
delims = _multiline_string_delims.findall(document.text)
opening = None
for delim in delims:
if opening is None:
opening = delim
elif delim == opening:
opening = None
return bool(opening)
if '\n' in document.text or ends_in_multiline_string():
return True
def line_ends_with_colon():
return document.current_line.rstrip()[-1:] == ':'
# If we just typed a colon, or still have open brackets, always insert a real newline.
if line_ends_with_colon() or \
(document.is_cursor_at_the_end and
has_unclosed_brackets(document.text_before_cursor)) or \
document.text.startswith('@'):
return True
# If the character before the cursor is a backslash (line continuation
# char), insert a new line.
elif document.text_before_cursor[-1:] == '\\':
return True
return False
def if_mousedown(handler):
"""
Decorator for mouse handlers.
Only handle event when the user pressed mouse down.
(When applied to a token list. Scroll events will bubble up and are handled
by the Window.)
"""
def handle_if_mouse_down(cli, mouse_event):
if mouse_event.event_type == MouseEventTypes.MOUSE_DOWN:
return handler(cli, mouse_event)
else:
return NotImplemented
return handle_if_mouse_down | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.259/Olde/rp 5.38.10 PM/rp_ptpython/utils.py | 0.516839 | 0.157234 | utils.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.application import Application
from prompt_toolkit.buffer import Buffer, AcceptAction
from prompt_toolkit.buffer_mapping import BufferMapping
from prompt_toolkit.document import Document
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import Condition, HasFocus, InFocusStack
from prompt_toolkit.key_binding.defaults import load_key_bindings
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.containers import HSplit, VSplit, Window, FloatContainer, Float, ConditionalContainer, Container, ScrollOffsets
from prompt_toolkit.layout.controls import BufferControl, FillControl
from prompt_toolkit.layout.dimension import LayoutDimension as D
from prompt_toolkit.layout.lexers import PygmentsLexer
from prompt_toolkit.layout.margins import Margin, ScrollbarMargin
from prompt_toolkit.layout.processors import Processor, Transformation, HighlightSearchProcessor, HighlightSelectionProcessor
from prompt_toolkit.layout.screen import Char
from prompt_toolkit.layout.toolbars import ArgToolbar, SearchToolbar
from prompt_toolkit.layout.toolbars import TokenListToolbar
from prompt_toolkit.layout.utils import token_list_to_text
from pygments.lexers import RstLexer
from pygments.token import Token
from .utils import if_mousedown
from rp.rp_ptpython.layout import get_inputmode_tokens
from functools import partial
import six
if six.PY2:
from pygments.lexers import PythonLexer
else:
from pygments.lexers import Python3Lexer as PythonLexer
HISTORY_BUFFER = 'HISTORY_BUFFER'
HELP_BUFFER = 'HELP_BUFFER'
HISTORY_COUNT = 2000
__all__ = (
'create_history_application',
)
HELP_TEXT = """
This interface is meant to select multiple lines from the
history and execute them together.
Typical usage
-------------
1. Move the ``cursor up`` in the history pane, until the
cursor is on the first desired line.
2. Hold down the ``space bar``, or press it multiple
times. Each time it will select one line and move to
the next one. Each selected line will appear on the
right side.
3. When all the required lines are displayed on the right
side, press ``Enter``. This will go back to the Python
REPL and show these lines as the current input. They
can still be edited from there.
Key bindings
------------
Many Emacs and Vi navigation key bindings should work.
Press ``F4`` to switch between Emacs and Vi mode.
Additional bindings:
- ``Space``: Select or delect a line.
- ``Tab``: Move the focus between the history and input
pane. (Alternative: ``Ctrl-W``)
- ``Ctrl-C``: Cancel. Ignore the result and go back to
the REPL. (Alternatives: ``q`` and ``Control-G``.)
- ``Enter``: Accept the result and go back to the REPL.
- ``F1``: Show/hide help. Press ``Enter`` to quit this
help message.
Further, remember that searching works like in Emacs
(using ``Ctrl-R``) or Vi (using ``/``).
"""
class BORDER:
" Box drawing characters. "
HORIZONTAL = '\u2501'
VERTICAL = '\u2503'
TOP_LEFT = '\u250f'
TOP_RIGHT = '\u2513'
BOTTOM_LEFT = '\u2517'
BOTTOM_RIGHT = '\u251b'
LIGHT_VERTICAL = '\u2502'
def create_popup_window(title, body):
"""
Return the layout for a pop-up window. It consists of a title bar showing
the `title` text, and a body layout. The window is surrounded by borders.
"""
assert isinstance(title, six.text_type)
assert isinstance(body, Container)
return HSplit([
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_LEFT, token=Token.Window.Border)),
TokenListToolbar(
get_tokens=lambda cli: [(Token.Window.Title, ' %s ' % title)],
align_center=True,
default_char=Char(BORDER.HORIZONTAL, Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_RIGHT, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
body,
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_LEFT, token=Token.Window.Border)),
Window(height=D.exact(1),
content=FillControl(BORDER.HORIZONTAL, token=Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_RIGHT, token=Token.Window.Border)),
]),
])
def create_layout(python_input, history_mapping):
"""
Create and return a `Container` instance for the history
application.
"""
processors = [
HighlightSearchProcessor(preview_search=True),
HighlightSelectionProcessor()]
help_window = create_popup_window(
title='History Help',
body=Window(
content=BufferControl(
buffer_name=HELP_BUFFER,
default_char=Char(token=Token),
lexer=PygmentsLexer(RstLexer),
input_processors=processors),
right_margins=[ScrollbarMargin()],
scroll_offsets=ScrollOffsets(top=2, bottom=2)))
return HSplit([
# Top title bar.
TokenListToolbar(
get_tokens=_get_top_toolbar_tokens,
align_center=True,
default_char=Char(' ', Token.Toolbar.Status)),
FloatContainer(
content=VSplit([
# Left side: history.
Window(
content=BufferControl(
buffer_name=HISTORY_BUFFER,
lexer=PygmentsLexer(PythonLexer),
input_processors=processors),
wrap_lines=False,
left_margins=[HistoryMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
# Separator.
Window(width=D.exact(1),
content=FillControl(BORDER.LIGHT_VERTICAL, token=Token.Separator)),
# Right side: result.
Window(
content=BufferControl(
buffer_name=DEFAULT_BUFFER,
input_processors=processors + [GrayExistingText(history_mapping)],
lexer=PygmentsLexer(PythonLexer)),
wrap_lines=False,
left_margins=[ResultMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
]),
floats=[
# Help text as a float.
Float(width=60, top=3, bottom=2,
content=ConditionalContainer(
# (We use InFocusStack, because it's possible to search
# through the help text as well, and at that point the search
# buffer has the focus.)
content=help_window, filter=InFocusStack(HELP_BUFFER))),
]
),
# Bottom toolbars.
ArgToolbar(),
SearchToolbar(),
TokenListToolbar(
get_tokens=partial(_get_bottom_toolbar_tokens, python_input=python_input),
default_char=Char(' ', Token.Toolbar.Status)),
])
def _get_top_toolbar_tokens(cli):
return [(Token.Toolbar.Status.Title, 'History browser - Insert from history')]
def _get_bottom_toolbar_tokens(cli, python_input):
@if_mousedown
def f1(cli, mouse_event):
_toggle_help(cli)
@if_mousedown
def tab(cli, mouse_event):
_select_other_window(cli)
return [
(Token.Toolbar.Status, ' ')
] + get_inputmode_tokens(cli, python_input) + [
(Token.Toolbar.Status, ' '),
(Token.Toolbar.Status.Key, '[Space]'),
(Token.Toolbar.Status, ' Toggle '),
(Token.Toolbar.Status.Key, '[Tab]', tab),
(Token.Toolbar.Status, ' Focus ', tab),
(Token.Toolbar.Status.Key, '[Enter]'),
(Token.Toolbar.Status, ' Accept '),
(Token.Toolbar.Status.Key, '[F1]', f1),
(Token.Toolbar.Status, ' Help ', f1),
]
class HistoryMargin(Margin):
"""
Margin for the history buffer.
This displays a green bar for the selected entries.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[HISTORY_BUFFER].document
lines_starting_new_entries = self.history_mapping.lines_starting_new_entries
selected_lines = self.history_mapping.selected_lines
current_lineno = document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
# Show stars at the start of each entry.
# (Visualises multiline entries.)
if line_number in lines_starting_new_entries:
char = '*'
else:
char = ' '
if line_number in selected_lines:
t = Token.History.Line.Selected
else:
t = Token.History.Line
if line_number == current_lineno:
t = t.Current
result.append((t, char))
result.append((Token, '\n'))
return result
class ResultMargin(Margin):
"""
The margin to be shown in the result pane.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[DEFAULT_BUFFER].document
current_lineno = document.cursor_position_row
offset = self.history_mapping.result_line_offset #original_document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
if (line_number is None or line_number < offset or
line_number >= offset + len(self.history_mapping.selected_lines)):
t = Token
elif line_number == current_lineno:
t = Token.History.Line.Selected.Current
else:
t = Token.History.Line.Selected
result.append((t, ' '))
result.append((Token, '\n'))
return result
def invalidation_hash(self, cli, document):
return document.cursor_position_row
class GrayExistingText(Processor):
"""
Turn the existing input, before and after the inserted code gray.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
self._lines_before = len(history_mapping.original_document.text_before_cursor.splitlines())
def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
if (lineno < self._lines_before or
lineno >= self._lines_before + len(self.history_mapping.selected_lines)):
text = token_list_to_text(tokens)
return Transformation(tokens=[(Token.History.ExistingInput, text)])
else:
return Transformation(tokens=tokens)
class HistoryMapping(object):
"""
Keep a list of all the lines from the history and the selected lines.
"""
def __init__(self, python_history, original_document):
self.python_history = python_history
self.original_document = original_document
self.lines_starting_new_entries = set()
self.selected_lines = set()
# Process history.
history_lines = []
for entry_nr, entry in list(enumerate(python_history))[-HISTORY_COUNT:]:
self.lines_starting_new_entries.add(len(history_lines))
for line in entry.splitlines():
history_lines.append(line)
if len(python_history) > HISTORY_COUNT:
history_lines[0] = '# *** History has been truncated to %s lines ***' % HISTORY_COUNT
self.history_lines = history_lines
self.concatenated_history = '\n'.join(history_lines)
# Line offset.
if self.original_document.text_before_cursor:
self.result_line_offset = self.original_document.cursor_position_row + 1
else:
self.result_line_offset = 0
def get_new_document(self, cursor_pos=None):
"""
Create a `Document` instance that contains the resulting text.
"""
lines = []
# Original text, before cursor.
if self.original_document.text_before_cursor:
lines.append(self.original_document.text_before_cursor)
# Selected entries from the history.
for line_no in sorted(self.selected_lines):
lines.append(self.history_lines[line_no])
# Original text, after cursor.
if self.original_document.text_after_cursor:
lines.append(self.original_document.text_after_cursor)
# Create `Document` with cursor at the right position.
text = '\n'.join(lines)
if cursor_pos is not None and cursor_pos > len(text):
cursor_pos = len(text)
return Document(text, cursor_pos)
def update_default_buffer(self, cli):
b = cli.buffers[DEFAULT_BUFFER]
b.set_document(
self.get_new_document(b.cursor_position), bypass_readonly=True)
def _toggle_help(cli):
" Display/hide help. "
if cli.current_buffer_name == HELP_BUFFER:
cli.pop_focus()
else:
cli.push_focus(HELP_BUFFER)
def _select_other_window(cli):
" Toggle focus between left/right window. "
if cli.current_buffer_name == HISTORY_BUFFER:
cli.focus(DEFAULT_BUFFER)
elif cli.current_buffer_name == DEFAULT_BUFFER:
cli.focus(HISTORY_BUFFER)
def create_key_bindings(python_input, history_mapping):
"""
Key bindings.
"""
registry = load_key_bindings(
enable_search=True,
enable_extra_page_navigation=True)
handle = registry.add_binding
@handle(' ', filter=HasFocus(HISTORY_BUFFER))
def _(event):
"""
Space: select/deselect line from history pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row
if line_no in history_mapping.selected_lines:
# Remove line.
history_mapping.selected_lines.remove(line_no)
history_mapping.update_default_buffer(event.cli)
else:
# Add line.
history_mapping.selected_lines.add(line_no)
history_mapping.update_default_buffer(event.cli)
# Update cursor position
default_buffer = event.cli.buffers[DEFAULT_BUFFER]
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
# Also move the cursor to the next line. (This way they can hold
# space to select a region.)
b.cursor_position = b.document.translate_row_col_to_index(line_no + 1, 0)
@handle(' ', filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.Delete, filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.ControlH, filter=HasFocus(DEFAULT_BUFFER))
def _(event):
"""
Space: remove line from default pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row - history_mapping.result_line_offset
if line_no >= 0:
try:
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass # When `selected_lines` is an empty set.
else:
history_mapping.selected_lines.remove(history_lineno)
history_mapping.update_default_buffer(event.cli)
help_focussed = HasFocus(HELP_BUFFER)
main_buffer_focussed = HasFocus(HISTORY_BUFFER) | HasFocus(DEFAULT_BUFFER)
@handle(Keys.Tab, filter=main_buffer_focussed)
@handle(Keys.ControlX, filter=main_buffer_focussed, eager=True)
# Eager: ignore the Emacs [Ctrl-X Ctrl-X] binding.
@handle(Keys.ControlW, filter=main_buffer_focussed)
def _(event):
" Select other window. "
_select_other_window(event.cli)
@handle(Keys.F4)
def _(event):
" Switch between Emacs/Vi mode. "
python_input.vi_mode = not python_input.vi_mode
@handle(Keys.F1)
def _(event):
" Display/hide help. "
_toggle_help(event.cli)
@handle(Keys.ControlJ, filter=help_focussed)
@handle(Keys.ControlC, filter=help_focussed)
@handle(Keys.ControlG, filter=help_focussed)
@handle(Keys.Escape, filter=help_focussed)
def _(event):
" Leave help. "
event.cli.pop_focus()
@handle('q', filter=main_buffer_focussed)
@handle(Keys.F3, filter=main_buffer_focussed)
@handle(Keys.ControlC, filter=main_buffer_focussed)
@handle(Keys.ControlG, filter=main_buffer_focussed)
def _(event):
" Cancel and go back. "
event.cli.set_return_value(None)
enable_system_bindings = Condition(lambda cli: python_input.enable_system_bindings)
@handle(Keys.ControlZ, filter=enable_system_bindings)
def _(event):
" Suspend to background. "
event.cli.suspend_to_background()
return registry
def create_history_application(python_input, original_document):
"""
Create an `Application` for the history screen.
This has to be run as a sub application of `python_input`.
When this application runs and returns, it retuns the selected lines.
"""
history_mapping = HistoryMapping(python_input.history, original_document)
def default_buffer_pos_changed(_):
""" When the cursor changes in the default buffer. Synchronize with
history buffer. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == DEFAULT_BUFFER:
try:
line_no = default_buffer.document.cursor_position_row - \
history_mapping.result_line_offset
if line_no < 0: # When the cursor is above the inserted region.
raise IndexError
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass
else:
history_buffer.cursor_position = \
history_buffer.document.translate_row_col_to_index(history_lineno, 0)
def history_buffer_pos_changed(_):
""" When the cursor changes in the history buffer. Synchronize. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == HISTORY_BUFFER:
line_no = history_buffer.document.cursor_position_row
if line_no in history_mapping.selected_lines:
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
history_buffer = Buffer(
initial_document=Document(history_mapping.concatenated_history),
on_cursor_position_changed=history_buffer_pos_changed,
accept_action=AcceptAction(
lambda cli, buffer: cli.set_return_value(default_buffer.document)),
read_only=True)
default_buffer = Buffer(
initial_document=history_mapping.get_new_document(),
on_cursor_position_changed=default_buffer_pos_changed,
read_only=True)
help_buffer = Buffer(
initial_document=Document(HELP_TEXT, 0),
accept_action=AcceptAction.IGNORE,
read_only=True
)
buffer_mapping = BufferMapping({
HISTORY_BUFFER: history_buffer,
DEFAULT_BUFFER: default_buffer,
HELP_BUFFER: help_buffer,
}, initial=HISTORY_BUFFER)
application = Application(
layout=create_layout(python_input, history_mapping),
use_alternate_screen=True,
buffers=buffer_mapping,
style=python_input._current_style,
mouse_support=Condition(lambda cli: python_input.enable_mouse_support),
key_bindings_registry=create_key_bindings(python_input, history_mapping)
)
return application | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.595/Olde/rp 11.48.10 PM/rp_ptpython/history_browser.py | 0.754101 | 0.161982 | history_browser.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.mouse_events import MouseEventTypes
import re
__all__ = (
'has_unclosed_brackets',
'get_jedi_script_from_document',
'document_is_multiline_python',
)
def has_unclosed_brackets(text):
"""
Starting at the end of the string. If we find an opening bracket
for which we didn't had a closing one yet, return True.
"""
stack = []
# Ignore braces inside strings
text = re.sub(r'''('[^']*'|"[^"]*")''', '', text) # XXX: handle escaped quotes.!
for c in reversed(text):
if c in '])}':
stack.append(c)
elif c in '[({':
if stack:
if ((c == '[' and stack[-1] == ']') or
(c == '{' and stack[-1] == '}') or
(c == '(' and stack[-1] == ')')):
stack.pop()
else:
# Opening bracket for which we didn't had a closing one.
return True
return False
def get_jedi_script_from_document(document, locals, globals):
import jedi # We keep this import in-line, to improve start-up time.
# Importing Jedi is 'slow'.
try:
return jedi.Interpreter(
document.text,
column=document.cursor_position_col,
line=document.cursor_position_row + 1,
path='input-text',
namespaces=[locals, globals])
except ValueError:
# Invalid cursor position.
# ValueError('`column` parameter is not in a valid range.')
return None
except AttributeError:
# Workaround for #65: https://github.com/jonathanslenders/python-prompt-toolkit/issues/65
# See also: https://github.com/davidhalter/jedi/issues/508
return None
except IndexError:
# Workaround Jedi issue #514: for https://github.com/davidhalter/jedi/issues/514
return None
except KeyError:
# Workaroud for a crash when the input is "u'", the start of a unicode string.
return None
except Exception:
# Workaround for: https://github.com/jonathanslenders/ptpython/issues/91
return None
_multiline_string_delims = re.compile('''[']{3}|["]{3}''')
def document_is_multiline_python(document):
"""
Determine whether this is a multiline Python document.
"""
def ends_in_multiline_string():
"""
``True`` if we're inside a multiline string at the end of the text.
"""
delims = _multiline_string_delims.findall(document.text)
opening = None
for delim in delims:
if opening is None:
opening = delim
elif delim == opening:
opening = None
return bool(opening)
if '\n' in document.text or ends_in_multiline_string():
return True
def line_ends_with_colon():
return document.current_line.rstrip()[-1:] == ':'
# If we just typed a colon, or still have open brackets, always insert a real newline.
if line_ends_with_colon() or \
(document.is_cursor_at_the_end and
has_unclosed_brackets(document.text_before_cursor)) or \
document.text.startswith('@'):
return True
# If the character before the cursor is a backslash (line continuation
# char), insert a new line.
elif document.text_before_cursor[-1:] == '\\':
return True
return False
def if_mousedown(handler):
"""
Decorator for mouse handlers.
Only handle event when the user pressed mouse down.
(When applied to a token list. Scroll events will bubble up and are handled
by the Window.)
"""
def handle_if_mouse_down(cli, mouse_event):
if mouse_event.event_type == MouseEventTypes.MOUSE_DOWN:
return handler(cli, mouse_event)
else:
return NotImplemented
return handle_if_mouse_down | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.595/Olde/rp 11.48.10 PM/rp_ptpython/utils.py | 0.516839 | 0.157234 | utils.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.application import Application
from prompt_toolkit.buffer import Buffer, AcceptAction
from prompt_toolkit.buffer_mapping import BufferMapping
from prompt_toolkit.document import Document
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import Condition, HasFocus, InFocusStack
from prompt_toolkit.key_binding.defaults import load_key_bindings
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.containers import HSplit, VSplit, Window, FloatContainer, Float, ConditionalContainer, Container, ScrollOffsets
from prompt_toolkit.layout.controls import BufferControl, FillControl
from prompt_toolkit.layout.dimension import LayoutDimension as D
from prompt_toolkit.layout.lexers import PygmentsLexer
from prompt_toolkit.layout.margins import Margin, ScrollbarMargin
from prompt_toolkit.layout.processors import Processor, Transformation, HighlightSearchProcessor, HighlightSelectionProcessor
from prompt_toolkit.layout.screen import Char
from prompt_toolkit.layout.toolbars import ArgToolbar, SearchToolbar
from prompt_toolkit.layout.toolbars import TokenListToolbar
from prompt_toolkit.layout.utils import token_list_to_text
from pygments.lexers import RstLexer
from pygments.token import Token
from .utils import if_mousedown
from rp.rp_ptpython.layout import get_inputmode_tokens
from functools import partial
import six
if six.PY2:
from pygments.lexers import PythonLexer
else:
from pygments.lexers import Python3Lexer as PythonLexer
HISTORY_BUFFER = 'HISTORY_BUFFER'
HELP_BUFFER = 'HELP_BUFFER'
HISTORY_COUNT = 2000
__all__ = (
'create_history_application',
)
HELP_TEXT = """
This interface is meant to select multiple lines from the
history and execute them together.
Typical usage
-------------
1. Move the ``cursor up`` in the history pane, until the
cursor is on the first desired line.
2. Hold down the ``space bar``, or press it multiple
times. Each time it will select one line and move to
the next one. Each selected line will appear on the
right side.
3. When all the required lines are displayed on the right
side, press ``Enter``. This will go back to the Python
REPL and show these lines as the current input. They
can still be edited from there.
Key bindings
------------
Many Emacs and Vi navigation key bindings should work.
Press ``F4`` to switch between Emacs and Vi mode.
Additional bindings:
- ``Space``: Select or delect a line.
- ``Tab``: Move the focus between the history and input
pane. (Alternative: ``Ctrl-W``)
- ``Ctrl-C``: Cancel. Ignore the result and go back to
the REPL. (Alternatives: ``q`` and ``Control-G``.)
- ``Enter``: Accept the result and go back to the REPL.
- ``F1``: Show/hide help. Press ``Enter`` to quit this
help message.
Further, remember that searching works like in Emacs
(using ``Ctrl-R``) or Vi (using ``/``).
"""
class BORDER:
" Box drawing characters. "
HORIZONTAL = '\u2501'
VERTICAL = '\u2503'
TOP_LEFT = '\u250f'
TOP_RIGHT = '\u2513'
BOTTOM_LEFT = '\u2517'
BOTTOM_RIGHT = '\u251b'
LIGHT_VERTICAL = '\u2502'
def create_popup_window(title, body):
"""
Return the layout for a pop-up window. It consists of a title bar showing
the `title` text, and a body layout. The window is surrounded by borders.
"""
assert isinstance(title, six.text_type)
assert isinstance(body, Container)
return HSplit([
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_LEFT, token=Token.Window.Border)),
TokenListToolbar(
get_tokens=lambda cli: [(Token.Window.Title, ' %s ' % title)],
align_center=True,
default_char=Char(BORDER.HORIZONTAL, Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_RIGHT, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
body,
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_LEFT, token=Token.Window.Border)),
Window(height=D.exact(1),
content=FillControl(BORDER.HORIZONTAL, token=Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_RIGHT, token=Token.Window.Border)),
]),
])
def create_layout(python_input, history_mapping):
"""
Create and return a `Container` instance for the history
application.
"""
processors = [
HighlightSearchProcessor(preview_search=True),
HighlightSelectionProcessor()]
help_window = create_popup_window(
title='History Help',
body=Window(
content=BufferControl(
buffer_name=HELP_BUFFER,
default_char=Char(token=Token),
lexer=PygmentsLexer(RstLexer),
input_processors=processors),
right_margins=[ScrollbarMargin()],
scroll_offsets=ScrollOffsets(top=2, bottom=2)))
return HSplit([
# Top title bar.
TokenListToolbar(
get_tokens=_get_top_toolbar_tokens,
align_center=True,
default_char=Char(' ', Token.Toolbar.Status)),
FloatContainer(
content=VSplit([
# Left side: history.
Window(
content=BufferControl(
buffer_name=HISTORY_BUFFER,
lexer=PygmentsLexer(PythonLexer),
input_processors=processors),
wrap_lines=False,
left_margins=[HistoryMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
# Separator.
Window(width=D.exact(1),
content=FillControl(BORDER.LIGHT_VERTICAL, token=Token.Separator)),
# Right side: result.
Window(
content=BufferControl(
buffer_name=DEFAULT_BUFFER,
input_processors=processors + [GrayExistingText(history_mapping)],
lexer=PygmentsLexer(PythonLexer)),
wrap_lines=False,
left_margins=[ResultMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
]),
floats=[
# Help text as a float.
Float(width=60, top=3, bottom=2,
content=ConditionalContainer(
# (We use InFocusStack, because it's possible to search
# through the help text as well, and at that point the search
# buffer has the focus.)
content=help_window, filter=InFocusStack(HELP_BUFFER))),
]
),
# Bottom toolbars.
ArgToolbar(),
SearchToolbar(),
TokenListToolbar(
get_tokens=partial(_get_bottom_toolbar_tokens, python_input=python_input),
default_char=Char(' ', Token.Toolbar.Status)),
])
def _get_top_toolbar_tokens(cli):
return [(Token.Toolbar.Status.Title, 'History browser - Insert from history')]
def _get_bottom_toolbar_tokens(cli, python_input):
@if_mousedown
def f1(cli, mouse_event):
_toggle_help(cli)
@if_mousedown
def tab(cli, mouse_event):
_select_other_window(cli)
return [
(Token.Toolbar.Status, ' ')
] + get_inputmode_tokens(cli, python_input) + [
(Token.Toolbar.Status, ' '),
(Token.Toolbar.Status.Key, '[Space]'),
(Token.Toolbar.Status, ' Toggle '),
(Token.Toolbar.Status.Key, '[Tab]', tab),
(Token.Toolbar.Status, ' Focus ', tab),
(Token.Toolbar.Status.Key, '[Enter]'),
(Token.Toolbar.Status, ' Accept '),
(Token.Toolbar.Status.Key, '[F1]', f1),
(Token.Toolbar.Status, ' Help ', f1),
]
class HistoryMargin(Margin):
"""
Margin for the history buffer.
This displays a green bar for the selected entries.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[HISTORY_BUFFER].document
lines_starting_new_entries = self.history_mapping.lines_starting_new_entries
selected_lines = self.history_mapping.selected_lines
current_lineno = document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
# Show stars at the start of each entry.
# (Visualises multiline entries.)
if line_number in lines_starting_new_entries:
char = '*'
else:
char = ' '
if line_number in selected_lines:
t = Token.History.Line.Selected
else:
t = Token.History.Line
if line_number == current_lineno:
t = t.Current
result.append((t, char))
result.append((Token, '\n'))
return result
class ResultMargin(Margin):
"""
The margin to be shown in the result pane.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[DEFAULT_BUFFER].document
current_lineno = document.cursor_position_row
offset = self.history_mapping.result_line_offset #original_document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
if (line_number is None or line_number < offset or
line_number >= offset + len(self.history_mapping.selected_lines)):
t = Token
elif line_number == current_lineno:
t = Token.History.Line.Selected.Current
else:
t = Token.History.Line.Selected
result.append((t, ' '))
result.append((Token, '\n'))
return result
def invalidation_hash(self, cli, document):
return document.cursor_position_row
class GrayExistingText(Processor):
"""
Turn the existing input, before and after the inserted code gray.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
self._lines_before = len(history_mapping.original_document.text_before_cursor.splitlines())
def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
if (lineno < self._lines_before or
lineno >= self._lines_before + len(self.history_mapping.selected_lines)):
text = token_list_to_text(tokens)
return Transformation(tokens=[(Token.History.ExistingInput, text)])
else:
return Transformation(tokens=tokens)
class HistoryMapping(object):
"""
Keep a list of all the lines from the history and the selected lines.
"""
def __init__(self, python_history, original_document):
self.python_history = python_history
self.original_document = original_document
self.lines_starting_new_entries = set()
self.selected_lines = set()
# Process history.
history_lines = []
for entry_nr, entry in list(enumerate(python_history))[-HISTORY_COUNT:]:
self.lines_starting_new_entries.add(len(history_lines))
for line in entry.splitlines():
history_lines.append(line)
if len(python_history) > HISTORY_COUNT:
history_lines[0] = '# *** History has been truncated to %s lines ***' % HISTORY_COUNT
self.history_lines = history_lines
self.concatenated_history = '\n'.join(history_lines)
# Line offset.
if self.original_document.text_before_cursor:
self.result_line_offset = self.original_document.cursor_position_row + 1
else:
self.result_line_offset = 0
def get_new_document(self, cursor_pos=None):
"""
Create a `Document` instance that contains the resulting text.
"""
lines = []
# Original text, before cursor.
if self.original_document.text_before_cursor:
lines.append(self.original_document.text_before_cursor)
# Selected entries from the history.
for line_no in sorted(self.selected_lines):
lines.append(self.history_lines[line_no])
# Original text, after cursor.
if self.original_document.text_after_cursor:
lines.append(self.original_document.text_after_cursor)
# Create `Document` with cursor at the right position.
text = '\n'.join(lines)
if cursor_pos is not None and cursor_pos > len(text):
cursor_pos = len(text)
return Document(text, cursor_pos)
def update_default_buffer(self, cli):
b = cli.buffers[DEFAULT_BUFFER]
b.set_document(
self.get_new_document(b.cursor_position), bypass_readonly=True)
def _toggle_help(cli):
" Display/hide help. "
if cli.current_buffer_name == HELP_BUFFER:
cli.pop_focus()
else:
cli.push_focus(HELP_BUFFER)
def _select_other_window(cli):
" Toggle focus between left/right window. "
if cli.current_buffer_name == HISTORY_BUFFER:
cli.focus(DEFAULT_BUFFER)
elif cli.current_buffer_name == DEFAULT_BUFFER:
cli.focus(HISTORY_BUFFER)
def create_key_bindings(python_input, history_mapping):
"""
Key bindings.
"""
registry = load_key_bindings(
enable_search=True,
enable_extra_page_navigation=True)
handle = registry.add_binding
@handle(' ', filter=HasFocus(HISTORY_BUFFER))
def _(event):
"""
Space: select/deselect line from history pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row
if line_no in history_mapping.selected_lines:
# Remove line.
history_mapping.selected_lines.remove(line_no)
history_mapping.update_default_buffer(event.cli)
else:
# Add line.
history_mapping.selected_lines.add(line_no)
history_mapping.update_default_buffer(event.cli)
# Update cursor position
default_buffer = event.cli.buffers[DEFAULT_BUFFER]
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
# Also move the cursor to the next line. (This way they can hold
# space to select a region.)
b.cursor_position = b.document.translate_row_col_to_index(line_no + 1, 0)
@handle(' ', filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.Delete, filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.ControlH, filter=HasFocus(DEFAULT_BUFFER))
def _(event):
"""
Space: remove line from default pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row - history_mapping.result_line_offset
if line_no >= 0:
try:
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass # When `selected_lines` is an empty set.
else:
history_mapping.selected_lines.remove(history_lineno)
history_mapping.update_default_buffer(event.cli)
help_focussed = HasFocus(HELP_BUFFER)
main_buffer_focussed = HasFocus(HISTORY_BUFFER) | HasFocus(DEFAULT_BUFFER)
@handle(Keys.Tab, filter=main_buffer_focussed)
@handle(Keys.ControlX, filter=main_buffer_focussed, eager=True)
# Eager: ignore the Emacs [Ctrl-X Ctrl-X] binding.
@handle(Keys.ControlW, filter=main_buffer_focussed)
def _(event):
" Select other window. "
_select_other_window(event.cli)
@handle(Keys.F4)
def _(event):
" Switch between Emacs/Vi mode. "
python_input.vi_mode = not python_input.vi_mode
@handle(Keys.F1)
def _(event):
" Display/hide help. "
_toggle_help(event.cli)
@handle(Keys.ControlJ, filter=help_focussed)
@handle(Keys.ControlC, filter=help_focussed)
@handle(Keys.ControlG, filter=help_focussed)
@handle(Keys.Escape, filter=help_focussed)
def _(event):
" Leave help. "
event.cli.pop_focus()
@handle('q', filter=main_buffer_focussed)
@handle(Keys.F3, filter=main_buffer_focussed)
@handle(Keys.ControlC, filter=main_buffer_focussed)
@handle(Keys.ControlG, filter=main_buffer_focussed)
def _(event):
" Cancel and go back. "
event.cli.set_return_value(None)
enable_system_bindings = Condition(lambda cli: python_input.enable_system_bindings)
@handle(Keys.ControlZ, filter=enable_system_bindings)
def _(event):
" Suspend to background. "
event.cli.suspend_to_background()
return registry
def create_history_application(python_input, original_document):
"""
Create an `Application` for the history screen.
This has to be run as a sub application of `python_input`.
When this application runs and returns, it retuns the selected lines.
"""
history_mapping = HistoryMapping(python_input.history, original_document)
def default_buffer_pos_changed(_):
""" When the cursor changes in the default buffer. Synchronize with
history buffer. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == DEFAULT_BUFFER:
try:
line_no = default_buffer.document.cursor_position_row - \
history_mapping.result_line_offset
if line_no < 0: # When the cursor is above the inserted region.
raise IndexError
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass
else:
history_buffer.cursor_position = \
history_buffer.document.translate_row_col_to_index(history_lineno, 0)
def history_buffer_pos_changed(_):
""" When the cursor changes in the history buffer. Synchronize. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == HISTORY_BUFFER:
line_no = history_buffer.document.cursor_position_row
if line_no in history_mapping.selected_lines:
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
history_buffer = Buffer(
initial_document=Document(history_mapping.concatenated_history),
on_cursor_position_changed=history_buffer_pos_changed,
accept_action=AcceptAction(
lambda cli, buffer: cli.set_return_value(default_buffer.document)),
read_only=True)
default_buffer = Buffer(
initial_document=history_mapping.get_new_document(),
on_cursor_position_changed=default_buffer_pos_changed,
read_only=True)
help_buffer = Buffer(
initial_document=Document(HELP_TEXT, 0),
accept_action=AcceptAction.IGNORE,
read_only=True
)
buffer_mapping = BufferMapping({
HISTORY_BUFFER: history_buffer,
DEFAULT_BUFFER: default_buffer,
HELP_BUFFER: help_buffer,
}, initial=HISTORY_BUFFER)
application = Application(
layout=create_layout(python_input, history_mapping),
use_alternate_screen=True,
buffers=buffer_mapping,
style=python_input._current_style,
mouse_support=Condition(lambda cli: python_input.enable_mouse_support),
key_bindings_registry=create_key_bindings(python_input, history_mapping)
)
return application | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.595/Olde/rp 5.45.01 PM/rp_ptpython/history_browser.py | 0.754101 | 0.161982 | history_browser.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.mouse_events import MouseEventTypes
import re
__all__ = (
'has_unclosed_brackets',
'get_jedi_script_from_document',
'document_is_multiline_python',
)
def has_unclosed_brackets(text):
"""
Starting at the end of the string. If we find an opening bracket
for which we didn't had a closing one yet, return True.
"""
stack = []
# Ignore braces inside strings
text = re.sub(r'''('[^']*'|"[^"]*")''', '', text) # XXX: handle escaped quotes.!
for c in reversed(text):
if c in '])}':
stack.append(c)
elif c in '[({':
if stack:
if ((c == '[' and stack[-1] == ']') or
(c == '{' and stack[-1] == '}') or
(c == '(' and stack[-1] == ')')):
stack.pop()
else:
# Opening bracket for which we didn't had a closing one.
return True
return False
def get_jedi_script_from_document(document, locals, globals):
import jedi # We keep this import in-line, to improve start-up time.
# Importing Jedi is 'slow'.
try:
return jedi.Interpreter(
document.text,
column=document.cursor_position_col,
line=document.cursor_position_row + 1,
path='input-text',
namespaces=[locals, globals])
except ValueError:
# Invalid cursor position.
# ValueError('`column` parameter is not in a valid range.')
return None
except AttributeError:
# Workaround for #65: https://github.com/jonathanslenders/python-prompt-toolkit/issues/65
# See also: https://github.com/davidhalter/jedi/issues/508
return None
except IndexError:
# Workaround Jedi issue #514: for https://github.com/davidhalter/jedi/issues/514
return None
except KeyError:
# Workaroud for a crash when the input is "u'", the start of a unicode string.
return None
except Exception:
# Workaround for: https://github.com/jonathanslenders/ptpython/issues/91
return None
_multiline_string_delims = re.compile('''[']{3}|["]{3}''')
def document_is_multiline_python(document):
"""
Determine whether this is a multiline Python document.
"""
def ends_in_multiline_string():
"""
``True`` if we're inside a multiline string at the end of the text.
"""
delims = _multiline_string_delims.findall(document.text)
opening = None
for delim in delims:
if opening is None:
opening = delim
elif delim == opening:
opening = None
return bool(opening)
if '\n' in document.text or ends_in_multiline_string():
return True
def line_ends_with_colon():
return document.current_line.rstrip()[-1:] == ':'
# If we just typed a colon, or still have open brackets, always insert a real newline.
if line_ends_with_colon() or \
(document.is_cursor_at_the_end and
has_unclosed_brackets(document.text_before_cursor)) or \
document.text.startswith('@'):
return True
# If the character before the cursor is a backslash (line continuation
# char), insert a new line.
elif document.text_before_cursor[-1:] == '\\':
return True
return False
def if_mousedown(handler):
"""
Decorator for mouse handlers.
Only handle event when the user pressed mouse down.
(When applied to a token list. Scroll events will bubble up and are handled
by the Window.)
"""
def handle_if_mouse_down(cli, mouse_event):
if mouse_event.event_type == MouseEventTypes.MOUSE_DOWN:
return handler(cli, mouse_event)
else:
return NotImplemented
return handle_if_mouse_down | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.595/Olde/rp 5.45.01 PM/rp_ptpython/utils.py | 0.516839 | 0.157234 | utils.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.application import Application
from prompt_toolkit.buffer import Buffer, AcceptAction
from prompt_toolkit.buffer_mapping import BufferMapping
from prompt_toolkit.document import Document
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import Condition, HasFocus, InFocusStack
from prompt_toolkit.key_binding.defaults import load_key_bindings
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.containers import HSplit, VSplit, Window, FloatContainer, Float, ConditionalContainer, Container, ScrollOffsets
from prompt_toolkit.layout.controls import BufferControl, FillControl
from prompt_toolkit.layout.dimension import LayoutDimension as D
from prompt_toolkit.layout.lexers import PygmentsLexer
from prompt_toolkit.layout.margins import Margin, ScrollbarMargin
from prompt_toolkit.layout.processors import Processor, Transformation, HighlightSearchProcessor, HighlightSelectionProcessor
from prompt_toolkit.layout.screen import Char
from prompt_toolkit.layout.toolbars import ArgToolbar, SearchToolbar
from prompt_toolkit.layout.toolbars import TokenListToolbar
from prompt_toolkit.layout.utils import token_list_to_text
from pygments.lexers import RstLexer
from pygments.token import Token
from .utils import if_mousedown
from rp.rp_ptpython.layout import get_inputmode_tokens
from functools import partial
import six
if six.PY2:
from pygments.lexers import PythonLexer
else:
from pygments.lexers import Python3Lexer as PythonLexer
HISTORY_BUFFER = 'HISTORY_BUFFER'
HELP_BUFFER = 'HELP_BUFFER'
HISTORY_COUNT = 2000
__all__ = (
'create_history_application',
)
HELP_TEXT = """
This interface is meant to select multiple lines from the
history and execute them together.
Typical usage
-------------
1. Move the ``cursor up`` in the history pane, until the
cursor is on the first desired line.
2. Hold down the ``space bar``, or press it multiple
times. Each time it will select one line and move to
the next one. Each selected line will appear on the
right side.
3. When all the required lines are displayed on the right
side, press ``Enter``. This will go back to the Python
REPL and show these lines as the current input. They
can still be edited from there.
Key bindings
------------
Many Emacs and Vi navigation key bindings should work.
Press ``F4`` to switch between Emacs and Vi mode.
Additional bindings:
- ``Space``: Select or delect a line.
- ``Tab``: Move the focus between the history and input
pane. (Alternative: ``Ctrl-W``)
- ``Ctrl-C``: Cancel. Ignore the result and go back to
the REPL. (Alternatives: ``q`` and ``Control-G``.)
- ``Enter``: Accept the result and go back to the REPL.
- ``F1``: Show/hide help. Press ``Enter`` to quit this
help message.
Further, remember that searching works like in Emacs
(using ``Ctrl-R``) or Vi (using ``/``).
"""
class BORDER:
" Box drawing characters. "
HORIZONTAL = '\u2501'
VERTICAL = '\u2503'
TOP_LEFT = '\u250f'
TOP_RIGHT = '\u2513'
BOTTOM_LEFT = '\u2517'
BOTTOM_RIGHT = '\u251b'
LIGHT_VERTICAL = '\u2502'
def create_popup_window(title, body):
"""
Return the layout for a pop-up window. It consists of a title bar showing
the `title` text, and a body layout. The window is surrounded by borders.
"""
assert isinstance(title, six.text_type)
assert isinstance(body, Container)
return HSplit([
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_LEFT, token=Token.Window.Border)),
TokenListToolbar(
get_tokens=lambda cli: [(Token.Window.Title, ' %s ' % title)],
align_center=True,
default_char=Char(BORDER.HORIZONTAL, Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_RIGHT, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
body,
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_LEFT, token=Token.Window.Border)),
Window(height=D.exact(1),
content=FillControl(BORDER.HORIZONTAL, token=Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_RIGHT, token=Token.Window.Border)),
]),
])
def create_layout(python_input, history_mapping):
"""
Create and return a `Container` instance for the history
application.
"""
processors = [
HighlightSearchProcessor(preview_search=True),
HighlightSelectionProcessor()]
help_window = create_popup_window(
title='History Help',
body=Window(
content=BufferControl(
buffer_name=HELP_BUFFER,
default_char=Char(token=Token),
lexer=PygmentsLexer(RstLexer),
input_processors=processors),
right_margins=[ScrollbarMargin()],
scroll_offsets=ScrollOffsets(top=2, bottom=2)))
return HSplit([
# Top title bar.
TokenListToolbar(
get_tokens=_get_top_toolbar_tokens,
align_center=True,
default_char=Char(' ', Token.Toolbar.Status)),
FloatContainer(
content=VSplit([
# Left side: history.
Window(
content=BufferControl(
buffer_name=HISTORY_BUFFER,
lexer=PygmentsLexer(PythonLexer),
input_processors=processors),
wrap_lines=False,
left_margins=[HistoryMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
# Separator.
Window(width=D.exact(1),
content=FillControl(BORDER.LIGHT_VERTICAL, token=Token.Separator)),
# Right side: result.
Window(
content=BufferControl(
buffer_name=DEFAULT_BUFFER,
input_processors=processors + [GrayExistingText(history_mapping)],
lexer=PygmentsLexer(PythonLexer)),
wrap_lines=False,
left_margins=[ResultMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
]),
floats=[
# Help text as a float.
Float(width=60, top=3, bottom=2,
content=ConditionalContainer(
# (We use InFocusStack, because it's possible to search
# through the help text as well, and at that point the search
# buffer has the focus.)
content=help_window, filter=InFocusStack(HELP_BUFFER))),
]
),
# Bottom toolbars.
ArgToolbar(),
SearchToolbar(),
TokenListToolbar(
get_tokens=partial(_get_bottom_toolbar_tokens, python_input=python_input),
default_char=Char(' ', Token.Toolbar.Status)),
])
def _get_top_toolbar_tokens(cli):
return [(Token.Toolbar.Status.Title, 'History browser - Insert from history')]
def _get_bottom_toolbar_tokens(cli, python_input):
@if_mousedown
def f1(cli, mouse_event):
_toggle_help(cli)
@if_mousedown
def tab(cli, mouse_event):
_select_other_window(cli)
return [
(Token.Toolbar.Status, ' ')
] + get_inputmode_tokens(cli, python_input) + [
(Token.Toolbar.Status, ' '),
(Token.Toolbar.Status.Key, '[Space]'),
(Token.Toolbar.Status, ' Toggle '),
(Token.Toolbar.Status.Key, '[Tab]', tab),
(Token.Toolbar.Status, ' Focus ', tab),
(Token.Toolbar.Status.Key, '[Enter]'),
(Token.Toolbar.Status, ' Accept '),
(Token.Toolbar.Status.Key, '[F1]', f1),
(Token.Toolbar.Status, ' Help ', f1),
]
class HistoryMargin(Margin):
"""
Margin for the history buffer.
This displays a green bar for the selected entries.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[HISTORY_BUFFER].document
lines_starting_new_entries = self.history_mapping.lines_starting_new_entries
selected_lines = self.history_mapping.selected_lines
current_lineno = document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
# Show stars at the start of each entry.
# (Visualises multiline entries.)
if line_number in lines_starting_new_entries:
char = '*'
else:
char = ' '
if line_number in selected_lines:
t = Token.History.Line.Selected
else:
t = Token.History.Line
if line_number == current_lineno:
t = t.Current
result.append((t, char))
result.append((Token, '\n'))
return result
class ResultMargin(Margin):
"""
The margin to be shown in the result pane.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[DEFAULT_BUFFER].document
current_lineno = document.cursor_position_row
offset = self.history_mapping.result_line_offset #original_document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
if (line_number is None or line_number < offset or
line_number >= offset + len(self.history_mapping.selected_lines)):
t = Token
elif line_number == current_lineno:
t = Token.History.Line.Selected.Current
else:
t = Token.History.Line.Selected
result.append((t, ' '))
result.append((Token, '\n'))
return result
def invalidation_hash(self, cli, document):
return document.cursor_position_row
class GrayExistingText(Processor):
"""
Turn the existing input, before and after the inserted code gray.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
self._lines_before = len(history_mapping.original_document.text_before_cursor.splitlines())
def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
if (lineno < self._lines_before or
lineno >= self._lines_before + len(self.history_mapping.selected_lines)):
text = token_list_to_text(tokens)
return Transformation(tokens=[(Token.History.ExistingInput, text)])
else:
return Transformation(tokens=tokens)
class HistoryMapping(object):
"""
Keep a list of all the lines from the history and the selected lines.
"""
def __init__(self, python_history, original_document):
self.python_history = python_history
self.original_document = original_document
self.lines_starting_new_entries = set()
self.selected_lines = set()
# Process history.
history_lines = []
for entry_nr, entry in list(enumerate(python_history))[-HISTORY_COUNT:]:
self.lines_starting_new_entries.add(len(history_lines))
for line in entry.splitlines():
history_lines.append(line)
if len(python_history) > HISTORY_COUNT:
history_lines[0] = '# *** History has been truncated to %s lines ***' % HISTORY_COUNT
self.history_lines = history_lines
self.concatenated_history = '\n'.join(history_lines)
# Line offset.
if self.original_document.text_before_cursor:
self.result_line_offset = self.original_document.cursor_position_row + 1
else:
self.result_line_offset = 0
def get_new_document(self, cursor_pos=None):
"""
Create a `Document` instance that contains the resulting text.
"""
lines = []
# Original text, before cursor.
if self.original_document.text_before_cursor:
lines.append(self.original_document.text_before_cursor)
# Selected entries from the history.
for line_no in sorted(self.selected_lines):
lines.append(self.history_lines[line_no])
# Original text, after cursor.
if self.original_document.text_after_cursor:
lines.append(self.original_document.text_after_cursor)
# Create `Document` with cursor at the right position.
text = '\n'.join(lines)
if cursor_pos is not None and cursor_pos > len(text):
cursor_pos = len(text)
return Document(text, cursor_pos)
def update_default_buffer(self, cli):
b = cli.buffers[DEFAULT_BUFFER]
b.set_document(
self.get_new_document(b.cursor_position), bypass_readonly=True)
def _toggle_help(cli):
" Display/hide help. "
if cli.current_buffer_name == HELP_BUFFER:
cli.pop_focus()
else:
cli.push_focus(HELP_BUFFER)
def _select_other_window(cli):
" Toggle focus between left/right window. "
if cli.current_buffer_name == HISTORY_BUFFER:
cli.focus(DEFAULT_BUFFER)
elif cli.current_buffer_name == DEFAULT_BUFFER:
cli.focus(HISTORY_BUFFER)
def create_key_bindings(python_input, history_mapping):
"""
Key bindings.
"""
registry = load_key_bindings(
enable_search=True,
enable_extra_page_navigation=True)
handle = registry.add_binding
@handle(' ', filter=HasFocus(HISTORY_BUFFER))
def _(event):
"""
Space: select/deselect line from history pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row
if line_no in history_mapping.selected_lines:
# Remove line.
history_mapping.selected_lines.remove(line_no)
history_mapping.update_default_buffer(event.cli)
else:
# Add line.
history_mapping.selected_lines.add(line_no)
history_mapping.update_default_buffer(event.cli)
# Update cursor position
default_buffer = event.cli.buffers[DEFAULT_BUFFER]
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
# Also move the cursor to the next line. (This way they can hold
# space to select a region.)
b.cursor_position = b.document.translate_row_col_to_index(line_no + 1, 0)
@handle(' ', filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.Delete, filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.ControlH, filter=HasFocus(DEFAULT_BUFFER))
def _(event):
"""
Space: remove line from default pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row - history_mapping.result_line_offset
if line_no >= 0:
try:
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass # When `selected_lines` is an empty set.
else:
history_mapping.selected_lines.remove(history_lineno)
history_mapping.update_default_buffer(event.cli)
help_focussed = HasFocus(HELP_BUFFER)
main_buffer_focussed = HasFocus(HISTORY_BUFFER) | HasFocus(DEFAULT_BUFFER)
@handle(Keys.Tab, filter=main_buffer_focussed)
@handle(Keys.ControlX, filter=main_buffer_focussed, eager=True)
# Eager: ignore the Emacs [Ctrl-X Ctrl-X] binding.
@handle(Keys.ControlW, filter=main_buffer_focussed)
def _(event):
" Select other window. "
_select_other_window(event.cli)
@handle(Keys.F4)
def _(event):
" Switch between Emacs/Vi mode. "
python_input.vi_mode = not python_input.vi_mode
@handle(Keys.F1)
def _(event):
" Display/hide help. "
_toggle_help(event.cli)
@handle(Keys.ControlJ, filter=help_focussed)
@handle(Keys.ControlC, filter=help_focussed)
@handle(Keys.ControlG, filter=help_focussed)
@handle(Keys.Escape, filter=help_focussed)
def _(event):
" Leave help. "
event.cli.pop_focus()
@handle('q', filter=main_buffer_focussed)
@handle(Keys.F3, filter=main_buffer_focussed)
@handle(Keys.ControlC, filter=main_buffer_focussed)
@handle(Keys.ControlG, filter=main_buffer_focussed)
def _(event):
" Cancel and go back. "
event.cli.set_return_value(None)
enable_system_bindings = Condition(lambda cli: python_input.enable_system_bindings)
@handle(Keys.ControlZ, filter=enable_system_bindings)
def _(event):
" Suspend to background. "
event.cli.suspend_to_background()
return registry
def create_history_application(python_input, original_document):
"""
Create an `Application` for the history screen.
This has to be run as a sub application of `python_input`.
When this application runs and returns, it retuns the selected lines.
"""
history_mapping = HistoryMapping(python_input.history, original_document)
def default_buffer_pos_changed(_):
""" When the cursor changes in the default buffer. Synchronize with
history buffer. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == DEFAULT_BUFFER:
try:
line_no = default_buffer.document.cursor_position_row - \
history_mapping.result_line_offset
if line_no < 0: # When the cursor is above the inserted region.
raise IndexError
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass
else:
history_buffer.cursor_position = \
history_buffer.document.translate_row_col_to_index(history_lineno, 0)
def history_buffer_pos_changed(_):
""" When the cursor changes in the history buffer. Synchronize. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == HISTORY_BUFFER:
line_no = history_buffer.document.cursor_position_row
if line_no in history_mapping.selected_lines:
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
history_buffer = Buffer(
initial_document=Document(history_mapping.concatenated_history),
on_cursor_position_changed=history_buffer_pos_changed,
accept_action=AcceptAction(
lambda cli, buffer: cli.set_return_value(default_buffer.document)),
read_only=True)
default_buffer = Buffer(
initial_document=history_mapping.get_new_document(),
on_cursor_position_changed=default_buffer_pos_changed,
read_only=True)
help_buffer = Buffer(
initial_document=Document(HELP_TEXT, 0),
accept_action=AcceptAction.IGNORE,
read_only=True
)
buffer_mapping = BufferMapping({
HISTORY_BUFFER: history_buffer,
DEFAULT_BUFFER: default_buffer,
HELP_BUFFER: help_buffer,
}, initial=HISTORY_BUFFER)
application = Application(
layout=create_layout(python_input, history_mapping),
use_alternate_screen=True,
buffers=buffer_mapping,
style=python_input._current_style,
mouse_support=Condition(lambda cli: python_input.enable_mouse_support),
key_bindings_registry=create_key_bindings(python_input, history_mapping)
)
return application | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.595/Olde/rp 7.24.17 AM/rp_ptpython/history_browser.py | 0.754101 | 0.161982 | history_browser.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.mouse_events import MouseEventTypes
import re
__all__ = (
'has_unclosed_brackets',
'get_jedi_script_from_document',
'document_is_multiline_python',
)
def has_unclosed_brackets(text):
"""
Starting at the end of the string. If we find an opening bracket
for which we didn't had a closing one yet, return True.
"""
stack = []
# Ignore braces inside strings
text = re.sub(r'''('[^']*'|"[^"]*")''', '', text) # XXX: handle escaped quotes.!
for c in reversed(text):
if c in '])}':
stack.append(c)
elif c in '[({':
if stack:
if ((c == '[' and stack[-1] == ']') or
(c == '{' and stack[-1] == '}') or
(c == '(' and stack[-1] == ')')):
stack.pop()
else:
# Opening bracket for which we didn't had a closing one.
return True
return False
def get_jedi_script_from_document(document, locals, globals):
import jedi # We keep this import in-line, to improve start-up time.
# Importing Jedi is 'slow'.
try:
return jedi.Interpreter(
document.text,
column=document.cursor_position_col,
line=document.cursor_position_row + 1,
path='input-text',
namespaces=[locals, globals])
except ValueError:
# Invalid cursor position.
# ValueError('`column` parameter is not in a valid range.')
return None
except AttributeError:
# Workaround for #65: https://github.com/jonathanslenders/python-prompt-toolkit/issues/65
# See also: https://github.com/davidhalter/jedi/issues/508
return None
except IndexError:
# Workaround Jedi issue #514: for https://github.com/davidhalter/jedi/issues/514
return None
except KeyError:
# Workaroud for a crash when the input is "u'", the start of a unicode string.
return None
except Exception:
# Workaround for: https://github.com/jonathanslenders/ptpython/issues/91
return None
_multiline_string_delims = re.compile('''[']{3}|["]{3}''')
def document_is_multiline_python(document):
"""
Determine whether this is a multiline Python document.
"""
def ends_in_multiline_string():
"""
``True`` if we're inside a multiline string at the end of the text.
"""
delims = _multiline_string_delims.findall(document.text)
opening = None
for delim in delims:
if opening is None:
opening = delim
elif delim == opening:
opening = None
return bool(opening)
if '\n' in document.text or ends_in_multiline_string():
return True
def line_ends_with_colon():
return document.current_line.rstrip()[-1:] == ':'
# If we just typed a colon, or still have open brackets, always insert a real newline.
if line_ends_with_colon() or \
(document.is_cursor_at_the_end and
has_unclosed_brackets(document.text_before_cursor)) or \
document.text.startswith('@'):
return True
# If the character before the cursor is a backslash (line continuation
# char), insert a new line.
elif document.text_before_cursor[-1:] == '\\':
return True
return False
def if_mousedown(handler):
"""
Decorator for mouse handlers.
Only handle event when the user pressed mouse down.
(When applied to a token list. Scroll events will bubble up and are handled
by the Window.)
"""
def handle_if_mouse_down(cli, mouse_event):
if mouse_event.event_type == MouseEventTypes.MOUSE_DOWN:
return handler(cli, mouse_event)
else:
return NotImplemented
return handle_if_mouse_down | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.595/Olde/rp 7.24.17 AM/rp_ptpython/utils.py | 0.516839 | 0.157234 | utils.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.application import Application
from prompt_toolkit.buffer import Buffer, AcceptAction
from prompt_toolkit.buffer_mapping import BufferMapping
from prompt_toolkit.document import Document
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import Condition, HasFocus, InFocusStack
from prompt_toolkit.key_binding.defaults import load_key_bindings
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.containers import HSplit, VSplit, Window, FloatContainer, Float, ConditionalContainer, Container, ScrollOffsets
from prompt_toolkit.layout.controls import BufferControl, FillControl
from prompt_toolkit.layout.dimension import LayoutDimension as D
from prompt_toolkit.layout.lexers import PygmentsLexer
from prompt_toolkit.layout.margins import Margin, ScrollbarMargin
from prompt_toolkit.layout.processors import Processor, Transformation, HighlightSearchProcessor, HighlightSelectionProcessor
from prompt_toolkit.layout.screen import Char
from prompt_toolkit.layout.toolbars import ArgToolbar, SearchToolbar
from prompt_toolkit.layout.toolbars import TokenListToolbar
from prompt_toolkit.layout.utils import token_list_to_text
from pygments.lexers import RstLexer
from pygments.token import Token
from .utils import if_mousedown
from rp.rp_ptpython.layout import get_inputmode_tokens
from functools import partial
import six
if six.PY2:
from pygments.lexers import PythonLexer
else:
from pygments.lexers import Python3Lexer as PythonLexer
HISTORY_BUFFER = 'HISTORY_BUFFER'
HELP_BUFFER = 'HELP_BUFFER'
HISTORY_COUNT = 2000
__all__ = (
'create_history_application',
)
HELP_TEXT = """
This interface is meant to select multiple lines from the
history and execute them together.
Typical usage
-------------
1. Move the ``cursor up`` in the history pane, until the
cursor is on the first desired line.
2. Hold down the ``space bar``, or press it multiple
times. Each time it will select one line and move to
the next one. Each selected line will appear on the
right side.
3. When all the required lines are displayed on the right
side, press ``Enter``. This will go back to the Python
REPL and show these lines as the current input. They
can still be edited from there.
Key bindings
------------
Many Emacs and Vi navigation key bindings should work.
Press ``F4`` to switch between Emacs and Vi mode.
Additional bindings:
- ``Space``: Select or delect a line.
- ``Tab``: Move the focus between the history and input
pane. (Alternative: ``Ctrl-W``)
- ``Ctrl-C``: Cancel. Ignore the result and go back to
the REPL. (Alternatives: ``q`` and ``Control-G``.)
- ``Enter``: Accept the result and go back to the REPL.
- ``F1``: Show/hide help. Press ``Enter`` to quit this
help message.
Further, remember that searching works like in Emacs
(using ``Ctrl-R``) or Vi (using ``/``).
"""
class BORDER:
" Box drawing characters. "
HORIZONTAL = '\u2501'
VERTICAL = '\u2503'
TOP_LEFT = '\u250f'
TOP_RIGHT = '\u2513'
BOTTOM_LEFT = '\u2517'
BOTTOM_RIGHT = '\u251b'
LIGHT_VERTICAL = '\u2502'
def create_popup_window(title, body):
"""
Return the layout for a pop-up window. It consists of a title bar showing
the `title` text, and a body layout. The window is surrounded by borders.
"""
assert isinstance(title, six.text_type)
assert isinstance(body, Container)
return HSplit([
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_LEFT, token=Token.Window.Border)),
TokenListToolbar(
get_tokens=lambda cli: [(Token.Window.Title, ' %s ' % title)],
align_center=True,
default_char=Char(BORDER.HORIZONTAL, Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.TOP_RIGHT, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
body,
Window(width=D.exact(1),
content=FillControl(BORDER.VERTICAL, token=Token.Window.Border)),
]),
VSplit([
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_LEFT, token=Token.Window.Border)),
Window(height=D.exact(1),
content=FillControl(BORDER.HORIZONTAL, token=Token.Window.Border)),
Window(width=D.exact(1), height=D.exact(1),
content=FillControl(BORDER.BOTTOM_RIGHT, token=Token.Window.Border)),
]),
])
def create_layout(python_input, history_mapping):
"""
Create and return a `Container` instance for the history
application.
"""
processors = [
HighlightSearchProcessor(preview_search=True),
HighlightSelectionProcessor()]
help_window = create_popup_window(
title='History Help',
body=Window(
content=BufferControl(
buffer_name=HELP_BUFFER,
default_char=Char(token=Token),
lexer=PygmentsLexer(RstLexer),
input_processors=processors),
right_margins=[ScrollbarMargin()],
scroll_offsets=ScrollOffsets(top=2, bottom=2)))
return HSplit([
# Top title bar.
TokenListToolbar(
get_tokens=_get_top_toolbar_tokens,
align_center=True,
default_char=Char(' ', Token.Toolbar.Status)),
FloatContainer(
content=VSplit([
# Left side: history.
Window(
content=BufferControl(
buffer_name=HISTORY_BUFFER,
lexer=PygmentsLexer(PythonLexer),
input_processors=processors),
wrap_lines=False,
left_margins=[HistoryMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
# Separator.
Window(width=D.exact(1),
content=FillControl(BORDER.LIGHT_VERTICAL, token=Token.Separator)),
# Right side: result.
Window(
content=BufferControl(
buffer_name=DEFAULT_BUFFER,
input_processors=processors + [GrayExistingText(history_mapping)],
lexer=PygmentsLexer(PythonLexer)),
wrap_lines=False,
left_margins=[ResultMargin(history_mapping)],
scroll_offsets=ScrollOffsets(top=2, bottom=2)),
]),
floats=[
# Help text as a float.
Float(width=60, top=3, bottom=2,
content=ConditionalContainer(
# (We use InFocusStack, because it's possible to search
# through the help text as well, and at that point the search
# buffer has the focus.)
content=help_window, filter=InFocusStack(HELP_BUFFER))),
]
),
# Bottom toolbars.
ArgToolbar(),
SearchToolbar(),
TokenListToolbar(
get_tokens=partial(_get_bottom_toolbar_tokens, python_input=python_input),
default_char=Char(' ', Token.Toolbar.Status)),
])
def _get_top_toolbar_tokens(cli):
return [(Token.Toolbar.Status.Title, 'History browser - Insert from history')]
def _get_bottom_toolbar_tokens(cli, python_input):
@if_mousedown
def f1(cli, mouse_event):
_toggle_help(cli)
@if_mousedown
def tab(cli, mouse_event):
_select_other_window(cli)
return [
(Token.Toolbar.Status, ' ')
] + get_inputmode_tokens(cli, python_input) + [
(Token.Toolbar.Status, ' '),
(Token.Toolbar.Status.Key, '[Space]'),
(Token.Toolbar.Status, ' Toggle '),
(Token.Toolbar.Status.Key, '[Tab]', tab),
(Token.Toolbar.Status, ' Focus ', tab),
(Token.Toolbar.Status.Key, '[Enter]'),
(Token.Toolbar.Status, ' Accept '),
(Token.Toolbar.Status.Key, '[F1]', f1),
(Token.Toolbar.Status, ' Help ', f1),
]
class HistoryMargin(Margin):
"""
Margin for the history buffer.
This displays a green bar for the selected entries.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[HISTORY_BUFFER].document
lines_starting_new_entries = self.history_mapping.lines_starting_new_entries
selected_lines = self.history_mapping.selected_lines
current_lineno = document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
# Show stars at the start of each entry.
# (Visualises multiline entries.)
if line_number in lines_starting_new_entries:
char = '*'
else:
char = ' '
if line_number in selected_lines:
t = Token.History.Line.Selected
else:
t = Token.History.Line
if line_number == current_lineno:
t = t.Current
result.append((t, char))
result.append((Token, '\n'))
return result
class ResultMargin(Margin):
"""
The margin to be shown in the result pane.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
def get_width(self, cli, ui_content):
return 2
def create_margin(self, cli, window_render_info, width, height):
document = cli.buffers[DEFAULT_BUFFER].document
current_lineno = document.cursor_position_row
offset = self.history_mapping.result_line_offset #original_document.cursor_position_row
visible_line_to_input_line = window_render_info.visible_line_to_input_line
result = []
for y in range(height):
line_number = visible_line_to_input_line.get(y)
if (line_number is None or line_number < offset or
line_number >= offset + len(self.history_mapping.selected_lines)):
t = Token
elif line_number == current_lineno:
t = Token.History.Line.Selected.Current
else:
t = Token.History.Line.Selected
result.append((t, ' '))
result.append((Token, '\n'))
return result
def invalidation_hash(self, cli, document):
return document.cursor_position_row
class GrayExistingText(Processor):
"""
Turn the existing input, before and after the inserted code gray.
"""
def __init__(self, history_mapping):
self.history_mapping = history_mapping
self._lines_before = len(history_mapping.original_document.text_before_cursor.splitlines())
def apply_transformation(self, cli, document, lineno, source_to_display, tokens):
if (lineno < self._lines_before or
lineno >= self._lines_before + len(self.history_mapping.selected_lines)):
text = token_list_to_text(tokens)
return Transformation(tokens=[(Token.History.ExistingInput, text)])
else:
return Transformation(tokens=tokens)
class HistoryMapping(object):
"""
Keep a list of all the lines from the history and the selected lines.
"""
def __init__(self, python_history, original_document):
self.python_history = python_history
self.original_document = original_document
self.lines_starting_new_entries = set()
self.selected_lines = set()
# Process history.
history_lines = []
for entry_nr, entry in list(enumerate(python_history))[-HISTORY_COUNT:]:
self.lines_starting_new_entries.add(len(history_lines))
for line in entry.splitlines():
history_lines.append(line)
if len(python_history) > HISTORY_COUNT:
history_lines[0] = '# *** History has been truncated to %s lines ***' % HISTORY_COUNT
self.history_lines = history_lines
self.concatenated_history = '\n'.join(history_lines)
# Line offset.
if self.original_document.text_before_cursor:
self.result_line_offset = self.original_document.cursor_position_row + 1
else:
self.result_line_offset = 0
def get_new_document(self, cursor_pos=None):
"""
Create a `Document` instance that contains the resulting text.
"""
lines = []
# Original text, before cursor.
if self.original_document.text_before_cursor:
lines.append(self.original_document.text_before_cursor)
# Selected entries from the history.
for line_no in sorted(self.selected_lines):
lines.append(self.history_lines[line_no])
# Original text, after cursor.
if self.original_document.text_after_cursor:
lines.append(self.original_document.text_after_cursor)
# Create `Document` with cursor at the right position.
text = '\n'.join(lines)
if cursor_pos is not None and cursor_pos > len(text):
cursor_pos = len(text)
return Document(text, cursor_pos)
def update_default_buffer(self, cli):
b = cli.buffers[DEFAULT_BUFFER]
b.set_document(
self.get_new_document(b.cursor_position), bypass_readonly=True)
def _toggle_help(cli):
" Display/hide help. "
if cli.current_buffer_name == HELP_BUFFER:
cli.pop_focus()
else:
cli.push_focus(HELP_BUFFER)
def _select_other_window(cli):
" Toggle focus between left/right window. "
if cli.current_buffer_name == HISTORY_BUFFER:
cli.focus(DEFAULT_BUFFER)
elif cli.current_buffer_name == DEFAULT_BUFFER:
cli.focus(HISTORY_BUFFER)
def create_key_bindings(python_input, history_mapping):
"""
Key bindings.
"""
registry = load_key_bindings(
enable_search=True,
enable_extra_page_navigation=True)
handle = registry.add_binding
@handle(' ', filter=HasFocus(HISTORY_BUFFER))
def _(event):
"""
Space: select/deselect line from history pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row
if line_no in history_mapping.selected_lines:
# Remove line.
history_mapping.selected_lines.remove(line_no)
history_mapping.update_default_buffer(event.cli)
else:
# Add line.
history_mapping.selected_lines.add(line_no)
history_mapping.update_default_buffer(event.cli)
# Update cursor position
default_buffer = event.cli.buffers[DEFAULT_BUFFER]
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
# Also move the cursor to the next line. (This way they can hold
# space to select a region.)
b.cursor_position = b.document.translate_row_col_to_index(line_no + 1, 0)
@handle(' ', filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.Delete, filter=HasFocus(DEFAULT_BUFFER))
@handle(Keys.ControlH, filter=HasFocus(DEFAULT_BUFFER))
def _(event):
"""
Space: remove line from default pane.
"""
b = event.current_buffer
line_no = b.document.cursor_position_row - history_mapping.result_line_offset
if line_no >= 0:
try:
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass # When `selected_lines` is an empty set.
else:
history_mapping.selected_lines.remove(history_lineno)
history_mapping.update_default_buffer(event.cli)
help_focussed = HasFocus(HELP_BUFFER)
main_buffer_focussed = HasFocus(HISTORY_BUFFER) | HasFocus(DEFAULT_BUFFER)
@handle(Keys.Tab, filter=main_buffer_focussed)
@handle(Keys.ControlX, filter=main_buffer_focussed, eager=True)
# Eager: ignore the Emacs [Ctrl-X Ctrl-X] binding.
@handle(Keys.ControlW, filter=main_buffer_focussed)
def _(event):
" Select other window. "
_select_other_window(event.cli)
@handle(Keys.F4)
def _(event):
" Switch between Emacs/Vi mode. "
python_input.vi_mode = not python_input.vi_mode
@handle(Keys.F1)
def _(event):
" Display/hide help. "
_toggle_help(event.cli)
@handle(Keys.ControlJ, filter=help_focussed)
@handle(Keys.ControlC, filter=help_focussed)
@handle(Keys.ControlG, filter=help_focussed)
@handle(Keys.Escape, filter=help_focussed)
def _(event):
" Leave help. "
event.cli.pop_focus()
@handle('q', filter=main_buffer_focussed)
@handle(Keys.F3, filter=main_buffer_focussed)
@handle(Keys.ControlC, filter=main_buffer_focussed)
@handle(Keys.ControlG, filter=main_buffer_focussed)
def _(event):
" Cancel and go back. "
event.cli.set_return_value(None)
enable_system_bindings = Condition(lambda cli: python_input.enable_system_bindings)
@handle(Keys.ControlZ, filter=enable_system_bindings)
def _(event):
" Suspend to background. "
event.cli.suspend_to_background()
return registry
def create_history_application(python_input, original_document):
"""
Create an `Application` for the history screen.
This has to be run as a sub application of `python_input`.
When this application runs and returns, it retuns the selected lines.
"""
history_mapping = HistoryMapping(python_input.history, original_document)
def default_buffer_pos_changed(_):
""" When the cursor changes in the default buffer. Synchronize with
history buffer. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == DEFAULT_BUFFER:
try:
line_no = default_buffer.document.cursor_position_row - \
history_mapping.result_line_offset
if line_no < 0: # When the cursor is above the inserted region.
raise IndexError
history_lineno = sorted(history_mapping.selected_lines)[line_no]
except IndexError:
pass
else:
history_buffer.cursor_position = \
history_buffer.document.translate_row_col_to_index(history_lineno, 0)
def history_buffer_pos_changed(_):
""" When the cursor changes in the history buffer. Synchronize. """
# Only when this buffer has the focus.
if buffer_mapping.focus_stack[-1] == HISTORY_BUFFER:
line_no = history_buffer.document.cursor_position_row
if line_no in history_mapping.selected_lines:
default_lineno = sorted(history_mapping.selected_lines).index(line_no) + \
history_mapping.result_line_offset
default_buffer.cursor_position = \
default_buffer.document.translate_row_col_to_index(default_lineno, 0)
history_buffer = Buffer(
initial_document=Document(history_mapping.concatenated_history),
on_cursor_position_changed=history_buffer_pos_changed,
accept_action=AcceptAction(
lambda cli, buffer: cli.set_return_value(default_buffer.document)),
read_only=True)
default_buffer = Buffer(
initial_document=history_mapping.get_new_document(),
on_cursor_position_changed=default_buffer_pos_changed,
read_only=True)
help_buffer = Buffer(
initial_document=Document(HELP_TEXT, 0),
accept_action=AcceptAction.IGNORE,
read_only=True
)
buffer_mapping = BufferMapping({
HISTORY_BUFFER: history_buffer,
DEFAULT_BUFFER: default_buffer,
HELP_BUFFER: help_buffer,
}, initial=HISTORY_BUFFER)
application = Application(
layout=create_layout(python_input, history_mapping),
use_alternate_screen=True,
buffers=buffer_mapping,
style=python_input._current_style,
mouse_support=Condition(lambda cli: python_input.enable_mouse_support),
key_bindings_registry=create_key_bindings(python_input, history_mapping)
)
return application | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.595/Olde/rp 5.38.10 PM/rp_ptpython/history_browser.py | 0.754101 | 0.161982 | history_browser.py | pypi |
from __future__ import unicode_literals
from prompt_toolkit.mouse_events import MouseEventTypes
import re
__all__ = (
'has_unclosed_brackets',
'get_jedi_script_from_document',
'document_is_multiline_python',
)
def has_unclosed_brackets(text):
"""
Starting at the end of the string. If we find an opening bracket
for which we didn't had a closing one yet, return True.
"""
stack = []
# Ignore braces inside strings
text = re.sub(r'''('[^']*'|"[^"]*")''', '', text) # XXX: handle escaped quotes.!
for c in reversed(text):
if c in '])}':
stack.append(c)
elif c in '[({':
if stack:
if ((c == '[' and stack[-1] == ']') or
(c == '{' and stack[-1] == '}') or
(c == '(' and stack[-1] == ')')):
stack.pop()
else:
# Opening bracket for which we didn't had a closing one.
return True
return False
def get_jedi_script_from_document(document, locals, globals):
import jedi # We keep this import in-line, to improve start-up time.
# Importing Jedi is 'slow'.
try:
return jedi.Interpreter(
document.text,
column=document.cursor_position_col,
line=document.cursor_position_row + 1,
path='input-text',
namespaces=[locals, globals])
except ValueError:
# Invalid cursor position.
# ValueError('`column` parameter is not in a valid range.')
return None
except AttributeError:
# Workaround for #65: https://github.com/jonathanslenders/python-prompt-toolkit/issues/65
# See also: https://github.com/davidhalter/jedi/issues/508
return None
except IndexError:
# Workaround Jedi issue #514: for https://github.com/davidhalter/jedi/issues/514
return None
except KeyError:
# Workaroud for a crash when the input is "u'", the start of a unicode string.
return None
except Exception:
# Workaround for: https://github.com/jonathanslenders/ptpython/issues/91
return None
_multiline_string_delims = re.compile('''[']{3}|["]{3}''')
def document_is_multiline_python(document):
"""
Determine whether this is a multiline Python document.
"""
def ends_in_multiline_string():
"""
``True`` if we're inside a multiline string at the end of the text.
"""
delims = _multiline_string_delims.findall(document.text)
opening = None
for delim in delims:
if opening is None:
opening = delim
elif delim == opening:
opening = None
return bool(opening)
if '\n' in document.text or ends_in_multiline_string():
return True
def line_ends_with_colon():
return document.current_line.rstrip()[-1:] == ':'
# If we just typed a colon, or still have open brackets, always insert a real newline.
if line_ends_with_colon() or \
(document.is_cursor_at_the_end and
has_unclosed_brackets(document.text_before_cursor)) or \
document.text.startswith('@'):
return True
# If the character before the cursor is a backslash (line continuation
# char), insert a new line.
elif document.text_before_cursor[-1:] == '\\':
return True
return False
def if_mousedown(handler):
"""
Decorator for mouse handlers.
Only handle event when the user pressed mouse down.
(When applied to a token list. Scroll events will bubble up and are handled
by the Window.)
"""
def handle_if_mouse_down(cli, mouse_event):
if mouse_event.event_type == MouseEventTypes.MOUSE_DOWN:
return handler(cli, mouse_event)
else:
return NotImplemented
return handle_if_mouse_down | /rp-0.1.923.tar.gz/rp-0.1.923/rp-0.1.595/Olde/rp 5.38.10 PM/rp_ptpython/utils.py | 0.516839 | 0.157234 | utils.py | pypi |
<!--- Copyright 2021 eprbell --->
<!--- 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. --->
# RP2 v1.5.0 Developer Guide
[](https://github.com/eprbell/rp2/actions/workflows/static_analysis.yml)
[](https://github.com/eprbell/rp2/actions/workflows/documentation_check.yml)
[](https://github.com/eprbell/rp2/actions/workflows/unix_unit_tests.yml)
[](https://github.com/eprbell/rp2/actions/workflows/windows_unit_tests.yml)
[](https://github.com/eprbell/rp2/actions/workflows/codeql-analysis.yml)
## Table of Contents
* **[Introduction](#introduction)**
* **[License](#license)**
* **[Download](#download)**
* **[Setup](#setup)**
* [Ubuntu Linux](#setup-on-ubuntu-linux)
* [macOS](#setup-on-macos)
* [Windows 10](#setup-on-windows-10)
* [Other Unix-like Systems](#setup-on-other-unix-like-systems)
* **[Source Code](#source-code)**
* **[Development](#development)**
* [Design Guidelines](#design-guidelines)
* [Development Workflow](#development-workflow)
* [Unit Tests](#unit-tests)
* **[Creating a Release](#creating-a-release)**
* **[Plugin Development](#plugin-development)**
* [Adding a New Report Generator](#adding-a-new-report-generator)
* [Adding a New Accounting Method](#adding-a-new-accounting-method)
* [Adding Support for a New Country](#adding-support-for-a-new-country)
* **[Localization](#localization)**
* **[Frequently Asked Developer Questions](#frequently-asked-developer-questions)**
## Introduction
This document describes [RP2](https://github.com/eprbell/rp2) setup instructions, development workflow, design principles, source tree structure and plugin architecture.
## License
RP2 is released under the terms of Apache License Version 2.0. For more information see [LICENSE](LICENSE) or <http://www.apache.org/licenses/LICENSE-2.0>.
## Download
The latest RP2 source can be downloaded at: <https://github.com/eprbell/rp2>
## Setup
RP2 has been tested on Ubuntu Linux, macOS and Windows 10 but it should work on all systems that have Python version 3.7.0 or greater. Virtualenv is recommended for RP2 development.
### Setup on Ubuntu Linux
First make sure Python, pip and virtualenv are installed. If not, open a terminal window and enter the following commands:
```
sudo apt-get update
sudo apt-get install python3 python3-pip virtualenv
```
Then install RP2 Python package requirements:
```
cd <rp2_directory>
virtualenv -p python3 .venv
. .venv/bin/activate
.venv/bin/pip3 install -e '.[dev]'
```
### Setup on macOS
First make sure [Homebrew](https://brew.sh) is installed, then open a terminal window and enter the following commands:
```
brew update
brew install python3 virtualenv
```
Then install RP2 Python package requirements:
```
cd <rp2_directory>
virtualenv -p python3 .venv
. .venv/bin/activate
.venv/bin/pip3 install -e '.[dev]'
```
### Setup on Windows 10
First make sure [Python](https://python.org) 3.7 or greater is installed (in the Python installer window be sure to click on "Add Python to PATH"), then open a PowerShell window and enter the following commands:
```
python -m pip install virtualenv
```
Then install RP2 Python package requirements:
```
cd <rp2_directory>
virtualenv -p python .venv
.venv\Scripts\activate.ps1
python -m pip install -e ".[dev]"
```
### Setup on Other Unix-like Systems
* install python 3.7 or greater
* install pip3
* install virtualenv
* cd _<rp2_directory>_
* `virtualenv -p python3 .venv`
* `.venv/bin/pip3 install -e '.[dev]'`
## Source Code
The RP2 source tree is organized as follows:
* `.bumpversion.cfg`: bumpversion configuration;
* `CHANGELOG.md`: change log document;
* `config/`: config files for examples and tests;
* `CONTRIBUTING.md`: contribution guidelines;
* `docs/`: additional documentation, referenced from the README files;
* `.editorconfig`;
* `.gitattributes`;
* `.github/workflows/`: configuration of Github continuous integration;
* `.gitignore`;
* `input/`: examples and tests;
* `input/golden/`: expected outputs that RP2 tests compare against;
* `.isort.cfg`: isort configuration;
* `LICENSE`: license information;
* `Makefile`: alternative old-school build flow;
* `MANIFEST.in`: source distribution configuration;
* `mypy.ini`: mypy configuration;
* `.pre-commit-config.yaml`: pre-commit configuration;
* `.pylintrc`: pylint configuration;
* `pyproject.toml`: packaging configuration;
* `README.dev.md`: developer documentation;
* `README.md`: user documentation;
* `setup.cfg`: static packaging configuration file;
* `setup.py`: dynamic packaging configuration file;
* `src/rp2`: RP2 code, including classes for transactions, gains, tax engine, balances, logger, ODS parser, etc.;
* `src/locales`: RP2 localization data;
* `src/rp2/plugin/accounting_method/`: accounting method plugins;
* `src/rp2/plugin/country/`: country plugins/entry points;
* `src/rp2/plugin/report/`: report generator plugins;
* `src/rp2/plugin/report/data/`: spreadsheet templates that are used by the builtin report plugins;
* `src/rp2/plugin/report/<country>`: country-specific report generator plugins;
* `src/stubs/`: RP2 relies on third-party libraries, some of which don't have typing information, so it is added here;
* `tests/`: unit tests.
## Development
Read the [Contributing](CONTRIBUTING.md) document on pull requests guidelines.
### Design Guidelines
RP2 code adheres to these principles:
* user privacy is of paramount importance: user data never leaves the user's machine and no network calls are allowed.
* all identifiers have [descriptive names](https://realpython.com/python-pep8/#how-to-choose-names);
* immutability:
* global variables have upper case names, are initialized where declared and are never modified afterwards;
* generally data structures are read-only (the only exceptions are for data structures that would incur a major complexity increase without write permission: e.g. AVL tree node):
* class fields are private (prepended with double-underscore). Fields that need public access have a read-only property. Write-properties are not used;
* @dataclass classes have `frozen=True`;
* data encapsulation: all data fields are private (prepended with double-underscore):
* for private access nothing else is needed;
* for protected access add a read-only property starting with single underscore or an accessor function starting with `_get_`;
* for public access add a read-only property starting with no underscore or an accessor function starting with `get_`;
* runtime checks: parameters of public functions are type-checked at runtime:
* `Configuration.type_check_*()` for primitive types;
* `<class>.type_check()` for classes;
* type hints: all variables and functions have Python type hints (with the exception of local variables, for which type hints are optional);
* no id-based hashing: classes that are added to dictionaries and sets redefine `__eq__()`, `__neq__()` and `__hash__()`;
* encapsulated math: all high-precision math is done via `RP2Decimal` (a subclass of Decimal), to ensure the correct precision is used throughout the code. `RP2Decimal` instances are never mixed with other types in expressions;
* f-strings only: every time string interpolation is needed, f-strings are used;
* no raw strings (unless they occur only once): use global constants instead;
* logging: logging is done via the `logger` module;
* no unnamed tuples: dataclasses or named tuples are used instead;
* one class per file (with exceptions for trivial classes);
* files containing a class must have the same name as the class (but lowercase with underscores): e.g. class AbstractEntry lives in file abstract_entry.py;
* abstract class names start with `Abstract`;
* no imports with `*`.
### Development Workflow
RP2 uses pre-commit hooks for quick validation at commit time and continuous integration via Github actions for deeper testing. Pre-commit hooks invoke: flake8, black, isort, pyupgrade and more. Github actions invoke: mypy, pylint, bandit, unit tests (on Linux, Mac and Windows), markdown link check and more.
While every commit and push is automatically tested as described, sometimes it's useful to run some of the above commands locally without waiting for continuous integration. Here's how to run the most common ones:
* run unit tests: `pytest --tb=native --verbose`
* type check: `mypy src tests`
* lint: `pylint -r y src tests/*.py`
* security check: `bandit -r src`
* reformat code: `black src tests`
* sort imports: `isort .`
* run pre-commit tests without committing: `pre-commit run --all-files`
Logs are stored in the `log` directory. To generate debug logs, prepend the command line with `LOG_LEVEL=DEBUG`, e.g.:
```
LOG_LEVEL=DEBUG rp2_us -o output -p crypto_example_ config/crypto_example.ini input/crypto_example.ods
```
### Unit Tests
RP2 has considerable unit test coverage to reduce the risk of regression. Unit tests are in the [tests](tests) directory. Please add unit tests for any new code.
## Creating a Release
This section is for project maintainers.
To create a new release:
* add a section named as the new version in CHANGELOG.md
* use the output of `git log` to collect significant changes since last version and add them to CHANGELOG.md as a list of brief bullet points
* `git add CHANGELOG.md`
* `git commit -m "Updated with latest changes" CHANGELOG.md`
* `bumpversion patch` (or `bumpversion minor` or `bumpversion major`)
* `git push`
* wait for all tests to pass successfully on Github
* add a tag in Github (named the same as the version but with a `v` in front, e.g. `v1.0.4`): click on "Releases" and then "Draft a new release"
To create a Pypi distribution:
* `make distribution`
* `make upload_distribution`
## Plugin Development
RP2 has a plugin architecture for countries, report generators and accounting methods, which makes it extensible for new use cases.
### Adding a New Report Generator
Report generator plugins translate data structures that result from tax computation into output. Writing a new report generator plugin is quite easy: the [tax_report_us](src/rp2/plugin/report/us/tax_report_us.py) generator is a simple example, the [rp2_full_report](src/rp2/plugin/report/rp2_full_report.py) one is more comprehensive.
Report generator plugins are discovered by RP2 at runtime and they must adhere to the conventions shown below. To add a new plugin follow this procedure:
* if the new plugin is not country-specific, add a new Python file in the `src/rp2/plugin/report/` directory and give it a meaningful name
* if the new plugin is country-specific, add a new Python file in the `src/rp2/plugin/report/<country>` directory and give it a meaningful name (where `<country>` is a 2-letter country code adhering to the [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format)
* import the following (plus any other RP2 or Python package you might need):
```
from typing import Dict
from rp2.abstract_country import AbstractCountry
from rp2.computed_data import ComputedData
from rp2.entry_types import TransactionType
from rp2.gain_loss import GainLoss
from rp2.gain_loss_set import GainLossSet
```
* Optionally, RP2 provides a logger facility:
```
from logger import LOGGER
```
* Add a class named `Generator`, deriving from `AbstractReportGenerator` or `AbstractODSGenerator` (if generating a .ods file):
```
class Generator(AbstractReportGenerator):
```
* Add a `generate()` method to the class with the following signature:
```
def generate(
self,
country: AbstractCountry,
accounting_method: str,
asset_to_computed_data: Dict[str, ComputedData],
output_dir_path: str,
output_file_prefix: str,
from_date: date,
to_date: date,
generation_language: str,
) -> None:
```
* write the body of the `generate()`. The parameters are:
* `country`: instance of [AbstractCountry](src/rp2/abstract_country.py); see [Adding Support for a New Country](#adding-support-for-a-new-country) for more details;
* `accounting_method`: string name of the accounting method used to compute the taxes. This is for purposes of generation only (it can be emitted in the output);
* `asset_to_computed_data`: dictionary mapping user assets (i.e. cryptocurrency) to the computed tax data for that asset. For each user asset there is one instance of [ComputedData](src/rp2/computed_data.py);
* `output_dir_path`: directory in which to write the output;
* `output_file_prefix`: prefix to be prepended to the output file name;
* `from_date`: filter out transactions before this date. This is for generation purposes only (it can be emitted in the output): the computed data is already time-filtered;
* `to_date`: filter out transactions after this date. This is for generation purposes only (it can be emitted in the output): the computed data is already time-filtered;
* `generation_language`: language to use for generation. This is a hint and, depending on the nature of the plugin it can be used or ignored: e.g.
* the tax_report_us plugin ignores `generation_language` because it generates a 8849-sytle report that has no use outside the US (so only English is used)
* the rp2_full_report plugin uses `generation_language` because it generates a generic report that can be useful in any country (so it has to be localization-friendly)
Report plugin output can be localized in many languages (see the [Localization](#localization) section for more on this): for an example of a localization-aware plugin see [rp2_full_report](src/rp2/plugin/report/rp2_full_report.py).
**NOTE**: If you're interested in adding support for a new report generator, open a [PR](CONTRIBUTING.md).
### Adding a New Accounting Method
Accounting method plugins modify the behavior of the tax engine. They pair in/out lots according to the given accounting algorithm: [FIFO](src/rp2/plugin/accounting_method/fifo.py) is an example of accounting method plugin.
Accounting method plugins are discovered by RP2 at runtime and they must adhere to the conventions shown below. To add a new plugin follow this procedure:
* add a new Python file to the `src/rp2/plugin/accounting_method/` directory and give it a meaningful name (like fifo.py)
* import the following (plus any other RP2 or Python package you might need):
```
from typing import Optional
from rp2.abstract_accounting_method import AbstractAccountingMethod
from rp2.abstract_accounting_method import AcquiredLotCandidates, AcquiredLotCandidatesOrder, AcquiredLotAndAmount
from rp2.abstract_transaction import AbstractTransaction
from rp2.in_transaction import InTransaction
from rp2.rp2_decimal import ZERO, RP2Decimal
```
* Add a class named `AccountingMethod`, deriving from `AbstractAccountingMethod`:
```
class AccountingMethod(AbstractAccountingMethod):
```
* Add a `seek_non_exhausted_acquired_lot()` method to the class with the following signature:
```
def seek_non_exhausted_acquired_lot(
self,
lot_candidates: AcquiredLotCandidates,
taxable_event: Optional[AbstractTransaction],
taxable_event_amount: RP2Decimal,
) -> Optional[AcquiredLotAndAmount]:
```
* write the body of the method. The parameters/return values are:
* `lot_candidates`: iterable of acquired lot candidates to select from according to the accounting method. The lots are in the order specified by the `lot_candidates_order()` method (see below);
* `taxable_event`: the taxable event the method is finding an acquired lot to pair with;
* `taxable_event_amount`: the amount left in taxable event;
* it returns `None` if it doesn't find a suitable acquired lot, or `AcquiredLotAndAmount`, which captures a new acquired lot and its remaining amount. Note that, since lots can be fractioned, the remaining amount can be less than `crypto_in`. In the body of the function use the `has_partial_amount()` and `get_partial_amount()` methods of `AcquiredLotCandidates` to check if the lot has a partial amount and how much it is.
* Add a `lot_candidates_order()` method to the class with the following signature:
```
def lot_candidates_order(self) -> AcquiredLotCandidatesOrder:
```
* write the body of the method: it returns `AcquiredLotCandidatesOrder.OLDER_TO_NEWER` or `AcquiredLotCandidatesOrder.NEWER_TO_OLDER`, depending on whether the desired chronological order is ascending or descending.
**NOTE**: If you're interested in adding support for a new accounting method, open a [PR](CONTRIBUTING.md).
### Adding Support for a New Country
RP2 has built-in support for the US but it also has infrastructure to support other countries. The abstract superclass of country plugins is [AbstractCountry](src/rp2/abstract_country.py), which captures the following:
* country code (2-letter string in [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) format);
* currency code (3-letter string in [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) format);
* long term capital gain period in days (e.g. for the US it's 365);
* accepted accounting methods;
* accepted report generators;
* default language for the country.
To add a new plugin follow this procedure:
* add a new Python file to the `src/rp2/plugin/country/` directory and name it after the ISO 3166-1 alpha-2, 2-letter code for the country (e.g. us.py or jp.py);
* add a class named as the ISO 3166-1 alpha-2, 2-letter code for the country (all uppercase), deriving from AbstractCountry;
* in the constructor invoke the superclass constructor passing in country code and currency code;
* add the `get_long_term_capital_gain_period()` method with the appropriate value. If there is no long-term capital gains, return `sys.maxsize`;
* `get_default_accounting_method()` method returning accounting method to use if the user doesn't specify one on the command line (e.g. for the US case it's `"fifo"`);
* `get_accounting_methods()` method returning a set of accounting methods that are accepted in the country (e.g. `{"fifo"}`);
* `get_report_generators()`: method returning a set of report generators to use if the user doesn't specify them on the command line;
* `get_default_generation_language()`: method returning the default language (in [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) format) to use at report generation if the user doesn't specify it on the command line;
* `rp2_entry()` global function calling `rp2_main()` and passing it an instance of the new country class (in fact technically subclasses of `AbstractCountry` are entry points, not plugins).
As an example see the [us.py](src/rp2/plugin/country/us.py) file.
Finally add a console script to [setup.cfg](setup.cfg) pointing the new country rp2_entry (see the US example in the console_scripts section of setup.cfg).
## Localization
RP2 supports generation of tax reports in any language via the Babel Python package. For example the JP country plugin accepts the rp2_full_report and the open_positions report generators. The user can use the `-g` command line option to generate Japanese taxes in English, Japanese, or any language for which there are translations (the argument to `-g` is a [ISO 639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) format, 2-letter string). Translatable strings are enclosed in the code with `_(...)` (see examples in the [rp2_full_report](src/rp2/plugin/report/rp2_full_report.py) plugin).
Localizable strings and their translations are kept in the `src/rp2/locales` directory and here's how to manage them, when strings change in the code:
* generate the main message catalog (locales/messages.pot):
```pybabel extract . -o src/rp2/locales/messages.pot --no-wrap --sort-output --copyright-holder=eprbell --project=rp2 --version=`cat .bumpversion.cfg | grep "current_version =" | cut -f3 -d " "` --no-location src ```
* manage language-specific catalogs (which are generated from src/rp2/locales/messages.pot): this step updates locales/<language>/LC_MESSAGES/messages.po:
* if the .po file doesn't exist, add support for a new language by creating a new translation catalog:
```pybabel init --no-wrap -l ja -i src/rp2/locales/messages.pot -d src/rp2/locales```
* or if the .po file already exists, update the catalog for a language:
```pybabel update -i src/rp2/locales/messages.pot -d src/rp2/locales --no-wrap```
* manually translate any new strings: open src/rp2/locales/<language>/LC_MESSAGES/messages.po and add the missing translations in `msgstr` lines. If you don't know how to translate strings for a language leave them blank.
* check for `fuzzy`-marked translations in src/rp2/locales/<language>/LC_MESSAGES/messages.po: sometimes Babel marks a translation as `fuzzy` in the .po file. Such entries must be reviewed manually for correctness and then the `fuzzy` comment must be removed (otherwise that translation doesn't get included at runtime).
* compile the .po file into the final binary format (.mo): this step updates src/rp2/locales/<language>/LC_MESSAGES/messages.mo:
```pybabel compile -d src/rp2/locales```
## Frequently Asked Developer Questions
Read the [frequently asked developer questions](docs/developer_faq.md).
| /rp2-1.5.0.tar.gz/rp2-1.5.0/README.dev.md | 0.650689 | 0.741463 | README.dev.md | pypi |
from dataclasses import replace
from typing import Callable, Generator, List, Tuple
from .instruction import Instruction, ProgramCounterAdvance
from .instruction_decoder import InstructionDecoder
from .shift_register import ShiftRegister
from .state import State
def emulate(
opcodes: List[int],
*,
stop_when: Callable[[int, State], bool],
initial_state: State = State(),
input_source: Callable[[int], int] | None = None,
shift_isr_right: bool = True,
shift_osr_right: bool = True,
side_set_base: int = 0,
side_set_count: int = 0,
jmp_pin: int = 0,
) -> Generator[Tuple[State, State], None, None]:
"""
Create and return a generator for emulating the given PIO program.
Parameters
----------
opcodes : List[int]
PIO program to emulate.
stop_when : function
Predicate used to determine if the emulation should stop or continue.
initial_state : State, optional
Initial values to use.
shift_isr_right : bool, optional
Shift the Input Shift Reigster (ISR) to the right when True and to the left when False.
shift_osr_right : bool, optional
Shift the Output Shift Reigster (OSR) to the right when True and to the left when False.
side_set_base : int, optional
First pin to use for the side-set.
side_set_count : int
Number of consecutive pins to include within the side-set.
jmp_pin : int
Pin that determines the branch taken by JMP PIN instructions.
Returns
-------
generator
"""
if stop_when is None:
raise ValueError("emulate() missing value for keyword argument: 'stop_when'")
shift_isr_method = (
ShiftRegister.shift_right if shift_isr_right else ShiftRegister.shift_left
)
shift_osr_method = (
ShiftRegister.shift_right if shift_osr_right else ShiftRegister.shift_left
)
instruction_decoder = InstructionDecoder(
shift_isr_method, shift_osr_method, jmp_pin
)
wrap_top = len(opcodes) - 1
current_state = initial_state
stalled = False
while not stop_when(opcodes[current_state.program_counter], current_state):
previous_state = current_state
if input_source:
masked_values = current_state.pin_values & current_state.pin_directions
masked_input = input_source(current_state.clock) & ~current_state.pin_directions
current_state = replace(
current_state,
pin_values=masked_values | masked_input,
)
opcode = opcodes[current_state.program_counter]
(side_set_value, delay_value) = _extract_delay_and_side_set_from_opcode(
opcode, side_set_count
)
instruction = instruction_decoder.decode(opcode)
if instruction is None:
return
condition_met = instruction.condition(current_state)
if condition_met:
new_state = instruction.callable(current_state)
if new_state is not None:
current_state = new_state
stalled = False
else:
stalled = True
current_state = _apply_side_effects(opcode, current_state)
# TODO: Check that the following still applies when an instruction is stalled
if side_set_count > 0:
current_state = _apply_side_set_to_pin_values(
current_state, side_set_base, side_set_count, side_set_value
)
if not stalled:
current_state = _advance_program_counter(
instruction, condition_met, 0, wrap_top, current_state
)
current_state = _apply_delay_value(
opcode, condition_met, delay_value, current_state
)
current_state = replace(current_state, clock=current_state.clock + 1)
yield (previous_state, current_state)
def _advance_program_counter(
instruction: Instruction,
condition_met: bool,
wrap_bottom: int,
wrap_top: int,
state: State,
) -> State:
if state.program_counter == wrap_top:
new_pc = wrap_bottom
else:
new_pc = state.program_counter + 1
match instruction.program_counter_advance:
case ProgramCounterAdvance.ALWAYS:
return replace(state, program_counter=new_pc)
case ProgramCounterAdvance.WHEN_CONDITION_MET if condition_met:
return replace(state, program_counter=new_pc)
case ProgramCounterAdvance.WHEN_CONDITION_NOT_MET if not condition_met:
return replace(state, program_counter=new_pc)
case _:
return state
def _apply_delay_value(
opcode: int, condition_met: bool, delay_value: int, state: State
) -> State:
jump_instruction = (opcode >> 13) == 0
if jump_instruction or condition_met:
return replace(state, clock=state.clock + delay_value)
return state
def _apply_side_effects(opcode: int, state: State) -> State:
if (opcode & 0xE0E0) == 0x0040:
return replace(state, x_register=state.x_register - 1)
elif (opcode & 0xE0E0) == 0x0080:
return replace(state, y_register=state.y_register - 1)
else:
return state
def _extract_delay_and_side_set_from_opcode(
opcode: int, side_set_count: int
) -> Tuple[int, int]:
combined_values = (opcode >> 8) & 0x1F
bits_for_delay = 5 - side_set_count
delay_mask = (1 << bits_for_delay) - 1
return (combined_values >> bits_for_delay, combined_values & delay_mask)
def _apply_side_set_to_pin_values(
state: State, pin_base: int, pin_count: int, pin_values: int
) -> State:
bit_mask = ~(((1 << pin_count) - 1) << pin_base) & 0xFFFF
new_pin_values = (state.pin_values & bit_mask) | (pin_values << pin_base)
return replace(state, pin_values=new_pin_values) | /rp2040_pio_emulator-0.81.0-py3-none-any.whl/pioemu/emulation.py | 0.867892 | 0.496643 | emulation.py | pypi |
from functools import partial
from typing import Callable, List, Tuple
from .conditions import (
always,
gpio_low,
gpio_high,
input_shift_register_full,
negate,
output_shift_register_empty,
x_register_equals_zero,
x_register_not_equal_to_y_register,
x_register_not_equal_to_zero,
y_register_equals_zero,
y_register_not_equal_to_zero,
)
from .instruction import Instruction, ProgramCounterAdvance
from .instructions.pull import (
pull_blocking,
pull_nonblocking,
)
from .instructions.push import (
push_blocking,
push_nonblocking,
)
from .primitive_operations import (
read_from_isr,
shift_into_isr,
read_from_osr,
shift_from_osr,
read_from_pins,
read_from_x,
read_from_y,
stall_unless_predicate_met,
supplies_value,
write_to_isr,
write_to_osr,
write_to_pin_directions,
write_to_pins,
write_to_program_counter,
write_to_x,
write_to_y,
write_to_null,
)
from .shift_register import ShiftRegister
from .state import State
class InstructionDecoder:
"""
Decodes opcodes representing instructions into callables that emulate those
instructions.
"""
def __init__(
self,
shift_isr_method: Callable[[ShiftRegister, int], Tuple[ShiftRegister, int]],
shift_osr_method: Callable[[ShiftRegister, int], Tuple[ShiftRegister, int]],
jmp_pin: int,
):
"""
Parameters
----------
isr_shift_method : Callable[[ShiftRegister, int], Tuple[ShiftRegister, int]]
Method to use to shift the contents of the Input Shift Register.
osr_shift_method : Callable[[ShiftRegister, int], Tuple[ShiftRegister, int]]
Method to use to shift the contents of the Output Shift Register.
jmp_pin : int
Pin that determines the branch taken by JMP PIN instructions.
"""
self.shift_isr_method = shift_isr_method
self.shift_osr_method = shift_osr_method
self.decoding_functions: List[Callable[[int], Instruction | None]] = [
self._decode_jmp,
self._decode_wait,
self._decode_in,
self._decode_out,
self._decode_push_pull,
self._decode_mov,
lambda _: None,
self._decode_set,
]
self.jmp_conditions: List[Callable[[State], bool]] = [
always,
x_register_equals_zero,
x_register_not_equal_to_zero,
y_register_equals_zero,
y_register_not_equal_to_zero,
x_register_not_equal_to_y_register,
partial(gpio_high, jmp_pin),
negate(output_shift_register_empty),
]
self.in_sources: List[Callable[[State], int] | None] = [
read_from_pins,
read_from_x,
read_from_y,
supplies_value(0),
None,
None,
read_from_isr,
read_from_osr,
]
self.mov_sources: List[Callable[[State], int] | None] = [
read_from_pins,
read_from_x,
read_from_y,
supplies_value(0),
None,
None,
read_from_isr,
read_from_osr,
]
self.mov_destinations: List[
Callable[[Callable[[State], int], State], State] | None
] = [
write_to_pins,
write_to_x,
write_to_y,
None,
None,
write_to_program_counter,
write_to_isr,
write_to_osr,
]
# FIXME: Different signature used by write_to_isr() conflicts with type-hints
self.out_destinations = [
write_to_pins,
write_to_x,
write_to_y,
write_to_null,
write_to_pin_directions,
write_to_program_counter,
write_to_isr,
None,
]
self.set_destinations: List[
Callable[[Callable[[State], int], State], State] | None
] = [
write_to_pins,
write_to_x,
write_to_y,
None,
write_to_pin_directions,
None,
None,
None,
]
def decode(self, opcode: int) -> Instruction | None:
"""
Decodes the given opcode and returns a callable which emulates it.
Parameters:
opcode (int): The opcode to decode.
Returns:
Instruction: Representation of the instruction or None.
"""
decoding_function = self.decoding_functions[(opcode >> 13) & 7]
return decoding_function(opcode)
def _decode_jmp(self, opcode: int) -> Instruction | None:
address = opcode & 0x1F
condition = self.jmp_conditions[(opcode >> 5) & 7]
if condition is not None:
return Instruction(
condition,
partial(write_to_program_counter, supplies_value(address)),
ProgramCounterAdvance.WHEN_CONDITION_NOT_MET,
)
return None
def _decode_mov(self, opcode: int) -> Instruction | None:
read_from_source = self.mov_sources[opcode & 7]
destination = (opcode >> 5) & 7
write_to_destination = self.mov_destinations[destination]
if read_from_source is None or write_to_destination is None:
return None
operation = (opcode >> 3) & 3
if operation == 1:
data_supplier = lambda state: read_from_source(state) ^ 0xFFFF_FFFF
else:
data_supplier = read_from_source
if destination == 5: # Program counter
program_counter_advance = ProgramCounterAdvance.NEVER
else:
program_counter_advance = ProgramCounterAdvance.ALWAYS
return Instruction(
always,
partial(write_to_destination, data_supplier),
program_counter_advance,
)
def _decode_in(self, opcode: int) -> Instruction | None:
read_from_source = self.in_sources[(opcode >> 5) & 7]
bit_count = opcode & 0x1F
if bit_count == 0:
bit_count = 32
return Instruction(
always,
partial(shift_into_isr, read_from_source, self.shift_isr_method, bit_count),
ProgramCounterAdvance.ALWAYS,
)
def _decode_out(self, opcode: int) -> Instruction | None:
destination = (opcode >> 5) & 7
write_to_destination = self.out_destinations[destination]
bit_count = opcode & 0x1F
if bit_count == 0:
bit_count = 32
if write_to_destination is None:
return None
def emulate_out(state: State) -> State:
state, shift_result = shift_from_osr(
self.shift_osr_method, bit_count, state
)
# Somewhat hacky workaround because 'OUT, ISR' also sets ISR shift counter to the
# bit_count but no other command where the ISR is written to has a similar effect.
# See the description of the ISR destination on section 3.4.5.2 of the RP2040 Datasheet
if write_to_destination == write_to_isr:
return write_to_destination(
supplies_value(shift_result), state, count=bit_count
)
return write_to_destination(supplies_value(shift_result), state)
if destination == 5: # Program counter
return Instruction(always, emulate_out, ProgramCounterAdvance.NEVER)
return Instruction(always, emulate_out, ProgramCounterAdvance.ALWAYS)
def _decode_set(self, opcode: int) -> Instruction | None:
write_to_destination = self.set_destinations[(opcode >> 5) & 7]
if write_to_destination is None:
return None
return Instruction(
always,
partial(write_to_destination, supplies_value(opcode & 0x1F)),
ProgramCounterAdvance.ALWAYS,
)
@staticmethod
def _decode_push_pull(opcode: int) -> Instruction:
block = bool(opcode & 0x0020)
if opcode & 0x0080:
# Pull
condition = output_shift_register_empty if (opcode & 0x0040) else always
instruction = Instruction(
condition,
pull_blocking if block else pull_nonblocking,
ProgramCounterAdvance.ALWAYS,
)
else:
# Push
condition = input_shift_register_full if (opcode & 0x0040) else always
instruction = Instruction(
condition,
push_blocking if block else push_nonblocking,
ProgramCounterAdvance.ALWAYS,
)
return instruction
@staticmethod
def _decode_wait(opcode: int) -> Instruction | None:
index = opcode & 0x001F
if opcode & 0x0080:
condition = partial(gpio_high, index)
else:
condition = partial(gpio_low, index)
return Instruction(
always,
partial(stall_unless_predicate_met, condition),
ProgramCounterAdvance.ALWAYS,
) | /rp2040_pio_emulator-0.81.0-py3-none-any.whl/pioemu/instruction_decoder.py | 0.798658 | 0.316765 | instruction_decoder.py | pypi |
from typing import Tuple
try:
from typing import Self
except:
# For versions of Python < 3.11
from typing import TypeVar
Self = TypeVar("_Self", bound="A")
class ShiftRegister:
"""Immutable shift register for 32-bit values.
The value held can be shifted by an arbitrary number of bits in either direction. Instances of
this class are immutable and therefore new representations of the shift register are returned
from each of its methods.
Attributes
----------
contents : int
Value held within this shift register.
counter : int
Total number of bits shifted out of / into this shift register (0-32).
"""
def __init__(self, contents: int, counter: int):
self._contents = contents
self._counter = counter
@property
def contents(self) -> int:
"""Return the value held within this shift register."""
return self._contents
@property
def counter(self) -> int:
"""Return the total number of bits shifted out of / into this shift register."""
return self._counter
def shift_left(self, bit_count: int, data_in: int = 0) -> Tuple[Self, int]:
"""Shifts the most significant bits out of the shift register.
Parameters
----------
bit_count : int
Number of bits to shift into and out of the register.
data_in : int, optional
Value to shift into the register's least significant bits.
Returns
-------
Tuple[ShiftRegister, int]
Tuple containing the new representation of this shift register and the result.
"""
bit_mask = (1 << bit_count) - 1
new_contents = ((self._contents << bit_count) & 0xFFFF_FFFF) | (
data_in & bit_mask
)
new_counter = min(32, self._counter + bit_count)
return ShiftRegister(new_contents, new_counter), self._contents >> (
32 - bit_count
)
def shift_right(self, bit_count: int, data_in: int = 0) -> Tuple[Self, int]:
"""Shifts the least significant bits out of the shift register.
Parameters
----------
bit_count : int
Number of bits to shift into and out of the register.
data_in : int, optional
Value to shift into the register's most significant bits.
Returns
-------
Tuple[ShiftRegister, int]
Tuple containing the new representation of this shift register and the result.
"""
bit_mask = (1 << bit_count) - 1
new_contents = (self._contents >> bit_count) | (
(data_in & bit_mask) << (32 - bit_count)
)
new_counter = min(32, self._counter + bit_count)
return (
ShiftRegister(new_contents, new_counter),
self._contents & bit_mask,
)
def __eq__(self, other: object) -> bool:
if self.__class__ is other.__class__:
return (self._contents, self._counter) == (other._contents, other._counter)
return NotImplemented
def __repr__(self) -> str:
return f"ShiftRegister(contents={self._contents!r}, counter={self._counter!r})" | /rp2040_pio_emulator-0.81.0-py3-none-any.whl/pioemu/shift_register.py | 0.961125 | 0.606236 | shift_register.py | pypi |
from dataclasses import replace
from typing import Callable, Tuple
from .shift_register import ShiftRegister
from .state import State
def read_from_isr(state: State) -> int:
"""Reads the contents of the input shift register."""
return state.input_shift_register.contents
def shift_into_isr(
data_supplier: Callable[[State], int],
shift_method: Callable[[ShiftRegister, int, int], Tuple[ShiftRegister, int]],
bit_count: int,
state: State,
) -> State:
"""Shifts the given data into the input shift register."""
new_isr, _ = shift_method(
state.input_shift_register, bit_count, data_supplier(state)
)
return replace(state, input_shift_register=new_isr)
def read_from_osr(state: State) -> int:
"""Reads the contents of the output shift register."""
return state.output_shift_register.contents
def shift_from_osr(
shift_method: Callable[[ShiftRegister, int], Tuple[ShiftRegister, int]],
bit_count: int,
state: State,
) -> Tuple[State, int]:
"""Shift the requested number of bits out of the output shift register."""
new_osr, shift_result = shift_method(state.output_shift_register, bit_count)
return (
replace(
state,
output_shift_register=new_osr,
),
shift_result,
)
def read_from_pin_directions(state: State) -> int:
"""Reads the contents of the pin direction register."""
return state.pin_directions
def read_from_pins(state: State) -> int:
"""Reads the contents of the pin values register."""
return state.pin_values
def read_from_x(state: State) -> int:
"""Reads the contents of the X scratch register."""
return state.x_register
def read_from_y(state: State) -> int:
"""Reads the contents of the Y scratch register."""
return state.y_register
def write_to_isr(
data_supplier: Callable[[State], int], state: State, count: int = 0
) -> State:
"""Copies the given data into the input shift register."""
return replace(
state,
input_shift_register=ShiftRegister(data_supplier(state) & 0xFFFF_FFFF, count),
)
def write_to_osr(
data_supplier: Callable[[State], int], state: State, count: int = 0
) -> State:
"""Copies the given data into the output shift register."""
return replace(
state,
output_shift_register=ShiftRegister(data_supplier(state) & 0xFFFF_FFFF, count),
)
def write_to_pin_directions(
data_supplier: Callable[[State], int], state: State
) -> State:
"""Copies the given data into the pin directions register."""
return replace(state, pin_directions=data_supplier(state) & 0xFFFF_FFFF)
def write_to_pins(data_supplier: Callable[[State], int], state: State) -> State:
"""Copies the given data into the pin values register."""
return replace(state, pin_values=data_supplier(state) & 0xFFFF_FFFF)
def write_to_program_counter(
data_supplier: Callable[[State], int], state: State
) -> State:
"""Copies the given data into the program counter."""
return replace(state, program_counter=data_supplier(state) & 0x1F)
def write_to_x(data_supplier: Callable[[State], int], state: State) -> State:
"""Copies the given data into the X scratch register."""
return replace(state, x_register=data_supplier(state) & 0xFFFF_FFFF)
def write_to_y(data_supplier: Callable[[State], int], state: State) -> State:
"""Copies the given data into the Y scratch register."""
return replace(state, y_register=data_supplier(state) & 0xFFFF_FFFF)
def write_to_null(data_supplier: Callable[[State], int], state: State) -> State:
"""Discards the given data."""
_ = data_supplier(state)
return state
def supplies_value(value: int) -> Callable[[State], int]:
"""Creates a function that returns the specified value when invoked."""
return lambda _: value
def stall_unless_predicate_met(
predicate: Callable[[State], bool],
state: State,
) -> State | None:
if predicate(state):
return state
return None # Represents a stall | /rp2040_pio_emulator-0.81.0-py3-none-any.whl/pioemu/primitive_operations.py | 0.940875 | 0.705529 | primitive_operations.py | pypi |
import time
import utime
import uasyncio
from machine import Pin, PWM, ADC
class SimpleOut:
def __init__(self, pin, default=0):
self.pin = Pin(pin, Pin.OUT)
self.pin.value(default)
def read(self):
return self.pin.value()
def write(self, value):
return self.pin.value(value)
def toggle(self):
value = 1 - self.pin.value()
self.pin.value(value)
def on(self):
self.pin.value(1)
def off(self):
self.pin.value(0)
class SimpleIn:
def __init__(self, pin, default=Pin.PULL_UP):
self.pin = Pin(pin, Pin.IN, default)
def read(self):
return self.pin.value()
def write(self, value):
return self.pin.value(value)
class Button(SimpleIn):
def __init__(self, pin, default=Pin.PULL_UP):
"""
A button is a simple input that can be pressed.
:param pin: pin
:param default: default value Pin.PULL_UP or Pin.PULL_DOWN
"""
super().__init__(pin, default)
if default == Pin.PULL_UP:
self.default = 1
elif default == Pin.PULL_DOWN:
self.default = 0
else:
raise ValueError("default must be Pin.PULL_UP or Pin.PULL_DOWN")
def is_pressed(self, wait=True):
"""
Returns True if the button is pressed.
"""
if not wait:
return self.pin.value() != self.default
if self.pin.value() != self.default:
utime.sleep_ms(15)
if self.pin.value() != self.default:
return True
return False
async def async_is_pressed(self, wait=True):
"""
Returns True if the button is pressed.
"""
if not wait:
return self.pin.value() != self.default
if self.pin.value() != self.default:
await uasyncio.sleep_ms(15)
if self.pin.value() != self.default:
return True
return False
def is_released(self, wait=True):
"""
Returns True if the button is released.
"""
if not wait:
return self.pin.value() == self.default
if self.pin.value() == self.default:
utime.sleep_ms(15)
if self.pin.value() == self.default:
return True
return False
async def async_is_released(self, wait=True):
"""
Returns True if the button is released.
"""
if not wait:
return self.pin.value() == self.default
if self.pin.value() == self.default:
await uasyncio.sleep_ms(15)
if self.pin.value() == self.default:
return True
return False
def pressed(self, callback=None, hard=False):
"""
设置按键按下回调
"""
if callback is None:
return
self.pin.irq(trigger=Pin.IRQ_FALLING if self.default else Pin.IRQ_RISING, handler=callback, hard=hard)
def released(self, callback=None, hard=False):
"""
设置按键释放回调
"""
if callback is None:
return
self.pin.irq(trigger=Pin.IRQ_RISING if self.default else Pin.IRQ_FALLING, handler=callback, hard=hard)
def pressed_or_released(self, callback=None, hard=False):
"""
设置按键按下或释放回调
"""
if callback is None:
return
self.pin.irq(trigger=Pin.IRQ_RISING | Pin.IRQ_FALLING, handler=callback, hard=hard)
class MatrixButton:
def __init__(self, shape, *pins):
self.pins_R = list(pins[:shape[0]])
self.pins_C = list(pins[shape[0]:])
self.shape = shape
def read_row(self):
for pin in self.pins_C:
Pin(pin, Pin.OUT).value(1)
result = [Pin(pin, Pin.IN, Pin.PULL_DOWN).value() for pin in self.pins_R]
time.sleep_ms(15)
for i, pin in enumerate(self.pins_R):
result[i] = Pin(pin, Pin.IN, Pin.PULL_DOWN).value() and result[i]
return result
def read_col(self):
for pin in self.pins_R:
Pin(pin, Pin.OUT).value(1)
result = [Pin(pin, Pin.IN, Pin.PULL_DOWN).value() for pin in self.pins_C]
time.sleep_ms(15)
for i, pin in enumerate(self.pins_C):
result[i] = Pin(pin, Pin.IN, Pin.PULL_DOWN).value() and result[i]
return result
def read(self):
data = [self.read_row(), self.read_col()]
result = [[] for _ in range(self.shape[0])]
for i in range(self.shape[0]):
for j in range(self.shape[1]):
result[i].append(data[0][i] and data[1][j])
return result
class Led:
def __init__(self, pin, status=False, grade=0xFFFF):
"""
:param pin: pin
:param grade: 0-65535
"""
self.pwm = PWM(Pin(pin))
self.pwm.freq(1000)
self.grade = grade
self.pwm.duty_u16(grade if status else 0)
def toggle(self, grade=None):
"""
switch the LED on or off.
:param grade: 0-65535
"""
if grade:
self.grade = grade
self.pwm.duty_u16(self.grade)
elif self.pwm.duty_u16() == 0:
self.pwm.duty_u16(self.grade)
else:
self.pwm.duty_u16(0)
def on(self):
self.pwm.duty_u16(self.grade)
def off(self):
self.pwm.duty_u16(0)
def read(self):
return self.pwm.duty_u16()
def write(self, value):
self.pwm.duty_u16(value) | /rp2040-tools-0.0.8.tar.gz/rp2040-tools-0.0.8/rp2040/base.py | 0.608129 | 0.256378 | base.py | pypi |
import utime
def _clamp(value, limits):
lower, upper = limits
if value is None:
return None
elif (upper is not None) and (value > upper):
return upper
elif (lower is not None) and (value < lower):
return lower
return value
class PID(object):
"""A simple PID controller."""
def __init__(
self,
Kp=1.0,
Ki=0.0,
Kd=0.0,
setpoint=0,
sample_time=None,
scale='s',
output_limits=[None, None],
auto_mode=True,
proportional_on_measurement=False,
error_map=None
):
"""
Initialize a new PID controller.
:param Kp: The value for the proportional gain Kp
:param Ki: The value for the integral gain Ki
:param Kd: The value for the derivative gain Kd
:param setpoint: The initial setpoint that the PID will try to achieve
:param sample_time: The interval in the setted scale which the controller should wait before generating
a new output value. The PID works best when it is constantly called (eg. during a
loop), but with a sample time set so that the time difference between each update is
(close to) constant. If set to None, the PID will compute a new output value every time
it is called, keep None to use param dt for timestep.
:param scale: Set the scale of the controller, accepted values are 's' for seconds, 'ms' for
miliseconds, 'us' for microseconds, 'ns' for nanoscondas and 'cpu' for the highest precision
at cpu clock. On default and on error set to seconds.
:param output_limits: The initial output limits to use, given as an iterable with 2
elements, for example: (lower, upper). The output will never go below the lower limit
or above the upper limit. Either of the limits can also be set to None to have no limit
in that direction. Setting output limits also avoids integral windup, since the
integral term will never be allowed to grow outside of the limits.
:param auto_mode: Whether the controller should be enabled (auto mode) or not (manual mode)
:param proportional_on_measurement: Whether the proportional term should be calculated on
the input directly rather than on the error (which is the traditional way). Using
proportional-on-measurement avoids overshoot for some types of systems.
:param error_map: Function to transform the error value in another constrained value.
"""
self.Kp, self.Ki, self.Kd = Kp, Ki, Kd
self.setpoint = setpoint
self.sample_time = sample_time
def get_scale(x):
return {
's': 'time',
'ms': 'ticks_ms',
'us': 'ticks_us',
'ns': 'time_ns',
'cpu': 'ticks_cpu'
}.get(x, 'time') # seconds is default if x is not found
self.scale = get_scale(scale)
def get_unit(x):
return {
's': 1,
'ms': 1e-3,
'us': 1e-6,
'ns': 1e-9,
'cpu': 1
}.get(x, 1) # tunings should be explicitly defined at 'ticks_cpu'
self.unit = get_unit(scale)
if hasattr(utime, self.scale) and callable(func := getattr(utime, self.scale)):
self.time = func
self._min_output, self._max_output = None, None
self._auto_mode = auto_mode
self.proportional_on_measurement = proportional_on_measurement
self.error_map = error_map
self._proportional = 0
self._integral = 0
self._derivative = 0
self._last_time = None
self._last_output = None
self._last_input = None
self.output_limits = output_limits
self.reset()
def __call__(self, input_, dt=None):
"""
Update the PID controller.
Call the PID controller with *input_* and calculate and return a control output if
sample_time has passed since the last update. If no new output is calculated,
return the previous output instead (or None if no value has been calculated yet).
:param dt: If set, uses this value for timestep instead of real time. This can be used in
simulations when simulation time is different from real time.
"""
if not self.auto_mode:
return self._last_output
now = self.time()
if dt is None:
dt = utime.ticks_diff(now, self._last_time) if (utime.ticks_diff(now, self._last_time)) else 1e-16
elif dt <= 0:
raise ValueError('dt has negative value {}, must be positive'.format(dt))
if self.sample_time is not None and dt < self.sample_time and self._last_output is not None:
# Only update every sample_time
return self._last_output
# Compute error terms
error = self.setpoint - input_
d_input = input_ - (self._last_input if (self._last_input is not None) else input_)
# Check if must map the error
if self.error_map is not None:
error = self.error_map(error)
# Compute the proportional term
if not self.proportional_on_measurement:
# Regular proportional-on-error, simply set the proportional term
self._proportional = self.Kp * error
else:
# Add the proportional error on measurement to error_sum
self._proportional -= self.Kp * self.unit * d_input
# Compute integral and derivative terms
self._integral += (self.Ki * self.unit) * error * dt
self._integral = _clamp(self._integral, self.output_limits) # Avoid integral windup
self._derivative = -(self.Kd / self.unit) * d_input / dt
# Compute final output
output = self._proportional + self._integral + self._derivative
output = _clamp(output, self.output_limits)
# Keep track of state
self._last_output = output
self._last_input = input_
self._last_time = now
return output
def __repr__(self):
return (
'{self.__class__.__name__}('
'Kp={self.Kp!r}, Ki={self.Ki!r}, Kd={self.Kd!r}, '
'setpoint={self.setpoint!r}, sample_time={self.sample_time!r}, '
'output_limits={self.output_limits!r}, auto_mode={self.auto_mode!r}, '
'proportional_on_measurement={self.proportional_on_measurement!r},'
'error_map={self.error_map!r}'
')'
).format(self=self)
@property
def components(self):
"""
The P-, I- and D-terms from the last computation as separate components as a tuple. Useful
for visualizing what the controller is doing or when tuning hard-to-tune systems.
"""
return self._proportional, self._integral, self._derivative
@property
def tunings(self):
"""The tunings used by the controller as a tuple: (Kp, Ki, Kd)."""
return self.Kp, self.Ki, self.Kd
@tunings.setter
def tunings(self, tunings):
"""Set the PID tunings."""
self.Kp, self.Ki, self.Kd = tunings
@property
def auto_mode(self):
"""Whether the controller is currently enabled (in auto mode) or not."""
return self._auto_mode
@auto_mode.setter
def auto_mode(self, enabled):
"""Enable or disable the PID controller."""
self.set_auto_mode(enabled)
def set_auto_mode(self, enabled, last_output=None):
"""
Enable or disable the PID controller, optionally setting the last output value.
This is useful if some system has been manually controlled and if the PID should take over.
In that case, disable the PID by setting auto mode to False and later when the PID should
be turned back on, pass the last output variable (the control variable) and it will be set
as the starting I-term when the PID is set to auto mode.
:param enabled: Whether auto mode should be enabled, True or False
:param last_output: The last output, or the control variable, that the PID should start
from when going from manual mode to auto mode. Has no effect if the PID is already in
auto mode.
"""
if enabled and not self._auto_mode:
# Switching from manual mode to auto, reset
self.reset()
self._integral = last_output if (last_output is not None) else 0
self._integral = _clamp(self._integral, self.output_limits)
self._auto_mode = enabled
@property
def output_limits(self):
"""
The current output limits as a 2-tuple: (lower, upper).
See also the *output_limits* parameter in :meth:`PID.__init__`.
"""
return self._min_output, self._max_output
@output_limits.setter
def output_limits(self, limits):
"""Set the output limits."""
if limits is None:
self._min_output, self._max_output = None, None
return
min_output, max_output = limits
if (None not in limits) and (max_output < min_output):
raise ValueError('lower limit must be less than upper limit')
self._min_output = min_output
self._max_output = max_output
self._integral = _clamp(self._integral, self.output_limits)
self._last_output = _clamp(self._last_output, self.output_limits)
def reset(self):
"""
Reset the PID controller internals.
This sets each term to 0 as well as clearing the integral, the last output and the last
input (derivative calculation).
"""
self._proportional = 0
self._integral = 0
self._derivative = 0
self._integral = _clamp(self._integral, self.output_limits)
self._last_time = self.time()
self._last_output = None
self._last_input = None | /rp2040-tools-0.0.8.tar.gz/rp2040-tools-0.0.8/rp2040/algorithm/PID.py | 0.89762 | 0.480418 | PID.py | pypi |
from machine import Pin, PWM
class SimpleServo360:
def __init__(self, pin):
"""
:param pin: pin
"""
self.pwm = PWM(Pin(pin))
self.pwm.freq(50)
self.stop()
def stop(self):
"""
停止
"""
self.pwm.duty_ns(1_500_000)
def clockwise(self, speed=1000):
"""
顺时针旋转
:param speed: 0-1000
"""
if speed <= 0:
self.stop()
elif speed > 1000:
speed = 1000
self.pwm.duty_ns(1_500_000 + speed * 1_000)
def anticlockwise(self, speed=1000):
"""
逆时针旋转
:param speed: 0-1000
"""
if speed <= 0:
self.stop()
elif speed > 1000:
speed = 1000
self.pwm.duty_ns(1_500_000 - speed * 1_000)
class SimpleServo:
def __init__(self, pin, angle, offset=0, angle_range=None):
"""
:param pin: pin
:param offset: 偏移量
:param angle_range: (-90, 90) 角度范围
"""
if angle_range is None:
angle_range = (-angle, angle)
self._angle = 0
self.__angle = 2_000_000 / angle
self.offset = offset
self.offset_range = (angle_range[0] - offset, angle_range[1] - offset)
self._range = None
self.range(angle_range)
self.pwm = PWM(Pin(pin))
self.pwm.freq(50)
self.stop()
def range(self, angle_range=None):
"""
设置角度范围
:param angle_range: (-90, 90)
"""
if angle_range is None:
return self._range
self._range = (
max(angle_range[0], self.offset_range[0]),
min(angle_range[1], self.offset_range[1])
)
return self._range
def stop(self):
"""
停止并居中
"""
self.angle(0)
def angle(self, angle=None):
"""
设置角度
:param angle: -90~90
"""
if angle is None:
return self._angle
if angle < self._range[0]:
angle = self._range[0]
elif angle > self._range[1]:
angle = self._range[1]
self.pwm.duty_ns(int(1_500_000 + (angle + self.offset) * self.__angle))
class SimpleServo180(SimpleServo):
def __init__(self, pin, offset=0, angle_range=None):
super().__init__(pin, 180, offset, angle_range)
class SimpleServo270(SimpleServo):
def __init__(self, pin, offset=0, angle_range=None):
super().__init__(pin, 270, offset, angle_range)
MG995D360 = SimpleServo360
MG995D180 = SimpleServo180
SG90180 = SimpleServo180
TBS_K20 = SimpleServo270 | /rp2040-tools-0.0.8.tar.gz/rp2040-tools-0.0.8/rp2040/powerhouse/servo.py | 0.696268 | 0.390302 | servo.py | pypi |
from machine import UART
import time
def func_timeout_ms(timeout: int = 1000):
"""
调用函数,超时返回
:param timeout: 超时时间
:return: 函数返回值
"""
def A(func):
def B(*args, **kwargs):
start_time = time.ticks_ms()
while True:
if time.ticks_ms() - start_time > timeout:
return None
result = func(*args, **kwargs)
if result is not None:
return result
return B
return A
class AT:
def __init__(self, mode: str = '', param: list = None):
if param is None:
param = []
self.mode = mode
self.param = param
def __str__(self):
return f'AT+{self.mode}=' + ','.join(self.param)
class HC04:
def __init__(self, uart: UART):
self.uart = uart
"""
通用指令
"""
def test(self):
"""
测试通讯
:return: bool
"""
self.uart.write(b'AT')
return self.uart.read(2) == b'OK'
def change_baudrate(self, baudrate: int = 9600, parity: str = 'N'):
"""
改蓝牙串口通讯波特率和校验位
:param baudrate: 波特率
:param parity: 校验位 N/E/O 无/偶/奇
"""
self.uart.write(b'AT+BAUD=' + str(baudrate).encode('utf-8') + b',' + parity.encode('utf-8'))
result = self.uart.read(2) == b'OK'
self.uart.read()
return result
def get_version(self):
"""
获取版本号
:return: 版本号
"""
self.uart.write(b'AT+VERSION')
return self.uart.read().decode('utf-8')
def set_led(self, state: bool):
"""
设置LED灯
:param state: 状态 True/False
"""
self.uart.write(b'AT+LED=' + str(int(state)).encode('utf-8'))
return self.uart.read(2) == b'OK'
def get_led(self):
"""
获取LED灯状态
:return: 状态 True/False
"""
self.uart.write(b'AT+LED?')
return bool(self.uart.read().decode('utf-8')[-1])
def reset(self):
"""
参数恢复默认值指令
:return: bool
"""
self.uart.write(b'AT+DEFAULT')
return self.uart.read(2) == b'OK'
def reboot(self):
"""
重启模块
:return: bool
"""
self.uart.write(b'AT+RESET')
return self.uart.read(2) == b'OK'
def set_silent(self, state: bool):
"""
设置静默模式
:param state: 状态 True/False
"""
self.uart.write(b'AT+BTMODE=' + str(int(state)).encode('utf-8'))
return bool(self.uart.read().decode('utf-8')[-1])
def set_role(self, role: str = 'BM'):
"""
设置模块角色
:param role: 角色 BM/M/S
"""
self.uart.write(b'AT+ROLE=' + role.encode('utf-8'))
return self.uart.read()[:2] == b'OK'
def get_role(self):
"""
获取模块角色
:return: Master/Slave
"""
self.uart.write(b'AT+ROLE?')
return self.uart.read().decode('utf-8')
def clear(self):
"""
主机清除已记录的从机地址指令(仅主机有效)
:return: bool
"""
self.uart.write(b'AT+CLEAR')
return self.uart.read(2) == b'OK'
"""
SPP 部分指令
"""
def spp_set_name(self, name: str):
"""
设置蓝牙名称
:param name: 名称
"""
self.uart.write(b'AT+NAME=' + name.encode('utf-8'))
return self.uart.read()[:2] == b'OK'
def spp_set_password(self, password: str):
"""
设置蓝牙密码
:param password: 密码
"""
self.uart.write(b'AT+PIN=' + password.encode('utf-8'))
return self.uart.read()[:2] == b'OK'
def spp_get_password(self):
"""
获取蓝牙密码
:return: 密码
"""
self.uart.write(b'AT+PIN=?')
return self.uart.read().decode('utf-8').split('=')[1]
def spp_set_address(self, address: str):
"""
设置蓝牙地址, 地址为 12 位的 0~F 大写字符,即 16 进制字符。只能修改后 10 位的地址,前面 2 位固定为 04
:param address: 地址
"""
if len(address) != 10:
return False
self.uart.write(b'AT+ADDR=' + address.encode('utf-8'))
return self.uart.read()[:2] == b'OK'
def spp_get_address(self):
"""
获取蓝牙地址
:return: 地址
"""
self.uart.write(b'AT+ADDR=?')
return self.uart.read().decode('utf-8').split('=')[1]
def spp_set_code(self, code: str):
"""
设置蓝牙编码,修改模块的 COD,默认值是 001F00。支持 6~8 位的 COD,少于 6 位,前面补 0。
如果有输入除 0~F 之外的字符,COD 将设置为 000000
:param code: 编码
"""
self.uart.write(b'AT+CODE=' + code.encode('utf-8'))
return self.uart.read()[:2] == b'OK'
def spp_get_code(self):
"""
获取蓝牙编码
:return: 编码
"""
self.uart.write(b'AT+CODE=?')
return self.uart.read().decode('utf-8').split('=')[1]
"""
BLE 部分指令
"""
def ble_set_broadcast(self, state: bool):
"""
设置广播开关
:param state: 状态 True/False
"""
self.uart.write(b'AT+BLE=' + str(int(state)).encode('utf-8'))
return self.uart.read()[:2] == b'OK'
def ble_get_broadcast(self):
"""
获取广播开关
:return: 状态 True/False
"""
self.uart.write(b'AT+BLE=?')
return self.uart.read().decode('utf-8').split('=')[1] == '1'
def ble_set_name(self, name: str):
"""
设置蓝牙名称
:param name: 名称
"""
self.uart.write(b'AT+BNAME=' + name.encode('utf-8'))
return self.uart.read()[:2] == b'OK'
def ble_get_name(self):
"""
获取蓝牙名称
:return: 名称
"""
self.uart.write(b'AT+BNAME=?')
return self.uart.read().decode('utf-8').split('=')[1]
def ble_set_address(self, address: str):
"""
设置蓝牙地址, 地址为 12 位的 0~F 大写字符,即 16 进制字符。只能修改后 10 位的地址,前面 2 位固定为 C4
:param address: 地址
"""
if len(address) != 10:
return False
self.uart.write(b'AT+BADDR=' + address.encode('utf-8'))
return self.uart.read()[:2] == b'OK'
def ble_set_broadcast_interval(self, interval: int):
"""
设置广播间隔,xx 的单位是 625us(即,若 xx=1,广播间隔就是 625us*1=625us),范围32~16000(相当于 20ms~10s)
默认值是 100 (62.5ms)
:param interval: 间隔
"""
self.uart.write(b'AT+AINT=' + str(interval).encode('utf-8'))
return self.uart.read()[:2] == b'OK'
def ble_get_broadcast_interval(self):
"""
获取广播间隔
:return: 间隔
"""
self.uart.write(b'AT+AINT=?')
return int(self.uart.read().decode('utf-8').split('=')[1])
def ble_set_connect_interval(self, interval_min: int, interval_max: int):
"""
设置连接间隔
单位 1.25ms,设置范围 6~3199(7.5ms~4s)。
1、此值直接影响实际连接间隔:xx≤实际连接间隔≤yy
2、必须符合条件 xx≤yy
3、可以单独输入一个参数 xx,yy 将直接等于 xx。
4、默认值:8,11
:param interval_min: 最小间隔
:param interval_max: 最大间隔
"""
self.uart.write(b'AT+INT=' + str(interval_min).encode('utf-8') + b',' + str(interval_max).encode('utf-8'))
return self.uart.read()[:2] == b'OK'
def ble_get_connect_interval(self):
"""
获取连接间隔
:return: 间隔
"""
self.uart.write(b'AT+INT=?')
return self.uart.read().decode('utf-8').split('=')[1].split(',')
def ble_set_connect_timeout(self, timeout: int):
"""
设置连接超时
单位 10ms,设置范围 100~3200(1s~32s)
:param timeout: 超时
"""
self.uart.write(b'AT+CTOUT=' + str(timeout).encode('utf-8'))
return self.uart.read()[:2] == b'OK'
def ble_get_connect_timeout(self):
"""
获取连接超时
:return: 超时
"""
self.uart.write(b'AT+CTOUT=?')
return int(self.uart.read().decode('utf-8').split('=')[1])
def ble_set_slave_latency(self, latency: int):
"""
设置从机延迟
单位 10ms,设置范围 0~499(0~5s)
:param latency: 延迟
"""
self.uart.write(b'AT+LATENCY=' + str(latency).encode('utf-8'))
return self.uart.read()[:2] == b'OK'
def ble_get_slave_latency(self):
"""
获取从机延迟
:return: 延迟
"""
self.uart.write(b'AT+LATENCY=?')
return int(self.uart.read().decode('utf-8').split('=')[1])
def ble_set_search_uuid(self, uuid: str):
"""
设置搜索 UUID
由于蓝牙设备繁多,所以一般蓝牙主机(因为没有显示屏,很难人工选择)
都设置了搜索 UUID 过滤。这样的话, 只有 UUID 相同的从机才能被搜索到。
默认 FFF0(意为 0xFFF0);参数必须要在 0~F 范围内,且长度为 4 位。
:param uuid: UUID
"""
self.uart.write(b'AT+LUUID=' + uuid.encode('utf-8'))
return self.uart.read()[:2] == b'OK'
def ble_get_search_uuid(self):
"""
获取搜索 UUID
:return: UUID
"""
self.uart.write(b'AT+LUUID=?')
return self.uart.read().decode('utf-8').split('=')[1]
def ble_set_service_uuid(self, uuid: str):
"""
设置服务 UUID
此服务 UUID 是主机找到服务的依据,找到服务才能找到具体的特征值。
默认 FFE0(意为 0xFFE0);参数必须要在 0~F 范围内,且长度为 4 位。
:param uuid: UUID
"""
self.uart.write(b'AT+UUID=' + uuid.encode('utf-8'))
return self.uart.read()[:2] == b'OK'
def ble_get_service_uuid(self):
"""
获取服务 UUID
:return: UUID
"""
self.uart.write(b'AT+UUID=?')
return self.uart.read().decode('utf-8').split('=')[1]
def ble_set_transmit_uuid(self, uuid: str):
"""
设置透传 UUID
此透传 UUID 必须正确才能正常透传,收发数据。
默认 FFE1(意为 0xFFE1);参数必须要在 0~F 范围内
:param uuid: UUID
"""
self.uart.write(b'AT+TUUID=' + uuid.encode('utf-8'))
return self.uart.read()[:2] == b'OK'
def ble_get_transmit_uuid(self):
"""
获取透传 UUID
:return: UUID
"""
self.uart.write(b'AT+TUUID=?')
return self.uart.read().decode('utf-8').split('=')[1]
"""
综合指令
"""
def info(self):
"""
获取设备信息
:return: 信息
"""
self.uart.write(b'AT+RX')
return {x.split('=')[0].split('+')[1]: x.split('=')[1] for x in self.uart.read().decode('utf-8').split('\n')}
"""
基础指令
"""
def send_byte(self, data: bytes):
"""
发送数据
:param data: 数据
"""
self.uart.write(data)
def read_byte(self):
"""
读取数据
:return: 数据
"""
return self.uart.read()
def send_str(self, data: str):
"""
发送字符串
:param data: 字符串
"""
self.uart.write(data.encode('utf-8'))
def read_str(self):
"""
读取字符串
:return: 字符串
"""
return self.uart.read().decode('utf-8')
def send(self, data):
if type(data) == str:
self.send_str(data)
elif type(data) == bytes:
self.send_byte(data)
def read(self):
return self.read_str()
class HC25:
def __init__(self, uart: UART):
self.uart = uart
def send(self, data):
if type(data) == str:
self.uart.write(data.encode())
elif type(data) == bytes:
self.uart.write(data)
@func_timeout_ms(500)
def read(self, n=-1):
try:
result = self.uart.read(n).decode()
return result or None
except Exception:
return None
def into_control_mode(self):
self.uart.write(b'+++')
return self.read(28)
def exit_control_mode(self):
self.uart.write(b'AT+ENTM')
return self.read()
def reset(self):
self.uart.write(b'AT+RESET')
return self.read()
def mac(self):
self.uart.write(b'AT+MAC')
return self.read()
def wscan(self):
self.uart.write(b'AT+WSCAN')
return self.read()
def wmode(self, mode):
self.uart.write(b'AT+WMODE=' + mode.encode())
return self.read() | /rp2040-tools-0.0.8.tar.gz/rp2040-tools-0.0.8/rp2040/drives/HC/__init__.py | 0.460046 | 0.24983 | __init__.py | pypi |
def calculate_crc(data):
"""
计算数据校验码
:param data: 2进制数据
:return: 16位数据校验码
"""
crc = 0xFFFF
for i in data:
crc ^= i
for _ in range(8):
crc = (crc >> 1) ^ 0xA001 if crc & 0x01 else crc >> 1
return crc.to_bytes(2, 'big')
class UartProtocol1:
"""
串口协议1
2字节帧头 1字节数据长度 1~250字节数据 2字节校验码
"""
def __init__(self, uart):
"""
初始化
:param uart: 串口对象
"""
self.uart = uart
def any(self):
"""
判断是否有数据
:return: True/False
"""
return self.uart.any()
def send(self, data):
"""
发送数据
:param data: 数据
:return: None
"""
header = b'\x55\xAA'
data = data.encode('utf-8')
length = len(data).to_bytes(1, 'big')
crc = sum(data).to_bytes(2, 'big')
self.uart.write(header + length + data + crc)
def receive(self, block=True):
"""
接收数据
:return: 数据
"""
header = self.uart.read(1)
if block:
while header not in [b'\x55', b'\xAA']:
header = self.uart.read(1)
elif header not in [b'\x55', b'\xAA']:
return
if header == b'\x55' and self.uart.read(1) != b'\xAA':
return
length = self.uart.read(1)
if length is None:
return None
length = int.from_bytes(length, 'big')
data = self.uart.read(length)
if data is None:
return None
crc = self.uart.read(2)
if crc is None:
return None
return None if crc != sum(data).to_bytes(2, 'big') else data.decode('utf-8')
class UartProtocolForSmallData:
def __init__(self, uart, number_of_bytes=1):
"""
初始化
:param uart: 串口对象
"""
self.uart = uart
self.number_of_bytes = number_of_bytes
self.length = number_of_bytes // 8 + bool(number_of_bytes % 8)
self.byte_length = 8 * self.length
def any(self):
"""
判断是否有数据
:return: True/False
"""
return self.uart.any()
def send(self, list_of_data):
"""
发送数据
:param list_of_data: 数据
:return: None
"""
data = 0x0
for dat in list_of_data:
data <<= 1
data |= dat
self.uart.write(b'\x55\xAA' + data.to_bytes(self.length, 'big'))
def receive(self, block=True):
"""
接收数据
:return: 数据
"""
header = self.uart.read(1)
if block:
while header not in [b'\x55', b'\xAA']:
header = self.uart.read(1)
elif header not in [b'\x55', b'\xAA']:
return
if header == b'\x55' and self.uart.read(1) != b'\xAA':
return
data = self.uart.read(self.length)
if data is None:
return None
data = int.from_bytes(data, 'big')
return [data >> (self.number_of_bytes - 1 - i) & 0x01 for i in range(self.number_of_bytes)] | /rp2040-tools-0.0.8.tar.gz/rp2040-tools-0.0.8/rp2040/message/protocol.py | 0.448426 | 0.682428 | protocol.py | pypi |
import os
import yaml
from rdkit.Chem import MolFromSmiles, MolFromInchi, AddHs
def default_config():
"""
Return the default configuration as a dictionnary.
"""
path = os.path.join(os.path.dirname(__file__), "conf", "default.yaml")
with open(path, 'r') as fh:
cfg = yaml.load(fh, Loader=yaml.Loader)
return cfg
def make_document_id(rule_id, substrate_id):
"""
Generate a document ID
"""
return rule_id + "_" + substrate_id
def as_document(rule_id, substrate_id, list_list_inchikeys=[], list_list_inchis=[], list_list_smiles=[],
list_stoechiometry=[]):
"""
Format data to be inserted into the cache DB.
Targeted DB is Mongo.
:param rule_id: unique ID for the rule
:param substrate_id: unique ID for the substrate
:param list_list_inchikeys: list of list of InchiKeys
:param list_list_inchis: list of list of Inchis
:param list_list_smiles: list of list of SMILES
:param list_stoechiometry: list of dict of stoechiometric coefficients
:return document: ready-to-be-inserted document
"""
return {
"_id": make_document_id(rule_id, substrate_id),
"rule_id": rule_id,
"substrate_id": substrate_id,
"list_list_inchikeys": list_list_inchikeys,
"list_list_inchis": list_list_inchis,
"list_list_smiles": list_list_smiles,
"list_stoechiometry": list_stoechiometry
}
def rdmols_from_document(document, build_from="inchi", add_hs=True):
"""
Convert back a document to a set of rdmols. This method is a companion of "as_document".
:param document: a document produced by the "as_mongo_document" method, dict
:param build_from: the type of depiction to be used to build back the rdmols, str in ["inchi", "smiles"]
:param add_hs: add Hs to RDKit mol object, default is True
:returns list_list_rdmols: list of list of rdmols
"""
assert build_from in ["inchi", "smiles"]
assert add_hs in [True, False]
list_list_rdmols = list()
list_stoechiometry = document['list_stoechiometry']
if build_from == 'inchi':
for list_inchis in document['list_list_inchis']:
list_rdmols = list()
for inchi in list_inchis:
rd_mol = MolFromInchi(inchi, sanitize=True)
if add_hs:
rd_mol = AddHs(rd_mol)
list_rdmols.append(rd_mol)
list_list_rdmols.append(list_rdmols)
elif build_from == 'smiles':
for list_smiles in document['list_list_smiles']:
list_rdmols = list()
for smiles in list_smiles:
rd_mol = MolFromSmiles(smiles, sanitize=True)
if add_hs:
rd_mol = AddHs(rd_mol)
list_rdmols.append(rd_mol)
list_list_rdmols.append(list_rdmols)
else:
raise NotImplementedError()
return list_list_rdmols, list_stoechiometry | /rp3_cache-1.2-py3-none-any.whl/rp3_cache/Utils.py | 0.533641 | 0.302971 | Utils.py | pypi |
import logging
import re
import smbus
__author__ = "Fernando Chorney <fchorney@djsbx.com>"
__version__ = "1.0.1"
log = logging.getLogger(__name__)
class I2C(object):
def __init__(self, address, bus=None):
log.debug("Initializing I2C bus for address: 0x%02X" % address)
self.address = address
self.bus = None
# Connect to the I2C bus
self.__connect_to_bus(bus)
# Test the connection to make sure we're connected to the right address
try:
test = self.read_raw_byte()
except IOError as e:
log.error(
"I2C Test Connection Failed for Address: 0x%02X" % self.address
)
raise
log.debug("Successfully Connected to 0x%02X" % address)
def clean_up(self):
"""
Close the I2C bus
"""
log.debug("Closing I2C bus for address: 0x%02X" % self.address)
self.bus.close()
# Write Functions
def write_quick(self):
"""
Send only the read / write bit
"""
self.bus.write_quick(self.address)
log.debug("write_quick: Sent the read / write bit")
def write_byte(self, cmd, value):
"""
Writes an 8-bit byte to the specified command register
"""
self.bus.write_byte_data(self.address, cmd, value)
log.debug(
"write_byte: Wrote 0x%02X to command register 0x%02X" % (
value, cmd
)
)
def write_word(self, cmd, value):
"""
Writes a 16-bit word to the specified command register
"""
self.bus.write_word_data(self.address, cmd, value)
log.debug(
"write_word: Wrote 0x%04X to command register 0x%02X" % (
value, cmd
)
)
def write_raw_byte(self, value):
"""
Writes an 8-bit byte directly to the bus
"""
self.bus.write_byte(self.address, value)
log.debug("write_raw_byte: Wrote 0x%02X" % value)
def write_block_data(self, cmd, block):
"""
Writes a block of bytes to the bus using I2C format to the specified
command register
"""
self.bus.write_i2c_block_data(self.address, cmd, block)
log.debug(
"write_block_data: Wrote [%s] to command register 0x%02X" % (
', '.join(['0x%02x' % x for x in block]),
cmd
)
)
# Read Functions
def read_raw_byte(self):
"""
Read an 8-bit byte directly from the bus
"""
result = self.bus.read_byte(self.address)
log.debug("read_raw_byte: Read 0x%02X from the bus" % result)
return result
def read_block_data(self, cmd, length):
"""
Read a block of bytes from the bus from the specified command register
Amount of bytes read in is defined by length
"""
results = self.bus.read_i2c_block_data(self.address, cmd, length)
log.debug(
"read_block_data: Read [%s] from command register 0x%02X" % (
', '.join(['0x%02X' % x for x in results]),
cmd
)
)
return results
def read_unsigned_byte(self, cmd):
"""
Read an unsigned byte from the specified command register
"""
result = self.bus.read_byte_data(self.address, cmd)
log.debug(
"read_unsigned_byte: Read 0x%02x from command register 0x%02x" % (
result, cmd
)
)
return result
def read_signed_byte(self, cmd):
"""
Read a signed byte from the specified command register
"""
result = self.bus.read_byte_data(self.address, cmd)
# Convert to signed data
if result > 127:
result -= 256
log.debug(
"read_signed_byte: Read 0x%02x from command register 0x%02X" % (
result, cmd
)
)
return result
def read_unsigned_word(self, cmd, little_endian=True):
"""
Read an unsigned word from the specified command register
We assume the data is in little endian mode, if it is in big endian
mode then set little_endian to False
"""
result = self.bus.read_word_data(self.address, cmd)
if not little_endian:
result = ((result << 8) & 0xFF00) + (result >> 8)
log.debug(
"read_unsigned_word: Read 0x%04X from command register 0x%02X" % (
result, cmd
)
)
return result
def read_signed_word(self, cmd, little_endian=True):
"""
Read a signed word from the specified command register
We assume the data is in little endian mode, if it is in big endian
mode then set little_endian to False
"""
result = self.bus.read_word_data(self.address, cmd)
if not little_endian:
result = ((result << 8) & 0xFF00) + (result >> 8)
# Convert to signed data
if result > 32767:
result -= 65536
log.debug(
"read_signed_word: Read 0x%04X from command register 0x%02X" % (
result, cmd
)
)
return result
def __connect_to_bus(self, bus):
"""
Attempt to connect to an I2C bus
"""
def connect(bus_num):
try:
log.debug("Attempting to connect to bus %s..." % bus_num)
self.bus = smbus.SMBus(bus_num)
log.debug("Success")
except IOError as e:
log.debug("Failed")
raise
# If the bus is not explicitly stated, try 0 and then try 1 if that
# fails
if bus is None:
try:
connect(0)
return
except IOError as e:
pass
try:
connect(1)
return
except IOError as e:
raise
else:
try:
connect(bus)
return
except IOError as e:
raise | /rpI2C-1.0.1.tar.gz/rpI2C-1.0.1/rpI2C.py | 0.465387 | 0.243777 | rpI2C.py | pypi |
from typing import Literal
import requests
class Vault:
"""
The library wraps Automation Anywhere 360 API, giving robots the ability to manage the values stored in the Credential Vault.
Args:
control_room_uri (str): URL of Automation Anywhere A360 Control Room
username (str): user name with access to the Vault (API)
password (str): user password
"""
def __init__(self, control_room_uri: str, username: str, password: str):
self.endpoints: dict = {
'control_room': control_room_uri.rstrip('//'),
'authentication': f'{control_room_uri.rstrip("//")}/v1/authentication',
'credentials': f'{control_room_uri.rstrip("//")}/v2/credentialvault/credentials'
}
self.username: str = username
self.password: str = password
self.token = None
def get_token(self) -> str:
"""
Returns token generated
Returns:
str: token value
"""
if self.token is None:
self.__authenticate__()
return self.token
def get_credential(self, name: str) -> dict:
"""
Fetch credential from the credential vault.
Args:
name (str): credential name
Raises:
Exception: requests exceptions
Returns:
dict: dictionary of all credential's attributes
"""
try:
response = self.__get_credentials_list__()
attributes: dict = {}
for item in response['list']:
if item['name'] == name:
for attribute in item['attributes']:
attributes[attribute['name']] = self.__get_attribute_value__(item['id'], attribute['id'])
return attributes
raise Exception(f'Cannot fetch credential {name} from the Credential Vault. Check if the name is correct.')
except Exception as ex:
raise Exception(f'Cannot fetch credential {name}.\n\r') from ex
def __get_credential__(self, name: str) -> dict:
for item in self.__get_credentials_list__()['list']:
if item['name'].lower() == name.lower():
return item
return {}
def __list_credentials__(self, output_format: Literal['json', 'string'] = 'json') -> list:
try:
response = self.__get_credentials_list__()
credentials: list = []
for item in response['list']:
if output_format == 'json':
credential: dict = {'name': item['name'].replace(' ', '-').lower(), 'value': {}, 'content_type': 'json'}
for attribute in item['attributes']:
credential['value'][attribute['name']] = self.__get_attribute_value__(item['id'], attribute['id'])
else:
credential: dict = {'name': item['name']}
for attribute in item['attributes']:
credential[attribute['name'].lower()] = self.__get_attribute_value__(item['id'], attribute['id'])
credentials.append(credential)
return credentials
except Exception as ex:
raise Exception('Cannot list credentials') from ex
def __authenticate__(self) -> str:
response = requests.post(
url=self.endpoints['authentication'],
json={"username": self.username, "password": self.password, "multipleLogin": True},
headers={"Content-Type": "application/json; charset=utf-8"},
timeout=30
)
if response.status_code != 200:
raise Exception(f'{response.status_code} : {response.text}') from requests.RequestException
self.token = response.json()['token']
return self.token
def __get_headers__(self):
if self.token is None:
self.__authenticate__()
return {'X-Authorization': self.token}
def __get_credentials_list__(self):
response = requests.post(
url=f'{self.endpoints["credentials"]}/list',
headers=self.__get_headers__(),
json={"fields": []},
timeout=360
)
if response.status_code != 200:
raise Exception(f'{response.status_code} : {response.text}') from requests.RequestException
return response.json()
def __get_attribute_value__(self, credential_id: str, attribute_id: str):
response = requests.get(
url=f'{self.endpoints["credentials"]}/{credential_id}/attributevalues?credentialAttributeId={attribute_id}',
headers=self.__get_headers__(),
timeout=360
)
if response.status_code != 200:
raise Exception(f'{response.status_code} : {response.text}') from requests.RequestException
values = response.json()['list']
for value in values:
if value['credentialAttributeId'] == attribute_id:
return value['value']
raise Exception(f'Cannot get value for credential id: {credential_id}, attribute id: {attribute_id}') from ValueError
def __get_file_extention__(self, file_path: str) -> str:
return file_path.split('.')[-1].lower() | /rpa-automationanywhere-1.0.0.tar.gz/rpa-automationanywhere-1.0.0/rpa_automationanywhere/Vault/Vault.py | 0.845656 | 0.167083 | Vault.py | pypi |
from typing import Literal
import datetime
import calendar
from dateutil.relativedelta import relativedelta
import requests
class Dates:
""" Delivers methods to operate with dates and times objects. """
def __init__(self) -> None:
self._date: datetime.datetime = datetime.date.today()
self.week_days: dict[str, int] = {
'mon': 0,
'tue': 1,
'wed': 2,
'thu': 3,
'fri': 4,
'sat': 5,
'sun': 6
}
def new_date(self, day: int, month: int, year: int, output_format: str = '%d.%m.%Y') -> str:
"""
Return new date in given format (default: %d.%m.%Y)
Args:
day (int): day of month (1 - 31)
month (int): month of year (1 - 12)
year (int): year
output_format (str, optional): pythonic date format. Defaults to '%d.%m.%Y'.
Returns:
str: date string in given format
More about date formats:
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
"""
try:
return datetime.date(year, month, day).strftime(output_format)
except (TypeError, ValueError) as ex:
raise ex
def change_date_format(self,
date_string: str | None = None,
date_format: str = '%d.%m.%Y',
output_format: str = '%d.%m.%Y'
) -> str:
"""
Convert the date from one format to another (default: %d.%m.%Y)
Args:
date_string (str): date string, ex. 12.12.2022
date_format (str, optional): pythonic date format. Defaults to '%d.%m.%Y'.
output_format (str, optional): pythonic date format. Defaults to '%d.%m.%Y'.
Returns:
str: date string in given format
More about date formats:
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
"""
try:
_date: datetime.datetime = self.__to_datetime__(date_string, date_format)
return _date.strftime(output_format)
except (TypeError, ValueError) as ex:
raise ex
def offset(self,
date_string: str | None = None,
date_format:str = '%d.%m.%Y',
seconds: int | None = None,
minutes: int | None = None,
hours: int | None = None,
days: int | None = None,
months: int | None = None,
years: int | None = None,
output_format: str = '%d.%m.%Y'
) -> str:
""" return string date calulcated by moving givned date with given value of the offset
Args:
date_string (str | None, optional): date string
date_format (str, optional): pythonic date format. Defaults to '%d.%m.%Y'.
seconds (int | None, optional): positive or negative value of the offset.
minutes (int | None, optional): positive or negative value of the offset.
hours (int | None, optional): positive or negative value of the offset.
days (int | None, optional): positive or negative value of the offset.
months (int | None, optional): positive or negative value of the offset.
years (int | None, optional): positive or negative value of the offset.
output_format (str, optional): pythonic date format. Defaults to '%d.%m.%Y'.
Returns:
str: date string in given format
More about date formats:
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
"""
try:
_date: datetime.datetime = self.__to_datetime__(date_string, date_format)
if seconds is not None:
_date += datetime.timedelta(seconds=seconds)
if minutes is not None:
_date += datetime.timedelta(minutes=minutes)
if hours is not None:
_date += datetime.timedelta(hours=hours)
if days is not None:
_date += datetime.timedelta(days=days)
if months is not None:
_date += relativedelta(months=months)
if years is not None:
_date += relativedelta(years=years)
return _date.strftime(output_format)
except (NameError, ValueError, TypeError, OverflowError) as ex:
raise ex
def today(self, output_format='%d.%m.%Y') -> str:
"""
Returns today's date in given string format (%d.%m.%Y as default)
Args:
output_format (str, optional): pythonic date format. Defaults to '%d.%m.%Y'.
Returns:
str: date string in given format
More about date formats:
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
"""
try:
return self._date.today().strftime(output_format)
except (TypeError, NameError, ValueError) as ex:
raise ex
def yesterday(self, output_format='%d.%m.%Y') -> str:
"""
Returns yesterday's date in given string format (%d.%m.%Y as default)
Args:
output_format (str, optional): pythonic date format. Defaults to '%d.%m.%Y'.
Returns:
str: date string in given format
"""
try:
return (self._date.today() - datetime.timedelta(days=1)).strftime(output_format)
except (TypeError, NameError, ValueError) as ex:
raise ex
def tomorrow(self, output_format='%d.%m.%Y') -> str:
"""
Returns tomorrow's date in given string format (%d.%m.%Y as default)
Args:
output_format (str, optional): pythonic date format. Defaults to '%d.%m.%Y'.
Returns:
str: date string in given format
"""
try:
return (self._date.today() + datetime.timedelta(days=1)).strftime(output_format)
except (TypeError, NameError, ValueError) as ex:
raise ex
def next_working_day(self,
date_string: str | None = None,
date_format:str = '%d.%m.%Y',
include_holidays: bool = False,
country_code: str | None = None,
output_format: str = '%d.%m.%Y'
) -> str:
"""
Returns date (str) of next working day (ommitting weekends and holidays if included)
Args:
date_string (str | None, optional): date string. Defaults to None.
date_format (str, optional): pythonic date format. Defaults to '%d.%m.%Y'.
include_holidays (bool, optional): determines if holidays should be included.
country_code (str | None, optional): country code ex. 'PL'.
output_format (str, optional): pythonic date format. Defaults to '%d.%m.%Y'.
Full list of country codes available here: https://date.nager.at/Country.
Returns:
str: date string in given format
More about date formats:
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
"""
try:
_date: datetime.datetime = self.__to_datetime__(date_string, date_format)
if _date.weekday() == 4: # Friday
_date += datetime.timedelta(days=3)
elif _date.weekday() == 5: # Saturday
_date += datetime.timedelta(days=2)
else: # Rest of days
_date += datetime.timedelta(days=1)
if include_holidays is True and country_code is not None:
str_date = _date.strftime(date_format)
while self.is_public_holiday(country_code, str_date, date_format) is True:
_date += datetime.timedelta(days=1)
if _date.weekday() == 5:
_date += datetime.timedelta(days=2)
elif _date.weekday() == 6:
_date += datetime.timedelta(days=1)
elif include_holidays is True and country_code is None:
raise ValueError('invalid country_code')
return _date.strftime(output_format)
except Exception as ex:
raise ex
def previous_working_day(self,
date_string: str | None = None,
date_format:str = '%d.%m.%Y',
include_holidays: bool = False,
country_code: str | None = None,
output_format: str = '%d.%m.%Y'
) -> str:
"""
Returns date (str) of previous working day (ommitting weekends and holidays if included)
Args:
date_string (str | None, optional): date string. Defaults to None.
date_format (str, optional): date format. Defaults to '%d.%m.%Y'.
include_holidays (bool, optional): determines if holidays should be included.
country_code (str | None, optional): country code ex. 'PL'.
output_format (str, optional): pythonic date format. Defaults to '%d.%m.%Y'.
Full list of available country codes is here: https://date.nager.at/Country.
Returns:
str: date string in given format
More about date formats:
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
"""
try:
_date: datetime.datetime = self.__to_datetime__(date_string, date_format)
if _date.weekday() == 0: # Monday
_date = _date - datetime.timedelta(days=3)
elif _date.weekday() == 6: # Sunday
_date = _date - datetime.timedelta(days=2)
else: # Rest of days
_date = _date - datetime.timedelta(days=1)
if include_holidays is True and country_code is not None:
str_date = _date.strftime(date_format)
while self.is_public_holiday(country_code, str_date, date_format) is True:
_date -= datetime.timedelta(days=1)
if _date.weekday() == 6:
_date -= datetime.timedelta(days=2)
elif _date.weekday() == 5:
_date -= datetime.timedelta(days=1)
return _date.strftime(output_format)
except Exception as ex:
raise ex
def first_day_of_month(self,
date_string: str | None = None,
date_format: str = '%d.%m.%Y',
output_format="%d.%m.%Y"
) -> str:
"""
Returns the first day of month for given string date in given string format.
Default format: %d.%m.%Y
Args:
date_string (str | None, optional): date string. Defaults to None.
date_format (str, optional): pythonic date format. Defaults to '%d.%m.%Y'.
output_format (str, optional): pythonic date format. Defaults to "%d.%m.%Y".
Returns:
str: date string in given format
More about date formats:
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
"""
try:
_date: datetime.datetime = self.__to_datetime__(date_string, date_format)
return _date.replace(day=1).strftime(output_format)
except (TypeError, NameError, ValueError, OverflowError) as ex:
raise ex
def last_day_of_month(self,
date_string: str | None = None,
date_format: str = '%d.%m.%Y',
output_format="%d.%m.%Y"
) -> str:
"""
Returns the last day of month for given string date in given string format.
Default format: %d.%m.%Y
Args:
date_string (str | None, optional): date string. Defaults to None.
date_format (str, optional): pythonic date format. Defaults to '%d.%m.%Y'.
output_format (str, optional): pythonic date format. Defaults to "%d.%m.%Y".
Returns:
str: date string in given format
More about date formats:
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
"""
try:
_date: datetime.datetime = self.__to_datetime__(date_string, date_format)
result = _date.replace(day=calendar.monthrange(_date.year, _date.month)[1])
return result.strftime(output_format)
except (TypeError, NameError, ValueError) as ex:
raise ex
def calculate_date_of_weekday(self,
date_string: str | None = None,
date_format: str = '%d.%m.%Y',
week_day: Literal['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] = 'mon',
output_format="%d.%m.%Y"
) -> str:
"""
Return the date of the week day from the week for given date in given output format.
Default format: %d.%m.%Y
Args:
date_string (str | None, optional): date string. Defaults to None.
date_format (str, optional): pythonic date format. Defaults to '%d.%m.%Y'.
week_day (Literal['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'], optional): weekday.
output_format (str, optional): pythonic date format. Defaults to "%d.%m.%Y".
Returns:
str: date string in given format
More about date formats:
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
"""
try:
_date: datetime.datetime = self.__to_datetime__(date_string, date_format)
monday: datetime.datetime = _date - datetime.timedelta(days=_date.weekday())
res: datetime.datetime = monday + datetime.timedelta(days=self.week_days[week_day])
return res.strftime(output_format)
except Exception as ex:
raise ex
def day_of_year(self, date_string: str | None = None, date_format: str = '%d.%m.%Y') -> int:
"""
Returns the day of year.
Args:
date_string (str | None, optional): date string. Defaults to None.
date_format (str, optional): pythonic date format. Defaults to '%d.%m.%Y'.
Returns:
int: number value of the day of year
More about date formats:
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
"""
try:
_date: datetime.datetime = datetime.datetime.strptime(date_string, date_format)
return int(_date.strftime('%j'))
except Exception as ex:
raise ex
def week_of_year(self, date_string: str | None = None,
date_format: str = '%d.%m.%Y',
iso_format: bool = True
) -> int:
"""
Returns the number of the week in ISO 8601 or non-ISO standard.
Args:
date_string (str | None, optional): date string. Defaults to None.
date_format (str, optional): pythonic date format. Defaults to '%d.%m.%Y'.
iso_format (bool, optional): pythonic date format. Defaults to True.
Returns:
int: number value of week of the year
More about date formats:
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
"""
try:
date: datetime.datetime = self.__to_datetime__(date_string, date_format)
match iso_format:
case True:
return(int(date.isocalendar().week))
case False:
return int((date - date.replace(month=1, day=1)).days / 7) + 1
except Exception as ex:
raise ex
def difference_between_dates(self,
first_date_string: str,
second_date_string: str,
date_format: str = '%d.%m.%Y',
unit: Literal['seconds', 'minutes', 'hours', 'days'] = 'days'
) -> int:
"""
Return the difference between two dates in given unit
Args:
first_date_string (str): date string of the first date
second_date_string (str): date string of the second date
date_format (str, optional): pythonic date format. Defaults to '%d.%m.%Y'.
unit (['seconds', 'minutes', 'hours', 'days' (default)], optional): measure unit.
Returns:
int: number value of the difference in selected unit (ex. days)
More about date formats:
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
"""
try:
_date1: datetime.datetime = self.__to_datetime__(first_date_string, date_format)
_date2: datetime.datetime = self.__to_datetime__(second_date_string, date_format)
diff: datetime.timedelta = _date1 - _date2
match unit:
case 'seconds':
return abs(diff.seconds)
case 'minutes':
return abs(diff.min)
case 'hours':
return abs(diff.min) / 60
case 'days':
return abs(diff.days)
except Exception as ex:
raise ex
def get_fiscal_year(self,
date_string: str | None = None,
date_format: str = '%d.%m.%Y',
start_month_of_fiscal_year: int = 4
) -> int:
"""
Return the fiscal year for given date
Args:
date_string (str | None, optional): date string. Defaults to None.
date_format (str, optional): pythonic date format. Defaults to '%d.%m.%Y'.
start_month_of_fiscal_year (int, optional): number of the first month of fiscal year.
Returns:
int: number value of the fiscal year
More about date formats:
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
"""
try:
_date: datetime.datetime = self.__to_datetime__(date_string, date_format)
return _date.year if _date.month < start_month_of_fiscal_year else _date.year + 1
except Exception as ex:
raise ex
def get_fiscal_month(self,
date_string: str | None = None,
date_format: str = '%d.%m.%Y',
start_month_of_fiscal_year: int = 4
) -> int:
"""
Return the fiscal month for given date
Args:
date_string (str | None, optional): date string. Defaults to None.
date_format (str, optional): pythonic date format. Defaults to '%d.%m.%Y'.
start_month_of_fiscal_year (int, optional): number of the first month of fiscal year.
Returns:
int: number value of the fiscal month
More about date formats:
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
"""
try:
_date: datetime.datetime = self.__to_datetime__(date_string, date_format)
return (_date - relativedelta(months=start_month_of_fiscal_year-1)).month
except Exception as ex:
raise ex
def get_public_holidays(self,
country_code: str,
year: int,
dates_only: bool = True
) -> dict | list:
"""
Return holidays for given year and given country.
Use https://date.nager.at API
List of countries: https://date.nager.at/Country
Args:
country_code (str): country code, ex. PL
year (int): number value of the year
dates_only (bool, optional): determines if results should contains only dates (list).
Returns:
dict | list: all holidays for the given country and the year
"""
try:
url: str = f'https://date.nager.at/api/v3/PublicHolidays/{year}/{country_code}'
response: requests.Response = requests.get(url, timeout=30)
if response.status_code == 200:
holidays: dict = {item['date']: item['name'] for item in response.json()}
return list(holidays.keys()) if dates_only is True else holidays
except requests.RequestException as ex:
raise ex
def is_public_holiday(self,
country_code: str,
date_string: str | None = None,
date_format: str = '%d.%m.%Y'
) -> bool:
"""
Check if given date is public holiday in given country.\n\r
Use https://date.nager.at API\n\r
List of countries: https://date.nager.at/Country\n\r
Args:
country_code (str): country code, ex. PL
date_string (str | None, optional): date string. Defaults to None.
date_format (str, optional): pythonic date format. Defaults to '%d.%m.%Y'.
Returns:
bool: True if the date is holiday, False if not
More about date formats:
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
"""
if date_string is None:
year: int = datetime.datetime.today().year
elif isinstance(date_string, str):
try:
year = datetime.datetime.strptime(date_string, date_format).year
except ValueError as ex:
raise ex
url: str = f'https://date.nager.at/api/v3/PublicHolidays/{year}/{country_code}'
res: requests.Response = requests.get(url, timeout=30)
if res.status_code != 200:
raise requests.RequestException
holidays: list = [
self.change_date_format(item['date'], '%Y-%m-%d', date_format) for item in res.json()
]
return date_string in holidays
def __to_datetime__(self, date_string: str | None = None, date_format: str = '%d.%m.%Y') -> str:
if date_string is None:
return datetime.datetime.today()
return datetime.datetime.strptime(date_string, date_format) | /rpa_dates-1.0.2-py3-none-any.whl/rpa_dates/Dates.py | 0.906287 | 0.334019 | Dates.py | pypi |
from sys import stdout
from textwrap import indent
from threading import Event, Thread
from typing import Callable, Hashable, Tuple, TextIO
from .task import *
from .utils.terminal import (
bold,
clear_current_row,
color,
print_spinner_and_text,
remove_ansi_escapes)
def get_indicator(status: str, ascii_only: bool = False) -> Tuple[str, str]:
'''Default value for `indicator_fn` parameter of
`rpa_logger.logger.Logger`.
Args:
status: Status of the task to be logged.
ascii_only: If true, use ascii only characters.
Returns:
Tuple of color and character to use as the status indicator.
'''
if status == SUCCESS:
return ('green', '✓' if not ascii_only else 'Y',)
if status == IGNORED:
return ('magenta', '✓' if not ascii_only else 'I',)
elif status == FAILURE:
return ('red', '✗' if not ascii_only else 'X',)
elif status == ERROR:
return ('yellow', '!',)
elif status == SKIPPED:
return ('blue', '–',)
elif status == STARTED:
return ('white', '#',)
else:
return ('grey', '?',)
def multiple_active_text(num_active: int) -> str:
'''Default value for `multiple_fn` parameter of `rpa_logger.logger.Logger`.
Args:
num_active: Number of currently active tasks.
Returns:
String to print when multiple tasks are in progress.
'''
return f'{num_active} tasks in progress'
def is_status_ok(status: str) -> bool:
'''Default value for `status_ok_fn` parameter of
`rpa_logger.logger.Logger`.
Args:
status: Status to determine OK status for.
Returns:
True if given status is OK, False otherwise.
'''
return status not in (FAILURE, ERROR,)
@dataclass
class LoggerOutputOptions:
'''Dataclass that stores the output options of a
`rpa_logger.logger.Logger`. See `rpa_logger.logger.Logger` args for
details on each attribute.
'''
animations: bool = True
colors: bool = True
ascii_only: bool = False
print_output_immediately: bool = False
target: TextIO = None
class Logger:
'''Interface for logging RPA tasks.
Args:
animations: If true, progress indicator is displayed.
colors: If true, ANSI escape codes are used when logging to console.
ascii_only: If true, use ascii only spinner and status indicators.
print_output_immediately: If true, print output as it is logged.
Otherwise, log output when task is finished.
target: File to print output to. Defaults to stdout.
multiple_fn: Function used to determine progress message when multiple
tasks are in progress. Defaults to
`rpa_logger.logger.multiple_active_text`.
indicator_fn: Function used to determine the color and character for
the status indicator. Defaults to
`rpa_logger.logger.get_indicator`.
status_ok_fn: Function used to determine if given task status is ok.
Defaults to `rpa_logger.logger.get_indicator`.
'''
def __init__(
self,
animations: bool = True,
colors: bool = True,
ascii_only: bool = False,
print_output_immediately: bool = False,
target: TextIO = None,
multiple_fn: Callable[[int], str] = None,
indicator_fn: Callable[[str, bool], Tuple[str, str]] = None,
status_ok_fn: Callable[[str], bool] = None):
self.options = LoggerOutputOptions(
animations=animations,
colors=colors,
ascii_only=ascii_only,
print_output_immediately=print_output_immediately,
target=target or stdout
)
self._get_multiple_active_str = multiple_fn or multiple_active_text
self._get_progress_indicator = indicator_fn or get_indicator
self._is_status_ok = status_ok_fn or is_status_ok
self._spinner_thread = None
self._spinner_stop_event = Event()
self.suite = TaskSuite(None)
'''`rpa_logger.task.TaskSuite` where logger stores task data.'''
def bold(self, text: str) -> str:
'''Shortcut for `rpa_logger.utils.terminal.bold`.
'''
return bold(text)
def color(self, text: str, color_name: str) -> str:
'''Shortcut for `rpa_logger.utils.terminal.color`.
'''
return color(text, color_name)
def _print(self, *args, **kwargs):
if not self.options.colors:
objs = (remove_ansi_escapes(str(arg)) for arg in args)
return print(*objs, file=self.options.target, **kwargs)
return print(*args, file=self.options.target, **kwargs)
def error(self, text: str) -> None:
'''Print error message.
Args:
text: Error message text.
'''
error_text = self.bold(self.color('ERROR:', 'red'))
self._print(f'{error_text} {text}')
def title(self, title: str = None, description: str = None) -> None:
'''Print title and description of the RPA process.
Args:
title: Title to print in bold.
description: Description to print under the title.
'''
self.suite.name = title
self.suite.description = description
title_text = f'{self.bold(title)}\n' if title else ''
self._print(f'{title_text}{description or ""}\n')
def _print_active(self):
if not self.options.animations:
return
num_active = len(self.suite.active_tasks)
if not num_active:
return
elif num_active > 1:
text = self._get_multiple_active_str(num_active)
else:
text = self.suite.active_tasks[0].name
clear_current_row(self.options.target)
self.stop_progress_animation()
self._spinner_thread = Thread(
target=print_spinner_and_text,
args=[
text,
self._spinner_stop_event,
self.options.target,
self.options.ascii_only])
self._spinner_stop_event.clear()
self._spinner_thread.start()
def _get_indicator_text(self, status):
color, symbol = self._get_progress_indicator(
status, self.options.ascii_only)
return self.bold(self.color(symbol, color))
def _print_task(self, key):
task = self.suite.get_task(key)
indicator_text = self._get_indicator_text(task.status)
indented_text = indent(task.name, ' ').strip()
self._print(f'{indicator_text} {indented_text}\n')
def start_task(self, text: str, key: Hashable = None) -> Hashable:
'''Create a new active task and print progress indicator.
Args:
text: Name or description of the task.
key: Key to identify the task with. If not provided, new uuid4
will be used.
Return:
Key to control to the created task with.
'''
key = self.suite.create_task(text, key)
if self.options.print_output_immediately:
self._print_task(key)
self._print_active()
return key
def stop_progress_animation(self) -> None:
'''Stop possible active progress indicators.
Should be used, for example, if the application is interrupted while
there are active progress indicators.
'''
self._spinner_stop_event.set()
if self._spinner_thread:
self._spinner_thread.join()
self._spinner_thread = None
def finish_task(
self,
status: str,
text: str = None,
key: Hashable = None) -> None:
'''Finish active or new task and print its status.
Calling this method is required to stop the progress spinner of a
previously started task.
Args:
status: Status string used to determine the status indicator.
text: Text to describe the task with. Defaults to the text used
when the task was created if `key` is given.
key: Key of the previously created task to be finished.
'''
self.stop_progress_animation()
if not key:
if not text:
raise RuntimeError(
f'No text provided or found for given key ({key}).')
return self.log_task(status, text)
self.suite.finish_task(key, status)
task = self.suite.get_task(key)
if text:
task.name = text
if self.options.print_output_immediately and task.output:
clear_current_row(self.options.target)
self._print('')
self._print_task(key)
if not self.options.print_output_immediately:
output_text = indent(
'\n'.join(i.text for i in task.output), ' ').rstrip()
if output_text:
self._print(f'{output_text}\n')
self._print_active()
def log_task(self, status: str, text: str) -> None:
'''Create and finish a new task.
This method can be used when the task to be logged was not previously
started.
Args:
status: Status to use for the finished task.
text: Name of the task.
'''
key = self.suite.log_task(status, text)
self._print_task(key)
self._print_active()
return key
def log_metadata(
self,
key: str,
value: Any,
task_key: Hashable = None) -> None:
'''Log metadata into the loggers task suite or any of its tasks.
Args:
key: Key for the metadata item.
value: Value for the metadata item. If task data is saved as json
or yaml, this value must be serializable.
task_key: Key of a task to log metadata into. If None, metadata
is logged to the suite.
'''
return self.suite.log_metadata(key, value, task_key)
def log_output(self, key: Hashable, text: str,
stream: str = 'stdout') -> None:
'''Append new `rpa_logger.utils.output.OutputText` to task output.
Args:
key: Key of the task to log output to.
text: Output text content.
stream: Output stream. Defaults to `stdout`.
'''
if self.options.print_output_immediately:
self.stop_progress_animation()
self._print(indent(text, ' '))
self._print_active()
self.suite.log_output(key, text, stream)
def _num_failed_tasks(self) -> int:
summary = self.suite.task_status_counter
return sum(summary.get(status, 0)
for status in summary if not self._is_status_ok(status))
def finish_suite(self, success_status: str = SUCCESS,
failure_status: str = ERROR) -> None:
'''Finish loggers task suite.
Args:
success_status: Status to use as suite status if all tasks have
ok status.
failure_status: Status to use as suite status if some of the tasks
have non-ok status.
'''
if self._num_failed_tasks() > 0:
return self.suite.finish(failure_status)
return self.suite.finish(success_status)
def summary(self) -> int:
'''Print summary of the logged tasks.
Returns:
Number of failed (status is either `FAILURE` or `ERROR`) tasks.
'''
summary = self.suite.task_status_counter
text = self.bold('Summary:')
for status in summary:
indicator = self._get_indicator_text(status)
text += f'\n{indicator} {status.title()}: {summary.get(status)}'
self._print(text)
return self._num_failed_tasks() | /rpa_logger-0.4.1.tar.gz/rpa_logger-0.4.1/rpa_logger/logger.py | 0.761361 | 0.233542 | logger.py | pypi |
from collections import Counter
from dataclasses import dataclass
from typing import Any, Dict, Hashable, List, Union
from uuid import uuid4
from .utils import timestamp
from .utils.output import OutputText
STARTED = 'STARTED'
SUCCESS = 'SUCCESS'
IGNORED = 'IGNORED'
FAILURE = 'FAILURE'
ERROR = 'ERROR'
SKIPPED = 'SKIPPED'
STATUSES = (STARTED, SUCCESS, IGNORED, FAILURE, ERROR, SKIPPED,)
@dataclass
class BaseTask:
'''Base class to define common functionality of `rpa_logger.task.Task` and
`rpa_logger.task.TaskSuite`
'''
type: str
'''Used to identify task type, when task is presented as dict'''
name: Union[str, None]
'''Human-readable name of the task.'''
status: str
'''Describes state of the task. For example `SUCCESS` or `ERROR`.'''
started: str
'''UTC ISO-8601 timestamp that stores the start time of the task.
Defined automatically when instance is created.
'''
finished: Union[str, None]
'''UTC ISO-8601 timestamp that stores the finish time of the task.
Defined automatically when `rpa_logger.task.BaseTask.finish` method is
called.
'''
metadata: Dict[str, Any]
'''Container for any other data stored in the task. Could, for example,
contain information about the execution environment or data that was
processed in the task.
'''
def __init__(self, name: Union[str, None], status: str = STARTED) -> None:
'''
Args:
name: Name of the task.
status: Status to use for the started task.
'''
self.status = status
self.name = name
self.started = timestamp()
self.finished = None
self.metadata = dict()
def finish(self, status) -> None:
'''Set finished timestamp and end status of the task
Args:
status: Status to use for the finished task.
'''
self.status = status
self.finished = timestamp()
def log_metadata(self, key: str, value: Any) -> None:
'''Log metadata for the task.
Args:
key: Key for the metadata item.
value: Value for the metadata item. If task data is saved as json
or yaml, this value must be serializable.
'''
self.metadata[key] = value
@dataclass
class Task(BaseTask):
'''Defines single task and stores its output and metadata
'''
output: List[OutputText]
def __init__(self, name: str, status: str = STARTED):
'''
Args:
name: Name of the task.
status: Status to use for the started task.
'''
super().__init__(name, status)
self.output = list()
@property
def type(self):
return 'TASK'
def log_output(self, text: str, stream: str = 'stdout') -> None:
'''Append new `rpa_logger.utils.output.OutputText` to task output.
Args:
text: Output text content.
stream: Output stream. Defaults to `stdout`.
'''
self.output.append(OutputText(text, stream))
@dataclass
class TaskSuite(BaseTask):
'''Defines task suite and stores its tasks and metadata
'''
description: Union[str, None]
tasks: List[Task]
def __init__(
self,
name: Union[str, None],
description: str = None,
status: str = STARTED):
'''
Args:
name: Name of the task suite.
description: Description of the task suite.
status: Status to use for the started task suite.
'''
super().__init__(name, status)
self.description = description
self._tasks: Dict[Hashable, Task] = dict()
@property
def type(self):
return 'SUITE'
@property
def tasks(self) -> List[Task]: # pylint: disable=function-redefined
'''Return suites tasks as list sorted by the started time.
'''
tasks = list(self._tasks.values())
tasks.sort(key=lambda i: i.started)
return tasks
@property
def active_tasks(self) -> List[Task]:
'''Return suites active tasks as list sorted by the started time.
Task is active until it is finished; Task is active, if its finished
variable is None.
'''
return [i for i in self.tasks if i.finished is None]
@property
def task_status_counter(self) -> Counter:
'''Return `Counter` instance initialized with suites task statuses.
'''
return Counter(i.status for i in self._tasks.values())
def create_task(
self,
name: str,
key: Hashable = None,
status: str = STARTED):
'''Create new task and store it in the suite tasks.
Args:
name: Name of the task.
key: Key to identify the created task with.
status: Status to use for the started task.
Returns:
Key of the created task.
'''
if not key:
key = uuid4()
self._tasks[key] = Task(name, status)
return key
def log_task(self, status: str, name: str) -> None:
'''Create and finish a new task.
Args:
name: Name of the task.
status: Status to use for the finished task.
Returns:
Key of the created task.
'''
key = self.create_task(name)
self.finish_task(key, status)
return key
def finish_task(self, key: Hashable, status: str) -> None:
'''Set finished timestamp and end status of the task
Args:
key: Key of the task to finish
status: Status to use for the finished task.
'''
return self._tasks[key].finish(status)
def get_task(self, key: Hashable) -> Task:
'''Get `rpa_logger.task.Task` with given key.
Args:
key: Key to try to find from suite.
Returns:
Task with matching key.
'''
return self._tasks.get(key)
def log_metadata(
self,
key: str,
value: Any,
task_key: Hashable = None) -> None:
'''Log metadata into the task suite or any of its tasks.
Args:
key: Key for the metadata item.
value: Value for the metadata item. If task data is saved as json
or yaml, this value must be serializable.
task_key: Key of a task to log metadata into. If None, metadata
is logged to the suite.
'''
if task_key:
self._tasks[task_key].log_metadata(key, value)
return
super().log_metadata(key, value)
def log_output(self, key: Hashable, text: str,
stream: str = 'stdout') -> None:
'''Append new `rpa_logger.utils.output.OutputText` to task output.
Args:
key: Key of the task to log output to.
text: Output text content.
stream: Output stream. Defaults to `stdout`.
'''
self._tasks[key].log_output(text, stream) | /rpa_logger-0.4.1.tar.gz/rpa_logger-0.4.1/rpa_logger/task.py | 0.919448 | 0.247612 | task.py | pypi |
import re
from shutil import get_terminal_size
from sys import stdout
from threading import Event
from typing import TextIO
# From cli-spinners (https://www.npmjs.com/package/cli-spinners)
INTERVAL = 0.080 # seconds
ASCII_FRAMES = ['|', '/', '-', '\\']
FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']
COLORS = dict(red=31, green=32, yellow=33, blue=34, magenta=35, grey=90)
'''Dictionary of supported color values for `rpa_logger.utils.terminal.color`.
'''
def bold(text: str) -> str:
'''Bold given text with ANSI escape codes.
Args:
text: Text to be formatted.
Returns:
String with formatted text.
'''
return f'\033[1m{text}\033[22m'
def color(text: str, color_name: str) -> str:
'''Color given text with ANSI escape codes.
Args:
text: Text to be formatted.
color_name: Color to format text with. See
`rpa_logger.utils.terminal.COLORS` for available values.
Returns:
String with formatted text.
'''
if color_name not in COLORS:
return text
return f'\033[{COLORS[color_name]}m{text}\033[39m'
def remove_ansi_escapes(text: str) -> str:
'''Remove ANSI escape codes from given string.
Args:
text: String with ANSI escape codes.
Returns:
`text` without any ANSI escape codes.
'''
return re.sub(r'\033\[[^m]+m', '', text)
def fit_to_width(text: str) -> str:
'''Fit formatted text into current terminal width
If text does not fit to current terminal width, the end of the string is
replaced with '…' character. If text contains ANSI escape codes,
formatting is cleared when text is truncated.
Args:
text: Text to fit to terminal width.
Returns:
The possibly truncated string
'''
max_len = get_terminal_size().columns
non_formatted_text = remove_ansi_escapes(text.replace('\r', ''))
if len(non_formatted_text) <= max_len:
return text
i = 0
j = 0
while i < max_len - 2:
match = re.match(r'\r|\033\[[0-9]+m', text[(i + j):])
if match:
j += len(match.group(0))
else:
i += 1
clear_formatting = '\033[0m' if re.search(r'\033\[[0-9]+m', text) else ''
return f'{text[:(i + j)]}{clear_formatting}…'
def clear_current_row(file: TextIO = stdout):
'''Clear current terminal row
Can be used, for example, when progress text is replaced with shorter one.
Args:
file: File to print output to. Defaults to stdout.
'''
width = get_terminal_size().columns
print(f'\r{" " * width}', file=file, end='')
def print_spinner_and_text(
text: str,
stop_event: Event,
file: TextIO = stdout,
ascii_only: bool = False) -> None:
'''Print spinner and text until stop event
Args:
text: Text to print after spinner.
stop_event: Event to stop spinner loop.
file: File to print output to. Defaults to stdout.
ascii_only: If true, use ascii only spinner.
'''
frames = FRAMES if not ascii_only else ASCII_FRAMES
i = 0
while not stop_event.wait(INTERVAL):
print(
fit_to_width(f'\r{frames[i % len(frames)]} {text}'),
file=file,
end='')
i += 1
print('\r', end='') | /rpa_logger-0.4.1.tar.gz/rpa_logger-0.4.1/rpa_logger/utils/terminal.py | 0.663342 | 0.304029 | terminal.py | pypi |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.