prompt
large_stringlengths
72
9.34k
completion
large_stringlengths
0
7.61k
<|file_name|>Class_LabExperimBased.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Class_LabExperimBased provides functionalities for data handling of data obtained in lab experiments in the field of (waste)water treatment. Copyright (C) 2016 Chaim De Mulder This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses/. """ import sys #import os #from os import listdir #import pandas as pd #import scipy as sp #import numpy as np #import datetime as dt import matplotlib.pyplot as plt #plotten in python import warnings as wn from wwdata.Class_HydroData import HydroData class LabExperimBased(HydroData): """ Superclass for a HydroData object, expanding the functionalities with specific functions for data gathered is lab experiments. Attributes ---------- timedata_column : str name of the column containing the time data data_type : str type of the data provided experiment_tag : str A tag identifying the experiment; can be a date or a code used by the producer/owner of the data. time_unit : str The time unit in which the time data is given units : array The units of the variables in the columns """ def __init__(self,data,timedata_column='index',data_type='NAT', experiment_tag='No tag given',time_unit=None): """ initialisation of a LabExperimBased object, based on a previously defined HydroData object. """ HydroData.__init__(self,data,timedata_column=timedata_column,data_type=data_type, experiment_tag=experiment_tag,time_unit=time_unit) def hours(self,time_column='index'): """ calculates the hours from the relative values Parameters ---------- time_column : string column containing the relative time values; default to index """ if time_column == 'index': self.data['index']=self.time.values self.data['h']= (self.data['indexes'])*24 + self.data['indexes'].shift(1) self.data['h'].fillna(0,inplace=True) self.data.drop('index', axis=1, inplace=True) else: <|fim_middle|> def add_conc(self,column_name,x,y,new_name='default'): """ calculates the concentration values of the given column and adds them as a new column to the DataFrame. Parameters ---------- column_name : str column with values x : int ... y : int ... new_name : str name of the new column, default to 'column_name + mg/L' """ if new_name == 'default': new_name = column_name + ' ' + 'mg/L' self.data[new_name] = self.data[column_name].values*x*y ## Instead of this function: define a dataframe/dict with conversion or ## concentration factors, so that you can have a function that automatically ## converts all parameters in the frame to concentrations def check_ph(self,ph_column='pH',thresh=0.4): """ gives the maximal change in pH Parameters ---------- ph_column : str column with pH-values, default to 'pH' threshold : int threshold value for warning, default to '0.4' """ dph = self.data[ph_column].max()-self.data[ph_column].min() if dph > thresh: wn.warn('Strong change in pH during experiment!') else: self.delta_ph = dph def in_out(self,columns): """ (start_values-end_values) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] in_out = inv-outv return in_out def removal(self,columns): """ total removal of nitrogen (1-(end_values/start_values)) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] removal = 1-(outv/inv) return removal def calc_slope(self,columns,time_column='h'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to calculate the slope for time_column : str time used for calculation; default to 'h' """ for column in columns: self.data[column + " " +'slope'] = (self.data[column].shift(1)-self.data[column])\ /(self.data[time_column]-self.data[time_column].shift(1)) def plot(self,columns,time_column='index'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to plot time_column : str time used for calculation; default to 'h' """ fig = plt.figure(figsize=(10,6)) ax = fig.add_subplot(111) if time_column=='index': for column in columns: ax.plot(self.time,self.data[column],marker='o') else: for column in columns: ax.plot(self.data[time_column],self.data[column],marker='o') ax.legend() return fig,ax ####################################### def _print_removed_output(original,new,type_): """ function printing the output of functions that remove datapoints. Parameters ---------- original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ print('Original dataset:',original,'datapoints') print('New dataset:',new,'datapoints') print(original-new,'datapoints ',type_) def _log_removed_output(log_file,original,new,type_): """ function writing the output of functions that remove datapoints to a log file. Parameters ---------- log_file : str string containing the directory to the log file to be written out original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ log_file = open(log_file,'a') log_file.write(str('\nOriginal dataset: '+str(original)+' datapoints; new dataset: '+ str(new)+' datapoints'+str(original-new)+' datapoints ',type_)) log_file.close() <|fim▁end|>
self.data['h']= (self.data[time_column])*24 + self.data[time_column].shift(1) self.data['h'].fillna(0,inplace=True)
<|file_name|>Class_LabExperimBased.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Class_LabExperimBased provides functionalities for data handling of data obtained in lab experiments in the field of (waste)water treatment. Copyright (C) 2016 Chaim De Mulder This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses/. """ import sys #import os #from os import listdir #import pandas as pd #import scipy as sp #import numpy as np #import datetime as dt import matplotlib.pyplot as plt #plotten in python import warnings as wn from wwdata.Class_HydroData import HydroData class LabExperimBased(HydroData): """ Superclass for a HydroData object, expanding the functionalities with specific functions for data gathered is lab experiments. Attributes ---------- timedata_column : str name of the column containing the time data data_type : str type of the data provided experiment_tag : str A tag identifying the experiment; can be a date or a code used by the producer/owner of the data. time_unit : str The time unit in which the time data is given units : array The units of the variables in the columns """ def __init__(self,data,timedata_column='index',data_type='NAT', experiment_tag='No tag given',time_unit=None): """ initialisation of a LabExperimBased object, based on a previously defined HydroData object. """ HydroData.__init__(self,data,timedata_column=timedata_column,data_type=data_type, experiment_tag=experiment_tag,time_unit=time_unit) def hours(self,time_column='index'): """ calculates the hours from the relative values Parameters ---------- time_column : string column containing the relative time values; default to index """ if time_column == 'index': self.data['index']=self.time.values self.data['h']= (self.data['indexes'])*24 + self.data['indexes'].shift(1) self.data['h'].fillna(0,inplace=True) self.data.drop('index', axis=1, inplace=True) else: self.data['h']= (self.data[time_column])*24 + self.data[time_column].shift(1) self.data['h'].fillna(0,inplace=True) def add_conc(self,column_name,x,y,new_name='default'): """ calculates the concentration values of the given column and adds them as a new column to the DataFrame. Parameters ---------- column_name : str column with values x : int ... y : int ... new_name : str name of the new column, default to 'column_name + mg/L' """ if new_name == 'default': <|fim_middle|> self.data[new_name] = self.data[column_name].values*x*y ## Instead of this function: define a dataframe/dict with conversion or ## concentration factors, so that you can have a function that automatically ## converts all parameters in the frame to concentrations def check_ph(self,ph_column='pH',thresh=0.4): """ gives the maximal change in pH Parameters ---------- ph_column : str column with pH-values, default to 'pH' threshold : int threshold value for warning, default to '0.4' """ dph = self.data[ph_column].max()-self.data[ph_column].min() if dph > thresh: wn.warn('Strong change in pH during experiment!') else: self.delta_ph = dph def in_out(self,columns): """ (start_values-end_values) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] in_out = inv-outv return in_out def removal(self,columns): """ total removal of nitrogen (1-(end_values/start_values)) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] removal = 1-(outv/inv) return removal def calc_slope(self,columns,time_column='h'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to calculate the slope for time_column : str time used for calculation; default to 'h' """ for column in columns: self.data[column + " " +'slope'] = (self.data[column].shift(1)-self.data[column])\ /(self.data[time_column]-self.data[time_column].shift(1)) def plot(self,columns,time_column='index'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to plot time_column : str time used for calculation; default to 'h' """ fig = plt.figure(figsize=(10,6)) ax = fig.add_subplot(111) if time_column=='index': for column in columns: ax.plot(self.time,self.data[column],marker='o') else: for column in columns: ax.plot(self.data[time_column],self.data[column],marker='o') ax.legend() return fig,ax ####################################### def _print_removed_output(original,new,type_): """ function printing the output of functions that remove datapoints. Parameters ---------- original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ print('Original dataset:',original,'datapoints') print('New dataset:',new,'datapoints') print(original-new,'datapoints ',type_) def _log_removed_output(log_file,original,new,type_): """ function writing the output of functions that remove datapoints to a log file. Parameters ---------- log_file : str string containing the directory to the log file to be written out original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ log_file = open(log_file,'a') log_file.write(str('\nOriginal dataset: '+str(original)+' datapoints; new dataset: '+ str(new)+' datapoints'+str(original-new)+' datapoints ',type_)) log_file.close() <|fim▁end|>
new_name = column_name + ' ' + 'mg/L'
<|file_name|>Class_LabExperimBased.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Class_LabExperimBased provides functionalities for data handling of data obtained in lab experiments in the field of (waste)water treatment. Copyright (C) 2016 Chaim De Mulder This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses/. """ import sys #import os #from os import listdir #import pandas as pd #import scipy as sp #import numpy as np #import datetime as dt import matplotlib.pyplot as plt #plotten in python import warnings as wn from wwdata.Class_HydroData import HydroData class LabExperimBased(HydroData): """ Superclass for a HydroData object, expanding the functionalities with specific functions for data gathered is lab experiments. Attributes ---------- timedata_column : str name of the column containing the time data data_type : str type of the data provided experiment_tag : str A tag identifying the experiment; can be a date or a code used by the producer/owner of the data. time_unit : str The time unit in which the time data is given units : array The units of the variables in the columns """ def __init__(self,data,timedata_column='index',data_type='NAT', experiment_tag='No tag given',time_unit=None): """ initialisation of a LabExperimBased object, based on a previously defined HydroData object. """ HydroData.__init__(self,data,timedata_column=timedata_column,data_type=data_type, experiment_tag=experiment_tag,time_unit=time_unit) def hours(self,time_column='index'): """ calculates the hours from the relative values Parameters ---------- time_column : string column containing the relative time values; default to index """ if time_column == 'index': self.data['index']=self.time.values self.data['h']= (self.data['indexes'])*24 + self.data['indexes'].shift(1) self.data['h'].fillna(0,inplace=True) self.data.drop('index', axis=1, inplace=True) else: self.data['h']= (self.data[time_column])*24 + self.data[time_column].shift(1) self.data['h'].fillna(0,inplace=True) def add_conc(self,column_name,x,y,new_name='default'): """ calculates the concentration values of the given column and adds them as a new column to the DataFrame. Parameters ---------- column_name : str column with values x : int ... y : int ... new_name : str name of the new column, default to 'column_name + mg/L' """ if new_name == 'default': new_name = column_name + ' ' + 'mg/L' self.data[new_name] = self.data[column_name].values*x*y ## Instead of this function: define a dataframe/dict with conversion or ## concentration factors, so that you can have a function that automatically ## converts all parameters in the frame to concentrations def check_ph(self,ph_column='pH',thresh=0.4): """ gives the maximal change in pH Parameters ---------- ph_column : str column with pH-values, default to 'pH' threshold : int threshold value for warning, default to '0.4' """ dph = self.data[ph_column].max()-self.data[ph_column].min() if dph > thresh: <|fim_middle|> else: self.delta_ph = dph def in_out(self,columns): """ (start_values-end_values) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] in_out = inv-outv return in_out def removal(self,columns): """ total removal of nitrogen (1-(end_values/start_values)) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] removal = 1-(outv/inv) return removal def calc_slope(self,columns,time_column='h'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to calculate the slope for time_column : str time used for calculation; default to 'h' """ for column in columns: self.data[column + " " +'slope'] = (self.data[column].shift(1)-self.data[column])\ /(self.data[time_column]-self.data[time_column].shift(1)) def plot(self,columns,time_column='index'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to plot time_column : str time used for calculation; default to 'h' """ fig = plt.figure(figsize=(10,6)) ax = fig.add_subplot(111) if time_column=='index': for column in columns: ax.plot(self.time,self.data[column],marker='o') else: for column in columns: ax.plot(self.data[time_column],self.data[column],marker='o') ax.legend() return fig,ax ####################################### def _print_removed_output(original,new,type_): """ function printing the output of functions that remove datapoints. Parameters ---------- original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ print('Original dataset:',original,'datapoints') print('New dataset:',new,'datapoints') print(original-new,'datapoints ',type_) def _log_removed_output(log_file,original,new,type_): """ function writing the output of functions that remove datapoints to a log file. Parameters ---------- log_file : str string containing the directory to the log file to be written out original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ log_file = open(log_file,'a') log_file.write(str('\nOriginal dataset: '+str(original)+' datapoints; new dataset: '+ str(new)+' datapoints'+str(original-new)+' datapoints ',type_)) log_file.close() <|fim▁end|>
wn.warn('Strong change in pH during experiment!')
<|file_name|>Class_LabExperimBased.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Class_LabExperimBased provides functionalities for data handling of data obtained in lab experiments in the field of (waste)water treatment. Copyright (C) 2016 Chaim De Mulder This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses/. """ import sys #import os #from os import listdir #import pandas as pd #import scipy as sp #import numpy as np #import datetime as dt import matplotlib.pyplot as plt #plotten in python import warnings as wn from wwdata.Class_HydroData import HydroData class LabExperimBased(HydroData): """ Superclass for a HydroData object, expanding the functionalities with specific functions for data gathered is lab experiments. Attributes ---------- timedata_column : str name of the column containing the time data data_type : str type of the data provided experiment_tag : str A tag identifying the experiment; can be a date or a code used by the producer/owner of the data. time_unit : str The time unit in which the time data is given units : array The units of the variables in the columns """ def __init__(self,data,timedata_column='index',data_type='NAT', experiment_tag='No tag given',time_unit=None): """ initialisation of a LabExperimBased object, based on a previously defined HydroData object. """ HydroData.__init__(self,data,timedata_column=timedata_column,data_type=data_type, experiment_tag=experiment_tag,time_unit=time_unit) def hours(self,time_column='index'): """ calculates the hours from the relative values Parameters ---------- time_column : string column containing the relative time values; default to index """ if time_column == 'index': self.data['index']=self.time.values self.data['h']= (self.data['indexes'])*24 + self.data['indexes'].shift(1) self.data['h'].fillna(0,inplace=True) self.data.drop('index', axis=1, inplace=True) else: self.data['h']= (self.data[time_column])*24 + self.data[time_column].shift(1) self.data['h'].fillna(0,inplace=True) def add_conc(self,column_name,x,y,new_name='default'): """ calculates the concentration values of the given column and adds them as a new column to the DataFrame. Parameters ---------- column_name : str column with values x : int ... y : int ... new_name : str name of the new column, default to 'column_name + mg/L' """ if new_name == 'default': new_name = column_name + ' ' + 'mg/L' self.data[new_name] = self.data[column_name].values*x*y ## Instead of this function: define a dataframe/dict with conversion or ## concentration factors, so that you can have a function that automatically ## converts all parameters in the frame to concentrations def check_ph(self,ph_column='pH',thresh=0.4): """ gives the maximal change in pH Parameters ---------- ph_column : str column with pH-values, default to 'pH' threshold : int threshold value for warning, default to '0.4' """ dph = self.data[ph_column].max()-self.data[ph_column].min() if dph > thresh: wn.warn('Strong change in pH during experiment!') else: <|fim_middle|> def in_out(self,columns): """ (start_values-end_values) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] in_out = inv-outv return in_out def removal(self,columns): """ total removal of nitrogen (1-(end_values/start_values)) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] removal = 1-(outv/inv) return removal def calc_slope(self,columns,time_column='h'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to calculate the slope for time_column : str time used for calculation; default to 'h' """ for column in columns: self.data[column + " " +'slope'] = (self.data[column].shift(1)-self.data[column])\ /(self.data[time_column]-self.data[time_column].shift(1)) def plot(self,columns,time_column='index'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to plot time_column : str time used for calculation; default to 'h' """ fig = plt.figure(figsize=(10,6)) ax = fig.add_subplot(111) if time_column=='index': for column in columns: ax.plot(self.time,self.data[column],marker='o') else: for column in columns: ax.plot(self.data[time_column],self.data[column],marker='o') ax.legend() return fig,ax ####################################### def _print_removed_output(original,new,type_): """ function printing the output of functions that remove datapoints. Parameters ---------- original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ print('Original dataset:',original,'datapoints') print('New dataset:',new,'datapoints') print(original-new,'datapoints ',type_) def _log_removed_output(log_file,original,new,type_): """ function writing the output of functions that remove datapoints to a log file. Parameters ---------- log_file : str string containing the directory to the log file to be written out original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ log_file = open(log_file,'a') log_file.write(str('\nOriginal dataset: '+str(original)+' datapoints; new dataset: '+ str(new)+' datapoints'+str(original-new)+' datapoints ',type_)) log_file.close() <|fim▁end|>
self.delta_ph = dph
<|file_name|>Class_LabExperimBased.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Class_LabExperimBased provides functionalities for data handling of data obtained in lab experiments in the field of (waste)water treatment. Copyright (C) 2016 Chaim De Mulder This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses/. """ import sys #import os #from os import listdir #import pandas as pd #import scipy as sp #import numpy as np #import datetime as dt import matplotlib.pyplot as plt #plotten in python import warnings as wn from wwdata.Class_HydroData import HydroData class LabExperimBased(HydroData): """ Superclass for a HydroData object, expanding the functionalities with specific functions for data gathered is lab experiments. Attributes ---------- timedata_column : str name of the column containing the time data data_type : str type of the data provided experiment_tag : str A tag identifying the experiment; can be a date or a code used by the producer/owner of the data. time_unit : str The time unit in which the time data is given units : array The units of the variables in the columns """ def __init__(self,data,timedata_column='index',data_type='NAT', experiment_tag='No tag given',time_unit=None): """ initialisation of a LabExperimBased object, based on a previously defined HydroData object. """ HydroData.__init__(self,data,timedata_column=timedata_column,data_type=data_type, experiment_tag=experiment_tag,time_unit=time_unit) def hours(self,time_column='index'): """ calculates the hours from the relative values Parameters ---------- time_column : string column containing the relative time values; default to index """ if time_column == 'index': self.data['index']=self.time.values self.data['h']= (self.data['indexes'])*24 + self.data['indexes'].shift(1) self.data['h'].fillna(0,inplace=True) self.data.drop('index', axis=1, inplace=True) else: self.data['h']= (self.data[time_column])*24 + self.data[time_column].shift(1) self.data['h'].fillna(0,inplace=True) def add_conc(self,column_name,x,y,new_name='default'): """ calculates the concentration values of the given column and adds them as a new column to the DataFrame. Parameters ---------- column_name : str column with values x : int ... y : int ... new_name : str name of the new column, default to 'column_name + mg/L' """ if new_name == 'default': new_name = column_name + ' ' + 'mg/L' self.data[new_name] = self.data[column_name].values*x*y ## Instead of this function: define a dataframe/dict with conversion or ## concentration factors, so that you can have a function that automatically ## converts all parameters in the frame to concentrations def check_ph(self,ph_column='pH',thresh=0.4): """ gives the maximal change in pH Parameters ---------- ph_column : str column with pH-values, default to 'pH' threshold : int threshold value for warning, default to '0.4' """ dph = self.data[ph_column].max()-self.data[ph_column].min() if dph > thresh: wn.warn('Strong change in pH during experiment!') else: self.delta_ph = dph def in_out(self,columns): """ (start_values-end_values) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] in_out = inv-outv return in_out def removal(self,columns): """ total removal of nitrogen (1-(end_values/start_values)) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] removal = 1-(outv/inv) return removal def calc_slope(self,columns,time_column='h'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to calculate the slope for time_column : str time used for calculation; default to 'h' """ for column in columns: self.data[column + " " +'slope'] = (self.data[column].shift(1)-self.data[column])\ /(self.data[time_column]-self.data[time_column].shift(1)) def plot(self,columns,time_column='index'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to plot time_column : str time used for calculation; default to 'h' """ fig = plt.figure(figsize=(10,6)) ax = fig.add_subplot(111) if time_column=='index': <|fim_middle|> else: for column in columns: ax.plot(self.data[time_column],self.data[column],marker='o') ax.legend() return fig,ax ####################################### def _print_removed_output(original,new,type_): """ function printing the output of functions that remove datapoints. Parameters ---------- original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ print('Original dataset:',original,'datapoints') print('New dataset:',new,'datapoints') print(original-new,'datapoints ',type_) def _log_removed_output(log_file,original,new,type_): """ function writing the output of functions that remove datapoints to a log file. Parameters ---------- log_file : str string containing the directory to the log file to be written out original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ log_file = open(log_file,'a') log_file.write(str('\nOriginal dataset: '+str(original)+' datapoints; new dataset: '+ str(new)+' datapoints'+str(original-new)+' datapoints ',type_)) log_file.close() <|fim▁end|>
for column in columns: ax.plot(self.time,self.data[column],marker='o')
<|file_name|>Class_LabExperimBased.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Class_LabExperimBased provides functionalities for data handling of data obtained in lab experiments in the field of (waste)water treatment. Copyright (C) 2016 Chaim De Mulder This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses/. """ import sys #import os #from os import listdir #import pandas as pd #import scipy as sp #import numpy as np #import datetime as dt import matplotlib.pyplot as plt #plotten in python import warnings as wn from wwdata.Class_HydroData import HydroData class LabExperimBased(HydroData): """ Superclass for a HydroData object, expanding the functionalities with specific functions for data gathered is lab experiments. Attributes ---------- timedata_column : str name of the column containing the time data data_type : str type of the data provided experiment_tag : str A tag identifying the experiment; can be a date or a code used by the producer/owner of the data. time_unit : str The time unit in which the time data is given units : array The units of the variables in the columns """ def __init__(self,data,timedata_column='index',data_type='NAT', experiment_tag='No tag given',time_unit=None): """ initialisation of a LabExperimBased object, based on a previously defined HydroData object. """ HydroData.__init__(self,data,timedata_column=timedata_column,data_type=data_type, experiment_tag=experiment_tag,time_unit=time_unit) def hours(self,time_column='index'): """ calculates the hours from the relative values Parameters ---------- time_column : string column containing the relative time values; default to index """ if time_column == 'index': self.data['index']=self.time.values self.data['h']= (self.data['indexes'])*24 + self.data['indexes'].shift(1) self.data['h'].fillna(0,inplace=True) self.data.drop('index', axis=1, inplace=True) else: self.data['h']= (self.data[time_column])*24 + self.data[time_column].shift(1) self.data['h'].fillna(0,inplace=True) def add_conc(self,column_name,x,y,new_name='default'): """ calculates the concentration values of the given column and adds them as a new column to the DataFrame. Parameters ---------- column_name : str column with values x : int ... y : int ... new_name : str name of the new column, default to 'column_name + mg/L' """ if new_name == 'default': new_name = column_name + ' ' + 'mg/L' self.data[new_name] = self.data[column_name].values*x*y ## Instead of this function: define a dataframe/dict with conversion or ## concentration factors, so that you can have a function that automatically ## converts all parameters in the frame to concentrations def check_ph(self,ph_column='pH',thresh=0.4): """ gives the maximal change in pH Parameters ---------- ph_column : str column with pH-values, default to 'pH' threshold : int threshold value for warning, default to '0.4' """ dph = self.data[ph_column].max()-self.data[ph_column].min() if dph > thresh: wn.warn('Strong change in pH during experiment!') else: self.delta_ph = dph def in_out(self,columns): """ (start_values-end_values) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] in_out = inv-outv return in_out def removal(self,columns): """ total removal of nitrogen (1-(end_values/start_values)) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] removal = 1-(outv/inv) return removal def calc_slope(self,columns,time_column='h'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to calculate the slope for time_column : str time used for calculation; default to 'h' """ for column in columns: self.data[column + " " +'slope'] = (self.data[column].shift(1)-self.data[column])\ /(self.data[time_column]-self.data[time_column].shift(1)) def plot(self,columns,time_column='index'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to plot time_column : str time used for calculation; default to 'h' """ fig = plt.figure(figsize=(10,6)) ax = fig.add_subplot(111) if time_column=='index': for column in columns: ax.plot(self.time,self.data[column],marker='o') else: <|fim_middle|> ax.legend() return fig,ax ####################################### def _print_removed_output(original,new,type_): """ function printing the output of functions that remove datapoints. Parameters ---------- original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ print('Original dataset:',original,'datapoints') print('New dataset:',new,'datapoints') print(original-new,'datapoints ',type_) def _log_removed_output(log_file,original,new,type_): """ function writing the output of functions that remove datapoints to a log file. Parameters ---------- log_file : str string containing the directory to the log file to be written out original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ log_file = open(log_file,'a') log_file.write(str('\nOriginal dataset: '+str(original)+' datapoints; new dataset: '+ str(new)+' datapoints'+str(original-new)+' datapoints ',type_)) log_file.close() <|fim▁end|>
for column in columns: ax.plot(self.data[time_column],self.data[column],marker='o')
<|file_name|>Class_LabExperimBased.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Class_LabExperimBased provides functionalities for data handling of data obtained in lab experiments in the field of (waste)water treatment. Copyright (C) 2016 Chaim De Mulder This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses/. """ import sys #import os #from os import listdir #import pandas as pd #import scipy as sp #import numpy as np #import datetime as dt import matplotlib.pyplot as plt #plotten in python import warnings as wn from wwdata.Class_HydroData import HydroData class LabExperimBased(HydroData): """ Superclass for a HydroData object, expanding the functionalities with specific functions for data gathered is lab experiments. Attributes ---------- timedata_column : str name of the column containing the time data data_type : str type of the data provided experiment_tag : str A tag identifying the experiment; can be a date or a code used by the producer/owner of the data. time_unit : str The time unit in which the time data is given units : array The units of the variables in the columns """ def <|fim_middle|>(self,data,timedata_column='index',data_type='NAT', experiment_tag='No tag given',time_unit=None): """ initialisation of a LabExperimBased object, based on a previously defined HydroData object. """ HydroData.__init__(self,data,timedata_column=timedata_column,data_type=data_type, experiment_tag=experiment_tag,time_unit=time_unit) def hours(self,time_column='index'): """ calculates the hours from the relative values Parameters ---------- time_column : string column containing the relative time values; default to index """ if time_column == 'index': self.data['index']=self.time.values self.data['h']= (self.data['indexes'])*24 + self.data['indexes'].shift(1) self.data['h'].fillna(0,inplace=True) self.data.drop('index', axis=1, inplace=True) else: self.data['h']= (self.data[time_column])*24 + self.data[time_column].shift(1) self.data['h'].fillna(0,inplace=True) def add_conc(self,column_name,x,y,new_name='default'): """ calculates the concentration values of the given column and adds them as a new column to the DataFrame. Parameters ---------- column_name : str column with values x : int ... y : int ... new_name : str name of the new column, default to 'column_name + mg/L' """ if new_name == 'default': new_name = column_name + ' ' + 'mg/L' self.data[new_name] = self.data[column_name].values*x*y ## Instead of this function: define a dataframe/dict with conversion or ## concentration factors, so that you can have a function that automatically ## converts all parameters in the frame to concentrations def check_ph(self,ph_column='pH',thresh=0.4): """ gives the maximal change in pH Parameters ---------- ph_column : str column with pH-values, default to 'pH' threshold : int threshold value for warning, default to '0.4' """ dph = self.data[ph_column].max()-self.data[ph_column].min() if dph > thresh: wn.warn('Strong change in pH during experiment!') else: self.delta_ph = dph def in_out(self,columns): """ (start_values-end_values) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] in_out = inv-outv return in_out def removal(self,columns): """ total removal of nitrogen (1-(end_values/start_values)) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] removal = 1-(outv/inv) return removal def calc_slope(self,columns,time_column='h'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to calculate the slope for time_column : str time used for calculation; default to 'h' """ for column in columns: self.data[column + " " +'slope'] = (self.data[column].shift(1)-self.data[column])\ /(self.data[time_column]-self.data[time_column].shift(1)) def plot(self,columns,time_column='index'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to plot time_column : str time used for calculation; default to 'h' """ fig = plt.figure(figsize=(10,6)) ax = fig.add_subplot(111) if time_column=='index': for column in columns: ax.plot(self.time,self.data[column],marker='o') else: for column in columns: ax.plot(self.data[time_column],self.data[column],marker='o') ax.legend() return fig,ax ####################################### def _print_removed_output(original,new,type_): """ function printing the output of functions that remove datapoints. Parameters ---------- original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ print('Original dataset:',original,'datapoints') print('New dataset:',new,'datapoints') print(original-new,'datapoints ',type_) def _log_removed_output(log_file,original,new,type_): """ function writing the output of functions that remove datapoints to a log file. Parameters ---------- log_file : str string containing the directory to the log file to be written out original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ log_file = open(log_file,'a') log_file.write(str('\nOriginal dataset: '+str(original)+' datapoints; new dataset: '+ str(new)+' datapoints'+str(original-new)+' datapoints ',type_)) log_file.close() <|fim▁end|>
__init__
<|file_name|>Class_LabExperimBased.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Class_LabExperimBased provides functionalities for data handling of data obtained in lab experiments in the field of (waste)water treatment. Copyright (C) 2016 Chaim De Mulder This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses/. """ import sys #import os #from os import listdir #import pandas as pd #import scipy as sp #import numpy as np #import datetime as dt import matplotlib.pyplot as plt #plotten in python import warnings as wn from wwdata.Class_HydroData import HydroData class LabExperimBased(HydroData): """ Superclass for a HydroData object, expanding the functionalities with specific functions for data gathered is lab experiments. Attributes ---------- timedata_column : str name of the column containing the time data data_type : str type of the data provided experiment_tag : str A tag identifying the experiment; can be a date or a code used by the producer/owner of the data. time_unit : str The time unit in which the time data is given units : array The units of the variables in the columns """ def __init__(self,data,timedata_column='index',data_type='NAT', experiment_tag='No tag given',time_unit=None): """ initialisation of a LabExperimBased object, based on a previously defined HydroData object. """ HydroData.__init__(self,data,timedata_column=timedata_column,data_type=data_type, experiment_tag=experiment_tag,time_unit=time_unit) def <|fim_middle|>(self,time_column='index'): """ calculates the hours from the relative values Parameters ---------- time_column : string column containing the relative time values; default to index """ if time_column == 'index': self.data['index']=self.time.values self.data['h']= (self.data['indexes'])*24 + self.data['indexes'].shift(1) self.data['h'].fillna(0,inplace=True) self.data.drop('index', axis=1, inplace=True) else: self.data['h']= (self.data[time_column])*24 + self.data[time_column].shift(1) self.data['h'].fillna(0,inplace=True) def add_conc(self,column_name,x,y,new_name='default'): """ calculates the concentration values of the given column and adds them as a new column to the DataFrame. Parameters ---------- column_name : str column with values x : int ... y : int ... new_name : str name of the new column, default to 'column_name + mg/L' """ if new_name == 'default': new_name = column_name + ' ' + 'mg/L' self.data[new_name] = self.data[column_name].values*x*y ## Instead of this function: define a dataframe/dict with conversion or ## concentration factors, so that you can have a function that automatically ## converts all parameters in the frame to concentrations def check_ph(self,ph_column='pH',thresh=0.4): """ gives the maximal change in pH Parameters ---------- ph_column : str column with pH-values, default to 'pH' threshold : int threshold value for warning, default to '0.4' """ dph = self.data[ph_column].max()-self.data[ph_column].min() if dph > thresh: wn.warn('Strong change in pH during experiment!') else: self.delta_ph = dph def in_out(self,columns): """ (start_values-end_values) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] in_out = inv-outv return in_out def removal(self,columns): """ total removal of nitrogen (1-(end_values/start_values)) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] removal = 1-(outv/inv) return removal def calc_slope(self,columns,time_column='h'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to calculate the slope for time_column : str time used for calculation; default to 'h' """ for column in columns: self.data[column + " " +'slope'] = (self.data[column].shift(1)-self.data[column])\ /(self.data[time_column]-self.data[time_column].shift(1)) def plot(self,columns,time_column='index'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to plot time_column : str time used for calculation; default to 'h' """ fig = plt.figure(figsize=(10,6)) ax = fig.add_subplot(111) if time_column=='index': for column in columns: ax.plot(self.time,self.data[column],marker='o') else: for column in columns: ax.plot(self.data[time_column],self.data[column],marker='o') ax.legend() return fig,ax ####################################### def _print_removed_output(original,new,type_): """ function printing the output of functions that remove datapoints. Parameters ---------- original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ print('Original dataset:',original,'datapoints') print('New dataset:',new,'datapoints') print(original-new,'datapoints ',type_) def _log_removed_output(log_file,original,new,type_): """ function writing the output of functions that remove datapoints to a log file. Parameters ---------- log_file : str string containing the directory to the log file to be written out original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ log_file = open(log_file,'a') log_file.write(str('\nOriginal dataset: '+str(original)+' datapoints; new dataset: '+ str(new)+' datapoints'+str(original-new)+' datapoints ',type_)) log_file.close() <|fim▁end|>
hours
<|file_name|>Class_LabExperimBased.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Class_LabExperimBased provides functionalities for data handling of data obtained in lab experiments in the field of (waste)water treatment. Copyright (C) 2016 Chaim De Mulder This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses/. """ import sys #import os #from os import listdir #import pandas as pd #import scipy as sp #import numpy as np #import datetime as dt import matplotlib.pyplot as plt #plotten in python import warnings as wn from wwdata.Class_HydroData import HydroData class LabExperimBased(HydroData): """ Superclass for a HydroData object, expanding the functionalities with specific functions for data gathered is lab experiments. Attributes ---------- timedata_column : str name of the column containing the time data data_type : str type of the data provided experiment_tag : str A tag identifying the experiment; can be a date or a code used by the producer/owner of the data. time_unit : str The time unit in which the time data is given units : array The units of the variables in the columns """ def __init__(self,data,timedata_column='index',data_type='NAT', experiment_tag='No tag given',time_unit=None): """ initialisation of a LabExperimBased object, based on a previously defined HydroData object. """ HydroData.__init__(self,data,timedata_column=timedata_column,data_type=data_type, experiment_tag=experiment_tag,time_unit=time_unit) def hours(self,time_column='index'): """ calculates the hours from the relative values Parameters ---------- time_column : string column containing the relative time values; default to index """ if time_column == 'index': self.data['index']=self.time.values self.data['h']= (self.data['indexes'])*24 + self.data['indexes'].shift(1) self.data['h'].fillna(0,inplace=True) self.data.drop('index', axis=1, inplace=True) else: self.data['h']= (self.data[time_column])*24 + self.data[time_column].shift(1) self.data['h'].fillna(0,inplace=True) def <|fim_middle|>(self,column_name,x,y,new_name='default'): """ calculates the concentration values of the given column and adds them as a new column to the DataFrame. Parameters ---------- column_name : str column with values x : int ... y : int ... new_name : str name of the new column, default to 'column_name + mg/L' """ if new_name == 'default': new_name = column_name + ' ' + 'mg/L' self.data[new_name] = self.data[column_name].values*x*y ## Instead of this function: define a dataframe/dict with conversion or ## concentration factors, so that you can have a function that automatically ## converts all parameters in the frame to concentrations def check_ph(self,ph_column='pH',thresh=0.4): """ gives the maximal change in pH Parameters ---------- ph_column : str column with pH-values, default to 'pH' threshold : int threshold value for warning, default to '0.4' """ dph = self.data[ph_column].max()-self.data[ph_column].min() if dph > thresh: wn.warn('Strong change in pH during experiment!') else: self.delta_ph = dph def in_out(self,columns): """ (start_values-end_values) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] in_out = inv-outv return in_out def removal(self,columns): """ total removal of nitrogen (1-(end_values/start_values)) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] removal = 1-(outv/inv) return removal def calc_slope(self,columns,time_column='h'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to calculate the slope for time_column : str time used for calculation; default to 'h' """ for column in columns: self.data[column + " " +'slope'] = (self.data[column].shift(1)-self.data[column])\ /(self.data[time_column]-self.data[time_column].shift(1)) def plot(self,columns,time_column='index'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to plot time_column : str time used for calculation; default to 'h' """ fig = plt.figure(figsize=(10,6)) ax = fig.add_subplot(111) if time_column=='index': for column in columns: ax.plot(self.time,self.data[column],marker='o') else: for column in columns: ax.plot(self.data[time_column],self.data[column],marker='o') ax.legend() return fig,ax ####################################### def _print_removed_output(original,new,type_): """ function printing the output of functions that remove datapoints. Parameters ---------- original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ print('Original dataset:',original,'datapoints') print('New dataset:',new,'datapoints') print(original-new,'datapoints ',type_) def _log_removed_output(log_file,original,new,type_): """ function writing the output of functions that remove datapoints to a log file. Parameters ---------- log_file : str string containing the directory to the log file to be written out original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ log_file = open(log_file,'a') log_file.write(str('\nOriginal dataset: '+str(original)+' datapoints; new dataset: '+ str(new)+' datapoints'+str(original-new)+' datapoints ',type_)) log_file.close() <|fim▁end|>
add_conc
<|file_name|>Class_LabExperimBased.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Class_LabExperimBased provides functionalities for data handling of data obtained in lab experiments in the field of (waste)water treatment. Copyright (C) 2016 Chaim De Mulder This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses/. """ import sys #import os #from os import listdir #import pandas as pd #import scipy as sp #import numpy as np #import datetime as dt import matplotlib.pyplot as plt #plotten in python import warnings as wn from wwdata.Class_HydroData import HydroData class LabExperimBased(HydroData): """ Superclass for a HydroData object, expanding the functionalities with specific functions for data gathered is lab experiments. Attributes ---------- timedata_column : str name of the column containing the time data data_type : str type of the data provided experiment_tag : str A tag identifying the experiment; can be a date or a code used by the producer/owner of the data. time_unit : str The time unit in which the time data is given units : array The units of the variables in the columns """ def __init__(self,data,timedata_column='index',data_type='NAT', experiment_tag='No tag given',time_unit=None): """ initialisation of a LabExperimBased object, based on a previously defined HydroData object. """ HydroData.__init__(self,data,timedata_column=timedata_column,data_type=data_type, experiment_tag=experiment_tag,time_unit=time_unit) def hours(self,time_column='index'): """ calculates the hours from the relative values Parameters ---------- time_column : string column containing the relative time values; default to index """ if time_column == 'index': self.data['index']=self.time.values self.data['h']= (self.data['indexes'])*24 + self.data['indexes'].shift(1) self.data['h'].fillna(0,inplace=True) self.data.drop('index', axis=1, inplace=True) else: self.data['h']= (self.data[time_column])*24 + self.data[time_column].shift(1) self.data['h'].fillna(0,inplace=True) def add_conc(self,column_name,x,y,new_name='default'): """ calculates the concentration values of the given column and adds them as a new column to the DataFrame. Parameters ---------- column_name : str column with values x : int ... y : int ... new_name : str name of the new column, default to 'column_name + mg/L' """ if new_name == 'default': new_name = column_name + ' ' + 'mg/L' self.data[new_name] = self.data[column_name].values*x*y ## Instead of this function: define a dataframe/dict with conversion or ## concentration factors, so that you can have a function that automatically ## converts all parameters in the frame to concentrations def <|fim_middle|>(self,ph_column='pH',thresh=0.4): """ gives the maximal change in pH Parameters ---------- ph_column : str column with pH-values, default to 'pH' threshold : int threshold value for warning, default to '0.4' """ dph = self.data[ph_column].max()-self.data[ph_column].min() if dph > thresh: wn.warn('Strong change in pH during experiment!') else: self.delta_ph = dph def in_out(self,columns): """ (start_values-end_values) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] in_out = inv-outv return in_out def removal(self,columns): """ total removal of nitrogen (1-(end_values/start_values)) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] removal = 1-(outv/inv) return removal def calc_slope(self,columns,time_column='h'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to calculate the slope for time_column : str time used for calculation; default to 'h' """ for column in columns: self.data[column + " " +'slope'] = (self.data[column].shift(1)-self.data[column])\ /(self.data[time_column]-self.data[time_column].shift(1)) def plot(self,columns,time_column='index'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to plot time_column : str time used for calculation; default to 'h' """ fig = plt.figure(figsize=(10,6)) ax = fig.add_subplot(111) if time_column=='index': for column in columns: ax.plot(self.time,self.data[column],marker='o') else: for column in columns: ax.plot(self.data[time_column],self.data[column],marker='o') ax.legend() return fig,ax ####################################### def _print_removed_output(original,new,type_): """ function printing the output of functions that remove datapoints. Parameters ---------- original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ print('Original dataset:',original,'datapoints') print('New dataset:',new,'datapoints') print(original-new,'datapoints ',type_) def _log_removed_output(log_file,original,new,type_): """ function writing the output of functions that remove datapoints to a log file. Parameters ---------- log_file : str string containing the directory to the log file to be written out original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ log_file = open(log_file,'a') log_file.write(str('\nOriginal dataset: '+str(original)+' datapoints; new dataset: '+ str(new)+' datapoints'+str(original-new)+' datapoints ',type_)) log_file.close() <|fim▁end|>
check_ph
<|file_name|>Class_LabExperimBased.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Class_LabExperimBased provides functionalities for data handling of data obtained in lab experiments in the field of (waste)water treatment. Copyright (C) 2016 Chaim De Mulder This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses/. """ import sys #import os #from os import listdir #import pandas as pd #import scipy as sp #import numpy as np #import datetime as dt import matplotlib.pyplot as plt #plotten in python import warnings as wn from wwdata.Class_HydroData import HydroData class LabExperimBased(HydroData): """ Superclass for a HydroData object, expanding the functionalities with specific functions for data gathered is lab experiments. Attributes ---------- timedata_column : str name of the column containing the time data data_type : str type of the data provided experiment_tag : str A tag identifying the experiment; can be a date or a code used by the producer/owner of the data. time_unit : str The time unit in which the time data is given units : array The units of the variables in the columns """ def __init__(self,data,timedata_column='index',data_type='NAT', experiment_tag='No tag given',time_unit=None): """ initialisation of a LabExperimBased object, based on a previously defined HydroData object. """ HydroData.__init__(self,data,timedata_column=timedata_column,data_type=data_type, experiment_tag=experiment_tag,time_unit=time_unit) def hours(self,time_column='index'): """ calculates the hours from the relative values Parameters ---------- time_column : string column containing the relative time values; default to index """ if time_column == 'index': self.data['index']=self.time.values self.data['h']= (self.data['indexes'])*24 + self.data['indexes'].shift(1) self.data['h'].fillna(0,inplace=True) self.data.drop('index', axis=1, inplace=True) else: self.data['h']= (self.data[time_column])*24 + self.data[time_column].shift(1) self.data['h'].fillna(0,inplace=True) def add_conc(self,column_name,x,y,new_name='default'): """ calculates the concentration values of the given column and adds them as a new column to the DataFrame. Parameters ---------- column_name : str column with values x : int ... y : int ... new_name : str name of the new column, default to 'column_name + mg/L' """ if new_name == 'default': new_name = column_name + ' ' + 'mg/L' self.data[new_name] = self.data[column_name].values*x*y ## Instead of this function: define a dataframe/dict with conversion or ## concentration factors, so that you can have a function that automatically ## converts all parameters in the frame to concentrations def check_ph(self,ph_column='pH',thresh=0.4): """ gives the maximal change in pH Parameters ---------- ph_column : str column with pH-values, default to 'pH' threshold : int threshold value for warning, default to '0.4' """ dph = self.data[ph_column].max()-self.data[ph_column].min() if dph > thresh: wn.warn('Strong change in pH during experiment!') else: self.delta_ph = dph def <|fim_middle|>(self,columns): """ (start_values-end_values) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] in_out = inv-outv return in_out def removal(self,columns): """ total removal of nitrogen (1-(end_values/start_values)) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] removal = 1-(outv/inv) return removal def calc_slope(self,columns,time_column='h'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to calculate the slope for time_column : str time used for calculation; default to 'h' """ for column in columns: self.data[column + " " +'slope'] = (self.data[column].shift(1)-self.data[column])\ /(self.data[time_column]-self.data[time_column].shift(1)) def plot(self,columns,time_column='index'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to plot time_column : str time used for calculation; default to 'h' """ fig = plt.figure(figsize=(10,6)) ax = fig.add_subplot(111) if time_column=='index': for column in columns: ax.plot(self.time,self.data[column],marker='o') else: for column in columns: ax.plot(self.data[time_column],self.data[column],marker='o') ax.legend() return fig,ax ####################################### def _print_removed_output(original,new,type_): """ function printing the output of functions that remove datapoints. Parameters ---------- original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ print('Original dataset:',original,'datapoints') print('New dataset:',new,'datapoints') print(original-new,'datapoints ',type_) def _log_removed_output(log_file,original,new,type_): """ function writing the output of functions that remove datapoints to a log file. Parameters ---------- log_file : str string containing the directory to the log file to be written out original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ log_file = open(log_file,'a') log_file.write(str('\nOriginal dataset: '+str(original)+' datapoints; new dataset: '+ str(new)+' datapoints'+str(original-new)+' datapoints ',type_)) log_file.close() <|fim▁end|>
in_out
<|file_name|>Class_LabExperimBased.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Class_LabExperimBased provides functionalities for data handling of data obtained in lab experiments in the field of (waste)water treatment. Copyright (C) 2016 Chaim De Mulder This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses/. """ import sys #import os #from os import listdir #import pandas as pd #import scipy as sp #import numpy as np #import datetime as dt import matplotlib.pyplot as plt #plotten in python import warnings as wn from wwdata.Class_HydroData import HydroData class LabExperimBased(HydroData): """ Superclass for a HydroData object, expanding the functionalities with specific functions for data gathered is lab experiments. Attributes ---------- timedata_column : str name of the column containing the time data data_type : str type of the data provided experiment_tag : str A tag identifying the experiment; can be a date or a code used by the producer/owner of the data. time_unit : str The time unit in which the time data is given units : array The units of the variables in the columns """ def __init__(self,data,timedata_column='index',data_type='NAT', experiment_tag='No tag given',time_unit=None): """ initialisation of a LabExperimBased object, based on a previously defined HydroData object. """ HydroData.__init__(self,data,timedata_column=timedata_column,data_type=data_type, experiment_tag=experiment_tag,time_unit=time_unit) def hours(self,time_column='index'): """ calculates the hours from the relative values Parameters ---------- time_column : string column containing the relative time values; default to index """ if time_column == 'index': self.data['index']=self.time.values self.data['h']= (self.data['indexes'])*24 + self.data['indexes'].shift(1) self.data['h'].fillna(0,inplace=True) self.data.drop('index', axis=1, inplace=True) else: self.data['h']= (self.data[time_column])*24 + self.data[time_column].shift(1) self.data['h'].fillna(0,inplace=True) def add_conc(self,column_name,x,y,new_name='default'): """ calculates the concentration values of the given column and adds them as a new column to the DataFrame. Parameters ---------- column_name : str column with values x : int ... y : int ... new_name : str name of the new column, default to 'column_name + mg/L' """ if new_name == 'default': new_name = column_name + ' ' + 'mg/L' self.data[new_name] = self.data[column_name].values*x*y ## Instead of this function: define a dataframe/dict with conversion or ## concentration factors, so that you can have a function that automatically ## converts all parameters in the frame to concentrations def check_ph(self,ph_column='pH',thresh=0.4): """ gives the maximal change in pH Parameters ---------- ph_column : str column with pH-values, default to 'pH' threshold : int threshold value for warning, default to '0.4' """ dph = self.data[ph_column].max()-self.data[ph_column].min() if dph > thresh: wn.warn('Strong change in pH during experiment!') else: self.delta_ph = dph def in_out(self,columns): """ (start_values-end_values) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] in_out = inv-outv return in_out def <|fim_middle|>(self,columns): """ total removal of nitrogen (1-(end_values/start_values)) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] removal = 1-(outv/inv) return removal def calc_slope(self,columns,time_column='h'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to calculate the slope for time_column : str time used for calculation; default to 'h' """ for column in columns: self.data[column + " " +'slope'] = (self.data[column].shift(1)-self.data[column])\ /(self.data[time_column]-self.data[time_column].shift(1)) def plot(self,columns,time_column='index'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to plot time_column : str time used for calculation; default to 'h' """ fig = plt.figure(figsize=(10,6)) ax = fig.add_subplot(111) if time_column=='index': for column in columns: ax.plot(self.time,self.data[column],marker='o') else: for column in columns: ax.plot(self.data[time_column],self.data[column],marker='o') ax.legend() return fig,ax ####################################### def _print_removed_output(original,new,type_): """ function printing the output of functions that remove datapoints. Parameters ---------- original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ print('Original dataset:',original,'datapoints') print('New dataset:',new,'datapoints') print(original-new,'datapoints ',type_) def _log_removed_output(log_file,original,new,type_): """ function writing the output of functions that remove datapoints to a log file. Parameters ---------- log_file : str string containing the directory to the log file to be written out original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ log_file = open(log_file,'a') log_file.write(str('\nOriginal dataset: '+str(original)+' datapoints; new dataset: '+ str(new)+' datapoints'+str(original-new)+' datapoints ',type_)) log_file.close() <|fim▁end|>
removal
<|file_name|>Class_LabExperimBased.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Class_LabExperimBased provides functionalities for data handling of data obtained in lab experiments in the field of (waste)water treatment. Copyright (C) 2016 Chaim De Mulder This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses/. """ import sys #import os #from os import listdir #import pandas as pd #import scipy as sp #import numpy as np #import datetime as dt import matplotlib.pyplot as plt #plotten in python import warnings as wn from wwdata.Class_HydroData import HydroData class LabExperimBased(HydroData): """ Superclass for a HydroData object, expanding the functionalities with specific functions for data gathered is lab experiments. Attributes ---------- timedata_column : str name of the column containing the time data data_type : str type of the data provided experiment_tag : str A tag identifying the experiment; can be a date or a code used by the producer/owner of the data. time_unit : str The time unit in which the time data is given units : array The units of the variables in the columns """ def __init__(self,data,timedata_column='index',data_type='NAT', experiment_tag='No tag given',time_unit=None): """ initialisation of a LabExperimBased object, based on a previously defined HydroData object. """ HydroData.__init__(self,data,timedata_column=timedata_column,data_type=data_type, experiment_tag=experiment_tag,time_unit=time_unit) def hours(self,time_column='index'): """ calculates the hours from the relative values Parameters ---------- time_column : string column containing the relative time values; default to index """ if time_column == 'index': self.data['index']=self.time.values self.data['h']= (self.data['indexes'])*24 + self.data['indexes'].shift(1) self.data['h'].fillna(0,inplace=True) self.data.drop('index', axis=1, inplace=True) else: self.data['h']= (self.data[time_column])*24 + self.data[time_column].shift(1) self.data['h'].fillna(0,inplace=True) def add_conc(self,column_name,x,y,new_name='default'): """ calculates the concentration values of the given column and adds them as a new column to the DataFrame. Parameters ---------- column_name : str column with values x : int ... y : int ... new_name : str name of the new column, default to 'column_name + mg/L' """ if new_name == 'default': new_name = column_name + ' ' + 'mg/L' self.data[new_name] = self.data[column_name].values*x*y ## Instead of this function: define a dataframe/dict with conversion or ## concentration factors, so that you can have a function that automatically ## converts all parameters in the frame to concentrations def check_ph(self,ph_column='pH',thresh=0.4): """ gives the maximal change in pH Parameters ---------- ph_column : str column with pH-values, default to 'pH' threshold : int threshold value for warning, default to '0.4' """ dph = self.data[ph_column].max()-self.data[ph_column].min() if dph > thresh: wn.warn('Strong change in pH during experiment!') else: self.delta_ph = dph def in_out(self,columns): """ (start_values-end_values) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] in_out = inv-outv return in_out def removal(self,columns): """ total removal of nitrogen (1-(end_values/start_values)) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] removal = 1-(outv/inv) return removal def <|fim_middle|>(self,columns,time_column='h'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to calculate the slope for time_column : str time used for calculation; default to 'h' """ for column in columns: self.data[column + " " +'slope'] = (self.data[column].shift(1)-self.data[column])\ /(self.data[time_column]-self.data[time_column].shift(1)) def plot(self,columns,time_column='index'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to plot time_column : str time used for calculation; default to 'h' """ fig = plt.figure(figsize=(10,6)) ax = fig.add_subplot(111) if time_column=='index': for column in columns: ax.plot(self.time,self.data[column],marker='o') else: for column in columns: ax.plot(self.data[time_column],self.data[column],marker='o') ax.legend() return fig,ax ####################################### def _print_removed_output(original,new,type_): """ function printing the output of functions that remove datapoints. Parameters ---------- original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ print('Original dataset:',original,'datapoints') print('New dataset:',new,'datapoints') print(original-new,'datapoints ',type_) def _log_removed_output(log_file,original,new,type_): """ function writing the output of functions that remove datapoints to a log file. Parameters ---------- log_file : str string containing the directory to the log file to be written out original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ log_file = open(log_file,'a') log_file.write(str('\nOriginal dataset: '+str(original)+' datapoints; new dataset: '+ str(new)+' datapoints'+str(original-new)+' datapoints ',type_)) log_file.close() <|fim▁end|>
calc_slope
<|file_name|>Class_LabExperimBased.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Class_LabExperimBased provides functionalities for data handling of data obtained in lab experiments in the field of (waste)water treatment. Copyright (C) 2016 Chaim De Mulder This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses/. """ import sys #import os #from os import listdir #import pandas as pd #import scipy as sp #import numpy as np #import datetime as dt import matplotlib.pyplot as plt #plotten in python import warnings as wn from wwdata.Class_HydroData import HydroData class LabExperimBased(HydroData): """ Superclass for a HydroData object, expanding the functionalities with specific functions for data gathered is lab experiments. Attributes ---------- timedata_column : str name of the column containing the time data data_type : str type of the data provided experiment_tag : str A tag identifying the experiment; can be a date or a code used by the producer/owner of the data. time_unit : str The time unit in which the time data is given units : array The units of the variables in the columns """ def __init__(self,data,timedata_column='index',data_type='NAT', experiment_tag='No tag given',time_unit=None): """ initialisation of a LabExperimBased object, based on a previously defined HydroData object. """ HydroData.__init__(self,data,timedata_column=timedata_column,data_type=data_type, experiment_tag=experiment_tag,time_unit=time_unit) def hours(self,time_column='index'): """ calculates the hours from the relative values Parameters ---------- time_column : string column containing the relative time values; default to index """ if time_column == 'index': self.data['index']=self.time.values self.data['h']= (self.data['indexes'])*24 + self.data['indexes'].shift(1) self.data['h'].fillna(0,inplace=True) self.data.drop('index', axis=1, inplace=True) else: self.data['h']= (self.data[time_column])*24 + self.data[time_column].shift(1) self.data['h'].fillna(0,inplace=True) def add_conc(self,column_name,x,y,new_name='default'): """ calculates the concentration values of the given column and adds them as a new column to the DataFrame. Parameters ---------- column_name : str column with values x : int ... y : int ... new_name : str name of the new column, default to 'column_name + mg/L' """ if new_name == 'default': new_name = column_name + ' ' + 'mg/L' self.data[new_name] = self.data[column_name].values*x*y ## Instead of this function: define a dataframe/dict with conversion or ## concentration factors, so that you can have a function that automatically ## converts all parameters in the frame to concentrations def check_ph(self,ph_column='pH',thresh=0.4): """ gives the maximal change in pH Parameters ---------- ph_column : str column with pH-values, default to 'pH' threshold : int threshold value for warning, default to '0.4' """ dph = self.data[ph_column].max()-self.data[ph_column].min() if dph > thresh: wn.warn('Strong change in pH during experiment!') else: self.delta_ph = dph def in_out(self,columns): """ (start_values-end_values) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] in_out = inv-outv return in_out def removal(self,columns): """ total removal of nitrogen (1-(end_values/start_values)) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] removal = 1-(outv/inv) return removal def calc_slope(self,columns,time_column='h'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to calculate the slope for time_column : str time used for calculation; default to 'h' """ for column in columns: self.data[column + " " +'slope'] = (self.data[column].shift(1)-self.data[column])\ /(self.data[time_column]-self.data[time_column].shift(1)) def <|fim_middle|>(self,columns,time_column='index'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to plot time_column : str time used for calculation; default to 'h' """ fig = plt.figure(figsize=(10,6)) ax = fig.add_subplot(111) if time_column=='index': for column in columns: ax.plot(self.time,self.data[column],marker='o') else: for column in columns: ax.plot(self.data[time_column],self.data[column],marker='o') ax.legend() return fig,ax ####################################### def _print_removed_output(original,new,type_): """ function printing the output of functions that remove datapoints. Parameters ---------- original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ print('Original dataset:',original,'datapoints') print('New dataset:',new,'datapoints') print(original-new,'datapoints ',type_) def _log_removed_output(log_file,original,new,type_): """ function writing the output of functions that remove datapoints to a log file. Parameters ---------- log_file : str string containing the directory to the log file to be written out original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ log_file = open(log_file,'a') log_file.write(str('\nOriginal dataset: '+str(original)+' datapoints; new dataset: '+ str(new)+' datapoints'+str(original-new)+' datapoints ',type_)) log_file.close() <|fim▁end|>
plot
<|file_name|>Class_LabExperimBased.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Class_LabExperimBased provides functionalities for data handling of data obtained in lab experiments in the field of (waste)water treatment. Copyright (C) 2016 Chaim De Mulder This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses/. """ import sys #import os #from os import listdir #import pandas as pd #import scipy as sp #import numpy as np #import datetime as dt import matplotlib.pyplot as plt #plotten in python import warnings as wn from wwdata.Class_HydroData import HydroData class LabExperimBased(HydroData): """ Superclass for a HydroData object, expanding the functionalities with specific functions for data gathered is lab experiments. Attributes ---------- timedata_column : str name of the column containing the time data data_type : str type of the data provided experiment_tag : str A tag identifying the experiment; can be a date or a code used by the producer/owner of the data. time_unit : str The time unit in which the time data is given units : array The units of the variables in the columns """ def __init__(self,data,timedata_column='index',data_type='NAT', experiment_tag='No tag given',time_unit=None): """ initialisation of a LabExperimBased object, based on a previously defined HydroData object. """ HydroData.__init__(self,data,timedata_column=timedata_column,data_type=data_type, experiment_tag=experiment_tag,time_unit=time_unit) def hours(self,time_column='index'): """ calculates the hours from the relative values Parameters ---------- time_column : string column containing the relative time values; default to index """ if time_column == 'index': self.data['index']=self.time.values self.data['h']= (self.data['indexes'])*24 + self.data['indexes'].shift(1) self.data['h'].fillna(0,inplace=True) self.data.drop('index', axis=1, inplace=True) else: self.data['h']= (self.data[time_column])*24 + self.data[time_column].shift(1) self.data['h'].fillna(0,inplace=True) def add_conc(self,column_name,x,y,new_name='default'): """ calculates the concentration values of the given column and adds them as a new column to the DataFrame. Parameters ---------- column_name : str column with values x : int ... y : int ... new_name : str name of the new column, default to 'column_name + mg/L' """ if new_name == 'default': new_name = column_name + ' ' + 'mg/L' self.data[new_name] = self.data[column_name].values*x*y ## Instead of this function: define a dataframe/dict with conversion or ## concentration factors, so that you can have a function that automatically ## converts all parameters in the frame to concentrations def check_ph(self,ph_column='pH',thresh=0.4): """ gives the maximal change in pH Parameters ---------- ph_column : str column with pH-values, default to 'pH' threshold : int threshold value for warning, default to '0.4' """ dph = self.data[ph_column].max()-self.data[ph_column].min() if dph > thresh: wn.warn('Strong change in pH during experiment!') else: self.delta_ph = dph def in_out(self,columns): """ (start_values-end_values) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] in_out = inv-outv return in_out def removal(self,columns): """ total removal of nitrogen (1-(end_values/start_values)) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] removal = 1-(outv/inv) return removal def calc_slope(self,columns,time_column='h'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to calculate the slope for time_column : str time used for calculation; default to 'h' """ for column in columns: self.data[column + " " +'slope'] = (self.data[column].shift(1)-self.data[column])\ /(self.data[time_column]-self.data[time_column].shift(1)) def plot(self,columns,time_column='index'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to plot time_column : str time used for calculation; default to 'h' """ fig = plt.figure(figsize=(10,6)) ax = fig.add_subplot(111) if time_column=='index': for column in columns: ax.plot(self.time,self.data[column],marker='o') else: for column in columns: ax.plot(self.data[time_column],self.data[column],marker='o') ax.legend() return fig,ax ####################################### def <|fim_middle|>(original,new,type_): """ function printing the output of functions that remove datapoints. Parameters ---------- original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ print('Original dataset:',original,'datapoints') print('New dataset:',new,'datapoints') print(original-new,'datapoints ',type_) def _log_removed_output(log_file,original,new,type_): """ function writing the output of functions that remove datapoints to a log file. Parameters ---------- log_file : str string containing the directory to the log file to be written out original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ log_file = open(log_file,'a') log_file.write(str('\nOriginal dataset: '+str(original)+' datapoints; new dataset: '+ str(new)+' datapoints'+str(original-new)+' datapoints ',type_)) log_file.close() <|fim▁end|>
_print_removed_output
<|file_name|>Class_LabExperimBased.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """ Class_LabExperimBased provides functionalities for data handling of data obtained in lab experiments in the field of (waste)water treatment. Copyright (C) 2016 Chaim De Mulder This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see http://www.gnu.org/licenses/. """ import sys #import os #from os import listdir #import pandas as pd #import scipy as sp #import numpy as np #import datetime as dt import matplotlib.pyplot as plt #plotten in python import warnings as wn from wwdata.Class_HydroData import HydroData class LabExperimBased(HydroData): """ Superclass for a HydroData object, expanding the functionalities with specific functions for data gathered is lab experiments. Attributes ---------- timedata_column : str name of the column containing the time data data_type : str type of the data provided experiment_tag : str A tag identifying the experiment; can be a date or a code used by the producer/owner of the data. time_unit : str The time unit in which the time data is given units : array The units of the variables in the columns """ def __init__(self,data,timedata_column='index',data_type='NAT', experiment_tag='No tag given',time_unit=None): """ initialisation of a LabExperimBased object, based on a previously defined HydroData object. """ HydroData.__init__(self,data,timedata_column=timedata_column,data_type=data_type, experiment_tag=experiment_tag,time_unit=time_unit) def hours(self,time_column='index'): """ calculates the hours from the relative values Parameters ---------- time_column : string column containing the relative time values; default to index """ if time_column == 'index': self.data['index']=self.time.values self.data['h']= (self.data['indexes'])*24 + self.data['indexes'].shift(1) self.data['h'].fillna(0,inplace=True) self.data.drop('index', axis=1, inplace=True) else: self.data['h']= (self.data[time_column])*24 + self.data[time_column].shift(1) self.data['h'].fillna(0,inplace=True) def add_conc(self,column_name,x,y,new_name='default'): """ calculates the concentration values of the given column and adds them as a new column to the DataFrame. Parameters ---------- column_name : str column with values x : int ... y : int ... new_name : str name of the new column, default to 'column_name + mg/L' """ if new_name == 'default': new_name = column_name + ' ' + 'mg/L' self.data[new_name] = self.data[column_name].values*x*y ## Instead of this function: define a dataframe/dict with conversion or ## concentration factors, so that you can have a function that automatically ## converts all parameters in the frame to concentrations def check_ph(self,ph_column='pH',thresh=0.4): """ gives the maximal change in pH Parameters ---------- ph_column : str column with pH-values, default to 'pH' threshold : int threshold value for warning, default to '0.4' """ dph = self.data[ph_column].max()-self.data[ph_column].min() if dph > thresh: wn.warn('Strong change in pH during experiment!') else: self.delta_ph = dph def in_out(self,columns): """ (start_values-end_values) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] in_out = inv-outv return in_out def removal(self,columns): """ total removal of nitrogen (1-(end_values/start_values)) Parameters ---------- columns : array of strings """ inv=0 outv=0 indexes= self.time.values for column in columns: inv += self.data[column][indexes[0]] for column in columns: outv += self.data[column][indexes[-1]] removal = 1-(outv/inv) return removal def calc_slope(self,columns,time_column='h'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to calculate the slope for time_column : str time used for calculation; default to 'h' """ for column in columns: self.data[column + " " +'slope'] = (self.data[column].shift(1)-self.data[column])\ /(self.data[time_column]-self.data[time_column].shift(1)) def plot(self,columns,time_column='index'): """ calculates the slope of the selected columns Parameters ---------- columns : array of strings columns to plot time_column : str time used for calculation; default to 'h' """ fig = plt.figure(figsize=(10,6)) ax = fig.add_subplot(111) if time_column=='index': for column in columns: ax.plot(self.time,self.data[column],marker='o') else: for column in columns: ax.plot(self.data[time_column],self.data[column],marker='o') ax.legend() return fig,ax ####################################### def _print_removed_output(original,new,type_): """ function printing the output of functions that remove datapoints. Parameters ---------- original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ print('Original dataset:',original,'datapoints') print('New dataset:',new,'datapoints') print(original-new,'datapoints ',type_) def <|fim_middle|>(log_file,original,new,type_): """ function writing the output of functions that remove datapoints to a log file. Parameters ---------- log_file : str string containing the directory to the log file to be written out original : int original length of the dataset new : int length of the new dataset type_ : str 'removed' or 'dropped' """ log_file = open(log_file,'a') log_file.write(str('\nOriginal dataset: '+str(original)+' datapoints; new dataset: '+ str(new)+' datapoints'+str(original-new)+' datapoints ',type_)) log_file.close() <|fim▁end|>
_log_removed_output
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models # Create your models here. class Profil(models.Model): awal = '' PILIHAN_JENJANG = ( (awal, '----'), ('Pertama', 'Perekayasa Pertama'), ('Muda', 'Perekayasa Muda'), ('Madya', 'Perekayasa Madya'), ('Utama', 'Perekayasa Utama'), ) nip = models.CharField(max_length=50, verbose_name='NIP') pendidikan = models.CharField(max_length=150, verbose_name='Pendidikan') instansi = models.TextField(verbose_name='Nama Lengkap Unit') instansi_kode = models.CharField(max_length=20, verbose_name='Singkatan Unit') satuan = models.TextField(verbose_name='Nama Lengkap Satuan kerja', blank=True) kantor = models.TextField(verbose_name='Nama Lengkap Kantor', blank=True) pangkat = models.TextField(verbose_name='Pangkat/Golongan Ruang/TMT') jabatan = models.CharField(max_length=150, verbose_name='Jabatan') jenjang = models.CharField(max_length=10, verbose_name='Jenjang Perekayasa', choices=PILIHAN_JENJANG, default=awal) user = models.ForeignKey('auth.User', verbose_name='Personil', on_delete=models.CASCADE) <|fim▁hole|> class Meta: verbose_name_plural = 'Profil' def __str__(self): return self.nip<|fim▁end|>
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models # Create your models here. class Profil(models.Model): <|fim_middle|> <|fim▁end|>
awal = '' PILIHAN_JENJANG = ( (awal, '----'), ('Pertama', 'Perekayasa Pertama'), ('Muda', 'Perekayasa Muda'), ('Madya', 'Perekayasa Madya'), ('Utama', 'Perekayasa Utama'), ) nip = models.CharField(max_length=50, verbose_name='NIP') pendidikan = models.CharField(max_length=150, verbose_name='Pendidikan') instansi = models.TextField(verbose_name='Nama Lengkap Unit') instansi_kode = models.CharField(max_length=20, verbose_name='Singkatan Unit') satuan = models.TextField(verbose_name='Nama Lengkap Satuan kerja', blank=True) kantor = models.TextField(verbose_name='Nama Lengkap Kantor', blank=True) pangkat = models.TextField(verbose_name='Pangkat/Golongan Ruang/TMT') jabatan = models.CharField(max_length=150, verbose_name='Jabatan') jenjang = models.CharField(max_length=10, verbose_name='Jenjang Perekayasa', choices=PILIHAN_JENJANG, default=awal) user = models.ForeignKey('auth.User', verbose_name='Personil', on_delete=models.CASCADE) class Meta: verbose_name_plural = 'Profil' def __str__(self): return self.nip
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models # Create your models here. class Profil(models.Model): awal = '' PILIHAN_JENJANG = ( (awal, '----'), ('Pertama', 'Perekayasa Pertama'), ('Muda', 'Perekayasa Muda'), ('Madya', 'Perekayasa Madya'), ('Utama', 'Perekayasa Utama'), ) nip = models.CharField(max_length=50, verbose_name='NIP') pendidikan = models.CharField(max_length=150, verbose_name='Pendidikan') instansi = models.TextField(verbose_name='Nama Lengkap Unit') instansi_kode = models.CharField(max_length=20, verbose_name='Singkatan Unit') satuan = models.TextField(verbose_name='Nama Lengkap Satuan kerja', blank=True) kantor = models.TextField(verbose_name='Nama Lengkap Kantor', blank=True) pangkat = models.TextField(verbose_name='Pangkat/Golongan Ruang/TMT') jabatan = models.CharField(max_length=150, verbose_name='Jabatan') jenjang = models.CharField(max_length=10, verbose_name='Jenjang Perekayasa', choices=PILIHAN_JENJANG, default=awal) user = models.ForeignKey('auth.User', verbose_name='Personil', on_delete=models.CASCADE) class Meta: <|fim_middle|> def __str__(self): return self.nip <|fim▁end|>
verbose_name_plural = 'Profil'
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models # Create your models here. class Profil(models.Model): awal = '' PILIHAN_JENJANG = ( (awal, '----'), ('Pertama', 'Perekayasa Pertama'), ('Muda', 'Perekayasa Muda'), ('Madya', 'Perekayasa Madya'), ('Utama', 'Perekayasa Utama'), ) nip = models.CharField(max_length=50, verbose_name='NIP') pendidikan = models.CharField(max_length=150, verbose_name='Pendidikan') instansi = models.TextField(verbose_name='Nama Lengkap Unit') instansi_kode = models.CharField(max_length=20, verbose_name='Singkatan Unit') satuan = models.TextField(verbose_name='Nama Lengkap Satuan kerja', blank=True) kantor = models.TextField(verbose_name='Nama Lengkap Kantor', blank=True) pangkat = models.TextField(verbose_name='Pangkat/Golongan Ruang/TMT') jabatan = models.CharField(max_length=150, verbose_name='Jabatan') jenjang = models.CharField(max_length=10, verbose_name='Jenjang Perekayasa', choices=PILIHAN_JENJANG, default=awal) user = models.ForeignKey('auth.User', verbose_name='Personil', on_delete=models.CASCADE) class Meta: verbose_name_plural = 'Profil' def __str__(self): <|fim_middle|> <|fim▁end|>
return self.nip
<|file_name|>models.py<|end_file_name|><|fim▁begin|>from django.db import models # Create your models here. class Profil(models.Model): awal = '' PILIHAN_JENJANG = ( (awal, '----'), ('Pertama', 'Perekayasa Pertama'), ('Muda', 'Perekayasa Muda'), ('Madya', 'Perekayasa Madya'), ('Utama', 'Perekayasa Utama'), ) nip = models.CharField(max_length=50, verbose_name='NIP') pendidikan = models.CharField(max_length=150, verbose_name='Pendidikan') instansi = models.TextField(verbose_name='Nama Lengkap Unit') instansi_kode = models.CharField(max_length=20, verbose_name='Singkatan Unit') satuan = models.TextField(verbose_name='Nama Lengkap Satuan kerja', blank=True) kantor = models.TextField(verbose_name='Nama Lengkap Kantor', blank=True) pangkat = models.TextField(verbose_name='Pangkat/Golongan Ruang/TMT') jabatan = models.CharField(max_length=150, verbose_name='Jabatan') jenjang = models.CharField(max_length=10, verbose_name='Jenjang Perekayasa', choices=PILIHAN_JENJANG, default=awal) user = models.ForeignKey('auth.User', verbose_name='Personil', on_delete=models.CASCADE) class Meta: verbose_name_plural = 'Profil' def <|fim_middle|>(self): return self.nip <|fim▁end|>
__str__
<|file_name|>tight_bbox.py<|end_file_name|><|fim▁begin|>""" This module is to support *bbox_inches* option in savefig command. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six import warnings from matplotlib.transforms import Bbox, TransformedBbox, Affine2D def adjust_bbox(fig, bbox_inches, fixed_dpi=None): """ Temporarily adjust the figure so that only the specified area (bbox_inches) is saved. It modifies fig.bbox, fig.bbox_inches, fig.transFigure._boxout, and fig.patch. While the figure size changes, the scale of the original figure is conserved. A function which restores the original values are returned. """ origBbox = fig.bbox origBboxInches = fig.bbox_inches _boxout = fig.transFigure._boxout asp_list = [] locator_list = [] for ax in fig.axes: pos = ax.get_position(original=False).frozen() locator_list.append(ax.get_axes_locator()) asp_list.append(ax.get_aspect()) def _l(a, r, pos=pos): return pos ax.set_axes_locator(_l) ax.set_aspect("auto") def restore_bbox(): for ax, asp, loc in zip(fig.axes, asp_list, locator_list): ax.set_aspect(asp) ax.set_axes_locator(loc) fig.bbox = origBbox fig.bbox_inches = origBboxInches<|fim▁hole|> fig.patch.set_bounds(0, 0, 1, 1) if fixed_dpi is not None: tr = Affine2D().scale(fixed_dpi) dpi_scale = fixed_dpi / fig.dpi else: tr = Affine2D().scale(fig.dpi) dpi_scale = 1. _bbox = TransformedBbox(bbox_inches, tr) fig.bbox_inches = Bbox.from_bounds(0, 0, bbox_inches.width, bbox_inches.height) x0, y0 = _bbox.x0, _bbox.y0 w1, h1 = fig.bbox.width * dpi_scale, fig.bbox.height * dpi_scale fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0, w1, h1) fig.transFigure.invalidate() fig.bbox = TransformedBbox(fig.bbox_inches, tr) fig.patch.set_bounds(x0 / w1, y0 / h1, fig.bbox.width / w1, fig.bbox.height / h1) return restore_bbox def process_figure_for_rasterizing(fig, bbox_inches_restore, fixed_dpi=None): """ This need to be called when figure dpi changes during the drawing (e.g., rasterizing). It recovers the bbox and re-adjust it with the new dpi. """ bbox_inches, restore_bbox = bbox_inches_restore restore_bbox() r = adjust_bbox(figure, bbox_inches, fixed_dpi) return bbox_inches, r<|fim▁end|>
fig.transFigure._boxout = _boxout fig.transFigure.invalidate()
<|file_name|>tight_bbox.py<|end_file_name|><|fim▁begin|>""" This module is to support *bbox_inches* option in savefig command. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six import warnings from matplotlib.transforms import Bbox, TransformedBbox, Affine2D def adjust_bbox(fig, bbox_inches, fixed_dpi=None): <|fim_middle|> def process_figure_for_rasterizing(fig, bbox_inches_restore, fixed_dpi=None): """ This need to be called when figure dpi changes during the drawing (e.g., rasterizing). It recovers the bbox and re-adjust it with the new dpi. """ bbox_inches, restore_bbox = bbox_inches_restore restore_bbox() r = adjust_bbox(figure, bbox_inches, fixed_dpi) return bbox_inches, r <|fim▁end|>
""" Temporarily adjust the figure so that only the specified area (bbox_inches) is saved. It modifies fig.bbox, fig.bbox_inches, fig.transFigure._boxout, and fig.patch. While the figure size changes, the scale of the original figure is conserved. A function which restores the original values are returned. """ origBbox = fig.bbox origBboxInches = fig.bbox_inches _boxout = fig.transFigure._boxout asp_list = [] locator_list = [] for ax in fig.axes: pos = ax.get_position(original=False).frozen() locator_list.append(ax.get_axes_locator()) asp_list.append(ax.get_aspect()) def _l(a, r, pos=pos): return pos ax.set_axes_locator(_l) ax.set_aspect("auto") def restore_bbox(): for ax, asp, loc in zip(fig.axes, asp_list, locator_list): ax.set_aspect(asp) ax.set_axes_locator(loc) fig.bbox = origBbox fig.bbox_inches = origBboxInches fig.transFigure._boxout = _boxout fig.transFigure.invalidate() fig.patch.set_bounds(0, 0, 1, 1) if fixed_dpi is not None: tr = Affine2D().scale(fixed_dpi) dpi_scale = fixed_dpi / fig.dpi else: tr = Affine2D().scale(fig.dpi) dpi_scale = 1. _bbox = TransformedBbox(bbox_inches, tr) fig.bbox_inches = Bbox.from_bounds(0, 0, bbox_inches.width, bbox_inches.height) x0, y0 = _bbox.x0, _bbox.y0 w1, h1 = fig.bbox.width * dpi_scale, fig.bbox.height * dpi_scale fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0, w1, h1) fig.transFigure.invalidate() fig.bbox = TransformedBbox(fig.bbox_inches, tr) fig.patch.set_bounds(x0 / w1, y0 / h1, fig.bbox.width / w1, fig.bbox.height / h1) return restore_bbox
<|file_name|>tight_bbox.py<|end_file_name|><|fim▁begin|>""" This module is to support *bbox_inches* option in savefig command. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six import warnings from matplotlib.transforms import Bbox, TransformedBbox, Affine2D def adjust_bbox(fig, bbox_inches, fixed_dpi=None): """ Temporarily adjust the figure so that only the specified area (bbox_inches) is saved. It modifies fig.bbox, fig.bbox_inches, fig.transFigure._boxout, and fig.patch. While the figure size changes, the scale of the original figure is conserved. A function which restores the original values are returned. """ origBbox = fig.bbox origBboxInches = fig.bbox_inches _boxout = fig.transFigure._boxout asp_list = [] locator_list = [] for ax in fig.axes: pos = ax.get_position(original=False).frozen() locator_list.append(ax.get_axes_locator()) asp_list.append(ax.get_aspect()) def _l(a, r, pos=pos): <|fim_middle|> ax.set_axes_locator(_l) ax.set_aspect("auto") def restore_bbox(): for ax, asp, loc in zip(fig.axes, asp_list, locator_list): ax.set_aspect(asp) ax.set_axes_locator(loc) fig.bbox = origBbox fig.bbox_inches = origBboxInches fig.transFigure._boxout = _boxout fig.transFigure.invalidate() fig.patch.set_bounds(0, 0, 1, 1) if fixed_dpi is not None: tr = Affine2D().scale(fixed_dpi) dpi_scale = fixed_dpi / fig.dpi else: tr = Affine2D().scale(fig.dpi) dpi_scale = 1. _bbox = TransformedBbox(bbox_inches, tr) fig.bbox_inches = Bbox.from_bounds(0, 0, bbox_inches.width, bbox_inches.height) x0, y0 = _bbox.x0, _bbox.y0 w1, h1 = fig.bbox.width * dpi_scale, fig.bbox.height * dpi_scale fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0, w1, h1) fig.transFigure.invalidate() fig.bbox = TransformedBbox(fig.bbox_inches, tr) fig.patch.set_bounds(x0 / w1, y0 / h1, fig.bbox.width / w1, fig.bbox.height / h1) return restore_bbox def process_figure_for_rasterizing(fig, bbox_inches_restore, fixed_dpi=None): """ This need to be called when figure dpi changes during the drawing (e.g., rasterizing). It recovers the bbox and re-adjust it with the new dpi. """ bbox_inches, restore_bbox = bbox_inches_restore restore_bbox() r = adjust_bbox(figure, bbox_inches, fixed_dpi) return bbox_inches, r <|fim▁end|>
return pos
<|file_name|>tight_bbox.py<|end_file_name|><|fim▁begin|>""" This module is to support *bbox_inches* option in savefig command. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six import warnings from matplotlib.transforms import Bbox, TransformedBbox, Affine2D def adjust_bbox(fig, bbox_inches, fixed_dpi=None): """ Temporarily adjust the figure so that only the specified area (bbox_inches) is saved. It modifies fig.bbox, fig.bbox_inches, fig.transFigure._boxout, and fig.patch. While the figure size changes, the scale of the original figure is conserved. A function which restores the original values are returned. """ origBbox = fig.bbox origBboxInches = fig.bbox_inches _boxout = fig.transFigure._boxout asp_list = [] locator_list = [] for ax in fig.axes: pos = ax.get_position(original=False).frozen() locator_list.append(ax.get_axes_locator()) asp_list.append(ax.get_aspect()) def _l(a, r, pos=pos): return pos ax.set_axes_locator(_l) ax.set_aspect("auto") def restore_bbox(): <|fim_middle|> if fixed_dpi is not None: tr = Affine2D().scale(fixed_dpi) dpi_scale = fixed_dpi / fig.dpi else: tr = Affine2D().scale(fig.dpi) dpi_scale = 1. _bbox = TransformedBbox(bbox_inches, tr) fig.bbox_inches = Bbox.from_bounds(0, 0, bbox_inches.width, bbox_inches.height) x0, y0 = _bbox.x0, _bbox.y0 w1, h1 = fig.bbox.width * dpi_scale, fig.bbox.height * dpi_scale fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0, w1, h1) fig.transFigure.invalidate() fig.bbox = TransformedBbox(fig.bbox_inches, tr) fig.patch.set_bounds(x0 / w1, y0 / h1, fig.bbox.width / w1, fig.bbox.height / h1) return restore_bbox def process_figure_for_rasterizing(fig, bbox_inches_restore, fixed_dpi=None): """ This need to be called when figure dpi changes during the drawing (e.g., rasterizing). It recovers the bbox and re-adjust it with the new dpi. """ bbox_inches, restore_bbox = bbox_inches_restore restore_bbox() r = adjust_bbox(figure, bbox_inches, fixed_dpi) return bbox_inches, r <|fim▁end|>
for ax, asp, loc in zip(fig.axes, asp_list, locator_list): ax.set_aspect(asp) ax.set_axes_locator(loc) fig.bbox = origBbox fig.bbox_inches = origBboxInches fig.transFigure._boxout = _boxout fig.transFigure.invalidate() fig.patch.set_bounds(0, 0, 1, 1)
<|file_name|>tight_bbox.py<|end_file_name|><|fim▁begin|>""" This module is to support *bbox_inches* option in savefig command. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six import warnings from matplotlib.transforms import Bbox, TransformedBbox, Affine2D def adjust_bbox(fig, bbox_inches, fixed_dpi=None): """ Temporarily adjust the figure so that only the specified area (bbox_inches) is saved. It modifies fig.bbox, fig.bbox_inches, fig.transFigure._boxout, and fig.patch. While the figure size changes, the scale of the original figure is conserved. A function which restores the original values are returned. """ origBbox = fig.bbox origBboxInches = fig.bbox_inches _boxout = fig.transFigure._boxout asp_list = [] locator_list = [] for ax in fig.axes: pos = ax.get_position(original=False).frozen() locator_list.append(ax.get_axes_locator()) asp_list.append(ax.get_aspect()) def _l(a, r, pos=pos): return pos ax.set_axes_locator(_l) ax.set_aspect("auto") def restore_bbox(): for ax, asp, loc in zip(fig.axes, asp_list, locator_list): ax.set_aspect(asp) ax.set_axes_locator(loc) fig.bbox = origBbox fig.bbox_inches = origBboxInches fig.transFigure._boxout = _boxout fig.transFigure.invalidate() fig.patch.set_bounds(0, 0, 1, 1) if fixed_dpi is not None: tr = Affine2D().scale(fixed_dpi) dpi_scale = fixed_dpi / fig.dpi else: tr = Affine2D().scale(fig.dpi) dpi_scale = 1. _bbox = TransformedBbox(bbox_inches, tr) fig.bbox_inches = Bbox.from_bounds(0, 0, bbox_inches.width, bbox_inches.height) x0, y0 = _bbox.x0, _bbox.y0 w1, h1 = fig.bbox.width * dpi_scale, fig.bbox.height * dpi_scale fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0, w1, h1) fig.transFigure.invalidate() fig.bbox = TransformedBbox(fig.bbox_inches, tr) fig.patch.set_bounds(x0 / w1, y0 / h1, fig.bbox.width / w1, fig.bbox.height / h1) return restore_bbox def process_figure_for_rasterizing(fig, bbox_inches_restore, fixed_dpi=None): <|fim_middle|> <|fim▁end|>
""" This need to be called when figure dpi changes during the drawing (e.g., rasterizing). It recovers the bbox and re-adjust it with the new dpi. """ bbox_inches, restore_bbox = bbox_inches_restore restore_bbox() r = adjust_bbox(figure, bbox_inches, fixed_dpi) return bbox_inches, r
<|file_name|>tight_bbox.py<|end_file_name|><|fim▁begin|>""" This module is to support *bbox_inches* option in savefig command. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six import warnings from matplotlib.transforms import Bbox, TransformedBbox, Affine2D def adjust_bbox(fig, bbox_inches, fixed_dpi=None): """ Temporarily adjust the figure so that only the specified area (bbox_inches) is saved. It modifies fig.bbox, fig.bbox_inches, fig.transFigure._boxout, and fig.patch. While the figure size changes, the scale of the original figure is conserved. A function which restores the original values are returned. """ origBbox = fig.bbox origBboxInches = fig.bbox_inches _boxout = fig.transFigure._boxout asp_list = [] locator_list = [] for ax in fig.axes: pos = ax.get_position(original=False).frozen() locator_list.append(ax.get_axes_locator()) asp_list.append(ax.get_aspect()) def _l(a, r, pos=pos): return pos ax.set_axes_locator(_l) ax.set_aspect("auto") def restore_bbox(): for ax, asp, loc in zip(fig.axes, asp_list, locator_list): ax.set_aspect(asp) ax.set_axes_locator(loc) fig.bbox = origBbox fig.bbox_inches = origBboxInches fig.transFigure._boxout = _boxout fig.transFigure.invalidate() fig.patch.set_bounds(0, 0, 1, 1) if fixed_dpi is not None: <|fim_middle|> else: tr = Affine2D().scale(fig.dpi) dpi_scale = 1. _bbox = TransformedBbox(bbox_inches, tr) fig.bbox_inches = Bbox.from_bounds(0, 0, bbox_inches.width, bbox_inches.height) x0, y0 = _bbox.x0, _bbox.y0 w1, h1 = fig.bbox.width * dpi_scale, fig.bbox.height * dpi_scale fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0, w1, h1) fig.transFigure.invalidate() fig.bbox = TransformedBbox(fig.bbox_inches, tr) fig.patch.set_bounds(x0 / w1, y0 / h1, fig.bbox.width / w1, fig.bbox.height / h1) return restore_bbox def process_figure_for_rasterizing(fig, bbox_inches_restore, fixed_dpi=None): """ This need to be called when figure dpi changes during the drawing (e.g., rasterizing). It recovers the bbox and re-adjust it with the new dpi. """ bbox_inches, restore_bbox = bbox_inches_restore restore_bbox() r = adjust_bbox(figure, bbox_inches, fixed_dpi) return bbox_inches, r <|fim▁end|>
tr = Affine2D().scale(fixed_dpi) dpi_scale = fixed_dpi / fig.dpi
<|file_name|>tight_bbox.py<|end_file_name|><|fim▁begin|>""" This module is to support *bbox_inches* option in savefig command. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six import warnings from matplotlib.transforms import Bbox, TransformedBbox, Affine2D def adjust_bbox(fig, bbox_inches, fixed_dpi=None): """ Temporarily adjust the figure so that only the specified area (bbox_inches) is saved. It modifies fig.bbox, fig.bbox_inches, fig.transFigure._boxout, and fig.patch. While the figure size changes, the scale of the original figure is conserved. A function which restores the original values are returned. """ origBbox = fig.bbox origBboxInches = fig.bbox_inches _boxout = fig.transFigure._boxout asp_list = [] locator_list = [] for ax in fig.axes: pos = ax.get_position(original=False).frozen() locator_list.append(ax.get_axes_locator()) asp_list.append(ax.get_aspect()) def _l(a, r, pos=pos): return pos ax.set_axes_locator(_l) ax.set_aspect("auto") def restore_bbox(): for ax, asp, loc in zip(fig.axes, asp_list, locator_list): ax.set_aspect(asp) ax.set_axes_locator(loc) fig.bbox = origBbox fig.bbox_inches = origBboxInches fig.transFigure._boxout = _boxout fig.transFigure.invalidate() fig.patch.set_bounds(0, 0, 1, 1) if fixed_dpi is not None: tr = Affine2D().scale(fixed_dpi) dpi_scale = fixed_dpi / fig.dpi else: <|fim_middle|> _bbox = TransformedBbox(bbox_inches, tr) fig.bbox_inches = Bbox.from_bounds(0, 0, bbox_inches.width, bbox_inches.height) x0, y0 = _bbox.x0, _bbox.y0 w1, h1 = fig.bbox.width * dpi_scale, fig.bbox.height * dpi_scale fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0, w1, h1) fig.transFigure.invalidate() fig.bbox = TransformedBbox(fig.bbox_inches, tr) fig.patch.set_bounds(x0 / w1, y0 / h1, fig.bbox.width / w1, fig.bbox.height / h1) return restore_bbox def process_figure_for_rasterizing(fig, bbox_inches_restore, fixed_dpi=None): """ This need to be called when figure dpi changes during the drawing (e.g., rasterizing). It recovers the bbox and re-adjust it with the new dpi. """ bbox_inches, restore_bbox = bbox_inches_restore restore_bbox() r = adjust_bbox(figure, bbox_inches, fixed_dpi) return bbox_inches, r <|fim▁end|>
tr = Affine2D().scale(fig.dpi) dpi_scale = 1.
<|file_name|>tight_bbox.py<|end_file_name|><|fim▁begin|>""" This module is to support *bbox_inches* option in savefig command. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six import warnings from matplotlib.transforms import Bbox, TransformedBbox, Affine2D def <|fim_middle|>(fig, bbox_inches, fixed_dpi=None): """ Temporarily adjust the figure so that only the specified area (bbox_inches) is saved. It modifies fig.bbox, fig.bbox_inches, fig.transFigure._boxout, and fig.patch. While the figure size changes, the scale of the original figure is conserved. A function which restores the original values are returned. """ origBbox = fig.bbox origBboxInches = fig.bbox_inches _boxout = fig.transFigure._boxout asp_list = [] locator_list = [] for ax in fig.axes: pos = ax.get_position(original=False).frozen() locator_list.append(ax.get_axes_locator()) asp_list.append(ax.get_aspect()) def _l(a, r, pos=pos): return pos ax.set_axes_locator(_l) ax.set_aspect("auto") def restore_bbox(): for ax, asp, loc in zip(fig.axes, asp_list, locator_list): ax.set_aspect(asp) ax.set_axes_locator(loc) fig.bbox = origBbox fig.bbox_inches = origBboxInches fig.transFigure._boxout = _boxout fig.transFigure.invalidate() fig.patch.set_bounds(0, 0, 1, 1) if fixed_dpi is not None: tr = Affine2D().scale(fixed_dpi) dpi_scale = fixed_dpi / fig.dpi else: tr = Affine2D().scale(fig.dpi) dpi_scale = 1. _bbox = TransformedBbox(bbox_inches, tr) fig.bbox_inches = Bbox.from_bounds(0, 0, bbox_inches.width, bbox_inches.height) x0, y0 = _bbox.x0, _bbox.y0 w1, h1 = fig.bbox.width * dpi_scale, fig.bbox.height * dpi_scale fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0, w1, h1) fig.transFigure.invalidate() fig.bbox = TransformedBbox(fig.bbox_inches, tr) fig.patch.set_bounds(x0 / w1, y0 / h1, fig.bbox.width / w1, fig.bbox.height / h1) return restore_bbox def process_figure_for_rasterizing(fig, bbox_inches_restore, fixed_dpi=None): """ This need to be called when figure dpi changes during the drawing (e.g., rasterizing). It recovers the bbox and re-adjust it with the new dpi. """ bbox_inches, restore_bbox = bbox_inches_restore restore_bbox() r = adjust_bbox(figure, bbox_inches, fixed_dpi) return bbox_inches, r <|fim▁end|>
adjust_bbox
<|file_name|>tight_bbox.py<|end_file_name|><|fim▁begin|>""" This module is to support *bbox_inches* option in savefig command. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six import warnings from matplotlib.transforms import Bbox, TransformedBbox, Affine2D def adjust_bbox(fig, bbox_inches, fixed_dpi=None): """ Temporarily adjust the figure so that only the specified area (bbox_inches) is saved. It modifies fig.bbox, fig.bbox_inches, fig.transFigure._boxout, and fig.patch. While the figure size changes, the scale of the original figure is conserved. A function which restores the original values are returned. """ origBbox = fig.bbox origBboxInches = fig.bbox_inches _boxout = fig.transFigure._boxout asp_list = [] locator_list = [] for ax in fig.axes: pos = ax.get_position(original=False).frozen() locator_list.append(ax.get_axes_locator()) asp_list.append(ax.get_aspect()) def <|fim_middle|>(a, r, pos=pos): return pos ax.set_axes_locator(_l) ax.set_aspect("auto") def restore_bbox(): for ax, asp, loc in zip(fig.axes, asp_list, locator_list): ax.set_aspect(asp) ax.set_axes_locator(loc) fig.bbox = origBbox fig.bbox_inches = origBboxInches fig.transFigure._boxout = _boxout fig.transFigure.invalidate() fig.patch.set_bounds(0, 0, 1, 1) if fixed_dpi is not None: tr = Affine2D().scale(fixed_dpi) dpi_scale = fixed_dpi / fig.dpi else: tr = Affine2D().scale(fig.dpi) dpi_scale = 1. _bbox = TransformedBbox(bbox_inches, tr) fig.bbox_inches = Bbox.from_bounds(0, 0, bbox_inches.width, bbox_inches.height) x0, y0 = _bbox.x0, _bbox.y0 w1, h1 = fig.bbox.width * dpi_scale, fig.bbox.height * dpi_scale fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0, w1, h1) fig.transFigure.invalidate() fig.bbox = TransformedBbox(fig.bbox_inches, tr) fig.patch.set_bounds(x0 / w1, y0 / h1, fig.bbox.width / w1, fig.bbox.height / h1) return restore_bbox def process_figure_for_rasterizing(fig, bbox_inches_restore, fixed_dpi=None): """ This need to be called when figure dpi changes during the drawing (e.g., rasterizing). It recovers the bbox and re-adjust it with the new dpi. """ bbox_inches, restore_bbox = bbox_inches_restore restore_bbox() r = adjust_bbox(figure, bbox_inches, fixed_dpi) return bbox_inches, r <|fim▁end|>
_l
<|file_name|>tight_bbox.py<|end_file_name|><|fim▁begin|>""" This module is to support *bbox_inches* option in savefig command. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six import warnings from matplotlib.transforms import Bbox, TransformedBbox, Affine2D def adjust_bbox(fig, bbox_inches, fixed_dpi=None): """ Temporarily adjust the figure so that only the specified area (bbox_inches) is saved. It modifies fig.bbox, fig.bbox_inches, fig.transFigure._boxout, and fig.patch. While the figure size changes, the scale of the original figure is conserved. A function which restores the original values are returned. """ origBbox = fig.bbox origBboxInches = fig.bbox_inches _boxout = fig.transFigure._boxout asp_list = [] locator_list = [] for ax in fig.axes: pos = ax.get_position(original=False).frozen() locator_list.append(ax.get_axes_locator()) asp_list.append(ax.get_aspect()) def _l(a, r, pos=pos): return pos ax.set_axes_locator(_l) ax.set_aspect("auto") def <|fim_middle|>(): for ax, asp, loc in zip(fig.axes, asp_list, locator_list): ax.set_aspect(asp) ax.set_axes_locator(loc) fig.bbox = origBbox fig.bbox_inches = origBboxInches fig.transFigure._boxout = _boxout fig.transFigure.invalidate() fig.patch.set_bounds(0, 0, 1, 1) if fixed_dpi is not None: tr = Affine2D().scale(fixed_dpi) dpi_scale = fixed_dpi / fig.dpi else: tr = Affine2D().scale(fig.dpi) dpi_scale = 1. _bbox = TransformedBbox(bbox_inches, tr) fig.bbox_inches = Bbox.from_bounds(0, 0, bbox_inches.width, bbox_inches.height) x0, y0 = _bbox.x0, _bbox.y0 w1, h1 = fig.bbox.width * dpi_scale, fig.bbox.height * dpi_scale fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0, w1, h1) fig.transFigure.invalidate() fig.bbox = TransformedBbox(fig.bbox_inches, tr) fig.patch.set_bounds(x0 / w1, y0 / h1, fig.bbox.width / w1, fig.bbox.height / h1) return restore_bbox def process_figure_for_rasterizing(fig, bbox_inches_restore, fixed_dpi=None): """ This need to be called when figure dpi changes during the drawing (e.g., rasterizing). It recovers the bbox and re-adjust it with the new dpi. """ bbox_inches, restore_bbox = bbox_inches_restore restore_bbox() r = adjust_bbox(figure, bbox_inches, fixed_dpi) return bbox_inches, r <|fim▁end|>
restore_bbox
<|file_name|>tight_bbox.py<|end_file_name|><|fim▁begin|>""" This module is to support *bbox_inches* option in savefig command. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import six import warnings from matplotlib.transforms import Bbox, TransformedBbox, Affine2D def adjust_bbox(fig, bbox_inches, fixed_dpi=None): """ Temporarily adjust the figure so that only the specified area (bbox_inches) is saved. It modifies fig.bbox, fig.bbox_inches, fig.transFigure._boxout, and fig.patch. While the figure size changes, the scale of the original figure is conserved. A function which restores the original values are returned. """ origBbox = fig.bbox origBboxInches = fig.bbox_inches _boxout = fig.transFigure._boxout asp_list = [] locator_list = [] for ax in fig.axes: pos = ax.get_position(original=False).frozen() locator_list.append(ax.get_axes_locator()) asp_list.append(ax.get_aspect()) def _l(a, r, pos=pos): return pos ax.set_axes_locator(_l) ax.set_aspect("auto") def restore_bbox(): for ax, asp, loc in zip(fig.axes, asp_list, locator_list): ax.set_aspect(asp) ax.set_axes_locator(loc) fig.bbox = origBbox fig.bbox_inches = origBboxInches fig.transFigure._boxout = _boxout fig.transFigure.invalidate() fig.patch.set_bounds(0, 0, 1, 1) if fixed_dpi is not None: tr = Affine2D().scale(fixed_dpi) dpi_scale = fixed_dpi / fig.dpi else: tr = Affine2D().scale(fig.dpi) dpi_scale = 1. _bbox = TransformedBbox(bbox_inches, tr) fig.bbox_inches = Bbox.from_bounds(0, 0, bbox_inches.width, bbox_inches.height) x0, y0 = _bbox.x0, _bbox.y0 w1, h1 = fig.bbox.width * dpi_scale, fig.bbox.height * dpi_scale fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0, w1, h1) fig.transFigure.invalidate() fig.bbox = TransformedBbox(fig.bbox_inches, tr) fig.patch.set_bounds(x0 / w1, y0 / h1, fig.bbox.width / w1, fig.bbox.height / h1) return restore_bbox def <|fim_middle|>(fig, bbox_inches_restore, fixed_dpi=None): """ This need to be called when figure dpi changes during the drawing (e.g., rasterizing). It recovers the bbox and re-adjust it with the new dpi. """ bbox_inches, restore_bbox = bbox_inches_restore restore_bbox() r = adjust_bbox(figure, bbox_inches, fixed_dpi) return bbox_inches, r <|fim▁end|>
process_figure_for_rasterizing
<|file_name|>implicitgrant.py<|end_file_name|><|fim▁begin|>#-*- coding: utf-8 -*- from .grant import Grant from ..endpoint import AuthorizationEndpoint class ImplicitGrant(Grant): """ The implicit grant type is used to obtain access tokens (it does not support the issuance of refresh tokens) and is optimized for public clients known to operate a particular redirection URI. These clients are typically implemented in a browser using a scripting language such as JavaScript. +----------+ | Resource | | Owner | | | +----------+ ^ | (B) +----|-----+ Client Identifier +---------------+ | -+----(A)-- & Redirection URI --->| | | User- | | Authorization | | Agent -|----(B)-- User authenticates -->| Server | | | | | | |<---(C)--- Redirection URI ----<| | | | with Access Token +---------------+ | | in Fragment | | +---------------+ | |----(D)--- Redirection URI ---->| Web-Hosted | | | without Fragment | Client | | | | Resource | | (F) |<---(E)------- Script ---------<| | | | +---------------+ +-|--------+ | | (A) (G) Access Token | | ^ v +---------+ | | | Client | | | +---------+<|fim▁hole|> Figure 4: Implicit Grant Flow """ def get_redirection_uri(self, expires_in): self._authorization_endpoint = AuthorizationEndpoint(self._server, self._request, self._client) return self._authorization_endpoint.implicit(expires_in)<|fim▁end|>
Note: The lines illustrating steps (A) and (B) are broken into two parts as they pass through the user-agent.
<|file_name|>implicitgrant.py<|end_file_name|><|fim▁begin|>#-*- coding: utf-8 -*- from .grant import Grant from ..endpoint import AuthorizationEndpoint class ImplicitGrant(Grant): <|fim_middle|> <|fim▁end|>
""" The implicit grant type is used to obtain access tokens (it does not support the issuance of refresh tokens) and is optimized for public clients known to operate a particular redirection URI. These clients are typically implemented in a browser using a scripting language such as JavaScript. +----------+ | Resource | | Owner | | | +----------+ ^ | (B) +----|-----+ Client Identifier +---------------+ | -+----(A)-- & Redirection URI --->| | | User- | | Authorization | | Agent -|----(B)-- User authenticates -->| Server | | | | | | |<---(C)--- Redirection URI ----<| | | | with Access Token +---------------+ | | in Fragment | | +---------------+ | |----(D)--- Redirection URI ---->| Web-Hosted | | | without Fragment | Client | | | | Resource | | (F) |<---(E)------- Script ---------<| | | | +---------------+ +-|--------+ | | (A) (G) Access Token | | ^ v +---------+ | | | Client | | | +---------+ Note: The lines illustrating steps (A) and (B) are broken into two parts as they pass through the user-agent. Figure 4: Implicit Grant Flow """ def get_redirection_uri(self, expires_in): self._authorization_endpoint = AuthorizationEndpoint(self._server, self._request, self._client) return self._authorization_endpoint.implicit(expires_in)
<|file_name|>implicitgrant.py<|end_file_name|><|fim▁begin|>#-*- coding: utf-8 -*- from .grant import Grant from ..endpoint import AuthorizationEndpoint class ImplicitGrant(Grant): """ The implicit grant type is used to obtain access tokens (it does not support the issuance of refresh tokens) and is optimized for public clients known to operate a particular redirection URI. These clients are typically implemented in a browser using a scripting language such as JavaScript. +----------+ | Resource | | Owner | | | +----------+ ^ | (B) +----|-----+ Client Identifier +---------------+ | -+----(A)-- & Redirection URI --->| | | User- | | Authorization | | Agent -|----(B)-- User authenticates -->| Server | | | | | | |<---(C)--- Redirection URI ----<| | | | with Access Token +---------------+ | | in Fragment | | +---------------+ | |----(D)--- Redirection URI ---->| Web-Hosted | | | without Fragment | Client | | | | Resource | | (F) |<---(E)------- Script ---------<| | | | +---------------+ +-|--------+ | | (A) (G) Access Token | | ^ v +---------+ | | | Client | | | +---------+ Note: The lines illustrating steps (A) and (B) are broken into two parts as they pass through the user-agent. Figure 4: Implicit Grant Flow """ def get_redirection_uri(self, expires_in): <|fim_middle|> <|fim▁end|>
self._authorization_endpoint = AuthorizationEndpoint(self._server, self._request, self._client) return self._authorization_endpoint.implicit(expires_in)
<|file_name|>implicitgrant.py<|end_file_name|><|fim▁begin|>#-*- coding: utf-8 -*- from .grant import Grant from ..endpoint import AuthorizationEndpoint class ImplicitGrant(Grant): """ The implicit grant type is used to obtain access tokens (it does not support the issuance of refresh tokens) and is optimized for public clients known to operate a particular redirection URI. These clients are typically implemented in a browser using a scripting language such as JavaScript. +----------+ | Resource | | Owner | | | +----------+ ^ | (B) +----|-----+ Client Identifier +---------------+ | -+----(A)-- & Redirection URI --->| | | User- | | Authorization | | Agent -|----(B)-- User authenticates -->| Server | | | | | | |<---(C)--- Redirection URI ----<| | | | with Access Token +---------------+ | | in Fragment | | +---------------+ | |----(D)--- Redirection URI ---->| Web-Hosted | | | without Fragment | Client | | | | Resource | | (F) |<---(E)------- Script ---------<| | | | +---------------+ +-|--------+ | | (A) (G) Access Token | | ^ v +---------+ | | | Client | | | +---------+ Note: The lines illustrating steps (A) and (B) are broken into two parts as they pass through the user-agent. Figure 4: Implicit Grant Flow """ def <|fim_middle|>(self, expires_in): self._authorization_endpoint = AuthorizationEndpoint(self._server, self._request, self._client) return self._authorization_endpoint.implicit(expires_in) <|fim▁end|>
get_redirection_uri
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>VERSION = (1, 0, 0,) __version__ = '.'.join(map(str, VERSION)) default_app_config = 'admin_sso.apps.AdminSSOConfig' # Do not use Django settings at module level as recommended try: from django.utils.functional import LazyObject except ImportError:<|fim▁hole|>else: class LazySettings(LazyObject): def _setup(self): from admin_sso import default_settings self._wrapped = Settings(default_settings) class Settings(object): def __init__(self, settings_module): for setting in dir(settings_module): if setting == setting.upper(): setattr(self, setting, getattr(settings_module, setting)) settings = LazySettings()<|fim▁end|>
pass
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>VERSION = (1, 0, 0,) __version__ = '.'.join(map(str, VERSION)) default_app_config = 'admin_sso.apps.AdminSSOConfig' # Do not use Django settings at module level as recommended try: from django.utils.functional import LazyObject except ImportError: pass else: class LazySettings(LazyObject): <|fim_middle|> class Settings(object): def __init__(self, settings_module): for setting in dir(settings_module): if setting == setting.upper(): setattr(self, setting, getattr(settings_module, setting)) settings = LazySettings() <|fim▁end|>
def _setup(self): from admin_sso import default_settings self._wrapped = Settings(default_settings)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>VERSION = (1, 0, 0,) __version__ = '.'.join(map(str, VERSION)) default_app_config = 'admin_sso.apps.AdminSSOConfig' # Do not use Django settings at module level as recommended try: from django.utils.functional import LazyObject except ImportError: pass else: class LazySettings(LazyObject): def _setup(self): <|fim_middle|> class Settings(object): def __init__(self, settings_module): for setting in dir(settings_module): if setting == setting.upper(): setattr(self, setting, getattr(settings_module, setting)) settings = LazySettings() <|fim▁end|>
from admin_sso import default_settings self._wrapped = Settings(default_settings)
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>VERSION = (1, 0, 0,) __version__ = '.'.join(map(str, VERSION)) default_app_config = 'admin_sso.apps.AdminSSOConfig' # Do not use Django settings at module level as recommended try: from django.utils.functional import LazyObject except ImportError: pass else: class LazySettings(LazyObject): def _setup(self): from admin_sso import default_settings self._wrapped = Settings(default_settings) class Settings(object): <|fim_middle|> settings = LazySettings() <|fim▁end|>
def __init__(self, settings_module): for setting in dir(settings_module): if setting == setting.upper(): setattr(self, setting, getattr(settings_module, setting))
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>VERSION = (1, 0, 0,) __version__ = '.'.join(map(str, VERSION)) default_app_config = 'admin_sso.apps.AdminSSOConfig' # Do not use Django settings at module level as recommended try: from django.utils.functional import LazyObject except ImportError: pass else: class LazySettings(LazyObject): def _setup(self): from admin_sso import default_settings self._wrapped = Settings(default_settings) class Settings(object): def __init__(self, settings_module): <|fim_middle|> settings = LazySettings() <|fim▁end|>
for setting in dir(settings_module): if setting == setting.upper(): setattr(self, setting, getattr(settings_module, setting))
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>VERSION = (1, 0, 0,) __version__ = '.'.join(map(str, VERSION)) default_app_config = 'admin_sso.apps.AdminSSOConfig' # Do not use Django settings at module level as recommended try: from django.utils.functional import LazyObject except ImportError: pass else: <|fim_middle|> <|fim▁end|>
class LazySettings(LazyObject): def _setup(self): from admin_sso import default_settings self._wrapped = Settings(default_settings) class Settings(object): def __init__(self, settings_module): for setting in dir(settings_module): if setting == setting.upper(): setattr(self, setting, getattr(settings_module, setting)) settings = LazySettings()
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>VERSION = (1, 0, 0,) __version__ = '.'.join(map(str, VERSION)) default_app_config = 'admin_sso.apps.AdminSSOConfig' # Do not use Django settings at module level as recommended try: from django.utils.functional import LazyObject except ImportError: pass else: class LazySettings(LazyObject): def _setup(self): from admin_sso import default_settings self._wrapped = Settings(default_settings) class Settings(object): def __init__(self, settings_module): for setting in dir(settings_module): if setting == setting.upper(): <|fim_middle|> settings = LazySettings() <|fim▁end|>
setattr(self, setting, getattr(settings_module, setting))
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>VERSION = (1, 0, 0,) __version__ = '.'.join(map(str, VERSION)) default_app_config = 'admin_sso.apps.AdminSSOConfig' # Do not use Django settings at module level as recommended try: from django.utils.functional import LazyObject except ImportError: pass else: class LazySettings(LazyObject): def <|fim_middle|>(self): from admin_sso import default_settings self._wrapped = Settings(default_settings) class Settings(object): def __init__(self, settings_module): for setting in dir(settings_module): if setting == setting.upper(): setattr(self, setting, getattr(settings_module, setting)) settings = LazySettings() <|fim▁end|>
_setup
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>VERSION = (1, 0, 0,) __version__ = '.'.join(map(str, VERSION)) default_app_config = 'admin_sso.apps.AdminSSOConfig' # Do not use Django settings at module level as recommended try: from django.utils.functional import LazyObject except ImportError: pass else: class LazySettings(LazyObject): def _setup(self): from admin_sso import default_settings self._wrapped = Settings(default_settings) class Settings(object): def <|fim_middle|>(self, settings_module): for setting in dir(settings_module): if setting == setting.upper(): setattr(self, setting, getattr(settings_module, setting)) settings = LazySettings() <|fim▁end|>
__init__
<|file_name|>test_write_worksheet.py<|end_file_name|><|fim▁begin|>############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2015, John McNamara, [email protected]<|fim▁hole|>from ...worksheet import Worksheet class TestWriteWorksheet(unittest.TestCase): """ Test the Worksheet _write_worksheet() method. """ def setUp(self): self.fh = StringIO() self.worksheet = Worksheet() self.worksheet._set_filehandle(self.fh) def test_write_worksheet(self): """Test the _write_worksheet() method""" self.worksheet._write_worksheet() exp = """<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">""" got = self.fh.getvalue() self.assertEqual(got, exp)<|fim▁end|>
# import unittest from ...compatibility import StringIO
<|file_name|>test_write_worksheet.py<|end_file_name|><|fim▁begin|>############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2015, John McNamara, [email protected] # import unittest from ...compatibility import StringIO from ...worksheet import Worksheet class TestWriteWorksheet(unittest.TestCase): <|fim_middle|> <|fim▁end|>
""" Test the Worksheet _write_worksheet() method. """ def setUp(self): self.fh = StringIO() self.worksheet = Worksheet() self.worksheet._set_filehandle(self.fh) def test_write_worksheet(self): """Test the _write_worksheet() method""" self.worksheet._write_worksheet() exp = """<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">""" got = self.fh.getvalue() self.assertEqual(got, exp)
<|file_name|>test_write_worksheet.py<|end_file_name|><|fim▁begin|>############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2015, John McNamara, [email protected] # import unittest from ...compatibility import StringIO from ...worksheet import Worksheet class TestWriteWorksheet(unittest.TestCase): """ Test the Worksheet _write_worksheet() method. """ def setUp(self): <|fim_middle|> def test_write_worksheet(self): """Test the _write_worksheet() method""" self.worksheet._write_worksheet() exp = """<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">""" got = self.fh.getvalue() self.assertEqual(got, exp) <|fim▁end|>
self.fh = StringIO() self.worksheet = Worksheet() self.worksheet._set_filehandle(self.fh)
<|file_name|>test_write_worksheet.py<|end_file_name|><|fim▁begin|>############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2015, John McNamara, [email protected] # import unittest from ...compatibility import StringIO from ...worksheet import Worksheet class TestWriteWorksheet(unittest.TestCase): """ Test the Worksheet _write_worksheet() method. """ def setUp(self): self.fh = StringIO() self.worksheet = Worksheet() self.worksheet._set_filehandle(self.fh) def test_write_worksheet(self): <|fim_middle|> <|fim▁end|>
"""Test the _write_worksheet() method""" self.worksheet._write_worksheet() exp = """<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">""" got = self.fh.getvalue() self.assertEqual(got, exp)
<|file_name|>test_write_worksheet.py<|end_file_name|><|fim▁begin|>############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2015, John McNamara, [email protected] # import unittest from ...compatibility import StringIO from ...worksheet import Worksheet class TestWriteWorksheet(unittest.TestCase): """ Test the Worksheet _write_worksheet() method. """ def <|fim_middle|>(self): self.fh = StringIO() self.worksheet = Worksheet() self.worksheet._set_filehandle(self.fh) def test_write_worksheet(self): """Test the _write_worksheet() method""" self.worksheet._write_worksheet() exp = """<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">""" got = self.fh.getvalue() self.assertEqual(got, exp) <|fim▁end|>
setUp
<|file_name|>test_write_worksheet.py<|end_file_name|><|fim▁begin|>############################################################################### # # Tests for XlsxWriter. # # Copyright (c), 2013-2015, John McNamara, [email protected] # import unittest from ...compatibility import StringIO from ...worksheet import Worksheet class TestWriteWorksheet(unittest.TestCase): """ Test the Worksheet _write_worksheet() method. """ def setUp(self): self.fh = StringIO() self.worksheet = Worksheet() self.worksheet._set_filehandle(self.fh) def <|fim_middle|>(self): """Test the _write_worksheet() method""" self.worksheet._write_worksheet() exp = """<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">""" got = self.fh.getvalue() self.assertEqual(got, exp) <|fim▁end|>
test_write_worksheet
<|file_name|>0001_initial.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings import django_pgjson.fields import django.utils.timezone import django.db.models.deletion import djorm_pgarray.fields import taiga.projects.history.models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('users', '0002_auto_20140903_0916'), ] operations = [ migrations.CreateModel( name='Membership', fields=[ ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')), ('is_owner', models.BooleanField(default=False)), ('email', models.EmailField(max_length=255, null=True, default=None, verbose_name='email', blank=True)), ('created_at', models.DateTimeField(default=django.utils.timezone.now, verbose_name='creado el')), ('token', models.CharField(max_length=60, null=True, default=None, verbose_name='token', blank=True)), ('invited_by_id', models.IntegerField(null=True, blank=True)), ], options={ 'ordering': ['project', 'user__full_name', 'user__username', 'user__email', 'email'], 'verbose_name_plural': 'membershipss', 'permissions': (('view_membership', 'Can view membership'),), 'verbose_name': 'membership', }, bases=(models.Model,), ), migrations.CreateModel( name='Project', fields=[ ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')), ('tags', djorm_pgarray.fields.TextArrayField(dbtype='text', verbose_name='tags')), ('name', models.CharField(max_length=250, unique=True, verbose_name='name')), ('slug', models.SlugField(max_length=250, unique=True, verbose_name='slug', blank=True)), ('description', models.TextField(verbose_name='description')), ('created_date', models.DateTimeField(default=django.utils.timezone.now, verbose_name='created date')), ('modified_date', models.DateTimeField(verbose_name='modified date')), ('total_milestones', models.IntegerField(null=True, default=0, verbose_name='total of milestones', blank=True)), ('total_story_points', models.FloatField(default=0, verbose_name='total story points')), ('is_backlog_activated', models.BooleanField(default=True, verbose_name='active backlog panel')), ('is_kanban_activated', models.BooleanField(default=False, verbose_name='active kanban panel')), ('is_wiki_activated', models.BooleanField(default=True, verbose_name='active wiki panel')), ('is_issues_activated', models.BooleanField(default=True, verbose_name='active issues panel')), ('videoconferences', models.CharField(max_length=250, null=True, choices=[('appear-in', 'AppearIn'), ('talky', 'Talky'), ('jitsi', 'Jitsi')], verbose_name='videoconference system', blank=True)), ('videoconferences_salt', models.CharField(max_length=250, null=True, verbose_name='videoconference room salt', blank=True)), ('anon_permissions', djorm_pgarray.fields.TextArrayField(choices=[('view_project', 'View project'), ('view_milestones', 'View milestones'), ('view_us', 'View user stories'), ('view_tasks', 'View tasks'), ('view_issues', 'View issues'), ('view_wiki_pages', 'View wiki pages'), ('view_wiki_links', 'View wiki links')], dbtype='text', default=[], verbose_name='anonymous permissions')), ('public_permissions', djorm_pgarray.fields.TextArrayField(choices=[('view_project', 'View project'), ('view_milestones', 'View milestones'), ('view_us', 'View user stories'), ('view_issues', 'View issues'), ('vote_issues', 'Vote issues'), ('view_tasks', 'View tasks'), ('view_wiki_pages', 'View wiki pages'), ('view_wiki_links', 'View wiki links'), ('request_membership', 'Request membership'), ('add_us_to_project', 'Add user story to project'), ('add_comments_to_us', 'Add comments to user stories'), ('add_comments_to_task', 'Add comments to tasks'), ('add_issue', 'Add issues'), ('add_comments_issue', 'Add comments to issues'), ('add_wiki_page', 'Add wiki page'), ('modify_wiki_page', 'Modify wiki page'), ('add_wiki_link', 'Add wiki link'), ('modify_wiki_link', 'Modify wiki link')], dbtype='text', default=[], verbose_name='user permissions')), ('is_private', models.BooleanField(default=False, verbose_name='is private')), ('tags_colors', djorm_pgarray.fields.TextArrayField(dbtype='text', dimension=2, default=[], null=False, verbose_name='tags colors')),<|fim▁hole|> ], options={ 'ordering': ['name'], 'verbose_name_plural': 'projects', 'permissions': (('view_project', 'Can view project'),), 'verbose_name': 'project', }, bases=(models.Model,), ), migrations.AddField( model_name='project', name='members', field=models.ManyToManyField(to=settings.AUTH_USER_MODEL, related_name='projects', verbose_name='members', through='projects.Membership'), preserve_default=True, ), migrations.AddField( model_name='project', name='owner', field=models.ForeignKey(to=settings.AUTH_USER_MODEL, related_name='owned_projects', verbose_name='owner'), preserve_default=True, ), migrations.AddField( model_name='membership', name='user', field=models.ForeignKey(blank=True, default=None, to=settings.AUTH_USER_MODEL, null=True, related_name='memberships'), preserve_default=True, ), migrations.AddField( model_name='membership', name='project', field=models.ForeignKey(default=1, to='projects.Project', related_name='memberships'), preserve_default=False, ), migrations.AlterUniqueTogether( name='membership', unique_together=set([('user', 'project')]), ), migrations.AddField( model_name='membership', name='role', field=models.ForeignKey(related_name='memberships', to='users.Role', default=1), preserve_default=False, ), ]<|fim▁end|>
<|file_name|>0001_initial.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings import django_pgjson.fields import django.utils.timezone import django.db.models.deletion import djorm_pgarray.fields import taiga.projects.history.models class Migration(migrations.Migration): <|fim_middle|> <|fim▁end|>
dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('users', '0002_auto_20140903_0916'), ] operations = [ migrations.CreateModel( name='Membership', fields=[ ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')), ('is_owner', models.BooleanField(default=False)), ('email', models.EmailField(max_length=255, null=True, default=None, verbose_name='email', blank=True)), ('created_at', models.DateTimeField(default=django.utils.timezone.now, verbose_name='creado el')), ('token', models.CharField(max_length=60, null=True, default=None, verbose_name='token', blank=True)), ('invited_by_id', models.IntegerField(null=True, blank=True)), ], options={ 'ordering': ['project', 'user__full_name', 'user__username', 'user__email', 'email'], 'verbose_name_plural': 'membershipss', 'permissions': (('view_membership', 'Can view membership'),), 'verbose_name': 'membership', }, bases=(models.Model,), ), migrations.CreateModel( name='Project', fields=[ ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')), ('tags', djorm_pgarray.fields.TextArrayField(dbtype='text', verbose_name='tags')), ('name', models.CharField(max_length=250, unique=True, verbose_name='name')), ('slug', models.SlugField(max_length=250, unique=True, verbose_name='slug', blank=True)), ('description', models.TextField(verbose_name='description')), ('created_date', models.DateTimeField(default=django.utils.timezone.now, verbose_name='created date')), ('modified_date', models.DateTimeField(verbose_name='modified date')), ('total_milestones', models.IntegerField(null=True, default=0, verbose_name='total of milestones', blank=True)), ('total_story_points', models.FloatField(default=0, verbose_name='total story points')), ('is_backlog_activated', models.BooleanField(default=True, verbose_name='active backlog panel')), ('is_kanban_activated', models.BooleanField(default=False, verbose_name='active kanban panel')), ('is_wiki_activated', models.BooleanField(default=True, verbose_name='active wiki panel')), ('is_issues_activated', models.BooleanField(default=True, verbose_name='active issues panel')), ('videoconferences', models.CharField(max_length=250, null=True, choices=[('appear-in', 'AppearIn'), ('talky', 'Talky'), ('jitsi', 'Jitsi')], verbose_name='videoconference system', blank=True)), ('videoconferences_salt', models.CharField(max_length=250, null=True, verbose_name='videoconference room salt', blank=True)), ('anon_permissions', djorm_pgarray.fields.TextArrayField(choices=[('view_project', 'View project'), ('view_milestones', 'View milestones'), ('view_us', 'View user stories'), ('view_tasks', 'View tasks'), ('view_issues', 'View issues'), ('view_wiki_pages', 'View wiki pages'), ('view_wiki_links', 'View wiki links')], dbtype='text', default=[], verbose_name='anonymous permissions')), ('public_permissions', djorm_pgarray.fields.TextArrayField(choices=[('view_project', 'View project'), ('view_milestones', 'View milestones'), ('view_us', 'View user stories'), ('view_issues', 'View issues'), ('vote_issues', 'Vote issues'), ('view_tasks', 'View tasks'), ('view_wiki_pages', 'View wiki pages'), ('view_wiki_links', 'View wiki links'), ('request_membership', 'Request membership'), ('add_us_to_project', 'Add user story to project'), ('add_comments_to_us', 'Add comments to user stories'), ('add_comments_to_task', 'Add comments to tasks'), ('add_issue', 'Add issues'), ('add_comments_issue', 'Add comments to issues'), ('add_wiki_page', 'Add wiki page'), ('modify_wiki_page', 'Modify wiki page'), ('add_wiki_link', 'Add wiki link'), ('modify_wiki_link', 'Modify wiki link')], dbtype='text', default=[], verbose_name='user permissions')), ('is_private', models.BooleanField(default=False, verbose_name='is private')), ('tags_colors', djorm_pgarray.fields.TextArrayField(dbtype='text', dimension=2, default=[], null=False, verbose_name='tags colors')), ], options={ 'ordering': ['name'], 'verbose_name_plural': 'projects', 'permissions': (('view_project', 'Can view project'),), 'verbose_name': 'project', }, bases=(models.Model,), ), migrations.AddField( model_name='project', name='members', field=models.ManyToManyField(to=settings.AUTH_USER_MODEL, related_name='projects', verbose_name='members', through='projects.Membership'), preserve_default=True, ), migrations.AddField( model_name='project', name='owner', field=models.ForeignKey(to=settings.AUTH_USER_MODEL, related_name='owned_projects', verbose_name='owner'), preserve_default=True, ), migrations.AddField( model_name='membership', name='user', field=models.ForeignKey(blank=True, default=None, to=settings.AUTH_USER_MODEL, null=True, related_name='memberships'), preserve_default=True, ), migrations.AddField( model_name='membership', name='project', field=models.ForeignKey(default=1, to='projects.Project', related_name='memberships'), preserve_default=False, ), migrations.AlterUniqueTogether( name='membership', unique_together=set([('user', 'project')]), ), migrations.AddField( model_name='membership', name='role', field=models.ForeignKey(related_name='memberships', to='users.Role', default=1), preserve_default=False, ), ]
<|file_name|>msp.py<|end_file_name|><|fim▁begin|>import sys import cv2 import helper as hp class MSP(): name = "MSP" def __init__(self): self.__patterns_num = []<|fim▁hole|> self.__labels_num = [] self.__labels_sym = [] msp_num, msp_sym = "msp/num", "msp/sym" self.__load_num_patterns(msp_num) self.__load_sym_patterns(msp_sym) print 'loading MSP...' def __load_num_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_num = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_num = [hp.get_test(path, "num")[0] for path in paths] def __load_sym_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_sym = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_sym = [hp.get_test(path, "sym")[0] for path in paths] def __get_mode(self, mode): if mode == "num": return self.__labels_num, self.__patterns_num elif mode == "sym": return self.__labels_sym, self.__patterns_sym def rec(self, img, mode): tmp_max, tmp, rec = sys.maxint, 0, 0 labels, patterns = self.__get_mode(mode) for pattern, label in zip(patterns, labels): tmp = cv2.countNonZero(pattern - img) if tmp < tmp_max: tmp_max, rec = tmp, label return rec<|fim▁end|>
self.__patterns_sym = []
<|file_name|>msp.py<|end_file_name|><|fim▁begin|>import sys import cv2 import helper as hp class MSP(): <|fim_middle|> <|fim▁end|>
name = "MSP" def __init__(self): self.__patterns_num = [] self.__patterns_sym = [] self.__labels_num = [] self.__labels_sym = [] msp_num, msp_sym = "msp/num", "msp/sym" self.__load_num_patterns(msp_num) self.__load_sym_patterns(msp_sym) print 'loading MSP...' def __load_num_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_num = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_num = [hp.get_test(path, "num")[0] for path in paths] def __load_sym_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_sym = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_sym = [hp.get_test(path, "sym")[0] for path in paths] def __get_mode(self, mode): if mode == "num": return self.__labels_num, self.__patterns_num elif mode == "sym": return self.__labels_sym, self.__patterns_sym def rec(self, img, mode): tmp_max, tmp, rec = sys.maxint, 0, 0 labels, patterns = self.__get_mode(mode) for pattern, label in zip(patterns, labels): tmp = cv2.countNonZero(pattern - img) if tmp < tmp_max: tmp_max, rec = tmp, label return rec
<|file_name|>msp.py<|end_file_name|><|fim▁begin|>import sys import cv2 import helper as hp class MSP(): name = "MSP" def __init__(self): <|fim_middle|> def __load_num_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_num = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_num = [hp.get_test(path, "num")[0] for path in paths] def __load_sym_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_sym = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_sym = [hp.get_test(path, "sym")[0] for path in paths] def __get_mode(self, mode): if mode == "num": return self.__labels_num, self.__patterns_num elif mode == "sym": return self.__labels_sym, self.__patterns_sym def rec(self, img, mode): tmp_max, tmp, rec = sys.maxint, 0, 0 labels, patterns = self.__get_mode(mode) for pattern, label in zip(patterns, labels): tmp = cv2.countNonZero(pattern - img) if tmp < tmp_max: tmp_max, rec = tmp, label return rec <|fim▁end|>
self.__patterns_num = [] self.__patterns_sym = [] self.__labels_num = [] self.__labels_sym = [] msp_num, msp_sym = "msp/num", "msp/sym" self.__load_num_patterns(msp_num) self.__load_sym_patterns(msp_sym) print 'loading MSP...'
<|file_name|>msp.py<|end_file_name|><|fim▁begin|>import sys import cv2 import helper as hp class MSP(): name = "MSP" def __init__(self): self.__patterns_num = [] self.__patterns_sym = [] self.__labels_num = [] self.__labels_sym = [] msp_num, msp_sym = "msp/num", "msp/sym" self.__load_num_patterns(msp_num) self.__load_sym_patterns(msp_sym) print 'loading MSP...' def __load_num_patterns(self, input_dir): <|fim_middle|> def __load_sym_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_sym = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_sym = [hp.get_test(path, "sym")[0] for path in paths] def __get_mode(self, mode): if mode == "num": return self.__labels_num, self.__patterns_num elif mode == "sym": return self.__labels_sym, self.__patterns_sym def rec(self, img, mode): tmp_max, tmp, rec = sys.maxint, 0, 0 labels, patterns = self.__get_mode(mode) for pattern, label in zip(patterns, labels): tmp = cv2.countNonZero(pattern - img) if tmp < tmp_max: tmp_max, rec = tmp, label return rec <|fim▁end|>
paths = hp.get_paths(input_dir) self.__patterns_num = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_num = [hp.get_test(path, "num")[0] for path in paths]
<|file_name|>msp.py<|end_file_name|><|fim▁begin|>import sys import cv2 import helper as hp class MSP(): name = "MSP" def __init__(self): self.__patterns_num = [] self.__patterns_sym = [] self.__labels_num = [] self.__labels_sym = [] msp_num, msp_sym = "msp/num", "msp/sym" self.__load_num_patterns(msp_num) self.__load_sym_patterns(msp_sym) print 'loading MSP...' def __load_num_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_num = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_num = [hp.get_test(path, "num")[0] for path in paths] def __load_sym_patterns(self, input_dir): <|fim_middle|> def __get_mode(self, mode): if mode == "num": return self.__labels_num, self.__patterns_num elif mode == "sym": return self.__labels_sym, self.__patterns_sym def rec(self, img, mode): tmp_max, tmp, rec = sys.maxint, 0, 0 labels, patterns = self.__get_mode(mode) for pattern, label in zip(patterns, labels): tmp = cv2.countNonZero(pattern - img) if tmp < tmp_max: tmp_max, rec = tmp, label return rec <|fim▁end|>
paths = hp.get_paths(input_dir) self.__patterns_sym = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_sym = [hp.get_test(path, "sym")[0] for path in paths]
<|file_name|>msp.py<|end_file_name|><|fim▁begin|>import sys import cv2 import helper as hp class MSP(): name = "MSP" def __init__(self): self.__patterns_num = [] self.__patterns_sym = [] self.__labels_num = [] self.__labels_sym = [] msp_num, msp_sym = "msp/num", "msp/sym" self.__load_num_patterns(msp_num) self.__load_sym_patterns(msp_sym) print 'loading MSP...' def __load_num_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_num = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_num = [hp.get_test(path, "num")[0] for path in paths] def __load_sym_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_sym = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_sym = [hp.get_test(path, "sym")[0] for path in paths] def __get_mode(self, mode): <|fim_middle|> def rec(self, img, mode): tmp_max, tmp, rec = sys.maxint, 0, 0 labels, patterns = self.__get_mode(mode) for pattern, label in zip(patterns, labels): tmp = cv2.countNonZero(pattern - img) if tmp < tmp_max: tmp_max, rec = tmp, label return rec <|fim▁end|>
if mode == "num": return self.__labels_num, self.__patterns_num elif mode == "sym": return self.__labels_sym, self.__patterns_sym
<|file_name|>msp.py<|end_file_name|><|fim▁begin|>import sys import cv2 import helper as hp class MSP(): name = "MSP" def __init__(self): self.__patterns_num = [] self.__patterns_sym = [] self.__labels_num = [] self.__labels_sym = [] msp_num, msp_sym = "msp/num", "msp/sym" self.__load_num_patterns(msp_num) self.__load_sym_patterns(msp_sym) print 'loading MSP...' def __load_num_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_num = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_num = [hp.get_test(path, "num")[0] for path in paths] def __load_sym_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_sym = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_sym = [hp.get_test(path, "sym")[0] for path in paths] def __get_mode(self, mode): if mode == "num": return self.__labels_num, self.__patterns_num elif mode == "sym": return self.__labels_sym, self.__patterns_sym def rec(self, img, mode): <|fim_middle|> <|fim▁end|>
tmp_max, tmp, rec = sys.maxint, 0, 0 labels, patterns = self.__get_mode(mode) for pattern, label in zip(patterns, labels): tmp = cv2.countNonZero(pattern - img) if tmp < tmp_max: tmp_max, rec = tmp, label return rec
<|file_name|>msp.py<|end_file_name|><|fim▁begin|>import sys import cv2 import helper as hp class MSP(): name = "MSP" def __init__(self): self.__patterns_num = [] self.__patterns_sym = [] self.__labels_num = [] self.__labels_sym = [] msp_num, msp_sym = "msp/num", "msp/sym" self.__load_num_patterns(msp_num) self.__load_sym_patterns(msp_sym) print 'loading MSP...' def __load_num_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_num = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_num = [hp.get_test(path, "num")[0] for path in paths] def __load_sym_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_sym = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_sym = [hp.get_test(path, "sym")[0] for path in paths] def __get_mode(self, mode): if mode == "num": <|fim_middle|> elif mode == "sym": return self.__labels_sym, self.__patterns_sym def rec(self, img, mode): tmp_max, tmp, rec = sys.maxint, 0, 0 labels, patterns = self.__get_mode(mode) for pattern, label in zip(patterns, labels): tmp = cv2.countNonZero(pattern - img) if tmp < tmp_max: tmp_max, rec = tmp, label return rec <|fim▁end|>
return self.__labels_num, self.__patterns_num
<|file_name|>msp.py<|end_file_name|><|fim▁begin|>import sys import cv2 import helper as hp class MSP(): name = "MSP" def __init__(self): self.__patterns_num = [] self.__patterns_sym = [] self.__labels_num = [] self.__labels_sym = [] msp_num, msp_sym = "msp/num", "msp/sym" self.__load_num_patterns(msp_num) self.__load_sym_patterns(msp_sym) print 'loading MSP...' def __load_num_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_num = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_num = [hp.get_test(path, "num")[0] for path in paths] def __load_sym_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_sym = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_sym = [hp.get_test(path, "sym")[0] for path in paths] def __get_mode(self, mode): if mode == "num": return self.__labels_num, self.__patterns_num elif mode == "sym": <|fim_middle|> def rec(self, img, mode): tmp_max, tmp, rec = sys.maxint, 0, 0 labels, patterns = self.__get_mode(mode) for pattern, label in zip(patterns, labels): tmp = cv2.countNonZero(pattern - img) if tmp < tmp_max: tmp_max, rec = tmp, label return rec <|fim▁end|>
return self.__labels_sym, self.__patterns_sym
<|file_name|>msp.py<|end_file_name|><|fim▁begin|>import sys import cv2 import helper as hp class MSP(): name = "MSP" def __init__(self): self.__patterns_num = [] self.__patterns_sym = [] self.__labels_num = [] self.__labels_sym = [] msp_num, msp_sym = "msp/num", "msp/sym" self.__load_num_patterns(msp_num) self.__load_sym_patterns(msp_sym) print 'loading MSP...' def __load_num_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_num = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_num = [hp.get_test(path, "num")[0] for path in paths] def __load_sym_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_sym = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_sym = [hp.get_test(path, "sym")[0] for path in paths] def __get_mode(self, mode): if mode == "num": return self.__labels_num, self.__patterns_num elif mode == "sym": return self.__labels_sym, self.__patterns_sym def rec(self, img, mode): tmp_max, tmp, rec = sys.maxint, 0, 0 labels, patterns = self.__get_mode(mode) for pattern, label in zip(patterns, labels): tmp = cv2.countNonZero(pattern - img) if tmp < tmp_max: <|fim_middle|> return rec <|fim▁end|>
tmp_max, rec = tmp, label
<|file_name|>msp.py<|end_file_name|><|fim▁begin|>import sys import cv2 import helper as hp class MSP(): name = "MSP" def <|fim_middle|>(self): self.__patterns_num = [] self.__patterns_sym = [] self.__labels_num = [] self.__labels_sym = [] msp_num, msp_sym = "msp/num", "msp/sym" self.__load_num_patterns(msp_num) self.__load_sym_patterns(msp_sym) print 'loading MSP...' def __load_num_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_num = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_num = [hp.get_test(path, "num")[0] for path in paths] def __load_sym_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_sym = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_sym = [hp.get_test(path, "sym")[0] for path in paths] def __get_mode(self, mode): if mode == "num": return self.__labels_num, self.__patterns_num elif mode == "sym": return self.__labels_sym, self.__patterns_sym def rec(self, img, mode): tmp_max, tmp, rec = sys.maxint, 0, 0 labels, patterns = self.__get_mode(mode) for pattern, label in zip(patterns, labels): tmp = cv2.countNonZero(pattern - img) if tmp < tmp_max: tmp_max, rec = tmp, label return rec <|fim▁end|>
__init__
<|file_name|>msp.py<|end_file_name|><|fim▁begin|>import sys import cv2 import helper as hp class MSP(): name = "MSP" def __init__(self): self.__patterns_num = [] self.__patterns_sym = [] self.__labels_num = [] self.__labels_sym = [] msp_num, msp_sym = "msp/num", "msp/sym" self.__load_num_patterns(msp_num) self.__load_sym_patterns(msp_sym) print 'loading MSP...' def <|fim_middle|>(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_num = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_num = [hp.get_test(path, "num")[0] for path in paths] def __load_sym_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_sym = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_sym = [hp.get_test(path, "sym")[0] for path in paths] def __get_mode(self, mode): if mode == "num": return self.__labels_num, self.__patterns_num elif mode == "sym": return self.__labels_sym, self.__patterns_sym def rec(self, img, mode): tmp_max, tmp, rec = sys.maxint, 0, 0 labels, patterns = self.__get_mode(mode) for pattern, label in zip(patterns, labels): tmp = cv2.countNonZero(pattern - img) if tmp < tmp_max: tmp_max, rec = tmp, label return rec <|fim▁end|>
__load_num_patterns
<|file_name|>msp.py<|end_file_name|><|fim▁begin|>import sys import cv2 import helper as hp class MSP(): name = "MSP" def __init__(self): self.__patterns_num = [] self.__patterns_sym = [] self.__labels_num = [] self.__labels_sym = [] msp_num, msp_sym = "msp/num", "msp/sym" self.__load_num_patterns(msp_num) self.__load_sym_patterns(msp_sym) print 'loading MSP...' def __load_num_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_num = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_num = [hp.get_test(path, "num")[0] for path in paths] def <|fim_middle|>(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_sym = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_sym = [hp.get_test(path, "sym")[0] for path in paths] def __get_mode(self, mode): if mode == "num": return self.__labels_num, self.__patterns_num elif mode == "sym": return self.__labels_sym, self.__patterns_sym def rec(self, img, mode): tmp_max, tmp, rec = sys.maxint, 0, 0 labels, patterns = self.__get_mode(mode) for pattern, label in zip(patterns, labels): tmp = cv2.countNonZero(pattern - img) if tmp < tmp_max: tmp_max, rec = tmp, label return rec <|fim▁end|>
__load_sym_patterns
<|file_name|>msp.py<|end_file_name|><|fim▁begin|>import sys import cv2 import helper as hp class MSP(): name = "MSP" def __init__(self): self.__patterns_num = [] self.__patterns_sym = [] self.__labels_num = [] self.__labels_sym = [] msp_num, msp_sym = "msp/num", "msp/sym" self.__load_num_patterns(msp_num) self.__load_sym_patterns(msp_sym) print 'loading MSP...' def __load_num_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_num = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_num = [hp.get_test(path, "num")[0] for path in paths] def __load_sym_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_sym = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_sym = [hp.get_test(path, "sym")[0] for path in paths] def <|fim_middle|>(self, mode): if mode == "num": return self.__labels_num, self.__patterns_num elif mode == "sym": return self.__labels_sym, self.__patterns_sym def rec(self, img, mode): tmp_max, tmp, rec = sys.maxint, 0, 0 labels, patterns = self.__get_mode(mode) for pattern, label in zip(patterns, labels): tmp = cv2.countNonZero(pattern - img) if tmp < tmp_max: tmp_max, rec = tmp, label return rec <|fim▁end|>
__get_mode
<|file_name|>msp.py<|end_file_name|><|fim▁begin|>import sys import cv2 import helper as hp class MSP(): name = "MSP" def __init__(self): self.__patterns_num = [] self.__patterns_sym = [] self.__labels_num = [] self.__labels_sym = [] msp_num, msp_sym = "msp/num", "msp/sym" self.__load_num_patterns(msp_num) self.__load_sym_patterns(msp_sym) print 'loading MSP...' def __load_num_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_num = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_num = [hp.get_test(path, "num")[0] for path in paths] def __load_sym_patterns(self, input_dir): paths = hp.get_paths(input_dir) self.__patterns_sym = [hp.get_gray_image(input_dir, path) for path in paths] self.__labels_sym = [hp.get_test(path, "sym")[0] for path in paths] def __get_mode(self, mode): if mode == "num": return self.__labels_num, self.__patterns_num elif mode == "sym": return self.__labels_sym, self.__patterns_sym def <|fim_middle|>(self, img, mode): tmp_max, tmp, rec = sys.maxint, 0, 0 labels, patterns = self.__get_mode(mode) for pattern, label in zip(patterns, labels): tmp = cv2.countNonZero(pattern - img) if tmp < tmp_max: tmp_max, rec = tmp, label return rec <|fim▁end|>
rec
<|file_name|>0012_auto_20150422_2019.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('managers', '0011_auto_20150422_2018'), ] <|fim▁hole|> field=models.ImageField(default=b'/static/assets/admin/layout/img/avatar.jpg', upload_to=b'profiles'), preserve_default=True, ), ]<|fim▁end|>
operations = [ migrations.AlterField( model_name='managerprofile', name='picture',
<|file_name|>0012_auto_20150422_2019.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): <|fim_middle|> <|fim▁end|>
dependencies = [ ('managers', '0011_auto_20150422_2018'), ] operations = [ migrations.AlterField( model_name='managerprofile', name='picture', field=models.ImageField(default=b'/static/assets/admin/layout/img/avatar.jpg', upload_to=b'profiles'), preserve_default=True, ), ]
<|file_name|>test_expand_path.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (nested_scopes, generators, division, absolute_import, with_statement, print_function, unicode_literals) from contextlib import contextmanager import os import unittest2 as unittest from pants.fs.fs import expand_path from pants.util.contextutil import environment_as, pushd, temporary_dir class ExpandPathTest(unittest.TestCase): def test_pure_relative(self): with self.root() as root: self.assertEquals(os.path.join(root, 'a'), expand_path('a')) <|fim▁hole|> def test_dot_relative(self): with self.root() as root: self.assertEquals(os.path.join(root, 'a'), expand_path('./a')) def test_absolute(self): self.assertEquals('/tmp/jake/bob', expand_path('/tmp/jake/bob')) def test_user_expansion(self): with environment_as(HOME='/tmp/jake'): self.assertEquals('/tmp/jake/bob', expand_path('~/bob')) def test_env_var_expansion(self): with self.root() as root: with environment_as(A='B', C='D'): self.assertEquals(os.path.join(root, 'B/D/E'), expand_path('$A/${C}/E')) @contextmanager def root(self): with temporary_dir() as root: # Avoid OSX issues where tmp dirs are reported as symlinks. real_root = os.path.realpath(root) with pushd(real_root): yield real_root<|fim▁end|>
<|file_name|>test_expand_path.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (nested_scopes, generators, division, absolute_import, with_statement, print_function, unicode_literals) from contextlib import contextmanager import os import unittest2 as unittest from pants.fs.fs import expand_path from pants.util.contextutil import environment_as, pushd, temporary_dir class ExpandPathTest(unittest.TestCase): <|fim_middle|> <|fim▁end|>
def test_pure_relative(self): with self.root() as root: self.assertEquals(os.path.join(root, 'a'), expand_path('a')) def test_dot_relative(self): with self.root() as root: self.assertEquals(os.path.join(root, 'a'), expand_path('./a')) def test_absolute(self): self.assertEquals('/tmp/jake/bob', expand_path('/tmp/jake/bob')) def test_user_expansion(self): with environment_as(HOME='/tmp/jake'): self.assertEquals('/tmp/jake/bob', expand_path('~/bob')) def test_env_var_expansion(self): with self.root() as root: with environment_as(A='B', C='D'): self.assertEquals(os.path.join(root, 'B/D/E'), expand_path('$A/${C}/E')) @contextmanager def root(self): with temporary_dir() as root: # Avoid OSX issues where tmp dirs are reported as symlinks. real_root = os.path.realpath(root) with pushd(real_root): yield real_root
<|file_name|>test_expand_path.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (nested_scopes, generators, division, absolute_import, with_statement, print_function, unicode_literals) from contextlib import contextmanager import os import unittest2 as unittest from pants.fs.fs import expand_path from pants.util.contextutil import environment_as, pushd, temporary_dir class ExpandPathTest(unittest.TestCase): def test_pure_relative(self): <|fim_middle|> def test_dot_relative(self): with self.root() as root: self.assertEquals(os.path.join(root, 'a'), expand_path('./a')) def test_absolute(self): self.assertEquals('/tmp/jake/bob', expand_path('/tmp/jake/bob')) def test_user_expansion(self): with environment_as(HOME='/tmp/jake'): self.assertEquals('/tmp/jake/bob', expand_path('~/bob')) def test_env_var_expansion(self): with self.root() as root: with environment_as(A='B', C='D'): self.assertEquals(os.path.join(root, 'B/D/E'), expand_path('$A/${C}/E')) @contextmanager def root(self): with temporary_dir() as root: # Avoid OSX issues where tmp dirs are reported as symlinks. real_root = os.path.realpath(root) with pushd(real_root): yield real_root <|fim▁end|>
with self.root() as root: self.assertEquals(os.path.join(root, 'a'), expand_path('a'))
<|file_name|>test_expand_path.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (nested_scopes, generators, division, absolute_import, with_statement, print_function, unicode_literals) from contextlib import contextmanager import os import unittest2 as unittest from pants.fs.fs import expand_path from pants.util.contextutil import environment_as, pushd, temporary_dir class ExpandPathTest(unittest.TestCase): def test_pure_relative(self): with self.root() as root: self.assertEquals(os.path.join(root, 'a'), expand_path('a')) def test_dot_relative(self): <|fim_middle|> def test_absolute(self): self.assertEquals('/tmp/jake/bob', expand_path('/tmp/jake/bob')) def test_user_expansion(self): with environment_as(HOME='/tmp/jake'): self.assertEquals('/tmp/jake/bob', expand_path('~/bob')) def test_env_var_expansion(self): with self.root() as root: with environment_as(A='B', C='D'): self.assertEquals(os.path.join(root, 'B/D/E'), expand_path('$A/${C}/E')) @contextmanager def root(self): with temporary_dir() as root: # Avoid OSX issues where tmp dirs are reported as symlinks. real_root = os.path.realpath(root) with pushd(real_root): yield real_root <|fim▁end|>
with self.root() as root: self.assertEquals(os.path.join(root, 'a'), expand_path('./a'))
<|file_name|>test_expand_path.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (nested_scopes, generators, division, absolute_import, with_statement, print_function, unicode_literals) from contextlib import contextmanager import os import unittest2 as unittest from pants.fs.fs import expand_path from pants.util.contextutil import environment_as, pushd, temporary_dir class ExpandPathTest(unittest.TestCase): def test_pure_relative(self): with self.root() as root: self.assertEquals(os.path.join(root, 'a'), expand_path('a')) def test_dot_relative(self): with self.root() as root: self.assertEquals(os.path.join(root, 'a'), expand_path('./a')) def test_absolute(self): <|fim_middle|> def test_user_expansion(self): with environment_as(HOME='/tmp/jake'): self.assertEquals('/tmp/jake/bob', expand_path('~/bob')) def test_env_var_expansion(self): with self.root() as root: with environment_as(A='B', C='D'): self.assertEquals(os.path.join(root, 'B/D/E'), expand_path('$A/${C}/E')) @contextmanager def root(self): with temporary_dir() as root: # Avoid OSX issues where tmp dirs are reported as symlinks. real_root = os.path.realpath(root) with pushd(real_root): yield real_root <|fim▁end|>
self.assertEquals('/tmp/jake/bob', expand_path('/tmp/jake/bob'))
<|file_name|>test_expand_path.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (nested_scopes, generators, division, absolute_import, with_statement, print_function, unicode_literals) from contextlib import contextmanager import os import unittest2 as unittest from pants.fs.fs import expand_path from pants.util.contextutil import environment_as, pushd, temporary_dir class ExpandPathTest(unittest.TestCase): def test_pure_relative(self): with self.root() as root: self.assertEquals(os.path.join(root, 'a'), expand_path('a')) def test_dot_relative(self): with self.root() as root: self.assertEquals(os.path.join(root, 'a'), expand_path('./a')) def test_absolute(self): self.assertEquals('/tmp/jake/bob', expand_path('/tmp/jake/bob')) def test_user_expansion(self): <|fim_middle|> def test_env_var_expansion(self): with self.root() as root: with environment_as(A='B', C='D'): self.assertEquals(os.path.join(root, 'B/D/E'), expand_path('$A/${C}/E')) @contextmanager def root(self): with temporary_dir() as root: # Avoid OSX issues where tmp dirs are reported as symlinks. real_root = os.path.realpath(root) with pushd(real_root): yield real_root <|fim▁end|>
with environment_as(HOME='/tmp/jake'): self.assertEquals('/tmp/jake/bob', expand_path('~/bob'))
<|file_name|>test_expand_path.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (nested_scopes, generators, division, absolute_import, with_statement, print_function, unicode_literals) from contextlib import contextmanager import os import unittest2 as unittest from pants.fs.fs import expand_path from pants.util.contextutil import environment_as, pushd, temporary_dir class ExpandPathTest(unittest.TestCase): def test_pure_relative(self): with self.root() as root: self.assertEquals(os.path.join(root, 'a'), expand_path('a')) def test_dot_relative(self): with self.root() as root: self.assertEquals(os.path.join(root, 'a'), expand_path('./a')) def test_absolute(self): self.assertEquals('/tmp/jake/bob', expand_path('/tmp/jake/bob')) def test_user_expansion(self): with environment_as(HOME='/tmp/jake'): self.assertEquals('/tmp/jake/bob', expand_path('~/bob')) def test_env_var_expansion(self): <|fim_middle|> @contextmanager def root(self): with temporary_dir() as root: # Avoid OSX issues where tmp dirs are reported as symlinks. real_root = os.path.realpath(root) with pushd(real_root): yield real_root <|fim▁end|>
with self.root() as root: with environment_as(A='B', C='D'): self.assertEquals(os.path.join(root, 'B/D/E'), expand_path('$A/${C}/E'))
<|file_name|>test_expand_path.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (nested_scopes, generators, division, absolute_import, with_statement, print_function, unicode_literals) from contextlib import contextmanager import os import unittest2 as unittest from pants.fs.fs import expand_path from pants.util.contextutil import environment_as, pushd, temporary_dir class ExpandPathTest(unittest.TestCase): def test_pure_relative(self): with self.root() as root: self.assertEquals(os.path.join(root, 'a'), expand_path('a')) def test_dot_relative(self): with self.root() as root: self.assertEquals(os.path.join(root, 'a'), expand_path('./a')) def test_absolute(self): self.assertEquals('/tmp/jake/bob', expand_path('/tmp/jake/bob')) def test_user_expansion(self): with environment_as(HOME='/tmp/jake'): self.assertEquals('/tmp/jake/bob', expand_path('~/bob')) def test_env_var_expansion(self): with self.root() as root: with environment_as(A='B', C='D'): self.assertEquals(os.path.join(root, 'B/D/E'), expand_path('$A/${C}/E')) @contextmanager def root(self): <|fim_middle|> <|fim▁end|>
with temporary_dir() as root: # Avoid OSX issues where tmp dirs are reported as symlinks. real_root = os.path.realpath(root) with pushd(real_root): yield real_root
<|file_name|>test_expand_path.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (nested_scopes, generators, division, absolute_import, with_statement, print_function, unicode_literals) from contextlib import contextmanager import os import unittest2 as unittest from pants.fs.fs import expand_path from pants.util.contextutil import environment_as, pushd, temporary_dir class ExpandPathTest(unittest.TestCase): def <|fim_middle|>(self): with self.root() as root: self.assertEquals(os.path.join(root, 'a'), expand_path('a')) def test_dot_relative(self): with self.root() as root: self.assertEquals(os.path.join(root, 'a'), expand_path('./a')) def test_absolute(self): self.assertEquals('/tmp/jake/bob', expand_path('/tmp/jake/bob')) def test_user_expansion(self): with environment_as(HOME='/tmp/jake'): self.assertEquals('/tmp/jake/bob', expand_path('~/bob')) def test_env_var_expansion(self): with self.root() as root: with environment_as(A='B', C='D'): self.assertEquals(os.path.join(root, 'B/D/E'), expand_path('$A/${C}/E')) @contextmanager def root(self): with temporary_dir() as root: # Avoid OSX issues where tmp dirs are reported as symlinks. real_root = os.path.realpath(root) with pushd(real_root): yield real_root <|fim▁end|>
test_pure_relative
<|file_name|>test_expand_path.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (nested_scopes, generators, division, absolute_import, with_statement, print_function, unicode_literals) from contextlib import contextmanager import os import unittest2 as unittest from pants.fs.fs import expand_path from pants.util.contextutil import environment_as, pushd, temporary_dir class ExpandPathTest(unittest.TestCase): def test_pure_relative(self): with self.root() as root: self.assertEquals(os.path.join(root, 'a'), expand_path('a')) def <|fim_middle|>(self): with self.root() as root: self.assertEquals(os.path.join(root, 'a'), expand_path('./a')) def test_absolute(self): self.assertEquals('/tmp/jake/bob', expand_path('/tmp/jake/bob')) def test_user_expansion(self): with environment_as(HOME='/tmp/jake'): self.assertEquals('/tmp/jake/bob', expand_path('~/bob')) def test_env_var_expansion(self): with self.root() as root: with environment_as(A='B', C='D'): self.assertEquals(os.path.join(root, 'B/D/E'), expand_path('$A/${C}/E')) @contextmanager def root(self): with temporary_dir() as root: # Avoid OSX issues where tmp dirs are reported as symlinks. real_root = os.path.realpath(root) with pushd(real_root): yield real_root <|fim▁end|>
test_dot_relative
<|file_name|>test_expand_path.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (nested_scopes, generators, division, absolute_import, with_statement, print_function, unicode_literals) from contextlib import contextmanager import os import unittest2 as unittest from pants.fs.fs import expand_path from pants.util.contextutil import environment_as, pushd, temporary_dir class ExpandPathTest(unittest.TestCase): def test_pure_relative(self): with self.root() as root: self.assertEquals(os.path.join(root, 'a'), expand_path('a')) def test_dot_relative(self): with self.root() as root: self.assertEquals(os.path.join(root, 'a'), expand_path('./a')) def <|fim_middle|>(self): self.assertEquals('/tmp/jake/bob', expand_path('/tmp/jake/bob')) def test_user_expansion(self): with environment_as(HOME='/tmp/jake'): self.assertEquals('/tmp/jake/bob', expand_path('~/bob')) def test_env_var_expansion(self): with self.root() as root: with environment_as(A='B', C='D'): self.assertEquals(os.path.join(root, 'B/D/E'), expand_path('$A/${C}/E')) @contextmanager def root(self): with temporary_dir() as root: # Avoid OSX issues where tmp dirs are reported as symlinks. real_root = os.path.realpath(root) with pushd(real_root): yield real_root <|fim▁end|>
test_absolute
<|file_name|>test_expand_path.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (nested_scopes, generators, division, absolute_import, with_statement, print_function, unicode_literals) from contextlib import contextmanager import os import unittest2 as unittest from pants.fs.fs import expand_path from pants.util.contextutil import environment_as, pushd, temporary_dir class ExpandPathTest(unittest.TestCase): def test_pure_relative(self): with self.root() as root: self.assertEquals(os.path.join(root, 'a'), expand_path('a')) def test_dot_relative(self): with self.root() as root: self.assertEquals(os.path.join(root, 'a'), expand_path('./a')) def test_absolute(self): self.assertEquals('/tmp/jake/bob', expand_path('/tmp/jake/bob')) def <|fim_middle|>(self): with environment_as(HOME='/tmp/jake'): self.assertEquals('/tmp/jake/bob', expand_path('~/bob')) def test_env_var_expansion(self): with self.root() as root: with environment_as(A='B', C='D'): self.assertEquals(os.path.join(root, 'B/D/E'), expand_path('$A/${C}/E')) @contextmanager def root(self): with temporary_dir() as root: # Avoid OSX issues where tmp dirs are reported as symlinks. real_root = os.path.realpath(root) with pushd(real_root): yield real_root <|fim▁end|>
test_user_expansion
<|file_name|>test_expand_path.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (nested_scopes, generators, division, absolute_import, with_statement, print_function, unicode_literals) from contextlib import contextmanager import os import unittest2 as unittest from pants.fs.fs import expand_path from pants.util.contextutil import environment_as, pushd, temporary_dir class ExpandPathTest(unittest.TestCase): def test_pure_relative(self): with self.root() as root: self.assertEquals(os.path.join(root, 'a'), expand_path('a')) def test_dot_relative(self): with self.root() as root: self.assertEquals(os.path.join(root, 'a'), expand_path('./a')) def test_absolute(self): self.assertEquals('/tmp/jake/bob', expand_path('/tmp/jake/bob')) def test_user_expansion(self): with environment_as(HOME='/tmp/jake'): self.assertEquals('/tmp/jake/bob', expand_path('~/bob')) def <|fim_middle|>(self): with self.root() as root: with environment_as(A='B', C='D'): self.assertEquals(os.path.join(root, 'B/D/E'), expand_path('$A/${C}/E')) @contextmanager def root(self): with temporary_dir() as root: # Avoid OSX issues where tmp dirs are reported as symlinks. real_root = os.path.realpath(root) with pushd(real_root): yield real_root <|fim▁end|>
test_env_var_expansion
<|file_name|>test_expand_path.py<|end_file_name|><|fim▁begin|># coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (nested_scopes, generators, division, absolute_import, with_statement, print_function, unicode_literals) from contextlib import contextmanager import os import unittest2 as unittest from pants.fs.fs import expand_path from pants.util.contextutil import environment_as, pushd, temporary_dir class ExpandPathTest(unittest.TestCase): def test_pure_relative(self): with self.root() as root: self.assertEquals(os.path.join(root, 'a'), expand_path('a')) def test_dot_relative(self): with self.root() as root: self.assertEquals(os.path.join(root, 'a'), expand_path('./a')) def test_absolute(self): self.assertEquals('/tmp/jake/bob', expand_path('/tmp/jake/bob')) def test_user_expansion(self): with environment_as(HOME='/tmp/jake'): self.assertEquals('/tmp/jake/bob', expand_path('~/bob')) def test_env_var_expansion(self): with self.root() as root: with environment_as(A='B', C='D'): self.assertEquals(os.path.join(root, 'B/D/E'), expand_path('$A/${C}/E')) @contextmanager def <|fim_middle|>(self): with temporary_dir() as root: # Avoid OSX issues where tmp dirs are reported as symlinks. real_root = os.path.realpath(root) with pushd(real_root): yield real_root <|fim▁end|>
root
<|file_name|>connectors_local.py<|end_file_name|><|fim▁begin|>import time from threading import Thread import threading from wtfj_ids import * from wtfj_utils import * class Printer: ''' Opens a new output window and prints messages sent to it ''' def __init__(self,header=''): self._header = header <|fim▁hole|> print(self._header+string) class Console: ''' Allows user to enter commands ''' def __init__(self,prompt='[$] '): self._prompt = prompt self._at = '' def poll(self,wait_s=None,uid=None): try: prompt = str(self._at)+str(self._prompt) msg = raw_input(prompt) if msg == '': self._at = '' return [] if msg[0] == '@': self._at = msg.split()[0]+' ' else: msg = self._at+msg return [msg] except Exception as e: print(repr(e)) return [] def subscribe(self,*uids): pass class Script: ''' Runs a script passed as a list, default frequency = 1000Hz ''' def __init__(self,msgs): self._msgs = msgs self._index = 0 self._period = 0.001 self._pid = 'SCRIPT' def poll(self,wait_s=None,uid=None): period = self._period if wait_s is None else wait_s time.sleep(period) try: msg = self._msgs[self._index] print(self._pid+' SEND > '+msg) self._index += 1 return [msg] except IndexError: return [] def subscribe(self,*uids): for uid in uids: if uid is not None: if uid[0] is '@': assert uid[1:] in get_attr(Uid) else: assert uid in get_attr(Uid) return self def load(self,msg_array): self._msgs += msg_array return self def set_period(self,period): self._period = period return self def run(self): t = threading.current_thread() self._pid = str(t.ident)+' '+str(t.name) while len(self.poll()) > 0: pass def run_async(self): Thread(target=self.run).start() if __name__ == '__main__': Printer('A simple printer: ').send('Just printing a msg to current_thread') script = [ '@other_uid topic data', '@other_uid topic', 'uid topic data', 'uid topic' ] async = ['async topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] async2 = ['async2 topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] Script(script).set_period(1).run() Script(async).set_period(0.15).run_async() Script(async2).set_period(0.2).run_async()<|fim▁end|>
def send(self,string):
<|file_name|>connectors_local.py<|end_file_name|><|fim▁begin|>import time from threading import Thread import threading from wtfj_ids import * from wtfj_utils import * class Printer: <|fim_middle|> class Console: ''' Allows user to enter commands ''' def __init__(self,prompt='[$] '): self._prompt = prompt self._at = '' def poll(self,wait_s=None,uid=None): try: prompt = str(self._at)+str(self._prompt) msg = raw_input(prompt) if msg == '': self._at = '' return [] if msg[0] == '@': self._at = msg.split()[0]+' ' else: msg = self._at+msg return [msg] except Exception as e: print(repr(e)) return [] def subscribe(self,*uids): pass class Script: ''' Runs a script passed as a list, default frequency = 1000Hz ''' def __init__(self,msgs): self._msgs = msgs self._index = 0 self._period = 0.001 self._pid = 'SCRIPT' def poll(self,wait_s=None,uid=None): period = self._period if wait_s is None else wait_s time.sleep(period) try: msg = self._msgs[self._index] print(self._pid+' SEND > '+msg) self._index += 1 return [msg] except IndexError: return [] def subscribe(self,*uids): for uid in uids: if uid is not None: if uid[0] is '@': assert uid[1:] in get_attr(Uid) else: assert uid in get_attr(Uid) return self def load(self,msg_array): self._msgs += msg_array return self def set_period(self,period): self._period = period return self def run(self): t = threading.current_thread() self._pid = str(t.ident)+' '+str(t.name) while len(self.poll()) > 0: pass def run_async(self): Thread(target=self.run).start() if __name__ == '__main__': Printer('A simple printer: ').send('Just printing a msg to current_thread') script = [ '@other_uid topic data', '@other_uid topic', 'uid topic data', 'uid topic' ] async = ['async topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] async2 = ['async2 topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] Script(script).set_period(1).run() Script(async).set_period(0.15).run_async() Script(async2).set_period(0.2).run_async()<|fim▁end|>
''' Opens a new output window and prints messages sent to it ''' def __init__(self,header=''): self._header = header def send(self,string): print(self._header+string)
<|file_name|>connectors_local.py<|end_file_name|><|fim▁begin|>import time from threading import Thread import threading from wtfj_ids import * from wtfj_utils import * class Printer: ''' Opens a new output window and prints messages sent to it ''' def __init__(self,header=''): <|fim_middle|> def send(self,string): print(self._header+string) class Console: ''' Allows user to enter commands ''' def __init__(self,prompt='[$] '): self._prompt = prompt self._at = '' def poll(self,wait_s=None,uid=None): try: prompt = str(self._at)+str(self._prompt) msg = raw_input(prompt) if msg == '': self._at = '' return [] if msg[0] == '@': self._at = msg.split()[0]+' ' else: msg = self._at+msg return [msg] except Exception as e: print(repr(e)) return [] def subscribe(self,*uids): pass class Script: ''' Runs a script passed as a list, default frequency = 1000Hz ''' def __init__(self,msgs): self._msgs = msgs self._index = 0 self._period = 0.001 self._pid = 'SCRIPT' def poll(self,wait_s=None,uid=None): period = self._period if wait_s is None else wait_s time.sleep(period) try: msg = self._msgs[self._index] print(self._pid+' SEND > '+msg) self._index += 1 return [msg] except IndexError: return [] def subscribe(self,*uids): for uid in uids: if uid is not None: if uid[0] is '@': assert uid[1:] in get_attr(Uid) else: assert uid in get_attr(Uid) return self def load(self,msg_array): self._msgs += msg_array return self def set_period(self,period): self._period = period return self def run(self): t = threading.current_thread() self._pid = str(t.ident)+' '+str(t.name) while len(self.poll()) > 0: pass def run_async(self): Thread(target=self.run).start() if __name__ == '__main__': Printer('A simple printer: ').send('Just printing a msg to current_thread') script = [ '@other_uid topic data', '@other_uid topic', 'uid topic data', 'uid topic' ] async = ['async topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] async2 = ['async2 topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] Script(script).set_period(1).run() Script(async).set_period(0.15).run_async() Script(async2).set_period(0.2).run_async()<|fim▁end|>
self._header = header
<|file_name|>connectors_local.py<|end_file_name|><|fim▁begin|>import time from threading import Thread import threading from wtfj_ids import * from wtfj_utils import * class Printer: ''' Opens a new output window and prints messages sent to it ''' def __init__(self,header=''): self._header = header def send(self,string): <|fim_middle|> class Console: ''' Allows user to enter commands ''' def __init__(self,prompt='[$] '): self._prompt = prompt self._at = '' def poll(self,wait_s=None,uid=None): try: prompt = str(self._at)+str(self._prompt) msg = raw_input(prompt) if msg == '': self._at = '' return [] if msg[0] == '@': self._at = msg.split()[0]+' ' else: msg = self._at+msg return [msg] except Exception as e: print(repr(e)) return [] def subscribe(self,*uids): pass class Script: ''' Runs a script passed as a list, default frequency = 1000Hz ''' def __init__(self,msgs): self._msgs = msgs self._index = 0 self._period = 0.001 self._pid = 'SCRIPT' def poll(self,wait_s=None,uid=None): period = self._period if wait_s is None else wait_s time.sleep(period) try: msg = self._msgs[self._index] print(self._pid+' SEND > '+msg) self._index += 1 return [msg] except IndexError: return [] def subscribe(self,*uids): for uid in uids: if uid is not None: if uid[0] is '@': assert uid[1:] in get_attr(Uid) else: assert uid in get_attr(Uid) return self def load(self,msg_array): self._msgs += msg_array return self def set_period(self,period): self._period = period return self def run(self): t = threading.current_thread() self._pid = str(t.ident)+' '+str(t.name) while len(self.poll()) > 0: pass def run_async(self): Thread(target=self.run).start() if __name__ == '__main__': Printer('A simple printer: ').send('Just printing a msg to current_thread') script = [ '@other_uid topic data', '@other_uid topic', 'uid topic data', 'uid topic' ] async = ['async topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] async2 = ['async2 topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] Script(script).set_period(1).run() Script(async).set_period(0.15).run_async() Script(async2).set_period(0.2).run_async()<|fim▁end|>
print(self._header+string)
<|file_name|>connectors_local.py<|end_file_name|><|fim▁begin|>import time from threading import Thread import threading from wtfj_ids import * from wtfj_utils import * class Printer: ''' Opens a new output window and prints messages sent to it ''' def __init__(self,header=''): self._header = header def send(self,string): print(self._header+string) class Console: <|fim_middle|> class Script: ''' Runs a script passed as a list, default frequency = 1000Hz ''' def __init__(self,msgs): self._msgs = msgs self._index = 0 self._period = 0.001 self._pid = 'SCRIPT' def poll(self,wait_s=None,uid=None): period = self._period if wait_s is None else wait_s time.sleep(period) try: msg = self._msgs[self._index] print(self._pid+' SEND > '+msg) self._index += 1 return [msg] except IndexError: return [] def subscribe(self,*uids): for uid in uids: if uid is not None: if uid[0] is '@': assert uid[1:] in get_attr(Uid) else: assert uid in get_attr(Uid) return self def load(self,msg_array): self._msgs += msg_array return self def set_period(self,period): self._period = period return self def run(self): t = threading.current_thread() self._pid = str(t.ident)+' '+str(t.name) while len(self.poll()) > 0: pass def run_async(self): Thread(target=self.run).start() if __name__ == '__main__': Printer('A simple printer: ').send('Just printing a msg to current_thread') script = [ '@other_uid topic data', '@other_uid topic', 'uid topic data', 'uid topic' ] async = ['async topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] async2 = ['async2 topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] Script(script).set_period(1).run() Script(async).set_period(0.15).run_async() Script(async2).set_period(0.2).run_async()<|fim▁end|>
''' Allows user to enter commands ''' def __init__(self,prompt='[$] '): self._prompt = prompt self._at = '' def poll(self,wait_s=None,uid=None): try: prompt = str(self._at)+str(self._prompt) msg = raw_input(prompt) if msg == '': self._at = '' return [] if msg[0] == '@': self._at = msg.split()[0]+' ' else: msg = self._at+msg return [msg] except Exception as e: print(repr(e)) return [] def subscribe(self,*uids): pass
<|file_name|>connectors_local.py<|end_file_name|><|fim▁begin|>import time from threading import Thread import threading from wtfj_ids import * from wtfj_utils import * class Printer: ''' Opens a new output window and prints messages sent to it ''' def __init__(self,header=''): self._header = header def send(self,string): print(self._header+string) class Console: ''' Allows user to enter commands ''' def __init__(self,prompt='[$] '): <|fim_middle|> def poll(self,wait_s=None,uid=None): try: prompt = str(self._at)+str(self._prompt) msg = raw_input(prompt) if msg == '': self._at = '' return [] if msg[0] == '@': self._at = msg.split()[0]+' ' else: msg = self._at+msg return [msg] except Exception as e: print(repr(e)) return [] def subscribe(self,*uids): pass class Script: ''' Runs a script passed as a list, default frequency = 1000Hz ''' def __init__(self,msgs): self._msgs = msgs self._index = 0 self._period = 0.001 self._pid = 'SCRIPT' def poll(self,wait_s=None,uid=None): period = self._period if wait_s is None else wait_s time.sleep(period) try: msg = self._msgs[self._index] print(self._pid+' SEND > '+msg) self._index += 1 return [msg] except IndexError: return [] def subscribe(self,*uids): for uid in uids: if uid is not None: if uid[0] is '@': assert uid[1:] in get_attr(Uid) else: assert uid in get_attr(Uid) return self def load(self,msg_array): self._msgs += msg_array return self def set_period(self,period): self._period = period return self def run(self): t = threading.current_thread() self._pid = str(t.ident)+' '+str(t.name) while len(self.poll()) > 0: pass def run_async(self): Thread(target=self.run).start() if __name__ == '__main__': Printer('A simple printer: ').send('Just printing a msg to current_thread') script = [ '@other_uid topic data', '@other_uid topic', 'uid topic data', 'uid topic' ] async = ['async topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] async2 = ['async2 topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] Script(script).set_period(1).run() Script(async).set_period(0.15).run_async() Script(async2).set_period(0.2).run_async()<|fim▁end|>
self._prompt = prompt self._at = ''
<|file_name|>connectors_local.py<|end_file_name|><|fim▁begin|>import time from threading import Thread import threading from wtfj_ids import * from wtfj_utils import * class Printer: ''' Opens a new output window and prints messages sent to it ''' def __init__(self,header=''): self._header = header def send(self,string): print(self._header+string) class Console: ''' Allows user to enter commands ''' def __init__(self,prompt='[$] '): self._prompt = prompt self._at = '' def poll(self,wait_s=None,uid=None): <|fim_middle|> def subscribe(self,*uids): pass class Script: ''' Runs a script passed as a list, default frequency = 1000Hz ''' def __init__(self,msgs): self._msgs = msgs self._index = 0 self._period = 0.001 self._pid = 'SCRIPT' def poll(self,wait_s=None,uid=None): period = self._period if wait_s is None else wait_s time.sleep(period) try: msg = self._msgs[self._index] print(self._pid+' SEND > '+msg) self._index += 1 return [msg] except IndexError: return [] def subscribe(self,*uids): for uid in uids: if uid is not None: if uid[0] is '@': assert uid[1:] in get_attr(Uid) else: assert uid in get_attr(Uid) return self def load(self,msg_array): self._msgs += msg_array return self def set_period(self,period): self._period = period return self def run(self): t = threading.current_thread() self._pid = str(t.ident)+' '+str(t.name) while len(self.poll()) > 0: pass def run_async(self): Thread(target=self.run).start() if __name__ == '__main__': Printer('A simple printer: ').send('Just printing a msg to current_thread') script = [ '@other_uid topic data', '@other_uid topic', 'uid topic data', 'uid topic' ] async = ['async topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] async2 = ['async2 topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] Script(script).set_period(1).run() Script(async).set_period(0.15).run_async() Script(async2).set_period(0.2).run_async()<|fim▁end|>
try: prompt = str(self._at)+str(self._prompt) msg = raw_input(prompt) if msg == '': self._at = '' return [] if msg[0] == '@': self._at = msg.split()[0]+' ' else: msg = self._at+msg return [msg] except Exception as e: print(repr(e)) return []
<|file_name|>connectors_local.py<|end_file_name|><|fim▁begin|>import time from threading import Thread import threading from wtfj_ids import * from wtfj_utils import * class Printer: ''' Opens a new output window and prints messages sent to it ''' def __init__(self,header=''): self._header = header def send(self,string): print(self._header+string) class Console: ''' Allows user to enter commands ''' def __init__(self,prompt='[$] '): self._prompt = prompt self._at = '' def poll(self,wait_s=None,uid=None): try: prompt = str(self._at)+str(self._prompt) msg = raw_input(prompt) if msg == '': self._at = '' return [] if msg[0] == '@': self._at = msg.split()[0]+' ' else: msg = self._at+msg return [msg] except Exception as e: print(repr(e)) return [] def subscribe(self,*uids): <|fim_middle|> class Script: ''' Runs a script passed as a list, default frequency = 1000Hz ''' def __init__(self,msgs): self._msgs = msgs self._index = 0 self._period = 0.001 self._pid = 'SCRIPT' def poll(self,wait_s=None,uid=None): period = self._period if wait_s is None else wait_s time.sleep(period) try: msg = self._msgs[self._index] print(self._pid+' SEND > '+msg) self._index += 1 return [msg] except IndexError: return [] def subscribe(self,*uids): for uid in uids: if uid is not None: if uid[0] is '@': assert uid[1:] in get_attr(Uid) else: assert uid in get_attr(Uid) return self def load(self,msg_array): self._msgs += msg_array return self def set_period(self,period): self._period = period return self def run(self): t = threading.current_thread() self._pid = str(t.ident)+' '+str(t.name) while len(self.poll()) > 0: pass def run_async(self): Thread(target=self.run).start() if __name__ == '__main__': Printer('A simple printer: ').send('Just printing a msg to current_thread') script = [ '@other_uid topic data', '@other_uid topic', 'uid topic data', 'uid topic' ] async = ['async topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] async2 = ['async2 topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] Script(script).set_period(1).run() Script(async).set_period(0.15).run_async() Script(async2).set_period(0.2).run_async()<|fim▁end|>
pass
<|file_name|>connectors_local.py<|end_file_name|><|fim▁begin|>import time from threading import Thread import threading from wtfj_ids import * from wtfj_utils import * class Printer: ''' Opens a new output window and prints messages sent to it ''' def __init__(self,header=''): self._header = header def send(self,string): print(self._header+string) class Console: ''' Allows user to enter commands ''' def __init__(self,prompt='[$] '): self._prompt = prompt self._at = '' def poll(self,wait_s=None,uid=None): try: prompt = str(self._at)+str(self._prompt) msg = raw_input(prompt) if msg == '': self._at = '' return [] if msg[0] == '@': self._at = msg.split()[0]+' ' else: msg = self._at+msg return [msg] except Exception as e: print(repr(e)) return [] def subscribe(self,*uids): pass class Script: <|fim_middle|> if __name__ == '__main__': Printer('A simple printer: ').send('Just printing a msg to current_thread') script = [ '@other_uid topic data', '@other_uid topic', 'uid topic data', 'uid topic' ] async = ['async topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] async2 = ['async2 topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] Script(script).set_period(1).run() Script(async).set_period(0.15).run_async() Script(async2).set_period(0.2).run_async()<|fim▁end|>
''' Runs a script passed as a list, default frequency = 1000Hz ''' def __init__(self,msgs): self._msgs = msgs self._index = 0 self._period = 0.001 self._pid = 'SCRIPT' def poll(self,wait_s=None,uid=None): period = self._period if wait_s is None else wait_s time.sleep(period) try: msg = self._msgs[self._index] print(self._pid+' SEND > '+msg) self._index += 1 return [msg] except IndexError: return [] def subscribe(self,*uids): for uid in uids: if uid is not None: if uid[0] is '@': assert uid[1:] in get_attr(Uid) else: assert uid in get_attr(Uid) return self def load(self,msg_array): self._msgs += msg_array return self def set_period(self,period): self._period = period return self def run(self): t = threading.current_thread() self._pid = str(t.ident)+' '+str(t.name) while len(self.poll()) > 0: pass def run_async(self): Thread(target=self.run).start()
<|file_name|>connectors_local.py<|end_file_name|><|fim▁begin|>import time from threading import Thread import threading from wtfj_ids import * from wtfj_utils import * class Printer: ''' Opens a new output window and prints messages sent to it ''' def __init__(self,header=''): self._header = header def send(self,string): print(self._header+string) class Console: ''' Allows user to enter commands ''' def __init__(self,prompt='[$] '): self._prompt = prompt self._at = '' def poll(self,wait_s=None,uid=None): try: prompt = str(self._at)+str(self._prompt) msg = raw_input(prompt) if msg == '': self._at = '' return [] if msg[0] == '@': self._at = msg.split()[0]+' ' else: msg = self._at+msg return [msg] except Exception as e: print(repr(e)) return [] def subscribe(self,*uids): pass class Script: ''' Runs a script passed as a list, default frequency = 1000Hz ''' def __init__(self,msgs): <|fim_middle|> def poll(self,wait_s=None,uid=None): period = self._period if wait_s is None else wait_s time.sleep(period) try: msg = self._msgs[self._index] print(self._pid+' SEND > '+msg) self._index += 1 return [msg] except IndexError: return [] def subscribe(self,*uids): for uid in uids: if uid is not None: if uid[0] is '@': assert uid[1:] in get_attr(Uid) else: assert uid in get_attr(Uid) return self def load(self,msg_array): self._msgs += msg_array return self def set_period(self,period): self._period = period return self def run(self): t = threading.current_thread() self._pid = str(t.ident)+' '+str(t.name) while len(self.poll()) > 0: pass def run_async(self): Thread(target=self.run).start() if __name__ == '__main__': Printer('A simple printer: ').send('Just printing a msg to current_thread') script = [ '@other_uid topic data', '@other_uid topic', 'uid topic data', 'uid topic' ] async = ['async topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] async2 = ['async2 topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] Script(script).set_period(1).run() Script(async).set_period(0.15).run_async() Script(async2).set_period(0.2).run_async()<|fim▁end|>
self._msgs = msgs self._index = 0 self._period = 0.001 self._pid = 'SCRIPT'
<|file_name|>connectors_local.py<|end_file_name|><|fim▁begin|>import time from threading import Thread import threading from wtfj_ids import * from wtfj_utils import * class Printer: ''' Opens a new output window and prints messages sent to it ''' def __init__(self,header=''): self._header = header def send(self,string): print(self._header+string) class Console: ''' Allows user to enter commands ''' def __init__(self,prompt='[$] '): self._prompt = prompt self._at = '' def poll(self,wait_s=None,uid=None): try: prompt = str(self._at)+str(self._prompt) msg = raw_input(prompt) if msg == '': self._at = '' return [] if msg[0] == '@': self._at = msg.split()[0]+' ' else: msg = self._at+msg return [msg] except Exception as e: print(repr(e)) return [] def subscribe(self,*uids): pass class Script: ''' Runs a script passed as a list, default frequency = 1000Hz ''' def __init__(self,msgs): self._msgs = msgs self._index = 0 self._period = 0.001 self._pid = 'SCRIPT' def poll(self,wait_s=None,uid=None): <|fim_middle|> def subscribe(self,*uids): for uid in uids: if uid is not None: if uid[0] is '@': assert uid[1:] in get_attr(Uid) else: assert uid in get_attr(Uid) return self def load(self,msg_array): self._msgs += msg_array return self def set_period(self,period): self._period = period return self def run(self): t = threading.current_thread() self._pid = str(t.ident)+' '+str(t.name) while len(self.poll()) > 0: pass def run_async(self): Thread(target=self.run).start() if __name__ == '__main__': Printer('A simple printer: ').send('Just printing a msg to current_thread') script = [ '@other_uid topic data', '@other_uid topic', 'uid topic data', 'uid topic' ] async = ['async topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] async2 = ['async2 topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] Script(script).set_period(1).run() Script(async).set_period(0.15).run_async() Script(async2).set_period(0.2).run_async()<|fim▁end|>
period = self._period if wait_s is None else wait_s time.sleep(period) try: msg = self._msgs[self._index] print(self._pid+' SEND > '+msg) self._index += 1 return [msg] except IndexError: return []
<|file_name|>connectors_local.py<|end_file_name|><|fim▁begin|>import time from threading import Thread import threading from wtfj_ids import * from wtfj_utils import * class Printer: ''' Opens a new output window and prints messages sent to it ''' def __init__(self,header=''): self._header = header def send(self,string): print(self._header+string) class Console: ''' Allows user to enter commands ''' def __init__(self,prompt='[$] '): self._prompt = prompt self._at = '' def poll(self,wait_s=None,uid=None): try: prompt = str(self._at)+str(self._prompt) msg = raw_input(prompt) if msg == '': self._at = '' return [] if msg[0] == '@': self._at = msg.split()[0]+' ' else: msg = self._at+msg return [msg] except Exception as e: print(repr(e)) return [] def subscribe(self,*uids): pass class Script: ''' Runs a script passed as a list, default frequency = 1000Hz ''' def __init__(self,msgs): self._msgs = msgs self._index = 0 self._period = 0.001 self._pid = 'SCRIPT' def poll(self,wait_s=None,uid=None): period = self._period if wait_s is None else wait_s time.sleep(period) try: msg = self._msgs[self._index] print(self._pid+' SEND > '+msg) self._index += 1 return [msg] except IndexError: return [] def subscribe(self,*uids): <|fim_middle|> def load(self,msg_array): self._msgs += msg_array return self def set_period(self,period): self._period = period return self def run(self): t = threading.current_thread() self._pid = str(t.ident)+' '+str(t.name) while len(self.poll()) > 0: pass def run_async(self): Thread(target=self.run).start() if __name__ == '__main__': Printer('A simple printer: ').send('Just printing a msg to current_thread') script = [ '@other_uid topic data', '@other_uid topic', 'uid topic data', 'uid topic' ] async = ['async topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] async2 = ['async2 topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] Script(script).set_period(1).run() Script(async).set_period(0.15).run_async() Script(async2).set_period(0.2).run_async()<|fim▁end|>
for uid in uids: if uid is not None: if uid[0] is '@': assert uid[1:] in get_attr(Uid) else: assert uid in get_attr(Uid) return self
<|file_name|>connectors_local.py<|end_file_name|><|fim▁begin|>import time from threading import Thread import threading from wtfj_ids import * from wtfj_utils import * class Printer: ''' Opens a new output window and prints messages sent to it ''' def __init__(self,header=''): self._header = header def send(self,string): print(self._header+string) class Console: ''' Allows user to enter commands ''' def __init__(self,prompt='[$] '): self._prompt = prompt self._at = '' def poll(self,wait_s=None,uid=None): try: prompt = str(self._at)+str(self._prompt) msg = raw_input(prompt) if msg == '': self._at = '' return [] if msg[0] == '@': self._at = msg.split()[0]+' ' else: msg = self._at+msg return [msg] except Exception as e: print(repr(e)) return [] def subscribe(self,*uids): pass class Script: ''' Runs a script passed as a list, default frequency = 1000Hz ''' def __init__(self,msgs): self._msgs = msgs self._index = 0 self._period = 0.001 self._pid = 'SCRIPT' def poll(self,wait_s=None,uid=None): period = self._period if wait_s is None else wait_s time.sleep(period) try: msg = self._msgs[self._index] print(self._pid+' SEND > '+msg) self._index += 1 return [msg] except IndexError: return [] def subscribe(self,*uids): for uid in uids: if uid is not None: if uid[0] is '@': assert uid[1:] in get_attr(Uid) else: assert uid in get_attr(Uid) return self def load(self,msg_array): <|fim_middle|> def set_period(self,period): self._period = period return self def run(self): t = threading.current_thread() self._pid = str(t.ident)+' '+str(t.name) while len(self.poll()) > 0: pass def run_async(self): Thread(target=self.run).start() if __name__ == '__main__': Printer('A simple printer: ').send('Just printing a msg to current_thread') script = [ '@other_uid topic data', '@other_uid topic', 'uid topic data', 'uid topic' ] async = ['async topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] async2 = ['async2 topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] Script(script).set_period(1).run() Script(async).set_period(0.15).run_async() Script(async2).set_period(0.2).run_async()<|fim▁end|>
self._msgs += msg_array return self
<|file_name|>connectors_local.py<|end_file_name|><|fim▁begin|>import time from threading import Thread import threading from wtfj_ids import * from wtfj_utils import * class Printer: ''' Opens a new output window and prints messages sent to it ''' def __init__(self,header=''): self._header = header def send(self,string): print(self._header+string) class Console: ''' Allows user to enter commands ''' def __init__(self,prompt='[$] '): self._prompt = prompt self._at = '' def poll(self,wait_s=None,uid=None): try: prompt = str(self._at)+str(self._prompt) msg = raw_input(prompt) if msg == '': self._at = '' return [] if msg[0] == '@': self._at = msg.split()[0]+' ' else: msg = self._at+msg return [msg] except Exception as e: print(repr(e)) return [] def subscribe(self,*uids): pass class Script: ''' Runs a script passed as a list, default frequency = 1000Hz ''' def __init__(self,msgs): self._msgs = msgs self._index = 0 self._period = 0.001 self._pid = 'SCRIPT' def poll(self,wait_s=None,uid=None): period = self._period if wait_s is None else wait_s time.sleep(period) try: msg = self._msgs[self._index] print(self._pid+' SEND > '+msg) self._index += 1 return [msg] except IndexError: return [] def subscribe(self,*uids): for uid in uids: if uid is not None: if uid[0] is '@': assert uid[1:] in get_attr(Uid) else: assert uid in get_attr(Uid) return self def load(self,msg_array): self._msgs += msg_array return self def set_period(self,period): <|fim_middle|> def run(self): t = threading.current_thread() self._pid = str(t.ident)+' '+str(t.name) while len(self.poll()) > 0: pass def run_async(self): Thread(target=self.run).start() if __name__ == '__main__': Printer('A simple printer: ').send('Just printing a msg to current_thread') script = [ '@other_uid topic data', '@other_uid topic', 'uid topic data', 'uid topic' ] async = ['async topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] async2 = ['async2 topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] Script(script).set_period(1).run() Script(async).set_period(0.15).run_async() Script(async2).set_period(0.2).run_async()<|fim▁end|>
self._period = period return self
<|file_name|>connectors_local.py<|end_file_name|><|fim▁begin|>import time from threading import Thread import threading from wtfj_ids import * from wtfj_utils import * class Printer: ''' Opens a new output window and prints messages sent to it ''' def __init__(self,header=''): self._header = header def send(self,string): print(self._header+string) class Console: ''' Allows user to enter commands ''' def __init__(self,prompt='[$] '): self._prompt = prompt self._at = '' def poll(self,wait_s=None,uid=None): try: prompt = str(self._at)+str(self._prompt) msg = raw_input(prompt) if msg == '': self._at = '' return [] if msg[0] == '@': self._at = msg.split()[0]+' ' else: msg = self._at+msg return [msg] except Exception as e: print(repr(e)) return [] def subscribe(self,*uids): pass class Script: ''' Runs a script passed as a list, default frequency = 1000Hz ''' def __init__(self,msgs): self._msgs = msgs self._index = 0 self._period = 0.001 self._pid = 'SCRIPT' def poll(self,wait_s=None,uid=None): period = self._period if wait_s is None else wait_s time.sleep(period) try: msg = self._msgs[self._index] print(self._pid+' SEND > '+msg) self._index += 1 return [msg] except IndexError: return [] def subscribe(self,*uids): for uid in uids: if uid is not None: if uid[0] is '@': assert uid[1:] in get_attr(Uid) else: assert uid in get_attr(Uid) return self def load(self,msg_array): self._msgs += msg_array return self def set_period(self,period): self._period = period return self def run(self): <|fim_middle|> def run_async(self): Thread(target=self.run).start() if __name__ == '__main__': Printer('A simple printer: ').send('Just printing a msg to current_thread') script = [ '@other_uid topic data', '@other_uid topic', 'uid topic data', 'uid topic' ] async = ['async topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] async2 = ['async2 topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] Script(script).set_period(1).run() Script(async).set_period(0.15).run_async() Script(async2).set_period(0.2).run_async()<|fim▁end|>
t = threading.current_thread() self._pid = str(t.ident)+' '+str(t.name) while len(self.poll()) > 0: pass
<|file_name|>connectors_local.py<|end_file_name|><|fim▁begin|>import time from threading import Thread import threading from wtfj_ids import * from wtfj_utils import * class Printer: ''' Opens a new output window and prints messages sent to it ''' def __init__(self,header=''): self._header = header def send(self,string): print(self._header+string) class Console: ''' Allows user to enter commands ''' def __init__(self,prompt='[$] '): self._prompt = prompt self._at = '' def poll(self,wait_s=None,uid=None): try: prompt = str(self._at)+str(self._prompt) msg = raw_input(prompt) if msg == '': self._at = '' return [] if msg[0] == '@': self._at = msg.split()[0]+' ' else: msg = self._at+msg return [msg] except Exception as e: print(repr(e)) return [] def subscribe(self,*uids): pass class Script: ''' Runs a script passed as a list, default frequency = 1000Hz ''' def __init__(self,msgs): self._msgs = msgs self._index = 0 self._period = 0.001 self._pid = 'SCRIPT' def poll(self,wait_s=None,uid=None): period = self._period if wait_s is None else wait_s time.sleep(period) try: msg = self._msgs[self._index] print(self._pid+' SEND > '+msg) self._index += 1 return [msg] except IndexError: return [] def subscribe(self,*uids): for uid in uids: if uid is not None: if uid[0] is '@': assert uid[1:] in get_attr(Uid) else: assert uid in get_attr(Uid) return self def load(self,msg_array): self._msgs += msg_array return self def set_period(self,period): self._period = period return self def run(self): t = threading.current_thread() self._pid = str(t.ident)+' '+str(t.name) while len(self.poll()) > 0: pass def run_async(self): <|fim_middle|> if __name__ == '__main__': Printer('A simple printer: ').send('Just printing a msg to current_thread') script = [ '@other_uid topic data', '@other_uid topic', 'uid topic data', 'uid topic' ] async = ['async topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] async2 = ['async2 topic '+str(n) for n in [1,2,3,4,5,6,7,8,9,0]] Script(script).set_period(1).run() Script(async).set_period(0.15).run_async() Script(async2).set_period(0.2).run_async()<|fim▁end|>
Thread(target=self.run).start()