branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>suvarnagupta/Data_classification_model<file_sep>/data_classification_model.py #!/usr/bin/env python # coding: utf-8 # ## Data Classification # In[1]: ## for system import sys import os ## for data import pandas as pd import numpy as np ## for plotting import matplotlib.pyplot as plt import seaborn as sns ## for statistical tests import scipy import statsmodels.formula.api as smf import statsmodels.api as sm ## for machine learning from sklearn import model_selection, preprocessing, feature_selection, ensemble, linear_model, metrics, decomposition import sklearn as sk from sklearn.preprocessing import LabelEncoder # In[2]: data = pd.read_csv(r'C:\Users\dell\Desktop\CC\DS_DATESET.xlsx') #data = pd.read_csv(sys.argv[1], header=0) data.head() # In[3]: def utils_recognize_type(data, col, max_cat=20): if (data[col].dtype == "O") | (data[col].nunique() < max_cat): return "cat" else: return "num" # In[4]: max_cat=20 dic_cols = {col:utils_recognize_type(data, col,max_cat=max_cat) for col in data.columns} heatmap = data.isnull() for k,v in dic_cols.items(): if v == "num": heatmap[k] = heatmap[k].apply(lambda x: 0.5 if x is False else 1) else: heatmap[k] = heatmap[k].apply(lambda x: 0 if x is False else 1) sns.heatmap(heatmap, cbar=False) plt.title('Dataset Overview') #plt.show() #print("\033[1;37;40m Categerocial ", "\033[1;30;41m Numeric ", "\033[1;30;47m NaN ") # In[5]: data = data.rename(columns={'Rate your verbal communication skills [1-10]':'Verbalcommskills','Rate your written communication skills [1-10]':'Writtencommskills','DOB [DD/MM/YYYY]':'DOB','How Did You Hear About This Internship?':'HearAbInternship','Programming Language Known other than Java (one major)':'OneMajorProglang','Which-year are you studying in?':'YearOfstudy','Major/Area of Study':'AreaOfstudy','CGPA/ percentage':'CGPA','Expected Graduation-year':'ExpGradYear','Zip Code':'ZipCode','First Name':'Fname','Last Name':'Lname','Email Address':'EmailId','College name':'ClgName','University Name':'UniName','Course Type':'CourseType','Areas of interest':'AreasOfInterest','Current Employment Status':'CurrentEmployStatus','Have you worked core Java':'WorkedCoreJava','Have you worked on MySQL or Oracle database':'WorkedMySQL','Have you studied OOP Concepts':'StudiedOOPConcepts'}) #data.info() # In[6]: data = data.rename(columns={"Label":"Y"}) # In[7]: y = "Y" ax = data[y].value_counts().sort_values().plot(kind="barh") totals= [] for i in ax.patches: totals.append(i.get_width()) total = sum(totals) for i in ax.patches: ax.text(i.get_width()+.3, i.get_y()+.20, str(round((i.get_width()/total)*100, 2))+'%', fontsize=10, color='black') ax.grid(axis="x") plt.suptitle(y, fontsize=20) #plt.show() # In[8]: cat, num = "Y", "Verbalcommskills" fig_dim = (10,5) fig, ax = plt.subplots(nrows=1, ncols=3, sharex=False, sharey=False, figsize=fig_dim) fig.suptitle("Rate your verbal communication skills vs Y", fontsize=10) ### distribution ax[0].title.set_text('density') for i in data[cat].unique(): sns.distplot(data[data[cat]==i][num], hist=False, label=i, ax=ax[0]) ax[0].grid(True) ### stacked ax[1].title.set_text('bins') breaks = np.quantile(data[num], q=np.linspace(0,1,20)) tmp = data.groupby([cat, pd.cut(data[num], breaks, duplicates='drop')]).size().unstack().T tmp = tmp[data[cat].unique()] tmp["tot"] = tmp.sum(axis=1) for col in tmp.drop("tot", axis=1).columns: tmp[col] = tmp[col] / tmp["tot"] tmp.drop("tot", axis=1).plot(kind='bar', stacked=True, ax=ax[1], legend=False, grid=True) ### boxplot ax[2].title.set_text('outliers') sns.boxplot(x=cat, y=num, data=data, ax=ax[2]) ax[2].grid(True) #plt.show() # In[9]: cat, num = "Y", "Writtencommskills" fig_dim = (10,5) fig, ax = plt.subplots(nrows=1, ncols=3, sharex=False, sharey=False, figsize=fig_dim) fig.suptitle("Rate your written communication skills vs Y", fontsize=10) ### distribution ax[0].title.set_text('density') for i in data[cat].unique(): sns.distplot(data[data[cat]==i][num], hist=False, label=i, ax=ax[0]) ax[0].grid(True) ### stacked ax[1].title.set_text('bins') breaks = np.quantile(data[num], q=np.linspace(0,1,20)) tmp = data.groupby([cat, pd.cut(data[num], breaks, duplicates='drop')]).size().unstack().T tmp = tmp[data[cat].unique()] tmp["tot"] = tmp.sum(axis=1) for col in tmp.drop("tot", axis=1).columns: tmp[col] = tmp[col] / tmp["tot"] tmp.drop("tot", axis=1).plot(kind='bar', stacked=True, ax=ax[1], legend=False, grid=True) ### boxplot ax[2].title.set_text('outliers') sns.boxplot(x=cat, y=num, data=data, ax=ax[2]) ax[2].grid(True) #plt.show() # In[15]: cat, num = "Y", "Age" model = smf.ols(num+' ~ '+cat, data=data).fit() table = sm.stats.anova_lm(model) p = table["PR(>F)"][0] coeff, p = None, round(p, 3) conclusion = "Correlated" if p < 0.05 else "Non-Correlated" pvalue = str(p) # In[16]: cat, num = "Y", "Writtencommskills" model = smf.ols(num+' ~ '+cat, data=data).fit() table = sm.stats.anova_lm(model) p = table["PR(>F)"][0] coeff, p = None, round(p, 3) conclusion = "Correlated" if p < 0.05 else "Non-Correlated" pvalue = str(p) # In[17]: cat, num = "Y", "Verbalcommskills" model = smf.ols(num+' ~ '+cat, data=data).fit() table = sm.stats.anova_lm(model) p = table["PR(>F)"][0] coeff, p = None, round(p, 3) conclusion = "Correlated" if p < 0.05 else "Non-Correlated" pvalue = str(p) # In[18]: cat, num = "Y", "CGPA" model = smf.ols(num+' ~ '+cat, data=data).fit() table = sm.stats.anova_lm(model) p = table["PR(>F)"][0] coeff, p = None, round(p, 3) conclusion = "Correlated" if p < 0.05 else "Non-Correlated" pvalue = str(p) # In[19]: cat, num = "Y", "ExpGradYear" model = smf.ols(num+' ~ '+cat, data=data).fit() table = sm.stats.anova_lm(model) p = table["PR(>F)"][0] coeff, p = None, round(p, 3) conclusion = "Correlated" if p < 0.05 else "Non-Correlated" pvalue = str(p) # In[20]: cat, num = "Y", "ZipCode" model = smf.ols(num+' ~ '+cat, data=data).fit() table = sm.stats.anova_lm(model) p = table["PR(>F)"][0] coeff, p = None, round(p, 3) conclusion = "Correlated" if p < 0.05 else "Non-Correlated" pvalue = str(p) # In[21]: x, y = "City", "Y" cont_table = pd.crosstab(index=data[x], columns=data[y]) chi2_test = scipy.stats.chi2_contingency(cont_table) chi2, p = chi2_test[0], chi2_test[1] n = cont_table.sum().sum() phi2 = chi2/n r,k = cont_table.shape phi2corr = max(0, phi2-((k-1)*(r-1))/(n-1)) rcorr = r-((r-1)**2)/(n-1) kcorr = k-((k-1)**2)/(n-1) coeff = np.sqrt(phi2corr/min((kcorr-1), (rcorr-1))) coeff, p = round(coeff, 3), round(p, 3) conclusion = "Significant" if p < 0.05 else "Non-Significant" pvalue = str(p) # In[22]: x, y = "AreasOfInterest", "Y" cont_table = pd.crosstab(index=data[x], columns=data[y]) chi2_test = scipy.stats.chi2_contingency(cont_table) chi2, p = chi2_test[0], chi2_test[1] n = cont_table.sum().sum() phi2 = chi2/n r,k = cont_table.shape phi2corr = max(0, phi2-((k-1)*(r-1))/(n-1)) rcorr = r-((r-1)**2)/(n-1) kcorr = k-((k-1)**2)/(n-1) coeff = np.sqrt(phi2corr/min((kcorr-1), (rcorr-1))) coeff, p = round(coeff, 3), round(p, 3) conclusion = "Significant" if p < 0.05 else "Non-Significant" pvalue = str(p) # In[23]: x, y = "OneMajorProglang", "Y" cont_table = pd.crosstab(index=data[x], columns=data[y]) chi2_test = scipy.stats.chi2_contingency(cont_table) chi2, p = chi2_test[0], chi2_test[1] n = cont_table.sum().sum() phi2 = chi2/n r,k = cont_table.shape phi2corr = max(0, phi2-((k-1)*(r-1))/(n-1)) rcorr = r-((r-1)**2)/(n-1) kcorr = k-((k-1)**2)/(n-1) coeff = np.sqrt(phi2corr/min((kcorr-1), (rcorr-1))) coeff, p = round(coeff, 3), round(p, 3) conclusion = "Significant" if p < 0.05 else "Non-Significant" pvalue = str(p) # In[24]: x, y = "YearOfstudy", "Y" cont_table = pd.crosstab(index=data[x], columns=data[y]) chi2_test = scipy.stats.chi2_contingency(cont_table) chi2, p = chi2_test[0], chi2_test[1] n = cont_table.sum().sum() phi2 = chi2/n r,k = cont_table.shape phi2corr = max(0, phi2-((k-1)*(r-1))/(n-1)) rcorr = r-((r-1)**2)/(n-1) kcorr = k-((k-1)**2)/(n-1) coeff = np.sqrt(phi2corr/min((kcorr-1), (rcorr-1))) coeff, p = round(coeff, 3), round(p, 3) conclusion = "Significant" if p < 0.05 else "Non-Significant" pvalue = str(p) # In[25]: x, y = "ClgName", "Y" cont_table = pd.crosstab(index=data[x], columns=data[y]) chi2_test = scipy.stats.chi2_contingency(cont_table) chi2, p = chi2_test[0], chi2_test[1] n = cont_table.sum().sum() phi2 = chi2/n r,k = cont_table.shape phi2corr = max(0, phi2-((k-1)*(r-1))/(n-1)) rcorr = r-((r-1)**2)/(n-1) kcorr = k-((k-1)**2)/(n-1) coeff = np.sqrt(phi2corr/min((kcorr-1), (rcorr-1))) coeff, p = round(coeff, 3), round(p, 3) conclusion = "Significant" if p < 0.05 else "Non-Significant" pvalue = str(p) # In[26]: x, y = "Degree", "Y" cont_table = pd.crosstab(index=data[x], columns=data[y]) chi2_test = scipy.stats.chi2_contingency(cont_table) chi2, p = chi2_test[0], chi2_test[1] n = cont_table.sum().sum() phi2 = chi2/n r,k = cont_table.shape phi2corr = max(0, phi2-((k-1)*(r-1))/(n-1)) rcorr = r-((r-1)**2)/(n-1) kcorr = k-((k-1)**2)/(n-1) coeff = np.sqrt(phi2corr/min((kcorr-1), (rcorr-1))) coeff, p = round(coeff, 3), round(p, 3) conclusion = "Significant" if p < 0.05 else "Non-Significant" pvalue = str(p) # In[22]: data['Y'] = data['Y'].replace('ineligible',0) data['Y'] = data['Y'].replace('eligible',1) # In[23]: ## split data data_train, data_test = model_selection.train_test_split(data, test_size=0.3) ## print info #print("X_train shape:", data_train.drop("Y",axis=1).shape, "| X_test shape:", data_test.drop("Y",axis=1).shape) #print("y_train mean:", round(np.mean(data_train["Y"]),2), "| y_test mean:", round(np.mean(data_test["Y"]),2)) #print(data_train.shape[1], "features:", data_train.drop("Y",axis=1).columns.to_list()) # In[24]: data_train = data_train.dropna(axis=1) # In[25]: data_train.isna() # In[26]: ## create dummy dummy = pd.get_dummies(data_train["AreaOfstudy"], prefix="AreaOfstudy") data_train= pd.concat([data_train, dummy], axis=1) #print( data_train.filter(like="AreaOfstudy", axis=1).head() ) ## drop the original categorical column data_train = data_train.drop("AreaOfstudy", axis=1) data_train.head() # In[27]: ## create dummy dummy = pd.get_dummies(data_train["Gender"], prefix="Gender") data_train= pd.concat([data_train, dummy], axis=1) #print( data_train.filter(like="Gender", axis=1).head()) ## drop the original categorical column data_train = data_train.drop("Gender", axis=1) data_train.head() # In[28]: ## create dummy '''dummy = pd.get_dummies(data_train["Degree"], prefix="Degree") data_train= pd.concat([data_train, dummy], axis=1) print( data_train.filter(like="Degree", axis=1).head() ) ## drop the original categorical column data_train = data_train.drop("Degree", axis=1) data_train.head()''' # Label Encode instead of dummy variables mappings = [] from sklearn.preprocessing import LabelEncoder label_encoder = LabelEncoder() data_train = data_train.drop('Degree', axis=1) for i, col in enumerate(data_train): if data_train[col].dtype == 'object': data_train[col] = label_encoder.fit_transform(np.array(data_train[col].astype(str)).reshape((-1,))) mappings.append(dict(zip(label_encoder.classes_, range(1, len(label_encoder.classes_)+1)))) # In[29]: ## create dummy dummy = pd.get_dummies(data_train["AreasOfInterest"], prefix="AreasOfInterest") data_train= pd.concat([data_train, dummy], axis=1) #print( data_train.filter(like="AreasOfInterest", axis=1).head()) ## drop the original categorical column data_train = data_train.drop("AreasOfInterest", axis=1) data_train.head() # In[30]: data_train.info() # In[31]: ## create dummy dummy = pd.get_dummies(data_train["HearAbInternship"], prefix="HearAbInternship") data_train= pd.concat([data_train, dummy], axis=1) #print( data_train.filter(like="HearAbInternship", axis=1).head()) ## drop the original categorical column data_train = data_train.drop("HearAbInternship", axis=1) data_train.head() # In[32]: #data_train.info() # In[33]: ## create dummy dummy = pd.get_dummies(data_train["OneMajorProglang"], prefix="OneMajorProglang") data_train= pd.concat([data_train, dummy], axis=1) #print( data_train.filter(like="OneMajorProglang", axis=1).head()) ## drop the original categorical column data_train = data_train.drop("OneMajorProglang", axis=1) data_train.head() # In[34]: ## create dummy dummy = pd.get_dummies(data_train["City"], prefix="City") data_train= pd.concat([data_train, dummy], axis=1) #print( data_train.filter(like="City", axis=1).head()) ## drop the original categorical column data_train = data_train.drop("City", axis=1) data_train.head() # In[35]: data_train = data_train.reset_index() data_train.head() # In[36]: data_train['YearOfstudy'].value_counts() # In[37]: #le=LabelEncoder() #le.fit_transform(['First-year','Second-year','Third-year','Fourth-year']) #data_train['YearOfstudy'] = data_train['YearOfstudy'].map({'First-year': 1,'Second-year': 2,'Third-year': 3,'Fourth-year': 4}) # In[38]: data_train.head() # In[39]: data_train = data_train.drop(['Fname','Lname','State','ZipCode','DOB','EmailId','Contact Number','Emergency Contact Number','UniName','CourseType','CurrentEmployStatus','WorkedMySQL','StudiedOOPConcepts','index'], axis=1) data_train.head() # In[40]: #le=LabelEncoder() #le.fit_transform(['No','Yes']) #data_train['WorkedCoreJava'] = data_train['WorkedCoreJava'].map({'No': 0,'Yes': 1}) #data_train.head() # In[41]: data_train['ClgName'].value_counts() # In[42]: data_train = data_train.drop(['ClgName'], axis=1) # In[43]: data_train.head() # In[44]: scaler = preprocessing.MinMaxScaler(feature_range=(0,1)) X = scaler.fit_transform(data_train.drop("Y", axis=1)) data_scaled= pd.DataFrame(X, columns=data_train.drop("Y", axis=1).columns, index=data_train.index) data_scaled["Y"] = data_train["Y"] data_scaled.head() # In[45]: corr_matrix = data.copy() for col in corr_matrix.columns: if corr_matrix[col].dtype == "O": corr_matrix[col] = corr_matrix[col].factorize(sort=True)[0] corr_matrix = corr_matrix.corr(method="pearson") sns.heatmap(corr_matrix, vmin=-1., vmax=1., annot=True, fmt='.2f', cmap="YlGnBu", cbar=True, linewidths=0.5) plt.title("pearson correlation") # In[46]: X = data_train.drop("Y", axis=1).values y = data_train["Y"].values feature_names = data_train.drop("Y", axis=1).columns ## Anova selector = feature_selection.SelectKBest(score_func= feature_selection.f_classif, k=10).fit(X,y) anova_selected_features = feature_names[selector.get_support()] ## Lasso regularization selector = feature_selection.SelectFromModel(estimator= linear_model.LogisticRegression(C=1, penalty="l1", solver='liblinear'), max_features=10).fit(X,y) lasso_selected_features = feature_names[selector.get_support()] ## Plot fig_dims = (10, 10) fig, ax = plt.subplots(figsize=fig_dims) data_features = pd.DataFrame({"features":feature_names}) data_features["anova"] = data_features["features"].apply(lambda x: "anova" if x in anova_selected_features else "") data_features["num1"] = data_features["features"].apply(lambda x: 1 if x in anova_selected_features else 0) data_features["lasso"] = data_features["features"].apply(lambda x: "lasso" if x in lasso_selected_features else "") data_features["num2"] = data_features["features"].apply(lambda x: 1 if x in lasso_selected_features else 0) data_features["method"] = data_features[["anova","lasso"]].apply(lambda x: (x[0]+" "+x[1]).strip(), axis=1) data_features["selection"] = data_features["num1"] + data_features["num2"] #sns.barplot(y="features", x="selection", hue="method", data=data_features.sort_values("selection", ascending=False), dodge=False, ax=ax) # In[47]: X = data_train.drop("Y", axis=1).values y = data_train["Y"].values feature_names = data_train.drop("Y", axis=1).columns.tolist() ## Importance model = ensemble.RandomForestClassifier(n_estimators=100, criterion="entropy", random_state=0) model.fit(X,y) importances = model.feature_importances_ ## Put in a pandas dtf data_importances = pd.DataFrame({"IMPORTANCE":importances, "VARIABLE":feature_names}).sort_values("IMPORTANCE", ascending=False) data_importances['cumsum'] = data_importances['IMPORTANCE'].cumsum(axis=0) data_importances = data_importances.set_index("VARIABLE") ## Plot fig_dim=(30,15) fig, ax = plt.subplots(nrows=1, ncols=2, sharex=False, sharey=False, figsize=fig_dim) fig.suptitle("Features Importance", fontsize=30) ax[0].title.set_text('variables') data_importances[["IMPORTANCE"]].sort_values(by="IMPORTANCE").plot(kind="barh", legend=False, ax=ax[0]).grid(axis="x") ax[0].set(ylabel="") ax[1].title.set_text('cumulative') data_importances[["cumsum"]].plot(kind="line", linewidth=4, legend=False, ax=ax[1]) ax[1].set(xlabel="", xticks=np.arange(len(data_importances)), xticklabels=data_importances.index) plt.xticks(rotation=70) plt.grid(axis='both') #plt.show() # In[48]: data_test = data_test.dropna(axis=1) # In[49]: data_test.isna() # In[50]: ## create dummy dummy = pd.get_dummies(data_test["AreaOfstudy"], prefix="AreaOfstudy") data_test= pd.concat([data_test, dummy], axis=1) #print( data_test.filter(like="AreaOfstudy", axis=1).head() ) ## drop the original categorical column data_test = data_test.drop("AreaOfstudy", axis=1) data_test.head() # In[51]: ## create dummy dummy = pd.get_dummies(data_test["Gender"], prefix="Gender") data_test= pd.concat([data_test, dummy], axis=1) #print( data_test.filter(like="Gender", axis=1).head()) ## drop the original categorical column data_test = data_test.drop("Gender", axis=1) data_test.head() # In[52]: ## create dummy '''dummy = pd.get_dummies(data_test["Degree"], prefix="Degree") data_test= pd.concat([data_test, dummy], axis=1) print( data_test.filter(like="Degree", axis=1).head() ) ## drop the original categorical column data_test = data_test.drop("Degree", axis=1) data_test.head()''' # Label Encode instead of dummy variables mappings = [] from sklearn.preprocessing import LabelEncoder label_encoder = LabelEncoder() data_test = data_test.drop('Degree', axis=1) for i, col in enumerate(data_test): if data_test[col].dtype == 'object': data_test[col] = label_encoder.fit_transform(np.array(data_test[col].astype(str)).reshape((-1,))) mappings.append(dict(zip(label_encoder.classes_, range(1, len(label_encoder.classes_)+1)))) # In[53]: ## create dummy dummy = pd.get_dummies(data_test["AreasOfInterest"], prefix="AreasOfInterest") data_test= pd.concat([data_test, dummy], axis=1) #print( data_test.filter(like="AreasOfInterest", axis=1).head()) ## drop the original categorical column data_test = data_test.drop("AreasOfInterest", axis=1) data_test.head() # In[54]: #data_test.info() # In[55]: ## create dummy dummy = pd.get_dummies(data_test["HearAbInternship"], prefix="HearAbInternship") data_test = pd.concat([data_test, dummy], axis=1) #print( data_test.filter(like="HearAbInternship", axis=1).head()) ## drop the original categorical column data_test = data_test.drop("HearAbInternship", axis=1) data_test.head() # In[165]: ## create dummy dummy = pd.get_dummies(data_test["OneMajorProglang"], prefix="OneMajorProglang") data_test= pd.concat([data_test, dummy], axis=1) #print( data_test.filter(like="OneMajorProglang", axis=1).head()) ## drop the original categorical column data_test = data_test.drop("OneMajorProglang", axis=1) data_test.head() # In[57]: ## create dummy dummy = pd.get_dummies(data_test["City"], prefix="City") data_test= pd.concat([data_test, dummy], axis=1) #print( data_test.filter(like="City", axis=1).head()) ## drop the original categorical column data_test = data_test.drop("City", axis=1) data_test.head() # In[58]: data_test = data_test.reset_index() data_test.head() # In[59]: #le=LabelEncoder() #le.fit_transform(['First-year','Second-year','Third-year','Fourth-year']) #data_test['YearOfstudy'] = data_test['YearOfstudy'].map({'First-year': 1,'Second-year': 2,'Third-year': 3,'Fourth-year': 4}) # In[60]: data_test = data_test.drop(['Fname','Lname','State','ZipCode','DOB','EmailId','Contact Number','Emergency Contact Number','UniName','CourseType','CurrentEmployStatus','WorkedMySQL','StudiedOOPConcepts','index','ClgName'], axis=1) data_test.head() # In[61]: #le=LabelEncoder() #le.fit_transform(['No','Yes']) #data_test['WorkedCoreJava'] = data_test['WorkedCoreJava'].map({'No': 0,'Yes': 1}) #data_test.head() # In[62]: scaler = preprocessing.MinMaxScaler(feature_range=(0,1)) X = scaler.fit_transform(data_test.drop("Y", axis=1)) data_scaled= pd.DataFrame(X, columns=data_test.drop("Y", axis=1).columns, index=data_test.index) data_scaled["Y"] = data_test["Y"] data_scaled.head() # In[63]: corr_matrix = data.copy() for col in corr_matrix.columns: if corr_matrix[col].dtype == "O": corr_matrix[col] = corr_matrix[col].factorize(sort=True)[0] corr_matrix = corr_matrix.corr(method="pearson") #sns.heatmap(corr_matrix, vmin=-1., vmax=1., annot=True, fmt='.2f', cmap="YlGnBu", cbar=True, linewidths=0.5) plt.title("pearson correlation") # In[64]: X = data_test.drop("Y", axis=1).values y = data_test["Y"].values feature_names = data_test.drop("Y", axis=1).columns ## Anova selector = feature_selection.SelectKBest(score_func= feature_selection.f_classif, k=10).fit(X,y) anova_selected_features = feature_names[selector.get_support()] ## Lasso regularization selector = feature_selection.SelectFromModel(estimator= linear_model.LogisticRegression(C=1, penalty="l1", solver='liblinear'), max_features=10).fit(X,y) lasso_selected_features = feature_names[selector.get_support()] ## Plot fig_dims = (10, 10) fig, ax = plt.subplots(figsize=fig_dims) data_features = pd.DataFrame({"features":feature_names}) data_features["anova"] = data_features["features"].apply(lambda x: "anova" if x in anova_selected_features else "") data_features["num1"] = data_features["features"].apply(lambda x: 1 if x in anova_selected_features else 0) data_features["lasso"] = data_features["features"].apply(lambda x: "lasso" if x in lasso_selected_features else "") data_features["num2"] = data_features["features"].apply(lambda x: 1 if x in lasso_selected_features else 0) data_features["method"] = data_features[["anova","lasso"]].apply(lambda x: (x[0]+" "+x[1]).strip(), axis=1) data_features["selection"] = data_features["num1"] + data_features["num2"] sns.barplot(y="features", x="selection", hue="method", data=data_features.sort_values("selection", ascending=False), dodge=False, ax=ax) # In[65]: X = data_test.drop("Y", axis=1).values y = data_test["Y"].values feature_names = data_test.drop("Y", axis=1).columns.tolist() ## Importance model = ensemble.RandomForestClassifier(n_estimators=100, criterion="entropy", random_state=0) model.fit(X,y) importances = model.feature_importances_ ## Put in a pandas dtf data_importances = pd.DataFrame({"IMPORTANCE":importances, "VARIABLE":feature_names}).sort_values("IMPORTANCE", ascending=False) data_importances['cumsum'] = data_importances['IMPORTANCE'].cumsum(axis=0) data_importances = data_importances.set_index("VARIABLE") ## Plot fig_dim=(30,15) fig, ax = plt.subplots(nrows=1, ncols=2, sharex=False, sharey=False, figsize=fig_dim) fig.suptitle("Features Importance", fontsize=30) ax[0].title.set_text('variables') data_importances[["IMPORTANCE"]].sort_values(by="IMPORTANCE").plot(kind="barh", legend=False, ax=ax[0]).grid(axis="x") ax[0].set(ylabel="") ax[1].title.set_text('cumulative') data_importances[["cumsum"]].plot(kind="line", linewidth=4, legend=False, ax=ax[1]) ax[1].set(xlabel="", xticks=np.arange(len(data_importances)), xticklabels=data_importances.index) plt.xticks(rotation=70) plt.grid(axis='both') #plt.show() # In[156]: #X_names = ["Age", "Writtencommskills", "Verbalcommskills", "CGPA", "ExpGradYear", "YearOfstudy",'WorkedCoreJava','AreasOfInterest_IoT','AreaOfstudy_Computer Engineering'] #X_names = data_train.reindex(columns=X_names) #X_train = data_train[X_names].values #y_train = data_train["Y"].values #X_test = data_test[X_names].values #y_test = data_test["Y"].values X_names = ["Age", "Writtencommskills", "Verbalcommskills", "CGPA", "ExpGradYear", "YearOfstudy",'WorkedCoreJava','AreaOfstudy_Computer Engineering','Gender_Female','City_2','AreasOfInterest_0','HearAbInternship_7'] X_train = data_train[X_names].values y_train = data_train["Y"].values X_test = data_test[X_names].values y_test = data_test["Y"].values # In[157]: import numpy as np cv = model_selection.StratifiedKFold(n_splits=10, shuffle=True) tprs, aucs = [], [] mean_fpr = np.linspace(0,1,100) fig = plt.figure() i = 1 for train, test in cv.split(X_train, y_train): prediction = model.fit(X_train[train],y_train[train]).predict_proba(X_train[test]) fpr, tpr, t = metrics.roc_curve(y_train[test], prediction[:, 1]) tprs.append(np.interp(mean_fpr, fpr, tpr)) roc_auc = metrics.auc(fpr, tpr) aucs.append(roc_auc) plt.plot(fpr, tpr, lw=2, alpha=0.3, label='ROC fold %d (AUC = %0.2f)' % (i, roc_auc)) i = i+1 plt.plot([0,1], [0,1], linestyle='--', lw=2, color='black') mean_tpr = np.mean(tprs, axis=0) mean_auc = metrics.auc(mean_fpr, mean_tpr) plt.plot(mean_fpr, mean_tpr, color='blue', label=r'Mean ROC (AUC = %0.2f )' % (mean_auc), lw=2, alpha=1) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('K-Fold Validation') plt.legend(loc="lower right") plt.show() # In[158]: ## train model.fit(X_train, y_train) ## test predicted_prob = model.predict_proba(X_test)[:,1] predicted = model.predict(X_test) # In[159]: classes = np.unique(y_test) fig, ax = plt.subplots() cm = metrics.confusion_matrix(y_test, predicted, labels=classes) sns.heatmap(cm, annot=True, fmt='d', cmap=plt.cm.Blues, cbar=False) ax.set(xlabel="Pred", ylabel="True", title="Confusion matrix") ax.set_yticklabels(labels=classes, rotation=0) #plt.show() # In[160]: #print("True:", y_test[40], "--> Pred:", predicted[40], "| Prob:", np.max(predicted_prob[40])) # In[161]: ## for explainer from lime import lime_tabular explainer = lime_tabular.LimeTabularExplainer(training_data=X_train, feature_names=X_names, class_names=np.unique(y_train), mode="classification") explained = explainer.explain_instance(X_test[4], model.predict_proba, num_features=10) explained.as_pyplot_figure() # In[162]: from sklearn import svm #Create a svm Classifier clf = svm.SVC(kernel='linear') # Linear Kernel #Train the model using the training sets clf.fit(X_train, y_train) #Predict the response for test dataset y_pred = clf.predict(X_test) # In[163]: #Import scikit-learn metrics module for accuracy calculation from sklearn import metrics # Model Accuracy print(metrics.accuracy_score(y_test, y_pred)) # In[164]: # Model Precision: what percentage of positive tuples are labeled as such? precision = metrics.precision_score(y_test, y_pred) # Model Recall: what percentage of positive tuples are labelled as such? recall = metrics.recall_score(y_test, y_pred) F1 = 2 * (precision * recall) / (precision + recall) #print(F1) # ## Logistic Regression # In[149]: from sklearn.linear_model import LogisticRegression # all parameters not specified are set to their defaults logisticRegr = LogisticRegression() logisticRegr.fit(X_train, y_train) # In[150]: logisticRegr.predict(X_test[0].reshape(1,-1)) # In[151]: logisticRegr.predict(X_test[0:10]) # In[152]: predictions = logisticRegr.predict(X_test) # In[153]: score = logisticRegr.score(X_test, y_test) #print(score) # In[154]: import matplotlib.pyplot as plt import seaborn as sns from sklearn import metrics cm = metrics.confusion_matrix(y_test, predictions) # In[155]: plt.figure(figsize=(9,9)) sns.heatmap(cm, annot=True, fmt=".3f", linewidths=.5, square = True, cmap = 'Blues_r'); plt.ylabel('Actual label'); plt.xlabel('Predicted label'); all_sample_title = 'Accuracy Score: {0}'.format(score) plt.title(all_sample_title, size = 15); <file_sep>/README.md # Data_classification_model This repository contains the final version of the data classification model for the intern dataset.
a920ca0c76a656738063f5940397d456f1e8a042
[ "Markdown", "Python" ]
2
Python
suvarnagupta/Data_classification_model
4aa7fe9cbd8d175c973aa8d70b29b96eb1b0d746
6af4ad11be576565f82a4a40df1616d993cd5c35
refs/heads/master
<repo_name>slorlior/Production-Company<file_sep>/src/models/movie.model.ts export class Movie { id: number; genre_ids: number[]; release_date: string; vote_average: number; vote_count: number; } export class DiscoverMoviesResult { results: Movie[]; total_pages: number; }<file_sep>/src/movies/movies.module.ts import { Module } from '@nestjs/common'; import { MoviesApiModule } from 'src/movies-api/movies-api.module'; import { MoviesService } from './movies.service'; @Module({ imports:[MoviesApiModule], providers: [MoviesService] }) export class MoviesModule { } <file_sep>/src/main.ts import { NestFactory } from '@nestjs/core'; import { MoviesModule } from './movies/movies.module'; import { MoviesService } from './movies/movies.service'; async function bootstrap(args: string[]) { const moviesModule = await NestFactory.create(MoviesModule); const moviesService = moviesModule.get<MoviesService>(MoviesService); await moviesService.start(args[0]); } // TODO: receive argument in a better way bootstrap(process.argv.slice(2)); <file_sep>/src/movies-api/movies-api.service.spec.ts import { Test, TestingModule } from '@nestjs/testing'; import { MoviesApiService } from './movies-api.service'; describe('TheMovieDbApiService', () => { let service: MoviesApiService; beforeEach(async () => { const module: TestingModule = await Test.createTestingModule({ providers: [MoviesApiService], }).compile(); service = module.get<MoviesApiService>(MoviesApiService); }); it('should be defined', () => { expect(service).toBeDefined(); }); }); <file_sep>/src/movies-api/movies-api.service.ts import { HttpService, Injectable } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { AxiosResponse } from 'axios'; import { DiscoverMoviesResult, Movie } from 'src/models/movie.model'; @Injectable() export class MoviesApiService { private api: string; private apiKey: string; constructor(private httpService: HttpService, private configService: ConfigService) { // TODO: throw error if missing variables this.api = this.configService.get<string>("MOVIES_API"); this.apiKey = this.configService.get<string>("API_KEY"); } public async getCompanyMovies(companyId: string): Promise<Movie[]> { let allMovies: Movie[] = []; const url = `${this.api}discover/movie?with_companies=${companyId}&release_date.gte=2020-01-01&api_key=${this.apiKey}`; const discoverMoviesResult = (await this.httpService.get<DiscoverMoviesResult>(url).toPromise()).data; allMovies = [...allMovies, ...discoverMoviesResult.results]; const totalPages = discoverMoviesResult.total_pages; if (totalPages > 1) { let pagesPromises = []; for (let i = 2; i <= totalPages; i++) { const discoverMoviePromise = this.httpService.get<DiscoverMoviesResult>(`${url}&page=${i}`).toPromise(); pagesPromises.push(discoverMoviePromise); } const allPages = await Promise.all<AxiosResponse<DiscoverMoviesResult>>(pagesPromises); for (let i = 0; i < allPages.length; i++) { allMovies = [...allMovies, ...allPages[i].data.results]; } } return allMovies; } } <file_sep>/src/movies/movies.service.ts import { Injectable, InternalServerErrorException } from '@nestjs/common'; import { Movie } from 'src/models/movie.model'; import { MoviesApiService } from 'src/movies-api/movies-api.service'; @Injectable() export class MoviesService { constructor(private moviesApiService: MoviesApiService) { } async start(companyId: string): Promise<void> { let movies: Movie[]; try { movies = await this.moviesApiService.getCompanyMovies(companyId); } catch (e) { console.log("TODO: Throw error with relavnt message"); throw new InternalServerErrorException(); } const { moviesCountPerMonth, moviesScoresPerGenresAndYear } = this.aggregateResult(movies); console.log("moviesCountPerMonth") console.log(moviesCountPerMonth) console.log("##################") console.log("moviesScoresPerGenresAndYear") console.log(moviesScoresPerGenresAndYear) // TODO : save result to DB under companyId } // TODO: add more types model private aggregateResult(movies: Movie[]): { moviesCountPerMonth: any, moviesScoresPerGenresAndYear: any } { let moviesCountPerMonth = {}; let moviesScoresPerGenresAndYear = {}; movies.forEach(movie => { const dateSplitted = movie.release_date.split('-'); const year = dateSplitted[0]; const month = dateSplitted[1]; const date = `${year}-${month}`; if (moviesCountPerMonth[date]) { moviesCountPerMonth[date]++; } else { moviesCountPerMonth[date] = 1; } if (movie.vote_count > 0) { if (!moviesScoresPerGenresAndYear[year]) { moviesScoresPerGenresAndYear[year] = {}; } movie.genre_ids.forEach(genreId => { if (!moviesScoresPerGenresAndYear[year][genreId]) { moviesScoresPerGenresAndYear[year][genreId] = { scoreSum: 0, movies: 0, average: 0 }; } moviesScoresPerGenresAndYear[year][genreId].scoreSum += movie.vote_average; moviesScoresPerGenresAndYear[year][genreId].movies++; moviesScoresPerGenresAndYear[year][genreId].average = moviesScoresPerGenresAndYear[year][genreId].scoreSum / moviesScoresPerGenresAndYear[year][genreId].movies; }); } }); return { moviesCountPerMonth, moviesScoresPerGenresAndYear }; } } <file_sep>/src/movies-api/movies-api.module.ts import { Module, HttpModule } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import { MoviesApiService } from './movies-api.service'; @Module({ imports: [HttpModule, ConfigModule.forRoot()], providers: [MoviesApiService], exports: [MoviesApiService] }) export class MoviesApiModule { }
3f91b0af1b025f05ad548034ae691136c9e8fa89
[ "TypeScript" ]
7
TypeScript
slorlior/Production-Company
f00372f1fdb0c65f3c110709ea11763615b26896
59b1e1653fdd26e11cb717e038530b6bc177e462
refs/heads/main
<repo_name>holworthy/ai-cw2<file_sep>/src/messages.py def text(content): return { "type": "text", "content": content } def ticket(ticket): return { "type": "ticket", "content": { "from_station": ticket.from_station.get_name(), "to_station": ticket.to_station.get_name(), "leave_at": ticket.leave_at.strftime("%Y-%m-%d %H:%M:%S"), "arrive_at": ticket.arrive_at.strftime("%Y-%m-%d %H:%M:%S"), # "travel_time": ticket.travel_time, "no_of_changes": ticket.no_of_changes, "price": ticket.price, "name": ticket.name, "provider": ticket.provider, "link": ticket.link } } def multiple_texts(texts): return [text(content) for content in texts] <file_sep>/README.md # ai-cw2 Artificial Intelligence Coursework 2 By <NAME>, <NAME> and <NAME> ## Requirements - Python 3.6 - requests - bs4 - spacy - en_core_web_lg - flask <file_sep>/src/ticket_generator.py import requests import bs4 import re import json import datetime import urllib.parse class Station: def __init__(self, name, postcode, code): self.name = name self.postcode = postcode self.code = code def get_name(self): return self.name def get_postcode(self): return self.postcode def get_code(self): return self.code def __str__(self): return f"Station<{self.name!r}, {self.postcode!r}, {self.code!r}>" def __repr__(self): return str(self) def __eq__(self, other): return self.get_name() == other.get_name() @staticmethod def get_stations(): with open("data/stations.json", "r") as f: return [Station(row["name"], row["postcode"], row["code"]) for row in json.load(f)] @staticmethod def is_a_station(station_name): stations = Station.get_stations() for station in stations: if station_name == station.get_name() or station_name == station.get_code() or station_name == station.get_postcode(): return True return False @staticmethod def get_from_name(name): for station in Station.get_stations(): if station.get_name().lower() == name.lower(): return station return None @staticmethod def get_from_code(code): for station in Station.get_stations(): if station.get_code() == code: return station return None class Ticket: def __init__(self, from_station, to_station, leave_at, arrive_at, no_changes, price, name, provider, link = None): self.from_station = from_station self.to_station = to_station self.leave_at = leave_at self.arrive_at = arrive_at self.travel_time = arrive_at - leave_at self.no_of_changes = no_changes self.price = price self.name = name self.provider = provider self.link = link def get_price(self): return self.price def __str__(self): return f"Ticket<{self.from_station}, {self.to_station}, {self.leave_at}, {self.arrive_at}, {self.travel_time}, {self.no_of_changes}, {self.price}, {self.name!r}, {self.provider!r}>" def __repr__(self): return str(self) class Railcard: def __init__(self): pass def get_tickets(from_station, to_station, when = None, arriving = False, is_return = False, return_when = None, return_arriving = False, adults = 1, children = 0, railcards = []): if not when: when = datetime.datetime.now() if not return_when: return_when = datetime.datetime.now() # You have to get these 3 pages before the main request or it doesn't work. # Do I know why? No. Not really. It's probably to do with cookies. # But that's someone else's problem now. :) session = requests.Session() session.get("https://www.nationalrail.co.uk/") session.get("https://ojp.nationalrail.co.uk/personal/member/welcome") session.get("https://ojp.nationalrail.co.uk/personal/omnibar/basket") response = session.post("https://ojp.nationalrail.co.uk/service/planjourney/plan", data = { "jpState": "1ingle" if is_return else "01ngle", "commandName": "journeyPlannerCommand", "from.searchTerm": from_station.get_name(), "to.searchTerm": to_station.get_name(), "timeOfOutwardJourney.arrivalOrDeparture": "ARRIVE" if arriving else "DEPART", "timeOfOutwardJourney.monthDay": when.strftime("%d/%m/%Y"), "timeOfOutwardJourney.hour": when.hour, "timeOfOutwardJourney.minute": when.minute, "checkbox": "true", "_checkbox": "on", "timeOfReturnJourney.arrivalOrDeparture": "ARRIVE" if return_arriving else "DEPART", "timeOfReturnJourney.monthDay": return_when.strftime("%d/%m/%Y"), "timeOfReturnJourney.hour": return_when.hour, "timeOfReturnJourney.minute": return_when.minute, "_showFastestTrainsOnly": "on", "numberOfAdults": adults, "numberOfChildren": children, "firstClass": "true", "_firstClass": "on", "standardClass": "true", "_standardClass": "on", "rcards": "", "numberOfEachRailcard": "0", "railcardCodes": "", "viaMode": "VIA", "via.searchTerm": "Station", "via1.searchTerm": "Station", "via2.searchTerm": "Station", "offSetOption": "0", "operator.code": "", "_reduceTransfers": "on", "_lookForSleeper": "on", "_directTrains": "on" }) soup = bs4.BeautifulSoup(response.content, "html.parser") mtx_rows = soup.select("#oft .mtx") tickets = [] returns = [] for mtx_row in mtx_rows: price = 0 name = "Ticket" provider = "Unknown" fare_breakdowns = [x.get("value").split("|") for x in mtx_row.select(".fare-breakdown input")] for fare_breakdown in fare_breakdowns: price += float(fare_breakdown[5]) name = fare_breakdown[3] provider = fare_breakdown[11] journey_breakdown = mtx_row.select_one(".journey-breakdown input").get("value").split("|") tickets.append(Ticket( from_station, to_station, when.replace(hour = int(journey_breakdown[2].split(":")[0]), minute = int(journey_breakdown[2].split(":")[1])), when.replace(hour = int(journey_breakdown[5].split(":")[0]), minute = int(journey_breakdown[5].split(":")[1])), journey_breakdown[8], price, name, provider, "https://ojp.nationalrail.co.uk/service/timesandfares/" + from_station.get_code() + "/" + to_station.get_code() + "/" + when.strftime("%d%m%y") + "/" + when.strftime("%H%M") + "/" + ("arr" if arriving else "dep") + ("" if not is_return else "/" + return_when.strftime("%d%m%y") + "/" + return_when.strftime("%H%M") + "/" + ("arr" if return_arriving else "dep")) )) return tickets def get_cheapest_ticket(from_station, to_station, time_date = None, arriving = False, is_return = False, return_time_date = None, return_arriving = False): tickets = get_tickets(from_station, to_station, time_date, arriving, is_return, return_time_date, return_arriving) tickets.sort(key = lambda tickets: tickets.get_price(), reverse=True) print("Cheapest Ticket:\n") try: print(tickets[0]) except: pass return tickets[0] <file_sep>/src/hsp.py import requests import pprint import datetime from ticket_generator import Station import sklearn.neighbors import sqlite3 import time import random EMAIL = "" PASSWORD = "" try: with open("src/passwords.txt") as f: EMAIL, PASSWORD = f.read().split(",") except: pass def station_code_to_number(code): a, b, c = code return (ord(a) - ord("A")) * 26 * 26 + (ord(b) - ord("A")) * 26 + (ord(c) - ord("A")) def time_to_number(hour, minute): return hour * 60 + minute db = sqlite3.connect("data/hsp.db") cur = db.cursor() cur.execute("CREATE TABLE IF NOT EXISTS services (id INTEGER PRIMARY KEY, origin_location TEXT, destination_location TEXT, gbtt_ptd TEXT, gbtt_pta TEXT, toc_code TEXT, date_of_service TEXT, rid INTEGER UNIQUE)") cur.execute("CREATE TABLE IF NOT EXISTS locations (service_id INTEGER, location TEXT, gbtt_ptd TEXT, gbtt_pta TEXT, actual_td TEXT, actual_ta TEXT, late_canc_reason TEXT, FOREIGN KEY (service_id) REFERENCES services(id))") db.commit() def download_data(from_station, to_station, from_date, to_date): N = 0 for day_type in ["WEEKDAY", "SATURDAY", "SUNDAY"]: response = requests.post("https://hsp-prod.rockshore.net/api/v1/serviceMetrics", auth = (EMAIL, PASSWORD), json = { "from_loc": from_station.get_code(), "to_loc": to_station.get_code(), "from_time": "0000", "to_time": "2359", "from_date": from_date.strftime("%Y-%m-%d"), "to_date": to_date.strftime("%Y-%m-%d"), "days": day_type }) N += 1 if response.status_code != 200: continue metrics = response.json() print(metrics) if "Services" not in metrics: continue for metric in metrics["Services"]: print(metric) rids = metric["serviceAttributesMetrics"]["rids"] for rid in rids: response = requests.post("https://hsp-prod.rockshore.net/api/v1/serviceDetails", auth = (EMAIL, PASSWORD), json = { "rid": rid }) N += 1 details = response.json() print(details) try: cur.execute("INSERT INTO services VALUES (NULL, ?, ?, ?, ?, ?, ?, ?)", [metric["serviceAttributesMetrics"]["origin_location"], metric["serviceAttributesMetrics"]["destination_location"], metric["serviceAttributesMetrics"]["gbtt_ptd"], metric["serviceAttributesMetrics"]["gbtt_pta"], metric["serviceAttributesMetrics"]["toc_code"], details["serviceAttributesDetails"]["date_of_service"], details["serviceAttributesDetails"]["rid"]]) except: continue s_id = cur.lastrowid for location in details["serviceAttributesDetails"]["locations"]: cur.execute("INSERT INTO locations VALUES (?, ?, ?, ?, ?, ?, ?)", [s_id, location["location"], location["gbtt_ptd"], location["gbtt_pta"], location["actual_td"], location["actual_ta"], location["late_canc_reason"]]) print(location) db.commit() return N def download_data_both(from_station, to_station, from_date, to_date): return download_data(from_station, to_station, from_date, to_date) + download_data(to_station, from_station, from_date, to_date) # knn = sklearn.neighbors.KNeighborsClassifier() # X = [] # y = [] # for t in train_data(Station.get_from_code("NRW"), Station.get_from_code("SSD"), datetime.datetime(year = 2020, month = 10, day = 1), datetime.datetime.now()): # if True or (t[1] > 5): # print(t) # X.append(t[0]) # y.append(t[1]) # knn.fit(X, y) # # [[2020, 10, 16, 10, 6, 10, 7, 10, 10, 10, 11], 4] # print(knn.predict([[2020, 10, 16, 10, 6, 10, 7, 10, 10, 10, 11]])) # for i in range(1, 13): # download_data(Station.get_from_code("NRW"), Station.get_from_code("SSD"), datetime.datetime(year = 2020, month = i, day = 1), datetime.datetime(year = 2020, month = i, day = 1) + datetime.timedelta(days = 32)) # time.sleep(2 * 60) # cities = ["Cambridge", "London", "Peterborough", "Ipswich", "Heathrow", "Aberystwyth", "Bournemouth", "Portsmouth", "Southampton", "Brighton", "Stevenage", "Dover", "Reading", "Oxford", "Swindon", "Bath", "Swansea", "Cardiff", "Bristol", "Exeter", "Plymouth", "Penzance", "Leicester", "Coventry", "Watford", "Gatwick", "Ashford", "Derby", "Nottingham", "Birmingham", "Wolverhampton", "Bangor", "Stoke", "Manchester", "Blackpool", "Preston", "Bradford", "Leeds", "Doncaster", "Grimsby", "Hull", "York", "Scarborough", "Grimsby", "Newcastle", "Carlisle", "Prestwick", "Edinburgh", "Stirling", "Perth", "Aberdeen", "Inverness", "Glasgow", "Norwich"] # city_stations = [station for station in Station.get_stations() if any(city in station.get_name() for city in cities)] # print(city_stations[90:]) # exit() # for i in range(20): # print(i) # # first = random.choice(city_stations) # first = Station.get_from_name("Norwich") # second = first # while second == first: # second = random.choice(city_stations) # print(first, "->", second) # N = download_data(first, second, datetime.datetime.now() - datetime.timedelta(weeks = 52), datetime.datetime.now()) # N += download_data(second, first, datetime.datetime.now() - datetime.timedelta(weeks = 52), datetime.datetime.now()) # print(N, "requests") # if N > 20: # time.sleep(60 * 5) # else: # time.sleep(10) # [download_data_both(Station.get_from_name("Norwich"), Station.get_from_name(name), datetime.datetime.now() - datetime.timedelta(weeks = 52), datetime.datetime.now()) for name in [ # "Peterborough", # "Ely", # "Stansted", # "Manchester", # "Birmingham", # "Edinburgh" # ]] # for city_station in city_stations[15:]: # if city_station != Station.get_from_name("Norwich"): # download_data_both(Station.get_from_name("Norwich"), city_station, datetime.datetime.now() - datetime.timedelta(weeks = 52), datetime.datetime.now()) download_data_both(Station.get_from_name(input("From: ")), Station.get_from_name(input("To: ")), datetime.datetime.now() - datetime.timedelta(weeks = 52 // 2), datetime.datetime.now()- datetime.timedelta(weeks = 0)) <file_sep>/src/templates/js/script.js var messages_div = document.getElementById("messages"); var form = document.getElementById("form"); var messagebox = document.getElementById("messagebox"); var chatbot_img = document.getElementById("chatbot_img"); // adds a message to the screen function addMessage(message, side) { var message_div = document.createElement("div"); message_div.classList.add("message"); message_div.classList.add(side); message_div.classList.add("hide"); if(message["type"] == "text"){ message_div.innerHTML = "<p>" + message["content"] + "</p>"; }else if(message["type"] == "ticket"){ let ticket = message["content"], from = ticket["from_station"], to = ticket["to_station"], leave_at = ticket["leave_at"], link = ticket["link"]; message_div.innerHTML = "<p><b>" + from + "</b> to <b>" + to + "</b> leaving at <b>" + leave_at + "</b></p><p><a href=\"" + link + "\">Book Here</a></p>"; } messages_div.append(message_div); messages_div.scrollTop = messages_div.scrollHeight; message_div.classList.remove("hide"); } function textMessage(text) { return { "type": "text", "content": text }; } // magic var queue = []; var queue_interval = null; function start_queue(){ if(queue_interval == null){ queue_interval = setInterval(() => { if(queue.length > 0){ addMessage(queue.shift(), "left"); }else{ clearInterval(queue_interval); queue_interval = null; } }, 1000); } } // add the initial messages to the screen queue queue.push(textMessage("Hi, I am trainbot! 🚂")); queue.push(textMessage("How can I help you?")); // empty the queue to the screen start_queue(); form.addEventListener("submit", (e) => { e.preventDefault(); var content = messagebox.value; chatbot_img.src = "/img/Chatbot_Processing_2.gif"; // send users message to server var xhr = new XMLHttpRequest(); xhr.open("POST", "/message"); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.addEventListener("load", (e) => { // get server response var response = JSON.parse(xhr.responseText); var messages = response["message"]; for(let i = 0; i < messages.length; i++){ // add server messages to the queue of messages to be added to screen queue.push(messages[i]); } // start adding server messages to the screen one by one start_queue(); var state = response["state"]; if(state == "start" || state == "end"){ setTimeout(()=>{chatbot_img.src = "/img/Chatbot_Happy.svg"}, 1000); } else if(state == "would_you_like_to_book" || state == prevstate){ setTimeout(()=>{chatbot_img.src = "/img/Chatbot_Confused.svg"}, 1000); } else{ setTimeout(()=>{chatbot_img.src = "/img/Chatbot_basic.svg"}, 1000); } prevstate = state; }); xhr.send(JSON.stringify(content)); // add users message to screen addMessage(textMessage(content), "right"); messagebox.value = ""; }); // function locate() { // navigator.geolocation.getCurrentPosition((e) => { // var xhr = new XMLHttpRequest(); // xhr.addEventListener("load", (e) => { // var xhr2 = new XMLHttpRequest(); // xhr2.open("POST", "/nearest_station"); // xhr2.setRequestHeader('Content-Type', 'application/json'); // xhr2.addEventListener("load", (e) => { // messagebox.value = xhr2.response; // }); // xhr2.send(JSON.stringify(JSON.parse(xhr.response).result[0].postcode)); // }); // xhr.open("GET", "https://api.postcodes.io/postcodes?lon=" + e.coords.longitude + "&lat=" + e.coords.latitude); // xhr.send(); // }); // } var prevstate = null; var xhr = new XMLHttpRequest(); xhr.open("POST", "/reset"); xhr.send(); <file_sep>/src/get_stations.py import requests import bs4 import re import json HEADERS = { "User-Agent": "ai-cw2 <https://github.com/dangee1705/ai-cw2>" } with open("data/stations.json", "w") as f: stations = [] for letter in "ABCDEFGHIJKLMNOPQRSTUVWYXZ": url = f"https://en.wikipedia.org/wiki/UK_railway_stations_-_{letter}" response = requests.get(url, headers = HEADERS) soup = bs4.BeautifulSoup(response.content, "html.parser") rows = soup.select("table.wikitable>tbody>tr") for row in rows: data = [x.text.strip() for x in row.select("td")] if data and re.match("^[A-Z]{1,2}[0-9]{1,2}[A-Z]? [0-9][A-Z]{2}$", data[1]) and data[-1]: stations.append({ "name": data[0].replace("'", ""), "postcode": data[1], "code": data[-1][:3] }) json.dump(stations, f) <file_sep>/src/knn.py import sklearn.neighbors import sqlite3 def station_code_to_number(code): a, b, c = code return (ord(a) - ord("A")) * 26 * 26 + (ord(b) - ord("A")) * 26 + (ord(c) - ord("A")) def time_string_to_hour_minute(time): return int(time[:2]), int(time[2:]) db = sqlite3.connect("data/hsp.db") cur = db.cursor() result = cur.execute("SELECT services.id, services.origin_location, services.destination_location, services.gbtt_ptd, services.gbtt_pta, services.toc_code, services.date_of_service, services.rid, locations.location, locations.gbtt_ptd, locations.gbtt_pta, locations.actual_td, locations.actual_ta, locations.late_canc_reason FROM services INNER JOIN locations ON services.id = locations.service_id") rows = [row for row in result] def predict_it(row1, from_station, to_station): knnc = sklearn.neighbors.KNeighborsClassifier() train_data = [] target_data = [] total_delay = 0 cur_service_id = None for services_id, services_origin_location, services_destination_location, services_gbtt_ptd, services_gbtt_pta, services_toc_code, services_date_of_service, services_rid, locations_location, locations_gbtt_ptd, locations_gbtt_pta, locations_actual_td, locations_actual_ta, locations_late_canc_reason in rows: # if services_origin_location != from_station.get_code() or services_destination_location != to_station.get_code(): # continue if cur_service_id != services_id: for i in range(len(train_data) - len(target_data)): target_data.append(total_delay) total_delay = 0 cur_service_id = services_id if locations_gbtt_pta != "" and locations_actual_ta != "" and locations_late_canc_reason == "": predicted_hour, predicted_minute = time_string_to_hour_minute(locations_gbtt_pta) actual_hour, actual_minute = time_string_to_hour_minute(locations_actual_ta) predicted = predicted_hour * 60 + predicted_minute actual = actual_hour * 60 + actual_minute delay = actual - predicted if abs(actual - predicted) < abs(actual + 1440 - predicted) else actual + 1440 - predicted if delay > 0: total_delay += delay train_data.append([ *map(int, services_date_of_service.split("-")), station_code_to_number(services_origin_location), station_code_to_number(services_destination_location), station_code_to_number(locations_location), *time_string_to_hour_minute(locations_gbtt_pta), *time_string_to_hour_minute(locations_actual_ta) ]) for i in range(len(train_data) - len(target_data)): target_data.append(total_delay) knnc.fit(train_data, target_data) try: return knnc.predict([row1]) except: return 0 <file_sep>/src/gui.py import json import time import flask import nlpu import ticket_generator from ticket_generator import Station import re app = flask.Flask(__name__) @app.route("/") def index(): return flask.send_from_directory("templates/", "index.html") @app.route("/css/<stylesheet>") def css(stylesheet): return flask.send_from_directory("templates/css/", stylesheet) @app.route("/js/<script>") def js(script): return flask.send_from_directory("templates/js/", script) @app.route("/img/<img>") def img(img): return flask.send_from_directory("templates/img/", img) @app.route("/favicon.ico") def favicon(): return flask.send_from_directory("templates/img/", "icon.png") def i_dont_understand(): return "Sorry, I'm not sure I know what you mean. Can you try again?" def text_message(text): return {"type": "text", "content": text} def ticket_message(ticket): return { "type": "ticket", "from_station": ticket.from_station, "to_station": ticket.to_station, "leave_at": ticket.leave_at, "arrive_at": ticket.arrive_at, "travel_time": ticket.travel_time, "no_of_changes": ticket.no_changes, "price": ticket.price, "name": ticket.name, "provider": ticket.provider, "link": ticket.link } @app.route("/message", methods = ["POST"]) def message(): msg = flask.request.get_json() response_dict = {"message":nlpu.process_message(msg, ticket_request), "state": nlpu.get_current_state()} return json.dumps(response_dict) @app.route("/nearest_station", methods = ["POST"]) def nearest_station(): msg = flask.request.get_json() stations = Station.get_stations() stations = [station for station in stations if station.get_postcode().startswith(re.findall("^[A-Z]{1,2}", msg)[0])] stations.sort(key = lambda x: int(re.findall("^[A-Z]{1,2}([0-9]{1,2})", x.get_postcode())[0])) for station in stations: if station.get_postcode() == msg: return station.get_name() for station in stations: if station.get_postcode() == msg.split()[0]: return station.get_name() return stations[0].get_name() @app.route("/reset", methods = ["POST"]) def reset(): ticket_request = nlpu.Ticket_Request() nlpu.state = "start" return "" ticket_request = nlpu.Ticket_Request() app.run() <file_sep>/src/nlpu.py import datetime import random import re from spellchecker import SpellChecker import knn import messages import ticket_generator from ticket_generator import Station, Ticket spell = SpellChecker() spell.word_frequency.load_words(station.get_name() for station in Station.get_stations()) class Ticket_Request: def __init__(self): self.from_station = None self.to_station = None self.time1 = None self.dep_arr1 = False self.is_return = False self.time2 = None self.dep_arr2 = False self.delay_from_station = None self.delay_to_station = None self.delay_current_station = None def set_from_station(self, from_station): self.from_station = from_station def set_to_station(self, to_station): self.to_station = to_station def set_time1(self, time1): self.time1 = time1 def set_dep_arr1(self, dep_arr1): self.dep_arr1 = dep_arr1 def set_is_return(self, is_return): self.is_return = is_return def set_time2(self, time2): self.time2 = time2 def set_dep_arr2(self, dep_arr2): self.dep_arr2 = dep_arr2 def get_from_station(self): return self.from_station def get_to_station(self): return self.to_station def get_time1(self): return self.time1 def get_dep_arr1(self): return self.dep_arr1 def get_is_return(self): return self.is_return def get_time2(self): return self.time2 def get_dep_arr2(self): return self.dep_arr2 def get_times(message): return [datetime.datetime.strptime(time[0], "%H:%M") for time in re.findall("((([1-9])|([0-1][0-9])|(2[0-3])):(([0-5][0-9])))", message)] def get_dates(message): dates = [] for date in re.findall(r"(\d+/\d+/\d+)", message): dates.append(datetime.datetime.strptime(date, "%d/%m/%y")) return dates def process_times_dates(message, ticket_request): dates = get_dates(message) times = get_times(message) time = None if not dates or not times: if "tomorrow" in message.lower(): print("boo") date_temp = datetime.datetime.now() date_temp += datetime.timedelta(days=1) date_temp = date_temp.replace(hour = 9) dates.append(date_temp) if "morning" in message.lower(): time_temp = datetime.datetime.now() time_temp = time_temp.replace(hour=9, minute=0) if not dates: if time_temp < datetime.datetime.now(): time_temp += datetime.timedelta(days=1) time = time_temp else: times.append(time_temp) if "evening" in message.lower(): time_temp = datetime.datetime.now() time_temp = time_temp.replace(hour=17, minute=0) if not dates: if time_temp < datetime.datetime.now(): time_temp += datetime.timedelta(days=1) time = time_temp else: times.append(time_temp) if "in an hour" in message.lower() or "in 1 hour" in message.lower(): time_temp = datetime.datetime.now() time_temp += datetime.timedelta(hours=1) if not dates: time = time_temp else: times.append(time_temp) if ticket_request.get_time1() != None and "next day" in message.lower(): date_temp = ticket_request.get_time1() date_temp += datetime.timedelta(days=1) date_temp = date_temp.replace(hour = 9) dates.append(date_temp) return time, times, dates def better_datetime_processing(message): dt = datetime.datetime.now() now = datetime.datetime.now() today = datetime.datetime(year = now.year, month = now.month, day = now.day) has_date_part = True has_time_part = True if "today" in message: dt = today elif "tomorrow" in message: dt = today + datetime.timedelta(days = 1) elif "in a week" in message or "a week today" in message: dt = today + datetime.timedelta(weeks = 1) elif "in a month" in message or "a month today" in message: dt = today + datetime.timedelta(months = 1) else: for i, day in enumerate(["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]): if day in message.lower(): days_ahead = i - dt.weekday() if days_ahead <= 0: days_ahead += 7 dt = dt + datetime.timedelta(days_ahead) break else: match = re.match("([0-9]{2}/[0-9]{2}/[0-9]{4})|([0-9]{4}-[0-9]{2}-[0-9]{2})", message) if match: for pattern in ["%d/%m/%Y", "%Y-%m-%d"]: try: dt = datetime.datetime.strptime(match.group(0), pattern) except Exception as e: continue break else: raise ValueError("Invalid date") else: has_date_part = False if "now" in message: dt = now elif "morning" in message: dt = dt.replace(hour = 9, minute = 0) elif "afternoon" in message or "after lunch" in message: dt = dt.replace(hour = 14, minute = 0) elif "lunchtime" in message or "midday" in message: dt = dt.replace(hour = 12, minute = 0) else: match = re.match("[0-9]{2}:[0-9]{2}", message) if match: try: t = datetime.time.fromisoformat(match.group(0)) dt = dt.replace(hour = t.hour, minute = t.minute, second = 0) except Exception as e: raise ValueError("Invalid time") else: for i in range(1, 12): if f"{i} am" in message or f"{i}am" in message: dt = dt.replace(hour = i, minute = 0, second = 0) break elif f"{i} pm" in message or f"{i}pm" in message: dt = dt.replace(hour = i + 12, minute = 0, second = 0) break else: if f"12 am" in message or f"12am" in message: dt = dt.replace(hour = 0, minute = 0, second = 0) elif f"12 pm" in message or f"12pm" in message: dt = dt.replace(hour = 12, minute = 0, second = 0) else: has_time_part = False if not has_date_part and not has_time_part: return None if not has_time_part: dt = dt.replace(hour = 9, minute = 0, second = 0) return dt state = "start" def message_is_yes(message): return message.lower() in ["yes", "yeah", "ye", "yee", "yep", "yes sir", "ok", "okay", "sure", "sure thing", "sure thang", "yes i would", "yes please", "y"] def message_is_no(message): return message.lower() in ["no", "noo", "nah", "neigh", "nope", "no sir", "no i wouldn't", "no i would not", "no thanks", "n"] def ticket_from_ticket_request(ticket_request): print(ticket_request.get_from_station(), ticket_request.get_to_station(), ticket_request.get_time1(), ticket_request.get_dep_arr1(), ticket_request.get_is_return(), ticket_request.get_time2(), ticket_request.get_dep_arr2()) return ticket_generator.get_cheapest_ticket( ticket_request.get_from_station(), ticket_request.get_to_station(), ticket_request.get_time1(), ticket_request.get_dep_arr1(), ticket_request.get_is_return(), ticket_request.get_time2(), ticket_request.get_dep_arr2() ) def get_current_state(): return state def get_similar_stations(message): similar_stations = [] for word in message.split(): if word.lower() != "street": for station in Station.get_stations(): for station_name in station.get_name().split(): if word.lower() == station_name.lower(): similar_stations.append(station) return similar_stations def process_message(message, ticket_request): message = " ".join(spell.correction(word) for word in message.split()) global state if state == "start": if message.lower() in ["hello", "hi", "hey", "sup"]: return messages.multiple_texts(["Hey There!", "How can I help?"]) elif "train" in message.lower() or "ticket" in message.lower(): state = "from" return messages.multiple_texts([ "Okay!", "Where would you like to go from?" ]) elif "delay" in message.lower() or "late" in message.lower() or "behind" in message.lower() or "where is my train" in message.lower(): state = "delay" return messages.multiple_texts([ "Ok I just need some details to locate your train and predict the delay.", "What was the first station on the journey?" ]) else: state = "would_you_like_to_book" return messages.multiple_texts([ "I'm sorry I'm not sure I know what you want.", "Would you like to book a ticket?" ]) elif state == "would_you_like_to_book": if message_is_yes(message): state = "from" return messages.multiple_texts([ "Okay!", "Where would you like to go from?" ]) elif message_is_no(message): state = "start" return messages.multiple_texts(["Ok, Have a nice day! 😊🚂"]) else: return messages.multiple_texts([ "I'm sorry, I don't understand", "Would you like to book a ticket?" ]) elif state == "from": from_station = Station.get_from_name(message) if from_station: ticket_request.set_from_station(from_station) state = "to" return messages.multiple_texts(["Nice!", "Where would you like to go to?"]) elif get_similar_stations(message): similar_stations = get_similar_stations(message) return messages.multiple_texts([ "Sorry I'm not sure I know where that is", "Did you mean any of the following station(s):", *[station.get_name() for station in similar_stations] ]) else: return messages.multiple_texts(["Sorry I'm not sure I know where that is", "Make sure you spelt that correctly and try again", "Where would you like your journey to start?"]) elif state == "to": to_station = Station.get_from_name(message) if to_station: ticket_request.set_to_station(to_station) state = "when" return messages.multiple_texts(["Cool!", "When would you like that ticket for?"]) elif get_similar_stations(message): similar_stations = get_similar_stations(message) return messages.multiple_texts([ "Sorry I'm not sure I know where that is", "Did you mean any of the following station(s):", *[station.get_name() for station in similar_stations] ]) else: return messages.multiple_texts(["Sorry I'm not sure I know where that is", "Make sure you spelt that correctly and try again", "Where would you like your journey to end?"]) elif state == "when": dt = better_datetime_processing(message) if not dt: return messages.multiple_texts(["Sorry I'm not sure what you mean", "When do you want the ticket for?"]) else: ticket_request.set_time1(dt) state = "arrive_depart_1" return messages.multiple_texts(["Awesome!", "Is that arriving or departing?"]) elif state == "arrive_depart_1": if any(x in message for x in ["Arriving", "arriving"]): ticket_request.set_dep_arr1(True) state = "is_return" return messages.multiple_texts(["Nice!", "Is it a return?"]) elif state == "is_return": if message_is_yes(message): ticket_request.set_is_return(True) state = "when_2" return messages.multiple_texts([ "Okay", "When would you like the return for?" ]) elif message_is_no(message): ticket_request.set_is_return(False) state = "start" try: return [*messages.multiple_texts([ "Alright then.", "Here is the cheapest ticket we could find", ]), messages.ticket(ticket_from_ticket_request(ticket_request))] except: return [*messages.multiple_texts([ "There are no tickets at that time.", "Anything else I can help?" ])] else: return messages.multiple_texts([ "I'm sorry I don't understand.", "Is that a return? yes or no?" ]) elif state == "when_2": dt = better_datetime_processing(message) if not dt: return messages.multiple_texts(["Sorry I'm not sure what you mean", "When do you want the ticket for?"]) else: ticket_request.set_time2(dt) state = "arrive_depart_2" return messages.multiple_texts(["Awesome!", "Is that arriving or departing?"]) elif state == "arrive_depart_2": if any(x in message for x in ["Arriving", "arriving", "Ariving", "ariving"]): ticket_request.set_dep_arr1(True) state = "start" try: return [*messages.multiple_texts([ "Alright then.", "Here is the cheapest tickets we could find", ]), messages.ticket(ticket_from_ticket_request(ticket_request))] except: return [*messages.multiple_texts([ "There are no tickets at those times.", "Anything else I can help?" ])] elif state == "delay": ticket_request.delay_to_station = Station.get_from_name(message) if ticket_request.delay_to_station: state = "delay_2" return messages.multiple_texts(["Got it.", "And where is the last station in the journey?"]) else: return messages.multiple_texts([ "Sorry I'm not sure I know where that is", "Make sure you spelt that correctly and try again", "Where would you like your journey to end?" ]) elif state == "delay_2": ticket_request.delay_from_station = Station.get_from_name(message) if ticket_request.delay_from_station: state = "delay_3" return messages.multiple_texts([ "Nice!", "What station are you currently at?" ]) else: return messages.multiple_texts([ "Sorry I'm not sure I know where that is", "Make sure you spelt that correctly and try again", "Where would you like your journey to end?"]) elif state == "delay_3": ticket_request.delay_current_station = Station.get_from_name(message) if ticket_request.delay_current_station: state = "delay_4" return messages.multiple_texts([ "Okay!", "How many minutes late are you at the moment?" ]) else: return messages.multiple_texts([ "Not sure I know where that is!", "Where are you currently?" ]) elif state == "delay_4": try: mins = int(message) now = datetime.datetime.now() now_plus_delay = now + datetime.timedelta(minutes = mins) delay = knn.predict_it( [now.year, now.month, now.day, knn.station_code_to_number(ticket_request.delay_from_station.get_code()), knn.station_code_to_number(ticket_request.delay_to_station.get_code()), knn.station_code_to_number(ticket_request.delay_current_station.get_code()), now.hour, now.minute, now_plus_delay.hour, now_plus_delay.minute], ticket_request.delay_from_station, ticket_request.delay_to_station ) state = "start" return messages.multiple_texts([ "Got it.", f"Based on previous data, your train will probably arrive at its final destination {int(delay[0])} minutes late", "Anything else I can help with?" ]) except: return messages.multiple_texts(["Please enter a number in minutes"]) return [messages.text("um thats awkward")]
9d0472335097a5f63cde29b0728864ee7b018625
[ "Markdown", "Python", "JavaScript" ]
9
Python
holworthy/ai-cw2
6e664fc93d59b22e129b4c9b82c06ce0ce22e6ae
fdf0db8b42718078756c239ac421076ffe41bfb0
refs/heads/master
<file_sep>package com.home.study; import java.util.Scanner; public class App { public static void main( String[] args ) { DataBase booksBase = new DataBase(); booksBase.createRandomBase(10); booksBase.add(new Book().getRandomBook()); Scanner scanner = new Scanner(System.in); System.out.print("Sort by(author,publishing,after year):"); String input = scanner.nextLine(); switch (input){ case "author": System.out.print("Write author's name:"); String requestAuthor = scanner.nextLine(); DataBase authors = booksBase.sortByAuthor(requestAuthor); authors.print(); break; case "publishing": System.out.print("Write name of publishing:"); String requestPublishing = scanner.nextLine(); DataBase publishing = booksBase.sortByPublishing(requestPublishing); publishing.print(); break; case "after year": System.out.print("Write year:"); int requestYear = scanner.nextInt(); DataBase years = booksBase.sortByYear(requestYear); years.print(); break; default: System.out.println("Incorrect request."); } } }
e7044ff7d095b0d5c29291cc406f3a89bc01fb3f
[ "Java" ]
1
Java
Petrovichq/JavaClassesMainTask
f693619aeaf6000a198e15ea768bfab13a6ce631
6a569795875a8a63dfb240b777cc859d4b6264b7
refs/heads/master
<repo_name>talam16-meet/MEET-YL2<file_sep>/app.py from flask import Flask, request, session, g, redirect, url_for, abort, render_template, flash app= Flask(__name__) @app.route("/") def Home(): return render_template("home.html") @app.route("/about_me") def About_me(): return render_template("about_me.html") @app.route("/contact_me") def Contact_me(): return render_template("contact_me.html") if __name__ == "__main__": app.debug = True app.run() <file_sep>/README.md # MEET-YL2dgtrd
1be954cd2eeca4ed6590c6ba3e26c72f1a68e0b0
[ "Markdown", "Python" ]
2
Python
talam16-meet/MEET-YL2
cd783bf3aa2f77418dbd0d1ff2641105e5962398
47cfb52ea50e91b725dd4f1af381b397c80432d4
refs/heads/master
<repo_name>kuckelvin/5.-Blur-Loading<file_sep>/script.js const counter = document.querySelector(".counter") const bg = document.querySelector(".bg") loading = 0 rate = setInterval (blurring, 30) function blurring() { loading++ if (loading > 99) { clearInterval (rate) } counter.innerText = `${loading}%` bg.style.filter = `blur(${scale(loading, 0, 100, 30, 0)}px)` counter.style.opacity = scale(loading, 0, 100, 1, 0) } const scale = (num, in_min, in_max, out_min, out_max) => { return ((num - in_min) * (out_max - out_min)) / (in_max - in_min) + out_min } // https://stackoverflow.com/questions/10756313/javascript-jquery-map-a-range-of-numbers-to-another-range-of-numbers
1b8e9dbb65f3b57a3228e2741918c46e50c37c80
[ "JavaScript" ]
1
JavaScript
kuckelvin/5.-Blur-Loading
0fdaf93b6c876ae068d90ada6a70436bd0382ea7
dc4bf65b4348fd01a5042faeb43c242320fc6dc9
refs/heads/master
<repo_name>HolgerGlysing/ImportingTool<file_sep>/Utility/Converters.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; using Uniconta.ClientTools; namespace ImportingTool.Utility { public class LocalizationValueConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return Localization.lookup(parameter.ToString()); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return value; } } } <file_sep>/Model/Log.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Controls; using Uniconta.API.System; using Uniconta.ClientTools; using Uniconta.Common; using Uniconta.DataModel; namespace ImportingTool.Model { public class GLPostingLineLocal : Uniconta.API.GeneralLedger.GLPostingLine { public string OrgText; public int primo; } public class MyGLAccount : GLAccount { public bool HasVat, HasChanges; } public partial class importLog : INotifyPropertyChanged { public TextBox target; public string LogMsg { get { return LogMessage.ToString(); } set { NotifyPropertyChanged("LogMsg"); } } StringBuilder LogMessage = new StringBuilder(); public void AppendLog(string msg) { LogMessage.Append(msg); LogMsg = LogMessage.ToString(); } public void AppendLogLine(string msg) { LogMessage.AppendLine(msg); LogMsg = LogMessage.ToString(); if (target != null) target.ScrollToEnd(); } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public MainWindow window; public string extension; public string path; public StringSplit sp; public string CurFile; public CrudAPI api; public List<PaymentTerm> pTerms; TextReader r; public bool FirstLineIsEmpty, ConvertDanishLetters; public bool HasDepartment, HasPorpose, HasCentre, HasBOM, HasItem, HasPriceList, HasDebitor, HasCreditor, HasContact; public int NumberOfDimensions; public SQLCache LedgerAccounts, vats, Debtors, Creditors, PriceLists, Items, ItemGroups, Employees, Payments, DebGroups, CreGroups; public SQLCache dim1, dim2, dim3; public string errorAccount, valutaDif; public Encoding C5Encoding; public byte[] CharBuf; public bool VatIsUpdated; public Currencies CompCurCode; public string CompCur; public CountryCode CompCountryCode; public string CompCountry; public CompanyFinanceYear[] years; public int Accountlen; public bool Set0InAccount; public void closeFile() { if (r != null) { var _r = r; r = null; _r.Dispose(); } } public importLog(string path) { this.path = path; } public void Ex(Exception ex) { api.ReportException(ex, string.Format("File={0}", CurFile)); AppendLogLine(ex.Message); } public bool OpenFile(string file, string comment = null) { closeFile(); if (comment != null) comment = string.Format("{0} - {1}", file, comment); else comment = file; CurFile = this.path + file + extension; if (!File.Exists(CurFile)) { AppendLogLine(String.Format(Uniconta.ClientTools.Localization.lookup("FileNotFound"), comment)); return false; } AppendLogLine(String.Format(Uniconta.ClientTools.Localization.lookup("ImportingFile"), comment)); r = new StreamReader(CurFile, Encoding.Default, true); if (r != null) { if (FirstLineIsEmpty) ReadLine(); // first line is empty return true; } AppendLogLine(string.Format("{0} : ", Uniconta.ClientTools.Localization.lookup("FileAccess"), CurFile)); return false; } public void Log(string s) { AppendLogLine(s); } public async Task Error(ErrorCodes Err) { var errors = await api.session.GetErrors(); var s = Err.ToString(); api.ReportException(null, string.Format("Error in conversion = {0}, file={1}", s, CurFile)); AppendLogLine(s); if (errors != null) { foreach(var er in errors) { if (er.inProperty != null) AppendLogLine(string.Format("In property = {0}", er.inProperty)); if (er.message != null) AppendLogLine(string.Format("Message = {0}", er.message)); } } } public string ReadLine() { return r.ReadLine(); } public List<string> GetLine(int minCols) { string oldLin = null; for (;;) { var lin = r.ReadLine(); if (lin == null) return null; if (ConvertDanishLetters) { int StartIndex = 0; int pos; while ((pos = lin.IndexOf('\\', StartIndex)) >= 0) { StartIndex = pos + 1; int val = 0; for (int i = 1; i <= 3; i++) { var ch = lin[pos + i]; if (ch >= '0' && ch <= '7') val = val * 8 + (ch - '0'); else break; } if (val >= 128 && val <= 255) { lin = lin.Remove(pos, 4); this.CharBuf[0] = (byte)val; var ch = this.C5Encoding.GetString(this.CharBuf); lin = lin.Insert(pos, ch); } } /* //****************************************************** //C5 data comes with special characters we must replace. lin = lin.Replace("\\221", "æ"); lin = lin.Replace("\\233", "ø"); lin = lin.Replace("\\206", "å"); lin = lin.Replace("\\222", "Æ"); lin = lin.Replace("\\235", "Ø"); lin = lin.Replace("\\217", "Å"); lin = lin.Replace("\\224", "ö"); lin = lin.Replace("\\201", "ü"); lin = lin.Replace("\\204", "ä"); lin = lin.Replace("\\341", "ß"); //****************************************************** */ } if (oldLin != null) lin = oldLin + " " + lin; var lines = sp.Split(lin); if (lines.Count >= minCols) return lines; oldLin = lin; } } static public double ToDouble(string str) { var val = Uniconta.Common.Utility.NumberConvert.ToDouble(str); if (double.IsNaN(val) || val > 9999999999999.99d || val < -9999999999999.99d) // 9.999.999.999.999,99d return 0d; return val; } //Leading zero's on GLAccount. public string GLAccountFromC5(string account) { if (account != string.Empty && Accountlen != 0) return account.PadLeft(Accountlen, '0'); else return account; } public string GLAccountFromC5_Validate(string account) { if (account == string.Empty) return string.Empty; account = this.GLAccountFromC5(account); if (this.LedgerAccounts.Get(account) != null) return account; return string.Empty; } public Currencies ConvertCur(string str) { if (str != string.Empty && this.CompCur != str) { Currencies cur; if (Enum.TryParse(str, true, out cur)) { if (cur != this.CompCurCode) return cur; } } return 0; } public string GetVat_Validate(string vat) { if (vat != string.Empty) { var rec = (GLVat)this.vats?.Get(vat); if (rec != null) return rec._Vat; } return string.Empty; } static public ItemUnit ConvertUnit(string str) { if (AppEnums.ItemUnit != null) { var unit = str.Replace(".", string.Empty); var unitId = AppEnums.ItemUnit.IndexOf(unit); if (unitId > 0) return (ItemUnit)unitId; } return 0; } public async Task<ErrorCodes> Insert(IEnumerable<UnicontaBaseEntity> lst) { closeFile(); if (window.Terminate) return ErrorCodes.NoSucces; var count = lst.Count(); AppendLogLine(string.Format("Saving {0}. Number of records = {1} ...", CurFile, count)); var lst2 = new List<UnicontaBaseEntity>(); int n = 0; int nError = 0; ErrorCodes ret = 0; window.progressBar.Maximum = lst.Count(); foreach (var rec in lst) { lst2.Add(rec); n++; if ((n % 100) == 0 || n == count) { if (n == count) window.UpdateProgressbar(count, null); else window.UpdateProgressbar(n * 100, null); var ret2 = await api.Insert(lst2); if (ret2 != Uniconta.Common.ErrorCodes.Succes) { foreach (var oneRec in lst2) { ret2 = await api.Insert(oneRec); if (ret2 != 0) { ret = ret2; nError++; } } if (ret != 0) await this.Error(ret); } lst2.Clear(); } } if (nError != 0) AppendLogLine(string.Format("Saved {0}. Number of records with error = {1}", CurFile, nError)); return ret; } public void Update(IEnumerable<UnicontaBaseEntity> lst) { closeFile(); var count = lst.Count(); AppendLogLine(string.Format("Updatating. Number of records = {0} ...", count)); api.UpdateNoResponse(lst); /* var lst2 = new List<UnicontaBaseEntity>(); int n = 0; ErrorCodes ret = 0; foreach (var rec in lst) { lst2.Add(rec); n++; if ((n % 100) == 0 || n == count) { ret = await api.Update(lst2); if (ret != Uniconta.Common.ErrorCodes.Succes) await this.Error(ret); lst2.Clear(); } } */ } } } <file_sep>/Model/eco.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Uniconta.API.Service; using Uniconta.API.System; using Uniconta.Common; using Uniconta.DataModel; using System.IO; using Uniconta.Common.Utility; using Uniconta.API.GeneralLedger; using System.Threading; using Uniconta.ClientTools; using System.ComponentModel; using System.Windows.Controls; using System.Windows.Threading; namespace ImportingTool.Model { public class DepartSplit { public string Afd; public double pct; static public Dictionary<string, List<DepartSplit>> importAfdelingFordeling(importLog log) { if (!log.OpenFile("AfdelingFordeling")) { return null; } try { var dim1 = log.dim1; List<string> lines; var dict = new Dictionary<string, List<DepartSplit>>(); while ((lines = log.GetLine(3)) != null) { var afdMaster = lines[0]; if (afdMaster == string.Empty) continue; var afd = lines[1]; if (dim1 != null && dim1.Get(afd) == null) continue; var pct = NumberConvert.ToDouble(lines[2]); List<DepartSplit> lst; if (dict.ContainsKey(afdMaster)) { lst = dict[afdMaster]; } else { lst = new List<DepartSplit>(); dict.Add(afdMaster, lst); } lst.Add(new DepartSplit() { Afd = afd, pct = pct }); } return dict; } catch (Exception ex) { log.Ex(ex); return null; } } } static public class eco { static public async Task<ErrorCodes> importAll(importLog log, int Country) { await eco.importYear(log, Country == 1 ? "RegnskabsAar" : "Regnskapsaar"); await importDepartment(log); var err = await eco.importCOA(log); if (err != 0) return err; eco.importSystemKonti(log); await eco.importMoms(log, Country == 1 ? "MomsKode" : "MvaKode"); eco.importAfgift(log, Country == 1 ? "AfgiftsKonto" : "AvgiftsKonto"); await eco.importDebtorGroup(log); await eco.importCreditorGroup(log); await eco.importPaymentGroup(log); await eco.importEmployee(log); await eco.importDebitor(log); await eco.importCreditor(log); await eco.importInvGroup(log); await eco.importInv(log); var orders = new Dictionary<long, UnicontaBaseEntity>(); await eco.importOrder(log, "Ordre", 1, orders); if (orders.Count > 0) await eco.importOrderLinje(log, "OrdreLinje", 1, orders); orders.Clear(); await eco.importOrder(log, "Tilbud", 3, orders); if (orders.Count > 0) await eco.importOrderLinje(log, "TilbudsLinje", 3, orders); orders = null; // clear memory log.Items = null; log.ItemGroups = null; log.PriceLists = null; log.Payments = null; log.Employees = null; await eco.importContact(log); if (log.window.Terminate) return ErrorCodes.NoSucces; var AfdSplit = DepartSplit.importAfdelingFordeling(log); // we we do not import years, we do not import transaction if (log.years != null && log.years.Length > 0) await eco.importGLTrans(log, AfdSplit); eco.UpdateVATonAccount(log); return ErrorCodes.Succes; } public static async Task importDepartment(importLog log) { if (!log.OpenFile("Afdeling")) { return; } try { List<string> lines; var lst = new List<GLDimType1>(); while ((lines = log.GetLine(2)) != null) { var rec = new GLDimType1(); rec._Dim = lines[0]; if (string.IsNullOrWhiteSpace(rec._Dim)) continue; rec._Name = lines[1]; lst.Add(rec); log.HasDepartment = true; } await log.Insert(lst); if (log.HasDepartment) { log.dim1 = new SQLCache(lst.ToArray(), true); var cc = log.api.CompanyEntity; cc._Dim1 = "Afdeling"; cc.NumberOfDimensions = 1; log.api.UpdateNoResponse(cc); } } catch (Exception ex) { log.Ex(ex); } } public static async Task importEmployee(importLog log) { if (!log.OpenFile("ProjektMedarbejder")) { return; } try { List<string> lines; var dim1 = log.dim1; var dim2 = log.dim2; var dim3 = log.dim3; var lst = new Dictionary<string, Employee>(StringNoCaseCompare.GetCompare()); while ((lines = log.GetLine(16)) != null) { var rec = new Employee(); rec._Number = lines[0]; if (rec._Number == string.Empty) continue; rec._Title = ContactTitle.Employee; rec._Name = lines[3]; rec._Address1 = lines[4]; rec._ZipCode = lines[5]; rec._City = lines[6]; if (lines[13] != string.Empty) rec._Hired = DateTime.Parse(lines[13]); if (lines[14] != string.Empty) rec._Terminated = DateTime.Parse(lines[14]); if (!lst.ContainsKey(rec.KeyStr)) lst.Add(rec.KeyStr, rec); } await log.Insert(lst.Values); var accs = lst.Values.ToArray(); log.Employees = new SQLCache(accs, true); } catch (Exception ex) { log.Ex(ex); } } static async Task importYear(importLog log, string Filname) { if (!log.OpenFile(Filname)) { log.AppendLogLine("Financial years not imported. No transactions will be imported"); return; } try { List<string> lines; var lst = new List<CompanyFinanceYear>(); var now = DateTime.Now; while ((lines = log.GetLine(4)) != null) { var rec = new CompanyFinanceYear(); rec._FromDate = DateTime.Parse(lines[1]); rec._ToDate = DateTime.Parse(lines[2]); rec._State = FinancePeriodeState.Open; // set to open, otherwise we can't import transactions rec.OpenAll(); if (rec._FromDate <= now && rec._ToDate >= now) rec._Current = true; log.AppendLogLine(rec._FromDate.ToShortDateString()); lst.Add(rec); } var err = await log.Insert(lst); if (err != 0) log.AppendLogLine("Financial years not imported. No transactions will be imported"); else log.years = lst.ToArray(); } catch (Exception ex) { log.Ex(ex); } } static async Task<ErrorCodes> importCOA(importLog log) { if (!log.OpenFile("konto")) { return ErrorCodes.FileDoesNotExist; } try { List<string> lines; var lst = new Dictionary<string, GLAccount>(StringNoCaseCompare.GetCompare()); while ((lines = log.GetLine(14)) != null) { var rec = new MyGLAccount(); rec.SetDimUsed(1, true); // we might have afdeling rec._Account = lines[0]; rec._Name = lines[1]; var t = (int)NumberConvert.ToInt(lines[2]); switch (t) { case 5: rec._AccountType = (byte)GLAccountTypes.Header; rec._PageBreak = true; rec._MandatoryTax = VatOptions.NoVat; break; case 4: rec._AccountType = (byte)GLAccountTypes.Header; rec._MandatoryTax = VatOptions.NoVat; break; case 3: rec._AccountType = (byte)GLAccountTypes.Sum; rec._SumInfo = lines[3] + ".." + lines[0]; rec._MandatoryTax = VatOptions.NoVat; break; case 1: rec._AccountType = (byte)GLAccountTypes.PL; break; case 2: rec._AccountType = (byte)GLAccountTypes.BalanceSheet; if (rec._Name.IndexOf("bank", StringComparison.CurrentCultureIgnoreCase) >= 0) { rec._MandatoryTax = VatOptions.NoVat; rec._AccountType = (byte)GLAccountTypes.Bank; } break; case 6: rec._AccountType = (byte)GLAccountTypes.Sum; rec._MandatoryTax = VatOptions.NoVat; if (rec._Account == "6112") rec._SumInfo = "1000..4990"; else if (rec._Account == "6199") rec._SumInfo = "1000..4990;6100..6199"; else if (rec._Account == "8999") rec._SumInfo = "1000..4990;6000..8999"; break; } if (!lst.ContainsKey(rec.KeyStr)) lst.Add(rec.KeyStr, rec); } var err = await log.Insert(lst.Values); if (err != 0) return err; var accs = lst.Values.ToArray(); log.LedgerAccounts = new SQLCache(accs, true); return ErrorCodes.Succes; } catch (Exception ex) { log.Ex(ex); return ErrorCodes.Exception; } } static async Task importMoms(importLog log, string Filename) { if (!log.OpenFile(Filename)) { return; } try { List<string> lines; var LedgerAccounts = log.LedgerAccounts; string lastAcc = null, lastAccOffset = null; var lst = new List<GLVat>(); while ((lines = log.GetLine(5)) != null) { var rec = new GLVat(); rec._Vat = lines[0]; rec._Name = lines[2]; rec._Account = lines[1]; rec._OffsetAccount = lines[5]; rec._Rate = importLog.ToDouble(lines[4]); if (rec._Account != string.Empty && rec._OffsetAccount != string.Empty) rec._Method = GLVatCalculationMethod.Netto; else rec._Method = GLVatCalculationMethod.Brutto; var t = NumberConvert.ToInt(lines[3]); switch (t) { case 1: case 3: rec._VatType = GLVatSaleBuy.Sales; if (log.CompCountryCode == CountryCode.Norway) { if (rec._Rate == 25.00d) rec._TypeSales = "s3"; else if (rec._Rate == 15.00d) rec._TypeSales = "s4"; else if (rec._Rate == 8.00d) rec._TypeSales = "s5"; else rec._TypeSales = "s10"; } else { rec._TypeSales = "s1"; } break; case 2: rec._VatType = GLVatSaleBuy.Buy; if (log.CompCountryCode == CountryCode.Norway) { if (rec._Rate == 25.00d) rec._TypeBuy = "k1"; else if (rec._Rate == 15.00d) rec._TypeBuy = "k2"; else if (rec._Rate == 8.00d) rec._TypeBuy = "k8"; else rec._TypeBuy = "k99"; } else { rec._TypeBuy = "k1"; } break; } switch(rec._Vat) { case "B25": rec._TypeBuy = "k3"; break; case "HREP": rec._TypeBuy = "k1"; break; case "REP": rec._TypeBuy = "k1"; break; case "I25": rec._TypeBuy = "k1"; break; case "IV25": rec._TypeBuy = "k4"; break; case "IY25": rec._TypeBuy = "k5"; break; case "U25": rec._TypeSales = "s1"; break; case "UEUV": rec._TypeSales = "s3"; break; case "UV0": rec._TypeSales = "s3"; break; case "UY0": rec._TypeSales = "s4"; break; case "Abr": rec._TypeSales = "s6"; break; } lst.Add(rec); if (rec._Account != "" && rec._Account != lastAcc) { lastAcc = rec._Account; var acc = (MyGLAccount)LedgerAccounts.Get(lastAcc); if (acc != null) { acc._SystemAccount = rec._VatType == GLVatSaleBuy.Sales ? (byte)SystemAccountTypes.SalesTaxPayable : (byte)SystemAccountTypes.SalesTaxReceiveable; acc.HasChanges = true; } } if (rec._VatType == GLVatSaleBuy.Buy && rec._OffsetAccount != "" && rec._OffsetAccount != lastAccOffset) { lastAccOffset = rec._OffsetAccount; var acc = (MyGLAccount)LedgerAccounts.Get(lastAccOffset); if (acc != null) { acc._SystemAccount = (byte)SystemAccountTypes.SalesTaxOffset; acc.HasChanges = true; } } } await log.Insert(lst); } catch (Exception ex) { log.Ex(ex); } } static void importAfgift(importLog log, string Filename) { if (!log.OpenFile(Filename)) { return; } try { var LedgerAccounts = log.LedgerAccounts; List<string> lines; while ((lines = log.GetLine(2)) != null) { var rec = (MyGLAccount)LedgerAccounts.Get(lines[1]); if (rec == null) continue; rec._SystemAccount = (byte)SystemAccountTypes.OtherTax; rec.HasChanges = true; } } catch (Exception ex) { log.Ex(ex); } } static void UpdateVATonAccount(importLog log) { if (log.VatIsUpdated) return; if (!log.OpenFile("konto")) { return; } try { log.AppendLogLine("Update VAT on Chart of Account"); List<string> lines; var lst = new List<GLAccount>(); var LedgerAccounts = log.LedgerAccounts; while ((lines = log.GetLine(14)) != null) { var rec = (MyGLAccount)LedgerAccounts.Get(lines[0]); if (rec == null) continue; rec._Vat = lines[4]; if (rec._Vat != string.Empty) { rec._MandatoryTax = VatOptions.Fixed; rec.HasChanges = true; } rec._DefaultOffsetAccount = lines[6]; if (rec._DefaultOffsetAccount != string.Empty) rec.HasChanges = true; rec._PrimoAccount = lines[7]; if (rec._PrimoAccount != string.Empty) rec.HasChanges = true; if (lines[12] != "0") { rec.SetDimMandatory(1, true); rec.HasChanges = true; } if (rec.HasChanges) lst.Add(rec); } log.Update(lst); log.VatIsUpdated = true; } catch (Exception ex) { log.Ex(ex); } } static void importSystemKonti(importLog log) { if (!log.OpenFile("SystemKonto")) { return; } try { List<string> lines; var lst = new List<GLAccount>(); var LedgerAccounts = log.LedgerAccounts; while ((lines = log.GetLine(2)) != null) { var rec = (GLAccount)LedgerAccounts.Get(lines[1]); if (rec != null) { switch (lines[0]) { case "Årsavslutning": case "Årsafslutning" : rec._SystemAccount = (byte)SystemAccountTypes.EndYearResultTransfer; c5.ClearDimension(rec); break; case "Gevinst på valutakursdifferanse, kunder": case "Gevinst på valutakursdifference, kunder" : rec._SystemAccount = (byte)SystemAccountTypes.ExchangeDif; break; case "Feilkonto": case "Fejlkonto": rec._SystemAccount = (byte)SystemAccountTypes.ErrorAccount; break; default: continue; } lst.Add(rec); } } log.Update(lst); } catch (Exception ex) { log.Ex(ex); } } static async Task importDebtorGroup(importLog log) { if (!log.OpenFile("KundeGruppe")) { return; } try { ErrorCodes err; List<string> lines; string lastAcc = null; var LedgerAccounts = log.LedgerAccounts; var lst = new Dictionary<string, DebtorGroup>(StringNoCaseCompare.GetCompare()); while ((lines = log.GetLine(3)) != null) { var rec = new DebtorGroup(); rec._Group = lines[0]; rec._Name = lines[1]; rec._SummeryAccount = lines[2]; rec._UseFirstIfBlank = true; if (!lst.Any()) rec._Default = true; if (!lst.ContainsKey(rec.KeyStr)) lst.Add(rec.KeyStr, rec); if (rec._SummeryAccount != "" && rec._SummeryAccount != lastAcc) { lastAcc = rec._SummeryAccount; var acc = (MyGLAccount)LedgerAccounts.Get(lastAcc); if (acc != null) { acc._AccountType = (byte)GLAccountTypes.Debtor; acc.HasChanges = true; } } } err = await log.Insert(lst.Values); var accs = lst.Values.ToArray(); log.DebGroups = new SQLCache(accs, true); } catch (Exception ex) { log.Ex(ex); } } static async Task importCreditorGroup(importLog log) { if (!log.OpenFile("LeverandoerGruppe")) { return; } try { ErrorCodes err; List<string> lines; string lastAcc = null; var LedgerAccounts = log.LedgerAccounts; var lst = new Dictionary<string, CreditorGroup>(StringNoCaseCompare.GetCompare()); while ((lines = log.GetLine(3)) != null) { var rec = new CreditorGroup(); rec._Group = lines[0]; rec._Name = lines[1]; rec._SummeryAccount = lines[2]; rec._UseFirstIfBlank = true; if (!lst.Any()) rec._Default = true; if (!lst.ContainsKey(rec.KeyStr)) lst.Add(rec.KeyStr, rec); if (rec._SummeryAccount != "" && rec._SummeryAccount != lastAcc) { lastAcc = rec._SummeryAccount; var acc = (MyGLAccount)LedgerAccounts.Get(lastAcc); if (acc != null) { acc._AccountType = (byte)GLAccountTypes.Creditor; acc.HasChanges = true; } } } err = await log.Insert(lst.Values); var accs = lst.Values.ToArray(); log.CreGroups = new SQLCache(accs, true); } catch (Exception ex) { log.Ex(ex); } } static async Task importInvGroup(importLog log) { if (!log.OpenFile("VareGruppe")) { return; } try { List<string> lines; var lst = new Dictionary<string, InvGroup>(StringNoCaseCompare.GetCompare()); while ((lines = log.GetLine(6)) != null) { var rec = new InvGroup(); rec._Group = lines[0]; rec._Name = lines[1]; rec._RevenueAccount = lines[2]; rec._RevenueAccount1 = lines[3]; rec._RevenueAccount2 = lines[4]; rec._RevenueAccount3 = lines[5]; rec._RevenueAccount4 = rec._RevenueAccount; rec._UseFirstIfBlank = true; if (!lst.Any()) rec._Default = true; if (!lst.ContainsKey(rec.KeyStr)) lst.Add(rec.KeyStr, rec); } await log.Insert(lst.Values); var accs = lst.Values.ToArray(); log.ItemGroups = new SQLCache(accs, true); } catch (Exception ex) { log.Ex(ex); } } static async Task importInv(importLog log) { if (!log.OpenFile("Vare")) { return; } try { List<string> lines; var grpCache = log.ItemGroups; var lst = new Dictionary<string, InvItem>(StringNoCaseCompare.GetCompare()); while ((lines = log.GetLine(10)) != null) { var rec = new InvItem(); rec._Item = lines[0]; if (string.IsNullOrEmpty(rec._Item)) continue; rec._Name = lines[1]; if (grpCache.Get(lines[3]) != null) rec._Group = lines[3]; rec._SalesPrice1 = importLog.ToDouble(lines[4]); rec._CostPrice = importLog.ToDouble(lines[5]); rec._Unit = importLog.ConvertUnit(lines[6]); if (!lst.ContainsKey(rec.KeyStr)) lst.Add(rec.KeyStr, rec); } await log.Insert(lst.Values); var accs = lst.Values.ToArray(); log.HasItem = accs.Length > 0; log.Items = new SQLCache(accs, true); } catch (Exception ex) { log.Ex(ex); } } static async Task importOrder(importLog log, string filename, byte DCType, Dictionary<long, UnicontaBaseEntity> orders) { if (!log.OpenFile(filename)) { return; } try { var Debtors = log.Debtors; List<string> lines; int MaxOrderNumber = 0; while ((lines = log.GetLine(40)) != null) { var KladdeNr = NumberConvert.ToInt(lines[0]); if (KladdeNr == 0) continue; var deb = Debtors.Get(lines[3]); if (deb == null) continue; DCOrder rec; if (DCType == 1) rec = new DebtorOrder(); else rec = new DebtorOffer(); rec._OrderNumber = (int)NumberConvert.ToInt(lines[1]); if (rec._OrderNumber > MaxOrderNumber) MaxOrderNumber = rec._OrderNumber; rec._DCAccount = deb.KeyStr; rec._DeliveryAddress1 = lines[11]; var str = string.Format("{0} {1}", lines[12], lines[13]); if (str.Length > 1) rec._DeliveryAddress2 = str; if (lines[14] != string.Empty) { VatZones vatz; rec._DeliveryCountry = c5.convertCountry(lines[14], log.CompCountryCode, out vatz); } rec._DeliveryAddress3 = lines[14]; if (lines[16] != string.Empty) rec._DeliveryDate = DateTime.Parse(lines[16]); rec._Currency = log.ConvertCur(lines[26]); rec._Remark = lines[23]; rec._YourRef = lines[36]; rec._Requisition = lines[37]; rec._OurRef = lines[38]; orders.Add(KladdeNr, (UnicontaBaseEntity)rec); } await log.Insert(orders.Values); if (DCType == 1) { var arr = await log.api.Query<CompanySettings>(); if (arr != null && arr.Length > 0) { arr[0]._SalesOrder = MaxOrderNumber; log.api.UpdateNoResponse(arr[0]); } } } catch (Exception ex) { log.Ex(ex); } } static async Task importOrderLinje(importLog log, string filename, byte DCType, Dictionary<long, UnicontaBaseEntity> orders) { if (!log.OpenFile(filename)) { return; } try { var Items = log.Items; List<string> lines; var lst = new List<UnicontaBaseEntity>(); while ((lines = log.GetLine(12)) != null) { var KladdeNr = NumberConvert.ToInt(lines[0]); if (KladdeNr == 0) continue; UnicontaBaseEntity order; if (! orders.TryGetValue(KladdeNr, out order)) continue; DCOrderLine rec; if (DCType == 1) rec = new DebtorOrderLine(); else rec = new DebtorOfferLine(); rec._LineNumber = NumberConvert.ToInt(lines[1]); if (!string.IsNullOrEmpty(lines[2])) { var item = (InvItem)Items.Get(lines[2]); if (item == null) continue; rec._Item = item._Item; rec._CostPrice = item._CostPrice; } rec._Text = lines[3]; rec._Qty = importLog.ToDouble(lines[4]); rec._Price = importLog.ToDouble(lines[5]); rec._DiscountPct = importLog.ToDouble(lines[6]); rec.SetMaster(order); lst.Add((UnicontaBaseEntity)rec); } await log.Insert(lst); } catch (Exception ex) { log.Ex(ex); } } static async Task importPaymentGroup(importLog log) { if (!log.OpenFile("BetalingsBetingelser")) { return; } try { List<string> lines; var lst = new Dictionary<string, PaymentTerm>(StringNoCaseCompare.GetCompare()); while ((lines = log.GetLine(4)) != null) { var rec = new PaymentTerm(); rec._Payment = lines[0]; rec._Name = lines[1]; rec._Days = (int)NumberConvert.ToInt(lines[3]); var t = (int)NumberConvert.ToInt(lines[2]); switch (t) { case 0: rec._PaymentMethod = PaymentMethodTypes.NetCash; rec._OffsetAccount = lines[4]; break; case 1: rec._PaymentMethod = PaymentMethodTypes.NetDays; break; case 2: rec._PaymentMethod = PaymentMethodTypes.EndMonth; break; } if (!lst.Any()) rec._Default = true; if (!lst.ContainsKey(rec.KeyStr)) lst.Add(rec.KeyStr, rec); } log.pTerms = lst.Values.ToList(); await log.Insert(lst.Values); var accs = lst.Values.ToArray(); log.Payments = new SQLCache(accs, true); } catch (Exception ex) { log.Ex(ex); } } static async Task importCreditor(importLog log) { if (!log.OpenFile("Leverandoer")) { return; } try { ErrorCodes err; List<string> lines; var grpCache = log.CreGroups; var lst = new Dictionary<string, Creditor>(StringNoCaseCompare.GetCompare()); while ((lines = log.GetLine(23)) != null) { var rec = new Creditor(); rec._Account = lines[0]; if (grpCache.Get(lines[1]) != null) rec._Group = lines[1]; rec._Name = lines[2]; rec._Address1 = lines[3]; rec._ZipCode = lines[4]; rec._City = lines[5]; rec._Address2 = lines[6]; rec._PaymentId = lines[12]; rec._LegalIdent = lines[13]; rec._ContactEmail = lines[16]; rec._PostingAccount = lines[20]; if (lines[22].Length != 0) rec._ContactPerson = lines[22]; else rec._ContactPerson = lines[21]; var t = (int)NumberConvert.ToInt(lines[8]); if (t > 0) rec._VatZone = (VatZones)(t - 1); rec._Country = c5.convertCountry(lines[7], log.CompCountryCode, out rec._VatZone); rec._Currency = log.ConvertCur(lines[9]); var pay = lines[11]; foreach (var p in log.pTerms) if (p._Name == pay) { rec._Payment = p._Payment; break; } if (!lst.ContainsKey(rec.KeyStr)) lst.Add(rec.KeyStr, rec); /* Now we have PostingAccount, so we do not need to update ledger if (lines[20] != "" && lines[20] != lastAcc) { lastAcc = lines[20]; var acc = new GLAccount(); acc._Account = lastAcc; err = await log.api.Read(acc); if (err == 0 && acc._DefaultOffsetAccount != null) { acc._DefaultOffsetAccountType = GLJournalAccountType.Creditor; acc._DefaultOffsetAccount = rec._Account; acclst.Add(acc); } } */ } await log.Insert(lst.Values); var accs = lst.Values.ToArray(); log.HasCreditor = accs.Length > 0; log.Creditors = new SQLCache(accs, true); } catch (Exception ex) { log.Ex(ex); } } static async Task importDebitor(importLog log) { if (!log.OpenFile("Kunde")) { return; } try { List<string> lines; var Employees = log.Employees; var grpCache = log.DebGroups; var lst = new Dictionary<string, Debtor>(StringNoCaseCompare.GetCompare()); while ((lines = log.GetLine(22)) != null) { var rec = new Debtor(); rec._Account = lines[0]; var key = grpCache.Get(lines[1]); if (key != null) rec._Group = key.KeyStr; rec._Name = lines[2]; rec._Address1 = lines[3]; rec._ZipCode = lines[4]; rec._City = lines[5]; rec._Phone = lines[7]; rec._ContactEmail = lines[8]; rec._LegalIdent = lines[13]; rec._EAN = lines[14]; rec._ContactPerson = lines[17]; rec._CreditMax = importLog.ToDouble(lines[20]); var t = (int)NumberConvert.ToInt(lines[11]); if (t > 0) rec._VatZone = (VatZones)(t - 1); rec._Country = c5.convertCountry(lines[6], log.CompCountryCode, out rec._VatZone); rec._Currency = log.ConvertCur(lines[12]); var pay = lines[15]; foreach (var p in log.pTerms) if (p._Name == pay) { rec._Payment = p._Payment; break; } key = Employees?.Get(lines[16]); if (key != null) rec._Employee = key.KeyStr; if (!lst.ContainsKey(rec.KeyStr)) lst.Add(rec.KeyStr, rec); } await log.Insert(lst.Values); var accs = lst.Values.ToArray(); log.HasDebitor = accs.Length > 0; log.Debtors = new SQLCache(accs, true); } catch (Exception ex) { log.Ex(ex); } } static async Task importContact(importLog log) { if (!log.OpenFile("KontaktPerson")) { return; } try { List<string> lines; SQLCache dcontact = log.Debtors, ccontact = log.Creditors; var lst = new List<Contact>(); while ((lines = log.GetLine(17)) != null) { var rec = new Contact(); rec._Name = lines[4]; rec._Mobil = lines[5]; rec._Email = lines[6]; if (lines[2] != "" && dcontact != null) { if (dcontact.Get(lines[2]) != null) { rec._DCAccount = lines[2]; rec._DCType = 1; } } else if (lines[3] != "" && ccontact != null) { if (ccontact.Get(lines[3]) != null) { rec._DCAccount = lines[3]; rec._DCType = 2; } } if (lines[10] != "0") rec._Invoice = true; if (lines[12] != "0") rec._AccountStatement = true; if (lines[13] != "0") rec._InterestNote = rec._CollectionLetter = true; if (string.IsNullOrWhiteSpace(rec._Name)) rec._Name = rec._DCAccount; if (string.IsNullOrWhiteSpace(rec._Name)) continue; lst.Add(rec); } if (lst.Count > 0) { await log.Insert(lst); log.HasContact = true; } } catch (Exception ex) { log.Ex(ex); } } static async Task importGLTrans(importLog log, Dictionary<string, List<DepartSplit>> AfdSplit) { if (!log.OpenFile("Postering")) { return; } try { List<string> lines; log.years = await log.api.Query<CompanyFinanceYear>(); var department = new Dictionary<string, GLDimType1>(StringNoCaseCompare.GetCompare()); var dim1 = log.dim1; var years = log.years; int nYears = years.Length; List<GLPostingLineLocal>[] YearLst = new List<GLPostingLineLocal>[nYears]; for (int i = nYears; (--i >= 0);) YearLst[i] = new List<GLPostingLineLocal>(); var Ledger = log.LedgerAccounts; DateTime FirstYearStart = years[0]._FromDate; DateTime FirstYearEnd = years[0]._ToDate; int cnt = 0; while ((lines = log.GetLine(22)) != null) { var posttype = lines[1].ToLower(); var Date = DateTime.Parse(lines[2]); if (Date < FirstYearStart || (Date > FirstYearEnd && posttype.Contains("primopostering"))) continue; bool CanSplit = false; var rec = new GLPostingLineLocal(); rec.Date = Date; rec.Account = lines[3]; rec.Voucher = (int)NumberConvert.ToInt(lines[4]); if (rec.Voucher == 0) rec.Voucher = 1; rec.Text = lines[5]; rec.Amount = importLog.ToDouble(lines[6]); var cur = log.ConvertCur(lines[7]); if (cur != 0) { rec.Currency = cur; rec.IgnoreCurDif = true; // we do not want to do any regulation in a conversion rec.AmountCur = importLog.ToDouble(lines[8]); if (rec.Amount * rec.AmountCur < 0d) // different sign { rec.Currency = null; rec.AmountCur = 0; } } if (lines[11].Length != 0) // debtor { rec.Settlements = "+"; // autosettle. rec.Account = lines[11]; rec.AccountType = GLJournalAccountType.Debtor; if (posttype.Contains("kundefaktura")) { rec.DCPostType = DCPostType.Invoice; if (lines[15].Length != 0) rec.DueDate = DateTime.Parse(lines[15]); if (lines[13].Length != 0) rec.Invoice = (int)NumberConvert.ToInt(lines[13]); } else rec.DCPostType = DCPostType.Payment; } else if (lines[12].Length != 0) // creditor { rec.Settlements = "+"; // autosettle. rec.Account = lines[12]; rec.AccountType = GLJournalAccountType.Creditor; if (posttype.Contains("leverandørfaktura")) { rec.DCPostType = DCPostType.Invoice; if (lines[15].Length != 0) rec.DueDate = DateTime.Parse(lines[15]); if (lines[14].Length != 0) rec.Invoice = (int)NumberConvert.ToInt(lines[14]); } else rec.DCPostType = DCPostType.Payment; } else // ledger { var vat = lines[16]; if (vat != string.Empty) { var acc = (MyGLAccount)Ledger.Get(rec.Account); if (acc != null) { if (acc._MandatoryTax != VatOptions.NoVat && acc.AccountTypeEnum != GLAccountTypes.Equity && acc.AccountTypeEnum != GLAccountTypes.Debtor && acc.AccountTypeEnum != GLAccountTypes.Creditor && acc.AccountTypeEnum != GLAccountTypes.Bank && acc.AccountTypeEnum != GLAccountTypes.LiquidAsset) { acc.HasVat = true; rec.Vat = vat; rec.VatHasBeenDeducted = true; } CanSplit = (acc.AccountTypeEnum == GLAccountTypes.PL); } } } if (rec.AccountType > 0) { IdKey dc; if (rec.AccountType == GLJournalAccountType.Debtor) dc = log.Debtors.Get(rec.Account); else dc = log.Creditors.Get(rec.Account); if (dc != null) c5.ConvertDKText(rec, (DCAccount)dc); } List<GLPostingLineLocal> yearList = null; for (int i = nYears; (--i >= 0);) { var y = years[i]; if (y._FromDate <= Date && y._ToDate >= Date) { yearList = YearLst[i]; yearList.Add(rec); break; } } var str = lines[17]; if (str != string.Empty) { if (AfdSplit != null && AfdSplit.ContainsKey(str)) { if (CanSplit) { var amount = rec.Amount; var sumAmount = 0d; var amountCur = rec.AmountCur; var sumAmountCur = 0d; var lst = AfdSplit[str]; bool first = true; foreach (var split in lst) { if (!first) { var rec2 = new GLPostingLineLocal(); rec2.Date = Date; rec2.Account = rec.Account; rec2.Voucher = rec.Voucher; rec2.Text = rec.Text; rec2.Currency = rec.Currency; rec2.Vat = rec.Vat; rec2.VatHasBeenDeducted = rec.VatHasBeenDeducted; rec = rec2; yearList.Add(rec2); } var afd = split.Afd; rec.SetDim(1, afd); if (dim1 == null && !department.ContainsKey(afd)) { var dim = new GLDimType1(); dim._Dim = afd; department.Add(afd, dim); } rec.Amount = Math.Round(amount * split.pct / 100d, 2); sumAmount += rec.Amount; rec.AmountCur = Math.Round(amountCur * split.pct / 100d, 2); sumAmountCur += rec.AmountCur; first = false; } rec.Amount += amount - sumAmount; rec.AmountCur += amountCur - sumAmountCur; } } else if (dim1 != null) { if (dim1.Get(str) != null) rec.SetDim(1, str); } else { rec.SetDim(1, str); if (!department.ContainsKey(str)) { var dim = new GLDimType1(); dim._Dim = str; department.Add(str, dim); } } } cnt++; } if (department.Count > 0) { await log.Insert(department.Values); log.HasDepartment = true; var cc = log.api.CompanyEntity; cc._Dim1 = "Afdeling"; cc.NumberOfDimensions = 1; log.api.UpdateNoResponse(cc); log.AppendLogLine(string.Format("Afdelinger {0}", department.Count)); department = null; } log.AppendLogLine(string.Format("Number of transactions = {0}", cnt)); log.window.progressBar.Maximum = nYears; var glSort = new c5.GLTransSort(); GLPostingHeader header = new GLPostingHeader(); header.NumberSerie = "NR"; header.NoDateSum = true; var ap = new Uniconta.API.GeneralLedger.PostingAPI(log.api); for (int i = 0; (i < nYears); i++) { var arr = YearLst[i].ToArray(); YearLst[i] = null; if (arr.Length > 0) { header.Comment = string.Format("Import {0} - {1} ", years[i]._FromDate.ToShortDateString(), years[i]._ToDate.ToShortDateString()); Array.Sort(arr, glSort); c5.UpdateLedgerTrans(arr); var res = await ap.PostJournal(header, arr, false); if (res.Err != 0) { log.AppendLogLine("Fejl i poster i " + header.Comment); await log.Error(res.Err); } else log.AppendLogLine("Posting " + header.Comment); } log.window.UpdateProgressbar(i, null); } foreach (var ac in (MyGLAccount[])Ledger.GetNotNullArray) { if (!ac.HasVat && ac._MandatoryTax != VatOptions.NoVat) { ac._MandatoryTax = VatOptions.NoVat; ac.HasChanges = true; } } eco.UpdateVATonAccount(log); log.AppendLogLine("Generate Primo Transactions"); var ap2 = new FinancialYearAPI(ap); for (int i = 1; (i < nYears); i++) { await ap2.GeneratePrimoTransactions(years[i], null, null, 9999, "NR"); } log.window.UpdateProgressbar(0, "Done"); } catch (Exception ex) { log.Ex(ex); } } } } <file_sep>/Utility/UtilFunctions.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using Uniconta.Common; namespace ImportingTool.Utility { public class UtilFunctions { public static void ShowErrorMessage(ErrorCodes ec) { MessageBox.Show(ec.ToString()); } } } <file_sep>/Pages/LoginWindow.xaml.cs using Uniconta.Common; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using ImportingTool.Utility; namespace ImportingTool.Pages { /// <summary> /// Interaction logic for LoginWindow.xaml /// </summary> public partial class LoginWindow : Window { static Guid ImportToolGuid = new Guid("00000000-0000-0000-0000-000000000000"); public LoginWindow() { InitializeComponent(); this.loginCtrl.loginButton.Click += loginButton_Click; this.loginCtrl.CancelButton.Click += CancelButton_Click; } void CancelButton_Click(object sender, RoutedEventArgs e) { this.DialogResult = false; } async void loginButton_Click(object sender, RoutedEventArgs e) { string password = <PASSWORD>; string userName = loginCtrl.UserName; if (ImportToolGuid == Guid.Empty) { MessageBox.Show("You need to have your own valid App id, obtained at your Uniconta partner or at Uniconta directly", "Error", MessageBoxButton.OK, MessageBoxImage.Error); return; } ErrorCodes errorCode = await SetLogin(userName, password); if (errorCode == ErrorCodes.Succes) { Uniconta.ClientTools.Localization.SetDefault((Language)SessionInitializer.CurrentSession.User._Language); this.DialogResult = true; } else UtilFunctions.ShowErrorMessage(errorCode); } private async Task<ErrorCodes> SetLogin(string username, string password) { if (! ValidateUserCredentials(username, password)) return ErrorCodes.NoSucces; try { var ses = SessionInitializer.GetSession(); return await ses.LoginAsync(username, password, Uniconta.Common.User.LoginType.PC_Windows, ImportToolGuid); } catch (Exception ex) { MessageBox.Show(ex.Message, "Fatal Error", MessageBoxButton.OK, MessageBoxImage.Error); this.Close(); return ErrorCodes.Exception; } } private bool ValidateUserCredentials(string username, string password) { if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password)) return true; return false; } } } <file_sep>/SessionInitializer.cs using Uniconta.API.Service; using Uniconta.API.System; using Uniconta.DataModel; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.CompilerServices; namespace ImportingTool { public static class SessionInitializer { /// <summary> /// Proeprty for Current Company /// </summary> public static Company CurrentCompany; /// <summary> /// Property for Containing Companies List /// </summary> public static Company[] Companies; /// <summary> /// Property for Session Variable /// </summary> public static Session CurrentSession; /// <summary> /// Property for Getting and setting the UserName /// </summary> public static string UserName; /// <summary> /// Property for getting and setting the Password /// </summary> public static string Password; /// <summary> /// Property to save User Information /// </summary> public static bool IsUserPersist; /// <summary> /// Readonly Property to Get base API instance /// </summary> public static CrudAPI GetBaseAPI { get { return new CrudAPI(CurrentSession, CurrentCompany); } } /// <summary> /// /// </summary> /// <param name="companyId"></param> /// <returns></returns> async public static Task SetCompany(int companyId) { CurrentCompany = CurrentSession.GetOpenCompany(companyId); if (CurrentCompany != null) CurrentSession.DefaultCompany = CurrentCompany; else CurrentCompany = await CurrentSession.OpenCompany(companyId, true); } /// <summary> /// Method to Get the Current Session /// </summary> /// <returns></returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Session GetSession() { return CurrentSession; } /// <summary> /// Method to Set all the Companies for the Loged In User /// </summary> /// <returns></returns> async public static Task SetupCompanies() { if (CurrentSession != null) Companies = await CurrentSession.GetCompanies(); } public static Session InitUniconta() { if (CurrentSession == null) { var corasauConnection = new UnicontaConnection(APITarget.Live); CurrentSession = new Session(corasauConnection); } return CurrentSession; } } } <file_sep>/Model/c5.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Uniconta.API.Service; using Uniconta.API.System; using Uniconta.Common; using Uniconta.DataModel; using System.IO; using Uniconta.Common.Utility; using Uniconta.API.GeneralLedger; using System.Threading; using Uniconta.ClientTools; using System.ComponentModel; using System.Windows.Controls; using System.Windows.Threading; namespace ImportingTool.Model { static public class c5 { //Get zipcode static public string GetZipCode(string zipcity) { if (zipcity.Contains(" ")) { string zip = zipcity.Substring(0, zipcity.IndexOf(" ", StringComparison.Ordinal)); return zip.Trim(); } else { string zip = zipcity; if (zip.Length > 4) zip = zip.Substring(0, 4); return zip; } } //Get country static public string GetCity(string zipcity) { if (zipcity.Contains(" ")) { string city = zipcity.Substring(zipcity.IndexOf(" ", StringComparison.Ordinal) + 1); return city.Trim(); } else { string city; if (zipcity.Length > 4) city = zipcity.Substring(4, zipcity.Length - 4); else city = ""; return city; } } static public async Task<ErrorCodes> importAll(importLog log, int DimensionImport) { if (log.Set0InAccount) c5.getGLAccountLen(log); if (DimensionImport >= 1) await c5.importDepartment(log); if (DimensionImport >= 2) await c5.importCentre(log); if (DimensionImport >= 3) await c5.importPurpose(log); c5.importCompany(log); await c5.importYear(log); var err = await c5.importCOA(log); if (err != 0) return err; // we will need to update system account, since we need it in posting c5.importSystemKonti(log); err = await c5.importMoms(log); if (err != 0) return err; await c5.importDebtorGroup(log); await c5.importCreditorGroup(log); await c5.importEmployee(log); await c5.importShipment(log); await c5.importPaymentGroup(log); err = await c5.importDebitor(log); if (err != 0) return err; err = await c5.importCreditor(log); if (err != 0) return err; await c5.importContact(log, 1); await c5.importContact(log, 2); await c5.importInvGroup(log); await c5.importPriceGroup(log); var items = c5.importInv(log); if (items != null) { await c5.importInvPrices(log, items); await c5.importInvBOM(log); } var orders = new Dictionary<long, DebtorOrder>(); await c5.importOrder(log, orders); if (orders.Count > 0) await c5.importOrderLinje(log, orders); orders = null; var purchages = new Dictionary<long, CreditorOrder>(); await c5.importPurchage(log, purchages); if (purchages.Count > 0) await c5.importPurchageLinje(log, purchages); purchages = null; // clear memory log.Items = null; log.ItemGroups = null; log.PriceLists = null; log.Payments = null; log.Employees = null; if (log.window.Terminate) return ErrorCodes.NoSucces; // we we do not import years, we do not import transaction if (log.years != null && log.years.Length > 0) { DCImportTrans[] debpost = null; if (log.Debtors != null) debpost = importDCTrans(log, true, log.Debtors); DCImportTrans[] krepost = null; if (log.Creditors != null) krepost = importDCTrans(log, false, log.Creditors); await c5.importGLTrans(log, debpost, krepost); } // We do that after posting is called, since we have fixe vat and other things that can prevent posting c5.UpdateVATonAccount(log); return ErrorCodes.Succes; } public static async Task importYear(importLog log) { if (!log.OpenFile("exp00031", "Finansperioder")) { log.AppendLogLine("Financial years not imported. No transactions will be imported"); return; } try { // first we load primo and ultimo periodes. List<List<string>> ValidLines = new List<List<string>>(); List<string> lin; while ((lin = log.GetLine(8)) != null) { if (lin[3] != "0") ValidLines.Add(lin); } // then we sort it in dato order var ValidLines2 = ValidLines.OrderBy(rec => rec[0]); var lst = new List<CompanyFinanceYear>(); DateTime fromdate = DateTime.MinValue; var now = DateTime.Now; foreach (var lines in ValidLines2) { var datastr = lines[0]; int year = int.Parse(datastr.Substring(0, 4)); int month = int.Parse(datastr.Substring(5, 2)); if (lines[3] == "1") { fromdate = new DateTime(year, month, 1); } else { if (fromdate == DateTime.MinValue) fromdate = new DateTime(year, month, 1); var dayinmonth = DateTime.DaysInMonth(year, month); var ToDate = new DateTime(year, month, dayinmonth); if (fromdate > ToDate) fromdate = ToDate.AddDays(1).AddYears(-1); var rec = new CompanyFinanceYear(); rec._FromDate = fromdate; rec._ToDate = ToDate; rec._State = FinancePeriodeState.Open; // set to open, otherwise we can't import transactions rec.OpenAll(); if (rec._FromDate <= now && rec._ToDate >= now) rec._Current = true; log.AppendLogLine(rec._FromDate.ToShortDateString()); lst.Add(rec); } } var Orderedlst = lst.OrderBy(rec => rec._FromDate); var err = await log.Insert(Orderedlst); if (err != 0) log.AppendLogLine("Financial years not imported. No transactions will be imported"); else log.years = Orderedlst.ToArray(); } catch (Exception ex) { log.Ex(ex); } } public static void getGLAccountLen(importLog log) { if (!log.OpenFile("exp00025", "Finanskonti")) { return; } try { List<string> lines; int AccountPrev = 0; int Accountlen = 0, nMax = 0; while ((lines = log.GetLine(2)) != null) { var _account = log.GLAccountFromC5(lines[1]); if (_account.Length >= Accountlen) { if (_account.Length == Accountlen) nMax++; else { int i = _account.Length; while (--i >= 0) { var ch = _account[0]; if (ch < '0' || ch > '9') break; } if (i < 0) { AccountPrev = Accountlen; Accountlen = _account.Length; nMax = 0; } } } } if (nMax > 2) log.Accountlen = Accountlen; else log.Accountlen = AccountPrev; } catch (Exception ex) { log.Ex(ex); } } public static async Task<ErrorCodes> importCOA(importLog log) { if (!log.OpenFile("exp00025", "Finanskonti")) { return ErrorCodes.FileDoesNotExist; } try { List<string> lines; var lst = new Dictionary<string, GLAccount>(StringNoCaseCompare.GetCompare()); var sum = new List<string>(); while ((lines = log.GetLine(25)) != null) { var rec = new MyGLAccount(); rec._Account = log.GLAccountFromC5(lines[1]); if (string.IsNullOrWhiteSpace(rec._Account)) continue; rec._Name = lines[2]; var counters = lines[15].ToLower(); var t = GetInt(lines[3]); if (t != 6 && counters != string.Empty) { int n = 0; foreach (var r in sum) { if (string.Compare(r, counters) == 0) { rec._SaveTotal = n + 1; break; } n++; } if (rec._SaveTotal == 0) { rec._SaveTotal = n + 1; sum.Add(counters); } } switch (t) { case 0: rec._AccountType = (byte)GLAccountTypes.PL; break; case 1: rec._AccountType = (byte)GLAccountTypes.BalanceSheet; if (rec._Name.IndexOf("bank", StringComparison.CurrentCultureIgnoreCase) >= 0) rec._AccountType = (byte)GLAccountTypes.Bank; break; case 2: rec._AccountType = (byte)GLAccountTypes.Header; rec._MandatoryTax = VatOptions.NoVat; break; case 3: rec._AccountType = (byte)GLAccountTypes.Header; rec._PageBreak = true; rec._MandatoryTax = VatOptions.NoVat; break; case 4: rec._AccountType = (byte)GLAccountTypes.Header; rec._MandatoryTax = VatOptions.NoVat; break; case 5: rec._AccountType = (byte)GLAccountTypes.Sum; rec._SumInfo = log.GLAccountFromC5(lines[10]) + ".." + rec._Account; rec._MandatoryTax = VatOptions.NoVat; break; case 6: { int n = 1; foreach (var r in sum) { counters = counters.Replace(r, string.Format("Sum({0})", n)); n++; } rec._SumInfo = counters; rec._AccountType = (byte)GLAccountTypes.CalculationExpression; rec._MandatoryTax = VatOptions.NoVat; break; } } // We can't set Mandatory = true, since we can't garantie that transaction has dimensions if (log.HasDepartment) rec.SetDimUsed(1, true); if (log.HasCentre) rec.SetDimUsed(2, true); if (log.HasPorpose) rec.SetDimUsed(3, true); if (!lst.ContainsKey(rec.KeyStr)) lst.Add(rec.KeyStr, rec); } var err = await log.Insert(lst.Values); if (err != 0) return err; var accs = lst.Values.ToArray(); log.LedgerAccounts = new SQLCache(accs, true); return ErrorCodes.Succes; } catch (Exception ex) { log.Ex(ex); return ErrorCodes.Exception; } } static public void ClearDimension(GLAccount Acc) { Acc.SetDimUsed(1, false); Acc.SetDimUsed(2, false); Acc.SetDimUsed(3, false); Acc.SetDimUsed(4, false); Acc.SetDimUsed(5, false); } public static async Task<ErrorCodes> importMoms(importLog log) { if (!log.OpenFile("exp00014", "Momskoder")) { return ErrorCodes.Succes; } try { ErrorCodes err; List<string> lines; var LedgerAccounts = log.LedgerAccounts; string lastAcc = null; string lastAccOffset = null; var lst = new Dictionary<string, GLVat>(StringNoCaseCompare.GetCompare()); while ((lines = log.GetLine(11)) != null) { var rec = new GLVat(); rec._Vat = lines[0]; if (string.IsNullOrWhiteSpace(rec._Vat)) continue; rec._Name = lines[1]; rec._Account = log.GLAccountFromC5_Validate(lines[3]); rec._OffsetAccount = log.GLAccountFromC5_Validate(lines[4]); var Rate = importLog.ToDouble(lines[2]); var Excempt = importLog.ToDouble(lines[5]); rec._Rate = Rate * (100d - Excempt) / 100d; if (rec._Account != string.Empty && rec._OffsetAccount != string.Empty) rec._Method = GLVatCalculationMethod.Netto; else rec._Method = GLVatCalculationMethod.Brutto; int vatId; var vattype = lines[10].ToLower(); if (string.IsNullOrEmpty(vattype)) { if (vattype.Contains("salg")) vatId = 1; else if (vattype.Contains("køb") || vattype.Contains("indg") || vattype.Contains("import")) vatId = 2; else vatId = 1; } else vatId = GetInt(vattype); switch (vatId) { case 0: case 1: rec._VatType = GLVatSaleBuy.Sales; rec._TypeSales = "s1"; break; case 2: rec._VatType = GLVatSaleBuy.Buy; rec._TypeBuy = "k1"; break; } // Here we are assigning the VAT operations. You can see that on the VAT table on the VAT operations switch (rec._Vat.ToLower()) { case "b25": rec._TypeBuy = "k3"; rec._VatType = GLVatSaleBuy.Buy; break; case "hrep": case "repr": case "rep": rec._TypeBuy = "k1"; rec._VatType = GLVatSaleBuy.Buy; rec._Rate = 6.25d; break; case "i25": rec._TypeBuy = "k1"; rec._VatType = GLVatSaleBuy.Buy; break; case "umoms": case "iv25": rec._TypeBuy = "k4"; rec._VatType = GLVatSaleBuy.Buy; break; case "iy25": rec._TypeBuy = "k5"; rec._VatType = GLVatSaleBuy.Buy; break; case "u25": rec._TypeSales = "s1"; rec._VatType = GLVatSaleBuy.Sales; break; case "ueuv": rec._TypeSales = "s3"; rec._VatType = GLVatSaleBuy.Sales; break; case "uv0": rec._TypeSales = "s3"; rec._VatType = GLVatSaleBuy.Sales; break; case "ueuy": rec._TypeSales = "s4"; rec._VatType = GLVatSaleBuy.Sales; break; case "uy0": rec._TypeSales = "s4"; rec._VatType = GLVatSaleBuy.Sales; break; case "abr": rec._TypeSales = "s6"; rec._VatType = GLVatSaleBuy.Sales; break; } if (!lst.ContainsKey(rec.KeyStr)) lst.Add(rec.KeyStr, rec); if (rec._Account != "" && rec._Account != lastAcc) { lastAcc = rec._Account; var acc = (MyGLAccount)LedgerAccounts.Get(lastAcc); if (acc != null) { acc._SystemAccount = rec._VatType == GLVatSaleBuy.Sales ? (byte)SystemAccountTypes.SalesTaxPayable : (byte)SystemAccountTypes.SalesTaxReceiveable; acc.HasChanges = true; } } if (rec._VatType == GLVatSaleBuy.Buy && rec._OffsetAccount != "" && rec._OffsetAccount != lastAccOffset) { lastAccOffset = rec._OffsetAccount; var acc = (MyGLAccount)LedgerAccounts.Get(lastAccOffset); if (acc != null) { acc._SystemAccount = (byte)SystemAccountTypes.SalesTaxOffset; acc.HasChanges = true; } } } err = await log.Insert(lst.Values); if (err != 0) return err; var vats = lst.Values.ToArray(); log.vats = new SQLCache(vats, true); return 0; } catch (Exception ex) { log.Ex(ex); return ErrorCodes.Exception; } } public static void UpdateVATonAccount(importLog log) { if (log.VatIsUpdated) return; if (!log.OpenFile("exp00025", "Finanskonti")) { return; } try { log.AppendLogLine("Update VAT on Chart of Account"); List<string> lines; var LedgerAccounts = log.LedgerAccounts; var acclst = new List<GLAccount>(); while ((lines = log.GetLine(16)) != null) { var rec = (MyGLAccount)LedgerAccounts.Get(log.GLAccountFromC5(lines[1])); if (rec == null) continue; var s = log.GetVat_Validate(lines[11]); if (s != string.Empty) { rec._Vat = s; rec.HasChanges = true; // To be updated laver. We risk that we can't import transactions, since we require VAT on transactions. if (lines.Count > (35 + 2) && lines[35] != "0") rec._MandatoryTax = VatOptions.Fixed; else rec._MandatoryTax = VatOptions.Optional; } s = log.GLAccountFromC5_Validate(lines[8]); if (s != string.Empty) { rec._DefaultOffsetAccount = s; rec.HasChanges = true; } rec._Currency = log.ConvertCur(lines[13]); if (rec._Currency != 0) rec.HasChanges = true; if (lines.Count > (36 + 2)) { s = log.GLAccountFromC5_Validate(lines[36]); if (s != string.Empty) { rec._PrimoAccount = s; rec.HasChanges = true; } } if (rec.HasChanges) acclst.Add(rec); } log.Update(acclst); log.VatIsUpdated = true; } catch (Exception ex) { log.Ex(ex); } } public static async Task importPriceGroup(importLog log) { if (!log.OpenFile("exp00064", "Prisgrupper")) { return; } List<string> lines; try { var lst = new Dictionary<string, DebtorPriceList>(StringNoCaseCompare.GetCompare()); while ((lines = log.GetLine(3)) != null) { var rec = new DebtorPriceList(); rec._Name = lines[0]; if (string.IsNullOrWhiteSpace(rec._Name)) continue; rec._InclVat = lines[2] == "1"; if (!lst.ContainsKey(rec.KeyStr)) lst.Add(rec.KeyStr, rec); } await log.Insert(lst.Values); var accs = lst.Values.ToArray(); log.PriceLists = new SQLCache(accs, true); } catch (Exception ex) { log.Ex(ex); } } public static void importSystemKonti(importLog log) { if (!log.OpenFile("exp00013", "SystemKonti")) { return; } try { List<string> lines; var lst = new List<GLAccount>(); var LedgerAccounts = log.LedgerAccounts; while ((lines = log.GetLine(15)) != null) { if (lines[1] == "0") { var rec = (MyGLAccount)LedgerAccounts.Get(log.GLAccountFromC5(lines[4])); if (rec == null) continue; switch (lines[0]) { case "ÅretsResultat" : case "SYS60928": rec._SystemAccount = (byte)SystemAccountTypes.EndYearResultTransfer; if (log.errorAccount == null) log.errorAccount = rec.KeyStr; ClearDimension(rec); break; case "Sek.Val.Afrunding" : case "SYS60933": rec._SystemAccount = (byte)SystemAccountTypes.ExchangeDif; log.valutaDif = rec.KeyStr; if (log.errorAccount == null) log.errorAccount = rec.KeyStr; break; case "Fejlkonto": case "SYS11607": rec._SystemAccount = (byte)SystemAccountTypes.ErrorAccount; log.errorAccount = rec.KeyStr; break; case "Øredifference": case "SYS34401": rec._SystemAccount = (byte)SystemAccountTypes.PennyDif; if (log.errorAccount == null) log.errorAccount = rec.KeyStr; break; case "AfgiftOlie": case "SYS60929": case "AfgiftEl": case "SYS60930": case "AfgiftVand": case "SYS60931": case "AfgiftKul": case "SYS60932": rec._SystemAccount = (byte)SystemAccountTypes.OtherTax; rec.HasChanges = true; continue; default: continue; } lst.Add(rec); } } log.Update(lst); } catch (Exception ex) { log.Ex(ex); } } public static async Task importDebtorGroup(importLog log) { if (!log.OpenFile("exp00034", "Debitorgrupper")) { return; } try { ErrorCodes err; List<string> lines; string lastAcc = null; var LedgerAccounts = log.LedgerAccounts; var lst = new Dictionary<string, DebtorGroup>(StringNoCaseCompare.GetCompare()); while ((lines = log.GetLine(10)) != null) { var rec = new DebtorGroup(); rec._Group = lines[0]; if (string.IsNullOrWhiteSpace(rec._Group)) continue; rec._Name = lines[1]; rec._SummeryAccount = log.GLAccountFromC5_Validate(lines[7]); if (string.IsNullOrWhiteSpace(rec._SummeryAccount) && lastAcc != null) rec._SummeryAccount = lastAcc; rec._RevenueAccount = log.GLAccountFromC5_Validate(lines[2]); rec._SettlementDiscountAccount = log.GLAccountFromC5_Validate(lines[8]); rec._EndDiscountAccount = log.GLAccountFromC5_Validate(lines[4]); rec._UseFirstIfBlank = true; if (!lst.Any()) rec._Default = true; if (!lst.ContainsKey(rec.KeyStr)) lst.Add(rec.KeyStr, rec); if (rec._SummeryAccount != "" && rec._SummeryAccount != lastAcc) { lastAcc = rec._SummeryAccount; var acc = (MyGLAccount)LedgerAccounts.Get(lastAcc); if (acc != null) { acc._AccountType = (byte)GLAccountTypes.Debtor; acc.HasChanges = true; } } } await log.Insert(lst.Values); var accs = lst.Values.ToArray(); log.DebGroups = new SQLCache(accs, true); } catch (Exception ex) { log.Ex(ex); } } public static async Task importCreditorGroup(importLog log) { if (!log.OpenFile("exp00042", "Kreditorgrupper")) { return; } try { ErrorCodes err; List<string> lines; string lastAcc = null; var LedgerAccounts = log.LedgerAccounts; var lst = new Dictionary<string, CreditorGroup>(StringNoCaseCompare.GetCompare()); while ((lines = log.GetLine(10)) != null) { var rec = new CreditorGroup(); rec._Group = lines[0]; if (string.IsNullOrWhiteSpace(rec._Group)) continue; rec._Name = lines[1]; rec._SummeryAccount = log.GLAccountFromC5_Validate(lines[7]); if (string.IsNullOrWhiteSpace(rec._SummeryAccount) && lastAcc != null) rec._SummeryAccount = lastAcc; rec._RevenueAccount = log.GLAccountFromC5_Validate(lines[2]); rec._SettlementDiscountAccount = log.GLAccountFromC5_Validate(lines[8]); rec._EndDiscountAccount = log.GLAccountFromC5_Validate(lines[4]); rec._UseFirstIfBlank = true; if (!lst.Any()) rec._Default = true; if (!lst.ContainsKey(rec.KeyStr)) lst.Add(rec.KeyStr, rec); if (rec._SummeryAccount != "" && rec._SummeryAccount != lastAcc) { lastAcc = rec._SummeryAccount; var acc = (MyGLAccount)LedgerAccounts.Get(lastAcc); if (acc != null) { acc._AccountType = (byte)GLAccountTypes.Creditor; acc.HasChanges = true; } } } await log.Insert(lst.Values); var accs = lst.Values.ToArray(); log.CreGroups = new SQLCache(accs, true); } catch (Exception ex) { log.Ex(ex); } } public static async Task importInvGroup(importLog log) { if (!log.OpenFile("exp00050", "Varegrupper")) { return; } try { List<string> lines; var lst = new Dictionary<string, InvGroup>(StringNoCaseCompare.GetCompare()); while ((lines = log.GetLine(15)) != null) { var rec = new InvGroup(); rec._Group = lines[0]; if (string.IsNullOrWhiteSpace(rec._Group)) continue; rec._Name = lines[1]; rec._CostAccount = log.GLAccountFromC5_Validate(lines[3]); rec._InvAccount = log.GLAccountFromC5_Validate(lines[9]); rec._InvReceipt = log.GLAccountFromC5_Validate(lines[10]); rec._RevenueAccount = log.GLAccountFromC5_Validate(lines[2]); rec._PurchaseAccount = log.GLAccountFromC5_Validate(lines[9]); rec._UseFirstIfBlank = true; if (!lst.Any()) rec._Default = true; if (! lst.ContainsKey(rec.KeyStr)) lst.Add(rec.KeyStr, rec); } var err = await log.Insert(lst.Values); if (err == 0) { var accs = lst.Values.ToArray(); log.ItemGroups = new SQLCache(accs, true); } } catch (Exception ex) { log.Ex(ex); } } public static async Task importShipment(importLog log) { if (!log.OpenFile("exp00019", "Forsendelser")) { return; } try { List<string> lines; var lst = new Dictionary<string, ShipmentType>(StringNoCaseCompare.GetCompare()); while ((lines = log.GetLine(2)) != null) { var rec = new ShipmentType(); rec._Number = lines[0]; if (rec._Number == string.Empty) continue; rec._Name = lines[1]; if (!lst.ContainsKey(rec.KeyStr)) lst.Add(rec.KeyStr, rec); } await log.Insert(lst.Values); } catch (Exception ex) { log.Ex(ex); } } public static async Task importEmployee(importLog log) { if (!log.OpenFile("exp00011", "Medarbejder")) { return; } try { List<string> lines; var dim1 = log.dim1; var dim2 = log.dim2; var dim3 = log.dim3; var lst = new Dictionary<string, Employee>(StringNoCaseCompare.GetCompare()); while ((lines = log.GetLine(12)) != null) { var rec = new Employee(); rec._Number = lines[0]; if (rec._Number == string.Empty) continue; rec._Name = lines[1]; rec._Address1 = lines[2]; rec._Address2 = lines[3]; rec._ZipCode = GetZipCode(lines[4]); rec._City = GetCity(lines[4]); rec._Mobil = lines[6]; rec._Email = lines[11]; var x = NumberConvert.ToInt(lines[10]); if (x == 0 || x == 3) rec._Title = ContactTitle.Employee; else if (x == 2) rec._Title = ContactTitle.Sales; else if (x == 4) rec._Title = ContactTitle.Purchase; if (dim1 != null && dim1.Get(lines[8]) != null) rec._Dim1 = lines[8]; if (dim2 != null && lines.Count > (12+2) && dim2.Get(lines[12]) != null) rec._Dim2 = lines[12]; if (dim3 != null && lines.Count > (13 + 2) && dim3.Get(lines[13]) != null) rec._Dim3 = lines[13]; if (lines.Count > (18 + 2) && lines[18] != string.Empty) rec._Mobil = lines[18]; if (!lst.ContainsKey(rec.KeyStr)) lst.Add(rec.KeyStr, rec); } var err = await log.Insert(lst.Values); var accs = lst.Values.ToArray(); log.Employees = new SQLCache(accs, true); } catch (Exception ex) { log.Ex(ex); } } public static Dictionary<string, InvItem> importInv(importLog log) { if (!log.OpenFile("exp00049", "Varer")) { log.api.CompanyEntity.Inventory = false; return null; } try { List<string> lines; var grpCache = log.ItemGroups; var dim1 = log.dim1; var dim2 = log.dim2; var dim3 = log.dim3; var Creditors = log.Creditors; var lst = new Dictionary<string, InvItem>(StringNoCaseCompare.GetCompare()); while ((lines = log.GetLine(47)) != null) { var rec = new InvItem(); rec._Item = lines[1]; if (rec._Item == string.Empty) continue; rec._Name = lines[2]; if (grpCache.Get(lines[9]) != null) rec._Group = lines[9]; if (Creditors?.Get(lines[13]) != null) rec._PurchaseAccount = lines[13]; if (lines[15] == "1") rec._Blocked = true; rec._PurchaseCurrency = (byte)log.ConvertCur(lines[7]); if (rec._PurchaseCurrency != 0) rec._PurchasePrice = importLog.ToDouble(lines[8]); else rec._CostPrice = importLog.ToDouble(lines[8]); rec._Decimals = Convert.ToByte(lines[18]); rec._Weight = importLog.ToDouble(lines[22]); rec._Volume = importLog.ToDouble(lines[23]); rec._StockPosition = lines[31]; rec._Unit = importLog.ConvertUnit(lines[25]); //cost price unit = importLog.ToDouble(lines[43]); if (dim1 != null && dim1.Get(lines[42]) != null) rec._Dim1 = lines[42]; if (dim2 != null && lines.Count > (54 + 2) && dim2.Get(lines[54]) != null) rec._Dim2 = lines[54]; if (dim3 != null && lines.Count > (55 + 2) && dim3.Get(lines[55]) != null) rec._Dim3 = lines[55]; switch (lines[5]) { case "0": rec._ItemType = (byte)ItemType.Item; break; //Item case "1": rec._ItemType = (byte)ItemType.Service; break; //Service case "2": rec._ItemType = (byte)ItemType.ProductionBOM; break; //BOM case "3": rec._ItemType = (byte)ItemType.BOM; break; //Kit } switch (lines[11]) { case "0": rec._CostModel = CostType.FIFO; break; //FIFO case "1": rec._CostModel = CostType.FIFO; break; //LIFO case "2": rec._CostModel = CostType.Fixed; break; //Cost price case "3": rec._CostModel = CostType.Average; break; //Average case "4": rec._CostModel = CostType.Fixed; break; //Serial number } if (!lst.ContainsKey(rec.KeyStr)) lst.Add(rec.KeyStr, rec); } return lst; } catch (Exception ex) { log.Ex(ex); } return null; } public static async Task importInvBOM(importLog log) { if (!log.OpenFile("exp00059", "Styklister")) { return; } try { var Items = log.Items; List<string> lines; var lst = new List<InvBOM>(); while ((lines = log.GetLine(5)) != null) { var item = Items.Get(lines[0]); if (item == null) continue; var rec = new InvBOM(); rec._ItemMaster = item.KeyStr; item = Items.Get(lines[2]); if (item == null) continue; rec._ItemPart = item.KeyStr; rec._LineNumber = NumberConvert.ToFloat(lines[1]); rec._Qty = NumberConvert.ToFloat(lines[3]); rec._QtyType = BOMQtyType.Propertional; rec._UnitSize = 1; rec._CostPriceFactor = 1; rec._MoveType = BOMMoveType.SalesAndBuy; lst.Add(rec); } if (lst.Count > 0) { var err = await log.Insert(lst); log.HasBOM = (err == 0); } } catch (Exception ex) { log.Ex(ex); } } public static async Task importInvPrices(importLog log, Dictionary<string, InvItem> invItems) { List<InvPriceListLine> lst = null; int nPrice = 0; var PriceLists = log.PriceLists; var ItemCurFile = log.CurFile; if (PriceLists != null && log.OpenFile("exp00063", "Priser")) { try { nPrice = PriceLists.Count; List<string> lines; InvItem item; lst = new List<InvPriceListLine>(); while ((lines = log.GetLine(5)) != null) { if (!invItems.TryGetValue(lines[0], out item)) continue; var priceList = PriceLists.Get(lines[4]); if (priceList == null) continue; var Price = importLog.ToDouble(lines[1]); var prisId = priceList.RowId; if (prisId <= 3) { byte priceCur = (byte)log.ConvertCur(lines[3]); if (prisId == 1) { item._SalesPrice1 = Price; item._Currency1 = priceCur; } else if (prisId == 2) { item._SalesPrice2 = Price; item._Currency2 = priceCur; } else { item._SalesPrice3 = Price; item._Currency3 = priceCur; } } if (nPrice > 1) { var rec = new InvPriceListLine(); rec.SetMaster((UnicontaBaseEntity)priceList); rec._DCType = 1; rec._Item = item._Item; rec._Price = Price; lst.Add(rec); } } } catch (Exception ex) { log.Ex(ex); } } try { var PriceCurFile = log.CurFile; log.CurFile = ItemCurFile; var err = await log.Insert(invItems.Values); if (err == 0) { log.HasItem = true; var accs = invItems.Values.ToArray(); log.Items = new SQLCache(accs, true); } if (nPrice > 1) { log.CurFile = PriceCurFile; log.HasPriceList = true; await log.Insert(lst); } } catch (Exception ex) { log.Ex(ex); } } public static async Task importPaymentGroup(importLog log) { if (!log.OpenFile("exp00021", "Betalingsbetingelser")) { return; } try { List<string> lines; var lst = new Dictionary<string, PaymentTerm>(StringNoCaseCompare.GetCompare()); while ((lines = log.GetLine(5)) != null) { var rec = new PaymentTerm(); rec._Payment = lines[0]; if (string.IsNullOrWhiteSpace(rec._Payment)) continue; rec._Name = lines[1]; rec._Days = GetInt(lines[3]); var t = GetInt(lines[2]); switch (t) { case 0: rec._PaymentMethod = PaymentMethodTypes.NetDays; break; //Net case 1: rec._PaymentMethod = PaymentMethodTypes.EndMonth; break; //End month case 2: rec._PaymentMethod = PaymentMethodTypes.EndMonth; rec._Days += 90; break; //End quarter case 3: rec._PaymentMethod = PaymentMethodTypes.EndMonth; rec._Days += 365; break; //End year case 4: rec._PaymentMethod = PaymentMethodTypes.EndWeek; break; //End week } if (!lst.Any()) rec._Default = true; if (!lst.ContainsKey(rec.KeyStr)) lst.Add(rec.KeyStr, rec); } var err = await log.Insert(lst.Values); if (err == 0) { var accs = lst.Values.ToArray(); log.Payments = new SQLCache(accs, true); } } catch (Exception ex) { log.Ex(ex); } } static public CountryCode convertCountry(string str, CountryCode companyCode, out VatZones zone) { zone = VatZones.Domestic; if (string.IsNullOrEmpty(str)) { CountryCode code; if (Enum.TryParse(str, true, out code)) { if (code == companyCode) zone = VatZones.Domestic; else zone = VatZones.EU; return code; } else { switch (str) { case "": return companyCode; case "DK": case "Danmark": if (companyCode != CountryCode.Denmark) zone = VatZones.Foreign; return CountryCode.Denmark; case "S": case "Sverige": zone = VatZones.EU; return CountryCode.Sweden; case "N": case "Norge": if (companyCode != CountryCode.Norway) zone = VatZones.Foreign; return CountryCode.Norway; case "Færøerne": zone = VatZones.EU; return CountryCode.FaroeIslands; case "Grønland": zone = VatZones.Domestic; return CountryCode.Greenland; case "Island": zone = VatZones.EU; return CountryCode.Iceland; case "D": case "Tyskland": zone = VatZones.EU; return CountryCode.Germany; case "NL": case "Holland": zone = VatZones.EU; return CountryCode.Netherlands; case "B": case "Belgien": zone = VatZones.EU; return CountryCode.Belgium; case "PL": case "Polen": zone = VatZones.EU; return CountryCode.Poland; case "Østrig": zone = VatZones.EU; return CountryCode.Austria; case "CH": case "Schweiz": zone = VatZones.EU; return CountryCode.Switzerland; case "F": case "Frankrig": zone = VatZones.EU; return CountryCode.France; case "ES": case "Spanien": zone = VatZones.EU; return CountryCode.Spain; case "I": case "Italien": zone = VatZones.EU; return CountryCode.Italy; case "Grækenland": zone = VatZones.EU; return CountryCode.Greece; case "UK": case "England": zone = VatZones.EU; return CountryCode.UnitedKingdom; case "Rusland": zone = VatZones.Foreign; return CountryCode.Russia; case "USA": zone = VatZones.Foreign; return CountryCode.UnitedStates; } } } return companyCode; } public static async Task<ErrorCodes> importCreditor(importLog log) { if (!log.OpenFile("exp00041", "kreditorer")) { return ErrorCodes.Succes; } try { List<string> lines; var dim1 = log.dim1; var dim2 = log.dim2; var dim3 = log.dim3; var Payments = log.Payments; var grpCache = log.CreGroups; var InvoiceAccs = new List<InvoiceAccounts>(); var lst = new Dictionary<string, Creditor>(StringNoCaseCompare.GetCompare()); while ((lines = log.GetLine(60)) != null) { var rec = new Creditor(); rec._Account = lines[1]; if (string.IsNullOrWhiteSpace(rec._Account)) continue; if (grpCache.Get(lines[11]) != null) rec._Group = lines[11]; rec._Name = lines[2]; rec._Address1 = lines[3]; rec._Address2 = lines[4]; rec._ZipCode = GetZipCode(lines[5]); rec._City = GetCity(lines[5]); if (string.IsNullOrEmpty(lines[30])) { rec._PaymentMethod = PaymentTypes.VendorBankAccount; rec._PaymentId = lines[30]; } rec._LegalIdent = lines[31]; rec._ContactEmail = lines[57]; rec._ContactPerson = lines[7]; rec._Phone = lines[8]; rec._Vat = log.GetVat_Validate(lines[25]); if (dim1 != null && dim1.Get(lines[32]) != null) rec._Dim1 = lines[32]; if (dim2 != null && lines.Count > (61 + 2) && dim2.Get(lines[61]) != null) rec._Dim2 = lines[61]; if (dim3 != null && lines.Count > (62 + 2) && dim3.Get(lines[62]) != null) rec._Dim3 = lines[62]; rec._PricesInclVat = lines[17] != "0"; rec._Country = convertCountry(lines[18], log.CompCountryCode, out rec._VatZone); rec._Currency = log.ConvertCur(lines[18]); if (Payments?.Get(lines[20]) != null) rec._Payment = lines[20]; if (!lst.ContainsKey(rec.KeyStr)) { lst.Add(rec.KeyStr, rec); if (lines[10] != string.Empty) InvoiceAccs.Add(new InvoiceAccounts { Acc = rec._Account, InvAcc = lines[10] }); } } await log.Insert(lst.Values); log.HasCreditor = true; var accs = lst.Values.ToArray(); log.Creditors = new SQLCache(accs, true); UpdateInvoiceAccount(log, InvoiceAccs, false); return ErrorCodes.Succes; } catch (Exception ex) { log.Ex(ex); return ErrorCodes.Exception; } } public class InvoiceAccounts { public string Acc, InvAcc; } static void UpdateInvoiceAccount(importLog log, List<InvoiceAccounts> InvoiceAccs, bool isDeb) { if (InvoiceAccs.Count > 0) { var recs = new List<UnicontaBaseEntity>(); foreach (var debUpd in InvoiceAccs) { DCAccount rec; if (isDeb) rec = (DCAccount)log.Debtors.Get(debUpd.Acc); else rec = (DCAccount)log.Creditors.Get(debUpd.Acc); if (rec != null) { rec._InvoiceAccount = debUpd.InvAcc; recs.Add((UnicontaBaseEntity)rec); } } log.Update(recs); } } public static async Task<ErrorCodes> importDebitor(importLog log) { if (!log.OpenFile("exp00033", "Debitorer")) { return ErrorCodes.Succes; } try { List<string> lines; var dim1 = log.dim1; var dim2 = log.dim2; var dim3 = log.dim3; var PriceLists = log.PriceLists; var Employees = log.Employees; var Payments = log.Payments; var grpCache = log.DebGroups; var InvoiceAccs = new List<InvoiceAccounts>(); var lst = new Dictionary<string, Debtor>(StringNoCaseCompare.GetCompare()); while ((lines = log.GetLine(55)) != null) { var rec = new Debtor(); rec._Account = lines[1]; if (string.IsNullOrWhiteSpace(rec._Account)) continue; var key = grpCache.Get(lines[11]); if (key != null) rec._Group = key.KeyStr; rec._Name = lines[2]; rec._Address1 = lines[3]; rec._Address2 = lines[4]; rec._ZipCode = GetZipCode(lines[5]); rec._City = GetCity(lines[5]); rec._LegalIdent = lines[27]; rec._ContactEmail = lines[52]; rec._ContactPerson = lines[7]; rec._Phone = lines[8]; if (lines.Count > (58 + 2)) rec._EAN = lines[58]; rec._Vat = log.GetVat_Validate(lines[24]); if (dim1 != null && dim1.Get(lines[29]) != null) rec._Dim1 = lines[29]; if (dim2 != null && lines.Count > (56 + 2) && dim2.Get(lines[56]) != null) rec._Dim2 = lines[56]; if (dim3 != null && lines.Count > (57 + 2) && dim3.Get(lines[57]) != null) rec._Dim3 = lines[57]; if (lines[42] != string.Empty) rec._CreditMax = importLog.ToDouble(lines[42]); if (PriceLists != null) { var priceRec = (InvPriceList)PriceLists.Get(lines[14]); if (priceRec != null) { rec._PriceList = priceRec.KeyStr; rec._PricesInclVat = priceRec._InclVat; } } //var t = (int)NumberConvert.ToInt(lines[11]); //if (t > 0) // rec._VatZone = (VatZones)(t - 1); rec._Country = convertCountry(lines[18], log.CompCountryCode, out rec._VatZone); rec._Currency = log.ConvertCur(lines[18]); if (Payments?.Get(lines[20]) != null) rec._Payment = lines[20]; if (Employees?.Get(lines[23]) != null) rec._Employee = lines[23]; if (!lst.ContainsKey(rec.KeyStr)) { lst.Add(rec.KeyStr, rec); // lines[10] invoice account if (lines[10] != string.Empty) InvoiceAccs.Add(new InvoiceAccounts { Acc = rec._Account, InvAcc = lines[10] }); } } await log.Insert(lst.Values); log.HasDebitor = true; var accs = lst.Values.ToArray(); log.Debtors = new SQLCache(accs, true); UpdateInvoiceAccount(log, InvoiceAccs, true); return ErrorCodes.Succes; } catch (Exception ex) { log.Ex(ex); return ErrorCodes.Exception; } } public static async Task importContact(importLog log, byte DCType) { string filename = (DCType == 1) ? "exp00177" : "exp00178"; if (!log.OpenFile(filename)) { log.AppendLogLine(String.Format(Localization.lookup("FileNotFound"), filename + " : KontaktPerson")); return; } try { SQLCache dk; if (DCType == 1) dk = log.Debtors; else dk = log.Creditors; List<string> lines; var lst = new List<Contact>(); while ((lines = log.GetLine(10)) != null) { var rec = new Contact(); rec._DCAccount = lines[0]; if (dk.Get(rec._DCAccount) != null) rec._DCType = DCType; else rec._DCAccount = null; rec._Name = lines[2]; if (string.IsNullOrWhiteSpace(rec._Name)) { rec._Name = lines[0]; if (string.IsNullOrWhiteSpace(rec._Name)) continue; } if (lines.Count >= 13+2) rec._Mobil = lines[12] != "" ? lines[12] : lines[9]; rec._Email = lines[8]; if (lines[1] != "0") rec._AccountStatement = rec._InterestNote = rec._CollectionLetter = rec._Invoice = true; lst.Add(rec); } await log.Insert(lst); if (lst.Count > 0) log.HasContact = true; } catch (Exception ex) { log.Ex(ex); } } static async Task importOrder(importLog log, Dictionary<long, DebtorOrder> orders) { if (!log.OpenFile("exp00127", "Salgsordre")) { return; } try { var Debtors = log.Debtors; var Employees = log.Employees; List<string> lines; int MaxOrderNumber = 0; var dim1 = log.dim1; var dim2 = log.dim2; var dim3 = log.dim3; var Payments = log.Payments; var PriceLists = log.PriceLists; while ((lines = log.GetLine(60)) != null) { var rec = new DebtorOrder(); rec._OrderNumber = (int)NumberConvert.ToInt(lines[1]); if (rec._OrderNumber == 0) continue; if (rec._OrderNumber > MaxOrderNumber) MaxOrderNumber = rec._OrderNumber; var deb = (Debtor)Debtors.Get(lines[5]); if (deb == null) continue; rec._DCAccount = deb._Account; if (deb._PriceList != null) { var plist = (InvPriceList)PriceLists.Get(deb._PriceList); rec._PricesInclVat = plist._InclVat; } rec._DeliveryAddress1 = lines[32]; rec._DeliveryAddress2 = lines[33]; rec._DeliveryAddress3 = lines[34]; if (lines[36] != string.Empty) { VatZones vatz; rec._DeliveryCountry = c5.convertCountry(lines[36], log.CompCountryCode, out vatz); } if (lines[4] != string.Empty) rec._DeliveryDate = GetDT(lines[4]); if (lines[3] != string.Empty) rec._Created = GetDT(lines[3]); rec._Currency = log.ConvertCur(lines[20]); rec._EndDiscountPct = importLog.ToDouble(lines[16]); var val = importLog.ToDouble(lines[27]); if (val <= 2) { rec._DeleteLines = true; rec._DeleteOrder = true; } rec._Remark = lines[23]; rec._YourRef = lines[37]; rec._OurRef = lines[38]; rec._Requisition = lines[39]; if (Payments?.Get(lines[22]) != null) rec._Payment = lines[22]; if (Employees?.Get(lines[25]) != null) rec._Employee = lines[25]; if (dim1 != null && dim1.Get(lines[28]) != null) rec._Dim1 = lines[28]; if (dim2 != null && lines.Count > (69 + 2) && dim2.Get(lines[69]) != null) rec._Dim2 = lines[69]; if (dim3 != null && lines.Count > (70 + 2) && dim3.Get(lines[70]) != null) rec._Dim3 = lines[70]; orders.Add(rec._OrderNumber, rec); } await log.Insert(orders.Values); var arr = await log.api.Query<CompanySettings>(); if (arr != null && arr.Length > 0) { arr[0]._SalesOrder = MaxOrderNumber; log.api.UpdateNoResponse(arr[0]); } } catch (Exception ex) { log.Ex(ex); } } static async Task importOrderLinje(importLog log, Dictionary<long, DebtorOrder> orders) { if (!log.OpenFile("exp00128", "Ordrelinjer")) { return; } try { var Items = log.Items; if (Items == null) return; List<string> lines; var lst = new List<DebtorOrderLine>(); while ((lines = log.GetLine(22)) != null) { var OrderNumber = NumberConvert.ToInt(lines[0]); if (OrderNumber == 0) continue; DebtorOrder order; if (!orders.TryGetValue(OrderNumber, out order)) continue; var rec = new DebtorOrderLine(); rec._LineNumber = NumberConvert.ToInt(lines[1]); InvItem item; if (!string.IsNullOrEmpty(lines[2])) { item = (InvItem)Items.Get(lines[2]); if (item == null) continue; rec._Item = item._Item; rec._CostPrice = item._CostPrice; } else item = null; rec._Text = lines[8]; rec._Qty = importLog.ToDouble(lines[4]); rec._Price = importLog.ToDouble(lines[5]); rec._DiscountPct = importLog.ToDouble(lines[6]); var amount = importLog.ToDouble(lines[7]); if (rec._Price * rec._Qty == 0d && amount != 0) rec._AmountEntered = amount; rec._QtyNow = importLog.ToDouble(lines[11]); if (rec._QtyNow == rec._Qty) rec._QtyNow = 0d; rec._Unit = importLog.ConvertUnit(lines[9]); if (item != null && item._Unit == rec._Unit) rec._Unit = 0; rec._Currency = order._Currency; if (rec._CostPrice == 0d) rec._CostPrice = importLog.ToDouble(lines[21]); rec.SetMaster(order); lst.Add(rec); } await log.Insert(lst); } catch (Exception ex) { log.Ex(ex); } } static async Task importPurchage(importLog log, Dictionary<long, CreditorOrder> purchages) { if (!log.OpenFile("exp00125", "Indkøbssordre")) { return; } try { var Creditors = log.Creditors; var Employees = log.Employees; List<string> lines; int MaxOrderNumber = 0; var dim1 = log.dim1; var dim2 = log.dim2; var dim3 = log.dim3; var Payments = log.Payments; var PriceLists = log.PriceLists; while ((lines = log.GetLine(60)) != null) { var rec = new CreditorOrder(); rec._OrderNumber = (int)NumberConvert.ToInt(lines[1]); if (rec._OrderNumber == 0) continue; if (rec._OrderNumber > MaxOrderNumber) MaxOrderNumber = rec._OrderNumber; var cre = Creditors.Get(lines[5]); if (cre == null) continue; rec._DCAccount = cre.KeyStr; rec._PricesInclVat = lines[16] == "1"; rec._DeliveryAddress1 = lines[32]; rec._DeliveryAddress2 = lines[33]; rec._DeliveryAddress3 = lines[34]; if (lines[4] != string.Empty) rec._DeliveryDate = GetDT(lines[4]); if (lines[3] != string.Empty) rec._Created = GetDT(lines[3]); rec._Currency = log.ConvertCur(lines[20]); rec._EndDiscountPct = importLog.ToDouble(lines[17]); var val = importLog.ToDouble(lines[27]); if (val <= 2) { rec._DeleteLines = true; rec._DeleteOrder = true; } rec._Remark = lines[23]; rec._YourRef = lines[37]; rec._OurRef = lines[38]; rec._Requisition = lines[39]; if (Payments?.Get(lines[22]) != null) rec._Payment = lines[22]; if (Employees?.Get(lines[25]) != null) rec._Employee = lines[25]; if (dim1 != null && dim1.Get(lines[28]) != null) rec._Dim1 = lines[28]; if (dim2 != null && lines.Count > (69 + 2) && dim2.Get(lines[69]) != null) rec._Dim2 = lines[69]; if (dim3 != null && lines.Count > (70 + 2) && dim3.Get(lines[70]) != null) rec._Dim3 = lines[70]; purchages.Add(rec._OrderNumber, rec); } await log.Insert(purchages.Values); var arr = await log.api.Query<CompanySettings>(); if (arr != null && arr.Length > 0) { arr[0]._PurchaceOrder = MaxOrderNumber; log.api.UpdateNoResponse(arr[0]); } } catch (Exception ex) { log.Ex(ex); } } static async Task importPurchageLinje(importLog log, Dictionary<long, CreditorOrder> purchages) { if (!log.OpenFile("exp00126", "Indkøbslinjer")) { return; } try { var Items = log.Items; if (Items == null) return; List<string> lines; var lst = new List<CreditorOrderLine>(); while ((lines = log.GetLine(22)) != null) { var OrderNumber = NumberConvert.ToInt(lines[0]); if (OrderNumber == 0) continue; CreditorOrder order; if (!purchages.TryGetValue(OrderNumber, out order)) continue; var rec = new CreditorOrderLine(); rec._LineNumber = NumberConvert.ToInt(lines[1]); InvItem item; if (!string.IsNullOrEmpty(lines[2])) { item = (InvItem)Items.Get(lines[2]); if (item == null) continue; rec._Item = item._Item; } else item = null; rec._Text = lines[8]; rec._Qty = importLog.ToDouble(lines[4]); rec._Price = importLog.ToDouble(lines[5]); rec._DiscountPct = importLog.ToDouble(lines[6]); var amount = importLog.ToDouble(lines[7]); if (rec._Price * rec._Qty == 0d && amount != 0) rec._AmountEntered = amount; rec._QtyNow = importLog.ToDouble(lines[11]); if (rec._QtyNow == rec._Qty) rec._QtyNow = 0d; rec._Unit = importLog.ConvertUnit(lines[9]); if (item != null && item._Unit == rec._Unit) rec._Unit = 0; rec._Currency = order._Currency; rec.SetMaster(order); lst.Add(rec); } await log.Insert(lst); } catch (Exception ex) { log.Ex(ex); } } public static void importCompany(importLog log) { if (!log.OpenFile("exp00010", "Firmaoplysninger")) { return; } try { List<string> lines; if ((lines = log.GetLine(28)) != null) { var rec = log.api.CompanyEntity; rec._Address1 = lines[1]; rec._Address2 = lines[2]; rec._Address3 = lines[3]; rec._Phone = lines[4]; rec._Id = lines[21]; rec._NationalBank = lines[6]; rec._FIK = lines[7]; if (string.IsNullOrWhiteSpace(rec._FIK)) rec._FIK = lines[28]; rec._IBAN = lines[27]; rec._SWIFT = lines[25]; rec._FIKDebtorIdPart = 7; if (log.HasDepartment) { rec.NumberOfDimensions = 1; rec._Dim1 = "Afdeling"; } if (log.HasCentre) { rec.NumberOfDimensions = 2; rec._Dim2 = "Bærer"; } if (log.HasPorpose) { rec.NumberOfDimensions = 3; rec._Dim3 = "Formål"; } log.NumberOfDimensions = rec.NumberOfDimensions; log.api.UpdateNoResponse(rec); } } catch (Exception ex) { log.Ex(ex); } } public static async Task importDepartment(importLog log) { if (!log.OpenFile("exp00017", "Afdelinger")) { return; } try { List<string> lines; var lst = new List<GLDimType1>(); while ((lines = log.GetLine(3)) != null) { var rec = new GLDimType1(); rec._Dim = lines[0]; if (string.IsNullOrWhiteSpace(rec._Dim)) continue; rec._Name = lines[1]; lst.Add(rec); log.HasDepartment = true; } await log.Insert(lst); if (log.HasDepartment) log.dim1 = new SQLCache(lst.ToArray(), true); } catch (Exception ex) { log.Ex(ex); } } public static async Task importCentre(importLog log) { if (!log.OpenFile("exp00182", "Bærer")) { return; } try { List<string> lines; var lst = new List<GLDimType2>(); while ((lines = log.GetLine(2)) != null) { var rec = new GLDimType2(); rec._Dim = lines[0]; if (string.IsNullOrWhiteSpace(rec._Dim)) continue; rec._Name = lines[1]; lst.Add(rec); log.HasCentre = true; } await log.Insert(lst); if (log.HasCentre) log.dim2 = new SQLCache(lst.ToArray(), true); } catch (Exception ex) { log.Ex(ex); } } public static async Task importPurpose(importLog log) { if (!log.OpenFile("exp00183", "Formål")) { return; } try { List<string> lines; var lst = new List<GLDimType3>(); while ((lines = log.GetLine(2)) != null) { var rec = new GLDimType3(); rec._Dim = lines[0]; if (string.IsNullOrWhiteSpace(rec._Dim)) continue; rec._Name = lines[1]; lst.Add(rec); log.HasPorpose = true; } await log.Insert(lst); if (log.HasPorpose) log.dim3 = new SQLCache(lst.ToArray(), true); } catch (Exception ex) { log.Ex(ex); } } public static void PostDK_NotFound(importLog log, DCImportTrans[] arr, List<GLPostingLineLocal>[] YearLst, GLJournalAccountType dktype) { SQLCache Accounts = dktype == GLJournalAccountType.Debtor ? log.Debtors : log.Creditors; SQLCache Groups = dktype == GLJournalAccountType.Debtor ? log.DebGroups : log.CreGroups; var years = log.years; int nYears = years.Length; for (int n = arr.Length; (--n >= 0);) { var p = arr[n]; if (p.Taken || p.Amount == 0) continue; // we did not find this transaaction in the ledger. we need to generate 2 new transaction, that will net each other out var rec = new GLPostingLineLocal(); rec.AccountType = dktype; rec.Account = p.Account; rec.Voucher = p.Voucher; rec.Text = p.Text; rec.Date = p.Date; rec.Invoice = p.Invoice; rec.Amount = p.Amount; rec.Currency = p.Currency; rec.AmountCur = p.AmountCur; var ac = (DCAccount)Accounts.Get(p.Account); if (ac == null) continue; var grp = (DCGroup)Groups.Get(ac._Group); if (grp == null) continue; ConvertDKText(rec, ac); var Offset = new GLPostingLineLocal(); Offset.Account = grp._SummeryAccount; Offset.Voucher = rec.Voucher; Offset.Text = rec.Text; Offset.Date = rec.Date; Offset.Invoice = rec.Invoice; Offset.DCPostType = rec.DCPostType; Offset.Amount = -rec.Amount; Offset.Currency = rec.Currency; Offset.AmountCur = -rec.AmountCur; var Date = rec.Date; for (int i = nYears; (--i >= 0);) { var y = years[i]; if (y._FromDate <= Date && y._ToDate >= Date) { var lst = YearLst[i]; lst.Add(rec); lst.Add(Offset); if (p.dif != 0d) { var kursDif = new GLPostingLineLocal(); kursDif.Date = rec.Date; kursDif.Voucher = rec.Voucher; kursDif.Text = rec.Text; kursDif.AccountType = dktype; kursDif.Account = rec.Account; kursDif.Amount = p.dif; kursDif.DCPostType = DCPostType.ExchangeRateDif; lst.Add(kursDif); kursDif = new GLPostingLineLocal(); kursDif.Date = rec.Date; kursDif.Voucher = rec.Voucher; kursDif.Text = "Ophævet kursdif fra konvertering"; kursDif.Account = Offset.Account; kursDif.Amount = -p.dif; kursDif.DCPostType = DCPostType.ExchangeRateDif; lst.Add(kursDif); } break; } } } } static public void UpdateLedgerTrans(GLPostingLineLocal[] arr) { int voucher = 0, Invoice = 0; DCPostType posttype = 0; bool clearText = false; string orgText = null; foreach (var rec in arr) { if (rec.AccountType > 0) { Invoice = rec.Invoice; voucher = rec.Voucher; posttype = rec.DCPostType; clearText = (rec.Text == null); orgText = rec.OrgText; } else if (voucher == rec.Voucher) { rec.Invoice = Invoice; rec.DCPostType = posttype; if (clearText && rec.Text == orgText) rec.Text = null; } } } static public void ConvertDKText(GLPostingLineLocal rec, DCAccount dc) { var t = rec.Text; if (t != null && t.Length > 6) { int index = 0; // "Fa:13325 D:33936765" eller Kn:13328 D:97911111" if (t.StartsWith("Fa:")) rec.DCPostType = DCPostType.Invoice; else if (t.IndexOf("fakt", StringComparison.CurrentCultureIgnoreCase) == 0) { rec.DCPostType = DCPostType.Invoice; index = 1; } else if (t.StartsWith("Kn:")) rec.DCPostType = DCPostType.Creditnote; else if (t.IndexOf("kreditno", StringComparison.CurrentCultureIgnoreCase) == 0) { rec.DCPostType = DCPostType.Creditnote; index = 1; } else if (t.StartsWith("Udlign")) { rec.DCPostType = DCPostType.Payment; index = 2; } else if (t.IndexOf("betal", StringComparison.CurrentCultureIgnoreCase) == 0) { rec.DCPostType = DCPostType.Payment; index = 1; } else { index = -1; var name = ((DCAccount)dc)._Name; if (name != null) { name = name.Replace(".", "").Replace(" ", ""); t = t.Replace(".", "").Replace(" ", ""); if (t.IndexOf(name, StringComparison.CurrentCultureIgnoreCase) >= 0 || name.IndexOf(t, StringComparison.CurrentCultureIgnoreCase) >= 0) { rec.OrgText = rec.Text; rec.Text = null; } } } if (index >= 0 && rec.DCPostType != 0) { if (rec.Invoice == 0) { var tt = t.Split(' '); if (tt.Length > index) { t = tt[index]; if (index == 0 && t.Length > 3) t = t.Substring(3); var l = t.Length; if (l > 0) { var ch = t[l - 1]; if (ch == ';' || ch == '.') t = t.Substring(0, l - 1); for (int lx = t.Length; (--lx >= 0);) { ch = t[lx]; if (ch < '0' || ch > '9') { t = null; break; } } if (t != null) rec.Invoice = GetInt(t); } } } if (rec.Invoice != 0) { rec.OrgText = rec.Text; rec.Text = null; } } } } public static async Task importGLTrans(importLog log, DCImportTrans[] debpost, DCImportTrans[] crepost) { if (!log.OpenFile("exp00030", "Finanspostering")) { return; } try { List<string> lines; log.years = await log.api.Query<CompanyFinanceYear>(); var Ledger = log.LedgerAccounts; var dim1 = log.dim1; var dim2 = log.dim2; var dim3 = log.dim3; DCImportTrans dksearch = new DCImportTrans(); var dkcmp = new DCImportTransSort(); var years = log.years; int nYears = years.Length; List<GLPostingLineLocal>[] YearLst = new List<GLPostingLineLocal>[nYears]; for (int i = nYears; (--i >= 0);) YearLst[i] = new List<GLPostingLineLocal>(); var primoPost = new List<GLPostingLineLocal>(); DateTime primoYear = DateTime.MaxValue; int cnt = 0; while ((lines = log.GetLine(19)) != null) { if (lines[1] != "0") //Not budget and primo. continue; bool IsPrimo; var Date = GetDT(lines[3], out IsPrimo); if (Date == DateTime.MinValue) continue; GLPostingLineLocal kursDif = null; var rec = new GLPostingLineLocal(); rec.Date = Date; var orgAccount = log.GLAccountFromC5(lines[0]); rec.Account = orgAccount; rec.Voucher = GetInt(lines[4]); if (rec.Voucher == 0) rec.Voucher = 1; rec.Text = lines[5]; rec.Amount = importLog.ToDouble(lines[6]); var cur = log.ConvertCur(lines[8]); if (cur != 0) { rec.Currency = cur; rec.IgnoreCurDif = true; // we do not want to do any regulation in a conversion rec.AmountCur = importLog.ToDouble(lines[7]); if (rec.Amount * rec.AmountCur < 0d) // different sign { rec.Currency = null; rec.AmountCur = 0; } } var acc = (MyGLAccount)Ledger.Get(rec.Account); if (acc == null) continue; if (Date < primoYear) // we have an earlier date than primo year. then we mark that as the first allowed primo date. { primoYear = Date; primoPost.Clear(); } if (IsPrimo) { if (Date == primoYear) // we only take primo from first year. { rec.primo = 1; primoPost.Add(rec); } continue; } if (acc.AccountTypeEnum == GLAccountTypes.Creditor || acc.AccountTypeEnum == GLAccountTypes.Debtor) { // here we convert account to debtor / creditor. var arr = (acc.AccountTypeEnum == GLAccountTypes.Debtor) ? debpost : crepost; if (arr != null) { dksearch.Amount = rec.Amount; dksearch.Date = rec.Date; dksearch.Voucher = rec.Voucher; DCImportTrans post; var idx = Array.BinarySearch(arr, dksearch, dkcmp); if (idx >= 0 && idx < arr.Length) { post = arr[idx]; while (post.Taken) { idx++; if (idx < arr.Length) { post = arr[idx]; if (dkcmp.Compare(post, dksearch) == 0) continue; } post = null; break; } } else post = null; if (post == null) { for (int i = arr.Length; (--i >= 0);) { var p = arr[i]; if (!p.Taken) { if (dkcmp.Compare(p, dksearch) == 0) { post = p; break; } } } } if (post != null) { IdKey dc; if (acc.AccountTypeEnum == GLAccountTypes.Debtor) { dc = log.Debtors.Get(post.Account); if (dc != null) rec.AccountType = GLJournalAccountType.Debtor; } else { dc = log.Creditors.Get(post.Account); if (dc != null) rec.AccountType = GLJournalAccountType.Creditor; } if (dc != null) { post.Taken = true; rec.Account = post.Account; rec.Invoice = post.Invoice; rec.Settlements = "+"; // autosettle. ConvertDKText(rec, (DCAccount)dc); if (post.dif != 0d) { kursDif = new GLPostingLineLocal(); kursDif.Date = rec.Date; kursDif.Voucher = rec.Voucher; kursDif.Text = rec.Text; kursDif.AccountType = rec.AccountType; kursDif.Account = rec.Account; kursDif.Amount = post.dif; kursDif.DCPostType = DCPostType.ExchangeRateDif; post.dif = 0d; } } } } } else if (acc._MandatoryTax != VatOptions.NoVat && acc.AccountTypeEnum != GLAccountTypes.Equity && acc.AccountTypeEnum != GLAccountTypes.Bank && acc.AccountTypeEnum != GLAccountTypes.LiquidAsset) { rec.Vat = log.GetVat_Validate(lines[9]); if (rec.Vat != string.Empty) acc.HasVat = true; rec.VatHasBeenDeducted = true; } if (dim1 != null && lines[2].Length != 0) { var str = lines[2]; if (dim1.Get(str) != null) rec.SetDim(1, str); } if (dim2 != null && lines.Count > (19+2) && lines[19].Length != 0) { var str = lines[19]; if (dim2.Get(str) != null) rec.SetDim(2, str); } if (dim3 != null && lines.Count > (20 + 2) && lines[20].Length != 0) { var str = lines[20]; if (dim3.Get(str) != null) rec.SetDim(3, str); } for (int i = nYears; (--i >= 0);) { var y = years[i]; if (y._FromDate <= Date && y._ToDate >= Date) { YearLst[i].Add(rec); if (kursDif != null) { YearLst[i].Add(kursDif); rec = new GLPostingLineLocal(); rec.Date = kursDif.Date; rec.Voucher = kursDif.Voucher; rec.Text = "Ophævet kursdif fra konvertering"; rec.Account = orgAccount; rec.Amount = -kursDif.Amount; rec.DCPostType = DCPostType.ExchangeRateDif; YearLst[i].Add(rec); } break; } } cnt++; } if (primoPost.Any()) { for (int i = nYears; (--i >= 0);) { var y = years[i]; if (y._FromDate <= primoYear && y._ToDate >= primoYear) { YearLst[i].AddRange(primoPost); cnt += primoPost.Count; primoPost = null; break; } } } log.AppendLogLine(string.Format("Number of transactions = {0}", cnt)); if (debpost != null) PostDK_NotFound(log, debpost, YearLst, GLJournalAccountType.Debtor); if (crepost != null) PostDK_NotFound(log, crepost, YearLst, GLJournalAccountType.Creditor); log.window.progressBar.Maximum = nYears; var glSort = new GLTransSort(); GLPostingHeader header = new GLPostingHeader(); header.NumberSerie = "NR"; header.NoDateSum = true; // var ap = new Uniconta.API.GeneralLedger.PostingAPI(log.api); for (int i = 0; (i < nYears); i++) { if (log.errorAccount != null) { long sum = 0; foreach (var rec in YearLst[i]) sum += NumberConvert.ToLong(rec.Amount * 100d); if (sum != 0) { var rec = new GLPostingLineLocal(); rec.Date = years[i]._ToDate; rec.Account = log.GLAccountFromC5(log.errorAccount); rec.Voucher = 99999; rec.Text = "Ubalance ved import fra C5"; rec.Amount = sum / -100d; YearLst[i].Add(rec); } } var arr = YearLst[i].ToArray(); YearLst[i] = null; if (arr.Length > 0) { header.Comment = string.Format("Import {0} - {1}", years[i]._FromDate.ToShortDateString(), years[i]._ToDate.ToShortDateString()); Array.Sort(arr, glSort); UpdateLedgerTrans(arr); var res = await ap.PostJournal(header, arr, false); if (res.Err != 0) { log.AppendLogLine("Fejl i poster i " + header.Comment); await log.Error(res.Err); } else log.AppendLogLine("Posting " + header.Comment); } log.window.UpdateProgressbar(i, null); } foreach (var ac in (MyGLAccount[])Ledger.GetNotNullArray) { if (!ac.HasVat && ac._MandatoryTax != VatOptions.NoVat) { ac._MandatoryTax = VatOptions.NoVat; ac.HasChanges = true; } } c5.UpdateVATonAccount(log); log.AppendLogLine("Generate Primo Transactions"); var ap2 = new FinancialYearAPI(ap); for (int i = 1; (i < nYears); i++) { await ap2.GeneratePrimoTransactions(years[i], null, null, 9999, "NR"); } log.window.UpdateProgressbar(0, "Done"); } catch (Exception ex) { log.Ex(ex); } } public class GLTransSort : IComparer<GLPostingLineLocal> { public int Compare(GLPostingLineLocal x, GLPostingLineLocal y) { int c = DateTime.Compare(x.Date, y.Date); if (c != 0) return c; c = y.primo - x.primo; if (c != 0) return c; c = x.Voucher - y.Voucher; if (c != 0) return c; c = (int)y.AccountType - (int)x.AccountType; if (c != 0) return c; var v = x.Amount - y.Amount; if (v > 0.001d) return 1; if (v < -0.001d) return 1; return 0; } } public class DCImportTransSort : IComparer<DCImportTrans> { public int Compare(DCImportTrans x, DCImportTrans y) { if (x.Date > y.Date) return 1; if (x.Date < y.Date) return -1; int c = x.Voucher - y.Voucher; if (c != 0) return c; var v = x.Amount - y.Amount; if (v > 0.001d) return 1; if (v < -0.001d) return 1; return 0; } } public class DCImportTrans { public DateTime Date; public DateTime DueDate; public DateTime DocumentDate; public double Amount; public double AmountCur; public double dif; public Currencies? Currency; public string Account; public string Text; public int Voucher; public int Invoice; public bool Taken; } public static int GetInt(string str) { var l = str.Length; if (l == 0) return 0; if (l > 8) str = str.Substring(l - 8); return (int)NumberConvert.ToInt(str); } public static DateTime GetDT(string str) { bool IsPrimo; return GetDT(str, out IsPrimo); } public static DateTime GetDT(string str, out bool IsPrimo) { IsPrimo = false; if (str.Length < 10) return DateTime.MinValue; int year = int.Parse(str.Substring(0, 4)); int month = int.Parse(str.Substring(5, 2)); var daystr = str.Substring(8, 2); int dayinmonth = 0; if (daystr == "PR") { IsPrimo = true; dayinmonth = 1; } else if (daystr == "UL") dayinmonth = DateTime.DaysInMonth(year, month); else dayinmonth = int.Parse(daystr); return new DateTime(year, month, dayinmonth); } public static DCImportTrans[] importDCTrans(importLog log, bool deb, SQLCache Accounts) { if (deb) { if (!log.OpenFile("exp00037", "Debitorposteringer")) return null; } else { if (!log.OpenFile("exp00045", "Kreditorposteringer")) return null; } try { List<string> lines; int offset = deb ? 0 : 1; // kreditor has one less List<DCImportTrans> lst = new List<DCImportTrans>(); while ((lines = log.GetLine(29)) != null) { var Date = GetDT(lines[3]); if (Date == DateTime.MinValue) continue; var ac = Accounts.Get(lines[1]); if (ac == null) continue; var rec = new DCImportTrans(); rec.Date = Date; rec.Account = ac.KeyStr; rec.Invoice = GetInt(lines[deb ? 4 : 22]); rec.Voucher = GetInt(lines[5 - offset]); if (rec.Voucher == 0) rec.Voucher = 1; rec.Text = lines[6 - offset]; rec.Amount = importLog.ToDouble(lines[8 - offset]); rec.dif = importLog.ToDouble(lines[22 - offset]); var cur = log.ConvertCur(lines[10 - offset]); if (cur != 0) { rec.Currency = cur; rec.AmountCur = importLog.ToDouble(lines[9 - offset]); if (rec.Amount * rec.AmountCur < 0d) // different sign { rec.Currency = null; rec.AmountCur = 0; } } lst.Add(rec); } if (lst.Count() > 0) { var arr = lst.ToArray(); Array.Sort(arr, new DCImportTransSort()); return arr; } } catch (Exception ex) { log.Ex(ex); } return null; } } } <file_sep>/MainWindow.xaml.cs using ImportingTool.Model; using ImportingTool.Pages; using Microsoft.Win32; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Forms; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using Uniconta.API.Service; using Uniconta.API.System; using Uniconta.Common; using Uniconta.DataModel; namespace ImportingTool { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { bool _terminate; public bool Terminate { get { return _terminate; } set { _terminate = value; BreakConversion(); } } public MainWindow() { this.DataContext = this; InitializeComponent(); this.Loaded += MainWindow_Loaded; this.MouseDown += MainWindow_MouseDown; btnCopyLog.Content = String.Format(Uniconta.ClientTools.Localization.lookup("CopyOBJ"), Uniconta.ClientTools.Localization.lookup("Logs")); progressBar.Visibility = Visibility.Collapsed; /* Remove it*/ progressBar.Visibility = Visibility.Visible; progressBar.Maximum = 100; UpdateProgressbar(0, null); } private void MainWindow_MouseDown(object sender, MouseButtonEventArgs e) { btnImport.IsEnabled = true; } void MainWindow_Loaded(object sender, RoutedEventArgs e) { DisplayLoginScreen(); cmbImportFrom.ItemsSource = Enum.GetNames(typeof(ImportFrom)); cmbImportDimension.ItemsSource = new List<string>() { "Ingen", "Kun Afdeling", "Afdeling, Bærer", "Afdeling, Bærer, Formål" }; cmbImportDimension.SelectedIndex = 3; } async private void DisplayLoginScreen() { var logon = new LoginWindow(); logon.Owner = this; logon.ShowDialog(); if (logon.DialogResult.HasValue && logon.DialogResult.Value) { await SessionInitializer.SetupCompanies(); } else this.Close(); } public async void Import(importLog log) { UpdateProgressbar(0, "Starting.."); var ses = SessionInitializer.CurrentSession; Company cc = new Company(); cc._Name = txtCompany.Text; cc._CurrencyId = Currencies.DKK; var country = CountryCode.Denmark; if (cmbImportFrom.SelectedIndex <= 1) { // c5 cc._ConvertedFrom = (int)ConvertFromType.C5; log.extension = ".def"; log.ConvertDanishLetters = true; log.CharBuf = new byte[1]; if (cmbImportFrom.SelectedIndex == 0) log.C5Encoding = Encoding.GetEncoding(850); // western Europe. 865 is Nordic else { country = CountryCode.Iceland; cc._CurrencyId = Currencies.ISK; log.C5Encoding = Encoding.GetEncoding(861); // Iceland } if (!log.OpenFile("exp00000", "Definitions")) { log.AppendLogLine("These is no c5-files in this directory"); return; } log.extension = ".kom"; } else { // eco cc._ConvertedFrom = (int)ConvertFromType.Eco; if (cmbImportFrom.SelectedIndex == 3) // Norsk Eco { country = CountryCode.Norway; cc._CurrencyId = Currencies.NOK; } log.extension = ".csv"; log.FirstLineIsEmpty = true; if (!log.OpenFile(country == CountryCode.Denmark ? "RegnskabsAar" : "Regnskapsaar")) { log.AppendLogLine("Der er ingen filer i dette bibliotek fra e-conomic"); return; } } var lin = log.ReadLine(); if (lin == null) { log.AppendLogLine("Filen er tom"); log.closeFile(); } char splitCh, apostrof; var cols = lin.Split(';'); if (cols.Length > 1) splitCh = ';'; else { cols = lin.Split(','); if (cols.Length > 1) splitCh = ','; else splitCh = '#'; } if (lin[0] == '\'') apostrof = '\''; else apostrof = '"'; log.sp = new StringSplit(splitCh, apostrof); cc._CountryId = country; UpdateProgressbar(0, "Opret firma.."); var err = await ses.CreateCompany(cc); if (err != 0) { log.AppendLogLine("Cannot create Company !"); return; } Company fromCompany = null; var ccList = await ses.GetStandardCompanies(country); foreach (var c in ccList) if ((c.CompanyId == 19 && country == CountryCode.Denmark) || // 19 = Dev/erp (c.CompanyId == 1855 && country == CountryCode.Iceland) || // 1855 = erp (c.CompanyId == 108 && country == CountryCode.Norway)) // 108 = Dev/erp { fromCompany = c; break; } if (fromCompany == null) { log.AppendLogLine("Cannot find standard Company !"); return; } CompanyAPI comApi = new CompanyAPI(ses, cc); err = await comApi.CopyBaseData(fromCompany, cc, false, true, true, false, true, false, false, false); if (err != 0) { log.AppendLogLine(string.Format("Copy of default company failed. Error = {0}", err.ToString())); log.AppendLogLine("Conversion has stopped"); return; } log.AppendLogLine("Import started...."); log.api = new CrudAPI(ses, cc); log.CompCurCode = log.api.CompanyEntity._CurrencyId; log.CompCur = log.CompCurCode.ToString(); log.CompCountryCode = log.api.CompanyEntity._CountryId; log.CompCountry = log.CompCountryCode.ToString(); if (cmbImportFrom.SelectedIndex <= 1) { err = await c5.importAll(log, cmbImportDimension.SelectedIndex); } else { err = await eco.importAll(log, cmbImportFrom.SelectedIndex - 1); } cc.InvPrice = (log.HasPriceList); cc.Inventory = (log.HasItem); cc.InvBOM = (log.HasBOM); cc.Creditor = (log.HasCreditor); cc.Debtor = (log.HasDebitor); cc.Contacts = (log.HasContact); cc.InvClientName = false; await log.api.Update(cc); log.closeFile(); log.AppendLogLine("Færdig !"); if (err == 0) { log.AppendLogLine(""); log.AppendLogLine("Du kan nu logge ind i Uniconta og åbne dit firma."); log.AppendLogLine("Der kan godt gå lidt tid inden alle dine poster er bogført."); log.AppendLogLine("Du kan slette firmaet i menuen Firma/Firmaoplysninger,"); log.AppendLogLine("hvis du ønsker at foretage en ny import."); log.AppendLogLine("Held og lykke med dit firma i Uniconta."); } else log.AppendLogLine(string.Format("Conversion has stopped due to an error {0}", err.ToString())); } private void cmbCompanies_SelectionChanged(object sender, SelectionChangedEventArgs e) { } FolderBrowserDialog openFolderDialog; private void btnImportFromDir_Click(object sender, RoutedEventArgs e) { openFolderDialog = new FolderBrowserDialog(); if (openFolderDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { txtImportFromDirectory.Text = openFolderDialog.SelectedPath; } } private void btnImport_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(txtCompany.Text)) { System.Windows.MessageBox.Show(String.Format(Uniconta.ClientTools.Localization.lookup("CannotBeBlank"), Uniconta.ClientTools.Localization.lookup("CompanyName"))); return; } if (cmbImportFrom.SelectedIndex == -1) { System.Windows.MessageBox.Show("Please select C5 or e-conomic."); return; } if (cmbImportDimension.SelectedIndex > -1) { } var path = txtImportFromDirectory.Text; if (string.IsNullOrEmpty(path)) { System.Windows.MessageBox.Show("Select directory"); return; } txtCompany.Focus(); btnImport.IsEnabled = false; if (path[path.Length - 1] != '\\') path += '\\'; importLog log = new importLog(path); log.window = this; if (cmbImportFrom.SelectedIndex <= 1) // c5 log.Set0InAccount = chkSetAccount.IsChecked.Value; log.target = txtLogs; txtLogs.DataContext = log; log.AppendLogLine(string.Format("Reading from path {0}", path)); Import(log); } private void cmbImportFrom_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (cmbImportFrom.SelectedIndex <= 1) // c5 { chkSetAccount.IsEnabled = true; cmbImportDimension.IsEnabled = true; } else { chkSetAccount.IsEnabled = false; cmbImportDimension.IsEnabled = false; } } private void btnCopyLog_Click(object sender, RoutedEventArgs e) { System.Windows.Forms.Clipboard.SetText(txtLogs.Text); } private void btnTerminate_Click(object sender, RoutedEventArgs e) { var res = System.Windows.MessageBox.Show("Are you sure?", Uniconta.ClientTools.Localization.lookup("Confirmation"), MessageBoxButton.YesNo); if (res == MessageBoxResult.Yes) { this.Terminate = true; } } void BreakConversion() { } public void UpdateProgressbar(int value, string text) { progressBar.Value = value; if (!string.IsNullOrEmpty(text)) progressBar.Tag = text; else progressBar.Tag = string.Format("{0} of {1}", value, progressBar.Maximum); } } public class HeightConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return (double)value - 30; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return (double)value + 30; } } /* For ProgressBar*/ public class RectConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { double width = (double)values[0]; double height = (double)values[1]; return new Rect(0, 0, width, height); } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } public enum ImportFrom { c5_Danmark, c5_Iceland, economic_Danmark, economic_Norge, } }
0767f8dabf684f72a91b7af942e53b4a9fd6ce6a
[ "C#" ]
8
C#
HolgerGlysing/ImportingTool
9b265f50206fe8f0d7040a1711c5a2bc27a3ab32
10bbe620997d6b6267a40d4772e0b162a9e0209a
refs/heads/master
<file_sep>using Ninject; using Ninject.Web.Common; using SimpleBlog.Core; using SimpleBlog.Core.Objects; using SimpleBlog.Providers; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace SimpleBlog { public class MvcApplication : NinjectHttpApplication { protected override IKernel CreateKernel() { var kernel = new StandardKernel(); kernel.Load(new RepositoryModule()); kernel.Bind<IBlogRepository>().To<BlogRepository>(); kernel.Bind<IAuthProvider>().To<AuthProvider>(); return kernel; } protected override void OnApplicationStarted() { FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); ModelBinders.Binders.Add(typeof(Post), new PostModelBinder(Kernel)); BundleConfig.RegisterBundles(BundleTable.Bundles); base.OnApplicationStarted(); } } } <file_sep>using Moq; using SimpleBlog.Controllers; using SimpleBlog.Models; using SimpleBlog.Providers; using System.Web; using System.Web.Mvc; using System.Web.Routing; using Xunit; namespace SimpleBlog.Tests { public class AdminControllerTests { AdminController adminController; Mock<IAuthProvider> authProvider; public AdminControllerTests() { authProvider = new Mock<IAuthProvider>(); adminController = new AdminController(authProvider.Object); var httpContextMock = new Mock<HttpContextBase>(); adminController.Url = new UrlHelper(new RequestContext(httpContextMock.Object, new RouteData())); } [Fact] public void IsLoggedIn_True_Test() { authProvider.Setup(s => s.IsLoggedIn).Returns(true); var actual = adminController.Login("/admin/manage"); Assert.IsType<RedirectResult>(actual); Assert.Equal("/admin/manage", (actual as RedirectResult).Url); } [Fact] public void IsLoggedIn_False_Test() { authProvider.Setup(s => s.IsLoggedIn).Returns(false); var actual = adminController.Login("/"); Assert.IsType<ViewResult>(actual); Assert.Equal("/", (actual as ViewResult).ViewBag.ReturnUrl); } [Fact] public void Post_Model_Invalid_Test() { var model = new LoginModel(); adminController.ModelState.AddModelError("UserName", "Username is required"); var actual = adminController.Login(model, "/"); Assert.IsType<ViewResult>(actual); } [Fact] public void Login_Post_User_Invalid_Test() { var model = new LoginModel { UserName = "invaliduser", Password = "<PASSWORD>" }; authProvider.Setup(s => s.Login(model.UserName, model.Password)) .Returns(false); var actual = adminController.Login(model, "/"); Assert.IsType<ViewResult>(actual); var modelStateErrors = adminController.ModelState[""].Errors; Assert.True(modelStateErrors.Count > 0); Assert.Equal("Username or password is invalid", modelStateErrors[0].ErrorMessage); } [Fact] public void Post_User_Valid_Test() { var model = new LoginModel { UserName = "validuser", Password = "<PASSWORD>" }; authProvider.Setup(s => s.Login(model.UserName, model.Password)) .Returns(true); var actual = adminController.Login(model, "/"); Assert.IsType<RedirectResult>(actual); Assert.Equal("/", (actual as RedirectResult).Url); } } } <file_sep>using SimpleBlog.Core; using SimpleBlog.Core.Objects; using System.Collections.Generic; namespace SimpleBlog.Models { public class ListViewModel { private ListViewModel() { } public ListViewModel(IBlogRepository blogRepository, int p) { Posts = blogRepository.Posts(p - 1, 10); TotalPosts = blogRepository.TotalPosts(); } public IList<Post> Posts { get; private set; } public int TotalPosts { get; private set; } public Category Category { get; private set; } public Tag Tag { get; private set; } public string Search { get; private set; } public static ListViewModel FromCategory(IBlogRepository blogRepository, string categorySlug, int p) { var model = new ListViewModel(); return new ListViewModel { Posts = blogRepository.PostsForCategory(categorySlug, p - 1, 10), TotalPosts = blogRepository.TotalPostsForCategory(categorySlug), Category = blogRepository.Category(categorySlug) }; } public static ListViewModel FromTag(IBlogRepository blogRepository, string tagSlug, int p) { return new ListViewModel { Posts = blogRepository.PostsForCategory(tagSlug, p - 1, 10), TotalPosts = blogRepository.TotalPostsForTag(tagSlug), Tag = blogRepository.Tag(tagSlug) }; } public static ListViewModel FromSearch(IBlogRepository blogRepository, string searchText, int p) { return new ListViewModel { Posts = blogRepository.PostsForSearch(searchText, p - 1, 10), TotalPosts = blogRepository.TotalPostsForSearch(searchText), Search = searchText }; } } }<file_sep>using SimpleBlog.Core.Objects; using System; using System.Configuration; using System.Web.Mvc; namespace SimpleBlog { public static class Extensions { public static string ToConfigLocalTime(this DateTime utcDT) { var istTZ = TimeZoneInfo.FindSystemTimeZoneById(ConfigurationManager.AppSettings["Timezone"]); return String.Format("{0} ({1})", TimeZoneInfo.ConvertTimeFromUtc(utcDT, istTZ).ToShortDateString(), ConfigurationManager.AppSettings["TimezoneAbbr"]); } } }<file_sep>using Newtonsoft.Json; using SimpleBlog.Core; using SimpleBlog.Core.Objects; using SimpleBlog.Models; using SimpleBlog.Providers; using System; using System.Text; using System.Linq; using System.Web.Mvc; using System.Web.Security; namespace SimpleBlog.Controllers { [Authorize] public class AdminController : Controller { readonly IAuthProvider authProvider; readonly IBlogRepository blogRepository; public AdminController(IAuthProvider authProvider, IBlogRepository blogRepository = null) { this.authProvider = authProvider; this.blogRepository = blogRepository; } [AllowAnonymous] public ActionResult Login(string returnUrl) { if (authProvider.IsLoggedIn) { return RedirectToLocalUrl(returnUrl); } ViewBag.ReturnUrl = returnUrl; return View(); } [AllowAnonymous, HttpPost, ValidateAntiForgeryToken] public ActionResult Login(LoginModel model, string returnUrl) { if (ModelState.IsValid && authProvider.Login(model.UserName, model.Password)) { return RedirectToLocalUrl(returnUrl); } ModelState.AddModelError("", "Username or password is invalid"); return View(); } public ActionResult Manage() { return View(); } public ActionResult Logout() { authProvider.Logout(); return RedirectToAction("Login", "Admin"); } public ActionResult Posts(JqInViewModel jqParams) { var posts = blogRepository.Posts(jqParams.page - 1, jqParams.rows, jqParams.sidx, jqParams.sord == "asc"); var totalPosts = blogRepository.TotalPosts(false); return Content(JsonConvert.SerializeObject(new { page = jqParams.page, records = totalPosts, rows = posts, total = Math.Ceiling((double)totalPosts / jqParams.rows) }), "application/json"); } ActionResult RedirectToLocalUrl(string url) { if (Url.IsLocalUrl(url)) { return Redirect(url); } else { return RedirectToAction("Manage"); } } [HttpPost, ValidateInput(false)] public ContentResult AddPost(Post post) { string json; ModelState.Clear(); if (TryValidateModel(post)) { var id = blogRepository.AddPost(post); json = JsonConvert.SerializeObject(new { id = id, success = true, message = "Post added successfully" }); } else { json = JsonConvert.SerializeObject(new { id = 0, success = false, message = "Failed to add the post" }); } return Content(json, "application/json"); } [HttpPost, ValidateInput(false)] public ContentResult EditPost(Post post) { string json; ModelState.Clear(); if (TryValidateModel(post)) { blogRepository.EditPost(post); json = JsonConvert.SerializeObject(new { id = post.Id, success = true, message = "Changes saved successfully." }); } else { json = JsonConvert.SerializeObject(new { id = 0, success = false, message = "Failed to save the changes." }); } return Content(json, "application/json"); } [HttpPost] public ContentResult DeletePost(int id) { blogRepository.DeletePost(id); var json = JsonConvert.SerializeObject(new { id = 0, success = true, message = "Post deleted successfully." }); return Content(json, "application/json"); } public ContentResult GetCategoriesHtml() { var categories = blogRepository.Categories().OrderBy(s => s.Name); var sb = new StringBuilder(); sb.AppendLine(@"<select>"); foreach (var category in categories) { sb.AppendLine(string.Format(@"<option value=""{0}"">{1}</option>", category.Id, category.Name)); } sb.AppendLine("<select>"); return Content(sb.ToString(), "text/html"); } public ContentResult GetTagsHtml() { var tags = blogRepository.Tags().OrderBy(s => s.Name); StringBuilder sb = new StringBuilder(); sb.AppendLine(@"<select multiple=""multiple"">"); foreach (var tag in tags) { sb.AppendLine(string.Format(@"<option value=""{0}"">{1}</option>", tag.Id, tag.Name)); } sb.AppendLine("<select>"); return Content(sb.ToString(), "text/html"); } public ContentResult Categories() { var categories = blogRepository.Categories(); return Content(JsonConvert.SerializeObject(new { page = 1, records = categories.Count, rows = categories, total = 1 }), "application/json"); } [HttpPost] public ContentResult AddCategory([Bind(Exclude = "Id")]Category category) { string json; if (ModelState.IsValid) { var id = blogRepository.AddCategory(category); json = JsonConvert.SerializeObject(new { id = id, success = true, message = "Category added successfully." }); } else { json = JsonConvert.SerializeObject(new { id = 0, success = false, message = "Failed to add the category." }); } return Content(json, "application/json"); } [HttpPost] public ContentResult EditCategory(Category category) { string json; if (ModelState.IsValid) { blogRepository.EditCategory(category); json = JsonConvert.SerializeObject(new { id = category.Id, success = true, message = "Changes saved successfully." }); } else { json = JsonConvert.SerializeObject(new { id = 0, success = false, message = "Failed to save the changes." }); } return Content(json, "application/json"); } [HttpPost] public ContentResult DeleteCategory(int id) { blogRepository.DeleteCategory(id); var json = JsonConvert.SerializeObject(new { id = 0, success = true, message = "Category deleted successfully." }); return Content(json, "application/json"); } public ContentResult Tags() { var tags = blogRepository.Tags(); return Content(JsonConvert.SerializeObject(new { page = 1, records = tags.Count, rows = tags, total = 1 }), "application/json"); } [HttpPost] public ContentResult AddTag([Bind(Exclude = "Id")]Tag tag) { string json; if (ModelState.IsValid) { var id = blogRepository.AddTag(tag); json = JsonConvert.SerializeObject(new { id = id, success = true, message = "Tag added successfully." }); } else { json = JsonConvert.SerializeObject(new { id = 0, success = false, message = "Failed to add the tag." }); } return Content(json, "application/json"); } [HttpPost] public ContentResult EditTag(Tag tag) { string json; if (ModelState.IsValid) { blogRepository.EditTag(tag); json = JsonConvert.SerializeObject(new { id = tag.Id, success = true, message = "Changes saved successfully." }); } else { json = JsonConvert.SerializeObject(new { id = 0, success = false, message = "Failed to save the changes." }); } return Content(json, "application/json"); } [HttpPost] public ContentResult DeleteTag(int id) { blogRepository.DeleteTag(id); var json = JsonConvert.SerializeObject(new { id = 0, success = true, message = "Tag deleted successfully." }); return Content(json, "application/json"); } } }<file_sep>using System.Web; using System.Web.Optimization; namespace SimpleBlog { public class BundleConfig { public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/js/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/js/jqueryval").Include( "~/Scripts/jquery.validate*")); bundles.Add(new ScriptBundle("~/js/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/js/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js")); bundles.Add(new ScriptBundle("~/js/app").Include( "~/Scripts/app.js")); bundles.Add(new StyleBundle("~/content/css").Include( "~/content/themes/simple/style.css", new CssRewriteUrlTransform())); bundles.Add(new StyleBundle("~/content/admin").Include( "~/content/themes/simple/admin.css", new CssRewriteUrlTransform())); bundles.Add(new StyleBundle("~/content/jqgrid") .Include("~/Scripts/jqgrid/css/ui.jqgrid.css",new CssRewriteUrlTransform()) .Include("~/Content/themes/simple/jqueryuicustom/css/sunny/jquery-ui-1.9.2.custom.min.css", new CssRewriteUrlTransform())); // Set EnableOptimizations to false for debugging. For more information, // visit http://go.microsoft.com/fwlink/?LinkId=301862 BundleTable.EnableOptimizations = true; } } } <file_sep>simple-blog =========== A simple blogging platform built on Asp.Net MVC 4 using Fluent NHibernate and Ninject. Based on this tutorial series: http://www.prideparrot.com/blog/archive/2012/12/how_to_create_a_simple_blog_part1 screenshots ----------- ![page](https://github.com/msm-code/simple-blog/raw/master/demo/page.png) ![admin](https://github.com/msm-code/simple-blog/raw/master/demo/admin.png) <file_sep>using Ninject; using SimpleBlog.Core; using SimpleBlog.Core.Objects; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace SimpleBlog { public class PostModelBinder : DefaultModelBinder { private readonly IKernel kernel; public PostModelBinder(IKernel kernel) { this.kernel = kernel; } public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var post = (Post)base.BindModel(controllerContext, bindingContext); var blogRepository = kernel.Get<IBlogRepository>(); if (post.Category != null) { post.Category = blogRepository.Category(post.Category.Id); } var tags = bindingContext.ValueProvider.GetValue("Tags").AttemptedValue.Split(','); if (tags.Length > 0) { post.Tags = new List<Tag>(); foreach (var tag in tags) { if (tag.Trim() != "") { post.Tags.Add(blogRepository.Tag(int.Parse(tag.Trim()))); } } } if (bindingContext.ValueProvider.GetValue("oper").AttemptedValue.Equals("edit")) post.Modified = DateTime.UtcNow; else post.PostedOn = DateTime.UtcNow; return post; } } }
d86ec544aed63be25f3b264dedb24a915c004a21
[ "Markdown", "C#" ]
8
C#
msm-code/simple-blog
cecf9621403b0ab40f09d96b363451951cf82afb
74cafa12624e359c8e6b18b5a978ec3f4c5d4d71
refs/heads/master
<file_sep>include ':app' rootProject.name='HitMeGame' <file_sep>package com.example.hitmegame; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.TextView; import android.widget.Toast; import java.io.Closeable; public class DifficultActivity extends AppCompatActivity { TextView tvGuess, tvBets; RadioGroup RGDifficultyLevel; Button btnSelectDifficulty; int Guess; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_difficult); RGDifficultyLevel = findViewById(R.id.RGDifficultyLevel); btnSelectDifficulty = findViewById(R.id.btnSelectDifficulty); tvGuess = findViewById(R.id.tvGuess); tvBets = findViewById(R.id.tvBets); btnSelectDifficulty.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int select = RGDifficultyLevel.getCheckedRadioButtonId(); RadioButton rbDiff = findViewById(select); //دزينة المعلومات من هاي الاكتفتي الى الصفحة الرئيسية if (select == -1) { Toast.makeText(DifficultActivity.this, "Should be select one", Toast.LENGTH_SHORT).show(); } else { Intent intent = new Intent(DifficultActivity.this, BetsActivity.class); intent.putExtra("DiffLevel", rbDiff.getText().toString()); String Diff = intent.getStringExtra("DiffLevel"); if (Diff.equals("Easy")) { Guess = 5; } else if (Diff.equals("Normal")) { Guess = 3; } else { Guess = 2; } intent.putExtra("Guess", Guess); DifficultActivity.this.startActivity(intent); } } }); } public void SelectDifficulty(View view) { int select = RGDifficultyLevel.getCheckedRadioButtonId(); RadioButton rbDiff = findViewById(select); //Toast.makeText(this,rbDiff.getText().toString(),Toast.LENGTH_SHORT).show(); //دزينة المعلومات من هاي الاكتفتي الى الصفحة الرئيسية Intent intent = new Intent(DifficultActivity.this, BetsActivity.class); intent.putExtra("DiffLevel", rbDiff.getText().toString()); String Diff = intent.getStringExtra("DiffLevel"); if (Diff.equals("Easy")) { Guess = 5; tvGuess.setText("The Guess is: " + Guess); tvBets.setText("The Bets is 0-9"); } else if (Diff.equals("Normal")) { Guess = 3; tvGuess.setText("The Guess is: " + Guess); tvBets.setText("The Bets is 0-50"); } else { Guess = 2; tvGuess.setText("The Guess is: " + Guess); tvBets.setText("The Bets is 0-100"); } } } <file_sep>package com.example.hitmegame; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { TextView tvGuessPoint; Button bHitMe,btnRestart; EditText etInput; int Bets, Hit, Guess; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //هاي اخذنة المعلومات من الاكتفتي الثانية final Intent intent = getIntent(); final String DiffLevel = intent.getStringExtra("DiffLevel"); Guess = intent.getIntExtra("Guess", 0); Bets = intent.getIntExtra("Bets", 0); tvGuessPoint = findViewById(R.id.tvGuessPoint); bHitMe = findViewById(R.id.bHitMe); btnRestart=findViewById(R.id.btn_Restart); etInput = findViewById(R.id.etInputHit); tvGuessPoint.setText("The Guess is :"+Guess); bHitMe.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String Hits = etInput.getText().toString(); if (Hits.matches("")) { Toast.makeText(MainActivity.this, "Enter The Hit", Toast.LENGTH_SHORT).show(); } else { Hit = Integer.valueOf(etInput.getText().toString()); if (DiffLevel.equals("Easy")) { if (Guess >= 1) { Guess -= 1; tvGuessPoint.setText("The Guess is :"+Guess); if (Hit <= 9) { if (Bets == Hit) { Intent intent = new Intent(MainActivity.this, WinnerActivity.class); MainActivity.this.startActivity(intent); } else { Toast.makeText(MainActivity.this, "Hit Again", Toast.LENGTH_SHORT).show(); } } else { Guess += 1; tvGuessPoint.setText("The Guess is :"+Guess); Toast.makeText(MainActivity.this, "You are out of range", Toast.LENGTH_SHORT).show(); } } else { Intent intent = new Intent(MainActivity.this, LoserActivity.class); MainActivity.this.startActivity(intent); } } else if (DiffLevel.equals("Normal")) { if (Guess >= 1) { Guess -= 1; tvGuessPoint.setText("The Guess is :"+Guess); if (Hit <= 50) { if (Bets == Hit) { Intent intent = new Intent(MainActivity.this, WinnerActivity.class); MainActivity.this.startActivity(intent); } else { Toast.makeText(MainActivity.this, "Hit Again", Toast.LENGTH_SHORT).show(); } } else { Guess += 1; tvGuessPoint.setText("The Guess is :"+Guess); Toast.makeText(MainActivity.this, "You are out of range", Toast.LENGTH_SHORT).show(); } } else { Intent intent = new Intent(MainActivity.this, LoserActivity.class); MainActivity.this.startActivity(intent); } } //Hard else { if (Guess >= 1) { Guess -= 1; tvGuessPoint.setText("The Guess is :"+Guess); if (Hit <= 100) { if (Bets == Hit) { Intent intent = new Intent(MainActivity.this, WinnerActivity.class); MainActivity.this.startActivity(intent); } else { Toast.makeText(MainActivity.this, "Hit Again", Toast.LENGTH_SHORT).show(); } } else { Guess += 1; tvGuessPoint.setText("The Guess is :"+Guess); Toast.makeText(MainActivity.this, "You are out of range", Toast.LENGTH_SHORT).show(); } } else { Intent intent = new Intent(MainActivity.this, LoserActivity.class); MainActivity.this.startActivity(intent); } } } } }); btnRestart.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(MainActivity.this,DifficultActivity.class); MainActivity.this.startActivity(intent); } }); } public void onBackPressed() { super.onBackPressed(); Intent intent = new Intent(this, DifficultActivity.class); this.startActivity(intent); } }
94cacff361c6bac5155258520e2bd0eb4dba5f4a
[ "Java", "Gradle" ]
3
Gradle
AhmedSadoon/HitMeGame
1ae364921865082b14202eafdd3434b1c3cb022a
9179569f64d103378a94168b12cb67c4f75abcee
refs/heads/master
<repo_name>ErmEvgeniy/New-Radioman<file_sep>/src/main/java/netology/Radio.java package netology; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @NoArgsConstructor @AllArgsConstructor @Data public class Radio { private int currentStation; private int minStationNumber = 0; private int maxStationNumber = 10; private int minSound = 0; private int maxSound = 100; private int currentSound; } <file_sep>/src/test/java/netology/RadioTest.java package netology; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class RadioTest { @Test public void shouldCreate (){ Radio radio = new Radio(); assertEquals(0, radio.getCurrentStation()); assertEquals(0, radio.getMinStationNumber()); assertEquals(10, radio.getMaxStationNumber()); assertEquals(0, radio.getMinSound()); assertEquals(100, radio.getMaxSound()); assertEquals(0, radio.getCurrentSound()); } @Test public void createRadio (){ Radio radio = new Radio(3,1,9,2,99,23); assertEquals(3, radio.getCurrentStation()); assertEquals(1, radio.getMinStationNumber()); assertEquals(9, radio.getMaxStationNumber()); assertEquals(2, radio.getMinSound()); assertEquals(99, radio.getMaxSound()); assertEquals(23, radio.getCurrentSound()); } @Test public void setCreateRadio (){ Radio radio = new Radio(); radio.setCurrentStation(5); radio.setMinStationNumber(2); radio.setMaxStationNumber(10); radio.setMinSound(3); radio.setMaxSound(95); radio.setCurrentSound(30); assertEquals(5, radio.getCurrentStation()); assertEquals(2, radio.getMinStationNumber()); assertEquals(10, radio.getMaxStationNumber()); assertEquals(3, radio.getMinSound()); assertEquals(95, radio.getMaxSound()); assertEquals(30, radio.getCurrentSound()); } @Test public void variableTestRadio () { int station = 3; int minStation = 1; int maxStation = 11; int minSound = 2; int maxSound = 95; int currentSound = 44; Radio radio = new Radio(station,minStation,maxStation,minSound,maxSound,currentSound); assertEquals(3, radio.getCurrentStation()); assertEquals(1, radio.getMinStationNumber()); assertEquals(11, radio.getMaxStationNumber()); assertEquals(2, radio.getMinSound()); assertEquals(95, radio.getMaxSound()); assertEquals(44, radio.getCurrentSound()); } }
fd6582db554e52d31b24a1c705926477e34b3cd6
[ "Java" ]
2
Java
ErmEvgeniy/New-Radioman
7991ec6f0dbdbc919c52675911ee2b9c0600d924
5b1b780bd81bc697b6ba320e9a70bf8baf389132
refs/heads/master
<file_sep># Uncomment this line to define a global platform for your project platform :ios, ‘9.3’ # Uncomment this line if you're using Swift use_frameworks! workspace ‘Blaylock’ target 'Blaylock' do #pod ‘NMPopUpViewSwift’ end <file_sep>// // Object.swift // Blalock // // Created by <NAME> on 4/14/16. // Copyright © 2016 <NAME>. All rights reserved. // import SpriteKit class Object: Hashable,CustomStringConvertible{ var column: Int var row: Int var sprite: SKSpriteNode? var spriteName: String var hashValue: Int{ return self.row ^ self.column } var description: String{ return "We are at: [\(row), \(column)]" } init(row:Int, column:Int){ self.row=row self.column=column self.spriteName="" } func shiftBy(rows: Int, columns: Int) { self.row += rows self.column += columns } func moveTo(row:Int, column: Int) { self.row = row self.column = column } } func ==(lhs: Object, rhs: Object) -> Bool { return lhs.column == rhs.column && lhs.row == rhs.row } <file_sep>// // GameScene.swift // Blalock // // Created by <NAME> on 4/9/16. // Copyright (c) 2016 <NAME>. All rights reserved. // import SpriteKit let BlockSize:CGFloat = CGFloat(0.8/Double(NumColumns)*Double(UIScreen.mainScreen().bounds.size.width)) class GameScene: SKScene { let gameLayer = SKNode() let shapeLayer = SKNode() let LayerPosition = CGPoint(x: 0.1*Double(UIScreen.mainScreen().bounds.size.width), y: -(Double(UIScreen.mainScreen().bounds.size.width))*0.6) //save time to render the same object var objectCache = Dictionary<String, SKTexture>() required init(coder aDecoder: NSCoder) { fatalError("NSCoder not supported") } override init(size: CGSize) { super.init(size: size) print(0.1*Double(UIScreen.mainScreen().bounds.size.width)) print(0.8/Double(NumColumns)*Double(UIScreen.mainScreen().bounds.size.width)) anchorPoint = CGPoint(x: 0, y: 1.0) let background = SKSpriteNode(imageNamed: "background") background.position = CGPoint(x: 0, y: 0) background.anchorPoint = CGPoint(x: 0, y: 1.0) background.size = CGSize(width: UIScreen.mainScreen().bounds.size.width, height: UIScreen.mainScreen().bounds.size.height) addChild(background) addChild(gameLayer) let gameBoardTexture = SKTexture(imageNamed: "gameboard") let gameBoard = SKSpriteNode(texture: gameBoardTexture, size: CGSizeMake(BlockSize * CGFloat(NumColumns), BlockSize * CGFloat(NumRows))) gameBoard.anchorPoint = CGPoint(x:0, y:1.0) gameBoard.position = LayerPosition shapeLayer.addChild(gameBoard) gameLayer.addChild(shapeLayer) } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ } func pointForColumn(column: Int, row: Int) -> CGPoint { let x = LayerPosition.x + (CGFloat(column) * BlockSize) + (BlockSize / 2) let y = LayerPosition.y - ((CGFloat(row) * BlockSize) + (BlockSize / 2)) return CGPointMake(x, y) } func addObjectToScene(object:Object, completion:() -> ()) { let sprite = SKSpriteNode(texture: getSprite(object)) sprite.position = pointForColumn(object.column, row:object.row) sprite.size = CGSize(width: BlockSize, height: BlockSize) shapeLayer.addChild(sprite) object.sprite = sprite // Animation sprite.alpha = 0 // #12 let fadeInAction = SKAction.fadeAlphaTo(1, duration: 0.5) fadeInAction.timingMode = .EaseOut sprite.runAction(fadeInAction,completion: completion) } func removeObject(object:Object){ let sprite = object.sprite! let fadeOutAction:SKAction = SKAction.fadeOutWithDuration(0.2) sprite.runAction(fadeOutAction) } func getSprite(object:Object) -> SKTexture{ var texture = objectCache[object.spriteName] if texture == nil { texture = SKTexture(imageNamed: object.spriteName) objectCache[object.spriteName] = texture } return texture! } func redrawObject(object:Object, duration:Double, completion:() -> ()) { let sprite = object.sprite! let moveTo = pointForColumn(object.column, row:object.row) let moveToAction:SKAction = SKAction.moveTo(moveTo, duration: duration) moveToAction.timingMode = .EaseOut sprite.runAction(moveToAction, completion: completion) } } <file_sep>// // GameViewController.swift // Blalock // // Created by <NAME> on 4/9/16. // Copyright (c) 2016 <NAME>. All rights reserved. // import UIKit import SpriteKit class GameViewController: UIViewController, GameDelegate, PopUpViewDelegate, UIGestureRecognizerDelegate { var scene: GameScene! var game:Game! var skView:SKView! var popViewController : PopUpViewControllerSwift! var popUpMenuIsOpen = false @IBOutlet weak var scoreLabel: UILabel! @IBOutlet weak var movesLabel: UILabel! @IBOutlet weak var livesLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() setupGame() game.beginGame() //NSUserDefaults.standardUserDefaults().setValue(0, forKey: "highscore") } func setupGame(){ view.userInteractionEnabled = false // Configure the view. skView = view as! SKView skView.multipleTouchEnabled = false // Create and configure the scene. scene = GameScene(size: skView.bounds.size) scene.scaleMode = .AspectFill // Present the scene. skView.presentScene(scene) game = Game() game.delegate=self popViewController = PopUpViewControllerSwift(nibName: "PopUpViewController", bundle: nil) popViewController.delegate = self } override func prefersStatusBarHidden() -> Bool { return true } @IBAction func didSwipeRight(sender: UISwipeGestureRecognizer) { detectSwipe(0, columns: 1) } @IBAction func didSwipeLeft(sender: UISwipeGestureRecognizer) { detectSwipe(0, columns: -1) } @IBAction func didSwipeUp(sender: UISwipeGestureRecognizer) { detectSwipe(-1, columns: 0) } @IBAction func didSwipeDown(sender: UISwipeGestureRecognizer) { detectSwipe(1, columns: 0) } func detectSwipe(rows: Int, columns: Int){ if popUpMenuIsOpen{ return } view.userInteractionEnabled = false if game.checkUserActionShift(game.mainChar!, rows: rows, columns: columns){ game.mainCharacterMoved() movesLabel.text = "\(game.movesLeft)" } game.checkForEndTurn(){ self.view.userInteractionEnabled = true } } func addObjectView(object: Object) { scene.addObjectToScene(object){} } func updateObjectView(object: Object, duration: Double, completion:() -> ()) { scene.redrawObject(object, duration: duration){ completion() } } func deleteObjectView(object: Object) { scene.removeObject(object) } func gameDidBegin(game: Game) { scoreLabel.text = "\(game.score)" movesLabel.text = "\(game.movesLeft)" livesLabel.text = "\(game.lives)" game.prepopulateGrid() // The following is false when restarting a new game if(game.mainChar == nil){ game.mainChar = MainCharacter(row: StartingRow, column: StartingColumn) game.gridArray[StartingColumn,StartingRow] = game.mainChar scene.addObjectToScene(game.mainChar!){ self.view.userInteractionEnabled = true } } } func updateScore(score: Int){ scoreLabel.text = "\(score)" } func gameDidEndTurn(game: Game, completion:() -> ()){ //pause? dispatch_after(dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), Int64(NSEC_PER_SEC/4)), dispatch_get_main_queue()) {//0.25s //delete right row of blocks game.deleteBlockRow() //move existing blocks right game.shiftExistingBlocks() //create new row of blocks game.addBlockRow(0) } //pause? dispatch_after(dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), Int64(NSEC_PER_SEC/2)), dispatch_get_main_queue()) {//0.5s //delete bottom row of enemies game.deleteEnemyRow() self.livesLabel.text = "\(game.lives)" //move existing enemies down game.shiftExistingEnemies() //create new row of enemies game.addEnemyRow(0) //reset move counter game.resetMoveCounter() self.movesLabel.text = "\(game.movesLeft)" //check for end game if game.outOfLives(){ self.gameDidEnd(game) } completion() } } func gameDidEnd(endedGame: Game) { if let oldHighScore = NSUserDefaults.standardUserDefaults().valueForKey("highscore") as? Int { if endedGame.score > oldHighScore{ NSUserDefaults.standardUserDefaults().setValue(endedGame.score, forKey: "highscore") } } else{ NSUserDefaults.standardUserDefaults().setValue(endedGame.score, forKey: "highscore") } popViewController.title = "Game Over" popUpMenuIsOpen = true popViewController.showInView(view, withImage: UIImage(named: "loserImage"), withMessage: "Final Score: \(game.score)", leftButtonLabel: "Try Again", rightButtonLabel: "Back To Home", animated: true) } func restartGame(){ popUpMenuIsOpen = false setupGame() game.beginGame() } func returnToHome(){ skView = nil scene = nil game = nil popViewController = nil self.performSegueWithIdentifier("segueGameToHome", sender: self) } @IBAction func pauseButton(sender: AnyObject) { popViewController.title = "Paused" popUpMenuIsOpen = true popViewController.showInView(view, withImage: UIImage(named: "pauseImage"), withMessage: "Paused", leftButtonLabel: "Resume", rightButtonLabel: "Back To Home", animated: true) } func resumeGame() { popUpMenuIsOpen = false } } <file_sep>// // yellowBlock.swift // Blalock // // Created by <NAME> on 5/14/16. // Copyright © 2016 <NAME>. All rights reserved. // import SpriteKit class yellowBlock:Block{ override var maxTravelDistance: Int{ return 2 } override init(row:Int, column:Int){ super.init(row: row,column: column) self.spriteName = "yellow" } }<file_sep>// // HomeViewController.swift // Blalock // // Created by <NAME> on 5/17/16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit import SpriteKit class HomeViewController: UIViewController, UIGestureRecognizerDelegate { @IBOutlet weak var HighScoreLabel: UILabel! @IBAction func unwindToHome(segue: UIStoryboardSegue) { updateHighScore() } override func viewDidLoad() { super.viewDidLoad() updateHighScore() } override func prefersStatusBarHidden() -> Bool { return true } func updateHighScore(){ if let highScore = NSUserDefaults.standardUserDefaults().valueForKey("highscore"){ HighScoreLabel.text = "\(highScore)" } else{ HighScoreLabel.text = "0" } } }<file_sep>// // Game.swift // Blalock // // Created by <NAME> on 4/14/16. // Copyright © 2016 <NAME>. All rights reserved. // let NumRows = 10 let NumColumns = 10 let StartingRow = 4 let StartingColumn = 4 let pointsPerEnemy = 10 let movesPerTurn = 5 var turn = 1 import SpriteKit protocol GameDelegate { // Invoked when the current round of Swiftris ends func gameDidEnd(game: Game) // Invoked after a new game has begun func gameDidBegin(game: Game) // need to redraw all shapes one square lower func gameDidEndTurn(game: Game, completion:() -> ()) //redraw object in scene func updateObjectView(object: Object, duration: Double, completion:() -> ()) func deleteObjectView(object: Object) func addObjectView(object: Object) func updateScore(score: Int) } class Game{ var gridArray:Array2D<Object> var mainChar:MainCharacter? var delegate:GameDelegate? var movesLeft:Int = movesPerTurn var lives:Int = 5 var score:Int = 0 var threshold:Int = 0 init() { gridArray = Array2D<Object>(rows: NumRows, columns: NumColumns) mainChar = nil } func beginGame() { delegate?.gameDidBegin(self) } func prepopulateGrid(){ for i in 0...2{ addBlockRow(i) addEnemyRow(i) } } func checkUserActionShift(object: Object, rows: Int, columns: Int) -> Bool { let (adjustedRows, adjustedColumns) = checkRecursiveCallWrapped(rows, columns: columns) if object is MainCharacter{ //check for wrap around if outOfBounds(object.row+rows, column: object.column+columns){ if rows != 0{ //only care about above recursive call now, so... return checkUserActionShift(object, rows: -(rows)*(NumRows-1), columns: 0) } else if columns != 0{ return checkUserActionShift(object, rows: 0, columns: -(columns)*(NumColumns-1)) } else{ print("shift is out of bounds but is (0,0)") } } if gridArray[object.row+rows,object.column+columns] is Enemy{ return false } if let block = gridArray[object.row+rows,object.column+columns] as? Block{ let distanceLeft = block.maxTravelDistance mainCharacterPushedBlock(block, rows: adjustedRows, columns: adjustedColumns, distanceLeft: distanceLeft) return false } } shiftBy(object, rows: rows, columns: columns, animationDuration: 0.2){ return true } return true } func mainCharacterPushedBlock(block: Block, rows: Int, columns: Int, distanceLeft: Int) { let (adjustedRows, adjustedColumns) = checkRecursiveCallWrapped(rows, columns: columns) if distanceLeft == 0{ return } if outOfBounds(block.row+rows, column: block.column+columns){ if columns < 0{ return } if columns > 0{ delegate?.deleteObjectView(block) gridArray[block.row, block.column] = nil return } if rows != 0{ //only care about above recursive call now, so... return mainCharacterPushedBlock(block, rows: -(rows)*(NumRows-1), columns: 0, distanceLeft: distanceLeft) } } let object = gridArray[block.row+rows, block.column+columns] if object is MainCharacter{ print("block that character pushed pushed the character") return } if let otherBlock = object as? Block{ mainCharacterPushedBlock(otherBlock, rows: adjustedRows, columns: adjustedColumns, distanceLeft: distanceLeft) return } if let enemy = object as? Enemy{ delegate?.deleteObjectView(enemy) gridArray[block.row+rows,block.column+columns] = nil score+=pointsPerEnemy delegate?.updateScore(score) } shiftBy(block, rows: rows, columns: columns, animationDuration: 0.3){ self.mainCharacterPushedBlock(block, rows: adjustedRows, columns: adjustedColumns, distanceLeft: distanceLeft-1) } } func checkEndTurnShift(object: Object, rows: Int, columns: Int) -> Bool { let (adjustedRows, adjustedColumns) = checkRecursiveCallWrapped(rows, columns: columns) if object is MainCharacter{ //check for wrap around if outOfBounds(object.row+rows, column: object.column+columns){ if rows != 0{ //only care about above recursive call now, so... return checkEndTurnShift(object, rows: -(rows)*(NumRows-1), columns: 0) } else if columns != 0{ return checkEndTurnShift(object, rows: 0, columns: -(columns)*(NumColumns-1)) } } //move enemy if let enemy = gridArray[object.row+rows,object.column+columns] as? Enemy{ if !checkEndTurnShift(enemy, rows: adjustedRows, columns: adjustedColumns){ print("character pushed enemy and enemy couldn't move") } } //move block if let block = gridArray[object.row+rows,object.column+columns] as? Block{ if !checkEndTurnShift(block, rows: adjustedRows, columns: adjustedColumns){ print("character pushed block and block couldn't move") } } } if object is Block{ //check for wrap around if outOfBounds(object.row+rows, column: object.column+columns){ if rows != 0{ //only care about above recursive call now, so... return checkEndTurnShift(object, rows: -(rows)*(NumRows-1), columns: 0) } else if columns < 0{ return false } else if columns > 0{ delegate?.deleteObjectView(object) gridArray[object.row,object.column] = nil return true } } //block squash enemy if let enemy = gridArray[object.row+rows,object.column+columns] as? Enemy{ delegate?.deleteObjectView(enemy) gridArray[object.row+rows,object.column+columns] = nil score+=pointsPerEnemy delegate?.updateScore(score) } //move mainChar if let tempChar = gridArray[object.row+rows,object.column+columns] as? MainCharacter{ if !checkEndTurnShift(tempChar, rows: adjustedRows, columns: adjustedColumns){ print("block pushed mainChar and mainChar couldn't move") } } //move block if let block = gridArray[object.row+rows,object.column+columns] as? Block{ if !checkEndTurnShift(block, rows: adjustedRows, columns: adjustedColumns){ print("block pushed block and block couldn't move") } } } if object is Enemy{ //check for wrap around if outOfBounds(object.row+rows, column: object.column+columns){ if columns != 0{ //only care about above recursive call now, so... return checkEndTurnShift(object, rows: 0, columns: -(columns)*(NumColumns-1)) } else if rows < 0{ return false } else if rows > 0{ enemyHitBottom(object) return true } } //move block if let block = gridArray[object.row+rows,object.column+columns] as? Block{ if !checkEndTurnShift(block, rows: adjustedRows, columns: adjustedColumns){ print("enemy pushed block and block couldn't move") } } //move mainChar if let tempChar = gridArray[object.row+rows,object.column+columns] as? MainCharacter{ if !checkEndTurnShift(tempChar, rows: adjustedRows, columns: adjustedColumns){ print("enemy pushed mainChar and mainChar couldn't move") } } } shiftBy(object, rows: rows, columns: columns, animationDuration: 0.2){ return true } return true } func checkRecursiveCallWrapped(rows: Int, columns: Int) -> (adjustedRows: Int, adjustedColumns: Int){ if rows < -1{ return (rows+NumRows,columns) } if columns < -1{ return (rows,columns+NumColumns) } if rows > 1{ return (rows-NumRows,columns) } if columns > 1{ return (rows,columns-NumColumns) } return (rows,columns) } func outOfBounds(row: Int, column: Int) -> Bool{ return row<0 || row>=NumRows || column<0 || column>=NumColumns } func shiftBy(object: Object, rows: Int, columns: Int, animationDuration: Double, completion: () -> ()) { gridArray[object.row,object.column] = nil object.shiftBy(rows, columns: columns) gridArray[object.row,object.column] = object delegate?.updateObjectView(object, duration: animationDuration){ completion() } } func mainCharacterMoved(){ movesLeft-=1 } func checkForEndTurn(completion:() -> ()){ if(movesLeft==0){ delegate?.gameDidEndTurn(self){ completion() } } else{ completion() } } func resetMoveCounter(){ turn+=1 movesLeft=movesPerTurn } func enemyHitBottom(object: Object){ delegate?.deleteObjectView(object) gridArray[object.row, object.column] = nil lives-=1 } //block methods func deleteBlockRow(){ //delete right row for r in 0...NumRows-1{ if let block = gridArray[r,NumColumns-1] as? Block{ delegate?.deleteObjectView(block) gridArray[r,NumColumns-1] = nil } } } func shiftExistingBlocks(){ //move rest of objects right for c in (0...NumColumns-1).reverse(){ for r in 0...NumRows-1{ if let block = gridArray[r,c] as? Block{ checkEndTurnShift(block, rows: 0, columns: 1) } } } } func addBlockRow(column: Int){ var emptyCells = [Int]() for r in 0...NumRows-1{ if gridArray[r,column] == nil{ emptyCells.append(r) } } let index = Int(arc4random_uniform(UInt32(emptyCells.count))) let block = newBlock(emptyCells[index],column: column) gridArray[emptyCells[index],column] = block delegate?.addObjectView(block) } //make a block based on score func newBlock(row: Int, column: Int) -> Block{ let i = Int(arc4random_uniform(UInt32(1000))) threshold = Int(500*(1-pow(1.1,-0.01 * Double(score)))) print(threshold) switch i{ //red and green share 50% probability, start with 50% green and yellow, end with 50% red and yellow case 0..<threshold: return redBlock(row: row, column: column) case threshold..<500: return greenBlock(row: row, column: column) default: return yellowBlock(row: row, column: column) } } //enemy methods func deleteEnemyRow(){ //delete bottom row for c in 0...NumColumns-1{ if let enemy = gridArray[NumRows-1,c] as? Enemy{ enemyHitBottom(enemy) } } } func shiftExistingEnemies(){ //move rest of objects down for c in 0...NumColumns-1{ for r in (0...NumRows-1).reverse(){ if let enemy = gridArray[r,c] as? Enemy{ checkEndTurnShift(enemy, rows: 1, columns: 0) } } } } func addEnemyRow(row: Int){ var emptyCells = [Int]() for c in 0...NumColumns-1{ if gridArray[row,c] == nil{ emptyCells.append(c) } } let index = Int(arc4random_uniform(UInt32(emptyCells.count))) let enemy = Enemy(row: row,column: emptyCells[index]) gridArray[row,emptyCells[index]] = enemy delegate?.addObjectView(enemy) } func outOfLives() -> Bool{ return lives <= 0 } } <file_sep>// // GameToHomeSegue.swift // Blalock // // Created by <NAME> on 5/17/16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit class GameToHomeSegue: UIStoryboardSegue { // override func perform() { // var firstVCView = destinationViewController.view as UIView! // var thirdVCView = sourceViewController.view as UIView! // // let screenHeight = UIScreen.mainScreen().bounds.size.height // // firstVCView.frame = CGRectOffset(firstVCView.frame, 0.0, screenHeight) // firstVCView.transform = CGAffineTransformScale(firstVCView.transform, 0.001, 0.001) // // // let window = UIApplication.sharedApplication().keyWindow // window?.insertSubview(firstVCView, aboveSubview: thirdVCView) // // // UIView.animateWithDuration(0.5, animations: { () -> Void in // // thirdVCView.transform = CGAffineTransformScale(thirdVCView.transform, 0.001, 0.001) // thirdVCView.frame = CGRectOffset(thirdVCView.frame, 0.0, -screenHeight) // // firstVCView.transform = CGAffineTransformIdentity // firstVCView.frame = CGRectOffset(firstVCView.frame, 0.0, -screenHeight) // // }) { (Finished) -> Void in // // self.sourceViewController.dismissViewControllerAnimated(false, completion: nil) // } // } override func perform() { let source = sourceViewController as UIViewController let destination = destinationViewController as UIViewController let window = UIApplication.sharedApplication().keyWindow! destination.view.alpha = 0.0 window.insertSubview(destination.view, belowSubview: source.view) UIView.animateWithDuration(0.5, animations: { () -> Void in source.view.alpha = 0.0 destination.view.alpha = 1.0 }) { (finished) -> Void in //source.view.alpha = 1.0 //source.presentViewController(destination, animated: false, completion: nil) source.dismissViewControllerAnimated(false, completion: nil) } } }<file_sep>// // Block.swift // Blalock // // Created by <NAME> on 4/15/16. // Copyright © 2016 <NAME>. All rights reserved. // import SpriteKit class Block: Object{ var maxTravelDistance: Int{ return 0 } override var description: String{ return "Our block is at: [\(row), \(column)]" } }<file_sep>// // RulesViewController.swift // Blaylock // // Created by <NAME> on 5/20/16. // Copyright © 2016 <NAME>. All rights reserved. // import UIKit import SpriteKit class RulesViewController: UIViewController, UIGestureRecognizerDelegate { override func viewDidLoad() { super.viewDidLoad() } override func prefersStatusBarHidden() -> Bool { return true } }<file_sep>// // greenBlock.swift // Blalock // // Created by <NAME> on 5/14/16. // Copyright © 2016 <NAME>. All rights reserved. // import SpriteKit class greenBlock:Block{ override var maxTravelDistance: Int{ return 3 } override init(row:Int, column:Int){ super.init(row: row,column: column) self.spriteName = "green" } }<file_sep>// // redBlock.swift // Blalock // // Created by <NAME> on 5/14/16. // Copyright © 2016 <NAME>. All rights reserved. // import SpriteKit class redBlock:Block{ override var maxTravelDistance: Int{ return 1 } override init(row:Int, column:Int){ super.init(row: row,column: column) self.spriteName = "orange" } }<file_sep>// // Enemy.swift // Blalock // // Created by <NAME> on 4/18/16. // Copyright © 2016 <NAME>. All rights reserved. // import SpriteKit class Enemy: Object{ override var description: String{ return "Our enemy is at: [\(row), \(column)]" } override init(row:Int, column:Int){ super.init(row: row,column: column) self.spriteName = "enemy" } }<file_sep>// // MainCharacter.swift // Blalock // // Created by <NAME> on 4/14/16. // Copyright © 2016 <NAME>. All rights reserved. // import SpriteKit class MainCharacter: Object{ override var description: String{ return "Our main character is at: [\(row), \(column)]" } override init(row:Int, column:Int){ super.init(row: row, column: column) //changeSprite() self.spriteName = "white" } override func shiftBy(rows: Int, columns: Int) { self.row += rows self.column += columns } // override func moveTo(column: Int, row:Int) { // self.column = column // self.row = row // //self.dir = Direction.South // } // func changeSprite(){ // self.spriteName = "mainChar"+self.dir.rawValue // } } //func ==(lhs: MainCharacter, rhs: MainCharacter) -> Bool { // return lhs.column == rhs.column && lhs.row == rhs.row && lhs.dir == rhs.dir //} <file_sep>// // RulesToHomeSegue.swift // Blalock // // Created by <NAME> on 5/17/16. // Copyright © 2016 <NAME>. All rights reserved. // import Foundation
51a1e007707e9bf42b63d1d575c72b9d07da132b
[ "Swift", "Ruby" ]
15
Ruby
Bobobocuz/Blaylock
59051c74fa134d68de48fe68fbe63ffd0a546123
ec50301ecc3fc69d0cb0ac5236406d51315ef652
refs/heads/master
<file_sep>- Understand the purpose of http methods/verbs. - Understand the separation of views/endpoints and internal models and logic. - Understand why task queues or out-of-sequence running of code is important. - Understand status codes? This might be irrelevant for endpoints thanks to intuitive endpoints exceptions. What were some of the trade-offs or struggles you faced when implementing the new game logic? Orginaly i was going to have the user provide the word they wanted to guess, similar to how the guessing game worked. But later i decided that it might be better to also provide a list of valid words as part of the game it self. Model wise Hangman is very similar to the guessing game. The differnce is isntead guessing a word instead fo a number. I had to add a some extra string to visually show the the word in a ***A*** format, so that the user could see where the letter was and better guess what the other letters could be <file_sep># Full Stack Nanodegree Project 4: Hangman Api ## Set-Up Instructions: 1. Update the value of application in app.yaml to the app ID you have registered in the App Engine admin console and would like to use to host your instance of this sample. 1. Run the app with the devserver using dev_appserver.py DIR, and ensure it's running by visiting the API Explorer - by default localhost:8080/_ah/api/explorer. 1. (Optional) Generate your client library(ies) with the endpoints tool. Deploy your application. ##Game Description: Hagman is a word guessing game, where you guess a letter and your told if it is in the word or not. Each right guess results in a letter of the word being revealed. Every wrong guess results in a turn being taken away. You keep guessing until the word is fully shown and you win, or you run out of turns and your lose ## Score: Two different score are keeps for this game. 1. Win and Losses. The first is the number of wins and losses you've had. A win is any time you complete a hangman game with out running out of guessess. A loss is any time you run out of guessess before completeing the game. Use the get_user_rankings to get the players with the most wins 1. Number of guesses: The second score is the number of guesses used to complete a word. The lower the number the less guess where used. ##Files Included: - api.py: Contains endpoints and game playing logic. - app.yaml: App configuration. - cron.yaml: Cronjob configuration. - main.py: Handler for taskqueue handler. - models.py: Entity and message definitions including helper methods. - utils.py: Helper function for retrieving ndb.Models by urlsafe Key string. ##Endpoints Included: - **create_user** - Path: 'user' - Method: POST - Parameters: user_name, email (optional) - Returns: Message confirming creation of the User. - Description: Creates a new User. user_name provided must be unique. Will raise a ConflictException if a User with that user_name already exists. - **new_game** - Path: 'game' - Method: POST - Parameters: user_name, target (optional), attemps (optional) - Returns: GameForm with initial game state. - Description: Creates a new Game. user_name provided must correspond to an existing user - will raise a NotFoundException if not. Target is optional, if you don't provided it a random word will be used. Attemps is the number of guess you have to guess the word. - **make_move** - Path: 'game/{urlsafe_game_key}' - Method: PUT - Parameters: urlsafe_game_key, guess - Returns: GameForm with new game state. - Description: Accepts a 'guess' and returns the updated state of the game. If this causes a game to end, a corresponding Score entity will be created. - **get_user_game** - Path: 'games/user/{urlsafe_game_key}' - Method: GET - Parameters: user_name - Returns: GameForms with the user's current games. - Description: Returns all of an individual User's active games. - **cancel_game** - Path: 'games/{urlsafe_game_key}' - Method: DELTETE - Parameters: urlsafe_game_key - Returns: Messages confirming deletion of the game. - Description: Cancel an unfished game. The game has been completely removed from the database and is no longer reachable - **get_high_scores** - Path: 'scores/high' - Method: GET - Parameters: user_name - Returns: ScoreForms - Description: Returns all winning Scores ascending ordered by the attempts used. - **get_user_rankings** - Path: 'ranking' - Method: GET - Parameters: None - Returns: UserForms - Description: Returns a list of user by most wins. - **get_game_history** - Path: 'game/history/{urlsafe_game_key}' - Method: GET - Parameters: urlsafe_game_key - Returns: MoveHistoryForm - Description: Returns all game moves. ##Models Included: - **User** - Stores unique user_name, (optional) email address, the number of winns, and losses. - **Game** - Stores unique game states. Associated with User model via KeyProperty. - **Score** - Records completed games. Associated with Users model via KeyProperty. ##Forms Included: - **GameForm** - Representation of a Game's state (urlsafe_key, attempts_remaining, game_over flag, message, user_name, revealed_word, moves). - **GameForms** - Multiple ScoreForm container. - **NewGameForm** - Used to create a new game (user_name, target, attempts) - **MakeMoveForm** - Inbound make move form (guess). - **ScoreForm** - Representation of a completed game's Score (user_name, date, won flag, guesses). - **ScoreForms** - Multiple ScoreForm container. - **UserForm** - Representation of a user's performance (user_name, performance). - **UserForms** - Multiple UserForm container. - **MoveHistoryForm** - MoveHistoryForm for outbound a completed game's moves history. - **StringMessage** - General purpose String container. ##Example of how to test - Call Hangman.create_user and create a user ```json { "message": "User user created" } ``` - Call hangman.new_game and give your username ```json { "attempts_remaining": "5", "game_over": false, "message": "Good Luck", "revealed_word": "***********", "urlsafe_key": "<KEY>", "user_name": "user" } ``` - Call hangman.make_move give urlsafe_key and pick a letter ```json { "attempts_remaining": "5", "game_over": false, "message": "Hit", "moves": [ "Guess: 'a', Result: '*********a*'" ], "revealed_word": "*********a*", "urlsafe_key": "<KEY>", "user_name": "user" } ``` ```json { "attempts_remaining": "4", "game_over": false, "message": "Miss", "moves": [ "Guess: 'a', Result: '*********a*'", "Guess: 'z', Result: '*********a*'" ], "revealed_word": "*********a*", "urlsafe_key": "<KEY>", "user_name": "user" } ``` - Call hangman.get_game and give the urlsafe_key ```json { "moves": [ "Guess: 'a', Result: '*********a*'", "Guess: 'z', Result: '*********a*'" ] } ``` - Call hangman.get_user_rankings to see the who has the most wins { ```json "items": [ { "loses": "0", "user_name": "carchi8py", "wins": "1" }, { "loses": "0", "user_name": "bob", "wins": "1" } ] } ``` - Call Hangman.get_high_scores to see who has the least ammount of guesses to win ```json { "items": [ { "date": "2016-07-06", "guesses": "0", "user_name": "bob", "won": true }, { "date": "2016-07-04", "guesses": "48", "user_name": "carchi8py", "won": true } ] } ``` <file_sep># -*- coding: utf-8 -*-` """api.py - Create and configure the Game API exposing the resources. This can also contain game logic. For more complex games it would be wise to move game logic to another file. Ideally the API will be simple, concerned primarily with communication to/from the API's users.""" import logging import endpoints from protorpc import remote, messages from google.appengine.api import memcache from google.appengine.api import taskqueue from models import User, Game, Score from models import StringMessage, NewGameForm, GameForm, MakeMoveForm,\ GameForms, ScoreForms, UserForms, MoveHistoryForm import util USER_REQUEST = endpoints.ResourceContainer( user_name = messages.StringField(1), email = messages.StringField(2)) NEW_GAME_REQUEST = endpoints.ResourceContainer(NewGameForm) MAKE_MOVE_REQUEST = endpoints.ResourceContainer( MakeMoveForm, urlsafe_game_key=messages.StringField(1),) GET_GAME_REQUEST = endpoints.ResourceContainer( urlsafe_game_key=messages.StringField(1),) HIGH_SCORE_REQUEST = endpoints.ResourceContainer( number_of_results=messages.IntegerField(1)) @endpoints.api(name = "hangman", version = "v1") class Hangman(remote.Service): @endpoints.method(request_message = USER_REQUEST, response_message = StringMessage, path = 'user', name = 'create_user', http_method = 'POST') def create_user(self, request): """ Creates a new User. Username is required """ if User.query(User.name == request.user_name).get(): raise endpoints.ConflictException( "Username: %s is already taken!" % request.user_name) user = User(name = request.user_name, email = request.email) user.put() return StringMessage(message = "User {} created".format( request.user_name)) @endpoints.method(request_message = NEW_GAME_REQUEST, response_message = GameForm, path = 'game', name = 'new_game', http_method = 'POST') def new_game(self, request): """ Creates a new hangman game. The word will be selected randomly from a file """ user = User.query(User.name == request.user_name).get() if not user: raise endpoints.NotFoundException( "Username: %s not found" % request.user_name) # new game can't fail (we are garenteed a username, the other 2) # options are optional so we don't need a try game = Game.new_game(user.key, request.target, request.attempts) return game.to_form("Good Luck") @endpoints.method(request_message=MAKE_MOVE_REQUEST, response_message=GameForm, path='game/{urlsafe_game_key}', name='make_move', http_method='PUT') def make_move(self, request): """ Alows the user to make a single move in Hangman """ game = util.get_by_urlsafe(request.urlsafe_game_key, Game) # If the game dosn't exist or has been cancled raise an error if not game: raise endpoints.NotFoundException("The game dose not exist") # If the user trys to make a move in a copleted game let them know # the game is over if game.game_over: return game.to_form("The Game is over") # if the user has guessed the word complete the game if request.guess == game.target: return game.to_form(self._winner(game)) # The User is only allowed to guess one charater at a time if len(request.guess) != 1: raise endpoints.BadRequestException( "Guess one letter at a time") #Check to see if the users has Found a letter or not hit_or_miss = "Miss" for i in range(len(game.target)): if game.target[i].lower() == request.guess.lower(): game.revealed_word = game.revealed_word[:i] + \ game.target[i] + game.revealed_word[i+1:] hit_or_miss = "Hit" if hit_or_miss == "Miss": game.attempts_remaining -= 1 move_history = "Guess: '%s', Result: '%s'" % ( request.guess, game.revealed_word) game.moves.append(move_history) # Now check to see if the user has if game.revealed_word == game.target: return game.to_form(self._winner(game)) # check to see if the player has lost if game.attempts_remaining < 1: lose_text = "Game Over" game.moves.append(lose_text) game.end_game(False) return game.to_form(lose_text) # If the user hasn't lost then move on to the next move else: game.put() return game.to_form(hit_or_miss) @endpoints.method(request_message=USER_REQUEST, response_message=GameForms, path='games/user/{user_name}', name='get_user_games', http_method='GET') def get_user_games(self, request): """ Returns all the Users active games """ user = User.query(User.name == request.user_name).get() if not user: raise endpoints.NotFoundException( "User %s dosn't exist" % request.user_name) # we only care about the game that are not complete games = Game.query(Game.user == user.key).filter(Game.game_over == False) return GameForms(items = [game.to_form('') for game in games]) @endpoints.method(request_message=GET_GAME_REQUEST, response_message=StringMessage, path='game/{urlsafe_game_key}', name='cancel_game', http_method='DELETE') def cancel_game(self, request): """ Cancels a game that has already started """ game = util.get_by_urlsafe(request.urlsafe_game_key, Game) # check to see if the game exist or not if not game: raise endpoints.NotFoundException("Game Not Found") # If we have a game and it not over delete the game if not game.game_over: game.key.delete() return StringMessage(message = "Game {} cancelled!".format( game.key.urlsafe())) # don't delete finished games else: return StringMessage(message = "Can't cancel, completed game".format( game.key.urlsafe())) @endpoints.method(request_message=HIGH_SCORE_REQUEST, response_message=ScoreForms, path='scores/high', name='get_high_scores', http_method='GET') def get_high_scores(self, request): """ Returns the leader-board for hangman """ scores = Score.query(Score.won == True).order(Score.guesses).fetch(request.number_of_results) return ScoreForms(items = [score.to_form() for score in scores]) @endpoints.method(response_message=UserForms, path='ranking', http_method='GET', name='get_user_rankings') def get_user_rankings(self, request): """ Order users by who has the most wins """ users = User.query(User.wins > 0).order(User.wins) return UserForms(items = [user.to_form() for user in users]) @endpoints.method(request_message=GET_GAME_REQUEST, response_message=MoveHistoryForm, path='game/history/{urlsafe_game_key}', name='get_game_history', http_method='GET') def get_game_history(self, request): """ Return all move in a game """ game = util.get_by_urlsafe(request.urlsafe_game_key, Game) if not game: raise endpoints.NotFoundException('Game not found!') return MoveHistoryForm(moves = game.moves) def _winner(self, game): """ Called in the different cases we have a winner """ winner_text = "You Win!" game.moves.append(winner_text) game.end_game(True) return winner_text api = endpoints.api_server([Hangman])<file_sep>"""models.py - This file contains the class definitions for the Datastore entities used by the Game. Because these classes are also regular Python classes they can include methods (such as 'to_form' and 'new_game').""" import random from datetime import date from protorpc import messages from google.appengine.ext import ndb #list of random words to use if the user hasn't given us a word WORDS = ["horse", "door", "baseball", "dominoes", "hockey", "aircraft", "password", "gingerbread", "shallow", "lightsaber"] class User(ndb.Model): """ User Profile """ name = ndb.StringProperty(required = True) email = ndb.StringProperty() wins = ndb.IntegerProperty(default = 0) loses = ndb.IntegerProperty(default = 0) def to_form(self): return UserForm(user_name = self.name, wins = self.wins, loses = self.loses) class Game(ndb.Model): """ Game Object """ target = ndb.StringProperty(required = True) revealed_word = ndb.StringProperty(required = True) attempts_allowed = ndb.IntegerProperty(required = True) attempts_remaining = ndb.IntegerProperty(required = True, default = 5) game_over = ndb.BooleanProperty(required = True, default = False) user = ndb.KeyProperty(required = True, kind = 'User') moves = ndb.StringProperty(repeated = True) @classmethod def new_game(cls, user, target, attempts): """ Creates a new game """ #if the user hasn't given us a word use a random word if not target: target = WORDS[random.randint(0,9)] game = Game(user = user, target = target, revealed_word = '*' * len(target), attempts_allowed = attempts, attempts_remaining = attempts, game_over = False, moves = []) game.put() return game def to_form(self, message): """ Returns a GameForm representation of the Game """ form = GameForm() form.urlsafe_key = self.key.urlsafe() form.user_name = self.user.get().name form.attempts_remaining = self.attempts_remaining form.game_over = self.game_over form.message = message form.revealed_word = self.revealed_word form.moves = self.moves return form def end_game(self, won=False): """ Ends the game """ self.game_over = True self.put() # Add the game to the score 'board' score = Score(user=self.user, date=date.today(), won=won, guesses=self.attempts_allowed - self.attempts_remaining) score.put() user = User.query(User.name == self.user.get().name).get() if won: user.wins += 1 else: user.loses += 1 user.put() class Score(ndb.Model): """ Score object """ user = ndb.KeyProperty(required = True, kind = 'User') date = ndb.DateProperty(required = True) won = ndb.BooleanProperty(required = True) guesses = ndb.IntegerProperty(required = True) def to_form(self): return ScoreForm(user_name = self.user.get().name, won = self.won, date = str(self.date), guesses = self.guesses) class GameForm(messages.Message): """ GameForm for outbound game state information """ urlsafe_key = messages.StringField(1, required = True) attempts_remaining = messages.IntegerField(2, required = True) game_over = messages.BooleanField(3, required = True) message = messages.StringField(4, required = True) user_name = messages.StringField(5, required = True) revealed_word = messages.StringField(6, required = True) moves = messages.StringField(7, repeated = True) class GameForms(messages.Message): """ Return multiple GameForms """ items = messages.MessageField(GameForm, 1, repeated = True) class NewGameForm(messages.Message): """ Used to create a new game """ user_name = messages.StringField(1, required = True) target = messages.StringField(2) attempts = messages.IntegerField(3, default = 5) class MakeMoveForm(messages.Message): """ Make a move in an existing game """ guess = messages.StringField(1, required = True) class ScoreForm(messages.Message): """ ScoreForm for outbound Score information """ user_name = messages.StringField(1, required = True) date = messages.StringField(2, required = True) won = messages.BooleanField(3, required = True) guesses = messages.IntegerField(4, required = True) class ScoreForms(messages.Message): """ Return multiple ScoreForms """ items = messages.MessageField(ScoreForm, 1, repeated = True) class UserForm(messages.Message): """ UserForm for outbound User's performance information """ user_name = messages.StringField(1, required = True) wins = messages.IntegerField(2, required = True) loses = messages.IntegerField(3, required = True) class UserForms(messages.Message): """ Return multiple UserForms """ items = messages.MessageField(UserForm, 1, repeated = True) class MoveHistoryForm(messages.Message): """ MoveHistoryForm for outbound a completed game's moves history """ moves = messages.StringField(1, repeated = True) class StringMessage(messages.Message): """ StringMessage-- outbound (single) string message """ message = messages.StringField(1, required = True)
f6958f10c26b3825668430fbba567b54b07b1261
[ "Markdown", "Python" ]
4
Markdown
carchi8py/FSND-P4-Design-A-Game
a159730b85b363ebb6c7fa3ec69125f76cc109a7
b6dbdc69fb4727fc9bc865201be455ee9ab7abdf
refs/heads/master
<file_sep>package edu.uco.twilliams84.termprojecttimothyw.Model; public class BallStateDead extends GameObjectState{ Ball ball; public BallStateDead(GameObject gameObject) { super(gameObject); Ball ball = (Ball) gameObject; } @Override public void update() { //Add score to high score list } } <file_sep>package edu.uco.twilliams84.termprojecttimothyw.Database; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList; import edu.uco.twilliams84.termprojecttimothyw.Model.Player; public class DatabaseOperator extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "PLAYER_DATABASE"; public DatabaseOperator(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(PlayerTable.SQL_CREATE_ENTRIES); db.execSQL(PlayerTable.SQL_CREATE_SCORE_ENTRIES); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(PlayerTable.SQL_DELETE_SCORE_ENTRIES); db.execSQL(PlayerTable.SQL_DELETE_ENTRIES); onCreate(db); } public boolean addPlayer(edu.uco.twilliams84.termprojecttimothyw.Model.Player player) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(PlayerTable.PlayerEntry.COLUMN_EMAIL, player.getEmail()); values.put(PlayerTable.PlayerEntry.COLUMN_NAME, player.getName()); values.put(PlayerTable.PlayerEntry.COLUMN_CITY, player.getCity()); values.put(PlayerTable.PlayerEntry.COLUMN_STATE, player.getState()); values.put(PlayerTable.PlayerEntry.COLUMN_PASS, player.getPassword()); long id = db.insert(PlayerTable.PlayerEntry.TABLE_NAME, null, values); db.close(); return true; } public boolean findPlayer(edu.uco.twilliams84.termprojecttimothyw.Model.Player player) { SQLiteDatabase database = this.getReadableDatabase(); String[] projection = { PlayerTable.PlayerEntry.COLUMN_NAME, PlayerTable.PlayerEntry.COLUMN_EMAIL, PlayerTable.PlayerEntry.COLUMN_PASS, PlayerTable.PlayerEntry.COLUMN_CITY, PlayerTable.PlayerEntry.COLUMN_STATE }; //Filter results where "COLUMN_EMAIL = email String selection = PlayerTable.PlayerEntry.COLUMN_EMAIL + " = ?"; String[] selectionArgs = {player.getEmail()}; Cursor cursor = database.query( PlayerTable.PlayerEntry.TABLE_NAME, //Table being queried projection, //The columns being returned selection, //The columns for the WHERE clause selectionArgs, //The values for the WHERE clause null, //No row grouping null, //No row group filtering null //Order of results ); //Navigate the results boolean found = false; if (cursor.moveToFirst()) { String retrievedPassword = cursor.getString(cursor.getColumnIndexOrThrow(PlayerTable.PlayerEntry.COLUMN_PASS)); if (retrievedPassword.equals(player.getPassword())) { String playerName = cursor.getString(cursor.getColumnIndexOrThrow(PlayerTable.PlayerEntry.COLUMN_NAME)); String playerCity = cursor.getString(cursor.getColumnIndexOrThrow(PlayerTable.PlayerEntry.COLUMN_CITY)); String playerState = cursor.getString(cursor.getColumnIndexOrThrow(PlayerTable.PlayerEntry.COLUMN_STATE)); String playerEmail = cursor.getString(cursor.getColumnIndexOrThrow(PlayerTable.PlayerEntry.COLUMN_EMAIL)); String playerPassword = cursor.getString(cursor.getColumnIndexOrThrow(PlayerTable.PlayerEntry.COLUMN_PASS)); Player.player = new Player( playerName, playerCity, playerState, playerEmail, playerPassword ); found = true; } } else { found = false; } return found; } public ArrayList<Player> gatherScores() { ArrayList<Player> players = new ArrayList<>(); SQLiteDatabase database = this.getReadableDatabase(); Cursor cursor = database.rawQuery(PlayerTable.SQL_GET_ALL_SCORES, null); while(cursor.moveToNext()) { String playerName = cursor.getString(cursor.getColumnIndexOrThrow(PlayerTable.PlayerEntry.COLUMN_NAME)); String playerCity = cursor.getString(cursor.getColumnIndexOrThrow(PlayerTable.PlayerEntry.COLUMN_CITY)); String playerState = cursor.getString(cursor.getColumnIndexOrThrow(PlayerTable.PlayerEntry.COLUMN_STATE)); String playerEmail = cursor.getString(cursor.getColumnIndexOrThrow(PlayerTable.PlayerEntry.COLUMN_EMAIL)); int playerScore = cursor.getInt(cursor.getColumnIndexOrThrow(PlayerTable.ScoreEntry.COLUMN_SCORE)); boolean foundPlayer = false; for (Player player : players) { if (player.getEmail().equals(playerEmail)) { player.addScore(playerScore); foundPlayer = true; } } if (!foundPlayer) { Player player = new Player(playerName, playerCity, playerState, playerEmail, null); player.addScore(playerScore); players.add(player); } } database.close(); return players; } public boolean addScore(Player player, int score) { SQLiteDatabase database = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(PlayerTable.ScoreEntry.COLUMN_EMAIL, player.getEmail()); values.put(PlayerTable.ScoreEntry.COLUMN_SCORE, score); long id = database.insert(PlayerTable.ScoreEntry.TABLE_NAME, null, values); return true; } } <file_sep>package edu.uco.twilliams84.termprojecttimothyw.View; import android.Manifest; import android.app.Activity; import android.content.ContentResolver; import android.content.pm.PackageManager; import android.database.Cursor; import android.os.Build; import android.os.Bundle; import android.provider.ContactsContract; import android.telephony.SmsManager; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.ArrayList; import java.util.Collections; import edu.uco.twilliams84.termprojecttimothyw.Model.Contact; import edu.uco.twilliams84.termprojecttimothyw.R; public class InviteActivity extends Activity { static ArrayList<Contact> contacts = new ArrayList<>(); private ListView contactsList; private String[] contactNames; private int currentContact; //Request int private static final int PERMISSION_REQEST_READ_CONTACTS = 1; private static final int PERMISSION_REQUEST_SEND_SMS = 2; @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); setContentView(R.layout.activity_invite); contacts.clear(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(android.Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSION_REQEST_READ_CONTACTS); } else { fillContacts(); } contactNames = new String[contacts.size()]; for (int i = 0; i < contacts.size(); i++) { contactNames[i] = contacts.get(i).getName(); } contactsList = (ListView) findViewById(R.id.invite_contacts); ArrayAdapter<String> adapter = new ArrayAdapter<String>( this, R.layout.contacts, contactNames ); contactsList.setAdapter(adapter); contactsList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { currentContact = position; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{Manifest.permission.SEND_SMS}, PERMISSION_REQUEST_SEND_SMS); } else { sendSmsMessage(); } } }); } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { if (requestCode == PERMISSION_REQEST_READ_CONTACTS) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { fillContacts(); } } else if (requestCode == PERMISSION_REQUEST_SEND_SMS) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { sendSmsMessage(); } } } public void fillContacts () { ContentResolver contentResolver = getContentResolver(); Cursor contactCursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); if (contactCursor.getCount() > 0) { while (contactCursor.moveToNext()) { String id = contactCursor.getString( contactCursor.getColumnIndex(ContactsContract.Contacts._ID) ); String name = contactCursor.getString( contactCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME) ); if (contactCursor.getInt(contactCursor.getColumnIndex( ContactsContract.Contacts.HAS_PHONE_NUMBER )) > 0) { Cursor phoneCursor = contentResolver.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", new String[]{id}, null); while (phoneCursor.moveToNext()) { String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER )); contacts.add(new Contact(name, phoneNumber)); } } } } Collections.sort(contacts, Contact.compareNames()); } public void sendSmsMessage() { SmsManager smsManger = SmsManager.getDefault(); smsManger.sendTextMessage(contacts.get(currentContact).getPhoneNumber(), null, "You've been invited by " + contacts.get(currentContact).getName() + " to play Ball Game!", null, null); Log.e(contacts.get(currentContact).getName(), contacts.get(currentContact).getPhoneNumber()); } } <file_sep>package edu.uco.twilliams84.termprojecttimothyw.View; import android.app.Activity; import android.location.Geocoder; import android.os.Bundle; import android.view.Window; import android.location.Address; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import java.io.IOException; import java.util.List; import java.util.Locale; import edu.uco.twilliams84.termprojecttimothyw.Database.DatabaseOperator; import edu.uco.twilliams84.termprojecttimothyw.Model.Player; import edu.uco.twilliams84.termprojecttimothyw.R; public class ScoreMapActivity extends Activity implements OnMapReadyCallback { private GoogleMap mMap; @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); setContentView(R.layout.activity_score_map); MapFragment mapFragment = (MapFragment) getFragmentManager() .findFragmentById(R.id.map); mapFragment.getMapAsync(this); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; try { DatabaseOperator databaseOperator = new DatabaseOperator(this); ScoreActivity.players = databaseOperator.gatherScores(); Geocoder geocoder = new Geocoder(this, Locale.getDefault()); for (Player player : ScoreActivity.players) { List<Address> addresses = geocoder.getFromLocationName(player.getCity() + ", " + player.getState() ,1); Address address = addresses.get(0); double longitude = address.getLongitude(); double lantitude = address.getLatitude(); LatLng latlng = new LatLng(lantitude, longitude); mMap.addMarker(new MarkerOptions() .position(latlng) .title(player.getName()) .snippet(player.getScores().get(0).toString())); mMap.moveCamera(CameraUpdateFactory.newLatLng(latlng)); } } catch (IOException e) { System.exit(0); } } } <file_sep>package edu.uco.twilliams84.termprojecttimothyw.Model; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.DashPathEffect; import android.graphics.Paint; import android.graphics.Point; import edu.uco.twilliams84.termprojecttimothyw.R; import edu.uco.twilliams84.termprojecttimothyw.View.GameView; public class Hole extends GameObject { public static final int OUTER_RADIUS = 65; private final int COLOR = gameView.getResources().getColor(R.color.game_hole_color); private final DashPathEffect dashPath = new DashPathEffect(new float[]{20,5}, (float)1.0); public Hole(Point point, int radius, GameView gameView) { super(point, radius, gameView); gameObjectState = new EnemyStateAlive(this); } @Override public void draw(Canvas canvas) { if (gameObjectState instanceof EnemyStateAlive) { paint.setStrokeWidth(5f); paint.setColor(Color.BLACK); paint.setPathEffect(dashPath); paint.setStyle(Paint.Style.STROKE); canvas.drawCircle(point.x, point.y, OUTER_RADIUS, paint); paint.setColor(COLOR); paint.setPathEffect(null); paint.setStyle(Paint.Style.FILL); canvas.drawCircle(point.x, point.y, length, paint); } } @Override public void incrementLength() { length += OUTER_RADIUS/lengthIncrement; } }<file_sep>package edu.uco.twilliams84.termprojecttimothyw.Model; import java.util.Comparator; public class Contact { String name; String phoneNumber; public Contact(String name, String phoneNumber) { this.name = name; this.phoneNumber = phoneNumber; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public static Comparator<Contact> compareNames() { Comparator comparator = new Comparator<Contact>() { @Override public int compare(Contact c1, Contact c2) { return c1.getName().compareTo(c2.getName()); } }; return comparator; } } <file_sep>package edu.uco.twilliams84.termprojecttimothyw.Controller; import edu.uco.twilliams84.termprojecttimothyw.Model.Ball; public class ScoreObserver extends Observer { private long startTime; public ScoreObserver(Ball ball) { this.ball = ball; this.startTime = System.currentTimeMillis(); } @Override public void update() { //Time long currentTime = System.currentTimeMillis(); if ((currentTime - startTime)/1000 >= 1){ ball.setScore(ball.getScore()+1); startTime = currentTime; } //Gem destroyed if (ball.isGemDestroyed()) { ball.setScore(ball.getScore()+10); ball.setGemDestroyed(false); } } } <file_sep>package edu.uco.twilliams84.termprojecttimothyw.Model; public class EnemyStateAlive extends GameObjectState{ public EnemyStateAlive(GameObject gameObject) { super(gameObject); } @Override public void update() { //Increment the size of the inner shape if (gameObject instanceof Wall) { Wall wall = (Wall) gameObject; if (wall.length >= Wall.OUTER_SIDE_LENGTH) { gameObject.setGameObjectState(new EnemyStateDead(gameObject)); } else { gameObject.incrementLength(); } } else if (gameObject instanceof Hole) { Hole hole = (Hole) gameObject; if (hole.length >= Hole.OUTER_RADIUS) { gameObject.setGameObjectState(new EnemyStateDead(gameObject)); } else { gameObject.incrementLength(); } } } }
a7992a00624e233409779aa17d3c8646364644f5
[ "Java" ]
8
Java
tcalebw/Ball-Game
e13edcc43a04de5c8634c0e6da8d16548e0a4b38
6916acfc5311d868f8a719d9cfe5aba19a9eabc3
refs/heads/master
<file_sep>import java.util.Scanner; import java.util.Random; public class Array1 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scn = new Scanner(System.in); Random rnd = new Random(); int date[] = new int[10]; int count=0; for(int i=0;i<10;i++){ date[i]=rnd.nextInt(100); if(date[i]%2==0){ count++; } } int j = 0; while(j<3){ System.out.println("請猜有多少個偶數"); int k=scn.nextInt(); if(k==count){ System.out.println("恭喜你猜對了"); for(int i=0;i<10;i++){ System.out.println(date[i]+"\t"); } break; }else{ System.out.println("你輸了");} for(int i=0;i<10;i++){ System.out.println(date[i]+"\t"); } j++; } System.out.println("遊戲結束"); } } <file_sep>import java.util.Scanner; public class Date81905 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scn = new Scanner(System.in); System.out.println("請輸入一個正整數"); int n = scn.nextInt(); System.out.println("請輸入進制(1~10)"); int b = scn.nextInt(); String str = ""; while (n >= b) { str = Integer.toString(n % b) + str; n = n / b; } str = Integer.toString(n % b) + str; System.out.print(str); } } <file_sep> import java.util.Scanner; public class A7 { public static void main(String[] args) { // TODO Auto-generated method stub Scanner scn =new Scanner(System.in); System.out.println("½Ð¿é¤JÄá¤ó"); Float C = scn.nextFloat(); Float F = C*9/5+32; System.out.print("µØ¤ó¬°"+F); } }
7ef30dd6bacaeed641a330bac41ddbb6e0736923
[ "Java" ]
3
Java
Tomorrow0w0/104-Jave
196b1134fb189c0400fa283470f7231660ed6541
c58a3fa23f2d5d0f48cb5bb870247e27089e6ceb
refs/heads/master
<repo_name>quanghieu2556/Test<file_sep>/README.md # Test V 1.0 <file_sep>/hello.cs main(){ printf("Hello world"); printf("Hello everyone"); printf("Welcom1"); }
55dbd33d527c7b45a74abee851c0ab35328a1980
[ "Markdown", "C#" ]
2
Markdown
quanghieu2556/Test
90c5ee72a4a26650df7cc4700f21b2a84f995490
7bb860833a573833e2ba97694f72252c68ab1f4d
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Params, Router } from '@angular/router'; import { HttpService } from '../http.service'; @Component({ selector: 'app-authors', templateUrl: './authors.component.html', styleUrls: ['./authors.component.css'] }) export class AuthorsComponent implements OnInit { authors: any; constructor( private _httpService: HttpService, private _route: ActivatedRoute, private _router: Router ) { this.authors = {}; } ngOnInit() { this._httpService.getAuthors().subscribe(authors => { this.authors = authors; }); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Params, Router } from '@angular/router'; import { HttpService } from '../http.service'; @Component({ selector: 'app-quote', templateUrl: './quote.component.html', styleUrls: ['./quote.component.css'] }) export class QuoteComponent implements OnInit { author: any; constructor( private _httpService: HttpService, private _route: ActivatedRoute, private _router: Router ) { this.author = {}; } ngOnInit() { this._route.params.subscribe((params: Params) => { this._httpService.getAuthor(params['id']).subscribe(author => { this.author = author; }); }); } addVote(quote, num) { quote.votes += num; this._httpService.addVote(quote).subscribe(() => {}); } deleteQuote(id) { this._httpService.deleteQuote(id).subscribe(deletedQuote => { for (let i = 0; i < this.author.quotes.length; i++) { if (this.author.quotes[i]._id === id) { this.author.quotes.splice(i, 1); break; } } }); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Params, Router } from '@angular/router'; import { HttpService } from '../http.service'; @Component({ selector: 'app-addauthor', templateUrl: './addauthor.component.html', styleUrls: ['./addauthor.component.css'] }) export class AddauthorComponent implements OnInit { author: any; constructor( private _httpService: HttpService, private _route: ActivatedRoute, private _router: Router ) { this.author = {}; } ngOnInit() {} createAuthor() { this._httpService.createAuthor(this.author).subscribe(() => {}); this._router.navigate(['/author']); } } <file_sep>import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class HttpService { constructor(private _http: HttpClient) {} getAuthors() { return this._http.get('/authors'); } getAuthor(id) { return this._http.get(`/authors/${id}`); } createAuthor(author) { return this._http.post('/authors', author); } addVote(quote) { return this._http.put(`/quotes/${quote._id}`, quote); } deleteQuote(id) { return this._http.delete(`/quotes/${id}`); } createQuote(quote) { return this._http.post('/quotes', quote); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Params, Router } from '@angular/router'; import { HttpService } from '../http.service'; @Component({ selector: 'app-newquote', templateUrl: './newquote.component.html', styleUrls: ['./newquote.component.css'] }) export class NewquoteComponent implements OnInit { author: any; quote: any; constructor( private _httpService: HttpService, private _route: ActivatedRoute, private _router: Router ) { this.author = {}; this.quote = {}; } ngOnInit() { this._route.params.subscribe((params: Params) => { this._httpService.getAuthor(params['id']).subscribe(author => { this.author = author; }); }); } createQuote() { this.quote.author = this.author.name; this._httpService.createQuote(this.quote).subscribe(() => {}); this._router.navigate(['/author/', this.author._id]); } }
b8c2ecd0654bb90c5c08eb01374ab6c98f05c5af
[ "TypeScript" ]
5
TypeScript
twilksonjr/quote_rank-mean-stack
06183fa2ea62baa794736323fa3fdedc51786e27
8931d9f3267548359b87092592dc6addb08ea635
refs/heads/master
<repo_name>wangzhongzhen/test<file_sep>/train.py #!/usr/bin/env python2 # -*- coding: utf-8 -*- import torch import resnet3d import torch.nn as nn from MakeData import myImageFloder device = torch.device ('cuda' if torch.cuda.is_available() else 'cpu') # train_dataset = myImageFloder(root = "data_test") #test_dataset = myImageFloder(root = 'data') # Data loader train_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size = 1, shuffle = True) #test_loader = torch.utils.data.DataLoader(dataset=test_dataset, # batch_size = 2, # shuffle = True) resnet = resnet3d.Resnet3d(resnet3d.Basicblock) net = resnet.to(device) def train(epoch): print('epoch:',epoch) for batch_idx,(inputs,targets) in enumerate(train_loader): print(inputs) inputs = torch.from_numpy(inputs) train(1)
8f43e30618b954e1ae3c19e32e01ee0c785555ef
[ "Python" ]
1
Python
wangzhongzhen/test
bd69c6a19b56561abd1dc12f228f1e7cc74df7f3
5341c8ff913e646ac3a9da5ca647a37186cd68a7
refs/heads/master
<file_sep>package it.polito.tdp.model; import java.util.ArrayList; import java.util.List; import it.polito.tdp.dao.EsameDAO; public class Model { private List<Esame> esami; private EsameDAO edao; private List<Esame> soluzione; private double bestAvg; public Model() { edao = new EsameDAO(); esami = edao.getTuttiEsami(); // Controllo se ho popolato correttamente // for(Esame e : esami) { // System.out.println(e); // } } public List<Esame> calcolaSottoinsiemeEsami(int numeroCrediti) { // inizializzazione soluzione = new ArrayList<Esame>(); bestAvg = 0.0; int step = 0; List<Esame> parziale = new ArrayList<>(); recursive(step, parziale, numeroCrediti); return soluzione; } private void recursive(int step, List<Esame> parziale, int numeroCrediti) { /* * NB: la funzione ricorsiva di solito ritorna: - void: se vogliamo la migliore * soluzione possibile (tra tutte) - boolean: se vogliamo una soluzione in * particolare (la prima ad esempio) */ // Debug // for (Esame e : parziale) { // System.out.print(e.getCodins() + " "); // } // System.out.println(" "); // Condizione di terminazione if (totCrediti(parziale) > numeroCrediti) { return; } // Controllo se ho trovato una soluzione migliore della precedente if (totCrediti(parziale) == numeroCrediti) { if (avg(parziale) > bestAvg) { soluzione = new ArrayList<>(parziale); // deep copy! (fotografia) bestAvg = avg(parziale); // aggiorno il 'bestAvg' } } // Generazione di una nuova soluzione parziale for (Esame esame : esami) { if (!parziale.contains(esame)) { // NB: per usare contains devo aver definito hashCode e equals !!! parziale.add(esame); recursive(step + 1, parziale, numeroCrediti); parziale.remove(esame); } } } private double avg(List<Esame> parziale) { double avg = 0; for (Esame e : parziale) { avg += e.getCrediti() * e.getVoto(); } avg /= totCrediti(parziale); return avg; } private int totCrediti(List<Esame> parziale) { int somma = 0; for (Esame e : parziale) { somma += e.getCrediti(); } return somma; } }
1314c146724f11715a2474b20845d425d459bdc7
[ "Java" ]
1
Java
riccardoandretta/VotiNobel
30814c6a9cee7300e06f683eb1649767fc32a559
10eb86646bd516e8fb18eac6c373b002785d3ecd
refs/heads/master
<file_sep>the folder mainly contain four kinds of files: #### **Mosfet parameter model card** The model card is generated by PTM website(http://ptm.asu.edu/) at 45nm technology node, which includes basic pmos and nmos BSIM4 model. #### **Clock buffer spice netlist** Clock buffer behaves as two serial inverters so it is contructed with two same inverters. Size of each inverter is designed same as the inverters in ISPD 2009 competition(http://www.ispd.cc/contests/09/ispd09cts.html) package currently. #### **Simulation process control** To generate target lookup tables (LUTs), we use ngspice as simulator to get simulation data. As our expected, we want to get three LUTs of buffer at Near-Threshold Voltage (NTV): delay model, transition (output slew) propagation model, power dissiption model. The first two model is different from normal buffer model which works at normal voltage, they are responsible for technology variation characterization. So , the simulation performs 200 times (for simplify) Monte Carlo simulation at 0.55v to get $\mu$ and $\sigma$ of delay and output slew. #### **Python scripts for automation** To sweep the different input slew and load capacitance combination conditions, we use python script to control input slew and load capacitance in the simulation process and automatically collcet the simulation results from log file after simulation. <file_sep># Paper_Reproduction reproduction paper researching in Ultra-low voltage (ULV) clock tree design # DP+DME DP+DME algorithm is proposed by <NAME> in 2010[1] to optimize clock tree slew and skew at ULV. The reproduction code is located in **DP_DME** folder. # BufH In [2], Seok proposed an un-buffered H-tree (or few clock buffer level) method to dramatically reduce clock skew variation at ULV. For impressive purpose , the buffered-Htree with limited buffer stage level is implemented in **H-Tree** folder. #### Reference [[1]](https://drive.google.com/file/d/1EDHklBIlDvOlwln5HmBJMbFlZlWSy5vJ/view?usp=sharing)Zhao, Xin, et al. "Variation-aware clock network design methodology for ultralow voltage (ULV) circuits." *IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems* 31.8 (2012): 1222-1234. [[2]](https://drive.google.com/file/d/1IH5j_FlfenFgr2vIS6LNwAvcRrhCVRd6/view?usp=sharing)[Seok, Mingoo, <NAME>, and <NAME>. "Robust clock network design methodology for ultra-low voltage operations." *IEEE Journal on Emerging and Selected Topics in Circuits and Systems* 1.2 (2011): 120-130.<file_sep># **h-tree复现** ### **un-buffered H-tree** 电路描述:该电路来自ispd2009的example电路,有81个sink。 复现说明:原文中是使用H-tree驱动mesh的方式来实现h-tree。我用h-tree驱动子树的方式实现。 ##### **2级时钟树** ![2level](/Users/mac/Desktop/2level.png) ##### **3级时钟树** ![3level](/Users/mac/Desktop/3level.png) ### **buffered H-tree** buffered H-tree相对简单,就是在分支处插buffer,具体实现及实验数据的结果还需要依赖buffer单元库。 <file_sep>ISPD 2009 Clock Synthesis contest This file explains the example package together with the evaluation script. //--------------------------------------------------------------------------// //--------------------------------------------------------------------------// Files in this package: tuned_45nm_HP.pm : model card for ngspice simulation clkinv0.subckt : spice subckt file describing an inverter eval2009.pl : evaluation script explain_s1_s1s : Notes on the sample input file "s1" and sample output file "s1s" s1 : sample input file s1s : sample output file s1.diff_names : sample input file; the problem is exactly the same as s0, with different node/buf/wireType name s1s.diff_names : sample output file; exactly same clock routing as s1s, with different node/buf/wireType name s1.pdf : explanation of s1 and s1s with pictures //--------------------------------------------------------------------------// //--------------------------------------------------------------------------// How to use eval2009.pl? ** to show help message ./eval2010.pl or ./eval2010.pl -h ** to run eval2009 ./eval2010.pl -s ispd10cnsSample.in ispd10cnsSample.out tuned_45nm_HP.pm "-s" is to prevent abort when slew violation exists in the example. RESULTS WILL BE LIKE THIS: ispd10cnsSample.in ispd10cnsSample.out wLCS 5.862 (ps) C 4587.744 (s 245.000 b 1380.000 w 2962.744)(fF) maxNominalSkew 60.660 It shows that using the clock routing "ispd10cnsSample.out", the worst local clock skew is 5.862ps while the total capacitance of clock network is 4587.744fF If you want to see the clock latency at all clock sinks, you can use "-v" switch ./eval2009.pl -v1 ispd10cnsSample.in ispd10cnsSample.out tuned_45nm_HP.pm NOTES: You must have ngspice in your PATH. You must have perl in /usr/bin/ //--------------------------------------------------------------------------// //--------------------------------------------------------------------------// <file_sep># -*- coding: utf-8 -*- # @Author: mac # @Date: 2019-10-22 20:19:53 # @Last Modified by: mac # @Last Modified time: 2019-10-23 20:57:31 import math from scipy import interpolate import copy import numpy as np import matplotlib.pyplot as plt from sklearn.cluster import KMeans import sys class leaf: def __init__(self,location): self.location = location self.queue = [] def add_to_queue(self,leaf): self.queue.append(leaf) class sink: def __init__(self,location,group=0): self.location = location self.group = group def set_group(self,group): self.group = group class htree: def __init__(self,sink_num,root_location,height,width): self.level = math.log(sink_num,4) self.root_location = root_location self.height = height self.width = width self.leaf_points = [leaf(location=root_location)] # list of list self.last_leaves = [] self.leaf2sink_groups = [] def generate_last_leaves(self): level = self.level if level == 1: cof = [-1/4,1/4] for i in range(2): for j in range(2): x = self.root_location[0] + cof[j]*self.width y = self.root_location[1] + cof[i]*self.height self.last_leaves.append(leaf(location=[x,y])) elif level == 2: cof = [-3/8,-1/8,1/8,3/8] for i in range(4): for j in range(4): x = self.root_location[0] + cof[j]*self.width y = self.root_location[1] + cof[i]*self.height self.last_leaves.append(leaf(location=[x,y])) elif level == 3: cof = [-7/16,-5/16,-3/16,-1/16,1/16,3/16,5/16,7/16] for i in range(8): for j in range(8): x = self.root_location[0] + cof[j]*self.width y = self.root_location[1] + cof[i]*self.height self.last_leaves.append(leaf(location=[x,y])) elif level == 4: cof = [-15/32,-13/32,-11/32,-9/32,-7/32,-5/32,-3/32,-1/32,1/32,3/32,5/32,7/32,9/32,11/32,13/32,15/32] for i in range(16): for j in range(16): x = self.root_location[0] + cof[j]*self.width y = self.root_location[1] + cof[i]*self.height self.last_leaves.append(leaf(location=[x,y])) else: print("level larger than 5 not supported") # cof1 = [-1/4,1/4] # cof2 = [-3/8,-1/8,1/8,3/8] # cof3 = [-7/16,-5/16,-3/16,-1/16,1/16,3/16,5/16,7/16] # cof4 = [-15/32,-13/32,-11/32,-9/32,-7/32,-5/32,-3/32,-1/32,1/32,3/32,5/32,7/32,9/32,11/32,13/32,15/32] def generate_leafpoints(self,center,level=0): if level != self.level: leaf1 = leaf(location=[center.location[0]-self.width/(4*2**level),center.location[1]-self.height/(4*2**level)]) leaf2 = leaf(location=[center.location[0]+self.width/(4*2**level),center.location[1]-self.height/(4*2**level)]) leaf3 = leaf(location=[center.location[0]-self.width/(4*2**level),center.location[1]+self.height/(4*2**level)]) leaf4 = leaf(location=[center.location[0]+self.width/(4*2**level),center.location[1]+self.height/(4*2**level)]) center.add_to_queue(leaf1) center.add_to_queue(leaf2) center.add_to_queue(leaf3) center.add_to_queue(leaf4) level = level + 1 self.generate_leafpoints(leaf1,level) self.generate_leafpoints(leaf2,level) self.generate_leafpoints(leaf3,level) self.generate_leafpoints(leaf4,level) def distance(self,location1,location2): return math.sqrt((location1[0]-location2[0])**2+(location1[1]-location2[1])**2) #TODO sink group is a list contain dictionary elements def generate_leaf_sinks_pair(self,sink_groups): for leaf_point in self.last_leaves: dis= np.inf for group in sink_groups: # group["centroid"] is a location list like [x,y] # group["sinks"] is a sink group contains sink0,sink1,.... dis_new = self.distance(leaf_point.location, group["centroid"]) if dis_new < dis: dis = dis_new current_sink_group = group["sinks"] self.leaf2sink_groups.append([leaf_point,current_sink_group]) # sink_groups.remove(current_sink_group) def generate_topology(self,sinks): self.generate_last_leaves() self.generate_leafpoints(center=self.leaf_points[0]) self.generate_leaf_sinks_pair(sinks) def readSinkLocations(file_path="s1r1.txt"): f = open(file_path, "r") bounds = f.readline().split(" ") sinks = [] minX = int(bounds[0]) minY = int(bounds[1]) maxX = int(bounds[2]) maxY = int(bounds[3]) # skip second Line f.readline() num_sinks_in_file = int(f.readline().split(" ")[2]) for u in range(num_sinks_in_file): data = f.readline().split(" ") location = [int(data[1]), int(data[2])] sinks.append(sink(location=location)) # update horizontal plot constraints if location[0] < minX: minX = location[0] elif location[0] > maxX: maxX = location[0] # update vertical plot constraints if location[1] < minY: minY = location[1] elif location[1] > maxY: maxY = location[1] f.close() shape = [minX,minY,maxX,maxY] return sinks, shape def partition_sinks(sinks,cluster_num): X = np.array([sink.location for sink in sinks]) kmeans = KMeans(n_clusters=cluster_num,random_state=0).fit(X) centroid = kmeans.cluster_centers_ for i in range(len(sinks)): sinks[i].group = kmeans.labels_[i] return centroid.tolist() def group_sinks(sinks,centroids): sink_groups = [] for i in range(len(centroids)): a_group = [] for sink in sinks: if sink.group == i: a_group.append(sink) sink_groups.append({"centroid":centroids[i],"sinks":a_group}) return sink_groups def draw(leaf,level=0): max_level = 3 if level != max_level: plt.plot([leaf.location[0],leaf.queue[0].location[0],leaf.queue[0].location[0]], [leaf.location[1],leaf.location[1],leaf.queue[0].location[1]],linewidth=1,c='k') plt.plot([leaf.location[0],leaf.queue[1].location[0],leaf.queue[1].location[0]], [leaf.location[1],leaf.location[1],leaf.queue[1].location[1]],linewidth=1,c='k') plt.plot([leaf.location[0],leaf.queue[2].location[0],leaf.queue[2].location[0]], [leaf.location[1],leaf.location[1],leaf.queue[2].location[1]],linewidth=1,c='k') plt.plot([leaf.location[0],leaf.queue[3].location[0],leaf.queue[3].location[0]], [leaf.location[1],leaf.location[1],leaf.queue[3].location[1]],linewidth=1,c='k') level = level + 1 draw(leaf.queue[0],level) draw(leaf.queue[1],level) draw(leaf.queue[2],level) draw(leaf.queue[3],level) def draw_connection(clock_tree): # draw connections between sinks and leafs for pairs in clock_tree.leaf2sink_groups: for i in range(len(pairs[1])): plt.plot([pairs[0].location[0],pairs[1][i].location[0]], [pairs[0].location[1],pairs[1][i].location[1]]) # draw connections between all level leafs leaf_points = clock_tree.leaf_points draw(leaf_points[0]) def main(): sinks,shape = readSinkLocations() htree_root = [int((shape[0]+shape[2])/2),int((shape[1]+shape[3])/2)] htree_width = shape[2] - shape[0] htree_height = shape[3] - shape[1] centroids = partition_sinks(sinks,64) sink_groups = group_sinks(sinks,centroids) print("intialize htree") htree_u = htree(64, htree_root, htree_height, htree_width) print("start generating topology") htree_u.generate_topology(sink_groups) fig = plt.figure() ax = fig.add_subplot(1,1,1) print("start drawing") draw_connection(htree_u) plt.show() if __name__ == '__main__': main()<file_sep>change sourcepath in "MC_buffer_fall.sp" and "MC_buffer_rise.sp" before running code <file_sep>##################################################################################### # The script is used to generate word document contains lookup table automatically. # # The data is collected from .txt file in buflib folder # ##################################################################################### from docx import Document from docx.shared import Inches,Pt buflib = ['X1','X2','X3','X4','X5'] buffer_size = {'X1':[2,1.37],'X2':[4,2.74], 'X3':[8,5.48],'X4':[16,10.96], 'X5':[32,21.92]} load_cap = [15,20,25,30,35,40,45] slew_in = [50,55,60,65,70,75,80] document = Document() document.add_heading('PTM45nm 0.55v下buffer查找表', 0) style = document.styles['Normal'] font = style.font font.name = 'SimHei' font.size = Pt(8) document.add_paragraph('时间单位:ps,电容单位:fF,功耗单位:uW') document.add_paragraph('buffer_type pmos(um) nmos(um)') for key,value in buffer_size.items(): document.add_paragraph('{} {} {}'.format(key,value[0],value[1])) document.add_page_break() for size in buflib: lut_fall = './buflib/{}/lut_fall.txt'.format(size) lut_rise = './buflib/{}/lut_rise.txt'.format(size) delay_table = [[] for i in range(7)] slew_table = [[] for i in range(7)] power_table = [[] for i in range(7)] # update lut data with open(lut_rise) as f: f.readline() for i in range(7): for j in range(7): data = f.readline().split() delay_table[i].append((data[0],data[1])) slew_table[i].append((data[2],data[3])) power_table[i].append(data[4]) document.add_heading(size, level=1) document.add_paragraph('输入信号上升沿', style='Intense Quote') document.add_paragraph('延迟及其波动表(均值/方差)', style='List Bullet') table = document.add_table(rows=1, cols=8) hdr_cells = table.rows[0].cells hdr_cells[0].text = "slew\\cap" for i,name in enumerate(load_cap): hdr_cells[i+1].text = str(name) for i,data in enumerate(delay_table): row_cells = table.add_row().cells row_cells[0].text = str(slew_in[i]) for j, delay in enumerate(data): miu,sigma = delay row_cells[j+1].text = "{:.1f}/{:.2f}".format(float(miu)*1e12,float(sigma)*1e12) document.add_paragraph('slew及其波动表(均值/方差)', style='List Bullet') table = document.add_table(rows=1, cols=8) hdr_cells = table.rows[0].cells hdr_cells[0].text = "slew\\cap" for i,name in enumerate(load_cap): hdr_cells[i+1].text = str(name) for i,data in enumerate(slew_table): row_cells = table.add_row().cells row_cells[0].text = str(slew_in[i]) for j, slew in enumerate(data): miu,sigma = slew row_cells[j+1].text = "{:.1f}/{:.2f}".format(float(miu)*1e12,float(sigma)*1e12) document.add_page_break() # update lut data delay_table = [[] for i in range(7)] slew_table = [[] for i in range(7)] power_table = [[] for i in range(7)] with open(lut_fall) as f: f.readline() for i in range(7): for j in range(7): data = f.readline().split() delay_table[i].append((data[0],data[1])) slew_table[i].append((data[2],data[3])) power_table[i].append(data[4]) document.add_heading(size, level=1) document.add_paragraph('输入信号下降沿', style='Intense Quote') document.add_paragraph('延迟及其波动表(均值/方差)', style='List Bullet') table = document.add_table(rows=1, cols=8) hdr_cells = table.rows[0].cells hdr_cells[0].text = "slew\\cap" for i,name in enumerate(load_cap): hdr_cells[i+1].text = str(name) for i,data in enumerate(delay_table): row_cells = table.add_row().cells row_cells[0].text = str(slew_in[i]) for j, delay in enumerate(data): miu,sigma = delay row_cells[j+1].text = "{:.1f}/{:.2f}".format(float(miu)*1e12,float(sigma)*1e12) document.add_paragraph('slew及其波动表(均值/方差)', style='List Bullet') table = document.add_table(rows=1, cols=8) hdr_cells = table.rows[0].cells hdr_cells[0].text = "slew\\cap" for i,name in enumerate(load_cap): hdr_cells[i+1].text = str(name) for i,data in enumerate(slew_table): row_cells = table.add_row().cells row_cells[0].text = str(slew_in[i]) for j, slew in enumerate(data): miu,sigma = slew row_cells[j+1].text = "{:.1f}/{:.2f}".format(float(miu)*1e12,float(sigma)*1e12) document.add_page_break() document.save('buffer_lut.docx') <file_sep>#DP+DME #### **输入**:抽象的时钟树 #### **输出**:完成buffer插入和布线的时钟树 #### **算法思路**:利用***动态规划(DP)***的思路,把时钟树buffer的插入问题分解为类似的子问题,即每两个节点的父节点合并问题。同时,这个过程是自底向上的,只有完成了当前父节点的合并,才能进行上一级的父节点合并。而对于每一个子问题,使用***DME算法***来完成节点合并。 ### **问题建模** **子问题描述**:定义该子问题的解集合$$\Gamma_p$$,其中每个解$\gamma_p$={ $S$,$M$,$D_{min}$,$D_{max}$,$C$,$P$ },代表一种合并方案。S是合并节点p的slew,M是子节点的合并style,$D_{min}$,$D_{max}$分别是合并节点p到其对应sink的最小和最大延迟,C是节点p的负载电容,P是合并方案的功耗开销。 **子问题模型:** 该子问题的解方案可以分成两类,有buffer插入的情况和没有buffer插入的情况 考虑如下情况,合并u和v得到p。其中用$\gamma_u$和$\gamma_v$表示u和v的解,用$\gamma_{u\rightarrow p}$和$\gamma_{v\rightarrow p}$表示临时解。以下s代表自定义的输入slew,$s\in \{s_0,s_1,\dots,s_n\}$,$\{s_0,s_1,\dots,s_n\}$是等差数列 1.对于没有buffer插入的情况(用$u\rightarrow p$说明): $$ S(\gamma_{u\rightarrow p})=S(\gamma_u)\\ D_{min}(\gamma_{u\rightarrow p})=D_{min}(\gamma_u)\\ D_{max}(\gamma_{u\rightarrow p})=D_{max}(\gamma_u)\\ C(\gamma_{u\rightarrow p})=C(\gamma_u)+c\times l_{pu}\\ P(\gamma_{u\rightarrow p})=P(\gamma_u) $$ 2.对于有buffer插入的情况(用$u\rightarrow p$说明): $$ S(\gamma_{u\rightarrow p})=s\\ C_b(\gamma_{u\rightarrow p})=CBuf(S(\gamma_{u\rightarrow p}),S(\gamma_u))\\ D_{min}(\gamma_{u\rightarrow p})=DBuf(S(\gamma_{u\rightarrow p}),C_b(\gamma_{u\rightarrow p}))+D_{min}(\gamma_u)\\ D_{max}(\gamma_{u\rightarrow p})=DBuf(S(\gamma_{u\rightarrow p}),C_b(\gamma_{u\rightarrow p}))+D_{max}(\gamma_u)\\ C(\gamma_{u\rightarrow p})=C_{in}+c\times d_{pb}\\ P(\gamma_{u\rightarrow p})=P(\gamma_u)+PBuf(S(\gamma_{u\rightarrow p}),C_b(\gamma_{u\rightarrow p})) $$ 对于以上两种情况,当把$\gamma_{u\rightarrow p}$和$\gamma_{v\rightarrow p}$合并时,有以下关系: $$ D_{min}(\gamma_p)=min(D_{min}(\gamma_{u\rightarrow p}),D_{min}(\gamma_{v\rightarrow p}))\\ D_{max}(\gamma_p)=max(D_{max}(\gamma_{u\rightarrow p}),D_{max}(\gamma_{v\rightarrow p}))\\ C(\gamma_p)=C(\gamma_{u\rightarrow p})+C(\gamma_{v\rightarrow p}) $$ **可能解的可行性检查**: 1.对于没有buffer插入的情况: $$ l_{pu}=d_{pu}\\ S(\gamma_{u\rightarrow p})=S(\gamma_{v\rightarrow p})=s\\ Skew(\gamma_p)=D_{max}(\gamma_p)-D_{min}(\gamma_p)\leq skewBnd $$ 2.对于有buffer插入的情况: $$ S(\gamma_{u\rightarrow p})=S(\gamma_{v\rightarrow p})=s\\ Skew(\gamma_p)=D_{max}(\gamma_p)-D_{min}(\gamma_p)\leq skewBnd\\ C_{b}(\gamma_{u\rightarrow p})\geq C(\gamma_u)\\ C_{b}(\gamma_{v\rightarrow p})\geq C(\gamma_v)\\ $$ 如果可能的解通过可行性检查,更新解方案$\gamma_p$中的所有信息,并添加到解集合$$\Gamma_p$$中。 其中$\gamma_p$剩下的的S、P、M计算如下: **S、P:** $$ S(\gamma_p)=s\\ P(\gamma_p)=P(\gamma_{u\rightarrow p})+P(\gamma_{v\rightarrow p}) $$ **M:** 对于没有buffer插入的情况,M包含$d_{pu}$和$d_{pv}$,计算如下: $$ d_{pu}=d_{pv}=L/2 $$ 其中L是u和v之间的最短曼哈顿距离 对于有buffer插入的情况,M包含$d_{bu}$、$d_{bv}、$$d_{pu}$和$d_{pv}$,计算如下: $$ d_{bu}=\frac{C_b(\gamma_{u\rightarrow p})-C(\gamma_u)}{c}\\ d_{bv}=\frac{C_b(\gamma_{v\rightarrow p})-C(\gamma_v)}{c}\\ d_{pu}=max(\frac{L-d_{bu}-d_{bv}}{2},0)+d_{bu}\\ d_{pu}=max(\frac{L-d_{bu}-d_{bv}}{2},0)+d_{bv} $$ ### **问题求解** **子问题求解思路:** 对于每一个s,控制对应的可行解的数量,记这个数量为K 在求解过程中调整等差数列的公差和K,实验并观察不同情况下时钟树的结果。 ### **复现代码** ```python # -*- coding: utf-8 -*- # @Author: mac # @Date: 2019-10-14 15:57:10 # @Last Modified by: mac # @Last Modified time: 2019-10-16 10:26:39 # 此版本中的查找表是自己定义的,没有采用DME来确定合并节点 import math from scipy import interpolate import copy import numpy as np import matplotlib.pyplot as plt # 论文中的一些自定义参数 capacitance_per_unit = 2e-6 #fF/nm buffer_input_capacitance = 10 #fF skew_bound = 200 #ps K = 6 c_max = 60 #fF #最大负载电容约束。这个论文中没提到,但是需要加上 # 定义solution类 class solution: def __init__(self,attributes,location,lvl=0,solution_type=0): self.S = attributes[0] self.M = attributes[1] self.D_min = attributes[2] self.D_max = attributes[3] self.C = attributes[4] self.P = attributes[5] self.location = location # type = 0 represents un-buffered solution # type = 1 represents buffered solution self.type = solution_type self.level = lvl self.queue = [] def add_to_queue(self,sub_solution): self.queue.append(sub_solution) # 读入ispd中的sink信息 def readSinkLocations(sink_num,slew_list=list(range(50,60,2)), file_path="s1r1.txt"): f = open(file_path, "r") bounds = f.readline().split(" ") sink_solutions = [] # skip second Line f.readline() num_sinks_in_file = int(f.readline().split(" ")[2]) for sink in range(sink_num): data = f.readline().split(" ") location = [int(data[1]), int(data[2])] a_solution = [] for s in slew_list: a_solution.append(solution(attributes=[s,[],0,0,10,0],location=[location[0], location[1]])) sink_solutions.append(a_solution) f.close() return sink_solutions #初始化CBuf查找表和插值函数 def init_cbuf(x,y): z = [[60,65,70,75,80],[55,60,65,70,75],[50,55,60,65,70],[45,50,55,60,65],[40,45,50,55,60]] f = interpolate.interp2d(x, y, z,kind='cubic') return f #初始DBuf查找表和插值函数 def init_dbuf(x,y): z = [[500,550,600,650,700],[550,600,650,700,750],[600,650,700,750,800],[650,700,750,800,850],[700,750,800,850,900]] f = interpolate.interp2d(x, y, z,kind='cubic') return f #初始化PBuf查找表和插值函数 def init_pbuf(x,y): z = [[1,2,3,4,5],[2,3,4,5,6],[3,4,5,6,7],[4,5,6,7,8],[5,6,7,8,9]] f = interpolate.interp2d(x, y, z,kind='cubic') return f #确定输入slew和负载电容的范围和步长,并初始化CBuf, DBuf, PBuf def initialize(): slew_bd = np.arange(50,100,10) #ps cap_bd = np.arange(50,100,10) #fF cbuf = init_cbuf(slew_bd,slew_bd) dbuf = init_dbuf(slew_bd,cap_bd) #ps pbuf = init_pbuf(slew_bd,cap_bd) #uW return cbuf,dbuf,pbuf #根据有buffer插入的方式生成父节点 def get_with_buffer_solution(solution_u,solution_v,slew,level,CBuf,DBuf,PBuf): length = math.sqrt((solution_u.location[0] - solution_v.location[0])**2 + (solution_u.location[1] - solution_v.location[1])**2) x = (solution_u.location[0] + solution_v.location[0])/2 y = (solution_u.location[1] + solution_v.location[1])/2 x_delta = (solution_u.location[0] - solution_v.location[0]) y_delta = (solution_u.location[1] - solution_v.location[1]) c_bu = CBuf(slew,solution_u.S) c_bv = CBuf(slew, solution_v.S) d_bu = (c_bu-solution_u.C)/capacitance_per_unit d_bv = (c_bv-solution_v.C)/capacitance_per_unit d_pb = max((length-d_bu-d_bv)/2,0) p_m = [d_bu,d_bv,d_bu+d_pb,d_bv+d_pb] p_location = [x-(d_bu-d_bv)*x_delta/(2*length), y-(d_bu-d_bv)*y_delta/(2*length)] D_bu = DBuf(slew, c_bu) D_bv = DBuf(slew, c_bv) d_min_u = D_bu + solution_u.D_min d_min_v = D_bv + solution_v.D_min d_max_u = D_bu + solution_u.D_max d_max_v = D_bv + solution_v.D_max p_D_min = min(d_min_u + d_min_v) p_D_max = max(d_max_u + d_max_v) p_C = (buffer_input_capacitance + capacitance_per_unit*d_pb) + (buffer_input_capacitance + capacitance_per_unit*d_pb) p_P = (PBuf(slew, c_bu) + solution_u.P) + (PBuf(slew, c_bv) + solution_v.P) attributes = [slew,p_m,p_D_min,p_D_max,p_C,p_P] solution_p = solution(attributes=attributes,location=p_location,lvl=level,solution_type=1) # check feasibility of solution if (solution_u.S == slew) and (solution_v.S ==slew) and ((solution_p.D_max - solution_p.D_min) <= skew_bound) and (solution_u.C <= c_bu) and (solution_v.C <= c_bv) and solution_p.C < c_max: return solution_p,True else: return solution_p,False # 根据没有buffer插入的方式生成父节点 def get_without_buffer_solution(solution_u,solution_v,slew,level): d_bu = 0 d_bv = 0 x = (solution_u.location[0] + solution_v.location[0])/2 y = (solution_u.location[1] + solution_v.location[1])/2 p_location = [x,y] half_length = math.sqrt((solution_u.location[0] - solution_v.location[0])**2 + (solution_u.location[1] - solution_v.location[1])**2)/2 p_m = [d_bu,d_bv,half_length,half_length] p_D_min = min(solution_u.D_min,solution_v.D_min) p_D_max = max(solution_u.D_max,solution_v.D_max) p_C = (solution_u.C + capacitance_per_unit*half_length) + (solution_v.C + capacitance_per_unit*half_length) p_P = solution_u.P + solution_v.P attributes = [slew,p_m,p_D_min,p_D_max,p_C,p_P] solution_p = solution(attributes=attributes,location=p_location,lvl=level,solution_type=0) # check feasibility of solution if (solution_u.S == slew) and (solution_v.S == slew) and ((solution_p.D_max - solution_p.D_min) <= skew_bound) and solution_p.C < c_max: return solution_p,True else: return solution_p,False # 根据不同slew产生所有可能的父节点solution,并挑选出top K个solution def get_father_solutions(solutions1,solutions2,level,cbuf,dbuf,pbuf): father_solutions = [] slew_list = list(range(50,80,2)) for solution1 in solutions1: for solution2 in solutions2: for slew in slew_list: father_solution,status = get_with_buffer_solution(solution1,solution2,slew,level,cbuf,dbuf,pbuf) if status == True: father_solution.add_to_queue([solution1,solution2]) father_solutions.append(father_solution) for solution1 in solutions1: for solution2 in solutions2: for slew in slew_list: father_solution,status = get_without_buffer_solution(solution1,solution2,slew,level) if status == True: father_solution.add_to_queue([solution1,solution2]) father_solutions.append(father_solution) father_solutions.sort(key=lambda x:x.P) return father_solutions[0:K] #画父节点和其子节点的连接关系 def draw_connection(solution,level): root_loc = solution.location root_type = solution.type child1_loc = solution.queue[0][0].location child2_loc = solution.queue[0][1].location plt.plot([root_loc[0],root_loc[0],child1_loc[0]],[root_loc[1],child1_loc[1],child1_loc[1]],linewidth=1,c='k') plt.plot([root_loc[0],root_loc[0],child2_loc[0]],[root_loc[1],child2_loc[1],child2_loc[1]],linewidth=1,c='k') if root_type == 1: plt.scatter(root_loc[0],root_loc[1],marker="<",c='r',s=40) else: plt.scatter(root_loc[0],root_loc[1],marker="o",c='g',s=20) if (level==1): plt.scatter(root_loc[0],root_loc[1],marker="H",c='b',s=80) # 画所有连接关系和solution的类型及位置 def draw(solution,level): total_level = 6 if level != total_level: level = level + 1 draw_connection(solution,level) draw(solution.queue[0][0],level) draw(solution.queue[0][1],level) # 主函数 def main(): sink_num = 64 # initialize lut cbuf,dbuf,pbuf=initialize() # initialize sink solution solution_sinks = readSinkLocations(sink_num=64) # final solutions sub_solution = copy.deepcopy(solution_sinks) root_solution = [] next_solutions = [] total_level = int(math.log2(sink_num)) print("initialize done") # generate all solutions for level in range(1,total_level+1): father_num = int(sink_num/2**level) next_solutions = [] if level != 1: for i in range(father_num): # get top K solutions for each pairs father_solution = get_father_solutions(sub_solution[2*i], sub_solution[2*i+1], level,cbuf,dbuf,pbuf) next_solutions.append(father_solution) else: for i in range(father_num): # get top K solutions for each pairs of sinks father_solution = get_father_solutions(solution_sinks[2*i], solution_sinks[2*i+1], level,cbuf,dbuf,pbuf) next_solutions.append(father_solution) sub_solution = next_solutions if len(next_solutions) == 1: root_solution = next_solutions[0] print("generate {}*{} solutions at {}th level".format(len(next_solutions),K,total_level - level + 1)) # select best solution combination in Top K roots = root_solution[0] print("start plotting") # create plot fig = plt.figure() ax = fig.add_subplot(1,1,1) # draw connections and solution draw(roots,level=0) # plot sinks for sink in solution_sinks: plt.scatter(sink[0].location[0],sink[0].location[1],marker='*',s=30,c='cyan') plt.show() if __name__ == '__main__': main() ``` ### **复现结果** ![Figure_1](/Users/mac/Documents/Figure_1.png)<file_sep># -*- coding: utf-8 -*- # @Author: mac # @Date: 2019-10-14 15:57:10 # @Last Modified by: <NAME> # @Last Modified time: 2019-11-06 15:31:23 import math from scipy import interpolate import copy import numpy as np import matplotlib.pyplot as plt # 论文中的一些自定义参数 capacitance_per_unit = 2e-6 #fF/nm buffer_input_capacitance = 10 #fF skew_bound = 200 #ps K = 6 c_max = 60 #fF #最大负载电容约束。这个论文中没提到,但是需要加上 # 定义solution类 class solution: def __init__(self,attributes,location,lvl=0,solution_type=0): self.S = attributes[0] self.M = attributes[1] self.D_min = attributes[2] self.D_max = attributes[3] self.C = attributes[4] self.P = attributes[5] self.location = location # type = 0 represents un-buffered solution # type = 1 represents buffered solution self.type = solution_type self.level = lvl self.queue = [] def add_to_queue(self,sub_solution): self.queue.append(sub_solution) # 读入ispd中的sink信息 def readSinkLocations(sink_num,slew_list=list(range(50,60,2)), file_path="s1r1.txt"): f = open(file_path, "r") bounds = f.readline().split(" ") sink_solutions = [] # skip second Line f.readline() num_sinks_in_file = int(f.readline().split(" ")[2]) for sink in range(sink_num): data = f.readline().split(" ") location = [int(data[1]), int(data[2])] a_solution = [] for s in slew_list: a_solution.append(solution(attributes=[s,[],0,0,10,0],location=[location[0], location[1]])) sink_solutions.append(a_solution) f.close() return sink_solutions def readntvLUT(lutfile='../../genLut/lut_fall.txt',option=0): lut_array = np.zeros((7,7)) with open(lutfile) as f: f.readline() # skip first line for i in range(7): # slew for for j in range(7): # cap for lut_array[i,j] = f.readline().split(" ")[option] return lut_array #初始化CBuf查找表和插值函数 def init_cbuf(): x = y = z = [[60,65,70,75,80],[55,60,65,70,75],[50,55,60,65,70],[45,50,55,60,65],[40,45,50,55,60]] f = interpolate.interp2d(x, y, z,kind='cubic') return f #初始DBuf查找表和插值函数 def init_dbuf(x,y): # z = [[500,550,600,650,700],[550,600,650,700,750],[600,650,700,750,800],[650,700,750,800,850],[700,750,800,850,900]] z = readntvLUT(option=0) f = interpolate.interp2d(x, y, z,kind='cubic') return f #初始化PBuf查找表和插值函数 def init_pbuf(x,y): # z = [[1,2,3,4,5],[2,3,4,5,6],[3,4,5,6,7],[4,5,6,7,8],[5,6,7,8,9]] z = readntvLUT(option=4) f = interpolate.interp2d(x, y, z,kind='cubic') return f #确定输入slew和负载电容的范围和步长,并初始化CBuf, DBuf, PBuf def initialize(): slew_bd = np.arange(50,85,5) #ps cap_bd = np.arange(15,50,5) #fF # cbuf = init_cbuf(slew_bd,slew_bd) cbuf = init_cbuf() dbuf = init_dbuf(slew_bd,cap_bd) #ps pbuf = init_pbuf(slew_bd,cap_bd) #uW return cbuf,dbuf,pbuf #根据有buffer插入的方式生成父节点 def get_with_buffer_solution(solution_u,solution_v,slew,level,CBuf,DBuf,PBuf): length = math.sqrt((solution_u.location[0] - solution_v.location[0])**2 + (solution_u.location[1] - solution_v.location[1])**2) x = (solution_u.location[0] + solution_v.location[0])/2 y = (solution_u.location[1] + solution_v.location[1])/2 x_delta = (solution_u.location[0] - solution_v.location[0]) y_delta = (solution_u.location[1] - solution_v.location[1]) c_bu = CBuf(slew,solution_u.S) c_bv = CBuf(slew, solution_v.S) d_bu = (c_bu-solution_u.C)/capacitance_per_unit d_bv = (c_bv-solution_v.C)/capacitance_per_unit d_pb = max((length-d_bu-d_bv)/2,0) p_m = [d_bu,d_bv,d_bu+d_pb,d_bv+d_pb] p_location = [x-(d_bu-d_bv)*x_delta/(2*length), y-(d_bu-d_bv)*y_delta/(2*length)] D_bu = DBuf(slew, c_bu) D_bv = DBuf(slew, c_bv) d_min_u = D_bu + solution_u.D_min d_min_v = D_bv + solution_v.D_min d_max_u = D_bu + solution_u.D_max d_max_v = D_bv + solution_v.D_max p_D_min = min(d_min_u + d_min_v) p_D_max = max(d_max_u + d_max_v) p_C = (buffer_input_capacitance + capacitance_per_unit*d_pb) + (buffer_input_capacitance + capacitance_per_unit*d_pb) p_P = (PBuf(slew, c_bu) + solution_u.P) + (PBuf(slew, c_bv) + solution_v.P) attributes = [slew,p_m,p_D_min,p_D_max,p_C,p_P] solution_p = solution(attributes=attributes,location=p_location,lvl=level,solution_type=1) # check feasibility of solution if (solution_u.S == slew) and (solution_v.S ==slew) and ((solution_p.D_max - solution_p.D_min) <= skew_bound) and (solution_u.C <= c_bu) and (solution_v.C <= c_bv) and solution_p.C < c_max: return solution_p,True else: return solution_p,False # 根据没有buffer插入的方式生成父节点 def get_without_buffer_solution(solution_u,solution_v,slew,level): d_bu = 0 d_bv = 0 x = (solution_u.location[0] + solution_v.location[0])/2 y = (solution_u.location[1] + solution_v.location[1])/2 p_location = [x,y] half_length = math.sqrt((solution_u.location[0] - solution_v.location[0])**2 + (solution_u.location[1] - solution_v.location[1])**2)/2 p_m = [d_bu,d_bv,half_length,half_length] p_D_min = min(solution_u.D_min,solution_v.D_min) p_D_max = max(solution_u.D_max,solution_v.D_max) p_C = (solution_u.C + capacitance_per_unit*half_length) + (solution_v.C + capacitance_per_unit*half_length) p_P = solution_u.P + solution_v.P attributes = [slew,p_m,p_D_min,p_D_max,p_C,p_P] solution_p = solution(attributes=attributes,location=p_location,lvl=level,solution_type=0) # check feasibility of solution if (solution_u.S == slew) and (solution_v.S == slew) and ((solution_p.D_max - solution_p.D_min) <= skew_bound) and solution_p.C < c_max: return solution_p,True else: return solution_p,False # 根据不同slew产生所有可能的父节点solution,并挑选出top K个solution def get_father_solutions(solutions1,solutions2,level,cbuf,dbuf,pbuf): father_solutions = [] slew_list = list(range(50,80,2)) for solution1 in solutions1: for solution2 in solutions2: for slew in slew_list: father_solution,status = get_with_buffer_solution(solution1,solution2,slew,level,cbuf,dbuf,pbuf) if status == True: father_solution.add_to_queue([solution1,solution2]) father_solutions.append(father_solution) for solution1 in solutions1: for solution2 in solutions2: for slew in slew_list: father_solution,status = get_without_buffer_solution(solution1,solution2,slew,level) if status == True: father_solution.add_to_queue([solution1,solution2]) father_solutions.append(father_solution) father_solutions.sort(key=lambda x:x.P) return father_solutions[0:K] #画父节点和其子节点的连接关系 def draw_connection(solution,level): root_loc = solution.location root_type = solution.type child1_loc = solution.queue[0][0].location child2_loc = solution.queue[0][1].location plt.plot([root_loc[0],root_loc[0],child1_loc[0]],[root_loc[1],child1_loc[1],child1_loc[1]],linewidth=1,c='k') plt.plot([root_loc[0],root_loc[0],child2_loc[0]],[root_loc[1],child2_loc[1],child2_loc[1]],linewidth=1,c='k') if root_type == 1: plt.scatter(root_loc[0],root_loc[1],marker="<",c='r',s=40) else: plt.scatter(root_loc[0],root_loc[1],marker="o",c='g',s=20) if (level==1): plt.scatter(root_loc[0],root_loc[1],marker="H",c='b',s=80) # 画所有连接关系和solution的类型及位置 def draw(solution,level): total_level = 6 if level != total_level: level = level + 1 draw_connection(solution,level) draw(solution.queue[0][0],level) draw(solution.queue[0][1],level) # 主函数 def main(): sink_num = 64 # initialize lut cbuf,dbuf,pbuf=initialize() # initialize sink solution solution_sinks = readSinkLocations(sink_num=64) # final solutions sub_solution = copy.deepcopy(solution_sinks) root_solution = [] next_solutions = [] total_level = int(math.log2(sink_num)) print("initialize done") # generate all solutions for level in range(1,total_level+1): father_num = int(sink_num/2**level) next_solutions = [] if level != 1: for i in range(father_num): # get top K solutions for each pairs father_solution = get_father_solutions(sub_solution[2*i], sub_solution[2*i+1], level,cbuf,dbuf,pbuf) next_solutions.append(father_solution) else: for i in range(father_num): # get top K solutions for each pairs of sinks father_solution = get_father_solutions(solution_sinks[2*i], solution_sinks[2*i+1], level,cbuf,dbuf,pbuf) next_solutions.append(father_solution) sub_solution = next_solutions if len(next_solutions) == 1: root_solution = next_solutions[0] print("generate {}*{} solutions at {}th level".format(len(next_solutions),K,total_level - level + 1)) # select best solution combination in Top K roots = root_solution[0] print("start plotting") # create plot fig = plt.figure() ax = fig.add_subplot(1,1,1) # draw connections and solution draw(roots,level=0) # plot sinks for sink in solution_sinks: plt.scatter(sink[0].location[0],sink[0].location[1],marker='*',s=30,c='cyan') plt.show() if __name__ == '__main__': main() <file_sep>################################################################################################## # The script is used to generate delay & output slew look-up table(LUT) of different buffer size.# # The result will be located in "buflib" folder after execution # ################################################################################################## import numpy as np import os slew_in_list = [50,55,60,65,70,75,80] #ps cap_load_list = [15,20,25,30,35,40,45] #fF lut_rise = np.zeros((len(slew_in_list),len(cap_load_list),5),dtype=np.float32) lut_fall = np.zeros((len(slew_in_list),len(cap_load_list),5),dtype=np.float32) buffer_size_lib = {'X1':[2,1.37],'X2':[4,2.74], 'X3':[8,5.48],'X4':[16,10.96], 'X5':[32,21.92]} def get_lut(option="fall",i=0,j=0): string2 = "ngspice -o MC_buffer_{}.log ./sim_ctrl/MC_buffer_{}.sp".format(option,option) os.system(string2) result1 = np.loadtxt('delay.log',delimiter=' ',usecols=(2)).astype(np.float32) result2 = np.loadtxt( 'slew.log',delimiter=' ',usecols=(2)).astype(np.float32) result3 = np.loadtxt( 'power.log',delimiter=' ',usecols=(2)).astype(np.float32) string3 = "rm bsim4v5.out *.log" os.system(string3) if option == "fall": lut_fall[i,j,0] = np.mean(result1).astype(np.float32) #mu of delay lut_fall[i,j,1] = np.std(result1).astype(np.float32) #sigma of delay lut_fall[i,j,2] = np.mean(result2).astype(np.float32) #mu of output slew lut_fall[i,j,3] = np.std(result2).astype(np.float32) #sigma of output slew lut_fall[i,j,4] = result3.astype(np.float32) #power dissiption else: lut_rise[i,j,0] = np.mean(result1).astype(np.float32) #mu of delay lut_rise[i,j,1] = np.std(result1).astype(np.float32) #sigma of delay lut_rise[i,j,2] = np.mean(result2).astype(np.float32) #mu of output slew lut_rise[i,j,3] = np.std(result2).astype(np.float32) #sigma of output slew lut_rise[i,j,4] = result3.astype(np.float32) #power dissiption def main(): for key,value in buffer_size_lib.items(): os.system("sed -i -e 's/pmos l=45n w=[0-9]*\.?[0-9]+u/pmos l=45n w={}u/g' \ -e 's/nmos l=45n w=[0-9]*\.?[0-9]+u/nmos l=45n w={}u/g' ./spice/buffer.sp".format(value[0],value[1])) for i,slew_in in enumerate(slew_in_list): for j,cap_load in enumerate(cap_load_list): os.system("sed -i -e 's/capload = [0-9]\+fF/capload = {}fF/g' \ -e 's/slew_in = [0-9]\+ps/slew_in = {}ps/g' ./spice/buffer.sp".format(cap_load,slew_in)) get_lut("fall",i,j) get_lut("rise",i,j) os.mkdir("./buflib/{}".format(key)) with open('./buflib/{}/lut_fall.txt'.format(key),'w') as f1, open('./buflib/{}/lut_rise.txt'.format(key),'w') as f2: f1.write("delay(miu){}delay(sigma){}slew(miu){}slew(sigma){}power{}input_slew{}output_cap\n".format(' '*12,' '*12,' '*12,' '*12,' '*12,' '*12,' '*12)) f2.write("delay(miu){}delay(sigma){}slew(miu){}slew(sigma){}power{}input_slew{}output_cap\n".format(' '*12,' '*12,' '*12,' '*12,' '*12,' '*12,' '*12)) for i in range(len(slew_in_list)): for j in range(len(cap_load_list)): f1.write("{} {} {} {} {} {} {}\n".format(lut_fall[i,j,0],lut_fall[i,j,1],lut_fall[i,j,2],lut_fall[i,j,3],lut_fall[i,j,4],slew_in_list[i],cap_load_list[j])) f2.write("{} {} {} {} {} {} {}\n".format(lut_rise[i,j,0],lut_rise[i,j,1],lut_rise[i,j,2],lut_rise[i,j,3],lut_rise[i,j,4],slew_in_list[i],cap_load_list[j])) if __name__ == '__main__': main() <file_sep>import numpy as np import os slew_in_list = [50,55,60,65,70,75,80] #ps slew_out_list = [50,55,60,65,70,75,80] #ps lut_rise = np.zeros((len(slew_in_list),len(slew_out_list)),dtype=np.float32) lut_fall = np.zeros((len(slew_in_list),len(slew_out_list)),dtype=np.float32) def get_lut(slin,slout,option="fall",i=0,j=0): string1 = "sed -i -e 's/let slew_out = [0-9]\+ps/let slew_out = {}ps/g' -e 's/slew_in = [0-9]\+ps/slew_in = {}ps/g' load_cap_{}.sp".format(slout,slin,option) os.system(string1) string2 = "ngspice load_cap_{}.sp".format(option,option) os.system(string2) result = np.loadtxt('loadcap.log',delimiter=' ',usecols=(2)).astype(np.float32) string3 = "rm bsim4v5.out *.log" os.system(string3) if option == "fall": lut_fall[i,j] = float(result) else: lut_rise[i,j] = float(result) def main(): for i,slew_in in enumerate(slew_in_list): for j,slew_out in enumerate(slew_out_list): get_lut(slew_in,slew_out,"fall",i,j) get_lut(slew_in,slew_out,"rise",i,j) with open('lut_fall.txt','w') as f1, open('lut_rise.txt','w') as f2: f1.write("buffer_load(fF){}input_slew{}output_slew\n".format(' '*12,' '*12)) f2.write("buffer_load(fF){}input_slew{}output_slew\n".format(' '*12,' '*12)) for i in range(len(slew_in_list)): for j in range(len(slew_out_list)): f1.write("{} {} {}\n".format(lut_fall[i,j],slew_in_list[i],slew_out_list[j])) f2.write("{} {} {}\n".format(lut_rise[i,j],slew_in_list[i],slew_out_list[j])) if __name__ == '__main__': main() <file_sep>change the source path in both lut_fall.txt and lut_rise.txt
9c775f2b971bdc1b5c8a6d6e15966823727475f5
[ "Markdown", "Python", "Text" ]
12
Markdown
tsengs0/CTS_Paper_Reproduction
ea1c3041fceb9586d7f5772e5a0159e2ba2e0f39
54ed165855f9cff8cd236ff895a26201bd494028
refs/heads/master
<file_sep>using System; using System.Globalization; using System.Net; using System.Net.NetworkInformation; using System.Text; using System.Threading; namespace csvPing { class Program { static void Main(string[] args) { if (args.Length < 1) { Console.WriteLine("Syntax: csvPing hostname|IPAddress [OPTIONS]"); Console.WriteLine(""); Console.WriteLine(" -t=VALUE [Timeout in milliseconds, default = 5000]"); Console.WriteLine(" -i=VALUE [Ping interval in milliseconds, default = 1000]"); Console.WriteLine(" -s=VALUE [Field separator, default = ','"); Console.WriteLine(""); } else { string outputSeparator = ","; long msBetweenPings = 5000; int msTimeout = 5000; for (int x = 1; x < args.Length; x++) { if (args[x].Contains("-i=")) msBetweenPings = Convert.ToInt64(args[x].Substring(3)); if (args[x].Contains("-s=")) outputSeparator = Convert.ToString(args[x].Substring(3)); if (args[x].Contains("-t=")) msTimeout = Convert.ToInt32(args[x].Substring(3)); } long respTime = 0; PingStats ps = new PingStats(Convert.ToDouble(msTimeout)); Console.WriteLine("Host" + outputSeparator + "LocalTime" + outputSeparator + "PingResponseTime" + outputSeparator + "Minimum" + outputSeparator + "Maximum" + outputSeparator + "Average" + outputSeparator + "TimeoutCount_" + msTimeout + "ms"); while (true) { respTime = PingHost(args[0], msTimeout); ps.Add(respTime); string rightNow = string.Format("{0:u}", DateTime.Now); Console.WriteLine(args[0] + outputSeparator + rightNow + outputSeparator + respTime.ToString("F0", CultureInfo.InvariantCulture) + outputSeparator + ps.Min.ToString("F0", CultureInfo.InvariantCulture) + outputSeparator + ps.Max.ToString("F0", CultureInfo.InvariantCulture) + outputSeparator + ps.Mean.ToString("F3", CultureInfo.InvariantCulture) + outputSeparator + ps.TimeoutCount.ToString("F0", CultureInfo.InvariantCulture)); Thread.Sleep(Convert.ToInt16(msBetweenPings)); } } } public static long PingHost(string nameOrAddress, int timeout) { bool pingable = false; Ping pinger = null; long responseTime = 0; PingOptions options = new PingOptions(); options.DontFragment = true; options.Ttl = 300; try { pinger = new Ping(); string data = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; byte[] buffer = Encoding.ASCII.GetBytes(data); PingReply reply = pinger.Send(nameOrAddress, timeout, buffer, options); responseTime = reply.RoundtripTime; pingable = reply.Status == IPStatus.Success; if (!pingable) { responseTime = 5000; } } catch (PingException) { responseTime = 5000; } finally { if (pinger != null) { pinger.Dispose(); } } return responseTime; } } class PingStats { public PingStats(double timeoutValue) { m_Count = 0; m_Sum = 0; m_Min = 1000000.0; m_Max = 0; m_Sum = 0; m_Mean = 0; m_TimeoutCount = 0; m_Timeout = timeoutValue; } private double m_Count; private double m_Sum; private double m_Min; private double m_Max; private double m_Mean; private double m_Timeout; private double m_TimeoutCount; public double Min { get => m_Min; } public double Max { get => m_Max; } public double Mean { get => m_Mean; } public double TimeoutCount { get => m_TimeoutCount; } public void Add(double pingTime) { if (pingTime < m_Timeout) { m_Count++; m_Sum += pingTime; m_Mean = m_Sum / m_Count; if (pingTime < m_Min) m_Min = pingTime; if (pingTime > m_Max) m_Max = pingTime; } else { m_TimeoutCount++; } } } }<file_sep>csvPing - Extended Ping Application for CSV Storage and Analysis .NET Core 2.1 Console Application Usage: csvPing hostname|IPAddress [OPTIONS] [OPTIONS] -t=VALUE [Timeout in milliseconds, default = 5000 -i=VALUE [Ping interval in milliseconds, default = 1000 -s=VALUE [Field separator, default = ','
4d15483de655287c5478246254bcf9ec607c1d10
[ "Markdown", "C#" ]
2
C#
bhollenStats/csvPing
51d9363ad29170fc158f8c80e4c1495d28316b83
830d6e1a32a39c13b18315e8a577bc7398b48533
refs/heads/master
<file_sep>package org.xson.common.object; public class XCOArrayField implements IField { private static final long serialVersionUID = 4848636595224033221L; protected String name; private XCO[] value; public XCOArrayField(String name, XCO[] value) { this.name = name; this.value = value; } @Override public Object getValue() { return value; } @Override public Object getValue(int dataType) { if (dataType == XCO_ARRAY_TYPE) { return value; } throw new XCOException("Type mismatch for field: " + this.name); } @Override public void toXMLString(StringBuilder builder) { builder.append("<XA " + DataType.PROPERTY_K + "=\"" + this.name + "\">"); for (int i = 0, length = value.length; i < length; i++) { value[i].toXMLString(null, builder); } builder.append("</XA>"); } @Override public void toJSONString(StringBuilder builder) { builder.append("\"").append(this.name).append("\"").append(":").append("["); for (int i = 0; i < this.value.length; i++) { if (i > 0) { builder.append(","); } builder.append(this.value[i].toJSON()); } builder.append("]"); } @Override public IField cloneSelf() { XCO[] array = new XCO[this.value.length]; for (int i = 0; i < this.value.length; i++) { array[i] = this.value[i].clone(); } return new XCOArrayField(name, array); } } <file_sep>package org.xson.common.object; import java.math.BigInteger; public class BigIntegerField implements IField { private static final long serialVersionUID = 4848636595224033221L; protected String name; private BigInteger value; public BigIntegerField(String name, BigInteger value) { this.name = name; this.value = value; } @Override public Object getValue() { return value; } @Override public Object getValue(int dataType) { if (dataType == BIGINTEGER_TYPE) { return value; } throw new XCOException("Type mismatch for field: " + this.name); } @Override public void toXMLString(StringBuilder builder) { builder.append("<K " + PROPERTY_K + "=\""); builder.append(this.name); builder.append("\" " + PROPERTY_V + "=\""); builder.append(this.value.toString()); builder.append("\"/>"); } @Override public void toJSONString(StringBuilder builder) { // builder.append("\"").append(this.name).append("\"").append(":").append(this.value.toString()); builder.append("\"").append(this.name).append("\"").append(":\"").append(this.value.toString()).append("\""); } @Override public IField cloneSelf() { return new BigIntegerField(name, new BigInteger(value.toString())); } } <file_sep>package test.xson.common.object; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import org.junit.Test; import org.xson.common.object.XCO; public class AppTest { @Test public void test01() { XCO xco = new XCO(); xco.setIntegerValue("a", 2); int[] intarray = { 1, 2, 3, 3333 }; xco.setIntegerArrayValue("intarray", intarray); XCO xco2 = new XCO(); xco2.setStringValue("b", "hello"); xco.setXCOValue("xx", xco2); System.out.println(xco.toXMLString()); String xml = xco.toXMLString(); XCO xco1 = XCO.fromXML(xml); System.out.println(xco1.toXMLString()); } @Test public void test02() { XCO xco = new XCO(); XCO[] array = new XCO[2]; array[0] = new XCO(); array[1] = new XCO(); array[0].setIntegerValue("i", 1); array[1].setStringValue("x", "b"); xco.setXCOArrayValue("array", array); String xml = xco.toXMLString(); System.out.println(xml); XCO xco1 = XCO.fromXML(xml); System.out.println(xco1.toXMLString()); } @Test public void test03() { XCO xco = new XCO(); XCO[] array = new XCO[2]; array[0] = new XCO(); array[1] = new XCO(); array[0].setIntegerValue("i", 1); array[1].setStringValue("x", "b"); List<XCO> list = new ArrayList<XCO>(); list.add(array[0]); list.add(array[1]); // xco.setXCOArrayValue("array", array); xco.setXCOListValue("list", list); String xml = xco.toXMLString(); System.out.println(xml); XCO xco1 = XCO.fromXML(xml); System.out.println(xco1.toXMLString()); } @Test public void test04() { XCO xco = new XCO(); XCO[] array = new XCO[2]; array[0] = new XCO(); array[1] = new XCO(); array[0].setIntegerValue("i", 1); array[1].setStringValue("x", "a>bc\"cc"); Set<XCO> set = new HashSet<XCO>(); set.add(array[0]); set.add(array[1]); // xco.setXCOArrayValue("array", array); xco.setXCOSetValue("set", set); String xml = xco.toXMLString(); System.out.println(xml); XCO xco1 = XCO.fromXML(xml); System.out.println(xco1.toXMLString()); } @Test public void test05() { XCO xco = new XCO(); xco.setStringValue("s", "a>bc\"cc"); String xml = xco.toXMLString(); System.out.println(xml); System.out.println(xco.toJSON()); XCO xco1 = XCO.fromXML(xml); System.out.println(xco1.toXMLString()); System.out.println(xco1.getStringValue("s")); } @Test public void test06() { XCO xco = new XCO(); xco.setStringValue("a", "av"); xco.setStringValue("a", null); XCO xco1 = new XCO(); xco1.setStringValue("b", "bv"); XCO xco2 = new XCO(); xco2.setStringValue("c", "cv"); XCO[] array = new XCO[2]; array[0] = new XCO(); array[1] = new XCO(); array[0].setIntegerValue("i", 1); array[1].setStringValue("x", "acc"); Set<XCO> set = new HashSet<XCO>(); set.add(array[0]); set.add(array[1]); List<XCO> list = new ArrayList<XCO>(); list.add(array[0]); list.add(array[1]); xco.setXCOValue("xco1", xco1); xco.setXCOSetValue("set", set); xco1.setXCOValue("xco2", xco2); xco1.setXCOArrayValue("array", array); xco2.setXCOListValue("list", list); System.out.println(xco); System.out.println(xco.get("xco1.xco2.c")); System.out.println(xco.get("set")); System.out.println(xco.get("set[0]")); System.out.println(xco.get("set[1]")); System.out.println(xco.get("xco1.array[1].x")); } @Test public void test07() { XCO xco = new XCO(); xco.setStringValue("a", "中国"); xco.setStringValue("b", "日本"); System.out.println(xco); XCO xco1 = new XCO(); xco1.setStringValue("a", "英国"); xco1.setStringValue("d", "美国"); xco1.setStringValue("e", "韩国"); System.out.println(xco1); // xco.append(xco1); // System.out.println(xco); xco1.append(xco); System.out.println(xco1); } @Test public void test08() { XCO xco = new XCO(); xco.setStringValue("www.baidu.com", "中国"); XCO xco1 = new XCO(); xco1.setStringValue("name", "日本"); xco.setXCOValue("x", xco1); System.out.println(xco); System.out.println(xco.get("www.baidu.com")); System.out.println(xco.get("x.name")); System.out.println(xco.get("wwww")); } @Test public void test09() { XCO xco = new XCO(); xco.setStringValue("name", "日本"); xco.setStringValue("name1", "日本"); xco.setStringValue("name2", "日本"); xco.setStringValue("name3", "日本"); String[] filters = { "name*" }; String xml = xco.toXMLString(filters); System.out.println(xml); } @Test public void testAll() { test01(); test02(); test03(); test04(); test05(); test06(); test07(); test08(); test09(); } } <file_sep>package org.xson.common.object; public class XCOException extends RuntimeException { private static final long serialVersionUID = 1L; public XCOException() { super(); } public XCOException(String message) { super(message); } public XCOException(String message, Throwable cause) { super(message, cause); } public XCOException(Throwable cause) { super(cause); } } <file_sep>package org.xson.common.object; import java.io.Serializable; public interface DataType extends Serializable { int BYTE_TYPE = 1; // B int SHORT_TYPE = 2; // H int INT_TYPE = 3; // I int LONG_TYPE = 4; // L int FLOAT_TYPE = 5; // F int DOUBLE_TYPE = 6; // D int CHAR_TYPE = 7; // C int BOOLEAN_TYPE = 8; // O int STRING_TYPE = 9; // S int XCO_TYPE = 10; // X int DATE_TYPE = 11; // A int SQLDATE_TYPE = 12; // E int SQLTIME_TYPE = 13; // G int TIMESTAMP_TYPE = 14; // J int BIGINTEGER_TYPE = 15; // K int BIGDICIMAL_TYPE = 16; // M int BYTE_ARRAY_TYPE = 21; // BA int SHORT_ARRAY_TYPE = 22; int INT_ARRAY_TYPE = 23; int LONG_ARRAY_TYPE = 24; int FLOAT_ARRAY_TYPE = 25; int DOUBLE_ARRAY_TYPE = 26; int CHAR_ARRAY_TYPE = 27; int BOOLEAN_ARRAY_TYPE = 28; int STRING_ARRAY_TYPE = 29; int XCO_ARRAY_TYPE = 30; int DATE_ARRAY_TYPE = 31; int SQLDATE_ARRAY_TYPE = 32; int SQLTIME_ARRAY_TYPE = 33; int TIMESTAMP_ARRAY_TYPE = 34; int BYTE_LIST_TYPE = 41; // BL int SHORT_LIST_TYPE = 42; int INT_LIST_TYPE = 43; int LONG_LIST_TYPE = 44; int FLOAT_LIST_TYPE = 45; int DOUBLE_LIST_TYPE = 46; int CHAR_LIST_TYPE = 47; int BOOLEAN_LIST_TYPE = 48; int STRING_LIST_TYPE = 49; int XCO_LIST_TYPE = 50; int DATE_LIST_TYPE = 51; int SQLDATE_LIST_TYPE = 52; int SQLTIME_LIST_TYPE = 53; int TIMESTAMP_LIST_TYPE = 54; int BYTE_SET_TYPE = 61; // BS int SHORT_SET_TYPE = 62; int INT_SET_TYPE = 63; int LONG_SET_TYPE = 64; int FLOAT_SET_TYPE = 65; int DOUBLE_SET_TYPE = 66; int CHAR_SET_TYPE = 67; int BOOLEAN_SET_TYPE = 68; int STRING_SET_TYPE = 69; int XCO_SET_TYPE = 70; int DATE_SET_TYPE = 71; int SQLDATE_SET_TYPE = 72; int SQLTIME_SET_TYPE = 73; int TIMESTAMP_SET_TYPE = 74; // List, Set String PROPERTY_K = "K"; String PROPERTY_V = "V"; String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; String DATE_FORMAT = "yyyy-MM-dd"; String TIME_FORMAT = "HH:mm:ss"; // public static final SimpleDateFormat DATETIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); // public static final SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HH:mm:ss"); } <file_sep>package org.xson.common.object; import java.sql.Timestamp; public class TimestampField implements IField { private static final long serialVersionUID = 4848636595224033221L; protected String name; private Timestamp value; public TimestampField(String name, Timestamp value) { this.name = name; this.value = value; } @Override public Object getValue() { return value; } @Override public Object getValue(int dataType) { if (dataType == TIMESTAMP_TYPE) { return value; } if (dataType == STRING_TYPE) { return XCOUtil.getTimestampString(value); } throw new XCOException("Type mismatch for field: " + this.name); } @Override public void toXMLString(StringBuilder builder) { builder.append("<J " + PROPERTY_K + "=\""); builder.append(this.name); builder.append("\" " + PROPERTY_V + "=\""); builder.append(XCOUtil.getTimestampString(this.value)); builder.append("\"/>"); } @Override public void toJSONString(StringBuilder builder) { builder.append("\"").append(this.name).append("\"").append(":\"").append(XCOUtil.getTimestampString(this.value)).append("\""); } @Override public IField cloneSelf() { return new TimestampField(name, new java.sql.Timestamp(this.value.getTime())); } } <file_sep>package org.xson.common.object; import org.xson.core.WriterModel; import org.xson.core.serializer.DefaultSerializer; public class XCOSerializer extends DefaultSerializer { public final static XCOSerializer instance = new XCOSerializer(); @Override public void write(Object target, WriterModel model) { // model.appendCreateUserObject(target.getClass()); // fix bug model.appendCreateObject(target.getClass()); XCO xco = (XCO) target; for (String key : xco.keysList()) { model.writeObject(key); model.writeObject(xco.getObjectValue(key)); } model.writeEnd(); } } <file_sep>package org.xson.common.object; import java.math.BigDecimal; public class BigDecimalField implements IField { private static final long serialVersionUID = 4848636595224033221L; protected String name; private BigDecimal value; public BigDecimalField(String name, BigDecimal value) { this.name = name; this.value = value; } @Override public Object getValue() { return value; } @Override public Object getValue(int dataType) { if (dataType == BIGDICIMAL_TYPE) { return value; } throw new XCOException("Type mismatch for field: " + this.name); } @Override public void toXMLString(StringBuilder builder) { builder.append("<M " + PROPERTY_K + "=\""); builder.append(this.name); builder.append("\" " + PROPERTY_V + "=\""); builder.append(this.value.toString()); builder.append("\"/>"); } @Override public void toJSONString(StringBuilder builder) { // builder.append("\"").append(this.name).append("\"").append(":").append(this.value.toString()); builder.append("\"").append(this.name).append("\"").append(":\"").append(this.value.toString()).append("\""); } @Override public IField cloneSelf() { return new BigDecimalField(name, new BigDecimal(value.toString())); } } <file_sep># XCO ------ ### 1. XCO简介 XCO(XSON common object)是一种通用的数据对象, 底层采用一种类似Map的数据结构进行数据的存储访问, 能够方便的以XML和Byte[]的方式对数据对象进行序列化和反序列化,适合同构、异构系统之间的数据传输和交换。 ### 2. XCO生态圈 ![XCO生态圈](images/xco-ecology.png) 1. xco-java:XCO Java版本; 2. xco-js:XCO JavaScript版本,具体请参考<http://xson.org/project/xco-js/> 3. xco-c :XCO C语言版本; ### 3. 支持的数据类型 01. 8种基本类型(byte, boolean, short, int, long, float, double, char)和其包装类型 02. 8种基本类型数组 03. String 04. String数组 05. String集合 06. java.util.Date 07. java.sql.Date 08. java.sql.Time 09. java.sql.Timestamp 10. BigInteger 11. BigDecimal 12. XCO 13. XCO数组 14. XCO集合 ### 4. 版本maven使用 当前最新版本:1.0.4 > maven中使用 <dependency> <groupId>org.xson</groupId> <artifactId>common-object</artifactId> <version>1.0.4</version> </dependency> ### 5. 更新说明 > 1.0.4 1. 调整取值策略,先整体取值,后OGNL取值 > 1.0.3版本 1. 增加append方法 > 1.0.2版本 1. 支持Ognl表达式取值 2. 增加getValue相关方法 3. 增加remove方法 4. 增加byte[]相关的序列化和反序列化操作 5. 增加getData方法 ### 6. 常用方法 > a. 赋值 public final void setIntegerValue(String field, int var) 设置一个int类型的值, field为key public final void setStringValue(String field, String var) 设置一个String类型的值, field为key //setXxx > b. 取值 public final int getIntegerValue(String field) 获取一个int类型的值, field为key public final String getStringValue(String field) 获取一个String类型的值, field为key //getXxx > c. 序列化 public String toXMLString() 把XCO对象以XML方式进行序列化 public static XCO fromXML(String xml) 从一个XML字符串反序列化为XCO对象 public String toJSON() 把XCO对象以JSON方式进行序列化 public byte[] toBytes() { 把XCO对象以byte[]方式进行序列化 public byte[] toBytes(int offsetLength) 把XCO对象以byte[]方式进行序列化,并保留偏移内容 public static XCO fromBytes(byte[] buffer) 从byte[]反序列化为XCO对象 public static XCO fromBytes(byte[] buffer, int offsetLength) 从byte[]的指定偏移长度开始,反序列化为XCO对象 ### 7. 整合XSON XCO对象的`toBytes`和`fromBytes`方法需要`XSON`框架支持,具体的使用操作如下: > a. 添加Maven依赖 <dependency> <groupId>org.xson</groupId> <artifactId>xson</artifactId> <version>1.0.2</version> </dependency> > b. 编辑xson.properties配置文件 # Support for XCO xco=true **提示** 关于`XSON`具体可参考<http://xson.org/project/xson/1.0.2/> ### 7. 使用示例 XCO xco = new XCO(); // 设置基本类型 xco.setByteValue("byteVal", (byte) 3); xco.setBooleanValue("booleanVal", true); xco.setShortValue("shortVal", (short) 5); xco.setIntegerValue("intVal", 2); xco.setLongValue("longVal", 2L); xco.setFloatValue("floatVal", 2.0F); xco.setDoubleValue("doubleVal", -0.3D); xco.setCharValue("charVal", 'x'); // 设置对象类型 xco.setStringValue("stringVal", "hello world"); xco.setDateTimeValue("dateTimeVal", new java.util.Date()); xco.setDateValue("dateVal", new java.sql.Date(System.currentTimeMillis())); xco.setTimeValue("TimeVal", new java.sql.Time(System.currentTimeMillis())); xco.setBigIntegerValue("bigIntegerVal", new BigInteger("1380000")); xco.setBigDecimalValue("bigDecimal", new BigDecimal("1380000.9999")); xco.setXCOValue("xcoVal", new XCO()); // 设置数组 xco.setIntegerArrayValue("intArray", new int[] { 1, 3, 5, 8 }); xco.setStringArrayValue("stringArray", new String[] { "aa", "bb", "cc" }); // 设置集合 List<String> list = new ArrayList<String>(); xco.setStringListValue("stringList", list); Set<String> set = new TreeSet<String>(); xco.setStringSetValue("stringSet", set); // 序列化为XML字符串 String xml = xco.toXMLString(); // 从XML字符串反序列化 XCO newXco = XCO.fromXML(xml); // 序列化为byte[] byte[] buffer = xco.toBytes(); // 从byte[]反序列化 XCO newXco1 = XCO.fromBytes(buffer); // 取值 byte byteVal = xco.getByteValue("byteVal"); boolean booleanVal = xco.getBooleanValue("booleanVal"); short shortVal = xco.getShortValue("shortVal"); int intVal = xco.getIntegerValue("intVal"); long longVal = xco.getLongValue("longVal"); float floatVal = xco.getFloatValue("floatVal"); double doubleVal = xco.getDoubleValue("doubleVal"); String stringVal = xco.getStringValue("stringVal"); XCO xcoVal = xco.getXCOValue("xcoVal"); ### 8. XML表示 上面使用示例中的XCO对象`xco`的XML表示如下: <?xml version="1.0" encoding="UTF-8"?> <X> <B K="byteVal" V="3"/> <O K="booleanVal" V="true"/> <H K="shortVal" V="5"/> <I K="intVal" V="2"/> <L K="longVal" V="2"/> <F K="floatVal" V="2.0"/> <D K="doubleVal" V="-0.3"/> <C K="charVal" V="x"/> <S K="stringVal" V="hello world"/> <A K="dateTimeVal" V="2016-09-02 16:58:25"/> <E K="dateVal" V="2016-09-02"/> <G K="TimeVal" V="16:58:25"/> <K K="bigIntegerVal" V="1380000"/> <M K="bigDecimal" V="1380000.9999"/> <X K="xcoVal"/> <IA K="intArray" V="1,3,5,8"/> <SA K="stringArray"> <S V="aa"/> <S V="bb"/> <S V="cc"/> </SA> <SL K="stringList"/> <SS K="stringSet"/> </X> > 说明 a. 以此为例:<H K="shortVal" V="5"/> H: 数据类型标识,当前标示short类型 K: key V: 具体数值 b. 数据类型标识说明 B: byte H: short I: int L: Long F: float D: double C: char O: boolean S: String X: xco A: date E: sql.date G: sql.time J: sql.timestamp K: bigInteger M: bigDecimal .. 其他详见:org.xson.common.object.DataType ### 9. 类图 ![XCO设计图](images/xco.png) > 类说明: 暂略. ### 10. 源码 <https://github.com/xsonorg/xco> <file_sep>package org.xson.common.object; import java.util.ArrayList; import java.util.List; public class ShortArrayField implements IField { private static final long serialVersionUID = 4848636595224033221L; protected String name; private short[] value; public ShortArrayField(String name, short[] value) { this.name = name; this.value = value; } @Override public Object getValue() { return value; } @Override public Object getValue(int dataType) { if (dataType == SHORT_ARRAY_TYPE) { return value; } throw new XCOException("Type mismatch for field: " + this.name); } @Override public void toXMLString(StringBuilder builder) { builder.append("<HA " + PROPERTY_K + "=\""); builder.append(this.name); builder.append("\" " + PROPERTY_V + "=\""); builder.append(arrayToString(this.value)); builder.append("\"/>"); } private String arrayToString(short[] a) { StringBuilder b = new StringBuilder(); for (int i = 0, length = a.length; i < length; i++) { if (i > 0) { b.append(","); } b.append(a[i]); } return b.toString(); } protected void setValue(String var) { if (null == var) { return; } List<String> list = new ArrayList<String>(); StringBuilder builder = new StringBuilder(); char[] src = var.toCharArray(); for (int i = 0; i < src.length; i++) { char key = src[i]; switch (key) { case ',': if (builder.length() > 0) { list.add(builder.toString()); builder = new StringBuilder(); } break; default: builder.append(key); break; } } if (builder.length() > 0) { list.add(builder.toString()); } int size = list.size(); value = new short[size]; for (int i = 0; i < size; i++) { value[i] = Short.parseShort(list.get(i)); } } @Override public void toJSONString(StringBuilder builder) { builder.append("\"").append(this.name).append("\"").append(":").append("["); for (int i = 0; i < this.value.length; i++) { if (i > 0) { builder.append(","); } builder.append(this.value[i]); } builder.append("]"); } @Override public IField cloneSelf() { return new ShortArrayField(name, value.clone()); } } <file_sep>package org.xson.common.object; import org.xson.core.XsonReader; import org.xson.core.XsonWriter; public class XCOForXSON { public static Class<?> getXCOClass() { return XCO.class; } public static XsonWriter getSerializer() { return new XCOSerializer(); } public static XsonReader getDeserializer() { return new XCODeserializer(); } }
70bfd289cae8c51a77bf6b633b1b33d73ab8f294
[ "Markdown", "Java" ]
11
Java
xsonorg/xco
cb427a21d6c319b55dfc65f49ca87fa3a54c763f
8db3c52de935b968d2e17ca84585cf1b3f83e97b
refs/heads/master
<repo_name>MarkBatchelder/footbag-united<file_sep>/table-moves-content.php <?php /** * The default template for displaying content * * Used for both single and index/archive/search. * * @package WordPress * @subpackage Twenty_Fourteen * @since Twenty Fourteen 1.0 */ ?> <tr id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <td class="move-header"> <?php if ( in_array( 'category', get_object_taxonomies( get_post_type() ) ) && twentyfourteen_categorized_blog() ) : ?> <div class="entry-meta"> <span class="cat-links"><?php echo get_the_category_list( _x( ', ', 'Used between list items, there is a space after the comma.', 'twentyfourteen' ) ); ?></span> </div> <?php endif; if ( is_single() ) : the_title( '<h2 class="move-title">', '</h2>' ); else : the_title( '<h2 class="move-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h2>' ); endif; ?> <?php if(get_field('technical_name')) { echo '<h3 class="move-subtitle">' . get_field('technical_name') . '</h3>'; } ?> <?php echo get_the_term_list( $post->ID, 'move_type', '<div class="move-type">', ', ', '</div>' ); ?> </td> <td class="move-basics"> <?php echo get_the_term_list( $post->ID, 'move_difficulty', '<div class="difficulty">', '', '</div>' ); ?> <div class="adds"><?php the_field('adds'); ?></div> </td> <td class="move-details"> <?php if(get_field('jobs_notation')) { echo '<pre class="notation1" title="Jobs Notation">' . get_field('jobs_notation') . '</pre>'; } if(get_field('jobs_notation_2')) { echo '<pre class="notation2" title="Another Jobs Notation">' . get_field('jobs_notation_2') . '</pre>'; } ?> <?php if(get_field('description')) { echo '<p class="description">' . get_field('description') . '</p>'; } if(get_field('example')) { echo '<p class="example"><strong>Example:</strong> ' . get_field('example') . '</p>'; } ?> </td> <td class="move-video"> <?php if ( 'post' == get_post_type() ) twentyfourteen_posted_on(); if ( ! post_password_required() && ( comments_open() || get_comments_number() ) ) : ?> <span class="move-video-link"><?php comments_popup_link( __( 'Post a Video', 'twentyfourteen' ), __( '1 Video', 'twentyfourteen' ), __( '% Videos', 'twentyfourteen' ) ); ?></span> <?php endif; ?> <?php twentyfourteen_post_thumbnail(); ?> </td> </tr><!-- #post-## --> <file_sep>/functions.php <?php /** * Twenty Fourteen Footbag functions and definitions. * * @link https://developer.wordpress.org/themes/basics/theme-functions/ * * @package Twenty Fourteen Footbag */ /** * This enqueues the parent and child theme stylesheets. * * @link https://codex.wordpress.org/Child_Themes */ function theme_enqueue_styles() { $parent_style = 'parent-style'; wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( $parent_style ) ); } add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' ); /** * Enqueue fonts. * * @link http://www.wpbeginner.com/wp-themes/how-add-google-web-fonts-wordpress-themes/ */ function footbag_fonts() { wp_enqueue_style( 'footbag_fonts', 'https://fonts.googleapis.com/css?family=Acme', false ); } add_action('wp_enqueue_scripts', 'footbag_fonts'); /** * Set up the content width value based on the theme's design. * * @see twentyfourteen_content_width() * * @since Twenty Fourteen 1.0 */ if ( ! isset( $content_width ) ) { $content_width = 750; } /** * @desc Set posts per page for custom post types and taxonomies */ function twentyfourteen_custom_posts_per_page($query) { if (!$query->is_main_query()) return $query; elseif ($query->is_post_type_archive('moves') || $query->is_tax('move_difficulty')) $query->set('posts_per_page', '100'); elseif ($query->is_post_type_archive('moves') || $query->is_tax('move_type')) $query->set('posts_per_page', '100'); $query->set('orderby', 'title'); $query->set('order', 'ASC'); return $query; } // Apply pre_get_posts filter - ensure this is not called when in admin if (!is_admin()) { add_filter('pre_get_posts', 'twentyfourteen_custom_posts_per_page'); }
aae51f17288ee28f50bb0399fac7a9b46ecba49b
[ "PHP" ]
2
PHP
MarkBatchelder/footbag-united
b76d851cc8f742097f95dae42693c01559c6e950
65d806b469eb6bd3e102febc76d31381f0dc1f91
refs/heads/master
<file_sep>package importre.intellij.android.selector.color; import javax.swing.*; import java.awt.*; public class ColorItemRenderer implements ListCellRenderer { DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer(); @Override public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Icon icon; String name; JLabel renderer = (JLabel) defaultRenderer .getListCellRendererComponent( list, value, index, isSelected, cellHasFocus); String values[] = (String[]) value; name = values[1]; icon = new ColorIcon(values[0]); renderer.setIcon(icon); renderer.setText(name); return renderer; } } <file_sep>[![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-android--selector--intellij--plugin-green.svg?style=flat)](https://android-arsenal.com/details/1/2342) # android-selector-intellij-plugin ![icon](src/icons/[email protected]) :art: Generate selectors for background drawable. You can use `colorButtonNormal` simply, but make easily touch feedback of normal `View`s as well as `Button`s with this plugin. ## Installation 1. open Android Studio(or IntelliJ) 2. Preferences :arrow_right: Plugins :arrow_right: Browse Repositories 3. Search "Android Selector" 4. Click "Install Plugin" button ## Usage - Set your colors(in `res/values/colors.xml`). ```xml <color name="colorPrimary">#519FE5</color> <color name="colorPrimaryDark">#388AC6</color> <color name="colorAccent">#FFFFFF</color> ``` - Select `New -> Android Selector(or Ctrl/Cmd + N)` on your `res` directory. ![screenshot1](images/screenshot1.png) - Select filename, color, pressed and pressed-v21 respectively. ![screenshot2](images/screenshot2.png) > ripple drawable is generated in drawable-v21 directory. > normal drawable is generated in drawable directory. - Use the drawable. ```xml <android.support.v7.widget.AppCompatButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="16dp" android:background="@drawable/<GENERATED_DRAWABLE>" android:gravity="center" android:minWidth="100dp" android:text="pressed" /> ``` ## Demo | Lollipop &gt; | Lollipop &lt;= | |---------------|----------------| | ![demo1][d1] | ![demo2][d2] | ## Dependency - com.android.support:appcompat-v7:22.+ ## License MIT © [<NAME>][importre] [importre]: http://import.re [d1]: images/demo1.png [d2]: images/demo2.png <file_sep>package importre.intellij.android.selector.form; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.vfs.VirtualFile; import importre.intellij.android.selector.color.ColorItemRenderer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import javax.swing.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathFactory; import java.io.*; import java.util.*; public class AndroidSelectorDialog extends DialogWrapper { private static final String INDENT_SPACE = "{http://xml.apache.org/xslt}indent-amount"; private static final String drawableDir = "drawable"; private static final String drawableV21Dir = "drawable-v21"; private static final String valuesColorsXml = "values/colors.xml"; private static final String localProps = "local.properties"; private static final String platformsRes = "%s/platforms/%s/data/res/values"; private static final String nsUri = "http://www.w3.org/2000/xmlns/"; private static final String androidUri = "http://schemas.android.com/apk/res/android"; private final VirtualFile dir; private final Project project; private JPanel contentPane; private JTextField filenameText; private JComboBox colorCombo; private JComboBox pressedCombo; private JComboBox pressedV21Combo; public AndroidSelectorDialog(@Nullable Project project, VirtualFile dir) { super(project); this.project = project; this.dir = dir; setTitle("Android Selector"); setResizable(false); init(); } @Override public void show() { try { if (initColors(dir)) { super.show(); } } catch (Exception e) { e.printStackTrace(); } } private boolean initColors(VirtualFile dir) { VirtualFile colorsXml = dir.findFileByRelativePath(valuesColorsXml); if (colorsXml != null && colorsXml.exists()) { HashMap<String, String> cmap = parseColorsXml(colorsXml); HashMap<String, String> andCmap = parseAndroidColorsXml(); if (cmap.isEmpty()) { String title = "Error"; String msg = "Cannot find colors in colors.xml"; showMessageDialog(title, msg); return false; } String regex = "^@(android:)?color/(.+$)"; ArrayList<String[]> elements = new ArrayList<String[]>(); for (String name : cmap.keySet()) { String color = cmap.get(name); while (color != null && color.matches(regex)) { if (color.startsWith("@color/")) { String key = color.replace("@color/", ""); color = cmap.get(key); } else if (color.startsWith("@android:color/")) { String key = color.replace("@android:color/", ""); color = andCmap.get(key); } else { // not reachable... } } if (color != null) { elements.add(new String[]{color, name}); } } ColorItemRenderer renderer = new ColorItemRenderer(); colorCombo.setRenderer(renderer); pressedCombo.setRenderer(renderer); pressedV21Combo.setRenderer(renderer); for (Object element : elements) { colorCombo.addItem(element); pressedCombo.addItem(element); pressedV21Combo.addItem(element); } return !elements.isEmpty(); } String title = "Error"; String msg = String.format("Cannot find %s", valuesColorsXml); showMessageDialog(title, msg); return false; } @NotNull private HashMap<String, String> parseColorsXml(VirtualFile colorsXml) { HashMap<String, String> map = new LinkedHashMap<String, String>(); try { NodeList colors = getColorNodes(colorsXml.getInputStream()); makeColorMap(colors, map); } catch (Exception e) { e.printStackTrace(); } return map; } private void makeColorMap(NodeList colors, HashMap<String, String> map) { for (int i = 0; i < colors.getLength(); i++) { Element node = (Element) colors.item(i); String nodeName = node.getNodeName(); if ("color".equals(nodeName) || "item".equals(nodeName)) { String name = node.getAttribute("name"); String color = node.getTextContent(); if (name != null && color != null && !map.containsKey(name)) { map.put(name, color); } } } } private NodeList getColorNodes(InputStream stream) throws Exception { XPath xPath = XPathFactory.newInstance().newXPath(); String expression = "//item[@type=\"color\"]|//color"; XPathExpression compile = xPath.compile(expression); DocumentBuilderFactory f = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = f.newDocumentBuilder(); Document doc = builder.parse(stream); return (NodeList) compile.evaluate(doc, XPathConstants.NODESET); } @NotNull private HashMap<String, String> parseAndroidColorsXml() { HashMap<String, String> map = new HashMap<String, String>(); if (project == null) return map; VirtualFile baseDir = project.getBaseDir(); VirtualFile prop = baseDir.findFileByRelativePath(localProps); if (prop == null) return map; Properties properties = new Properties(); try { properties.load(prop.getInputStream()); } catch (IOException e) { e.printStackTrace(); } String sdkDir = properties.getProperty("sdk.dir"); File file = new File(sdkDir + File.separator + "platforms"); if (!file.isDirectory()) return map; ArrayList<String> platforms = new ArrayList<String>(); Collections.addAll(platforms, file.list()); Collections.reverse(platforms); for (int i = 0, size = platforms.size(); i < size; i++) { String platform = platforms.get(i); if (platform.matches("^android-\\d+$")) continue; if (i > 3) break; String path = String.format(platformsRes, sdkDir, platform); File[] files = new File(path).listFiles(); if (files == null) continue; for (File f : files) { if (f.getName().matches("colors.*\\.xml")) { try { FileInputStream stream = new FileInputStream(f); NodeList colors = getColorNodes(stream); makeColorMap(colors, map); } catch (Exception e) { e.printStackTrace(); } } } } return map; } @Nullable @Override protected JComponent createCenterPanel() { return contentPane; } private String getColorName(JComboBox combo) { Object colorItem = combo.getSelectedItem(); try { if (colorItem instanceof Object[]) { return "@color/" + ((Object[]) (colorItem))[1]; } } catch (Exception e) { e.printStackTrace(); } return ""; } @Override protected void doOKAction() { String f = filenameText.getText(); final String filename = (f.endsWith(".xml") ? f : f + ".xml").trim(); final String color = getColorName(colorCombo); final String pressed = getColorName(pressedCombo); final String pressedV21 = getColorName(pressedV21Combo); if (!valid(filename, color, pressed, pressedV21)) { String title = "Invalidation"; String msg = "color, pressed, pressedV21 must start with `@color/`"; showMessageDialog(title, msg); return; } if (exists(filename)) { String title = "Cannot create files"; String msg = String.format(Locale.US, "`%s` already exists", filename); showMessageDialog(title, msg); return; } Application app = ApplicationManager.getApplication(); app.runWriteAction(new Runnable() { @Override public void run() { try { createDrawable(filename, color, pressed); createDrawableV21(filename, color, pressedV21); } catch (Exception e) { e.printStackTrace(); } } }); super.doOKAction(); } private boolean valid(String filename, String color, String pressed, String pressedV21) { if (filename.isEmpty() || ".xml".equals(filename)) return false; String regex = "^@color/.+"; return color.matches(regex) || pressed.matches(regex) || pressedV21.matches(regex); } private boolean exists(String filename) { String[] dirs = new String[]{drawableDir, drawableV21Dir}; for (String d : dirs) { VirtualFile f = dir.findChild(d); if (f != null && f.isDirectory()) { VirtualFile dest = f.findChild(filename); if (dest != null && dest.exists()) { return true; } } } return false; } private void createDrawable(String filename, String color, String pressed) throws Exception { VirtualFile child = dir.findChild(drawableDir); if (child == null) { child = dir.createChildDirectory(null, drawableDir); } VirtualFile newXmlFile = child.findChild(filename); if (newXmlFile != null && newXmlFile.exists()) { newXmlFile.delete(null); } newXmlFile = child.createChildData(null, filename); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); Element root = doc.createElement("selector"); root.setAttributeNS(nsUri, "xmlns:android", androidUri); doc.appendChild(root); Element item = doc.createElement("item"); item.setAttribute("android:drawable", "@drawable/abc_list_selector_disabled_holo_light"); item.setAttribute("android:state_enabled", "false"); item.setAttribute("android:state_focused", "true"); item.setAttribute("android:state_pressed", "true"); root.appendChild(item); item = doc.createElement("item"); item.setAttribute("android:drawable", "@drawable/abc_list_selector_disabled_holo_light"); item.setAttribute("android:state_enabled", "false"); item.setAttribute("android:state_focused", "true"); root.appendChild(item); item = doc.createElement("item"); item.setAttribute("android:drawable", pressed); item.setAttribute("android:state_focused", "true"); item.setAttribute("android:state_pressed", "true"); root.appendChild(item); item = doc.createElement("item"); item.setAttribute("android:drawable", pressed); item.setAttribute("android:state_focused", "false"); item.setAttribute("android:state_pressed", "true"); root.appendChild(item); item = doc.createElement("item"); item.setAttribute("android:drawable", color); root.appendChild(item); OutputStream os = newXmlFile.getOutputStream(null); PrintWriter out = new PrintWriter(os); StringWriter writer = new StringWriter(); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(INDENT_SPACE, "4"); transformer.transform(new DOMSource(doc), new StreamResult(writer)); out.println(writer.getBuffer().toString()); out.close(); } private void createDrawableV21(String filename, String color, String pressed) throws Exception { VirtualFile child = dir.findChild(drawableV21Dir); if (child == null) { child = dir.createChildDirectory(null, drawableV21Dir); } VirtualFile newXmlFile = child.findChild(filename); if (newXmlFile != null && newXmlFile.exists()) { newXmlFile.delete(null); } newXmlFile = child.createChildData(null, filename); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.newDocument(); Element root = doc.createElement("ripple"); root.setAttributeNS(nsUri, "xmlns:android", androidUri); root.setAttribute("android:color", pressed); doc.appendChild(root); Element item = doc.createElement("item"); item.setAttribute("android:drawable", color); root.appendChild(item); OutputStream os = newXmlFile.getOutputStream(null); PrintWriter out = new PrintWriter(os); StringWriter writer = new StringWriter(); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(INDENT_SPACE, "4"); transformer.transform(new DOMSource(doc), new StreamResult(writer)); out.println(writer.getBuffer().toString()); out.close(); } private void showMessageDialog(String title, String message) { Messages.showMessageDialog( project, message, title, Messages.getErrorIcon()); } }
4ba81e4cc1c59b9663c280dc19008db4ece777de
[ "Markdown", "Java" ]
3
Java
IsMarx/android-selector-intellij-plugin
16569b0225089224553f01bd35ae2993b22547fc
1e96ba5f9fee2a4c1e0c00d6669433a461c6ada9
refs/heads/master
<repo_name>spatome/my<file_sep>/src/main/java/com/spatome/applet/common/enums/StatusEnum.java package com.spatome.applet.common.enums; public enum StatusEnum { ON("开启"), OFF("关闭"), STOP("暂停"); private String text; StatusEnum(String text) { this.text = text; } public String getText() { return text; } public void setText(String text) { this.text = text; } } <file_sep>/src/main/java/com/spatome/applet/dao/ActivityZjMapper.java package com.spatome.applet.dao; import java.util.List; import com.spatome.applet.common.dao.Mapper; import com.spatome.applet.entity.ActivityZj; public interface ActivityZjMapper extends Mapper<ActivityZj> { List<ActivityZj> selectByBean(ActivityZj activityZjQuery); }<file_sep>/src/main/java/com/spatome/applet/factory/impl/ServiceFactoryImpl.java package com.spatome.applet.factory.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import com.spatome.applet.factory.ServiceFactory; import com.spatome.applet.service.DemoService; @Lazy @Service public class ServiceFactoryImpl implements ServiceFactory { @Autowired private DemoService demoServiceImpl; @Override public DemoService getDemoService() { return demoServiceImpl; } } <file_sep>/src/main/java/com/spatome/applet/controller/DemoController.java package com.spatome.applet.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.spatome.applet.vo.BaseVO; @RestController @RequestMapping("demo") public class DemoController extends BaseController { @RequestMapping(value = "test", method = RequestMethod.GET) public Object test(HttpServletRequest request, HttpServletResponse response) { BaseVO<Object> result = new BaseVO<Object>(); LOGGER.info("this is demo/test"); result.setBody("boot.demo"); return result; } @RequestMapping(value = "test1", method = RequestMethod.POST) public Object test1(HttpServletRequest request, HttpServletResponse response) { BaseVO<Object> result = new BaseVO<Object>(); LOGGER.info("this is demo/test"); result.setBody("boot.demo"); return result; } } <file_sep>/src/test/java/com/spatome/applet/App.java package com.spatome.applet; import org.apache.commons.lang3.EnumUtils; import com.spatome.applet.common.enums.StatusEnum; import com.spatome.applet.util.business.ZjUtil; public class App { public static void main(String[] args) { App app = new App(); app.test2(); } public void test1(String status){ if(status!=null && EnumUtils.isValidEnum(StatusEnum.class, status)){ System.err.println(true); }else{ System.err.println(false); } } public void test2(){ int t = 0; for (int i = 0; i < 100; i++) { boolean ret = ZjUtil.getInstance().draw(2, 1); if(ret){ t++; } } System.out.println(t); } } <file_sep>/src/main/java/com/spatome/applet/util/ExcelUtil.java //package com.hengpeng.util; // //import java.io.File; //import java.io.FileNotFoundException; //import java.io.FileOutputStream; //import java.io.IOException; //import java.io.InputStream; //import java.io.PrintStream; //import java.nio.file.Paths; //import java.text.SimpleDateFormat; //import java.util.ArrayList; //import java.util.Date; //import java.util.List; //import javax.xml.parsers.ParserConfigurationException; //import javax.xml.parsers.SAXParser; //import javax.xml.parsers.SAXParserFactory; // //import org.apache.commons.io.FileUtils; //import org.apache.commons.lang3.StringUtils; //import org.apache.poi.hssf.usermodel.HSSFDateUtil; //import org.apache.poi.openxml4j.exceptions.OpenXML4JException; //import org.apache.poi.openxml4j.opc.OPCPackage; //import org.apache.poi.openxml4j.opc.PackageAccess; //import org.apache.poi.ss.usermodel.BuiltinFormats; //import org.apache.poi.ss.usermodel.DataFormatter; //import org.apache.poi.ss.usermodel.Row; //import org.apache.poi.ss.usermodel.Sheet; //import org.apache.poi.ss.usermodel.Workbook; //import org.apache.poi.xssf.eventusermodel.ReadOnlySharedStringsTable; //import org.apache.poi.xssf.eventusermodel.XSSFReader; //import org.apache.poi.xssf.model.StylesTable; //import org.apache.poi.xssf.usermodel.XSSFCellStyle; //import org.apache.poi.xssf.usermodel.XSSFRichTextString; //import org.apache.poi.xssf.usermodel.XSSFWorkbook; //import org.xml.sax.Attributes; //import org.xml.sax.InputSource; //import org.xml.sax.SAXException; //import org.xml.sax.XMLReader; //import org.xml.sax.helpers.DefaultHandler; // ///** // * @ClassName: ExcelUtil // * @Description: xlsx文件处理 // * @author: zhangwei // * @date: 2017年9月29日 上午7:11:34 // */ //public class ExcelUtil { // // private OPCPackage xlsxPackage; // private int minColumns; // private PrintStream output; // private String sheetName; // // public ExcelUtil(OPCPackage pkg, PrintStream output, String sheetName, int minColumns) { // this.xlsxPackage = pkg; // this.output = output; // this.minColumns = minColumns; // this.sheetName = sheetName; // } // // public List<String[]> processSheet(StylesTable styles, ReadOnlySharedStringsTable strings, InputStream sheetInputStream) // throws IOException, ParserConfigurationException, SAXException { // InputSource sheetSource = new InputSource(sheetInputStream); // SAXParserFactory saxFactory = SAXParserFactory.newInstance(); // SAXParser saxParser = saxFactory.newSAXParser(); // XMLReader sheetParser = saxParser.getXMLReader(); // MyXSSFSheetHandler handler = new MyXSSFSheetHandler(styles, strings, this.minColumns, this.output); // sheetParser.setContentHandler(handler); // sheetParser.parse(sheetSource); // // return handler.getRows(); // } // // public List<String[]> process() throws IOException, OpenXML4JException, ParserConfigurationException, SAXException { // ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(this.xlsxPackage); // XSSFReader xssfReader = new XSSFReader(this.xlsxPackage); // List<String[]> list = null; // StylesTable styles = xssfReader.getStylesTable(); // XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData(); // // int index = 0; // while (iter.hasNext()) { // InputStream stream = iter.next(); // String sheetNameTemp = iter.getSheetName(); // if (this.sheetName.equals(sheetNameTemp)) { // list = processSheet(styles, strings, stream); // stream.close(); // // ++index; // } // } // return list; // } // // /*================================START 内部类=============================*/ // class MyXSSFSheetHandler extends DefaultHandler { // private StylesTable stylesTable; // private ReadOnlySharedStringsTable sharedStringsTable; // private final PrintStream output; // private final int minColumnCount; // private boolean vIsOpen; // private xssfDataType nextDataType; // private short formatIndex; // private String formatString; // private final DataFormatter formatter; // private int thisColumn = -1; // private int lastColumnNumber = -1; // private StringBuffer value; // private String[] record; // private List<String[]> rows = new ArrayList<String[]>(); // private boolean isCellNull = false; // // public MyXSSFSheetHandler(StylesTable styles, ReadOnlySharedStringsTable strings, int cols, PrintStream target) { // this.stylesTable = styles; // this.sharedStringsTable = strings; // this.minColumnCount = cols; // this.output = target; // this.value = new StringBuffer(); // this.nextDataType = xssfDataType.NUMBER; // this.formatter = new DataFormatter(); // record = new String[this.minColumnCount]; // rows.clear();// 每次读取都清空行集合 // } // // public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException { // if ("inlineStr".equals(name) || "v".equals(name)) { // vIsOpen = true; // // Clear contents cache // value.setLength(0); // } // // c => cell // else if ("c".equals(name)) { // // Get the cell reference // String r = attributes.getValue("r"); // int firstDigit = -1; // for (int c = 0; c < r.length(); ++c) { // if (Character.isDigit(r.charAt(c))) { // firstDigit = c; // break; // } // } // thisColumn = nameToColumn(r.substring(0, firstDigit)); // // // Set up defaults. // this.nextDataType = xssfDataType.NUMBER; // this.formatIndex = -1; // this.formatString = null; // String cellType = attributes.getValue("t"); // String cellStyleStr = attributes.getValue("s"); // if ("b".equals(cellType)) // nextDataType = xssfDataType.BOOL; // else if ("e".equals(cellType)) // nextDataType = xssfDataType.ERROR; // else if ("inlineStr".equals(cellType)) // nextDataType = xssfDataType.INLINESTR; // else if ("s".equals(cellType)) // nextDataType = xssfDataType.SSTINDEX; // else if ("str".equals(cellType)) // nextDataType = xssfDataType.FORMULA; // else if (cellStyleStr != null) { // // It's a number, but almost certainly one // // with a special style or format // int styleIndex = Integer.parseInt(cellStyleStr); // XSSFCellStyle style = stylesTable.getStyleAt(styleIndex); // this.formatIndex = style.getDataFormat(); // this.formatString = style.getDataFormatString(); // if (this.formatString == null) this.formatString = BuiltinFormats.getBuiltinFormat(this.formatIndex); // } // } // } // // public void endElement(String uri, String localName, String name) throws SAXException { // String thisStr = null; // // v => contents of a cell // if ("v".equals(name)) { // // Process the value contents as required. // // Do now, as characters() may be called more than once // switch (nextDataType) { // case BOOL: // char first = value.charAt(0); // thisStr = first == '0' ? "FALSE" : "TRUE"; // break; // case ERROR: // thisStr = "\"ERROR:" + value.toString() + '"'; // break; // case FORMULA: // // A formula could result in a string value, // // so always add double-quote characters. // thisStr = '"' + value.toString() + '"'; // break; // case INLINESTR: // // TODO: have seen an example of this, so it's untested. // XSSFRichTextString rtsi = new XSSFRichTextString(value.toString()); // thisStr = '"' + rtsi.toString() + '"'; // break; // case SSTINDEX: // String sstIndex = value.toString(); // try { // int idx = Integer.parseInt(sstIndex); // XSSFRichTextString rtss = new XSSFRichTextString(sharedStringsTable.getEntryAt(idx)); // //////////zw/////thisStr = '"' + rtss.toString() + '"'; // thisStr = String.valueOf(rtss); // }catch (NumberFormatException ex) { // output.println("Failed to parse SST index '" + sstIndex + "': " + ex.toString()); // } // break; // case NUMBER: // String n = value.toString(); // // 判断是否是日期格式 // if(HSSFDateUtil.isADateFormat(this.formatIndex, n)) { // Double d = Double.parseDouble(n); // Date date=HSSFDateUtil.getJavaDate(d); // thisStr=formateDateToString(date); // }else if (this.formatString != null) // thisStr = formatter.formatRawCellContents(Double.parseDouble(n), this.formatIndex, this.formatString); // else // thisStr = n; // break; // default: // thisStr = "(TODO: Unexpected type: " + nextDataType + ")"; // break; // } // // // Output after we've seen the string contents // // Emit commas for any fields that were missing on this row // if(lastColumnNumber == -1) { // lastColumnNumber = 0; // } // //判断单元格的值是否为空 // if (thisStr == null || "".equals(isCellNull)) { // isCellNull = true;// 设置单元格是否为空值 // } // record[thisColumn] = thisStr; // // Update column // if (thisColumn > -1) lastColumnNumber = thisColumn; // } else if ("row".equals(name)) { // //读到一行末尾 // // Print out any missing commas if needed // if (minColumns > 0) { // // Columns are 0 based // if (lastColumnNumber == -1) { // lastColumnNumber = 0; // } // //START 空行忽略 // boolean isBlank = true; // for (String f : record) { // if(StringUtils.isNotBlank(f)){ // isBlank = false; // break; // } // } // if(!isCellNull && !isBlank){ // rows.add(record.clone()); // isCellNull = false; // for (int i = 0; i < record.length; i++) { // record[i] = null; // } // } // //END 空行忽略 // } // lastColumnNumber = -1; // } // } // // public List<String[]> getRows() { // return rows; // } // // public void setRows(List<String[]> rows) { // this.rows = rows; // } // // public void characters(char[] ch, int start, int length) throws SAXException { // if (vIsOpen) value.append(ch, start, length); // } // // private int nameToColumn(String name) { // int column = -1; // for (int i = 0; i < name.length(); ++i) { // int c = name.charAt(i); // column = (column + 1) * 26 + c - 'A'; // } // return column; // } // // private String formateDateToString(Date date) { // SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//格式化日期 // return sdf.format(date); // } // } // // enum xssfDataType { // BOOL, ERROR, FORMULA, INLINESTR, SSTINDEX, NUMBER, // } // // /*================================END 内部类=============================*/ // // // public static List<String[]> readerExcel(String filePath, String sheetName, int minColumns) throws IOException, OpenXML4JException, ParserConfigurationException, SAXException{ // OPCPackage p = OPCPackage.open(filePath, PackageAccess.READ); // ExcelUtil excelUtil = new ExcelUtil(p, System.out, sheetName, minColumns); // List<String[]> list = excelUtil.process(); // p.close(); // // return list; // } // // public static void writeExcel(String path, String fileName, List<String[]> ssList) throws Exception { // if(ssList==null || ssList.size()<1) { // return; // } // // FileUtils.forceMkdir(new File(path)); // // String[] titleArray = ssList.get(0); // int columeCount = titleArray.length; // // Workbook workbook = null; // try { // workbook = new XSSFWorkbook(); // Sheet sheet = workbook.createSheet("Sheet1"); // // for(int i=0; i<ssList.size(); i++) { // String[] ss = ssList.get(i); // if(ss==null || ss.length==0){ // continue; // } // // Row row = sheet.createRow(i); // for (int j = 0; j < columeCount; j++) { // row.createCell(j); // } // // for(int j=0;j<ss.length;j++) { // row.getCell(j).setCellValue(ss[j]); // } // } // // //写到磁盘上 // FileOutputStream fileOutputStream = null; // try { // fileOutputStream = new FileOutputStream(Paths.get(path, fileName).toFile()); // workbook.write(fileOutputStream); // fileOutputStream.close(); // } catch (FileNotFoundException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } finally { // if(fileOutputStream!=null){ // try { // fileOutputStream.close(); // } catch (IOException e) { // } // } // } // } finally { // if(workbook!=null){ // try { // workbook.close(); // } catch (IOException e) { // } // } // } // } // // public static void main(String[] args) throws Exception { // List<String[]> list = ExcelUtil.readerExcel("D:\\file\\lianwa\\excel\\test.xlsx", "Sheet1", 10); // // for (String[] s : list) { // System.out.println(String.format("%20s%20s%20s%20s%20s%20s", s[0], s[1], s[2], s[3], s[4], s[5])); // } // } //} <file_sep>/src/main/java/com/spatome/applet/controller/TransTypeController.java package com.spatome.applet.controller; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.spatome.applet.service.TranService; import com.spatome.applet.util.SpringUtil; import lombok.extern.slf4j.Slf4j; @RestController @RequestMapping(value = "/process") @Slf4j public class TransTypeController extends BaseController { @RequestMapping(value = "{transType}", method = RequestMethod.POST) public Object process( @PathVariable String transType, @RequestParam Map<String, String> inMap, HttpServletRequest request, HttpServletResponse response ) throws Exception { log.debug("==>"+inMap); Object result = null; try { Object bean = SpringUtil.getApplicationContext().getBean("tran" + transType + "ServiceImpl"); result = ((TranService) bean).execute(inMap, request, response); } catch (Exception e) { log.error("transType{}data{}", transType, inMap); throw e; } return result; } } <file_sep>/src/main/java/com/spatome/applet/service/impl/zj/Tran10018ServiceImpl.java package com.spatome.applet.service.impl.zj; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.spatome.applet.common.constants.RedisConstants; import com.spatome.applet.entity.ActivityZj; import com.spatome.applet.service.TranService; import com.spatome.applet.service.impl.BaseService; import com.spatome.applet.util.business.ZjUtil; import com.spatome.applet.vo.BaseVO; import lombok.extern.slf4j.Slf4j; /** * 活动抓阄 * * 抓 */ @Service @Slf4j public class Tran10018ServiceImpl extends BaseService implements TranService { @Override @Transactional public Object execute(Map<String, String> request, HttpServletRequest req, HttpServletResponse res) { BaseVO<Object> result = new BaseVO<Object>(); log.debug("获取参数"); String activityId = request.get("activityId"); String userId = request.get("userId"); log.debug("检查参数"); Map<String, String> paramMap = new HashMap<String, String>(); paramMap.put("activityId", activityId); paramMap.put("userId", userId); super.checkNotEmpty(paramMap); log.debug("===========================业务处理========================="); ActivityZj record = daoFactory.getActivityZjMapper().selectByPrimaryKey(Long.valueOf(activityId)); if (record == null) { result.setCodeMessage("9999", "活动不存在"); return result; } boolean isJoin = super.stringRedisTemplate.boundSetOps(RedisConstants.APPLET_ZJ_JOIN+activityId).isMember(userId); if(isJoin){ result.setCodeMessage("9999", "您已参与,只能抽取一次!"); return result; } long totalCount = record.getTotalCount(); //总数 long totaldrawCount = record.getDrawCount(); //奖品数 long joinCount = super.stringRedisTemplate.boundSetOps(RedisConstants.APPLET_ZJ_JOIN+activityId).size(); long totalCountBalance = totalCount - joinCount; //总剩余次数 if(totalCountBalance<=0){ result.setCodeMessage("9999", "已达抽取上限!"); return result; } long drawedCount = super.stringRedisTemplate.boundSetOps(RedisConstants.APPLET_ZJ_DRAWED+activityId).size(); long drawCountBalance = totaldrawCount - drawedCount; //奖品余额 boolean isDrawed = ZjUtil.getInstance().draw(totalCountBalance, drawCountBalance); super.stringRedisTemplate.boundSetOps(RedisConstants.APPLET_ZJ_JOIN+activityId).add(userId); if(isDrawed){ super.stringRedisTemplate.boundSetOps(RedisConstants.APPLET_ZJ_DRAWED+activityId).add(userId); } result.setBody(isDrawed); return result; } } <file_sep>/src/main/java/com/spatome/applet/util/HttpUtil.java package com.spatome.applet.util; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.ParseException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import lombok.extern.slf4j.Slf4j; /** * httpClient工具 */ @Slf4j public class HttpUtil { private static volatile HttpUtil instance; private HttpUtil() { this.init(); }; public static HttpUtil getInstance() { if (instance == null) { synchronized (HttpUtil.class) { if (instance == null) { instance = new HttpUtil(); } } } return instance; } private RequestConfig requestConfig = null; private CloseableHttpClient httpClient = null; public void init() { // 设置请求和传输超时时间 requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build(); httpClient = HttpClients.createDefault(); } public String httpPost(String url, Map<String, String> maps) { log.debug("httpPost:" + maps.toString()); HttpPost post = new HttpPost(url); CloseableHttpResponse response = null; try { List<NameValuePair> params = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : maps.entrySet()) { params.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } post.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); post.setHeader("Content-type", "application/x-www-form-urlencoded"); post.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); response = httpClient.execute(post); HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toString(entity, "UTF-8"); } else { log.error("http post失败:" + url); throw new RuntimeException("http post异常:没有回应数据"); } } catch (UnsupportedEncodingException e) { log.error("编码处理异常:" + e); throw new RuntimeException("编码处理异常:" + e.getMessage()); } catch (ClientProtocolException e) { log.error("协议处理异常:" + e); throw new RuntimeException("协议处理异常:" + e.getMessage()); } catch (ParseException e) { log.error("数据格式处理异常:" + e); throw new RuntimeException("数据格式处理异常:" + e.getMessage()); } catch (IOException e) { log.error("IO异常:" + e); throw new RuntimeException("IO异常:" + e.getMessage()); } finally { if (response != null) { try { EntityUtils.consume(response.getEntity()); } catch (IOException e) { } } if (post != null) post.abort(); } }; public String httpGet(String url) { HttpGet get = new HttpGet(url); get.setConfig(requestConfig); CloseableHttpResponse response = null; try { get.setHeader("Content-type", "application/x-www-form-urlencoded"); get.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); response = httpClient.execute(get); HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toString(entity, "UTF-8"); } else { log.error("http get失败:" + url); throw new RuntimeException("http get异常:没有回应数据"); } } catch (UnsupportedEncodingException e) { log.error("编码处理异常:" + e); throw new RuntimeException("编码处理异常:" + e.getMessage()); } catch (ClientProtocolException e) { log.error("协议处理异常:" + e); throw new RuntimeException("协议处理异常:" + e.getMessage()); } catch (ParseException e) { log.error("数据格式处理异常:" + e); throw new RuntimeException("数据格式处理异常:" + e.getMessage()); } catch (IOException e) { log.error("IO异常:" + e); throw new RuntimeException("IO异常:" + e.getMessage()); } finally { if (response != null) { try { EntityUtils.consume(response.getEntity()); } catch (IOException e) { } } if (get != null) get.abort(); } }; } <file_sep>/src/main/java/com/spatome/applet/service/impl/zj/Tran10012ServiceImpl.java package com.spatome.applet.service.impl.zj; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang3.EnumUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.spatome.applet.common.enums.StatusEnum; import com.spatome.applet.entity.ActivityZj; import com.spatome.applet.service.TranService; import com.spatome.applet.service.impl.BaseService; import com.spatome.applet.util.DUtil; import com.spatome.applet.vo.BaseVO; import lombok.extern.slf4j.Slf4j; /** * 活动抓阄 * 基本增删改查 * * 修改 */ @Service @Slf4j public class Tran10012ServiceImpl extends BaseService implements TranService { @Override @Transactional public Object execute(Map<String, String> request, HttpServletRequest req, HttpServletResponse res) { BaseVO<Object> result = new BaseVO<Object>(); log.debug("获取参数"); String activityId = request.get("activityId"); //String ownerNo = request.get("ownerNo"); String activityName = request.get("activityName"); String beginTime = request.get("beginTime"); //开始时间 yyyy-MM-dd HH:mm:ss String endTime = request.get("endTime"); //结束时间 yyyy-MM-dd HH:mm:ss String descs = request.get("descs"); //活动详情 String totalCount = request.get("totalCount"); //总数 String drawCount = request.get("drawCount"); //中奖数 String imageName = request.get("imageName"); //图片 String status = request.get("status"); //状态 log.debug("检查参数"); Map<String, String> paramMap = new HashMap<String, String>(); paramMap.put("activityId", activityId); super.checkNotEmpty(paramMap); Date bTime = DUtil.parseFormatNoMM(beginTime); Date eTime = DUtil.parseFormatNoMM(endTime); Integer tCount = StringUtils.isBlank(totalCount)?null:Integer.valueOf(totalCount); Integer dCount = StringUtils.isBlank(drawCount)?null:Integer.valueOf(drawCount); log.debug("===========================业务处理========================="); if(status!=null && !EnumUtils.isValidEnum(StatusEnum.class, status)){ result.setCodeMessage("9999", "状态未定义"); return result; } ActivityZj record = daoFactory.getActivityZjMapper().selectByPrimaryKey(Long.valueOf(activityId)); if (record == null) { result.setCodeMessage("9999", "活动不存在"); return result; } ActivityZj updateActivityZj = new ActivityZj(); updateActivityZj.setId(record.getId()); updateActivityZj.setStatus(status); updateActivityZj.setActivityName(activityName); updateActivityZj.setBeginTime(bTime); updateActivityZj.setEndTime(eTime); updateActivityZj.setDescs(descs); updateActivityZj.setTotalCount(tCount); updateActivityZj.setDrawCount(dCount); updateActivityZj.setImageName(imageName); daoFactory.getActivityZjMapper().updateByPrimaryKeySelective(updateActivityZj); return result; } } <file_sep>/src/main/java/com/spatome/applet/AppletApplication.java package com.spatome.applet; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.ComponentScan; import org.springframework.scheduling.annotation.EnableAsync; @SpringBootApplication @EnableAsync @EnableConfigurationProperties @ComponentScan("com.spatome") @MapperScan("com.spatome.applet.dao") public class AppletApplication { public static void main(String[] args) { SpringApplication.run(AppletApplication.class, args); } } <file_sep>/src/main/java/com/spatome/applet/service/impl/zj/Tran10011ServiceImpl.java package com.spatome.applet.service.impl.zj; //package com.spatome.applet.service.impl.basic; // //import java.util.Date; //import java.util.HashMap; //import java.util.Map; // //import javax.servlet.http.HttpServletRequest; //import javax.servlet.http.HttpServletResponse; // //import org.springframework.stereotype.Service; //import org.springframework.transaction.annotation.Transactional; // //import com.spatome.applet.entity.ActivityZj; //import com.spatome.applet.service.TranService; //import com.spatome.applet.service.impl.BaseService; //import com.spatome.applet.vo.BaseVO; // //import lombok.extern.slf4j.Slf4j; // ///** // * 活动抓阄 // * 基本增删改查 // * // * 激活、关闭 // */ //@Service //@Slf4j //public class Tran10011ServiceImpl extends BaseService implements TranService { // // @Override // @Transactional // public Object execute(Map<String, String> request, HttpServletRequest req, HttpServletResponse res) { // BaseVO<Object> result = new BaseVO<Object>(); // // log.debug("获取参数"); // String activityId = request.get("activityId"); // String status = request.get("status"); // log.debug("检查参数"); // Map<String, String> paramMap = new HashMap<String, String>(); // paramMap.put("activityId", activityId); // paramMap.put("status", status); // super.checkNotEmpty(paramMap); // // log.debug("===========================业务处理========================="); // switch (status) { // case "ON": // break; // case "OFF": // break; // case "STOP": // break; // default: // result.setCodeMessage("9999", "未定义状态"); // return result; // } // // ActivityZj record = daoFactory.getActivityZjMapper().selectByPrimaryKey(Long.valueOf(activityId)); // if(record==null){ // log.warn("活动{{}}不存在", activityId); // result.setCodeMessage("9999", "活动不存在"); // return result; // } // if(record.getStatus().equals(status)){ // return result; // } // // ActivityZj updateActivityZj = new ActivityZj(); // updateActivityZj.setId(record.getId()); // updateActivityZj.setUpdateTime(new Date()); // updateActivityZj.setStatus(status); // daoFactory.getActivityZjMapper().updateByPrimaryKeySelective(updateActivityZj); // // return result; // } //} <file_sep>/src/main/java/com/spatome/applet/service/impl/zj/Tran10010ServiceImpl.java package com.spatome.applet.service.impl.zj; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.spatome.applet.entity.ActivityZj; import com.spatome.applet.service.TranService; import com.spatome.applet.service.impl.BaseService; import com.spatome.applet.util.DUtil; import com.spatome.applet.vo.BaseVO; import lombok.extern.slf4j.Slf4j; /** * 活动抓阄 * 基本增删改查 * * 增加 */ @Service @Slf4j public class Tran10010ServiceImpl extends BaseService implements TranService { @Override @Transactional public Object execute(Map<String, String> request, HttpServletRequest req, HttpServletResponse res) { BaseVO<Object> result = new BaseVO<Object>(); log.debug("获取参数"); String ownerNo = request.get("ownerNo"); String activityName = request.get("activityName"); String beginTime = request.get("beginTime"); //开始时间 yyyy-MM-dd String endTime = request.get("endTime"); //结束时间 yyyy-MM-dd String descs = request.get("descs"); //活动详情 String totalCount = request.get("totalCount"); //总数 String drawCount = request.get("drawCount"); //中奖数 String imageName = request.get("imageName"); //图片 log.debug("检查参数"); Map<String, String> paramMap = new HashMap<String, String>(); paramMap.put("ownerNo", ownerNo); paramMap.put("activityName", activityName); paramMap.put("beginTime", beginTime); paramMap.put("endTime", endTime); paramMap.put("totalCount", totalCount); paramMap.put("drawCount", drawCount); super.checkNotEmpty(paramMap); System.out.println(beginTime); Date bTime = DUtil.parseShortFormat(beginTime); Date eTime = DUtil.parseShortFormat(endTime); Date date = new Date(); log.debug("===========================业务处理========================="); ActivityZj record = new ActivityZj(); record.setStatus("ON"); record.setCreateTime(date); record.setUpdateTime(date); record.setActivityName(activityName); record.setOwnerNo(ownerNo); record.setTotalCount(Integer.valueOf(totalCount)); record.setDrawCount(Integer.valueOf(drawCount)); record.setImageName(imageName); record.setBeginTime(bTime); record.setEndTime(eTime); //record.setHintNo(hintNo); record.setDescs(descs); daoFactory.getActivityZjMapper().insertSelective(record); result.setBody(String.valueOf(record.getId())); return result; } } <file_sep>/src/main/java/com/spatome/applet/util/convert/JUtil.java package com.spatome.applet.util.convert; import java.util.List; import java.util.Map; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.JSONLibDataFormatSerializer; import com.alibaba.fastjson.serializer.SerializeConfig; import com.alibaba.fastjson.serializer.SerializerFeature; /** * JSON工具类 */ public class JUtil { private static final SerializeConfig config; static { config = new SerializeConfig(); config.put(java.util.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式 config.put(java.sql.Date.class, new JSONLibDataFormatSerializer()); // 使用和json-lib兼容的日期输出格式 } private static final SerializerFeature[] features = {SerializerFeature.WriteMapNullValue, // 输出空置字段 SerializerFeature.WriteNullListAsEmpty, // list字段如果为null,输出为[],而不是null SerializerFeature.WriteNullNumberAsZero, // 数值字段如果为null,输出为0,而不是null SerializerFeature.WriteNullBooleanAsFalse, // Boolean字段如果为null,输出为false,而不是null SerializerFeature.WriteNullStringAsEmpty // 字符类型字段如果为null,输出为"",而不是null }; /** * 对象转JSON * 格式化 */ public static String toJsonFeature(Object object) { return JSON.toJSONString(object, config, features); } /** * 对象转JSON * 不格式化 */ public static String toJson(Object object) { return JSON.toJSONString(object, config); } /** * json转对象 */ public static Object toBean(String json) { return JSON.parse(json); } /** * json转对象 */ public static <T> T toBean(String json, Class<T> clazz) { return JSON.parseObject(json, clazz); } /** * 转换为数组 */ public static <T> Object[] toArray(String json) { return toArray(json, null); } /** * 转换为数组 */ public static <T> Object[] toArray(String json, Class<T> clazz) { return JSON.parseArray(json, clazz).toArray(); } /** * 转换为List */ public static <T> List<T> toList(String json, Class<T> clazz) { return JSON.parseArray(json, clazz); } /** * json字符串转化为map * @param s * @return */ public static <K, V> Map<K, V> toMap(String json) { @SuppressWarnings("unchecked") Map<K, V> m = (Map<K, V>) JSON.parseObject(json); return m; } public static void main(String[] args) { /* Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>(); Map<String, String> map1 = new HashMap<String, String>(); map1.put("a", "1"); map1.put("b", "2"); Map<String, String> map2 = new HashMap<String, String>(); map2.put("aa", "11"); map2.put("bb", "21"); map.put("m1", map1); map.put("m2", map2); String ret = JsonUtil.toJson(map); System.out.println(ret);*/ String json = "{\"m1\":{\"a\":\"1\",\"b\":\"2\"},\"m2\":{\"aa\":\"11\",\"bb\":null}}"; Map<String, Map<String, String>> map = JUtil.toMap(json); for (Map.Entry<String, Map<String, String>> entry : map.entrySet()) { System.out.println("key:" + entry.getKey()); for (Map.Entry<String, String> entry1 : entry.getValue().entrySet()) { System.out.println("key:" + entry1.getKey() + " value:" + entry1.getValue()); } } } } <file_sep>/src/main/java/com/spatome/applet/util/CollectionUtil.java //package com.spatome.boot.util; // //import java.lang.reflect.Method; //import java.util.ArrayList; //import java.util.HashMap; //import java.util.Iterator; //import java.util.List; //import java.util.Map; //import java.util.Set; // //import org.apache.commons.lang.StringUtils; //import org.slf4j.Logger; //import org.slf4j.LoggerFactory; // //import com.fasterxml.jackson.core.JsonParser.Feature; //import com.fasterxml.jackson.databind.ObjectMapper; //import com.spatome.demo.core.exception.SException; // ///** // * @ClassName: CollectionUtil // * @Description: TODO // * @author: zhangwei // * @date: 2017年9月18日 下午6:24:53 // */ //public class CollectionUtil { // private static final Logger LOGGER = LoggerFactory.getLogger(CollectionUtil.class); // // /** // * List 分页 // */ // public static <T> List<List<T>> splitList(List<T> list, int len) { // if (list == null || list.size() == 0 || len < 1) { // return null; // } // // List<List<T>> result = new ArrayList<List<T>>(); // // int size = list.size(); // int count = (size + len - 1) / len; // // for (int i = 0; i < count; i++) { // List<T> subList = list.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1))); // result.add(subList); // } // return result; // } // ///* @SuppressWarnings({ "unchecked", "rawtypes" }) // public static <T> void sort(List<T> list, String property, boolean asc) { // Comparator<?> comparator = ComparableComparator.getInstance(); // comparator = ComparatorUtils.nullLowComparator(comparator); // if (!asc) { // comparator = ComparatorUtils.reversedComparator(comparator); // } // Collections.sort(list, new BeanComparator(property, comparator)); // }*/ // // /** // * @Description: 分组 // */ // public static <K, T> boolean listGroup2Map(List<T> list, Map<K, List<T>> map, String methodName, Class<T> clazz) { // try { // Method method = clazz.getDeclaredMethod(methodName); // // List<T> listTmp = null; // for (T t : list) { // @SuppressWarnings("unchecked") // K key = (K)method.invoke(t); // listTmp = map.get(key); // if(listTmp==null){ // listTmp = new ArrayList<T>(); // map.put(key, listTmp); // } // listTmp.add(t); // } // // return true; // } catch (Exception e) { // return false; // } // } // // /** // * @Description: Bean转Map // * 去除value是null的 // */ ///* public static <T> Map<String, String> beanToMap(T bean) { // Map<String, String> map = Maps.newHashMap(); // if (bean != null) { // BeanMap beanMap = BeanMap.create(bean); // for (Object key : beanMap.keySet()) { // if(beanMap.get(key)!=null){ // map.put(key + "", beanMap.get(key)+""); // } // } // } // // return map; // }*/ // // /** // * @Description: JSON字符串转MAP // */ // @SuppressWarnings("unchecked") // public static Map<String, String> toMap(String data) throws SException { // Map<String, String> result = new HashMap<String, String>(); // // try { // if(StringUtils.isBlank(data)){ // }else{ // ObjectMapper om = new ObjectMapper(); // om.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); // result = om.readValue(data, Map.class); // } // } catch (Exception e) { // LOGGER.error("toMap", e); // throw new SException("9999", "JSON String 转Map失败:"+e.getMessage()); // } // // return result; // } // // /** // * MAP转JSON字符串 // */ // public static <T> String toJson(Map<String, T> map) throws SException { // try { // if(map==null || map.size()==0){ // return "{}"; // }else{ // ObjectMapper om = new ObjectMapper(); // om.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); // return om.writeValueAsString(map); // } // } catch (Exception e) { // LOGGER.error("toJson", e); // throw new SException("9999", "Map转JSON失败"); // } // } // ///* public static <T> String toString(Map<String, T> map, String div){ // if(map==null){ // return ""; // } // // StringBuilder sb = new StringBuilder(); // for (Map.Entry<String, T> f : map.entrySet()) { // sb.append(f.getKey()).append("{").append(f.getValue()).append("}").append(div); // } // // return sb.toString(); // }*/ // // public static void ps(List<?> resultList){ // System.out.println("******************开始打印数据*****************"); // if(resultList!=null){ // System.out.println("当前记录条数为:"+resultList.size()); // for(Object result : resultList){ // System.out.println(result); // } // } // System.out.println("*****************打印结束****************"); // }; // // @SuppressWarnings("rawtypes") // public static boolean isSetEqual(Set set1, Set set2) // { // // if (set1 == null && set2 == null) // { // return true; // } // if(set1!=null && set1.size()==0 && set2!=null && set2.size()==0){ // return true; // } // if (set1 == null || set2 == null || set1.size() != set2.size()) // { // return false; // } // // Iterator ite2 = set2.iterator(); // // boolean isFullEqual = true; // // while (ite2.hasNext()) // { // if (!set1.contains(ite2.next())) // { // isFullEqual = false; // } // } // // return isFullEqual; // } // // public static void main(String[] args) { // } //}<file_sep>/src/main/java/com/spatome/applet/util/SpringUtil.java package com.spatome.applet.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.stereotype.Component; @Component public final class SpringUtil implements ApplicationContextAware { private final static Logger LOGGER = LoggerFactory.getLogger(SpringUtil.class); private static ApplicationContext applicationContext = null; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if (SpringUtil.applicationContext == null) { SpringUtil.applicationContext = applicationContext; LOGGER.info("创建SpringUtil成功!"); } } public static ApplicationContext getApplicationContext() { return applicationContext; } } <file_sep>/src/main/java/com/spatome/applet/controller/BaseController.java package com.spatome.applet.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import com.spatome.applet.common.config.MyConfig; import com.spatome.applet.common.exception.SException; import com.spatome.applet.factory.DaoFactory; import com.spatome.applet.factory.ServiceFactory; import com.spatome.applet.vo.BaseVO; @ControllerAdvice public class BaseController { protected final static Logger LOGGER = LoggerFactory.getLogger(BaseController.class); @Autowired protected DaoFactory daoFactory; @Autowired protected ServiceFactory serviceFactory; @Autowired protected MyConfig myConfig; @ExceptionHandler(Exception.class) @ResponseBody public BaseVO<Object> handlerException(Exception ex){ LOGGER.error("service未知异常:", ex); return new BaseVO<Object>("9999", "内部异常,清稍后重试"); } @ExceptionHandler(SException.class) @ResponseBody public BaseVO<Object> sException(SException ex){ LOGGER.error("service自定义异常:", ex); return new BaseVO<Object>(ex.getCode(), ex.getMessage()); } } <file_sep>/src/main/java/com/spatome/applet/entity/ZjRecord.java package com.spatome.applet.entity; import java.util.Date; public class ZjRecord { private Long id; private Long activityZjId; private String ownerNo; private String actorNo; private String isWin; private Date createTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getActivityZjId() { return activityZjId; } public void setActivityZjId(Long activityZjId) { this.activityZjId = activityZjId; } public String getOwnerNo() { return ownerNo; } public void setOwnerNo(String ownerNo) { this.ownerNo = ownerNo == null ? null : ownerNo.trim(); } public String getActorNo() { return actorNo; } public void setActorNo(String actorNo) { this.actorNo = actorNo == null ? null : actorNo.trim(); } public String getIsWin() { return isWin; } public void setIsWin(String isWin) { this.isWin = isWin == null ? null : isWin.trim(); } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } }<file_sep>/src/main/java/com/spatome/applet/factory/impl/DaoFactoryImpl.java package com.spatome.applet.factory.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Service; import com.spatome.applet.dao.ActivityZjMapper; import com.spatome.applet.dao.ZjRecordMapper; import com.spatome.applet.factory.DaoFactory; @Lazy @Service public class DaoFactoryImpl implements DaoFactory { @Autowired public ActivityZjMapper activityZjMapper; @Autowired public ZjRecordMapper zjRecordMapper; @Override public ActivityZjMapper getActivityZjMapper() { return activityZjMapper; } @Override public ZjRecordMapper getZjRecordMapper() { return zjRecordMapper; } }<file_sep>/src/main/java/com/spatome/applet/service/impl/DemoServiceImpl.java package com.spatome.applet.service.impl; import org.springframework.stereotype.Service; import com.spatome.applet.service.DemoService; @Service public class DemoServiceImpl extends BaseService implements DemoService { @Override public String test(String name) { return null; } } <file_sep>/src/main/java/com/spatome/applet/common/config/redis/RedisConfig.java package com.spatome.applet.common.config.redis; import java.io.Serializable; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; @Configuration @AutoConfigureAfter(RedisAutoConfiguration.class) public class RedisConfig { @Bean public RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) { RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<String, Serializable>(); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); redisTemplate.setConnectionFactory(redisConnectionFactory); return redisTemplate; } }
0dd36e6e69f65c35ce7135c3f5bc56f4a7af25fd
[ "Java" ]
21
Java
spatome/my
09ad095cdbf788b0d9cbf34263b9bd0cd22c8edf
c4b52eaae2005eabc7165277e90dff0a563c6a86
refs/heads/master
<repo_name>PankajSavaliyaGit/MultiImage<file_sep>/app/src/main/java/socialinfotech/multiimage/AddAdapter.java package socialinfotech.multiimage; import android.app.Activity; import android.content.Context; import android.net.Uri; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; /** * Created by pankaj on 18/12/15. */ public class AddAdapter extends RecyclerView.Adapter<MainViewHolder> { private ArrayList<UploadInfo> groups = new ArrayList<UploadInfo>(); private Context mContext; @Override public MainViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { LayoutInflater mInflater = LayoutInflater.from(viewGroup.getContext()); ViewGroup vGroup0 = (ViewGroup) mInflater.inflate(R.layout.raw_add_image, viewGroup, false); return new AddItemViewHolder(vGroup0); } @Override public void onBindViewHolder(MainViewHolder viewHolder, final int i) { UploadInfo info = groups.get(i); AddItemViewHolder vhGroup0 = (AddItemViewHolder) viewHolder; vhGroup0.remove.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { remove(i); } }); vhGroup0.imageView.setImageURI(Uri.fromFile(info.getmThumbnile())); } @Override public int getItemCount() { return groups.size(); } public AddAdapter(Activity context) { this.mContext = context; this.groups = new ArrayList<UploadInfo>(); } public void add(UploadInfo sample) { this.groups.add(sample); notifyDataSetChanged(); } public void remove(int position) { this.groups.remove(position); notifyDataSetChanged(); } public void Clear() { this.groups.clear(); notifyDataSetChanged(); } public ArrayList<UploadInfo> getData() { return groups; } }<file_sep>/app/src/main/java/socialinfotech/multiimage/AddItemViewHolder.java package socialinfotech.multiimage; import android.view.View; import android.widget.ImageButton; import android.widget.ProgressBar; import com.facebook.drawee.view.SimpleDraweeView; import butterknife.ButterKnife; import butterknife.InjectView; /** * Created by pankaj on 18/12/15. */ public class AddItemViewHolder extends MainViewHolder { @InjectView(R.id.cover_image_view) SimpleDraweeView imageView; @InjectView(R.id.remove) ImageButton remove; public AddItemViewHolder(View itemView) { super(itemView); ButterKnife.inject(this, itemView); } } <file_sep>/app/src/main/java/socialinfotech/multiimage/MyRestAdapter.java package socialinfotech.multiimage; /** * Created by pankaj on 31/08/16. */ import com.squareup.okhttp.OkHttpClient; import retrofit.RestAdapter; import retrofit.client.OkClient; import rx.Observable; public class MyRestAdapter { private api myService; private static MyRestAdapter myRestAdapter; public MyRestAdapter() { myService = restAdapter().create(api.class); } public static synchronized MyRestAdapter getInstance() { if (myRestAdapter == null) { myRestAdapter = new MyRestAdapter(); } return myRestAdapter; } public RestAdapter restAdapter() { RestAdapter restAdapter; if (BuildConfig.DEBUG) { restAdapter = new retrofit.RestAdapter.Builder().setEndpoint(api.API) .setLogLevel(RestAdapter.LogLevel.BASIC).setClient(new OkClient(new OkHttpClient())) .build(); } else { restAdapter = new retrofit.RestAdapter.Builder().setEndpoint(api.API) .setClient(new OkClient(new OkHttpClient())) .build(); } return restAdapter; } //file upload upload public Observable<image> getImageName(ProgressedTypedFile typedFile) { return myService.getImageName(typedFile); } } <file_sep>/app/src/main/java/socialinfotech/multiimage/api.java package socialinfotech.multiimage; import retrofit.http.Multipart; import retrofit.http.POST; import retrofit.http.Part; import rx.Observable; /** * Created by pankaj on 31/08/16. */ public interface api { String API="http://www.example/api/v1"; @Multipart @POST("/upload") Observable<image> getImageName(@Part("mimage") ProgressedTypedFile attachments); }
631d58fce3d2fdb33758e2a28f6c1fa240fc6a9f
[ "Java" ]
4
Java
PankajSavaliyaGit/MultiImage
2a590ca601c21c9744dd4f230000f68c82a31036
7a6d06c9df633920ee1bfa1f3788bee1be70d7c7
refs/heads/master
<file_sep><?php session_start(); if($_SESSION['student']) { include_once 'functions/actions.php'; $obj=new DataOperations(); } else{ header('location:login.php'); } ?> <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Star Admin Premium Bootstrap Admin Dashboard Template</title> <?php include_once 'includes/head.php'?> </head> <body> <div class="container-scroller"> <!-- partial:../../partials/_navbar.html --> <?php include_once 'includes/navbar.php'?> <!-- partial --> <div class="container-fluid page-body-wrapper"> <!-- partial:../../partials/_sidebar.html --> <?php include_once 'includes/sidebar.php'?> <!-- partial --> <div class="main-panel"> <div class="content-wrapper"> <div class="row"> <div class="col-md-6 d-flex align-items-stretch"> <div class="row"> </div> </div> <!-- content-wrapper ends --> </div> <!-- main-panel ends --> </div> <!-- partial:../../partials/_footer.html --> <?php include_once 'includes/footer.php'?> <!-- partial --> <!-- page-body-wrapper ends --> </div> <!-- container-scroller --> <!-- plugins:js --> <script src="assets/vendors/js/vendor.bundle.base.js"></script> <script src="assets/vendors/js/vendor.bundle.addons.js"></script> <!-- endinject --> <!-- inject:js --> <script src="assets/js/shared/off-canvas.js"></script> <script src="assets/js/shared/misc.js"></script> <!-- endinject --> </body> </html><file_sep><?php session_start(); include 'functions/actions.php'; $obj = new DataOperations(); $error = $success=$username=""; $_SESSION['username']=''; if(isset($_POST['login'])) { $username = $obj->con->real_escape_string(htmlentities($_POST['username'])); $password = $obj->con->real_escape_string(htmlentities($_POST['password'])); $where = array("username"=>$username,"password"=>$password); $exist = $obj->fetch_records("admin",$where); if($exist) { $_SESSION['username'] = $username; header('location: transactionReport.php'); } else { $error = "Wrong username or password!"; } } ?> <!DOCTYPE html> <html> <head> <title>Signin</title> <link rel="stylesheet" type="text/css" href="login.css"> <?php include 'plugins/styles.php';?> </head> <body> <div id="logo" align="center"><img src="images/logo1.png"></div> <div id="login"> <div id="container"> <div align="center" style="color:red"> <?php if($error) { $obj->errorDisplay($error); } if($success) { $obj->successDisplay($success); } ?> </div> <form method="post" action="<?php echo htmlentities($_SERVER['PHP_SELF'])?>"> <div id="login_form"> <div class="input-group"> <span class="input-group-addon input-sm"><span class="glyphicon glyphicon-user"></span></span> <input class="form-control" placeholder="Username" name="username" type="username" size=20 autofocus></input> </div> <div class="input-group"> <span class="input-group-addon input-sm"><span class="glyphicon glyphicon-lock"></span></span> <input class="form-control" placeholder="<PASSWORD>" name="password" type="<PASSWORD>" size=20></input> </div> <input class="btn btn-primary btn-block" type="submit" name="login" value="Login"/> </div> </form> </div> <h1>Maseno University Retake</h1> </div> </body> </html><file_sep><?php session_start(); /** * Created by PhpStorm. * User: Maxipain * Date: 8/2/2019 * Time: 9:23 AM */ include_once 'functions/actions.php'; $obj=new DataOperations(); if(isset($_POST['submit'])){ $admission = $obj->con->real_escape_string(htmlentities($_POST['admission'])); $password = md5($_POST['password']); $where = array('adm'=>$admission,'student_password'=>$password); if($obj->fetch_records('student',$where)){ $_SESSION['student'] = $admission; header('location:index.php'); } else{ echo "<script>alert('wrong login details')</script>"; } } ?> <html> <head> <title>login</title> </head> <body> <form action="" method="post"> <p>Admission number</p> <input type="text" name="admission" placeholder="Enter username"/> <p>Password</p> <input type="<PASSWORD>" name="password" placeholder="Enter password"/><br><br> <button type="submit" name="submit">Login</button> </form> </body> </html> <file_sep><?php session_start(); if(!$_SESSION['username']) { header('location:login.php'); } else { include 'functions/transactionReport.php'; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Transaction report</title> <!-- CSS --> <?php include 'plugins/styles.php';?> <style> th { color: #000; font-family: 'Trocchi', serif; font-size: 15px; font-weight: normal; line-height: 38px; margin: 0; } </style> </head> <body> <?php include'plugins/navigation.php';?> <div id="page-wrapper"> <div id="page-inner"> <div class="row"> <div class="panel panel-default"> <div class="panel-heading">Students payment Report</div> <div class="panel-body"> <?php if($error) { $obj->errorDisplay($error); } if($success) { $obj->successDisplay($success); } ?> <table class="table table-hover table-striped table-bordered display nowrap" id="table"> <thead> <tr> <th>Bill Ref. Number</th> <th>Transaction ID</th> <th>Transaction Amount</th> <th>First Name</th> <th>Middle Name</th> <th>lastname Name</th> <th>Reverse</th> </tr> </thead> <tbody> <?php $obj = new DataOperations(); $get_data = $obj->fetch_all_records("mobile_payments"); foreach ($get_data as $row) { $BillRefNumber = $row['BillRefNumber']; $TransID = $row['TransID']; $TransAmount = $row['TransAmount']; $FirstName = $row['FirstName']; $MiddleName= $row['MiddleName']; $LastName = $row['LastName']; $data[] = $row['TransAmount']; $json= json_encode($data); ?> <tr> <td><?php echo $BillRefNumber?></td> <td><?php echo $TransID?></td> <td><?php echo $TransAmount?></td> <td><?php echo $FirstName?></td> <td><?php echo $MiddleName?></td> <td><?php echo $LastName?></td> <td> <div class="btn-group"> <a href="#delete<?php echo $BillRefNumber;?>" data-toggle="modal" title="delete"><button type="button" class="btn btn-danger btn-sm"><span class="glyphicon glyphicon-transfer" aria-hidden="true"></span> </button> </a> </div> </td> </tr> <div class="modal fade" id="delete<?php echo $BillRefNumber;?>" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Reverse prompt</h4> </div> <div class="modal-body"> <form method="post" action="<?php htmlspecialchars($_SERVER['PHP_SELF'])?>"> <div class="alert alert-danger"> <p>Are you sure you want to reverse payments from <b><?php echo $FirstName?> </b> <b><?php echo $LastName?></b> with admision <b><?php echo $BillRefNumber?> </b>?</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button> <button name="reverse" class="btn btn-primary" value="<>" data-dismiss="modal">Yes</button> </div> </form> </div> </div> </div> </div> <?php } ?> </tbody> <strong><?php echo "sum(TransAmount) = " . array_sum($data) . "\n";?></strong> <br><br> </table> </div> </div> </div> </div> </div> <?php include 'plugins/scripts.php'; ?> <script> $('.table').DataTable(); </script> <script> </body> </html><file_sep><nav class="navbar default-layout col-lg-12 col-12 p-0 fixed-top d-flex flex-row"> <div class="text-center navbar-brand-wrapper d-flex align-items-top justify-content-center"> <a class="navbar-brand brand-logo" href="../../index.php"> <img src="assets/images/pettyprologo.png" alt="logo" /> </a> <a class="navbar-brand brand-logo-mini" href="../../index.php"> <img src="assets/images/pettyprologo-thumbnail.png" alt="logo" /> </a> </div> <div class="navbar-menu-wrapper d-flex align-items-center"> <ul class="navbar-nav"> <li class="nav-item font-weight-semibold d-none d-lg-block"> <a href="index.php"><button type="button" class="btn btn-warning btn-fw">Account balance:</button></a> ksh <?php $where = array('admission'=>$_SESSION['student']); $balance = 0; $fetch_balance = $obj->fetch_records('student_ledger',$where); if($fetch_balance){ foreach ($fetch_balance as $row){ $balance = $row['amount']; } } echo $balance; ?> </li> <!-- <li class="nav-item dropdown language-dropdown">--> <!-- <a class="nav-link dropdown-toggle px-2 d-flex align-items-center" id="LanguageDropdown" href="#" data-toggle="dropdown" aria-expanded="false">--> <!-- <div class="d-inline-flex mr-0 mr-md-3">--> <!-- <div class="flag-icon-holder">--> <!-- <i class="flag-icon flag-icon-ke"></i>--> <!-- </div>--> <!-- </div>--> <!-- <span class="profile-text font-weight-medium d-none d-md-block">Swa</span>--> <!-- </a>--> <!-- <div class="dropdown-menu dropdown-menu-left navbar-dropdown py-2" aria-labelledby="LanguageDropdown">--> <!-- <a class="dropdown-item">--> <!-- <div class="flag-icon-holder">--> <!-- <i class="flag-icon flag-icon-us"></i>--> <!-- </div>English--> <!-- </a>--> <!-- <a class="dropdown-item">--> <!-- <div class="flag-icon-holder">--> <!-- <i class="flag-icon flag-icon-fr"></i>--> <!-- </div>French--> <!-- </a>--> <!-- <a class="dropdown-item">--> <!-- <div class="flag-icon-holder">--> <!-- <i class="flag-icon flag-icon-ae"></i>--> <!-- </div>Arabic--> <!-- </a>--> <!-- <a class="dropdown-item">--> <!-- <div class="flag-icon-holder">--> <!-- <i class="flag-icon flag-icon-ru"></i>--> <!-- </div>Russian--> <!-- </a>--> <!-- </div>--> <!-- </li>--> </ul> <!-- <form class="ml-auto search-form d-none d-md-block" action="#">--> <!-- <div class="form-group">--> <!-- <input type="search" class="form-control" placeholder="Search Here">--> <!-- </div>--> <!-- </form>--> <ul class="navbar-nav ml-auto"> <li class="nav-item dropdown"> <a class="nav-link count-indicator" href="cart.php" > <i class="fa fa-shopping-cart text-primary"></i> <span class="count " style="background-color: #000000"> <?php $cart = 0; $admission = $_SESSION['student']; $exe = mysqli_query($obj->con,"SELECT id FROM cart WHERE admission = '$admission' AND state=0"); if(mysqli_num_rows($exe)>0) { $cart = mysqli_num_rows($exe); } echo $cart; ?> </span> </a> </li> <li class="nav-item dropdown"> <a class="nav-link count-indicator" id="messageDropdown" href="#" data-toggle="dropdown" aria-expanded="false"> <i class="fa fa-envelope text-warning"></i> <span class="count" style="background-color: #000000"> 9 </span> </a> <div class="dropdown-menu dropdown-menu-right navbar-dropdown preview-list pb-0" aria-labelledby="messageDropdown"> <a class="dropdown-item py-3"> <p class="mb-0 font-weight-medium float-left">You have 7 unread mails </p> <span class="badge badge-pill badge-primary float-right">View all</span> </a> <div class="dropdown-divider"></div> <a class="dropdown-item preview-item"> <div class="preview-thumbnail"> <img src="assets/images/faces/face10.jpg" alt="image" class="img-sm profile-pic"> </div> <div class="preview-item-content flex-grow py-2"> <p class="preview-subject ellipsis font-weight-medium text-dark"><NAME> </p> <p class="font-weight-light small-text"> The meeting is cancelled </p> </div> </a> <a class="dropdown-item preview-item"> <div class="preview-thumbnail"> <img src="assets/images/faces/face12.jpg" alt="image" class="img-sm profile-pic"> </div> <div class="preview-item-content flex-grow py-2"> <p class="preview-subject ellipsis font-weight-medium text-dark"><NAME> </p> <p class="font-weight-light small-text"> The meeting is cancelled </p> </div> </a> <a class="dropdown-item preview-item"> <div class="preview-thumbnail"> <img src="assets/images/faces/face1.jpg" alt="image" class="img-sm profile-pic"> </div> <div class="preview-item-content flex-grow py-2"> <p class="preview-subject ellipsis font-weight-medium text-dark"><NAME> </p> <p class="font-weight-light small-text"> The meeting is cancelled </p> </div> </a> </div> </li> <!-- <li class="nav-item dropdown">--> <!-- <a class="nav-link count-indicator" id="notificationDropdown" href="#" data-toggle="dropdown">--> <!-- <i class="mdi mdi-cash"></i>--> <!-- <span class="count bg-success">3</span>--> <!-- <span class="fa">3</span>--> <!-- </a>--> <!-- <div class="dropdown-menu dropdown-menu-right navbar-dropdown preview-list pb-0" aria-labelledby="notificationDropdown">--> <!-- <a class="dropdown-item py-3 border-bottom">--> <!-- <p class="mb-0 font-weight-medium float-left">You have 4 new notifications </p>--> <!-- <span class="badge badge-pill badge-primary float-right">View all</span>--> <!-- </a>--> <!-- <a class="dropdown-item preview-item py-3">--> <!-- <div class="preview-thumbnail">--> <!-- <i class="mdi mdi-alert m-auto text-primary"></i>--> <!-- </div>--> <!-- <div class="preview-item-content">--> <!-- <h6 class="preview-subject font-weight-normal text-dark mb-1">Application Error</h6>--> <!-- <p class="font-weight-light small-text mb-0"> Just now </p>--> <!-- </div>--> <!-- </a>--> <!-- <a class="dropdown-item preview-item py-3">--> <!-- <div class="preview-thumbnail">--> <!-- <i class="mdi mdi-settings m-auto text-primary"></i>--> <!-- </div>--> <!-- <div class="preview-item-content">--> <!-- <h6 class="preview-subject font-weight-normal text-dark mb-1">Settings</h6>--> <!-- <p class="font-weight-light small-text mb-0"> Private message </p>--> <!-- </div>--> <!-- </a>--> <!-- <a class="dropdown-item preview-item py-3">--> <!-- <div class="preview-thumbnail">--> <!-- <i class="mdi mdi-airballoon m-auto text-primary"></i>--> <!-- </div>--> <!-- <div class="preview-item-content">--> <!-- <h6 class="preview-subject font-weight-normal text-dark mb-1">New user registration</h6>--> <!-- <p class="font-weight-light small-text mb-0"> 2 days ago </p>--> <!-- </div>--> <!-- </a>--> <!-- </div>--> <!-- </li>--> <li class="nav-item dropdown d-none d-xl-inline-block user-dropdown"> <a class="nav-link dropdown-toggle" id="UserDropdown" href="#" data-toggle="dropdown" aria-expanded="false"> <img class="img-xs rounded-circle" src="assets/images/maseno.png" alt="Profile image"> </a> <div class="dropdown-menu dropdown-menu-right navbar-dropdown" aria-labelledby="UserDropdown"> <div class="dropdown-header text-center"> <img class="img-md rounded-circle" src="assets/images/maseno.png" alt="Profile image"> <p class="mb-1 mt-3 font-weight-semibold"><NAME></p> <p class="font-weight-light text-muted mb-0"><EMAIL></p> </div> <a class="dropdown-item">My Profile <span class="badge badge-pill badge-danger">1</span><i class="dropdown-item-icon ti-dashboard"></i></a> <a class="dropdown-item">Messages<i class="dropdown-item-icon ti-comment-alt"></i></a> <a class="dropdown-item">Activity<i class="dropdown-item-icon ti-location-arrow"></i></a> <a class="dropdown-item">FAQ<i class="dropdown-item-icon ti-help-alt"></i></a> <a class="dropdown-item">Sign Out<i class="dropdown-item-icon ti-power-off"></i></a> </div> </li> </ul> <button class="navbar-toggler navbar-toggler-right d-lg-none align-self-center" type="button" data-toggle="offcanvas"> <span class="mdi mdi-menu"></span> </button> </div> </nav><file_sep><?php session_start(); $error = $success =""; if(!$_SESSION['username']) { header('location:login.php'); } else { include 'functions/actions.php'; $obj = new DataOperations(); if(isset($_POST['save'])) { $password = $obj->con->real_escape_string(htmlentities($_POST['password'])); $password_confirm = $obj->con->real_escape_string(htmlentities($_POST['password_confirm'])); if($password !== $password_confirm) { $error = "Password do not much!"; } else { $where = array("username"=>$_SESSION['username']); $data = array("password"=>$password); if($obj->update_record("admin",$where,$data)) { $success = "Admin password updated successfully"; } else { $error = mysqli_error($obj->con); } } } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Admin Reset Password</title> <!-- CSS --> <?php include 'plugins/styles.php';?> </head> <body> <?php include'plugins/navigation.php';?> <div id="page-wrapper"> <div id="page-inner"> <div class="row"> <form action="<?php echo htmlentities($_SERVER['PHP_SELF'])?>" method="post"> <div class="col-md-6 col-md-offset-2"> <!--error dispaly--> <?php if($error) { $obj->errorDisplay($error); } if($success) { $obj->successDisplay($success); } ?> <div class="form-group"> <label>New Password</label> <input type="<PASSWORD>" placeholder="<PASSWORD>" class="form-control" name="password" value="" required> </div> <div class="form-group"> <label>Confirm New Password</label> <input type="password" placeholder="Confirm password" class="form-control" name="password_confirm" value="" required> </div> <div class="form-group"> <button class="btn btn-primary" name="save" type="submit" >Update</button> </div> </div> </form> </div> </div> </div> <?php include 'plugins/scripts.php'; ?> </body> </html><file_sep><?php $error=$success=""; session_start(); if(!$_SESSION['username']) { header('location:login.php'); } else { include 'functions/actions.php'; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Filter Payments</title> <!-- CSS --> <?php include 'plugins/styles.php';?> <style> table { border-collapse: separate; border-spacing: 10px 0; } </style> <script> $(function() { $('.dates #usr1').datepicker({ 'format': 'yyyy-mm-dd', 'autoclose': true }); }); </script> </head> <body> <?php include'plugins/navigation.php';?> <div id="page-wrapper"> <div id="page-inner"> <div class="row"> <form method="post" action="<?php htmlspecialchars($_SERVER['PHP_SELF'])?>"> <table> <tr> </tr> <tr> <td> <div class="dates"> <input type="text" id="usr1" class="form-control " style="width:200px;background-color:#fff;" name="startDate" placeholder="start date" required="required" autocomplete="off"> </div> </td> <td> <div class="dates"> <input type="text" id="usr1" class="form-control " style="width:200px;background-color:#fff;" name="endDate" placeholder="end date" required="required" autocomplete="off"> </div> </td> <td> <input type="submit" name="submit" class="btn btn-primary"> </td> </tr> </table> </form> <?php $obj = new DataOperations(); $con=new mysqli("localhost","root", "","mobile_payment") or die('error with connection'); if(isset($_POST['submit'])) { $startDate= $obj->con->real_escape_string(htmlentities($_POST['startDate'])); $endDate= $obj->con->real_escape_string(htmlentities($_POST['endDate'])); $query="SELECT * FROM mobile_payments WHERE TransTime BETWEEN '$startDate' AND '$endDate' "; $result=$con->query($query); if(mysqli_num_rows($result)>0){ $data= array(); foreach($result as $row){ $data[] = $row; $Amount[] = $row['TransAmount']; } print json_encode($data); echo "sum(TransAmount) = " . array_sum($Amount) . "\n";; } else{ $error= "No transaction for the period $startDate to $endDate"; } } ?> <div class="row"> <div class="col-md-6" style="margin-top: 25px;"> <?php if($error){ $obj->errorDisplay($error); } else if($success){ $obj->successDisplay($success); } ?> </div> </div> </div> </div> </div> <script type="text/javascript"> $(function () { $('#datetimepicker1').datetimepicker(); }); </script> <?php include 'plugins/scripts.php'; ?> </body> </html><file_sep>-- phpMyAdmin SQL Dump -- version 4.5.1 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: Aug 02, 2019 at 05:33 PM -- Server version: 10.1.13-MariaDB -- PHP Version: 5.6.20 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `pettypro` -- -- -------------------------------------------------------- -- -- Table structure for table `admin` -- CREATE TABLE `admin` ( `id` int(11) NOT NULL, `username` varchar(150) NOT NULL, `password` varchar(150) NOT NULL, `access_level` int(2) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `admin` -- INSERT INTO `admin` (`id`, `username`, `password`, `access_level`) VALUES (1, 'oduor', '1', 0), (2, 'oduorsamuel', '<PASSWORD>', 0), (3, 'petty', 'pro', 0); -- -------------------------------------------------------- -- -- Table structure for table `cart` -- CREATE TABLE `cart` ( `admission` varchar(199) NOT NULL, `unit_code` varchar(199) NOT NULL, `unit_name` varchar(199) NOT NULL, `state` int(1) NOT NULL, `id` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `cart` -- INSERT INTO `cart` (`admission`, `unit_code`, `unit_name`, `state`, `id`) VALUES ('ci/00078/014', 'MSU 101', 'Probability theory', 1, 5), ('ci/00078/014', 'MSU 101', 'Discrete Mathematics', 1, 6), ('ci/00078/014', 'MSU 101', 'Probability theory', 1, 7), ('ci/00078/014', 'MSU 101', 'Probability theory', 1, 8), ('ci/00078/014', 'MSU 101', 'Scientific themes', 1, 9), ('ci/00078/014', 'MSU 101', 'Probability theory', 1, 10), ('ci/00078/014', 'MSU 101', 'Discrete Mathematics', 1, 12); -- -------------------------------------------------------- -- -- Table structure for table `mobile_payments` -- CREATE TABLE `mobile_payments` ( `transLoID` int(11) NOT NULL, `TransactionType` varchar(10) NOT NULL, `TransID` varchar(10) NOT NULL, `TransTime` varchar(14) NOT NULL, `TransAmount` varchar(6) NOT NULL, `BusinessShortCode` varchar(6) NOT NULL, `BillRefNumber` varchar(6) NOT NULL, `InvoiceNumber` varchar(6) NOT NULL, `OrgAccountBalance` varchar(10) NOT NULL, `ThirdPartyTransID` varchar(10) NOT NULL, `MSISDN` varchar(14) NOT NULL, `FirstName` varchar(10) DEFAULT NULL, `MiddleName` varchar(10) DEFAULT NULL, `LastName` varchar(10) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `mobile_payments` -- INSERT INTO `mobile_payments` (`transLoID`, `TransactionType`, `TransID`, `TransTime`, `TransAmount`, `BusinessShortCode`, `BillRefNumber`, `InvoiceNumber`, `OrgAccountBalance`, `ThirdPartyTransID`, `MSISDN`, `FirstName`, `MiddleName`, `LastName`) VALUES (43, 'Pay Bill', 'NFE01H8ON2', '2019-06-11', '129', '600580', 'inv130', '', '70247.00', '', '254708374149', 'John', 'J.', 'Doe'), (46, 'Pay Bill', 'NFE11H8ON3', '2019-06-12', '23000.', '600580', '14', '', '93247.00', '', '254708374149', 'John', 'J.', 'Doe'), (49, 'Pay Bill', 'NFE41H8ON6', '20190614115447', '25000', '600580', '12', '', '118247.00', '', '254708374149', 'John', 'J.', 'Doe'), (52, 'Pay Bill', 'NFE21H8OQG', '20190614135154', '65.00', '600580', 'inv12', '', '118312.00', '', '254708374149', 'John', 'J.', 'Doe'); -- -------------------------------------------------------- -- -- Table structure for table `staff` -- CREATE TABLE `staff` ( `names` varchar(100) NOT NULL, `staff_id` varchar(60) NOT NULL, `category` varchar(60) NOT NULL, `state` int(1) NOT NULL, `department` varchar(30) NOT NULL, `last_login` timestamp(6) NOT NULL DEFAULT CURRENT_TIMESTAMP ) ; -- -------------------------------------------------------- -- -- Table structure for table `student` -- CREATE TABLE `student` ( `adm` varchar(200) NOT NULL, `first_name` varchar(50) NOT NULL, `last_name` varchar(50) NOT NULL, `school` varchar(200) NOT NULL, `department` varchar(200) NOT NULL, `program` varchar(200) NOT NULL, `student_password` varchar(200) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `student` -- INSERT INTO `student` (`adm`, `first_name`, `last_name`, `school`, `department`, `program`, `student_password`) VALUES ('', '', '', '', '', '', '<PASSWORD>'), ('0', 'ruth', 'ruth', 'computing', 'scjhjh', 'sam', '<PASSWORD>'), ('2', 'ruth', 'ruth', 'computing', 'scjhjh', 'sam', '<PASSWORD>'), ('3', 'ruth', 'ruth', 'computing', 'scjhjh', 'sam', '<PASSWORD>'), ('67', 'ruth', 'ruth', 'computing', 'scjhjh', 'sam', '<PASSWORD>'), ('ci/000/25/015', 'ruth', 'ruth', 'computing', 'scjhjh', 'sam', '<PASSWORD>'), ('ci/000/25/0153', 'ruth', 'ruth', 'computing', 'scjhjh', 'sam', '25d55ad283aa400af464c76d713c07ad'), ('ci/000/25/0157', 'ruth', 'ruth', 'computing', 'scjhjh', 'sam', '25d55ad283aa400af464c76d713c07ad'), ('ci/00078/014', 'Maxwell', 'Maragia', 'School of Agriculture', 'Department of Agriculture', 'Information Technology', '25d55ad283aa400af464c76d713c07ad'); -- -------------------------------------------------------- -- -- Table structure for table `student_ledger` -- CREATE TABLE `student_ledger` ( `admission` varchar(100) NOT NULL, `amount` int(11) NOT NULL, `id` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `student_ledger` -- INSERT INTO `student_ledger` (`admission`, `amount`, `id`) VALUES ('ci/00078/014', 0, 1); -- -------------------------------------------------------- -- -- Table structure for table `units` -- CREATE TABLE `units` ( `year` int(1) NOT NULL, `course` varchar(199) NOT NULL, `unit_name` varchar(199) NOT NULL, `unit_code` varchar(199) NOT NULL, `id` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Indexes for dumped tables -- -- -- Indexes for table `admin` -- ALTER TABLE `admin` ADD PRIMARY KEY (`id`); -- -- Indexes for table `cart` -- ALTER TABLE `cart` ADD PRIMARY KEY (`id`); -- -- Indexes for table `mobile_payments` -- ALTER TABLE `mobile_payments` ADD PRIMARY KEY (`transLoID`), ADD UNIQUE KEY `TransID` (`TransID`); -- -- Indexes for table `student` -- ALTER TABLE `student` ADD PRIMARY KEY (`adm`); -- -- Indexes for table `student_ledger` -- ALTER TABLE `student_ledger` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `admission` (`admission`), ADD UNIQUE KEY `id` (`id`); -- -- Indexes for table `units` -- ALTER TABLE `units` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `admin` -- ALTER TABLE `admin` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT for table `cart` -- ALTER TABLE `cart` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13; -- -- AUTO_INCREMENT for table `mobile_payments` -- ALTER TABLE `mobile_payments` MODIFY `transLoID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=53; -- -- AUTO_INCREMENT for table `student_ledger` -- ALTER TABLE `student_ledger` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `units` -- ALTER TABLE `units` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep><?php /** * Created by PhpStorm. * User: maxipain * Date: 11/26/2017 * Time: 5:47 PM */ class DATABASE{ public $con; public function __construct() { $this->con=mysqli_connect("localhost","kipasise_ideal","Codei@maseno","kipasise_ideal")or die(mysqli_error($this->con)); if(!$this->con) { echo "failed to connect"; } } } $obj=new DATABASE();<file_sep><?php session_start(); if($_SESSION['student']) { include_once 'functions/actions.php'; $obj=new DataOperations(); $admission = $_SESSION['student']; $success = ''; if(isset($_POST['submit'])){ $unit_name = $_POST['unit']; $data = array('admission'=>$admission,'unit_code'=>'MSU 101','unit_name'=>$unit_name); if($obj->insert_record('cart',$data)) { $success = "Unit registered successfully"; } } } else{ header('location:login.php'); } ?> <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Star Admin Premium Bootstrap Admin Dashboard Template</title> <?php include_once 'includes/head.php' ?> </head> <body> <div class="container-scroller"> <!-- partial:../../partials/_navbar.html --> <?php include_once 'includes/navbar.php' ?> <!-- partial --> <div class="container-fluid page-body-wrapper"> <!-- partial:../../partials/_sidebar.html --> <?php include_once 'includes/sidebar.php'?> <!-- partial --> <div class="main-panel"> <div class="content-wrapper"> <!-- Page Title Header Starts--> <div class="row page-title-header"> <div class="col-12"> <div class="page-header"> <h4 class="page-title text-pri-color"><span class="fa fa-pencil-square-o text-sec-color"></span> &nbsp; Register units</h4> <!-- <div class="quick-link-wrapper w-100 d-md-flex flex-md-wrap">--> <!-- <ul class="quick-links">--> <!-- <li><a href="#">ICE Market data</a></li>--> <!-- <li><a href="#">Own analysis</a></li>--> <!-- <li><a href="#">Historic market data</a></li>--> <!-- </ul>--> <!-- <ul class="quick-links ml-auto">--> <!-- <li><a href="#">Settings</a></li>--> <!-- <li><a href="#">Analytics</a></li>--> <!-- <li><a href="#">Watchlist</a></li>--> <!-- </ul>--> <!-- </div>--> </div> </div> </div> <div class="row"> <div class="col-md-12 d-flex align-items-stretch"> <div class="col-12 grid-margin"> <div class="card"> <div class="card-body"> <form class="form-sample" method="post" action=""> <?php if($success){$obj->successDisplay($success);}?> <div class="row"> <div class="col-md-6"> <div class="form-group row"> <label class="col-sm-3 col-form-label">Course</label> <div class="col-sm-9"> <select class="form-control" name="course" required="required"> <option value="">choose</option> <option>Bachelor in IT</option> <option>Bachelor in economics</option> <option>Bachelor in mathematics</option> <option>Bachelor in physics</option> <option>Bachelor in accounting</option> <option>Bachelor in hacking</option> </select> </div> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="form-group row"> <label class="col-sm-3 col-form-label">Year</label> <div class="col-sm-9"> <select class="form-control"> <option>Choose</option> <option>1</option> <option>2</option> <option>3</option> <option>4</option> </select> </div> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="form-group row"> <label class="col-sm-3 col-form-label">Unit</label> <div class="col-sm-9"> <select class="form-control" required="required" name="unit"> <option value="">Choose</option> <option>Discrete Mathematics</option> <option>Probability theory</option> <option>Scientific themes</option> </select> </div> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="form-group row"> <div class="col-sm-9"> <button class="btn btn-primary" name="submit" type="submit">Register</button> </div> </div> </div> </div> </form> </div> </div> </div> </div> <!-- content-wrapper ends --> </div> <!-- main-panel ends --> </div> <!-- partial:../../partials/_footer.html --> <?php include_once 'includes/footer.php'?> <!-- partial --> <!-- page-body-wrapper ends --> </div> <!-- container-scroller --> <!-- plugins:js --> <script src="assets/vendors/js/vendor.bundle.base.js"></script> <script src="assets/vendors/js/vendor.bundle.addons.js"></script> <!-- endinject --> <!-- inject:js --> <script src="assets/js/shared/off-canvas.js"></script> <script src="assets/js/shared/misc.js"></script> <!-- endinject --> </body> </html><file_sep><?php session_start(); if($_SESSION['student']) { include_once 'functions/actions.php'; $obj=new DataOperations(); $admission = $_SESSION['student']; $success = ''; if(isset($_POST['delete'])) { $id = $_POST['delete']; $where = array('id'=>$id); $obj->delete_record('cart',$where); } if(isset($_POST['checkout'])){ $cart = $_POST['checkout']; $where = array('admission'=>$admission,'state'=>0); $data = array('state'=>1); $amount = $cart*200; if($obj->update_record('cart',$where,$data)){ $exe = mysqli_query($obj->con,"UPDATE student_ledger SET amount = amount - $amount WHERE admission='$admission'" ); $success = "$cart unit/s registered"; } } } else{ header('location:login.php'); } ?> <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Star Admin Premium Bootstrap Admin Dashboard Template</title> <?php include_once 'includes/head.php'?> </head> <body> <div class="container-scroller"> <!-- partial:../../partials/_navbar.html --> <?php include_once 'includes/navbar.php'?> <!-- partial --> <div class="container-fluid page-body-wrapper"> <!-- partial:../../partials/_sidebar.html --> <?php include_once 'includes/sidebar.php'?> <!-- partial --> <div class="main-panel"> <div class="content-wrapper"> <div class="row page-title-header"> <div class="col-12"> <div class="page-header"> <h4 class="page-title text-pri-color"><span class="fa fa-shopping-cart text-sec-color"></span> &nbsp; Cart</h4> <!-- <div class="quick-link-wrapper w-100 d-md-flex flex-md-wrap">--> <!-- <ul class="quick-links">--> <!-- <li><a href="#">ICE Market data</a></li>--> <!-- <li><a href="#">Own analysis</a></li>--> <!-- <li><a href="#">Historic market data</a></li>--> <!-- </ul>--> <!-- <ul class="quick-links ml-auto">--> <!-- <li><a href="#">Settings</a></li>--> <!-- <li><a href="#">Analytics</a></li>--> <!-- <li><a href="#">Watchlist</a></li>--> <!-- </ul>--> <!-- </div>--> </div> </div> </div> <div class="col-lg-12 grid-margin stretch-card"> <div class="card"> <div class="card-body"> <?php if($success){$obj->successDisplay($success);}?> <h4 class="card-title">Selected units</h4> <p class="card-description">To delete a unit simply click on the <span class="fa fa-trash-o primary-icon-color"> button</span> </p> <form method="post" action=""> <table class="table table-hover"> <thead> <tr> <th >Unit name</th> <th>Unit code</th> <th>Delete</th> </tr> </thead> <tbody> <?php $where = array('admission'=>$admission,'state'=>0); $get_cart = $obj->fetch_records('cart',$where); foreach ($get_cart as $row) { $unit= $row['unit_name']; $code = $row['unit_code']; $id = $row['id']; ?> <tr> <td><?=$unit?></td> <td><?=$code?></td> <td> <button style="font-size: 20px" value="<?=$id?>" name="delete" type="submit"><span class="fa fa-trash-o primary-icon-color"></span></button> </td> </tr> <?php } ?> </tbody> </table> </form> </div> </div> </div> <div class="col-md-12 grid-margin stretch-card"> <?php if($cart>0) { ?> <div class="card"> <div class="card-body"> <div class="row"> <div class="col-md-3"> <div class="d-flex align-items-center pb-2"> <div class="dot-indicator bg-primary mr-2"></div> <p class="mb-0">Total payable</p> </div> <h4 class="font-weight-semibold">Ksh <?=$cart*200;?></h4> <div class="progress progress-md"> <div class="progress-bar bg-primary" role="progressbar" style="width: 100%" aria-valuenow="78" aria-valuemin="0" aria-valuemax="78"></div> </div> </div> <div class="col-md-3 mt-4 mt-md-0"> <div class="d-flex align-items-center pb-2"> <div class="dot-indicator bg-primary mr-2"></div> <p class="mb-0">Current balance</p> </div> <h4 class="font-weight-semibold">Ksh <?=$balance?></h4> <div class="progress progress-md"> <div class="progress-bar bg-primary" role="progressbar" style="width: 45%" aria-valuenow="45" aria-valuemin="0" aria-valuemax="45"></div> </div> </div> <div class="col-md-3 mt-4 mt-md-0"> <div class="d-flex align-items-center pb-2"> <div class="dot-indicator bg-warning mr-2"></div> <p class="mb-0">Deficit</p> </div> <h4 class="font-weight-semibold">Ksh <?php $deficit=($cart*200)-$balance; if($deficit>0) { echo $deficit; } else{ echo 0; } ?> </h4> <div class="progress progress-md"> <div class="progress-bar bg-warning" role="progressbar" style="width: 45%" aria-valuenow="45" aria-valuemin="0" aria-valuemax="45"></div> </div> </div> <div class="col-md-3 grid-margin stretch-card average-price-card"> <?php if($deficit>0) { ?> <div class="card text-white"> <div class="card-body bg-primary" style="align-content: center"> <!-- <div class="d-flex justify-content-between pb-2 align-items-center">--> <!-- <h2 class="font-weight-semibold mb-0">4,624</h2>--> <!-- <div class="icon-holder">--> <!-- <i class="mdi mdi-briefcase-outline"></i>--> <!-- </div>--> <!-- </div>--> <!-- <h5 class="font-weight-semibold mb-0">Average Price</h5>--> <p class="text-white mb-0">Deposit cash to checkout</p> </div> </div> <?php } else{ ?> <form action="" method="post"> <button class="btn btn-success" type="submit" name="checkout" value="<?=$cart?>"><span class="fa fa-check"></span> Checkout</button> </form> <?php } ?> </div> </div> </div> </div> <?php } ?> </div> <!-- content-wrapper ends --> <!-- main-panel ends --> </div> <!-- partial:../../partials/_footer.html --> <?php include_once 'includes/footer.php'?> <!-- partial --> <!-- page-body-wrapper ends --> </div> <!-- container-scroller --> <!-- plugins:js --> <script src="assets/vendors/js/vendor.bundle.base.js"></script> <script src="assets/vendors/js/vendor.bundle.addons.js"></script> <!-- endinject --> <!-- inject:js --> <script src="assets/js/shared/off-canvas.js"></script> <script src="assets/js/shared/misc.js"></script> <!-- endinject --> </body> </html><file_sep><?php include 'actions.php'; $obj = new DataOperations(); $error = $success = ""; $first_name = $last_name =$adm = $school = $department = $program = ""; if(isset($_POST['register'])) { $first_name = $obj->con->real_escape_string(htmlentities($_POST['first_name'])); $last_name = $obj->con->real_escape_string(htmlentities($_POST['last_name'])); $adm = $obj->con->real_escape_string(htmlentities($_POST['adm'])); $school = $obj->con->real_escape_string(htmlentities($_POST['school'])); $department = $obj->con->real_escape_string(htmlentities($_POST['department'])); $program = $obj->con->real_escape_string(htmlentities($_POST['program'])); $password = password_hash($adm, PASSWORD_DEFAULT); $where = array("adm"=>$adm); $exist = $obj->fetch_records("student",$where); if($exist) { $error = "Student with the same admission number already exist!"; } else { $data = array( "adm"=>$adm, "first_name"=>$first_name, "last_name"=>$last_name, "school"=>$school, "program"=>$program, "department"=>$department, "student_password"=>$password, ); $insert = $obj->insert_record("student",$data); if($insert) { $success = "New student registered successfully"; } else { $error = mysqli_error($obj->con); } } } ?><file_sep><?php session_start(); if(!$_SESSION['username']) { header('location:login.php'); } else { include 'functions/actions.php'; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Petty Pro</title> <script> function refreshPage(){ window.location.reload(); } </script> <!-- CSS --> <?php include 'plugins/styles.php' ?> </head> <body> <?php include'plugins/navigation.php';?> <div id="page-wrapper"> <div id="page-inner"> <div class="row"> <div class="row"> </div> </div> <?php include 'plugins/scripts.php'; ?> </body> </html><file_sep>-- phpMyAdmin SQL Dump -- version 4.5.1 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: Jun 29, 2019 at 01:24 PM -- Server version: 10.1.13-MariaDB -- PHP Version: 5.6.20 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `mobile_payment` -- -- -------------------------------------------------------- -- -- Table structure for table `admin` -- CREATE TABLE `admin` ( `id` int(11) NOT NULL, `username` varchar(150) NOT NULL, `password` varchar(150) NOT NULL, `access_level` int(2) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `admin` -- INSERT INTO `admin` (`id`, `username`, `password`, `access_level`) VALUES (1, 'oduor', '1', 0), (2, 'oduorsamuel', '<PASSWORD>', 0), (3, 'petty', 'pro', 0); -- -------------------------------------------------------- -- -- Table structure for table `mobile_payments` -- CREATE TABLE `mobile_payments` ( `transLoID` int(11) NOT NULL, `TransactionType` varchar(10) NOT NULL, `TransID` varchar(10) NOT NULL, `TransTime` varchar(14) NOT NULL, `TransAmount` varchar(6) NOT NULL, `BusinessShortCode` varchar(6) NOT NULL, `BillRefNumber` varchar(6) NOT NULL, `InvoiceNumber` varchar(6) NOT NULL, `OrgAccountBalance` varchar(10) NOT NULL, `ThirdPartyTransID` varchar(10) NOT NULL, `MSISDN` varchar(14) NOT NULL, `FirstName` varchar(10) DEFAULT NULL, `MiddleName` varchar(10) DEFAULT NULL, `LastName` varchar(10) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `mobile_payments` -- INSERT INTO `mobile_payments` (`transLoID`, `TransactionType`, `TransID`, `TransTime`, `TransAmount`, `BusinessShortCode`, `BillRefNumber`, `InvoiceNumber`, `OrgAccountBalance`, `ThirdPartyTransID`, `MSISDN`, `FirstName`, `MiddleName`, `LastName`) VALUES (43, 'Pay Bill', 'NFE01H8ON2', '2019-06-11', '129', '600580', 'inv130', '', '70247.00', '', '254708374149', 'John', 'J.', 'Doe'), (46, 'Pay Bill', 'NFE11H8ON3', '2019-06-12', '23000.', '600580', '14', '', '93247.00', '', '254708374149', 'John', 'J.', 'Doe'), (49, 'Pay Bill', 'NFE41H8ON6', '20190614115447', '25000', '600580', '12', '', '118247.00', '', '254708374149', 'John', 'J.', 'Doe'), (52, 'Pay Bill', 'NFE21H8OQG', '20190614135154', '65.00', '600580', 'inv12', '', '118312.00', '', '254708374149', 'John', 'J.', 'Doe'); -- -------------------------------------------------------- -- -- Table structure for table `student` -- CREATE TABLE `student` ( `adm` varchar(200) NOT NULL, `first_name` varchar(50) NOT NULL, `last_name` varchar(50) NOT NULL, `school` varchar(200) NOT NULL, `department` varchar(200) NOT NULL, `program` varchar(200) NOT NULL, `student_password` varchar(200) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `student` -- INSERT INTO `student` (`adm`, `first_name`, `last_name`, `school`, `department`, `program`, `student_password`) VALUES ('', '', '', '', '', '', '$2y$10$RFTkuWWu0PTct.N56YBdFeFievNNl3YeDDPnwQjztYUC2Fkgf4Cru'), ('0', 'ruth', 'ruth', 'computing', 'scjhjh', 'sam', '$2y$10$WhsFp/0gIZW8gRGWz3n7GuxFNIvkTj6.CzLx349MkCjNUxw4I..iK'), ('2', 'ruth', 'ruth', 'computing', 'scjhjh', 'sam', '$2y$10$UaXbv15AWvyMcRTunrB/zetk4uDaBb5QjTm7NveVKt8PJ8qrEXg4q'), ('3', 'ruth', 'ruth', 'computing', 'scjhjh', 'sam', '$2y$10$/jTbxZ24ACmrgw5n/H/di.uQq6q/80ZDVk2TdgNfYBYY.LIYUIZgm'), ('67', 'ruth', 'ruth', 'computing', 'scjhjh', 'sam', '$2y$10$ii0kmf/Q0x638UgYzDO7XudAIeSj8SX6.MZDgpRAkau2dOYunYGeu'), ('ci/000/25/015', 'ruth', 'ruth', 'computing', 'scjhjh', 'sam', '$2y$10$zHgG5.ZPSaXVYMsEw8cT3uZHVZ7JohUZTHAG4oS/sz7Bi/hWeK7NK'), ('ci/000/25/0153', 'ruth', 'ruth', 'computing', 'scjhjh', 'sam', '$2y$10$pNwbAtWUs.W/RMPCmtyXvufv9o7Oya70jYWm/gmqLoW03MX8JEG3K'), ('ci/000/25/0157', 'ruth', 'ruth', 'computing', 'scjhjh', 'sam', '$2y$10$6nIkaoBHVndJwyUZuzNXWOSxRy.0NyZw5XA/S1EVHaLsvZlb422R2'); -- -- Indexes for dumped tables -- -- -- Indexes for table `admin` -- ALTER TABLE `admin` ADD PRIMARY KEY (`id`); -- -- Indexes for table `mobile_payments` -- ALTER TABLE `mobile_payments` ADD PRIMARY KEY (`transLoID`), ADD UNIQUE KEY `TransID` (`TransID`); -- -- Indexes for table `student` -- ALTER TABLE `student` ADD PRIMARY KEY (`adm`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `admin` -- ALTER TABLE `admin` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT for table `mobile_payments` -- ALTER TABLE `mobile_payments` MODIFY `transLoID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=53; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep><!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>Resit cards</title> <?php include_once 'includes/head.php'?> </head> <body> <div class="container-scroller"> <!-- partial:../../partials/_navbar.html --> <?php include_once 'includes/navbar.php'?> <!-- partial --> <div class="container-fluid page-body-wrapper"> <!-- partial:../../partials/_sidebar.html --> <?php include_once 'includes/sidebar.php'?> <!-- partial --> <div class="main-panel"> <div class="content-wrapper"> <div class="row page-title-header"> <div class="col-12"> <div class="page-header"> <h4 class="page-title text-pri-color"><span class="fa fa-download text-sec-color"></span> &nbsp; Resit cards</h4> <!-- <div class="quick-link-wrapper w-100 d-md-flex flex-md-wrap">--> <!-- <ul class="quick-links">--> <!-- <li><a href="#">ICE Market data</a></li>--> <!-- <li><a href="#">Own analysis</a></li>--> <!-- <li><a href="#">Historic market data</a></li>--> <!-- </ul>--> <!-- <ul class="quick-links ml-auto">--> <!-- <li><a href="#">Settings</a></li>--> <!-- <li><a href="#">Analytics</a></li>--> <!-- <li><a href="#">Watchlist</a></li>--> <!-- </ul>--> <!-- </div>--> </div> </div> </div> <div class="col-lg-12 grid-margin stretch-card"> <div class="card"> <div class="card-body"> <!-- <h4 class="card-title">Selected units</h4>--> <p class="card-description">To download a card click on the <span class="fa fa-download text-primary"> button</span> </p> <table class="table table-hover"> <thead> <tr> <th >Unit name</th> <th>Unit code</th> <th>Date to sit</th> <th>Download</th> </tr> </thead> <tbody> <tr> <td>Jacob</td> <td>Photoshop</td> <td class=""> 28.76% </td> <td> <a href="#" class="fa fa-download primary-icon-color" style="font-size: 20px"></a> </td> </tr> <tr> <td>Messsy</td> <td>Flash</td> <td> 21.06% </td> <td> <a href="#" class="fa fa-download primary-icon-color" style="font-size: 20px"></a> </td> </tr> <tr> <td>John</td> <td>Premier</td> <td> 35.00% </i> </td> <td> <a href="#" class="fa fa-download primary-icon-color" style="font-size: 20px"></a> </td> </tr> <tr> <td>Peter</td> <td>After effects</td> <td> 82.00% </td> <td> <a href="#" class="fa fa-download primary-icon-color" style="font-size: 20px"></a> </td> </tr> <tr> <td>Dave</td> <td>53275535</td> <td> 98.05% </td> <td> <a href="#" class="fa fa-download primary-icon-color" style="font-size: 20px"></a> </td> </tr> </tbody> </table> </div> </div> </div> <!-- <div class="col-md-12 grid-margin stretch-card">--> <!-- <div class="card">--> <!-- <div class="card-body">--> <!-- <div class="row">--> <!-- <div class="col-md-3">--> <!-- <div class="d-flex align-items-center pb-2">--> <!-- <div class="dot-indicator bg-primary mr-2"></div>--> <!-- <p class="mb-0">Total payable</p>--> <!-- </div>--> <!-- <h4 class="font-weight-semibold">Ksh 7,590</h4>--> <!-- <div class="progress progress-md">--> <!-- <div class="progress-bar bg-primary" role="progressbar" style="width: 100%" aria-valuenow="78" aria-valuemin="0" aria-valuemax="78"></div>--> <!-- </div>--> <!-- </div>--> <!-- <div class="col-md-3 mt-4 mt-md-0">--> <!-- <div class="d-flex align-items-center pb-2">--> <!-- <div class="dot-indicator bg-primary mr-2"></div>--> <!-- <p class="mb-0">Current balance</p>--> <!-- </div>--> <!-- <h4 class="font-weight-semibold">Ksh 5,460</h4>--> <!-- <div class="progress progress-md">--> <!-- <div class="progress-bar bg-primary" role="progressbar" style="width: 45%" aria-valuenow="45" aria-valuemin="0" aria-valuemax="45"></div>--> <!-- </div>--> <!-- </div>--> <!-- <div class="col-md-3 mt-4 mt-md-0">--> <!-- <div class="d-flex align-items-center pb-2">--> <!-- <div class="dot-indicator bg-warning mr-2"></div>--> <!-- <p class="mb-0">Deficit</p>--> <!-- </div>--> <!-- <h4 class="font-weight-semibold">Ksh 5,460</h4>--> <!-- <div class="progress progress-md">--> <!-- <div class="progress-bar bg-warning" role="progressbar" style="width: 45%" aria-valuenow="45" aria-valuemin="0" aria-valuemax="45"></div>--> <!-- </div>--> <!-- </div>--> <!-- <div class="col-md-3 grid-margin stretch-card average-price-card">--> <!----> <!-- <div class="card text-white">--> <!-- <div class="card-body bg-primary" style="align-content: center">--> <!-- <div class="d-flex justify-content-between pb-2 align-items-center">--> <!-- <h2 class="font-weight-semibold mb-0">4,624</h2>--> <!-- <div class="icon-holder">--> <!-- <i class="mdi mdi-briefcase-outline"></i>--> <!-- </div>--> <!-- </div>--> <!----> <!-- <h5 class="font-weight-semibold mb-0">Average Price</h5>--> <!-- <p class="text-white mb-0"><span class="fa fa-check"></span>Check out</p>--> <!----> <!-- </div>--> <!-- </div>--> <!-- </div>--> <!-- </div>--> <!-- </div>--> <!-- </div>--> <!-- </div>--> <!-- content-wrapper ends --> <!-- main-panel ends --> </div> <!-- partial:../../partials/_footer.html --> <?php include_once 'includes/footer.php'?> <!-- partial --> <!-- page-body-wrapper ends --> </div> <!-- container-scroller --> <!-- plugins:js --> <script src="assets/vendors/js/vendor.bundle.base.js"></script> <script src="assets/vendors/js/vendor.bundle.addons.js"></script> <!-- endinject --> <!-- inject:js --> <script src="assets/js/shared/off-canvas.js"></script> <script src="assets/js/shared/misc.js"></script> <!-- endinject --> </body> </html><file_sep><?php session_start(); if(!$_SESSION['username']) { header('location:login.php'); } else { include 'functions/register_student.php'; } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Events</title> <!-- CSS --> <?php include 'plugins/styles.php';?> <style> label { color: #000; font-family: 'Trocchi', serif; font-size: 15px; font-weight: normal; line-height: 38px; margin: 0; } </style> </head> <body> <?php include'plugins/navigation.php';?> <div id="page-wrapper"> <div id="page-inner"> <div class="row"> <!-- new --> <form class="well form-horizontal" action="<?php echo htmlentities($_SERVER['PHP_SELF'])?>" method="post" id="contact_form"> <?php if($error) { $obj->errorDisplay($error); } if($success) { $obj->successDisplay($success); } ?> <fieldset> <!-- Form Name --> <legend><center><h5><b>Register Student</b></h5></center></legend><br> <!-- Text input--> <div class="form-group"> <label class="col-md-4 control-label" >Admission</label> <div class="col-md-4 inputGroupContainer"> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span> <input name="adm" placeholder="Adm number" class="form-control" required type="text"> </div> </div> </div> <div class="form-group"> <label class="col-md-4 control-label">First Name</label> <div class="col-md-4 inputGroupContainer"> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span> <input name="first_name" placeholder="<NAME>" class="form-control" required type="text"> </div> </div> </div> <!-- Text input--> <div class="form-group"> <label class="col-md-4 control-label" >Last Name</label> <div class="col-md-4 inputGroupContainer"> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span> <input name="last_name" placeholder="<NAME>" class="form-control" required type="text"> </div> </div> </div> <!-- school --> <div class="form-group"> <label class="col-md-4 control-label">School</label> <div class="col-md-4 selectContainer"> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-list"></i></span> <select name="school" class="form-control selectpicker"> <option value="">Select your School</option> <option>School of Engineering</option> <option>School of Agriculture</option> </select> </div> </div> </div> <!-- school --> <div class="form-group"> <label class="col-md-4 control-label">Department</label> <div class="col-md-4 selectContainer"> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-list"></i></span> <select name="department" class="form-control selectpicker"> <option value="">Select your Department</option> <option>Department of Engineering</option> <option>Department of Agriculture</option> <option >Accounting Office</option> <option >Tresurer's Office</option> <option >MPDC</option> <option >MCTC</option> <option >MCR</option> <option >Mayor's Office</option> <option >Tourism Office</option> </select> </div> </div> </div> <!-- program --> <div class="form-group"> <label class="col-md-4 control-label">Program</label> <div class="col-md-4 selectContainer"> <div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-list"></i></span> <select name="program" class="form-control selectpicker"> <option value="">Select your Program</option> <option>Information Technology</option> <option>Computer Technology</option> </select> </div> </div> </div> <!-- program --> <!-- Button --> <div class="form-group"> <label class="col-md-4 control-label"></label> <div class="col-md-4"><br> &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<button type="submit" class="btn btn-primary" name="register" >&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspSUBMIT <span class="glyphicon glyphicon-send"></span>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</button> </div> </div> </fieldset> </form> </div> <!-- end new --> </div> </div> </div> </div> </div> <?php include 'plugins/scripts.php'; ?> </body> </html><file_sep>Create database pettypro Import database file named pettypro.sql from database folder as sql To view student side navigate to "localhost/pettypro-master User admission "ci/00078/014" password "<PASSWORD>" to login To view admin side navigate to "localhost/pettypro-master/management Username "petty" password "pro" <file_sep><?php /** * secret servers. */ class DATABASE{ public $con; public function __construct() { $this->con=mysqli_connect("localhost","root","","mobile_payment")or die(mysqli_error($this->con)); if(!$this->con) { echo "failed to connect"; } } } $obj=new DATABASE();<file_sep><?php include 'actions.php'; $obj = new DataOperations(); $error=$success=''; if(isset($_POST['reverse'])) { } ?><file_sep><?php try { //Set the response content type to application/json require 'actions.php'; header("Content-Type:application/json"); $resp = '{"ResultCode":0,"ResultDesc":"Confirmation recieved successfully"}'; //read incoming request $postData = file_get_contents('php://input'); //log file $filePath = "confirmation.txt"; //error log $errorLog = "errors.log"; //Parse payload to json $jsonMpesaResponse = json_decode($postData,true); //perform business operations on $jdata here //save json data to database $data = array( 'TransactionType' => $TransactionType, 'TransID' => $TransID, 'TransTime' => $TransTime, 'TransAmount' => $TransAmount, 'BusinessShortCode' => $BusinessShortCode, 'BillRefNumber' => $BillRefNumber, 'InvoiceNumber' => $InvoiceNumber, 'OrgAccountBalance' => $OrgAccountBalance, 'ThirdPartyTransID' => $ThirdPartyTransID, 'MSISDN' => $MSISDN, 'FirstName' => $FirstName, 'MiddleName' => $MiddleName, 'LastName' => $LastName ); $TransactionType = $obj->con->real_escape_string(htmlentities($jsonMpesaResponse['TransactionType'])); $TransID = $obj->con->real_escape_string(htmlentities($jsonMpesaResponse['TransID'])); $TransTime = $obj->con->real_escape_string(htmlentities($jsonMpesaResponse['TransTime'])); $TransAmount = $obj->con->real_escape_string(htmlentities($jsonMpesaResponse['TransAmount'])); $BusinessShortCode = $obj->con->real_escape_string(htmlentities($jsonMpesaResponse['BusinessShortCode'])); $BillRefNumber = $obj->con->real_escape_string(htmlentities($jsonMpesaResponse['BillRefNumber'])); $InvoiceNumber = $obj->con->real_escape_string(htmlentities($jsonMpesaResponse['InvoiceNumber'])); $OrgAccountBalance = $obj->con->real_escape_string(htmlentities($jsonMpesaResponse['OrgAccountBalance'])); $ThirdPartyTransID = $obj->con->real_escape_string(htmlentities($jsonMpesaResponse['ThirdPartyTransID'])); $MSISDN = $obj->con->real_escape_string(htmlentities($jsonMpesaResponse['MSISDN'])); $FirstName = $obj->con->real_escape_string(htmlentities($jsonMpesaResponse['FirstName'])); $MiddleName = $obj->con->real_escape_string(htmlentities($jsonMpesaResponse['MiddleName'])); $LastName = $obj->con->real_escape_string(htmlentities($jsonMpesaResponse['LastName'])); $data = array( 'TransactionType' => $TransactionType, 'TransID' => $TransID, 'TransTime' => $TransTime, 'TransAmount' => $TransAmount, 'BusinessShortCode' => $BusinessShortCode, 'BillRefNumber' => $BillRefNumber, 'InvoiceNumber' => $InvoiceNumber, 'OrgAccountBalance' => $OrgAccountBalance, 'ThirdPartyTransID' => $ThirdPartyTransID, 'MSISDN' => $MSISDN, 'FirstName' => $FirstName, 'MiddleName' => $MiddleName, 'LastName' => $LastName ); $save_transaction = $obj->insert_record('mobile_payments',$data); if($save_transaction){ $data = array( $sql = "UPDATE student_ledger SET amount=amount+$TransAmount WHERE admission='$BillRefNumber'"; $exe = mysqli_query($obj->con,$sql); } //open text file for logging messages by appending $file = fopen($filePath,"a"); //log incoming request fwrite($file, $postData); fwrite($file,"\r\n"); //log response and close file fwrite($file,$resp); fclose($file); } catch (Exception $ex){ //append exception to errorLog $logErr = fopen($errorLog,"a"); fwrite($logErr, $ex->getMessage()); fwrite($logErr,"\r\n"); fclose($logErr); } //echo response echo $resp; ?> <file_sep><?php header('Content-Type: application/json'); $mysqli=new mysqli("localhost","root", "","mobile_payment") or die('error with connection'); $query=sprintf("SELECT * FROM mobile_payments "); $result=$mysqli->query($query); $data= array(); foreach($result as $row){ $data[] = $row; } $result->close(); $mysqli -> close(); print json_encode($data); ?>
b1ab9f5a1781621e835f7a287f8308ecee47931b
[ "Markdown", "SQL", "PHP" ]
21
PHP
maxipain/pettypro
a2c6cb269a0d60ebc916cb134efffed60078608e
b304f525d4b8d2b6f2cf88485ab12bd9adb7e1bf
refs/heads/master
<file_sep>import json import numpy as np from glob import glob import os import time def get_paths(directory, input_type='png'): """ Get a list of input_type paths params args: return: a list of paths """ paths = glob(os.path.join(directory, '*.{}'.format(input_type))) assert len(paths) > 0, '\n\tDirectory:\t{}\n\tInput type:\t{} \n num of paths must be > 0'.format( dir, input_type) print('Found {} files {}'.format(len(paths), input_type)) return paths # Json def read_json(path): '''Read a json path. Arguments: path: string path to json Returns: A dictionary of the json file ''' with open(path, 'r') as f: data = json.load(f) return data def load_db(path_json, max_length=10e12): img_dir = os.path.split(path_json)[0] d = read_json(path_json) labels = list(d.values()) paths = [os.path.join(img_dir, path) for path in list(d.keys())] for i, (p, l) in enumerate(zip(paths, labels)): if not type(l) is str \ or not os.path.exists(p)\ or len(l) > max_length: paths.remove(p) labels.remove(l) print('\rChecking database: {:0.2f} %'.format(i/len(paths)), end='') assert len(paths) == len(labels), '{}-{}'.format(len(paths), len(labels)) return paths, labels def load_multiple_db(dbs, max_length=10e12): paths, labels = load_db(dbs[0], max_length) for db in dbs[1:]: rv_ = load_db(db, max_length) paths += rv_[0] labels += rv_[1] return paths, labels def get_angle(p1, p2): x1, y1 = p1 x2, y2 = p2 dx = abs(x1 - x2) dy = abs(y1 - y2) return np.argtan(dy/dx)*180 def timeit(method): def timed(*args, **kw): ts = time.time() result = method(*args, **kw) te = time.time() if 'log_time' in kw: name = kw.get('log_name', method.__name__.upper()) kw['log_time'][name] = int((te - ts) * 1000) else: print('%r %2.2f ms' % (method.__name__, (te - ts) * 1000)) return result return timed def noralize_filenames(directory, ext='*'): paths = glob('{}.{}'.format(directory, ext)) for i, path in enumerate(paths): base_dir, base_name = os.path.split(path) name, base_ext = base_name.split('.') new_name = '{:0>4d}.{}'.format(i, base_ext) new_path = os.path.join(base_dir, new_name) print('Rename: {} --> {}'.format(path, new_path)) os.rename(path, new_path) if __name__ == '__main__': path = 'sample_image/1.png' image = read_img(path) print('Test show from path') show(path) print('Test show from np image') show(image)
e043e79eb001a1f3908ae5930e6765ededecad45
[ "Python" ]
1
Python
phamquiluan/pyson
95ef67815994dfbfb4bf9a607cd86353ca41248a
e101dc49bcfbcded10d783a30dc187d13ce37a19
refs/heads/master
<file_sep>#!/usr/bin/env bash uptime pwd
ff821aca383bf52e33c437e151847d15321f3b94
[ "Shell" ]
1
Shell
moondev/spinnaker-script-stage
616e4e2ad673efe8d05255a6a815857e2e2edb8c
2760d55a76f1ad0a3768e1c59827c2a0c40b2c2a
refs/heads/master
<file_sep><?php require_once("../delete/index.php"); require_once("task_list.php"); require_once("../../user/logout/index.php"); ?> <!DOCTYPE html> <html> <head> <title>List Task</title> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <link href="../public/frontend/css/main.css" rel="stylesheet"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <style> .form{ display: flex; } .form form{ margin-right: 5px; } button{ margin-right: 5px; } .table td, .table th{ border-top: 0px; } .category{ text-align: center; } .btn{ margin-top: 5px; } .header button{ margin-left: 90%; } .btn-warning { color: #000; background-color: #f0ad4e; border-color: #eea236; } .back{ text-align: center; } .table{ width: 50%; margin: auto; } </style> </head> <body> <div class="header"> <div class="navigation"> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class="collapse navbar-collapse" id="navbarNav"> <form method="POST" action=""> <button type="submit" class='logout btn btn-warning left-margin' name="logout" value="logout">Logout</button> </form> </div> </nav> </div> </div> <table class="table"> <thead> <tr> <th scope="col">TASK ID</th> <th scope="col">TASK NAME</th> <th scope="col">TASK DETAIL</th> <th scope="col"></th> </tr> </thead> <tbody> <?php foreach ($data as $item) { echo '<tr> <td>'.$item['id'].'</td> <td>'.$item['task_name'].'</td> <td>'.$item['task_detail'].'</td> <td style="width: 5%;"><a href="/task/task/update/?id='.$item['id'].'"><button class="btn btn-warning left-margin">Edit</button></a></td> <td> <form method="POST"> <button class="btn btn-warning left-margin" type="submit" name="delete" value="'.$item['id'].'">Delete</button> </form> </td> </tr>'; } ?> </tbody> </table> <div class="back"> <a href="/task/task/insert" class="btn btn-warning left-margin">New Task</a> </div> </body> </html><file_sep><?php require_once('index.php'); require_once('../../database/db_helper.php'); session_start(); if (!empty($_SESSION["users"])){ header('Location: /task/task/list'); } class Login extends DB { public $msg; protected $username; protected $password; public function __construct($username, $password) { $this->username = $username; $this->password = md5($password); } function login() { if(!empty($this->username) && !empty($this->password)) { $sql = "SELECT * FROM user WHERE username = '$this->username' and password = '$this->password'"; $this->executeResult($sql); if(!empty($this->data[0])) { $_SESSION['users'] = $this->data[0]; header('Location: /task/task/list'); die(); } } } } if(!empty($_POST['login'])){ $user = $_POST['username']; $pass = $_POST['password']; $login = new Login($user, $pass); $data1 = $login->login(); } ?><file_sep><?php session_start(); if (empty($_SESSION['users'])) { header("location:/task/user/login"); } require_once("../../database/db_helper.php"); class getTask extends DB{ protected $taskID; function __construct($taskID) { $this->taskID = $taskID; } function getTask() { $sql = "SELECT * FROM task WHERE id = '$this->taskID'"; return $this->executeResult($sql); } } if(!empty($_GET['id'])){ $taskID = $_GET['id']; $task = new getTask($taskID); $data = $task->getTask(); } class updateTask extends DB{ protected $id; protected $taskName; protected $taskDetail; function __construct($id, $taskName, $taskDetail) { $this->id = $id; $this->taskName = $taskName; $this->taskDetail = $taskDetail; } function updateTask() { $sql = "UPDATE task SET task_name = '$this->taskName', task_detail = '$this->taskDetail' WHERE id='$this->id'"; return $this->execute($sql); } } if(!empty($_POST['update_task'])){ $id = $_POST['id']; $name = $_POST['name']; $detail = $_POST['detail']; $update = new updateTask($id, $name, $detail); $update->updateTask(); } ?><file_sep><?php require_once ('config.php'); class DB{ protected $data; function execute($sql) { $con = mysqli_connect(HOST, USERNAME, PASSWORD, DATABASE); mysqli_query($con, $sql); mysqli_close($con); } function executeResult($sql) { $con = mysqli_connect(HOST, USERNAME, PASSWORD, DATABASE); $result = mysqli_query($con, $sql); if ($result != null) { while ($row = mysqli_fetch_array($result, 1)) { $this->data[] = $row; } } mysqli_close($con); return $this->data; } } $db = new DB(); ?><file_sep><?php session_start(); if (empty($_SESSION['users'])) { header("location:/task/user/login"); } require_once("../../database/db_helper.php"); class deleteTask extends DB{ protected $id; function __construct($id) { $this->id = $id; } function delete() { $sql = "DELETE FROM task WHERE id = '$this->id'"; $this->execute($sql); header('Location: /task/task/list'); } } if(!empty($_POST['delete'])) { $id = $_POST['delete']; $delete = new deleteTask($id); return $delete->delete(); } ?><file_sep><?php header('Location: /task/user/login'); ?><file_sep><?php if(empty($_SESSION)){ session_start(); } if (empty($_SESSION['users'])) { header("location:/task/user/login"); } require_once("../../database/db_helper.php"); class listTask extends DB{ public function getList() { $sql = "SELECT * FROM task"; return $this->executeResult($sql); } } $list = new listTask(); $data = $list->getList(); ?><file_sep><?php require_once('index.php'); require_once('../../database/db_helper.php'); class Register extends DB{ protected $username; protected $password; protected $confirm_psw; function __construct($username, $password, $confirm_psw) { $this->username = $username; $this->password =$<PASSWORD>; $this->confirm_psw = $confirm_psw; } function register() { if(!empty($this->username) && !empty($this->username) && !empty($this->username) && $this->password === $this->confirm_psw){ $pass = md5($this->password); $sql = "INSERT INTO user(id, username, password) values (null, '$this->username', '$pass')"; return $this->execute($sql); } } } if(!empty($_POST['register'])){ $user = $_POST['username']; $pass = $_POST['<PASSWORD>']; $confirm = $_POST['confirm_pwd']; $register = new Register($user, $pass, $confirm); return $register->register(); } ?><file_sep><?php require_once("update.php"); ?> <!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <link href="../public/frontend/css/main.css" rel="stylesheet"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Update Product</title> <style> body { font-family: Arial, Helvetica, sans-serif; } * { box-sizing: border-box; } .container { width: 50%; margin: auto; padding: 16px; background-color: white; border: 5px solid green; } /* Full-width input fields */ input[type=text], input[type=password] { width: 100%; padding: 15px; margin: 5px 0 22px 0; display: inline-block; border: none; background: #f1f1f1; } input[type=text]:focus, input[type=password]:focus { background-color: #ddd; outline: none; } hr { border: 1px solid #f1f1f1; margin-bottom: 25px; } .slug{ background-color: #04AA6D; color: white; padding: 16px 20px; margin: 8px 0; border: none; cursor: pointer; width: 100%; opacity: 0.9; } .slug:hover { opacity: 1; } a { color: dodgerblue; } .signin { background-color: #f1f1f1; text-align: center; } </style> </head> <body> <div class="container"> <form method="POST"> <h1>UPDATE TASK</h1> <hr> <label for="name"><b>Task ID:</b></label> <input type="text" name="id" value="<?php if(!empty($data)){ foreach($data as $value){ echo $value['id']; } } ?>" readonly> <label for="name"><b>Task</b></label> <input type="text" placeholder="Enter Name" name="name"value="<?php if(!empty($data)){ foreach($data as $value){ echo $value['task_name']; } } ?>"> <label for="detail"><b>Detail</b></label> <textarea class="form-control" rows="5" name="detail"><?php if(!empty($data)){ foreach($data as $value){ echo $value['task_detail']; } } ?></textarea> <hr> <button type="submit" class='update_task btn btn-warning left-margin' name="update_task" value="save">Update</button> <br> <div class="back" class='btn btn-warning left-margin'> <a href="/task/task/list">List Task</a> </div> </form> </div> </body> </html> <file_sep><?php session_start(); if (empty($_SESSION['users'])) { header("location:/task/user/login"); } require_once('index.php'); require_once ("../../database/db_helper.php"); class newTask extends DB{ protected $name; protected $detail; public function __construct($task_name, $task_detail) { $this->name = $task_name; $this->detail = $task_detail; } public function new() { if(!empty($this->name) && !empty($this->detail)) { $sql = "INSERT INTO task(id, task_name, task_detail) values (null, '$this->name', '$this->detail')"; $this->execute($sql); return $this->msg = "thanh cong"; } else { return $this->msg = "that bai"; } } } if(!empty($_POST['add_task'])) { $task_name = $_POST['name']; $task_detail = $_POST['detail']; $newTask = new newTask($task_name, $task_detail); $data = $newTask->new(); } ?><file_sep><?php if(empty($_SESSION)){ session_start(); } class Logout{ public function logout() { if(!empty($_POST['logout'])){ session_destroy(); header('Location: /task/user/login'); } } } $logout = new Logout(); return $logout->logout(); ?>
3f03d8643697433b7da997e248a07351f160ec1e
[ "PHP" ]
11
PHP
NamPham1329/task
90e5a049755a94a598f2fbaa78b0ca6a51efefe9
0393b2853d6bd1f1b5214379cdb04f7b6b188ac4
refs/heads/master
<repo_name>Coderdotnew/swift_method_math<file_sep>/method_math.swift // Write your code below! NOTE: you may need to look up the last two. Remember: Google is your friend! //Create a function that takes in two integer arguments and adds them together when the function is called. //Create a function that takes in two integer arguments and subtracts them from eachother when the function is called. //Create a function that takes in two integer arguments and multiplies them together when the function is called. //Create a function that takes in two integer arguments and divides the integers when the function is called. //Create a function that takes in two integer arguments and finds the remainder when the first number is divided by the second number when the function is called. //Create a function that takes in two integer arguments (base and exponent) that creates an exponential equation the function is called. (i.e. base ^ exponent) //Create a function that takes in one integer argument and finds the square root when the function is called.
e1186e178e8e504715b10e61da07c624f8be1d8d
[ "Swift" ]
1
Swift
Coderdotnew/swift_method_math
387b3ba690d20218838ab53770f04e1fe4aeab53
baade36fb1dd38b26b237b9efbfccb7d96922445
refs/heads/master
<file_sep>#!/bin/bash sudo apt-get update sudo apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys <KEY> sudo apt-add-repository 'deb https://apt.dockerproject.org/repo ubuntu-xenial main' sudo apt-get update sudo apt-get install -y docker-engine apt-get update && apt-get install docker-ce -y #sample deploy docker run -d -p 9000:9000 -v /root/portainer/data:/data -v /var/run/docker.sock:/var/run/docker.sock portainer/portainer
b23f622d8cd5878ff037bf7ba705e2e3b5c2d773
[ "Shell" ]
1
Shell
billyprice1/deployscripts
cb10cd0a353b42d6ede4576b3942865dd7da5733
be45093624b6c5e57c051d9af4dea48b6edc9957
refs/heads/master
<repo_name>borkoyz/challenge-6<file_sep>/README.md # Challenge 6 The Complete Web Developer in 2019: Zero to Mastery - Challlenge 6 <file_sep>/challenge1.js // Clean the room function: given an input of // [1, 2, 4, 591, 392, 391, 2, 5, 10, 2, 1, 1, 1, 20, 20], // make a function that organizes these into // individual array that is ordered. // For example answer(ArrayFromAbove) should return : // [[1, 1, 1, 1], [2, 2, 2], 4, 5, 10, [20, 20], 391, 392, 591]. // Bonus: Make it so it organizes strings differently // from number types.i.e.[1, "2", "3", 2] should return // [ [1, 2], ["2", "3"]] const input = [1,2,4,591,'zdfg',392,'abc',391,2,5,'1',10,'1',2,'2',1,1,1,'zzzz','3',20,20,'sdfs','sdfsdfff','zzzz','4']; const output = []; console.log(`Original Data: ${input}`); const organizeFN=(dataIn,dataOut)=>{ //duplicate the array into an obj let temp = { categories:[], arr:[...dataIn], // makes a copy of the array }; //filters through the array finding the typeof eg 'string', number, etc and creates a typeof category into the temp obj temp.arr.filter(item=>{ let itemName = `${typeof item}Arr`; //if the category doesnt exist then it will create one if(!temp[itemName]){ temp[itemName] = []; //creates a category for the types available within the object temp.categories.push({name:`${typeof item}Arr`,type:typeof item}); } //pushes the item into the appropriate category temp[itemName].push(item); }); //goes through each category temp.categories.forEach(cat=>{ //sorting if(cat.type==='number'){ temp[cat.name].sort((a, b) => a - b); }else{ temp[cat.name].sort(); } //grouping let tempGroup =[]; let tempFullGroup =[]; //while the array length is above 0 it will look at the first item and compare it with the next item //then will remove the first item and then repeat while(temp[cat.name].length>0){ tempGroup.push(temp[cat.name][0]); //once the comparison doesnt match will add to the Full group Array if(temp[cat.name][0]!==temp[cat.name][1]){ //if there was only 1 item then dont group else group eg [1,1,1,1] if(tempGroup.length===1){ tempFullGroup.push(tempGroup[0]); }else{ tempFullGroup.push(tempGroup); } tempGroup =[]; } //remove the item at index 0 then repeat temp[cat.name].splice(0,1); } temp[cat.name] = tempFullGroup; dataOut.push(...temp[cat.name]); console.log(`${cat.type} Data: ${temp[cat.name]}`); }); console.log(`Final Output: ${JSON.stringify(dataOut)}`); } organizeFN(input,output);
36546d71cafe2251d47546f3e8e35945e8d2b738
[ "Markdown", "JavaScript" ]
2
Markdown
borkoyz/challenge-6
c7ca377cc80e082acfe795b509f30a60fca996b3
9bbf623e45a711e0ce9af95834d1dd63163ddccf
refs/heads/master
<repo_name>julioperezdev/blog-restapi<file_sep>/src/main/resources/sql/tables/ImagePresentation.sql CREATE TABLE ImagePresentation( idPost INT, imageUrl VARCHAR(300), publicId VARCHAR(300), PRIMARY KEY (idPost), FOREIGN KEY (idPost) REFERENCES Post(id) );<file_sep>/src/main/resources/sql/tables/TypeVisualContent.sql CREATE TABLE TypeVisualContent( id INT IDENTITY(1,1), name VARCHAR(100), PRIMARY KEY (id) );<file_sep>/src/main/resources/sql/tables/Category.sql CREATE TABLE Category( id INT IDENTITY(1,1), name VARCHAR(200) NOT NULL UNIQUE, PRIMARY KEY (id) );<file_sep>/src/main/java/dev/protobot/blogrestapi/model/VideoContent.java package dev.protobot.blogrestapi.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "VideoContent") public class VideoContent { @Id @Column(name = "idPost") private Long idPost; @Column(name = "idTypeVisualContent") private Long idTypeVisualContent; @Column(name = "videoUrl") private String videoUrl; public VideoContent(Long idPost, Long idTypeVisualContent, String videoUrl) { this.idPost = idPost; this.idTypeVisualContent = idTypeVisualContent; this.videoUrl = videoUrl; } public VideoContent(Long idTypeVisualContent, String videoUrl) { this.idTypeVisualContent = idTypeVisualContent; this.videoUrl = videoUrl; } public VideoContent() { } public Long getId() { return idPost; } public void setId(Long idPost) { this.idPost = idPost; } public Long getIdTypeVisualContent() { return idTypeVisualContent; } public void setIdTypeVisualContent(Long idTypeVisualContent) { this.idTypeVisualContent = idTypeVisualContent; } public String getVideoUrl() { return videoUrl; } public void setVideoUrl(String videoUrl) { this.videoUrl = videoUrl; } } <file_sep>/src/main/resources/sql/tables/AuthorCertificate.sql CREATE TABLE AuthorCertificate( id INT IDENTITY(1,1), code VARCHAR(200) NOT NULL, idAuthor INT NOT NULL UNIQUE, PRIMARY KEY (id), FOREIGN KEY (idAuthor) REFERENCES Author(id) );<file_sep>/src/main/java/dev/protobot/blogrestapi/model/ImagePresentation.java package dev.protobot.blogrestapi.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "ImagePresentation") public class ImagePresentation { @Id @Column(name = "idPost") private Long idPost; @Column(name = "imageUrl") private String imageUrl; @Column(name = "publicId") private String publicId; public ImagePresentation(Long idPost, String imageUrl, String publicId) { this.idPost = idPost; this.imageUrl = imageUrl; this.publicId = publicId; } public ImagePresentation(String imageUrl, String publicId) { this.imageUrl = imageUrl; this.publicId = publicId; } public ImagePresentation() { } public Long getIdPost() { return idPost; } public void setIdPost(Long idPost) { this.idPost = idPost; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getPublicId() { return publicId; } public void setPublicId(String publicId) { this.publicId = publicId; } } <file_sep>/src/main/java/dev/protobot/blogrestapi/helper/shared/CheckIfNullOrEmptyString.java package dev.protobot.blogrestapi.helper.shared; import dev.protobot.blogrestapi.exceptions.helper.shared.HelperCheckIfNullOrEmptyStringException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; @Service public class CheckIfNullOrEmptyString { Logger logger = LoggerFactory.getLogger(CheckIfNullOrEmptyString.class); public CheckIfNullOrEmptyString() { } public void check (String string){ logger.info("Checking if Null or Empty this String"); if(isNullOrEmpty(string)) throw new HelperCheckIfNullOrEmptyStringException(); } private boolean isNullOrEmpty(String string) { return !(string != null && !string.equals("")); } }<file_sep>/src/main/java/dev/protobot/blogrestapi/service/implementation/CategoryServiceImplementation.java package dev.protobot.blogrestapi.service.implementation; import dev.protobot.blogrestapi.model.Category; import dev.protobot.blogrestapi.service.CategoryService; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class CategoryServiceImplementation implements CategoryService { @Override public List<Category> getAllCategory() { return null; } @Override public Optional<Category> getCategoryById(Long id) { return Optional.empty(); } @Override public Category saveCategory(Category category) { return null; } @Override public String deleteCategoryById(Long id) { return null; } } <file_sep>/src/main/resources/sql/tables/Author.sql CREATE TABLE Author( id INT IDENTITY(1,1), name VARCHAR(200) NOT NULL, email VARCHAR(200) NOT NULL UNIQUE, imageUrl VARCHAR(300), publicId VARCHAR(300), PRIMARY KEY (id) );<file_sep>/src/test/java/dev/protobot/blogrestapi/controller/TypeVisualContentControllerTest.java package dev.protobot.blogrestapi.controller; import dev.protobot.blogrestapi.model.TypeVisualContent; import dev.protobot.blogrestapi.service.implementation.TypeVisualContentServiceImplementation; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import java.util.ArrayList; import java.util.List; import java.util.Optional; import static org.hamcrest.Matchers.hasSize; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.then; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; @ExtendWith(MockitoExtension.class) class TypeVisualContentControllerTest { @Mock TypeVisualContentServiceImplementation typeVisualContentServiceImplementation; @InjectMocks TypeVisualContentController controller; MockMvc mockMvc; @BeforeEach void setUp() { mockMvc = MockMvcBuilders.standaloneSetup(controller).build(); } @Nested public class itShouldGetAllTypeVisualContentCases{ List<TypeVisualContent> allTypeVisualContent = new ArrayList<>(); TypeVisualContent typeVisualContentA = new TypeVisualContent(1L, "Java"); TypeVisualContent typeVisualContentB = new TypeVisualContent(2L, "Sql"); TypeVisualContent typeVisualContentC = new TypeVisualContent(3L, "Docker"); @BeforeEach void setUp() { allTypeVisualContent.add(typeVisualContentA); allTypeVisualContent.add(typeVisualContentB); allTypeVisualContent.add(typeVisualContentC); } @Test void itShouldGetAllTypeVisualContentHappyCase() throws Exception { //given given(typeVisualContentServiceImplementation.getAllTypeVisualContent()).willReturn(allTypeVisualContent); //when controller.getAllTypeVisualContent(); //then then(typeVisualContentServiceImplementation).should().getAllTypeVisualContent(); assertEquals(3, allTypeVisualContent.size()); mockMvc.perform(get("/type-visual-content/getall")) //.andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) //.andExpect(jsonPath("$.status", is("OK"))) .andExpect(jsonPath("$.body", hasSize(3))); } } @Nested public class itShouldGetTypeVisualContentByIdCases{ Long idA = 1L; TypeVisualContent typeVisualContentA = new TypeVisualContent(1L, "Java"); @BeforeEach void setUp() { } @Test void itShouldGetTypeVisualContentByIdHappyCase() throws Exception { //given given(typeVisualContentServiceImplementation.getTypeVisualContentById(anyLong())).willReturn(Optional.of(typeVisualContentA)); //when controller.getTypeVisualContentById(idA); //then then(typeVisualContentServiceImplementation).should().getTypeVisualContentById(anyLong()); //assertEquals(3, allTypeVisualContent.size()); mockMvc.perform(get("/api/v1/type-visual-content/get/byid/1")) //.andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)); //.andExpect(jsonPath("$.status", is("OK"))); } } @Nested public class itShouldSaveTypeVisualContentCase{ TypeVisualContent toCreateTypeVisualContent = new TypeVisualContent("java"); TypeVisualContent createdTypeVisualContent = new TypeVisualContent(1L,"java"); @Test void itShouldSaveTypeVisualContentHappyCase() throws Exception { //given given(typeVisualContentServiceImplementation.saveTypeVisualContent(toCreateTypeVisualContent)) .willReturn(createdTypeVisualContent); //when controller.saveTypeVisualContent(toCreateTypeVisualContent); //then then(typeVisualContentServiceImplementation).should().saveTypeVisualContent(any(TypeVisualContent.class)); // mockMvc.perform(post("/api/v1/type-visual-content/save")) // .andExpect(content().contentType(MediaType.APPLICATION_JSON)); } } @Nested public class itShouldDeleteTypeVisualContentByIdCase{ @Test void itShouldTypeVisualContentByIdHappyCase() throws Exception { //given Long id = 1L; String responseService = "OK"; given(typeVisualContentServiceImplementation.deleteTypeVisualContentById(anyLong())).willReturn(responseService); //when controller.deleteTypeVisualContentById(id); //then then(typeVisualContentServiceImplementation).should().deleteTypeVisualContentById(id); mockMvc.perform(delete("/api/v1/type-visual-content/delete/byid/"+id)) .andExpect(content().contentType(MediaType.APPLICATION_JSON)); } } }<file_sep>/src/main/java/dev/protobot/blogrestapi/model/AuthorCertificate.java package dev.protobot.blogrestapi.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "AuthorCertificate") public class AuthorCertificate { @Id private Long id; private String code; @Column(name = "idAuthor") private Long idAuthor; public AuthorCertificate(Long id, String code, Long idAuthor) { this.id = id; this.code = code; this.idAuthor = idAuthor; } public AuthorCertificate(String code, Long idAuthor) { this.code = code; this.idAuthor = idAuthor; } public AuthorCertificate() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public Long getIdAuthor() { return idAuthor; } public void setIdAuthor(Long idAuthor) { this.idAuthor = idAuthor; } } <file_sep>/src/main/resources/sql/tables/ImageContent.sql CREATE TABLE ImageContent( idPost INT, idTypeVisualContent INT, imageUrl VARCHAR(300), publicId VARCHAR(300), PRIMARY KEY (idPost), FOREIGN KEY (idPost) REFERENCES Post(id), FOREIGN KEY (idTypeVisualContent) REFERENCES TypeVisualContent(id) );<file_sep>/src/main/resources/sql/tables/Post.sql CREATE TABLE Post( id INT IDENTITY(1,1), title VARCHAR(300) NOT NULL UNIQUE, dates DATETIME NOT NULL, description VARCHAR(1699) NOT NULL UNIQUE, idCategory INT NOT NULL, idTypeVisualContent INT NOT NULL, idAuthor INT NOT NULL, PRIMARY KEY (id), FOREIGN KEY (idTypeVisualContent) REFERENCES TypeVisualContent (id), FOREIGN KEY (idCategory) REFERENCES Category(id), FOREIGN KEY (idAuthor) REFERENCES Author(id) );<file_sep>/src/main/resources/sql/tables/VideoContent.sql CREATE TABLE VideoContent( idPost INT, idTypeVisualContent INT, videoUrl VARCHAR(300), PRIMARY KEY (idPost), FOREIGN KEY (idPost) REFERENCES Post(id), FOREIGN KEY (idTypeVisualContent) REFERENCES TypeVisualContent(id) );<file_sep>/src/test/java/dev/protobot/blogrestapi/helper/shared/ConvertStringToLowerCaseTest.java package dev.protobot.blogrestapi.helper.shared; import dev.protobot.blogrestapi.exceptions.helper.shared.HelperStringCanNotHaveAnyNumberException; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.*; @ExtendWith(MockitoExtension.class) class ConvertStringToLowerCaseTest { @Mock CheckIfStringHaveNumber checkIfStringHaveNumber; @InjectMocks ConvertStringToLowerCase helper; @Test void itShouldCheckIfConvertToLowerCaseAllLetterHaveUpperCaseHappyCase() { //given String oldString = "ABC"; //when String stringConverted = helper.convert(oldString); //then assertEquals("abc", stringConverted); } @Test void itShouldCheckIfConvertToLowerCaseSomeLetterHaveUpperCaseHappyCase() { //given String oldString = "AbCdeF"; //when String stringConverted = helper.convert(oldString); //then assertEquals("abcdef", stringConverted); } @Test void itShouldCheckIfConvertToLowerCaseAnyLetterHaveUpperCaseHappyCase() { //given String oldString = "zxcvbnm"; //when String stringConverted = helper.convert(oldString); //then assertEquals(oldString, stringConverted); } @Test void itShouldCheckIfConvertToLowerCaseRa() { //given String oldString = "zxFv2bnM"; //when helper.convert(oldString); //then then(checkIfStringHaveNumber).should().check(oldString); } }<file_sep>/src/main/java/dev/protobot/blogrestapi/service/CategoryService.java package dev.protobot.blogrestapi.service; import dev.protobot.blogrestapi.model.Category; import java.util.List; import java.util.Optional; public interface CategoryService { List<Category> getAllCategory(); Optional<Category> getCategoryById(Long id); Category saveCategory(Category category); String deleteCategoryById(Long id); } <file_sep>/src/main/java/dev/protobot/blogrestapi/helper/shared/CheckIfNullOrZeroLong.java package dev.protobot.blogrestapi.helper.shared; import dev.protobot.blogrestapi.exceptions.helper.shared.HelperCheckIfNullOrZeroLongException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; @Service public class CheckIfNullOrZeroLong { Logger logger = LoggerFactory.getLogger(CheckIfNullOrZeroLong.class); public CheckIfNullOrZeroLong() { } public void check(Long longNumber){ logger.info("Checking if Null or Zero this " + longNumber); if(isZeroOrNull(longNumber)) throw new HelperCheckIfNullOrZeroLongException(); } private boolean isZeroOrNull(Long longNumber) { return !(longNumber != null && !longNumber.equals(0L)); } }<file_sep>/src/main/resources/sql/tables/PostLikesUser.sql CREATE TABLE PostLikesUser( id INT IDENTITY (1,1), idPost INT NOT NULL, idUser INT NOT NULL, PRIMARY KEY (id), FOREIGN KEY (idPost) REFERENCES Post(id), FOREIGN KEY (idUser) REFERENCES Users(id) );<file_sep>/src/main/java/dev/protobot/blogrestapi/model/PostLikesUser.java package dev.protobot.blogrestapi.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "PostLikesUser") public class PostLikesUser { @Id private Long id; @Column(name = "idPost") private Long idPost; @Column(name = "idUser") private Long idUser; public PostLikesUser(Long id, Long idPost, Long idUser) { this.id = id; this.idPost = idPost; this.idUser = idUser; } public PostLikesUser(Long idPost, Long idUser) { this.idPost = idPost; this.idUser = idUser; } public PostLikesUser() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getIdPost() { return idPost; } public void setIdPost(Long idPost) { this.idPost = idPost; } public Long getIdUser() { return idUser; } public void setIdUser(Long idUser) { this.idUser = idUser; } } <file_sep>/src/main/java/dev/protobot/blogrestapi/service/implementation/TypeVisualContentServiceImplementation.java package dev.protobot.blogrestapi.service.implementation; import dev.protobot.blogrestapi.model.TypeVisualContent; import dev.protobot.blogrestapi.service.TypeVisualContentService; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class TypeVisualContentServiceImplementation implements TypeVisualContentService { @Override public List<TypeVisualContent> getAllTypeVisualContent() { return null; } @Override public Optional<TypeVisualContent> getTypeVisualContentById(Long id) { return Optional.empty(); } @Override public TypeVisualContent saveTypeVisualContent(TypeVisualContent typeVisualContent) { return null; } @Override public String deleteTypeVisualContentById(Long id) { return null; } } <file_sep>/src/main/java/dev/protobot/blogrestapi/model/Post.java package dev.protobot.blogrestapi.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import java.time.Instant; @Entity @Table(name = "Post") public class Post { @Id private Long id; private String title; private String description; @Column(name = "idCategory") private Long idCategory; @Column(name = "idTypeVisualContent") private Long idTypeVisualContent; private Instant dates; @Column(name = "idAuthor") private Long idAuthor; public Post(Long id, String title, String description, Long idCategory, Long idTypeVisualContent, Instant dates, Long idAuthor) { this.id = id; this.title = title; this.description = description; this.idCategory = idCategory; this.idTypeVisualContent = idTypeVisualContent; this.dates = dates; this.idAuthor = idAuthor; } public Post(String title, String description, Long idCategory, Long idTypeVisualContent, Instant dates, Long idAuthor) { this.title = title; this.description = description; this.idCategory = idCategory; this.idTypeVisualContent = idTypeVisualContent; this.dates = dates; this.idAuthor = idAuthor; } public Post() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Long getIdCategory() { return idCategory; } public void setIdCategory(Long idCategory) { this.idCategory = idCategory; } public Long getIdTypeVisualContent() { return idTypeVisualContent; } public void setIdTypeVisualContent(Long idTypeVisualContent) { this.idTypeVisualContent = idTypeVisualContent; } public Instant getDates() { return dates; } public void setDates(Instant dates) { this.dates = dates; } public Long getIdAuthor() { return idAuthor; } public void setIdAuthor(Long idAuthor) { this.idAuthor = idAuthor; } } <file_sep>/src/main/java/dev/protobot/blogrestapi/model/Author.java package dev.protobot.blogrestapi.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "Author") public class Author { @Id private Long id; private String email; @Column(name = "name") private String fullName; @Column(name = "imageUrl") private String imageUrl; @Column(name = "publicId") private String publicId; public Author(Long id, String email, String fullName, String imageUrl, String publicId) { this.id = id; this.email = email; this.fullName = fullName; this.imageUrl = imageUrl; this.publicId = publicId; } public Author(String email, String fullName, String imageUrl, String publicId) { this.email = email; this.fullName = fullName; this.imageUrl = imageUrl; this.publicId = publicId; } public Author() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this.fullName = fullName; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getPublicId() { return publicId; } public void setPublicId(String publicId) { this.publicId = publicId; } }
b5e31a8fd0745e92c7cda6cf2212bdc4b45e7340
[ "Java", "SQL" ]
22
SQL
julioperezdev/blog-restapi
ba26582c6776934431ab35b1ac8db5348552474d
7f5f4179a987b60b46510bf5bc7d4b3ca9c01409
refs/heads/master
<file_sep><?php namespace Tests\Unit; use Tests\TestCase; class CarYearTest extends TestCase { /** * A basic unit test example. * * @return void */ public function testCarYearTest() { $car = factory(\App\Car::class)->make(); // $this->assertTrue(is_integer($car->year)); $this->assertInternalType("int", $car->year); } } <file_sep><?php namespace Tests\Unit; use Tests\TestCase; class CarMakeTest extends TestCase { /** * A basic unit test example. * * @return void */ public function testValidMakeTest() { $car = factory(\App\Car::class)->make(); $this->assertContains($car->make, ['toyota', 'ford', 'honda']); } } <file_sep><?php namespace Tests\Unit; use App\Car; use App\User; use Tests\TestCase; class CarCountTest extends TestCase { /** * A basic unit test example. * * @return void */ public function testCarCountTest() { $this->seed(); $carCount = Car::all()->count(); $this->assertEquals(50, $carCount); } } <file_sep><?php namespace Tests\Unit; use App\Car; use Tests\TestCase; class CartInsertTest extends TestCase { /** * A basic unit test example. * * @return void */ public function testCarInsertTest() { $AuniqueMakeString = 'Makeeeee00000'; $car = new Car(); $car->make = $AuniqueMakeString; $car->model = 'model'; $car->year = 1990; $car->save(); //taken from here : https://laravel.com/docs/5.8/database-testing $this->assertDatabaseHas('cars', [ 'make' => $AuniqueMakeString ]); } } <file_sep><?php namespace Tests\Unit; use App\User; use Tests\TestCase; class UserCountTest extends TestCase { /** * A basic unit test example. * * @return void */ public function testCountUsersTest() { // reference https://laravel-news.com/seeding-data-testing $this->seed(); $count = User::all()->count(); // Taken from here https://www.5balloons.info/laravel-tdd-beginner-crud-example/ $this->assertEquals(50, $count); } } <file_sep><?php namespace Tests\Unit; use Tests\TestCase; class UserUpdateToSteveSmithTest extends TestCase { /** * A basic unit test example. * * @return void */ public function testRenameTest() { // create some random data using the seeders $this->seed(); $newName = '<NAME>'; $user = \App\User::inRandomOrder()->first(); $user->name = $newName; $user->save(); //taken from here : https://laravel.com/docs/5.8/database-testing $this->assertDatabaseHas('users', [ 'name' => $newName ]); } } <file_sep><?php namespace Tests\Unit; use App\Car; use Tests\TestCase; class CarUpdateToYear2000 extends TestCase { /** * A basic unit test example. * * @return void */ public function testUpdateTo2kTest() { // make sure we have some data pre-seeded $this->seed(); $aCar = \App\Car::inRandomOrder()->first(); $aCar->year = 2000; $aCar->save(); $check = Car::find($aCar); $this->assertEquals(2000, $check->year); } } <file_sep><?php namespace Tests\Unit; use Tests\TestCase; class UserInsertTest extends TestCase { /** * A basic unit test example. * * @return void */ public function testInsertTest() { $email = '<EMAIL>'; $user = factory(\App\User::class)->make([ 'email' => $email ]); $user->save(); //taken from here : https://laravel.com/docs/5.8/database-testing $this->assertDatabaseHas('users', [ 'email' => $email ]); } } <file_sep><?php namespace Tests; use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Foundation\Testing\TestCase as BaseTestCase; abstract class TestCase extends BaseTestCase { use CreatesApplication; // reference https://laravel-news.com/seeding-data-testing use DatabaseTransactions; } <file_sep><?php namespace Tests\Unit; use App\User; use Tests\TestCase; class UserDeletionTest extends TestCase { /** * A basic unit test example. * * @return void */ public function testDeletionTest() { // unique email $email = '<EMAIL>'; $opts = [ 'email' => $email ]; $user = factory(\App\User::class)->make($opts); $user->save(); $user = User::where($opts)->first(); // let's check if it's saved $this->assertTrue($user != null); //taken from here : https://laravel.com/docs/5.8/database-testing $this->assertDatabaseHas('users', $opts); // Now delete it $user->delete(); // Try to find it again $user = User::where($opts)->first(); // Let's make sure it doesn't exist $this->assertNull($user); } } <file_sep><?php namespace Tests\Unit; use App\Car; use Tests\TestCase; class CarDeletionTest extends TestCase { /** * A basic unit test example. * * @return void */ public function testDeletionTest() { // make sure we have some data pre-seeded $this->seed(); $aCar = \App\Car::inRandomOrder()->first(); $id = $aCar->id; $aCar->delete(); $check = Car::find($id); $this->assertNull($check); } } <file_sep><?php namespace Tests\Unit; use Tests\TestCase; class CarModelTest extends TestCase { /** * A basic unit test example. * * @return void */ public function testCarModelTest() { $car = factory(\App\Car::class)->make(); $this->assertInternalType("string", $car->model); } }
ad675898620ed02dbe3e9815d41458970cd82ac2
[ "PHP" ]
12
PHP
ALopez201/MiniProject2
1e1e74f61f59687fe9f19e8aac903c3b9cc60e4d
9c435bbdd94442a5f526d802eb92239fceea27d2
refs/heads/master
<repo_name>ediezindell/js-cms<file_sep>/src/js/cms_view_modals/ServerInfoView.js var ServerInfoView = (function(){ var view; var v = {}; /* ---------- ---------- ---------- */ //初期化 function init(){ view = $('#ServerInfoView'); stageInit(); createlayout(); setBtn(); } /* ---------- ---------- ---------- */ //レイアウト作成・イベントアサイン function createlayout(){ v = ModalViewCreater.createBaseView(EmbedTagListView,view); var tag = "" tag += '<div class="_title">サーバー情報</div>' v.header.html(tag); tag = "" tag += '<div class="_cms_btn _btn_close">閉じる</div> '; v.footer.html(tag) setBtn(); } function setBtn(){ view.find('._bg ,._btn_close').click(function(){ stageOut() }); } /* ---------- ---------- ---------- */ //個別処理 function render(){ var u = "storage.php?action=info"; var tag = ""; // tag += '<div class="_h2">PHP INFO</div>' tag += '<div class="_p"><iframe id="myFrame" class="" src ="'+u+'" ></iframe></div>' tag += '<div style="text-align:right;"><a href="'+u+'" target="_blank">別ウィンドウで見る <i class="fa fa-external-link-square "></i></a></div>' // tag += '<div class="_h2">その他</div>' if(window.IS_ESCAPE_WAF){ tag += '<div class="_p _anno">' tag += '<b>WAF機能が有効です</b><br>' tag += 'このサーバーはWAF機能が有効のため、WAF機能を回避するモードで動作しています。<br>' tag += 'その場合、通常より保存・公開処理にかかる時間が少し増えます。<br>' tag += '</div>' tag += '<div class="_p"><b>WAF機能をOFF (無効) にするには</b><br>' tag += 'レンタルサーバーを利用であれば、各サーバー会社さまの管理画面より、WAF機能をOFFにしてください。<br>'; tag += '( OFFにしても、反映されるまで5分〜1時間程度、時間がかかります )<br>'; tag += '独自サーバーの場合は、サーバー管理者に相談してください。'; tag += '</div>' } else{ tag += '<div class="_p">とくにありません</div>' } v.body.html(tag); } /* ---------- ---------- ---------- */ //表示・非表示処理 var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } function stageIn(){ if(! isOpen){ isOpen = true; view.show(); if(isFirst){ render() } isFirst = false; } } function stageOut(){ if(isOpen){ isOpen = false; view.hide(); } } return { init:init, stageIn:stageIn, stageOut:stageOut } })(); <file_sep>/src/js/cms_stage_asset/CMS_Asset_FileEditorView.js var CMS_Asset_FileEditorView = (function(){ var view; var v = {}; function init(){ view = $('#CMS_Asset_FileEditorView'); } /* ---------- ---------- ---------- */ function _getID (_id,_dir){ return CMS_AssetDB.getID(_id,_dir) } function _has (){ return CMS_AssetDB.hasCurrent(); } function _getCurrent (){ return CMS_AssetDB.getCurrentPage(); } function _has_ps (_id,_dir){ for (var i = 0; i < _ps.length ; i++) { var id1 = _getID(_id,_dir); var id2 = _getID(_ps[i].id,_ps[i].dir); if(id1 == id2)return true; } return false; } /* ---------- ---------- ---------- */ function save (){ if(isOpen){ if(_has()) _getCurrent().saveData(); } } /* ---------- ---------- ---------- */ var _ps = []; var _current; function openPage (_param){ if(_param == undefined) { if(_current == undefined)return; _param = _current; } //ページ作成 if(_has_ps(_param.id,_param.dir) == false){ _ps.push(new CMS_Asset_FileEditorClass( view , _param)); } _current = _param; //前のページは非表示にして、現在のページを表示 if(_has()) _getCurrent().stageOut(); for (var i = 0; i < _ps.length ; i++) { var id1 = _getID(_param.id,_param.dir) var id2 = _getID(_ps[i].id,_ps[i].dir) if(id1 == id2) _ps[i].stageIn(_param.extra);//extra } } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } function stageIn(_param){ // if(! isOpen){ isOpen = true; view.show(); openPage(_param); // } } function stageOut(){ // if(isOpen){ isOpen = false; view.hide(); // } } /* ---------- ---------- ---------- */ function getH(){ return view.height(); } return { init: init, stageIn: stageIn, stageOut: stageOut, save: save, getH: getH } })();<file_sep>/src/js/cms_main/CMS_LOCK.js var CMS_LOCK = (function(){ var view; var v = {}; function init(){ view = $('#CMS_LOCK'); stageInit(); stageIn(); createlayout(); setBtn(); window.isLocked = CMS_LOCK.getIsLocked; if(USE_EDIT_LOCK == false){ v.btn_lock.hide(); v.btn_unlock.hide(); window.isLocked = function(){ return false; } } // if(window.location.href.indexOf("http://192.168.1.23:999") == 0){ // setIsLocked(false); // return; // } setIsLocked(true); } /* ---------- ---------- ---------- */ function createlayout(){ var tag = "" tag += '<div class="_btn _btn_lock " '+TIP("#+L","R")+'><i class="fa fa-lock "></i><span>ロック</span></div>'; tag += '<div class="_btn _btn_unlock "'+TIP("#+L","R")+'><i class="fa fa-unlock-alt "></i><span>ロック</span></div>'; view.html(tag); } function setBtn(){ v.btn_lock = view.find('._btn_lock'); v.btn_lock.click(function(){ setIsLocked(false) }); v.btn_unlock = view.find('._btn_unlock'); v.btn_unlock.click(function(){ setIsLocked(true) }); } /* ---------- ---------- ---------- */ var isLocked = true; function getIsLocked(_b){ if(! USE_EDIT_LOCK )return; if(isLocked){ if(_b){ CMS_AlertLockView.stageIn() } } return isLocked; } function setIsLocked_toggle(){ if(! USE_EDIT_LOCK )return; setIsLocked((isLocked) ? false:true); } function setIsLocked(_b){ if(! USE_EDIT_LOCK )return; isLocked = _b; if(_b){ view.removeClass("_unlock"); } else{ view.addClass("_unlock"); } isLocked = _b; } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } function stageIn(){ if(! isOpen){ isOpen = true; view.show(); if(isFirst){} isFirst = false; } } function stageOut(){ if(isOpen){ isOpen = false; view.hide(); } } return { init: init, stageIn: stageIn, stageOut: stageOut, getIsLocked: getIsLocked, setIsLocked: setIsLocked, setIsLocked_toggle: setIsLocked_toggle } })(); <file_sep>/src/js/cms_model/PageElement.object.share.js PageElement.object.share = (function(){ var _ = new PageModel.Object_(); /* ---------- ---------- ---------- */ _.pageInfo = new PageModel.Object_Info({ id : "object.share", name : "シェアボタン", name2 : "", inputs : ["CLASS","CSS","DETAIL"], // cssDef : {file:"block",key:"[シェアボタンブロック]"} cssDef : {selector:".cms-socials"} }); /* ---------- ---------- ---------- */ _.grids = [ /* ---------- ---------- ---------- */ new PageModel.Object_Grid({ gridType:Dic.GridType.BASE, gridInfo:new PageModel.OG_info({ id : "list", name : "シェアボタン", note : "" }), textData:{ info:new PageModel.OG_SubInfo({ name: "ボタンの種類", note: "" }), cells:[ new PageModel.OG_Cell( { id:"facebook_share", name:"Facebook シェアボタン", type:CELL_TYPE.CHECK , def:"1" }), new PageModel.OG_Cell( { id:"facebook", name:"Facebook いいねボタン", type:CELL_TYPE.CHECK , def:"1" }), new PageModel.OG_Cell( { id:"twitter", name:"Tweetボタン", type:CELL_TYPE.CHECK , def:"1" }), new PageModel.OG_Cell( { id:"plus", name:"Google Plusボタン", type:CELL_TYPE.CHECK , def:"1" }), new PageModel.OG_Cell( { id:"hatena", name:"はてなブックマークボタン", type:CELL_TYPE.CHECK , def:"1" }), new PageModel.OG_Cell( { id:"pocket", name:"Pocketボタン(あとで読む系のサービス)", type:CELL_TYPE.CHECK , def:"1" }) ] }, gridData:null }), /* ---------- ---------- ---------- */ new PageModel.Object_Grid({ gridType:Dic.GridType.BASE, gridInfo:new PageModel.OG_info({ id : "param", name : "", note : "" }), textData:{ info:new PageModel.OG_SubInfo({ name: "ボタンの設定", note: "" }), cells:[ new PageModel.OG_Cell({ id: "select", name: "サイズ", type: CELL_TYPE.SELECT, vals: [ ["M","Mサイズ","1"], ["L","Lサイズ","0"] ], view: "", def: "1" }), new PageModel.OG_Cell({ id: "url_input", name: "シェアするURL", type: CELL_TYPE.SINGLE, style:SS.w400, note:(function(){ var s = "" s += '何も入力しない場合は、個々のページのURLがシェア設定されます。<br>' s += '例えば、個々のページURLではなく、サイトトップのURLを個別のページでシェアしたい場合は、URLを入力してください。<br>' return s; })() }), new PageModel.OG_Cell({ id: "title", name: "シェアするタイトル名", type: CELL_TYPE.SINGLE, style:SS.w200, note:(function(){ var s = "" s += '何も入力しなければ、個々のページHTMLのタイトルタグの値が使用されます。<br>' s += 'サイトトップのURLを指定した場合などに、サイトタイトルを設定したりします。' return s; })() }), new PageModel.OG_Cell( { id:"preview", name:"シェア情報(タイトルとURL)を表示", type:CELL_TYPE.CHECK , style:"", view:"", def:"1" }) ] }, gridData:null }) /* ---------- ---------- ---------- */ ] _.getInitData = function(){ var o = {}; o.type = _.pageInfo.id; o.data = { list: { texts: { facebook_share: "1", facebook: "1", twitter: "1", plus: "1", hatena: "1", pocket: "1" }, grid: [] }, param: { texts: { select: "M", url: "PAGE", url_input: "" }, grid: [] } } o.attr = {css:"default"}; o.attr.class = o.attr.css; return o; } _.getPreview = function(_o){ var data = _o.data; var attr = _o.attrs; var tag = ""; attr = attr.split('class="').join('class="cms-socials clearfix '); tag += '<div '+attr+'>\n' tag += '<ul class="clearfix">\n' if(data.list.texts.facebook_share){ if(data.param.texts.select == "M"){ tag += ' <li><div class="_share ss_share _fs_m"></div></li>'; } else { tag += ' <li><div class="_share ss_share _fs_l"></div></li>'; } } if(data.list.texts.facebook){ if(data.param.texts.select == "M"){ tag += ' <li><div class="_share ss_share _f_m"></div></li>'; } else { tag += ' <li><div class="_share ss_share _f_l"></div></li>'; } } if(data.list.texts.twitter){ if(data.param.texts.select == "M"){ tag += ' <li><div class="_share ss_share _t_m"></div></li>'; } else { tag += ' <li><div class="_share ss_share _t_l"></div></li>'; } } if(data.list.texts.plus){ if(data.param.texts.select == "M"){ tag += ' <li><div class="_share ss_share _g_m"></div></li>'; } else { tag += ' <li><div class="_share ss_share _g_l"></div></li>'; } } if(data.list.texts.hatena){ if(data.param.texts.select == "M"){ tag += ' <li><div class="_share ss_share _h_m"></div></li>'; } else { tag += ' <li><div class="_share ss_share _h_l"></div></li>'; } } if(data.list.texts.pocket){ if(data.param.texts.select == "M"){ tag += ' <li><div class="_share ss_share _p_m"></div></li>'; } else { tag += ' <li><div class="_share ss_share _p_l"></div></li>'; } } tag += ' <li style="color:#888;padding:5px 0 0 0;font-size:10px;"></li>'; tag += '</ul>'; tag += '<div style="color:red;margin:10px 0 0 0;font-size:12px;">※ボタンは仮表示です。ページを公開して、確認してください。</div>'; var ss = (data.param.texts.url_input) ? data.param.texts.url_input :"現在のページのURL"; tag += '<div style="color:#888;margin:10px 0 0 0;font-size:12px;">シェアされるURL:'+ ss +'</div>'; tag += '</div>'; return tag; } _.getHTML = function(_o){ var data = _o.data; var attr = _o.attrs; attr = attr.split('class="').join('class="cms-socials clearfix '); var s = []; if(data.list.texts.twitter) s.push("twitter"); if(data.list.texts.plus) s.push("plus"); if(data.list.texts.facebook) s.push("facebook"); if(data.list.texts.facebook_share) s.push("facebook_share"); if(data.list.texts.hatena) s.push("hatena"); if(data.list.texts.pocket) s.push("pocket"); var url ="" if(data.param.texts.url_input){ url = data.param.texts.url_input; } var title = "" if(data.param.texts.title){ title = data.param.texts.title; } var preview = "" if(data.param.texts.preview){ preview = "1" } var tag = "" tag = '<div '+attr+' data-share="{DATA}" data-size="{SIZE}" data-url="{URL}" data-title="{TITLE}" data-preview="{PREVIEW}"></div>\n' tag = tag.split("{DATA}").join(s.join(",")); tag = tag.split("{SIZE}").join(data.param.texts.select); tag = tag.split("{URL}").join(url); tag = tag.split("{TITLE}").join(title); tag = tag.split("{PREVIEW}").join(preview); tag += '<script>\n' tag += '$(function(){\n'; tag += ' $(".cms-socials").cms_socials();\n'; tag += '});\n' tag += '</script>\n' return tag; } /* ---------- ---------- ---------- */ return _; })(); <file_sep>/src/js/cms_view_floats/InputCnadidate.js var InputCnadidate = (function(){ var view function init(){ view = $("#InputCnadidate"); $(document).on("click","._candidate_item",function(){ clickItem($(this).data("val")); }) $(document).on("focus","input[data-candidate]",function(){ stageIn($(this)); }); $(document).on("click","input[data-candidate]",function(){ stageIn($(this)); }); // $(document).on("mouseout","input[data-candidate]",function(){ // stageOut_delay(); // }); view.on("mouseover",function(){ clearTimer(); }); view.on("mouseout",function(){ stageOut_delay(); }); stageInit(); } /* ---------- ---------- ---------- */ var currentTar function showList(_tar){ if(!_tar.data("candidate"))return; var id = _tar.data("candidate"); var ls = InputCnadidateDic.getList(id) if(!ls)return; currentTar = _tar; var tag = "" for (var i = 0; i < ls.length ; i++) { if(ls[i][1] == "") ls[i][1] = ls[i][0]; tag += '<div class="_candidate_item" data-val="'+ls[i][1]+'">' + ls[i][0] + '</div>' } // view.css({ // top:_tar.offset().top + 18, // left:_tar.offset().left + 30 // }) view.html(tag); _tar.parent().css("position","relative").append(view); // _tar.parent().css("border","solid 1px #888").append(view); } /* ---------- ---------- ---------- */ function clickItem(_val){ if(!currentTar)return; if(_val == "")return; if(_val == undefined)return; if(_val == "--"){ currentTar.val("").keyup(); } else{ currentTar.val(_val).keyup(); } stageOut(); } /* ---------- ---------- ---------- */ //表示・非表示処理 var isOpen = false; // var isFirst = true; function stageInit(){ view.hide(); } function stageIn(_tar){ stageOut(); if(! isOpen){ isOpen = true; // if(isFirst){} // isFirst = false; view.show(); showList(_tar); } } var tID; function clearTimer(){ if(tID) clearTimeout(tID); } function stageOut_delay(){ clearTimer(); tID = setTimeout(function(){ stageOut(); },200); } function stageOut(){ clearTimer(); if(isOpen){ isOpen = false; view.hide(); } } return { init: init, stageIn: stageIn, stageOut: stageOut } })(); var InputCnadidateDic = (function(){ var dic = {} dic._cms_image_width = [ ["100%",""], ["50%",""], ["25%",""], ["600px",""], ["400px",""], ["200px",""], ["100px",""], ["リセット","--"] ] dic._cms_image_ratio = [ ["1:1",""], ["2:1",""], ["2:3",""], ["3:2",""], ["16:9",""] , ["リセット","--"] ] dic._cms_images_margin = [ ["0",""], ["0 10px 10px 0",""], ["0 20px 20px 0",""], ["リセット","--"] ] dic._cms_text_size = [ ["10px",""], ["12px",""], ["14px",""], ["16px",""], ["18px",""], ["24px",""], ["32px",""], ["42px",""], ["60px",""], ["80px",""], ["120px",""], ["リセット","--"] ] dic._cms_text_align = [ ["left",""], ["center",""], ["right",""], ["リセット","--"] ] dic._cms_line_heiht = [ ["1",""], ["1.2",""], ["1.4",""], ["1.6",""], ["1.8",""], ["2",""], ["リセット","--"] ] dic._cms_box_round = [ ["2px",""], ["5px",""], ["10px",""], ["5%",""], ["10%",""], ["25%",""], ["50%",""], ["リセット","--"] ] dic._cms_border_w = [ ["1px",""], ["2px",""], ["4px",""], ["リセット","--"] ] dic._cms_text_bold = [ ["太字","bold"], ["リセット","--"] ] dic._cms_text_font = [ ["明朝体","serif"], ["ゴシック体","sans-serif"], ["筆記体","cursive"], ["装飾体","fantasy"], ["等幅体","monospace"], ["リセット","--"] ] dic._cms_text_sdw = [ ["1","1"], ["2","2"], ["4","4"], ["8","8"], ["16","16"], ["32","32"], ["リセット","--"] ] function getList(_v){ if(!dic)return; if(!dic[_v])return; return dic[_v]; } return { getList:getList } })(); var ColorPickerView = (function(){ var view; var v = {}; /* ---------- ---------- ---------- */ //初期化 function init(){ view = $('#ColorPickerView'); stageInit(); createlayout(); setBtn(); } /* ---------- ---------- ---------- */ //レイアウト作成・イベントアサイン function createlayout(){ var tag = ''; tag += '<div class="_color_preview">***</div>'; tag += '<canvas id="CMS_ColorCanvas" width="255" height="181"></canvas>'; tag += '<div class="_btn_reset">色をクリア</div>'; view.append(tag); v.color_preview = view.find("._color_preview"); v.btn_reset = view.find("._btn_reset"); v.btn_reset.click(function(){ reset() }); initCanvas(); } var currentSel; function setBtn(){ $(document).on("focus","input._colorPicker",function(){ currentSel = $(this); previewColor(currentSel.val()); stageIn(currentSel,function(_val){ currentSel.val(_val).keyup(); stageOut(); }); }); $(document).on("click","input._colorPicker",function(){ currentSel = $(this); previewColor(currentSel.val()); stageIn(currentSel,function(_val){ currentSel.val(_val).keyup(); stageOut(); }); }) $(document).on("mouseout","input._colorPicker",function(){ stageOut_delay(); }); view.on("mouseover",function(){ clearTimer(); }); view.on("mouseout",function(){ stageOut_delay(); }); } /* ---------- ---------- ---------- */ //個別処理 var canvas; var ctx; function initCanvas(){ canvas = document.getElementById("CMS_ColorCanvas"); ctx = canvas.getContext("2d"); var image = new Image(); image.src = "./images/colorlist.png"; image.onload = function(){ ctx.clearRect(0, 0, canvas.width, canvas.height); var x = (canvas.width - image.width) / 2; var y = (canvas.height - image.height) / 2; ctx.drawImage(image, x, y); }; canvas.onclick = function(e){ selectColor(getColor(e)); } canvas.onmousemove = function(e){ previewColor(getColor(e)); } } function getColor(e) { var x = parseInt(e.offsetX); var y = parseInt(e.offsetY); var imagedata = ctx.getImageData(x, y, 1, 1); return rgba2hex(imagedata.data[0],imagedata.data[1],imagedata.data[2]); } function previewColor(_val) { v.color_preview.css( { background : _val } ); v.color_preview.html( _val ); } function selectColor(_val) { if(cb){ cb(_val); } } function rgba2hex(r,g,b) { r = r.toString(16); if (r.length == 1) r = "0" + r; g = g.toString(16); if (g.length == 1) g = "0" + g; b = b.toString(16); if (b.length == 1) b = "0" + b; return '#' + r + g + b; } /* ---------- ---------- ---------- */ function reset() { currentSel.val("").keyup(); stageOut(); } /* ---------- ---------- ---------- */ function showList(_tar) { view.css({ top:_tar.offset().top + 22, left:_tar.offset().left }) } /* ---------- ---------- ---------- */ //表示・非表示処理 var isOpen = false; var isFirst = true; var cb; function stageInit(){ view.hide(); } function stageIn(_tar,_cb){ if(! isOpen){ isOpen = true; view.show(); if(isFirst){} isFirst = false; cb = _cb; showList(_tar); } } var tID; function clearTimer(){ if(tID) clearTimeout(tID); } function stageOut_delay(){ clearTimer(); tID = setTimeout(function(){ stageOut(); },200); } function stageOut(){ clearTimer(); if(isOpen){ isOpen = false; view.hide(); } } return { init:init, stageIn:stageIn, stageOut:stageOut } })(); <file_sep>/src/js/cms_data/CMS_Data.MyTag.p3.js CMS_Data.MyTagU = (function(){ //Myタグ定義のJSONから、Myタグ定義リストを作成する。 //グローバル、ローカル共に、コールされる function parseData(_json) { var a = []; if(_json["body"] == undefined) return a; if(_json.body["free"] == undefined) return a; var ls = _json.body.free[0].data; for (var i = 0; i < ls.length ; i++) { if(ls[i].type == "replace.div"){ var id = ls[i].attr.replaceID; var label = ls[i].attr.replaceTitle; var o = { type:"tag", id:id, label:label, val:ls[i].data } a.push(o); } if(ls[i].type == "object.replaceTexts"){ //テキストリスト if(ls[i].data.texts){ var trs = ls[i].data.texts.grid; for (var ii = 0; ii < trs.length ; ii++) { if(trs[ii].publicData){ var s = CMS_TagU.convertCellBR( trs[ii]["val"] ); var o = { type : "text", id : trs[ii]["id"], label : trs[ii]["val"], val : s } a.push(o); } } } //画像リスト if(ls[i].data.images){ var trs = ls[i].data.images.grid; for (var ii = 0; ii < trs.length ; ii++) { if(trs[ii].publicData){ var o = { type : "image", id : trs[ii]["id"], label : "", val : trs[ii]["val"], extra : { isTag:trs[ii].isTag } } o.label = _getImageTag(o,false); a.push(o); } } } //リンクリスト if(ls[i].data.links){ var trs = ls[i].data.links.grid; for (var ii = 0; ii < trs.length ; ii++) { if(trs[ii].publicData){ var o = { type : "link", id : trs[ii]["id"], label : "", val : trs[ii]["val"], extra : { isTag:trs[ii].isTag } } o.label = _getAnchorTag(o,false); a.push(o); } } } } } return a; } //置換え処理メイン function getReplaceTag(_temp, _keys){ if(!_keys) return _temp; for (var i = 0; i < _keys.length ; i++) { var key = "{{" + _keys[i].id + "}}"; if(_temp.indexOf(key) != -1){ var type = _keys[i].type var vals = _keys[i].val; var _s = ""; if( type == "text"){ _s = vals; } else if(type == "image"){ _s = _getImageTag(_keys[i],true); } else if(type == "link"){ _s = _getAnchorTag(_keys[i],true); } else if(type == "tag"){ //myタグ-コンテナ for (var n = 0; n < vals.length ; n++) { _s += PageElement_HTMLService.getTag(vals[n]); } } _temp = _temp.split(key).join(_s); } } return _temp; } function _getImageTag(_param,_isPub){ var tag = ""; if(_param.extra.isTag == "path"){ if(_param.val.mode == "simple"){ tag = CMS_Path.MEDIA.getImagePath(_param.val.path , _isPub ); } } else{ var w = _isPub ? _param.val.width : "50px"; tag = CMS_ImgBlockU.getImageTag({ path : _param.val.path, isPub : _isPub, width : w, ratio : _param.val.ratio, alt : "", attr : "" }); } tag = tag.split("\n").join(""); return tag; } function _getAnchorTag(_param,_isPub){ var tag = ""; if(_param.extra.isTag == "path"){ tag = CMS_Path.MEDIA.getAnchorPath( _param.val.href , _isPub ); } else if(_param.extra.isTag == "attr"){ tag = getAnchorAttr(_param.val,_isPub); } else { tag = CMS_AnchorU.getAnchorTag( _param.val,"",_isPub); } return tag; } function getAnchorAttr(_link,_isPub){ var tag = "" var href = CMS_Path.MEDIA.getAnchorPath( _link.href , _isPub ); tag += 'href="'+href+'" '; var tar = _link.target; if(tar) tag += 'target="'+tar+'" '; return tag; } return { parseData:parseData, getReplaceTag:getReplaceTag, getAnchorAttr:getAnchorAttr } })(); //ひな形ブロックの置換え処理で、一時的に状態の管理を行う CMS_Data.HinagataSearvice = (function(){ var list; function setState(_list){ list = _list; } function reset(){ list = null; } function trace(){ console.log(list); } function getJSParam(){ var o = []; if(list){ for (var i = 0; i < list.length ; i++) { o[list[i].id] = list[i].val; } } var pageTags = HTMLServiceU.getCurrentReplaceTags(); for (var n in pageTags) { o[n] = pageTags[n]; } return o; } //tag.jsからもコールされる function replace(_s,_type){ if(!list) return _s; if(typeof _s === "string"){ for (var i = 0; i < list.length ; i++) { var id = list[i].id.split(" ").join(""); var val = list[i].val; _s = _s.split(id).join( CMS_TagU.t_2_tag(val) ); } } return _s; } return{ setState: setState, getJSParam:getJSParam, reset: reset, trace:trace, replace:replace, } })(); CMS_Data.PageTag = (function(){ var list = [ { label:"編集内容", items:[ { id:"PAGE_CONTENTS",text:"公開ページで確認してください", label:"HTMLページの編集内容をHTMLに変換した値 ", } ] }, { label:"ディレクトリ情報", items:[ { id:"SITE_DIR", text:"../",label:"HTMLページから見た、サイトルートのパス<br>リンクや画像を直書きするときに、パスの抽象化を行えます。" }, { id:"ASSET_DIR", text:"html/",label:"HTMLページから見た、アセットファイルのパス" }, { id:"DEF_DIR", text:"html/",label:"HTMLページから見た、サイトディレクトリのパス" } ] }, { label:"ページ関連", items:[ { id:"PAGE_DIR", text:"/html/",label:"サイトルートから見た、HTMLページのディレクトリのパス" }, { id:"PAGE_ID", text:"company_outline",label:"HTMLページのページID" }, { id:"PAGE_NAME", text:"会社概要",label:"HTMLページのページ名" }, { id:"PAGE_GROUP_IDS", text:"company company_sub",label:"HTMLページが所属しているグループのID(複数)" }, { id:"PAGE_GROUP_IDS[0]", text:"company" ,label:"PAGE_GROUP_IDSの1つめの値" }, { id:"PAGE_GROUP_IDS[1]", text:"company_sub" ,label:"PAGE_GROUP_IDSの2つめの値" }, { id:"PAGE_GROUP_IDS[2]", text:"" ,label:"PAGE_GROUP_IDSの3つめの値" }, { id:"PAGE_GROUP_NAMES", text:"会社について,our company",label:"HTMLページが所属しているグループの名称(複数)" }, { id:"PAGE_BREADLIST", text:"公開ページで確認してください",label:"パンくずリスト" } ] }, { label:"ブログ関連", items:[ { id:"PAGE_TAG", text:"",label:"ページに登録されている分類用タグ名" }, { id:"PAGE_READ", text:"",label:"ページに登録されているページ説明" }, { id:"PAGE_DATE", text:"",label:"ページに登録されている日付" } ] }, { label:"その他", items:[ { id:"PAGE_PUB_DATE", text:"2016/07/15 23:37:46",label:"HTMLが公開された日付" } //{ id:"PAGE_TEMPLATE", text:"default.html",label:"HTMLのテンプレートファイルのパス" } ] } ] function getData() { return list; } return { getData:getData } })(); <file_sep>/src/js/cms_stage_page/CMS_PageListViewTree.js var CMS_PageListViewTree = (function(){ var view; var v = {}; function init(){ view = $('#CMS_PageListViewTree'); stageInit(); } /* ---------- ---------- ---------- */ //サイトマップデータロード function loadSitemapData (){ loadDirManager(); } /* ---------- ---------- ---------- */ //#サイトマップのフォルダ開閉状態のメモリ var listOpenManager //ロード function loadDirManager(){ listOpenManager= new Storage.Local("cms_listOpenManager",[]); listOpenManager.load(function(){ showSitemap(); }); } //保存 function saveDirManager(){ var dirs = $('._subDir'); var list = []; for (var i = 0; i < dirs.length ; i++) { list[i] = [ dirs.eq(i).attr("id"), 1 ]; if(dirs.eq(i).attr("data-isOpen") == "0") list[i][1] = 0; } listOpenManager.setData(list); listOpenManager.save(function(){}); CMS_StatusFunc.setSitemapDirOpens(listOpenManager.getData()); } /* ! ---------- ---------- ---------- ---------- ---------- */ function editSubFiles(){ filelist.editSubFiles() } function publishAll(){ filelist.publishAll() } /* ! ---------- ---------- ---------- ---------- ---------- */ var filelist; function showSitemap(){ //開閉リストを登録 CMS_StatusFunc.setSitemapDirOpens(listOpenManager.getData()); filelist = new CMS_PageList_ListClass(); filelist.registParent(this,view,0); filelist.initData(CMS_Data.Sitemap.getData(),0); //CMS_MainController.openPage(); view.scrollTop(Storage.Memo.getSideMenuY()) setTimeout(function(){ isSaveable = true; },500); } //ファイル名変更 function changeFileName(_edited,_original){ if(_edited.id != _original.id || _edited.dir != _original.dir){ if(isLog)console.log("●changeFileName : " + _original.id + " > " + _edited.id ); Storage.Util.rename(_original , _edited); } UpdateDelay.delay(function(){ CMS_MainController.removePage(_original.id,_original.dir); CMS_MainController.openPage_by_id(_edited.id,_edited.dir); }) } //ファイル削除 function deleteFile(_edited){ //削除 if(isLog)console.log("●deleteFile : " + _edited.id ); Storage.Util.delete_(_edited); UpdateDelay.delay(function(){ CMS_MainController.removePage(_edited.id,_edited.dir); CMS_MainController.openIntroPage(); }) } //アップデート var isSaveable = false function updatedSitemap(){ if(!isSaveable) return; CMS_Data.Sitemap.save(); // Float_Preview.updateSitemapDate() } /* ---------- ---------- ---------- */ //ページを開く function openPage_(){ //CMS_MainController.openPage(_param); } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } function stageIn(){ if(! isOpen){ isOpen = true; view.show(); if(isFirst){ loadSitemapData(); } isFirst = false; } } function stageOut(){ if(isOpen){ isOpen = false; view.hide(); } } return { init:init, stageIn:stageIn, stageOut:stageOut , openPage_ :openPage_, updatedSitemap :updatedSitemap, changeFileName :changeFileName, deleteFile :deleteFile, saveDirManager:saveDirManager, editSubFiles:editSubFiles, publishAll:publishAll } })(); <file_sep>/src/js/cms_model/PageElement.tag.js PageElement.tag = {}<file_sep>/src/js/cms_model/PageElement.layout.cols.js PageElement.layout.cols = (function(){ var _ = new PageModel.Tag_(); /* ---------- ---------- ---------- */ _.pageInfo = new PageModel.Object_Info({ id : "layout.cols", name : "段組み", name2 : "<TABLE>", inputs : ["CLASS","CSS"], cssDef : {selector:".cms-column"} }); /* ---------- ---------- ---------- */ _.getInitData = function(_param){ var _p = PageElement_JText.P; var n = Number(_param); var o = {}; o.type = _.pageInfo.id; o.data = []; o.attr ={css:"col-p40",class:"col-p40"} for (var i = 0; i < n ; i++) { o.data.push({ type: "layout.div", attr: { style: "" }, data: [{ type: "tag.p", attr: { "class": "default", css: "default" }, data: _p }] }); } return o; } /* ---------- ---------- ---------- */ _.getPreview = function(_o){ return ""; } /* ---------- ---------- ---------- */ _.getHTML = function(_o,_tab){ return ""; } /* ---------- ---------- ---------- */ return _; })();<file_sep>/src/js/cms_view_modals/MiniEditer.js var MiniEditer = (function(){ var view; var v = {}; function init(){ view = $('#MiniEditer'); v.body = $("body"); stageInit(); } /* ---------- ---------- ---------- */ function createlayout(){ var tag = "" tag += '<div class="_bg"></div>'; tag += '<div class="_anno">編集完了:背景クリック or '+TIP2("#+Enter") + '</div>'; tag += '<div class="_modalBox">'; tag += ' <div class="_header _header_def clearfix">'; tag += ' <div class="_title">'+Dic.I.Edit+' <span></span></div>'; tag += ' <div class="_btn_full ss_icon _icon_full" '+TIP("F11","T")+'></div>'; tag += ' <div class="_dragBar"></div>'; tag += ' </div>'; tag += ' <div class="_header _header_full clearfix">'; tag += ' <div class="_title">'+Dic.I.Edit+' <span></span></div>'; tag += ' <div class="_btn_full_off ss_icon _icon_full_off" '+TIP("F11","T")+'></div>'; tag += ' </div>'; tag += ' <div class="_body clearfix"></div>'; tag += '</div>'; view.html(tag) v.bg = view.find('._bg'); v.anno = view.find('._anno'); v.header = view.find('._header'); v.headerD = view.find('._header_def'); v.headerF = view.find('._header_full'); v.modalBox = view.find('._modalBox'); v.bodyArea = view.find('._body'); v.title = view.find('._title span'); v.btn_full = view.find('._btn_full'); v.btn_full_off = view.find('._btn_full_off'); v.btn_full .click(toggleFullScreen); v.btn_full_off .click(toggleFullScreen); MiniEditer.Editors.init(v.bodyArea); setEvent(); setBtn(); CMS_ScreenManager.registResize(function(){ resize() }); } /* ---------- ---------- ---------- */ function setBtn(){ v.bg.bind("mousedown",function(){stageOut();}); v.anno.bind("mousedown",function(){stageOut();}); } /* ---------- ---------- ---------- */ function setEvent(){ v.modalBox.draggable({ distance: 5, handle: v.headerD }); v.modalBox.resizable( { resize: onResuze, stop: onResuzeStop, minWidth:350, }); v.headerD.bind("dblclick",function(){ startFullScreen(); }) v.headerF.bind("click",function(){ endFullScreen(); }) } var tID; function onResuze(event,ui){ if(tID) clearTimeout(tID); tID = setTimeout(function(){ setTextareaSize(ui.size.height-100); },10); } function onResuzeStop(event,ui){ setTextareaSizeEnd(ui.size.height-100); } var currentTextareaH = 150; function setTextareaSize(_h){ currentTextareaH = _h ; MiniEditer.Editors.resize(currentTextareaH); } function getTextareaSize(){ return currentTextareaH; } function setTextareaSizeEnd(_h){ setTextareaSize(_h); v.modalBox.css("height","auto"); } /* ---------- ---------- ---------- */ var defVal = ""; var prevVal = ""; var currentVal = ""; function setData(_s){ if(_s == undefined) _s = ""; currentVal = defVal = _s; MiniEditer.Editors.setData( _s, type, function(_s){ currentVal = _s; if(isFull == false){ _callback(); } } ); updateTitle(type); if(type.indexOf("input:") != -1){ v.modalBox.css("width",200+"px") } if(type.indexOf("input:") != -1){ v.modalBox.css("width",ws.single+"px"); } else{ v.modalBox.css("width",ws.multi+"px"); } } var callbackTID; function _callback(){ if(callbackTID) clearTimeout(callbackTID); callbackTID = setTimeout(function(){ callback(currentVal); },200); } /* ---------- ---------- ---------- */ function updateTitle(_s){ var t = _s.split(":")[1] var s = "テキスト編集" if (t == "style") s = "style属性編集"; if (t == "single-class") s = "class属性編集"; if (t == "markdown") s = "Markdown編集"; if (t == "html") s = "HTML編集"; if (t == "js") s = "JavaScript編集"; v.title.html(s); } /* ---------- ---------- ---------- */ function compliteEdit(){ stageOut(); } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } var type; var callback; function stageIn(_s,_callback,_type){ stageOut() if(! isOpen){ isOpen = true; showModalView(this); if (isFirst) { createlayout(); } isFirst = false; view.show(); callback = _callback; type = _type; setData(_s); v.body.addClass("_modalTextEditing"); updatePos(); // v.anno.hide().delay(100).fadeIn(100); } } function stageOut(){ if(isOpen){ isOpen = false; hideModalView(); view.hide(); v.body.removeClass("_modalTextEditing"); endFullScreen() memoryW(); } } /* ---------- ---------- ---------- */ var defW = 400; var ws = { single:defW, multi:defW } function memoryW(){ if(type){ if(type.indexOf("input:") != -1){ ws.single = v.modalBox.width() } else{ ws.multi = v.modalBox.width() } } } /* ---------- ---------- ---------- */ var currentPos = {x:0,y:0}; var closeTime = new Date(); function updatePos(){ var y = 0; var x = 0; // if (CMS_Status.mouseX > CMS_StatusW*0.66) { x = CMS_Status.mouseX - v.modalBox.width()- 20; } else{ x = CMS_Status.mouseX + 20; // x = CMS_Status.mouseX - 50; } if (CMS_Status.mouseY > CMS_StatusH*0.8) { y = CMS_Status.mouseY - v.modalBox.height() - 20; } else{ y = CMS_Status.mouseY + 15; // y = CMS_Status.mouseY - 25; } if (CMS_Status.mouseY == 0) { y = 200; x = 200; } var w = v.modalBox.width() + 10; var h = v.modalBox.height() + 10; if (window.isFireEnterClick) { x = CMS_StatusW / 2 - (w / 2); y = CMS_StatusH / 2 - (h / 2); } if (x + w > CMS_StatusW) { x = CMS_StatusW - w } if (y + h > CMS_StatusH) { y = CMS_StatusH - h } if (x < 0) { x = 10 } if (y < 0) { y = 10 } //前回の表示位置や時間があまり変わらない場合は、同じ位置に var saX = Math.abs(currentPos.x - x); var saY = Math.abs(currentPos.y - y); var saT = new Date().getTime() - closeTime.getTime(); var b = false; if(saX + saY > 150) b = true; if(saT > 1000) b = true; if(b){ v.modalBox.css({ left: x, top: y }); currentPos = {x:x,y:y}; } closeTime = new Date(); } function resize(){ if(isFull){ setTextareaSize(CMS_StatusH-70); } } /* ---------- ---------- ---------- */ var isFull = false var modalRect = {x:0,y:0,w:0,h:0} var tempH = 0 function startFullScreen(){ if(isFull == true)return; isFull = true; updateFullScreen(); } function endFullScreen(){ if(isFull == false)return; isFull = false; updateFullScreen(); } function toggleFullScreen(){ if(isFull == false){ isFull = true; } else{ isFull = false; } updateFullScreen() } window.editFullScreen = toggleFullScreen; function updateFullScreen(){ if(isFull){ modalRect = { y : v.modalBox.offset().top, x : v.modalBox.offset().left, w : v.modalBox.width(), h : v.modalBox.height() } $("body").addClass("_editFullscreen"); v.modalBox.css({ top:"0px", bottom:"0px", left:"0px", right:"0px", width:"100%", height:"100%" }) tempH = currentTextareaH; setTextareaSizeEnd(CMS_StatusH-70); } else{ $("body").removeClass("_editFullscreen"); v.modalBox.css({ top : modalRect.y + "px", bottom : "auto", left : modalRect.x + "px", right : "auto", width : modalRect.w + "px", height : modalRect.h + "px" }) setTextareaSizeEnd(tempH); _callback(currentVal); } } function setRect(_rect){ } /* ---------- ---------- ---------- */ return { init: init, stageIn: stageIn, stageOut: stageOut, resize: resize, compliteEdit: compliteEdit } })();<file_sep>/src/js/cms_model/PageElement.object.feed.js PageElement.object.feed = (function(){ var _ = new PageModel.Object_(); /* ---------- ---------- ---------- */ _.pageInfo = new PageModel.Object_Info({ id : "object.feed", name : "RSSフィード表示", name2 : "", inputs : ["CLASS","CSS","DETAIL"], // cssDef : {file:"block",key:"[RSSフィード表示ブロック]"} cssDef : {selector:".cms-feed"} }); /* ---------- ---------- ---------- */ _.grids = [ /* ---------- ---------- ---------- */ new PageModel.Object_Grid({ gridType:Dic.GridType.BASE, gridInfo:new PageModel.OG_info({ id : "setting", name : "RSSフィード登録", note : "" }), textData:{ info: new PageModel.OG_SubInfo({ name: "", note: "" }), cells:[ new PageModel.OG_Cell( { id:"url", name:"RSSフィードのファイルパス<br>もしくはフルパス", type:CELL_TYPE.SINGLE , style:SS.w400, note:(function(){ var s = "" s += 'サイトルートからのRSSフィードのファイルパスを入力してください。ex... rss.xml <br>' s += 'ファイルパスでの場合は、対応するフィードの形式はRSSのみになります。<br>' s += 'データブロックのRSSデータで作成・書き出したデータに対応しています。<br><br>' s += 'フルパス(http://〜)で指定した場合は、Google Feed API ( https://developers.google.com/feed/ )を使用してフィードを取得します。<br>' s += 'Google Feed APIが対応してるフィードの形式であれば、読み込むことができます。<br>' s += 'ただし、Feed APIにキャッシュされるので、最新のフィードの内容とは、少しタイムラグが出る場合があります。' return s; })() }), new PageModel.OG_Cell( { id:"sum", name:"表示件数(上限数)", type:CELL_TYPE.SINGLE , style:SS.w100 }), new PageModel.OG_Cell({ id: "template", name: "テンプレートHTML", type: CELL_TYPE.MULTI, style: SS.w800h200, view: "", note: (function(){ var s = ""; s += '使用できるテンプレート用置き換えタグ<br>'; s += '<b>{LINK}</b>...リンクURL<br>'; s += '<b>{DATE}</b>...更新日<br>'; s += '<b>{TITLE}</b>...タイトル<br>'; s += '<b>{CONTENT}</b>...サマリー(本文)<br>'; s += '<b>{REPEAT_START}</b>...繰り返し領域の始まり<br>'; s += '<b>{REPEAT_END}</b>...繰り返し領域のおわり<br>'; return s; })() }), ] }, gridData:null }) /* ---------- ---------- ---------- */ ] _.getInitData = function(){ var o = {}; o.type = _.pageInfo.id; var def = { setting: { texts: { url: "http://rss.dailynews.yahoo.co.jp/fc/rss.xml", sum: "5", template: (function(){ var s = ""; s += '<ul>\n'; // id="{ID}" s += '{REPEAT_START}\n'; s += ' <li>\n'; s += ' <p class="feed_date">{DATE}</p>\n'; s += ' <p class="feed_title"><a href="{LINK}">{TITLE}</a></p>\n'; s += ' <p class="feed_content">{CONTENT}</p>\n'; s += ' </li>\n'; s += '{REPEAT_END}\n'; s += '</ul>\n'; return s; })() }, grid: [] } } o.data = def; o.attr = {css:"default"}; o.attr.class = o.attr.css; return o; } _.getPreview = function(_o,_isPub){ var data = _o.data; var attr = _o.attrs; var url = defaultVal(data.setting.texts.url,""); var tag = ""; tag += '<div class="_cms_preview">' tag += ' <div class="_title">ガジェット / RSSフィード表示</div>'; tag += ' <div class="_notes">※この要素の表示は、プレビューページか、公開サイトで確認してください。</div>'; tag += ' <p>RSSのURL:<b>' + url + '</b></p>' tag += '</div>' return tag; } _.getHTML = function(_o){ var data = _o.data; var attr = _o.attrs; attr = attr.split('class="').join('class="cms-feed clearfix '); var sum = defaultVal(data.setting.texts.sum,"1"); var url = defaultVal(data.setting.texts.url,""); url = url.split(" ").join(""); url = url.split(" ").join(""); var temp = defaultVal(data.setting.texts.template,""); var tag = ""; if(url.substr(0,4) == "http"){ tag += '<script type="text/javascript" src="//www.google.com/jsapi"></script>\n'; tag += '<script type="text/javascript">google.load("feeds", "1");</script>\n'; } else{ url = CONST.SITE_DIR + url } url = url.split('"').join(""); sum = sum.split('"').join(""); tag += '<div ' + attr + '>\n'; tag += '<div class="cms-rss" data-url="'+url+'" data-sum="'+sum+'">\n'; tag += '<textarea style="display:none;">'; tag += temp; tag += '</textarea>\n'; tag += '</div>\n'; tag += '</div>\n'; tag += '<script>\n'; tag += '$(function(){\n'; tag += ' $(".cms-rss").cms_rss();\n'; tag += '});\n' tag += '</script>\n'; return tag; } /* ---------- ---------- ---------- */ return _; })(); <file_sep>/src/js/cms_stage_asset/CMS_Asset_UploaderView.js var CMS_Asset_UploaderView = (function(){ var view; var v = {}; function init(){ view = $('#CMS_Asset_UploaderView'); stageInit(); } function createlayout(){ var tag = ""; tag += '<div class="_header">' tag += ' <div class="_guide">'+CMS_GuideU.getGuideTag("window/upload","_BASE_")+'</div>' tag += ' <div class="_title"><i class="fa fa-upload "></i> ファイルアップロード</div>' tag += ' <div class="_btn_close"><i class="fa fa-lg fa-times-circle "></i> </div>' tag += '</div>' tag += '<div class="_body">'; if(Env_.isIE9){ tag += ' <div style="padding:10px;color:red;font-size:18px;">' tag += ' ファイルアップロードは、ご利用のブラウザでは利用出来ません。<br>' tag += ' GoogleChoromeか、IE10以上を利用してください。' tag += ' </div>'; } else{ tag += ' <div class="_path"></div>'; tag += ' <div class="_uploadArea"></div>'; tag += ' <div class="_alertArea">' tag += ' <i class="fa fa-exclamation-triangle "></i> このディレクトリには、書き込み権限が無いため、ファイルをアップロードできません。<BR>' tag += ' FTPソフトなどで書き込み権限(707など)のパーミッションを設定してください。<br><br>'; tag += ' <div class="_cms_btn-mini _btn_check_reload ">再度チェック</div>' tag += ' </div>'; } tag += '</div>'; view.html(tag); v.btn_check_reload = view.find('._btn_check_reload') v.btn_check_reload.click(function(){ v.alertArea.hide() setTimeout(function(){ checkDir() },200); }); v.btn_close = view.find('._btn_close'); v.path = view.find('._path') v.alertArea = view.find('._alertArea') v.uploadArea = view.find('._uploadArea') v.alertArea.hide() v.uploadArea.hide(); setBtn(); } function setBtn(){ v.btn_close.click(function(){ stageOut() }); registAssetFloatView(function(){stageOut()}); } /* ---------- ---------- ---------- */ var dir var callback var fileListClass function initUpload(_dir,_fileListClass,_callback){ if(uploaderView){ uploaderView.remove(); uploaderView = null; } var this_ = this; dir = _dir; fileListClass = _fileListClass; callback = _callback; var path = dir.split(CMS_Path.SITE.REL).join(""); v.path.html('アップ先ディレクトリ:<span class="_bold"><span class="_icon_dir_mini"></span>' + path +'</span>'); createMain() } var uploaderView function createMain(){ checkDir(); } function checkDir(){ var param = '?action=checkDir'; param += '&upload_dir=' + escape_url(dir); var url = CMS_Path.PHP_UPLOAD + param; $.ajax({ scriptCharset : 'utf-8', type : 'GET', url : url, dataType : 'json', success : function(data) { if(data.status == "1"){ createMain_uploader(); } else{ createMain_error(); } }, error: function(data) { CMS_ErrorView.stageIn("NET",url,null,data); } }); } var isWriteable function createMain_uploader(){ isWriteable = true; v.alertArea.hide() v.uploadArea.show(); if(uploaderView) return; uploaderView = new CMS_Asset_UploaderView2( v.uploadArea , dir , fileListClass , callback ); } function createMain_error(){ isWriteable = false; v.alertArea.show() v.uploadArea.hide(); } /* ---------- ---------- ---------- */ function updateFileList(){ if(uploaderView) uploaderView.updateFileList() } /* ---------- ---------- ---------- */ var uploadWapView /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; var callback = true; // var currentPath = ""; function stageInit(){ view.hide(); } function stageIn(_dir,_fileListClass,_callback){ if(! isOpen){ isOpen = true; showModalView(this); if(isFirst){ createlayout(); } isFirst = false; initUpload(_dir,_fileListClass,_callback); view.show(); } } function stageOut(){ if(isOpen){ isOpen = false; hideModalView(); view.hide(); } } return { init: init, // updateFileList: updateFileList, stageIn: stageIn, stageOut: stageOut } })();<file_sep>/src/js/cms_view_modals/PresetStageView.2.js var PresetStage_PageListView = (function(){ var view; var v = {}; /* ---------- ---------- ---------- */ //初期化 function init(){ view = $('#PresetStage_PageListView'); stageInit(); } /* ---------- ---------- ---------- */ //レイアウト作成・イベントアサイン function createlayout(){ var gloups = PRESET_PAGE_LIST; var tag = '' tag += '<div class="_header">' tag += ' <div class="_title">プリセット</div>' tag += '</div>'; tag += '<div class="_inner _simple-scroll">'; for (var g = 0; g < gloups.length ; g++) { tag += '<div class="_gloup_name">'+gloups[g].name+'</div>' var list = gloups[g].list; tag += '<div class="_page_items">' for (var i = 0; i < list.length ; i++) { var tar = list[i]; var id = "_preset_list_" +tar.id; tag += '<div class="_item" id="'+id+'"+ data-id="'+tar.id+'" data-name="'+tar.name+'">'; tag += '<i class="fa fa-file-text" style="margin:2px 2px 0 2px;"></i> '; tag += list[i].name; tag += '</div>'; } tag += "</div>"; } tag += "</div>"; view.html(tag); v.item = view.find("._item"); v.item.click(function(){ var tar = $(this); openPage( tar.data("id") , tar.data("name") ); }); v.item.eq(0).click(); setBtn(); } function setBtn(){ } /* ---------- ---------- ---------- */ //個別処理 var current function openPage(_id,_name){ var param = { type: Dic.PageType.PRESET, dir: Dic.DirName.PRESET, id:_id, name:_name } if(current){ current.removeClass("_current") } current = view.find("#_preset_list_"+_id); current.addClass("_current"); PresetStageView.openPage(param); } /* ---------- ---------- ---------- */ //表示・非表示処理 var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } function stageIn(){ if(! isOpen){ isOpen = true; view.show(); if(isFirst){ createlayout(); } isFirst = false; } } function stageOut(){ if(isOpen){ isOpen = false; view.hide(); } } return { init:init, stageIn:stageIn, stageOut:stageOut } })(); <file_sep>/src/js/cms_main/CMS_AlertLockView.js var CMS_AlertLockView = (function(){ var view; var v = {}; function init(){ view = $('#CMS_AlertLockView'); stageInit(); } /* ---------- ---------- ---------- */ function createlayout(){ var tag = "" tag += '<div class="_bg"></div>' tag += '<div class="_modalBox">' tag += '<div class="_read">更新ロックを解除してください<br><i class="fa fa-2x fa-lock "></i> <i class="fa fa-long-arrow-right "></i> <i class="fa fa-2x fa-unlock-alt "></i> </div>' // tag += '<div class="_btn_close">閉じる</div>' tag += '<div class="_mark"></div>' tag += '</div>' view.html(tag) setBtn(); } function setBtn(){ view.click(function(){ stageOut() }); // view.find('._btn_close').click(function(){ stageOut() }); } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; var callback; function stageInit(){ view.hide(); } var tID function stageIn(){ if(! isOpen){ isOpen = true; view.show(); if(isFirst){ createlayout(); } isFirst = false; setTimeout(function(){ view.addClass("_show"); },10); if(tID) clearTimeout(tID) tID = setTimeout(function(){ stageOut() },3500); } } function stageOut(){ if(isOpen){ isOpen = false; view.hide(); view.removeClass("_show"); if(tID)clearTimeout(tID) } } return { init:init, stageIn:stageIn, stageOut:stageOut } })(); <file_sep>/src/js/cms_model/PageElement.tag.heading.js PageElement.tag.heading = (function(){ var _ = new PageModel.Tag_(); /* ---------- ---------- ---------- */ _.pageInfo = new PageModel.Object_Info({ id : "tag.heading", name : "見出し", name2 : "<H1>〜<H6>", inputs : ["HEADLINE","CLASS","CSS"], // cssDef : {file:"block",key:"[見出しブロック]",tag:"heading"} cssDef : {selector:"{h1-h6}"} }); /* { "node" : "h1.designA", "name" : "注釈" } */ /* ---------- ---------- ---------- */ _.getInitData = function(_param){ var o = {}; o.type = _.pageInfo.id; o.data = { heading: "h1", main: { text: "", link: null }, right: { text: "", link: null } } o.data.heading = _param; if(_param == "h1")o.data.main.text = "<em>h1</em> {{PAGE_NAME}} <small>headline1</small>";//<em>H1</em> if(_param == "h2")o.data.main.text = "<em>h2</em> 大見出し <small>headline2</small>";//<em>H2</em> if(_param == "h3")o.data.main.text = "<em>h3</em> 中見出し <small>headline3</small>";//<em>H3</em> if(_param == "h4")o.data.main.text = "<em>h4</em> 小見出し <small>headline4</small>";//<em>H4</em> if(_param == "h5")o.data.main.text = "<em>h5</em> 小見出し2 <small>headline5</small>";//<em>H4</em> if(_param == "h6")o.data.main.text = "<em>h6</em> 小見出し3 <small>headline6</small>";//<em>H4</em> o.attr = { css:"default " } o.attr.class = o.attr.css; return o; } /* ---------- ---------- ---------- */ _.getPreview = function(_o){ var data = _o.data; var attr = _o.attrs; var tag = "" if(data.main.text == "" ){ tag += '<span class="_no-input-data">データを入力...</span>' } else{ var nn = data.heading.split("h").join(""); tag += getHeaderTag(nn, data,attr, ""); } return tag; } /* ---------- ---------- ---------- */ _.getHTML = function(_o,_tab){ var data = _o.data; var attr = _o.attrs; var tab = (_tab != undefined) ? _tab:""; var tag = ""; { var nn = data.heading.split("h").join("") tag += getHeaderTag(nn, data,attr, _tab); } return tag; } function getHeaderTag (_tag,_data,_attr,_tab) { _attr = _attr.split('class="').join('class="cms-h '); var s = { main : "", right : "" } try{ s.main = CMS_AnchorU.getWapperTag(_data.main.link, _data.main.text); s.right = CMS_AnchorU.getWapperTag(_data.right.link, _data.right.text); }catch( e ){} var tag = ""; tag += _tab + ' <h{TAG} '+_attr+'>' if(s.right) tag += _tab + '<span class="cms-h-right">' + s.right + '</span>' tag += s.main tag += '</h{TAG}>\n' tag = tag.split("{TAG}").join(_tag); return tag; } /* ---------- ---------- ---------- */ return _; })();<file_sep>/src/js/cms_stage_page/CMS_PageStage.js var CMS_PageStage = (function(){ var view; var v = {}; /* ---------- ---------- ---------- */ //初期化 function init(){ view = $('#CMS_PageStage'); // stageInit(); createlayout(); setBtn(); } /* ---------- ---------- ---------- */ //レイアウト作成・イベントアサイン function createlayout(){ var tag = "" tag += ' <div id="CMS_PageListView"></div>'; tag += ' <div id="CMS_PageListBgView"></div>'; tag += ' <div id="CMS_PagesView"></div>'; tag += ' <div id="CMS_IntroView"></div>'; tag += ' <div id="AddElements"></div>'; view.append(tag); CMS_PageListView.init(); CMS_PageListBgView.init(); CMS_PagesView.init(); CMS_IntroView.init(); AddElements.init(); } function setBtn(){ view.on("mousedown",function(){ CMS_KeyManager.setType(""); }) } /* ---------- ---------- ---------- */ //個別処理 /* ---------- ---------- ---------- */ //表示・非表示処理 var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } function stageIn(){ if(! isOpen){ isOpen = true; view.show(); if(isFirst){ CMS_PageListView.stageIn(); } isFirst = false; } } function stageOut(){ if(isOpen){ isOpen = false; view.hide(); } } return { init:init, stageIn:stageIn, stageOut:stageOut } })(); <file_sep>/js_cms/_cms/storage.funcs.php <?php /** * JS_CMS -- realtime website development web application * http://js-cms.jp/ * Copyright 2015 <NAME> - <EMAIL> * licensed under the MIT licenses. */ //usleep(200*1000);//test if (!defined('CMS')) exit; $isDev = false; if($isDev){ ini_set( 'display_errors', 1 ); error_reporting(E_ALL & ~E_NOTICE); header("Access-Control-Allow-Origin:*"); }else{ error_reporting(0); } if (get_magic_quotes_gpc()) { function strip_magic_quotes_slashes($arr) { return is_array($arr) ? array_map('strip_magic_quotes_slashes', $arr) : stripslashes($arr); } $_GET = strip_magic_quotes_slashes($_GET); $_POST = strip_magic_quotes_slashes($_POST); } function status_success(){ echo( '{"status":1 , "message":"success"}'); exit(); } function status_fileNotFound_weak(){ echo( '{"status":0 ,"level":0 ,"message":"file or directory not found"}');exit(); } function status_fileNotFound(){ echo( '{"status":0 ,"level":1 , "message":"file or directory not found"}');exit(); } function status_error( $s){ echo( '{"status":0 , "level":1, "message":"'.$s.'"}');exit(); } function status_error_dir( $s){ echo( '{"status":0 , "level":1, "message":"dir error", "extra":"'.$s.'"}');exit(); } function checkFileExist_weak($f){ if(! file_exists($f)){ status_fileNotFound_weak(); } } function checkFileExist($f){ if(! file_exists($f)){ status_fileNotFound(); } } function getVAL($_s,$_def,$_type){ $v = $_def; if(isset($_GET[$_s])) $v = $_GET[$_s]; if(isset($_POST[$_s])) $v = $_POST[$_s]; if($_type == "number"){ $v = intval($v); } if($_type == "boolean"){ if($v == "1") $v = true; } if($_type == "path"){ if(! is_filePath($v)) { status_error("invalid path"); } } if($_type == "dir"){ $v = str_replace("__DIR__", "../",$v); } if($_type == "path"){ $v = str_replace("__DIR__", "../",$v); } if($_type == "paths"){ $v = str_replace("__DIR__", "../",$v); $v = explode("__SEP__",$v); } if($_type == "paths2"){ $v = str_replace("__DIR__", "../",$v); $v = explode(",",$v); } return $v; } function is_action($text) { if($text =="") return true; if (preg_match("/^[a-zA-Z0-9]+$/",$text)) { return true; } else { return false; } } function getExtention($text) { $path_parts = pathinfo($text); return mb_strtolower($path_parts['extension']); } function matchExtention($text,$ar) { $ex = getExtention($text); for ($i = 0 ; $i < count($ar); $i++) { if($ar[$i] ==$ex )return true; } return false; } function is_fileName($text) { if($text =="") return true; if (preg_match("/^[a-zA-Z0-9._¥-]+$/",$text)) { return true; } else { return false; } } function is_filePath($text) { if($text =="") return true; if (preg_match("/^[\/a-zA-Z0-9._¥-]+$/",$text)) { if(checkPathDepth($text)) return true; } return false; } function checkPathDepth($text) { if($text{0} == "/")return false; $ps = explode( "/",$text ); $c = 0; for ($i = 0 ; $i < count($ps); $i++) { if($ps[$i] == "..") $c++; } if($c > 2 ) return false; return true; } function isWritableDir($dir) { if(is_filePath($dir)){ if(file_exists($dir)){ if(is_writable($dir)){ return true; } } } return false; } function removeAllDirectory($dir) { if ($handle = opendir("$dir")) { while (false !== ($item = readdir($handle))) { if ($item != "." && $item != "..") { if (is_dir("$dir/$item")) { removeAllDirectory("$dir/$item"); } else { unlink("$dir/$item"); } } } closedir($handle); rmdir($dir); } } if (!function_exists('file_put_contents')) { function file_put_contents($filename, $data) { $f = @fopen($filename, 'w'); if (!$f) { return false; } else { $bytes = fwrite($f, $data); fclose($f); return $bytes; } } } if (!function_exists('scandir')) { function scandir() { return -1; } } //backup function isIgnoreFile($s,$list){ $b = false; for ($i = 0; $i< count($list); $i++) { if(strpos($s,$list[$i]) !== false){ $b =true; } } return $b; } function getR($length) { $str = array_merge(range('a', 'z'), range('0', '9'), range('A', 'Z')); $r_str = null; for ($i = 0; $i < $length; $i++) { $r_str .= $str[rand(0, count($str))]; } return $r_str; } <file_sep>/src/js/cms_view_modals/MiniEditer.Editors.js MiniEditer.Editors = (function(){ var view; var v = {}; function init(_parentView){ view = $('<div class="_textarea"></div>'); _parentView.append(view); } var editors = {} var callback; var prevEditor; var currentEditor; var initTID; function setData(_s,_type,_callback){ callback = _callback; if(currentEditor)currentEditor.stageOut() if(! editors[_type]){ var t = _type.split(":")[1]; if(_type.indexOf("input:") != -1){ currentEditor = new MiniEditer.InputView(view,t); } else{ //multi,table currentEditor = new MiniEditer.CodeView(view,t); } editors[_type] = currentEditor; } else{ currentEditor = editors[_type]; } //データセット時のアップデートをスルーする処理 var isUpdateable = false; if(initTID) clearTimeout(initTID); initTID = setTimeout(function() { isUpdateable = true; }, 100); currentEditor.stageIn(); currentEditor.setData(_s,function(_s){ if(!isUpdateable) return; callback(_s); }); resize(); } var currentH = 150; function resize(_h){ if(_h) currentH = _h; currentEditor.resize(currentH); } return { init: init, setData: setData, resize: resize } })();<file_sep>/src/js/cms_model/PageElement.tag.js.js PageElement.tag.js = (function(){ var _ = new PageModel.Tag_(); /* ---------- ---------- ---------- */ _.pageInfo = new PageModel.Object_Info({ id : "tag.js", name : "JavaScript", name2 : "", inputs : [] }); /* ---------- ---------- ---------- */ _.getInitData = function(){ var o = {}; o.type = _.pageInfo.id; var s = "" s += '//ページ公開時に、JavaScriptコードを実行し、返り値を出力します。\n\n'; s += '(function(_param){\n'; s += ' var tag = "";\n'; s += ' var a = _param["{1}"];\n'; s += ' var b = _param["{2}"];\n'; s += ' return a + b;\n'; s += '});\n'; o.data = s; o.attr = { } // o.attr ={ } return o; } /* ---------- ---------- ---------- */ _.getPreview = function(_o){ var data = _o.data; var attr = _o.attrs; var tag = ""; if(data == ""){ tag += '<span class="_no-input-data">JavaScriptを入力...</span>' } else{ tag += '<div class="_element_js_code">' tag += '<div class="_code_inner">' tag += CMS_TagU.tag_2_t(data).split("\n").join("<br>") tag += '</div>'; tag += '<div class="_anno">※ 上記のJavaScriptは、ページ公開時などに実行され、return が出力されます。</div>'; tag += '</div>'; } return tag; } /* ---------- ---------- ---------- */ _.getHTML = function(_o,_tab){ var data = _o.data; var attr = _o.attrs; // var tab = (_tab != undefined) ? _tab:""; // throw new Error(); var tag = ""; try{ var jsparam = CMS_Data.HinagataSearvice.getJSParam(); tag += eval(data)(jsparam); } catch( e ){ } return tag; } /* ---------- ---------- ---------- */ return _; })();<file_sep>/src/js/cms_model/Dic.js var SS = (function(){ var o = {} o.repID = "color:#4A66A0;font-size:12px;font-weight:bold;"; o.repID20 = "color:#4A66A0;font-size:16px;font-weight:bold;width:200px;"; o.memo = "color:#999;font-size:12px;"; o.multiDef = "width:600px;height:100px;"; o.w50 = "width:50px;"; o.w100 = "width:100px;"; o.w150 = "width:150px;"; o.w200 = "width:200px;"; o.w300 = "width:300px;"; o.w400 = "width:400px;"; o.w500 = "width:500px;"; o.w600 = "width:600px;"; o.w300h50 = "width:300px;height:50px;"; o.w300h100 = "width:300px;height:100px;"; o.w300h200 = "width:300px;height:200px;"; o.w400h50 = "width:400px;height:50px;"; o.w400h100 = "width:400px;height:100px;"; o.w400h200 = "width:400px;height:200px;"; o.w600h50 = "width:600px;height:50px;"; o.w600h100 = "width:600px;height:100px;"; o.w600h200 = "width:600px;height:200px;"; o.w600h50 = "width:600px;height:50px;"; o.w600h100 = "width:600px;height:100px;"; o.w600h200 = "width:600px;height:200px;"; o.w800 = "width:800px;"; o.w800h50 = "width:800px;height:50px;"; o.w800h100 = "width:800px;height:100px;"; o.w800h200 = "width:800px;height:200px;"; o.img80 = "width:80px;height:80px;overflow:scroll"; o.img50p = "max-width:300px;"; o.html = "color:#888;font-weight:bold;"; o.js = "color:#B20000;"; o.css = "color:#003ca4;"; o.SelectVals = { pub : [["公開","公開"], ["非公開","非公開"]], linkTarget : [["_self","同一ウィンドウ"], ["_blank","別ウィンドウ"]], YN : [["1","YES"], ["0","NO"]], TRBL : [["top","上に配置"],["right","右に配置"],["bottom","下に配置"],["left","左に配置"]] } return o; })(); var PageElement_DIC = [] window.PageElement_DIC = PageElement_DIC; var CELL_TYPE = {} CELL_TYPE.SINGLE = "single"; CELL_TYPE.MULTI = "multi"; CELL_TYPE.MULTI_JS = "multi,js" CELL_TYPE.MULTI_STYLE = "multi,style" CELL_TYPE.MULTI_HTML = "multi,html" CELL_TYPE.TABLE = "table" CELL_TYPE.SELECT = "select"; CELL_TYPE.CHECK = "checkbox"; CELL_TYPE.IMAGE = "image"; CELL_TYPE.ANCHOR = "anchor"; CELL_TYPE.BTN = "textAnchor"; CELL_TYPE.YYYYMMDD = "yyyymmdd"; CELL_TYPE.STATE = "_state";<file_sep>/src/js/cms_view_modals/Preset_IconView.js var Preset_IconView = (function(){ var view; var v = {}; function init(){ view = $('#Preset_IconView'); stageInit(); } /* ---------- ---------- ---------- */ function createlayout(){ v = ModalViewCreater.createBaseView(Preset_IconView,view); var tag = "" tag += '<div class="_guide">'+CMS_GuideU.getGuideTag("window/icon","_BASE_")+'</div>' tag += '<div class="_title">アイコンライブラリ</div>' v.header.html(tag); tag = "" v.body.html(tag) v.texts = view.find('._texts'); v.status = view.find('._status'); tag = "" tag += '<div class="_cms_btn _btn_close" '+TIP_ENTER+'>閉じる</div> '; v.footer.html(tag); createFontList(); setBtn(); } function setBtn(){ view.find('._bg ,._btn_close').click(function(){ stageOut() }); } function createFontList(){ var tag = "" tag +='<div class="_p">サイト内では、オープンソースのウェブフォントFont Awesome ( http://fontawesome.io/ ) を利用できます。<br>' tag +='利用したいアイコンをコピーできます。本文やボタンはもちろん、メニューでも利用できます。</div>' tag +='<div class="_cols" style="margin:10px 0 0 0;">' tag +=' <div class="_col _sizeSelect"></div>' tag +=' <div class="_col _rotSelect"></div>' tag +=' <div class="_col _fixSelect"></div>' tag +='</div>' tag +='<div class="_searchArea" style="margin:5px 0;font-size:12px;">●絞り込み  <input placeholder="arrow"></div>' tag +='<div class="_listArea"></div>' v.body.html(tag); v.searchArea = view.find('._searchArea input'); v.listArea = view.find('._listArea'); CMS_FormU.createCheckBox( view.find('._sizeSelect'), "●アイコンサイズ", [ '普通','1.3X','2X','3X','4X' ], 0, function(_n){ setSize(_n) } ) CMS_FormU.createCheckBox( view.find('._rotSelect'), "●回転", [ '普通','90度','180度','270度'/*,'横反転','縦反転' */], 0, function(_n){ setRot(_n) } ) CMS_FormU.createCheckBox( view.find('._fixSelect'), "●固定幅", [ '普通','固定幅' ], 0, function(_n){ setFix(_n) } ) v.searchArea.keyup(function(){ searchIcon($(this).val()); }) view.on("click",'.fa',function(){ var a = [] a.push($(this).data("id")); a.push(sizeCs[currentSize]); a.push(rotCs[currentRot]); a.push(fixCs[currentFix]); var ss = a.join(" "); ss = ss.split(" ").join(" ") ss = ss.split(" ").join(" ") selectIcon ( '<i class="fa '+ ss +'"></i> ') }); update(); } function selectIcon(_s){ if(callback){ stageOut(); UpdateDelay.delay(function(){ callback(_s); }); } else { CMS_CopyView.stageIn(_s,function(){}) } } var searchString = ""; function searchIcon(_s){ searchString = _s; update() } /* ---------- ---------- ---------- */ function update(){ var fontList = ICON_FONT_LIST; var list = [] for (var i = 0; i < fontList.length ; i++) { var b = false; var tag = ""; tag += '<div class="_h2">'+fontList[i].title+"</div>" tag += '<div class="_g">' for (var ii = 0; ii < fontList[i].list.length ; ii++) { if(fontList[i].list[ii].indexOf(searchString) != -1){ b = true; var a = []; a.push(fontList[i].list[ii]); a.push(sizeCs[currentSize]); a.push(rotCs[currentRot]); a.push(fixCs[currentFix]); tag += '<span><i class="fa '+ a.join(" ") +'" data-id="'+fontList[i].list[ii]+'"></i></span>' } } tag += '</div>' if(b) list.push(tag); } v.listArea.html(list.join("")); } /* ---------- ---------- ---------- */ var sizeCs = ["","fa-lg", "fa-2x", "fa-3x", "fa-4x"]; var rotCs = ["","fa-rotate-90", "fa-rotate-180", "fa-rotate-270"/*, "fa-flip-horizontal" ,"fa-flip-vertical"*/]; var fixCs = ["","fa-fw"]; var currentSize = 0; var currentRot = 0; var currentFix = 0; function setSize(_n){ currentSize = _n; update(); } function setRot(_n) { currentRot = _n; update(); } function setFix(_n) { currentFix = _n; update(); } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } var callback function stageIn(_callback){ if(! isOpen){ isOpen = true; showModalView(this); _callback = _callback ? _callback:null; callback = _callback; view.show(); if(isFirst){createlayout();} isFirst = false; } } function stageOut(){ if(isOpen){ isOpen = false; hideModalView(); view.hide(); } } function resize(){ if(isOpen){ } } return { init:init, stageIn:stageIn, stageOut:stageOut,resize:resize } })();//modal var ICON_FONT_LIST = [ { title:"よく使うアイコン", list:[ "fa-external-link", "fa-external-link-square", "fa-folder", "fa-folder-open", "fa-check", "fa-check-square", "fa-envelope", "fa-rss", "fa-rss-square", "fa-facebook", "fa-facebook-square", "fa-google-plus", "fa-google-plus-square", "fa-twitter", "fa-twitter-square", "fa-refresh", "fa-times", "fa-times-circle", "fa-warning" ] },{ title:"Web Application Icons", list:[ "fa-adjust", "fa-anchor", "fa-archive", "fa-area-chart", "fa-arrows", "fa-arrows-h", "fa-arrows-v", "fa-asterisk", "fa-at", "fa-automobile (alias)", "fa-balance-scale", "fa-ban", "fa-bank (alias)", "fa-bar-chart", "fa-bar-chart-o (alias)", "fa-barcode", "fa-bars", "fa-battery-0 (alias)", "fa-battery-1 (alias)", "fa-battery-2 (alias)", "fa-battery-3 (alias)", "fa-battery-4 (alias)", "fa-battery-empty", "fa-battery-full", "fa-battery-half", "fa-battery-quarter", "fa-battery-three-quarters", "fa-bed", "fa-beer", "fa-bell", "fa-bell-o", "fa-bell-slash", "fa-bell-slash-o", "fa-bicycle", "fa-binoculars", "fa-birthday-cake", "fa-bluetooth", "fa-bluetooth-b", "fa-bolt", "fa-bomb", "fa-book", "fa-bookmark", "fa-bookmark-o", "fa-briefcase", "fa-bug", "fa-building", "fa-building-o", "fa-bullhorn", "fa-bullseye", "fa-bus", "fa-cab (alias)", "fa-calculator", "fa-calendar", "fa-calendar-check-o", "fa-calendar-minus-o", "fa-calendar-o", "fa-calendar-plus-o", "fa-calendar-times-o", "fa-camera", "fa-camera-retro", "fa-car", "fa-caret-square-o-down", "fa-caret-square-o-left", "fa-caret-square-o-right", "fa-caret-square-o-up", "fa-cart-arrow-down", "fa-cart-plus", "fa-cc", "fa-certificate", "fa-check", "fa-check-circle", "fa-check-circle-o", "fa-check-square", "fa-check-square-o", "fa-child", "fa-circle", "fa-circle-o", "fa-circle-o-notch", "fa-circle-thin", "fa-clock-o", "fa-clone", "fa-close (alias)", "fa-cloud", "fa-cloud-download", "fa-cloud-upload", "fa-code", "fa-code-fork", "fa-coffee", "fa-cog", "fa-cogs", "fa-comment", "fa-comment-o", "fa-commenting", "fa-commenting-o", "fa-comments", "fa-comments-o", "fa-compass", "fa-copyright", "fa-creative-commons", "fa-credit-card", "fa-credit-card-alt", "fa-crop", "fa-crosshairs", "fa-cube", "fa-cubes", "fa-cutlery", "fa-dashboard (alias)", "fa-database", "fa-desktop", "fa-diamond", "fa-dot-circle-o", "fa-download", "fa-edit (alias)", "fa-ellipsis-h", "fa-ellipsis-v", "fa-envelope", "fa-envelope-o", "fa-envelope-square", "fa-eraser", "fa-exchange", "fa-exclamation", "fa-exclamation-circle", "fa-exclamation-triangle", "fa-external-link", "fa-external-link-square", "fa-eye", "fa-eye-slash", "fa-eyedropper", "fa-fax", "fa-feed (alias)", "fa-female", "fa-fighter-jet", "fa-file-archive-o", "fa-file-audio-o", "fa-file-code-o", "fa-file-excel-o", "fa-file-image-o", "fa-file-movie-o (alias)", "fa-file-pdf-o", "fa-file-photo-o (alias)", "fa-file-picture-o (alias)", "fa-file-powerpoint-o", "fa-file-sound-o (alias)", "fa-file-video-o", "fa-file-word-o", "fa-file-zip-o (alias)", "fa-film", "fa-filter", "fa-fire", "fa-fire-extinguisher", "fa-flag", "fa-flag-checkered", "fa-flag-o", "fa-flash (alias)", "fa-flask", "fa-folder", "fa-folder-o", "fa-folder-open", "fa-folder-open-o", "fa-frown-o", "fa-futbol-o", "fa-gamepad", "fa-gavel", "fa-gear (alias)", "fa-gears (alias)", "fa-gift", "fa-glass", "fa-globe", "fa-graduation-cap", "fa-group (alias)", "fa-hand-grab-o (alias)", "fa-hand-lizard-o", "fa-hand-paper-o", "fa-hand-peace-o", "fa-hand-pointer-o", "fa-hand-rock-o", "fa-hand-scissors-o", "fa-hand-spock-o", "fa-hand-stop-o (alias)", "fa-hashtag", "fa-hdd-o", "fa-headphones", "fa-heart", "fa-heart-o", "fa-heartbeat", "fa-history", "fa-home", "fa-hotel (alias)", "fa-hourglass", "fa-hourglass-1 (alias)", "fa-hourglass-2 (alias)", "fa-hourglass-3 (alias)", "fa-hourglass-end", "fa-hourglass-half", "fa-hourglass-o", "fa-hourglass-start", "fa-i-cursor", "fa-image (alias)", "fa-inbox", "fa-industry", "fa-info", "fa-info-circle", "fa-institution (alias)", "fa-key", "fa-keyboard-o", "fa-language", "fa-laptop", "fa-leaf", "fa-legal (alias)", "fa-lemon-o", "fa-level-down", "fa-level-up", "fa-life-bouy (alias)", "fa-life-buoy (alias)", "fa-life-ring", "fa-life-saver (alias)", "fa-lightbulb-o", "fa-line-chart", "fa-location-arrow", "fa-lock", "fa-magic", "fa-magnet", "fa-mail-forward (alias)", "fa-mail-reply (alias)", "fa-mail-reply-all (alias)", "fa-male", "fa-map", "fa-map-marker", "fa-map-o", "fa-map-pin", "fa-map-signs", "fa-meh-o", "fa-microphone", "fa-microphone-slash", "fa-minus", "fa-minus-circle", "fa-minus-square", "fa-minus-square-o", "fa-mobile", "fa-mobile-phone (alias)", "fa-money", "fa-moon-o", "fa-mortar-board (alias)", "fa-motorcycle", "fa-mouse-pointer", "fa-music", "fa-navicon (alias)", "fa-newspaper-o", "fa-object-group", "fa-object-ungroup", "fa-paint-brush", "fa-paper-plane", "fa-paper-plane-o", "fa-paw", "fa-pencil", "fa-pencil-square", "fa-pencil-square-o", "fa-percent", "fa-phone", "fa-phone-square", "fa-photo (alias)", "fa-picture-o", "fa-pie-chart", "fa-plane", "fa-plug", "fa-plus", "fa-plus-circle", "fa-plus-square", "fa-plus-square-o", "fa-power-off", "fa-print", "fa-puzzle-piece", "fa-qrcode", "fa-question", "fa-question-circle", "fa-quote-left", "fa-quote-right", "fa-random", "fa-recycle", "fa-refresh", "fa-registered", "fa-remove (alias)", "fa-reorder (alias)", "fa-reply", "fa-reply-all", "fa-retweet", "fa-road", "fa-rocket", "fa-rss", "fa-rss-square", "fa-search", "fa-search-minus", "fa-search-plus", "fa-send (alias)", "fa-send-o (alias)", "fa-server", "fa-share", "fa-share-alt", "fa-share-alt-square", "fa-share-square", "fa-share-square-o", "fa-shield", "fa-ship", "fa-shopping-bag", "fa-shopping-basket", "fa-shopping-cart", "fa-sign-in", "fa-sign-out", "fa-signal", "fa-sitemap", "fa-sliders", "fa-smile-o", "fa-soccer-ball-o (alias)", "fa-sort", "fa-sort-alpha-asc", "fa-sort-alpha-desc", "fa-sort-amount-asc", "fa-sort-amount-desc", "fa-sort-asc", "fa-sort-desc", "fa-sort-down (alias)", "fa-sort-numeric-asc", "fa-sort-numeric-desc", "fa-sort-up (alias)", "fa-space-shuttle", "fa-spinner", "fa-spoon", "fa-square", "fa-square-o", "fa-star", "fa-star-half", "fa-star-half-empty (alias)", "fa-star-half-full (alias)", "fa-star-half-o", "fa-star-o", "fa-sticky-note", "fa-sticky-note-o", "fa-street-view", "fa-suitcase", "fa-sun-o", "fa-support (alias)", "fa-tablet", "fa-tachometer", "fa-tag", "fa-tags", "fa-tasks", "fa-taxi", "fa-television", "fa-terminal", "fa-thumb-tack", "fa-thumbs-down", "fa-thumbs-o-down", "fa-thumbs-o-up", "fa-thumbs-up", "fa-ticket", "fa-times", "fa-times-circle", "fa-times-circle-o", "fa-tint", "fa-toggle-down (alias)", "fa-toggle-left (alias)", "fa-toggle-off", "fa-toggle-on", "fa-toggle-right (alias)", "fa-toggle-up (alias)", "fa-trademark", "fa-trash", "fa-trash-o", "fa-tree", "fa-trophy", "fa-truck", "fa-tty", "fa-tv (alias)", "fa-umbrella", "fa-university", "fa-unlock", "fa-unlock-alt", "fa-unsorted (alias)", "fa-upload", "fa-user", "fa-user-plus", "fa-user-secret", "fa-user-times", "fa-users", "fa-video-camera", "fa-volume-down", "fa-volume-off", "fa-volume-up", "fa-warning (alias)", "fa-wheelchair", "fa-wifi", "fa-wrench", ] },{ title:"Hand Icons", list:[ "fa-hand-grab-o (alias)", "fa-hand-lizard-o", "fa-hand-o-down", "fa-hand-o-left", "fa-hand-o-right", "fa-hand-o-up", "fa-hand-paper-o", "fa-hand-peace-o", "fa-hand-pointer-o", "fa-hand-rock-o", "fa-hand-scissors-o", "fa-hand-spock-o", "fa-hand-stop-o (alias)", "fa-thumbs-down", "fa-thumbs-o-down", "fa-thumbs-o-up", "fa-thumbs-up", ] },{ title:"Transportation Icons", list:[ "fa-ambulance", "fa-automobile (alias)", "fa-bicycle", "fa-bus", "fa-cab (alias)", "fa-car", "fa-fighter-jet", "fa-motorcycle", "fa-plane", "fa-rocket", "fa-ship", "fa-space-shuttle", "fa-subway", "fa-taxi", "fa-train", "fa-truck", "fa-wheelchair", ] },{ title:"Gender Icons", list:[ "fa-genderless", "fa-intersex (alias)", "fa-mars", "fa-mars-double", "fa-mars-stroke", "fa-mars-stroke-h", "fa-mars-stroke-v", "fa-mercury", "fa-neuter", "fa-transgender", "fa-transgender-alt", "fa-venus", "fa-venus-double", "fa-venus-mars", ] },{ title:"File Type Icons", list:[ "fa-file", "fa-file-archive-o", "fa-file-audio-o", "fa-file-code-o", "fa-file-excel-o", "fa-file-image-o", "fa-file-movie-o (alias)", "fa-file-o", "fa-file-pdf-o", "fa-file-photo-o (alias)", "fa-file-picture-o (alias)", "fa-file-powerpoint-o", "fa-file-sound-o (alias)", "fa-file-text", "fa-file-text-o", "fa-file-video-o", "fa-file-word-o", "fa-file-zip-o (alias)", ] },{ title:"Spinner Icons", list:[ "fa-circle-o-notch", "fa-cog", "fa-gear (alias)", "fa-refresh", "fa-spinner", ] },{ title:"Form Control Icons", list:[ "fa-check-square", "fa-check-square-o", "fa-circle", "fa-circle-o", "fa-dot-circle-o", "fa-minus-square", "fa-minus-square-o", "fa-plus-square", "fa-plus-square-o", "fa-square", "fa-square-o", ] },{ title:"Payment Icons", list:[ "fa-cc-amex", "fa-cc-diners-club", "fa-cc-discover", "fa-cc-jcb", "fa-cc-mastercard", "fa-cc-paypal", "fa-cc-stripe", "fa-cc-visa", "fa-credit-card", "fa-credit-card-alt", "fa-google-wallet", "fa-paypal", ] },{ title:"Chart Icons", list:[ "fa-area-chart", "fa-bar-chart", "fa-bar-chart-o (alias)", "fa-line-chart", "fa-pie-chart", ] },{ title:"Currency Icons", list:[ "fa-bitcoin (alias)", "fa-btc", "fa-cny (alias)", "fa-dollar (alias)", "fa-eur", "fa-euro (alias)", "fa-gbp", "fa-gg", "fa-gg-circle", "fa-ils", "fa-inr", "fa-jpy", "fa-krw", "fa-money", "fa-rmb (alias)", "fa-rouble (alias)", "fa-rub", "fa-ruble (alias)", "fa-rupee (alias)", "fa-shekel (alias)", "fa-sheqel (alias)", "fa-try", "fa-turkish-lira (alias)", "fa-usd", "fa-won (alias)", "fa-yen (alias)", ] },{ title:"Text Editor Icons", list:[ "fa-align-center", "fa-align-justify", "fa-align-left", "fa-align-right", "fa-bold", "fa-chain (alias)", "fa-chain-broken", "fa-clipboard", "fa-columns", "fa-copy (alias)", "fa-cut (alias)", "fa-dedent (alias)", "fa-eraser", "fa-file", "fa-file-o", "fa-file-text", "fa-file-text-o", "fa-files-o", "fa-floppy-o", "fa-font", "fa-header", "fa-indent", "fa-italic", "fa-link", "fa-list", "fa-list-alt", "fa-list-ol", "fa-list-ul", "fa-outdent", "fa-paperclip", "fa-paragraph", "fa-paste (alias)", "fa-repeat", "fa-rotate-left (alias)", "fa-rotate-right (alias)", "fa-save (alias)", "fa-scissors", "fa-strikethrough", "fa-subscript", "fa-superscript", "fa-table", "fa-text-height", "fa-text-width", "fa-th", "fa-th-large", "fa-th-list", "fa-underline", "fa-undo", "fa-unlink (alias)", ] },{ title:"Directional Icons", list:[ "fa-angle-double-down", "fa-angle-double-left", "fa-angle-double-right", "fa-angle-double-up", "fa-angle-down", "fa-angle-left", "fa-angle-right", "fa-angle-up", "fa-arrow-circle-down", "fa-arrow-circle-left", "fa-arrow-circle-o-down", "fa-arrow-circle-o-left", "fa-arrow-circle-o-right", "fa-arrow-circle-o-up", "fa-arrow-circle-right", "fa-arrow-circle-up", "fa-arrow-down", "fa-arrow-left", "fa-arrow-right", "fa-arrow-up", "fa-arrows", "fa-arrows-alt", "fa-arrows-h", "fa-arrows-v", "fa-caret-down", "fa-caret-left", "fa-caret-right", "fa-caret-square-o-down", "fa-caret-square-o-left", "fa-caret-square-o-right", "fa-caret-square-o-up", "fa-caret-up", "fa-chevron-circle-down", "fa-chevron-circle-left", "fa-chevron-circle-right", "fa-chevron-circle-up", "fa-chevron-down", "fa-chevron-left", "fa-chevron-right", "fa-chevron-up", "fa-exchange", "fa-hand-o-down", "fa-hand-o-left", "fa-hand-o-right", "fa-hand-o-up", "fa-long-arrow-down", "fa-long-arrow-left", "fa-long-arrow-right", "fa-long-arrow-up", "fa-toggle-down (alias)", "fa-toggle-left (alias)", "fa-toggle-right (alias)", "fa-toggle-up (alias)", "fa-Video Player Icons", "fa-arrows-alt", "fa-backward", "fa-compress", "fa-eject", "fa-expand", "fa-fast-backward", "fa-fast-forward", "fa-forward", "fa-pause", "fa-pause-circle", "fa-pause-circle-o", "fa-play", "fa-play-circle", "fa-play-circle-o", "fa-random", "fa-step-backward", "fa-step-forward", "fa-stop", "fa-stop-circle", "fa-stop-circle-o", "fa-youtube-play", ] },{ title:"Brand Icons", list:[ "fa-500px", "fa-adn", "fa-amazon", "fa-android", "fa-angellist", "fa-apple", "fa-behance", "fa-behance-square", "fa-bitbucket", "fa-bitbucket-square", "fa-bitcoin (alias)", "fa-black-tie", "fa-bluetooth", "fa-bluetooth-b", "fa-btc", "fa-buysellads", "fa-cc-amex", "fa-cc-diners-club", "fa-cc-discover", "fa-cc-jcb", "fa-cc-mastercard", "fa-cc-paypal", "fa-cc-stripe", "fa-cc-visa", "fa-chrome", "fa-codepen", "fa-codiepie", "fa-connectdevelop", "fa-contao", "fa-css3", "fa-dashcube", "fa-delicious", "fa-deviantart", "fa-digg", "fa-dribbble", "fa-dropbox", "fa-drupal", "fa-edge", "fa-empire", "fa-expeditedssl", "fa-facebook", "fa-facebook-f (alias)", "fa-facebook-official", "fa-facebook-square", "fa-firefox", "fa-flickr", "fa-fonticons", "fa-fort-awesome", "fa-forumbee", "fa-foursquare", "fa-ge (alias)", "fa-get-pocket", "fa-gg", "fa-gg-circle", "fa-git", "fa-git-square", "fa-github", "fa-github-alt", "fa-github-square", "fa-gittip (alias)", "fa-google", "fa-google-plus", "fa-google-plus-square", "fa-google-wallet", "fa-gratipay", "fa-hacker-news", "fa-houzz", "fa-html5", "fa-instagram", "fa-internet-explorer", "fa-ioxhost", "fa-joomla", "fa-jsfiddle", "fa-lastfm", "fa-lastfm-square", "fa-leanpub", "fa-linkedin", "fa-linkedin-square", "fa-linux", "fa-maxcdn", "fa-meanpath", "fa-medium", "fa-mixcloud", "fa-modx", "fa-odnoklassniki", "fa-odnoklassniki-square", "fa-opencart", "fa-openid", "fa-opera", "fa-optin-monster", "fa-pagelines", "fa-paypal", "fa-pied-piper", "fa-pied-piper-alt", "fa-pinterest", "fa-pinterest-p", "fa-pinterest-square", "fa-product-hunt", "fa-qq", "fa-ra (alias)", "fa-rebel", "fa-reddit", "fa-reddit-alien", "fa-reddit-square", "fa-renren", "fa-safari", "fa-scribd", "fa-sellsy", "fa-share-alt", "fa-share-alt-square", "fa-shirtsinbulk", "fa-simplybuilt", "fa-skyatlas", "fa-skype", "fa-slack", "fa-slideshare", "fa-soundcloud", "fa-spotify", "fa-stack-exchange", "fa-stack-overflow", "fa-steam", "fa-steam-square", "fa-stumbleupon", "fa-stumbleupon-circle", "fa-tencent-weibo", "fa-trello", "fa-tripadvisor", "fa-tumblr", "fa-tumblr-square", "fa-twitch", "fa-twitter", "fa-twitter-square", "fa-usb", "fa-viacoin", "fa-vimeo", "fa-vimeo-square", "fa-vine", "fa-vk", "fa-wechat (alias)", "fa-weibo", "fa-weixin", "fa-whatsapp", "fa-wikipedia-w", "fa-windows", "fa-wordpress", "fa-xing", "fa-xing-square", "fa-y-combinator", "fa-y-combinator-square (alias)", "fa-yahoo", "fa-yc (alias)", "fa-yc-square (alias)", "fa-yelp", "fa-youtube", "fa-youtube-play", "fa-youtube-square", ] },{ title:"Medical Icons", list:[ "fa-ambulance", "fa-h-square", "fa-heart", "fa-heart-o", "fa-heartbeat", "fa-hospital-o", "fa-medkit", "fa-plus-square", "fa-stethoscope", "fa-user-md", "fa-wheelchair", ] } ] <file_sep>/src/js/cms_model/PageModel.OG_info.js PageModel.OG_info = (function() { /* ---------- ---------- ---------- */ var c = function(o) { this.init(o); } var p = c.prototype; /* ---------- ---------- ---------- */ p.param; p.id; p.name; p.note; p.sub; p.image; p.def;//フリーレイアウトの初期値として使用している p.callback; p.init = function(o) { this.param = o; this.setParam(); } p.setParam = function (){ this.id = defaultVal(this.param.id, ""); this.freeHTML = defaultVal(this.param.freeHTML, ""); this.name = defaultVal(this.param.name, ""); this.note = defaultVal(this.param.note, ""); this.sub = defaultVal(this.param.sub, ""); this.image = defaultVal(this.param.image, ""); this.def = defaultVal(this.param.def, ""); this.callback = defaultVal(this.param.callback, null); } p.getHeadTag = function (){ var tag = "" tag += '<div class="_head">' if(this.freeHTML != "")tag += this.freeHTML; if(this.name != "")tag += '<div class="_h2">'+this.name +'</div>' if(this.note != "")tag += '<div class="_read">'+this.note +'</div>' tag += this.getGuideImageTag(); tag += '</div>' return tag; } p.uid = "" p.getFootTag = function (){ var tag = ""; tag += '<div class="_foot">' if(this.sub != ""){ tag += '<div class="_read">'+this.sub +'</div>' } tag += '</div>' // if(this.callback){ this.uid = "_pagemodel_" + DateUtil.getRandamCharas(10); tag += '<div id="'+this.uid+'"></div>' } return tag; } p.getGuideImageTag = function (){ var tag = ""; if(this.image) tag += '<img src="' + this.image +'?1" style="">' return tag; } // p.callbackView p.update = function (o){ var s = "" if(this.callback){ // if(!this.callbackView) { // this.callbackView = $("#SubPageView").find("#"+this.uid); // console.log(this.callbackView); // } s = this.callback(o,this.uid); } return s; } p.getTestTag = function() { var tag = ""; tag += '<table class="_ut_info _ut_w200">'; tag += '<tr><th>id</th><td>' + this.id + '</td></tr>'; tag += '<tr><th>name</th><td>' + this.name + '</td></tr>'; tag += '<tr><th>note</th><td>' + this.note + '</td></tr>'; tag += '<tr><th>sub</th><td>' + this.sub + '</td></tr>'; tag += '<tr><th>image</th><td>' + this.image + '</td></tr>'; //tag += '<tr><th>def</th><td>' + this.def + '</td></tr>'; tag += '<tr><th>callback</th><td>' + this.callback + '</td></tr>'; tag += '</table>'; return tag; } return c; })();<file_sep>/src/js/cms_storage/Storage.StatusCheck.js var API_StatusCheck = (function(){ var view; var v = {}; function openAlert(_s){ if(CMS_AlertView){ CMS_AlertView.stageIn("エラー",_s); } else{ alert(_s); } } function check(data){ if(data["status"] != undefined){ if(data.status == -1) { openAlert("ログインしていません。再度、ログインしてください。"); window.location.reload(); return false; } if(data.status == 0){ var b = true if(data["level"] != undefined){ if(data.level == "0") b = false; } if(b){ var mm = data.message if(data.message == CMS_E.DIR_ERROR) { mm = ""; if(data["extra"] != undefined) mm += data.extra mm += "ディレクトリが存在しないか、書き込み権限がありません。" } openAlert("処理が正常に終了しませんでした。\n"+mm) return false; } else{ return true; } } if(data.status == 1){ return true; } } return true; } function checkWeak(data){ if(data["status"] != undefined){ if(data.status == -1) { openAlert("ログインしていません。再度、ログインしてください。"); window.location.reload(); return false; } if(data.status == 0){ return false; } if(data.status == 1){ return true; } } return true; } /** * ファイル名のリネームや、削除時のチェック * ファイルが存在しない場合があるので,0の場合もtrue */ /* function checkRename(data){ if(data["status"] != undefined){ if(data.status == -1) { openAlert("ログインしていません。再度、ログインしてください。"); window.location.reload(); return false; } if(data.status == 0){ return true; } if(data.status == 1){ return true; } } return true; } */ return { check: check, checkWeak: checkWeak }})(); <file_sep>/js_cms/_cms/grid/grid_setting.js //サイトマップパス (JS CMS形式) var GRID_SITEMAP_JSON = "../../html/_setting/sitemap.json"; //サイトマップパス (テキスト形式) //var GRID_SITEMAP_TXT = "grid_sitemap.txt"; //var GRID_SITEMAP_TXT = "__grid_sitemap_test.txt"; //カスタマイズ用のタブ var GRID_MY_TAB = ["A","B","C","D","E"]; //一度に表示するページ数 var GRID_PAGE_UNIT = 10; //編集ページURL var GRID_EDIT_URL = "../#"; //プリセット var GRID_PRESETs = [ { scale: 33.3, height: 1200, widths: [1200] }, { scale: 15, height: 4000, widths: [1200] }, { scale: 50, height: 1500, widths: [320] }, { scale: 25, height: 1500, widths: [800] }, { scale: 25, height: 1500, widths: [1200, 320] } ]; <file_sep>/src/js/cms_view_imagemap/ImageMap.06.js ImageMap.LayerClass = (function() { /* ---------- ---------- ---------- */ var c = function() { this.init(); } var p = c.prototype; /* ---------- ---------- ---------- */ p.view; p.v; p.init = function() { var s = '<div class="_layer" data-no="{NO}"></div>'; this.view = $(s); this.v = {} } p.setData = function(_class,_i){ this.class = _class; this.no = _i; this.update(); } p.update = function(){ var self = this; var s = '{I_V1}{I_V2} <div class="_lock">{I_L1}{I_L2}</div> {NO}.{TEXT}'; s = s.split("{NO}").join(this.no); s = s.split("{TEXT}").join(ImageMapCode.getLayerData(this.class.data)); s = s.split("{I_V1}").join('<span class="_btn_hide_on"><i class="fa fa-eye-slash"></i></span>'); s = s.split("{I_V2}").join('<span class="_btn_hide_off"><i class="fa fa-eye"></i></span>'); s = s.split("{I_L1}").join('<span class="_btn_lock_on"><i class="fa fa-lock "></i></span>'); s = s.split("{I_L2}").join('<span class="_btn_lock_off"><i class="fa fa-unlock-alt "></i></span>'); this.view.html(s); this.view.click(function(){ self.selectItem()}) this.v.btn_hide_on = this.view.find("._btn_hide_on"); this.v.btn_hide_off = this.view.find("._btn_hide_off"); this.v.btn_lock_on = this.view.find("._btn_lock_on"); this.v.btn_lock_off = this.view.find("._btn_lock_off"); this.v.btn_hide_on.click(function(){ self.hideItem(false) }) this.v.btn_hide_off.click(function(){ self.hideItem(true) }) this.v.btn_lock_on.click(function(){ self.lockItem(false) }) this.v.btn_lock_off.click(function(){ self.lockItem(true) }) this.updateCheck(); } p.updateCheck=function(){ this.v.btn_hide_on.hide(); this.v.btn_hide_off.hide(); this.v.btn_lock_on.hide(); this.v.btn_lock_off.hide(); if(this.class.data.hide){ this.v.btn_hide_on.show(); } else{ this.v.btn_hide_off.show(); } if(this.class.data.lock){ this.v.btn_lock_on.show(); } else{ this.v.btn_lock_off.show(); } if(this.class.isCurrent){ this.select(); } } /* ---------- ---------- ---------- */ p.updateData=function(){ this.update(); } /* ---------- ---------- ---------- */ p.selectItem=function(){ this.class.selectItem(); // ImageMap.MainStage.selectItem(this.class); } p.hideItem=function(_b){ this.class.data.hide = _b; ImageMap.MainStage.hideItem(this.no,_b); this.updateCheck(); } p.lockItem=function(_b){ this.class.data.lock = _b; ImageMap.MainStage.lockItem(this.no,_b); this.updateCheck(); } /* ---------- ---------- ---------- */ p.select=function(){ this.view.addClass("_current") } p.unselect=function(){ this.view.removeClass("_current") } p.getView=function(){ return this.view; } return c; })(); <file_sep>/src/js/cms_model/PageTypeList.free.js window.FREEPAGE_DEF_DATA = [ { "type": "tag.heading", "data": { "heading": "h1", "main": { "text": "{{PAGE_NAME}}", "link": null }, "right": { "text": "", "link": null } }, "attr": { "css": "default", "narrow": "", "class": "default", "hide": "" } }, { "type": "tag.markdown", "data": "##大見出し\n文書が入ります。文書が入ります。文書が入ります。文書が入ります。文書が入ります。文書が入ります。文書が入ります。文書が入ります。文書が入ります。文書が入ります。文書が入ります。\n\n###中見出し\n文書が入ります。文書が入ります。文書が入ります。文書が入ります。\n\n####小見出し\n文書が入ります。文書が入ります。文書が入ります。\n\n * 項目1\n * 項目2\n * 項目3\n", "attr": { "preview": "", "narrow": "", "class": "default", "hide": "", "css": "default " } } ] PageTypeList.page = (function(){ var _ = new PageModel.Object_(); /* ---------- ---------- ---------- */ _.pageInfo = new PageModel.Object_Info({ id : "free", name : "自由入力ページ", }); /* ---------- ---------- ---------- */ _.grids = [ /* ---------- ---------- ---------- */ new PageModel.Object_Grid({ gridType:Dic.GridType.FREE, gridInfo:new PageModel.OG_info({ id : "free", name : "自由入力エリア", def : [{ "type": "layout.div", "attr": {}, "data": FREEPAGE_DEF_DATA }] }) }) /* ---------- ---------- ---------- */ ] /* ---------- ---------- ---------- */ return _; })(); <file_sep>/src/js/cms_model/PageElement.object.tabList.js PageElement.object.tabList = (function(){ var _ = new PageModel.Object_(); /* ---------- ---------- ---------- */ _.pageInfo = new PageModel.Object_Info({ id : "object.tabList", name : "タブリスト", name2 : "", inputs : ["CLASS","CSS","DETAIL"], // cssDef : {file:"block",key:"[タブリストブロック]"} cssDef : {selector:".cms-tab"} }); /* ---------- ---------- ---------- */ _.grids = [ /* ---------- ---------- ---------- */ new PageModel.Object_Grid({ gridType:Dic.GridType.BASE, gridInfo:new PageModel.OG_info({ id : "list", name : "リスト<UL>", note : "" }), textData:null, gridData:{ info:new PageModel.OG_SubInfo({}), cells:[ new PageModel.OG_Cell({ id: "t1", name: "タブ名<LI>", type: CELL_TYPE.SINGLE }), new PageModel.OG_Cell({ id: "id", name: "選択したときに表示する要素ID", type: CELL_TYPE.SINGLE }), new PageModel.OG_Cell({ id: "class", name: "class", type: CELL_TYPE.SINGLE }) ] } }) /* ---------- ---------- ---------- */ ] _.getInitData = function(){ var o = {}; o.type = _.pageInfo.id; o.data = JSON.parse('{"list": {"texts": {},"grid": [{"t1": "タブ01","id": "tab01","publicData": "1"},{"t1": "タブ02","id": "tab02","publicData": "1"},{"t1": "タブ03","id": "tab03","publicData": "1"}]}}') o.attr = {css:"default",style:""}; o.attr.class = o.attr.css; return o; } _.getPreview = function(_o){ var data = _o.data; var attr = _o.attrs; var tag = ""; attr = attr.split('class="').join('class="cms-tab clearfix '); var list = CMS_U.getPublicList(data.list.grid); if(list.length == 0 ){ tag += '<span class="_no-input-data">タブデータを入力...</span>' } else{ var style = ""; tag += '<ul '+ attr+' >\n'; for (var i = 0; i < list.length ; i++) { var c = (list[i]["class"] != undefined) ? list[i]["class"] :""; tag += ' <li style="' + style +'" data="'+list[i].id+'" class="'+c+'">' tag += list[i].t1 tag += '</li>\n' } tag += '</ul>\n' } return tag; } _.getHTML = function(_o){ var data = _o.data; var attr = _o.attrs; var tag = "" attr = attr.split('class="').join('class="cms-tab clearfix ') var list = CMS_U.getPublicList(data.list.grid); if(list.length == 0) return ""; { var style = ""; tag += '<ul '+ attr+'>\n'; for (var i = 0; i < list.length ; i++) { var c = (list[i]["class"] != undefined) ? list[i]["class"] :""; tag += ' <li style="' + style +'" data="'+list[i].id+'" class="_btn_default '+c+'">' tag += list[i].t1 tag += '</li>\n' } tag += '</ul>\n' tag += '<script>\n' tag += '$(function(){\n'; tag += ' $(".cms-tab").cms_tab();\n'; tag += '});\n'; tag += '</script>\n'; } return tag; } /* ---------- ---------- ---------- */ return _; })(); <file_sep>/src/js/cms_model/PageElement.js var PageElement = {} window.PageElement = PageElement; <file_sep>/tasks/css.js var gulp = require("gulp"); var sass = require("gulp-sass"); var pleeease = require('gulp-pleeease'); var sourcemaps = require('gulp-sourcemaps'); var concat = require("gulp-concat") var runSequence = require('run-sequence'); /* ! ---------- __val__ ---------- ---------- ---------- ---------- */ var dir = './js_cms/_cms/css'; var css = { main:{ dest:'cms.css', src:[ "./src/sass/cms.scss" ] } } /* ! ---------- __val__ ---------- ---------- ---------- ---------- */ gulp.task("sass", function() { return gulp.src(css.main.src) //.pipe(sourcemaps.init()) .pipe(sass()) .pipe(pleeease({ autoprefixer: { 'browsers': ['last 2 versions','IE 9']}, mqpacker: false, minifier: false //out: 'all.min.css', })) //.pipe(sourcemaps.write('./maps')) .pipe(gulp.dest(dir)); }); gulp.task('concat:css', function(callback) { return runSequence( 'sass', callback ); }); <file_sep>/src/js/cms_view_modals/Editer_CodeCopyView.js var Editer_CodeCopyView = (function(){ var view; var v = {}; function init(){ view = $('#Editer_CodeCopyView'); stageInit(); } /* ---------- ---------- ---------- */ function createlayout(){ v = ModalViewCreater.createBaseView(Editer_CodeCopyView,view); var tag = ""; tag = '<div class="_title">コードコピー</div>'; v.header.html(tag); tag = ""; tag += '<div class="_read"></div>'; tag += '<textarea id="codeFrame" wrap="off" readonly></textarea> '; v.body.html(tag); v.read = v.body.find("._read"); v.codeFrame = view.find('#codeFrame'); tag = ""; tag += '<div class="_cms_btn _btn_close">閉じる</div> '; v.footer.html(tag); v.textarea = view.find('textarea'); setBtn(); } function setBtn(){ view.find('._bg ,._btn_close').click(function(){ stageOut() }); } function update(_type,_a){ if(_type == "formMail"){ updateFormMail(_a); } } function updateFormMail(_a){ v.read.html("以下のコードを、<b>php/mail.php</b>へコピーし保存してください。"); var temp = CMS_Data.CodeDic.getCode("mailform.php"); temp = temp.split("{MAIL}").join(_a[0]); temp = temp.split("{FORMS}").join(_a[1]); v.codeFrame.val(temp); } /* ---------- ---------- ---------- */ //class style function getData(){ return "" } /* ---------- ---------- ---------- */ function compliteEdit(){ stageOut(); } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); createlayout(); } var callback function stageIn(_type,_a,_callback){ if(! isOpen){ isOpen = true; showModalView(this); callback = _callback; view.show(); if(isFirst){} isFirst = false; update(_type,_a); resize(); } } function stageOut(){ if(isOpen){ isOpen = false; hideModalView(); view.hide(); } } function resize(){ if(isOpen){ var h = $(window).height() -300; v.codeFrame.height(h); } } return { init:init, stageIn:stageIn, stageOut:stageOut,resize:resize,compliteEdit:compliteEdit } })(); <file_sep>/src/js/cms_view_floats/Float_Preview.2.js var Float_PreviewTab = (function(){ var view; var v = {}; function init(){ view = $('#Float_PreviewTab'); stageInit(); createlayout(); setBtn(); } /* ---------- ---------- ---------- */ function createlayout(){ var tag = ""; tag += '<div class="_inner"></div>'; view.html(tag) v.inner = view.find('._inner'); } function setBtn(){ view.hover(function(){ if(tID) clearTimeout(tID) } , function(){ stageOut(); }) } /* ---------- ---------- ---------- */ function update(_x,_param){ updatePos(_x); var tag = '' tag += '<span class="_name">{NAME}</span> ' if(_param.type == "page"){ tag += '<span class="_filePath_blue">{URL_ABS}</span>' } var name = (_param.name) ? _param.name :_param.id; v.inner.html(name); var tempP = { name :name, id :_param.id, dir :_param.dir, prevPub :"" } v.inner.html( Float_Preview.DoTemplate( tag , tempP )); } /* ---------- ---------- ---------- */ var isHover = false function updatePos(_x){ view.css("left", _x + "px"); view.hover( function(){ isHover = true; }, function(){ isHover = false; stageOut() } ) } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } function stageIn(_x,_param){ view.show(); update(_x,_param) } var tID function stageOut(){ if(isHover)return; view.hide(); } function stageOut_core(){ if(tID) clearTimeout(tID) view.hide(); } return { init: init, stageIn: stageIn, stageOut: stageOut, stageOut_core: stageOut_core } })();<file_sep>/README.md # JS CMS v4.1.5.3 簡単・無料・国産のWebデザイナー向けCMSです。 このページでは、JS CMSのソースコードを配布しています。 ソースコードといっても、JSファイルを連結して、`/js-cms/js_cms/_cms/js/cms.js`を生成するのと、`/js_cms/_cms/css/cms.css`をSASSから生成するだけです。 ## 公式サイト http://www.js-cms.jp/ ## ライセンス MIT licenses <file_sep>/src/js/cms_view_modals/CMS_LogView.js var CMS_LogView = (function(){ var view; var v = {}; function init(){ view = $('#CMS_LogView'); stageInit(); } /* ---------- ---------- ---------- */ function log(_s){ stageIn(); view.html(_s); } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } function stageIn(){ if(! isOpen){ isOpen = true; view.show(); if(isFirst){} isFirst = false; } } function stageOut(){ if(isOpen){ isOpen = false; view.hide(); } } return { init: init, log: log, stageIn: stageIn, stageOut: stageOut } })(); <file_sep>/src/js/cms_view_editable/EditableView.FreeLayoutCols.js EditableView.FreeLayoutCols = (function() { /* ---------- ---------- ---------- */ var c = function(_gridType) { this.init(_gridType); } var p = c.prototype; /* ---------- ---------- ---------- */ p.init = function () { this.v = {}; } p.registParent = function (_parent,_parentView,_pageParam,_deep){ this.parent = _parent; this.parentView = _parentView; this.pageParam = _pageParam; this.deep = (_deep == null) ? 0 : _deep; } /* ---------- ---------- ---------- */ //#Data p.initData = function (_data,_no){ this.no = _no; this.type = _data.type; this.attr = _data.attr; this.gridData = new EditableView.GridClass(); if(_data.data.length == 0) _data.data = []; this.gridData.initRecords(_data.data); this.setInitView(); this.update(); } p.changeData = function (data,no){ this.gridData.overrideRecordAt(data,no); this.parent.updateSubData(); } p.duplicateData = function (no){ this.gridData.duplicateAt(no); this.parent.update(); this.parent.updateSubData(); } p.removeData = function (no){ this.gridData.removeRecordAt(no); this.parent.update(); this.parent.updateSubData(); InspectView.stageOut(); } p.setInitView = function (){ var list = this.gridData.getRecords(); var self = this; var style = CMS_BlockAttrU.getStyle(this.attr); var class_ = CMS_BlockAttrU.getClass(this.attr); var blockInfo = CMS_BlockAttrU.getMarkTag(this.attr,true) var tag = ''; tag += '<div class="_freeLayoutTable _freeLayoutToggle " data-no="'+this.no+'" style="'+style+'">'; tag += '<div class="cms-column ' + class_ + '">'; for (var i = 0; i < list.length ; i++) { tag += ' <div class="cms-column-col " data-no="'+i+'"></div>'; } tag += '</div>'; tag += blockInfo; tag += '<span class="_btn_delete"></span>'; if(this.deep == 1){ if(this.attr.narrow){ tag += '<span class="_block_toggle _block_toggle_close"></span>'; } else{ tag += '<span class="_block_toggle"></span>'; } } tag += '</div>'; this.view = $(tag); this.parentView.append(this.view); this.v.replaceView = this.view.find('> .cms-column > .cms-column-col'); this.view.find(' > ._btn_delete').click(function(){ $(this).parent().click(); InspectView.doCommand("delete"); }); this.view.find(' > ._block_toggle').click(function(){ $(this).parent().click(); $(this).toggleClass("_block_toggle_close"); InspectView.doCommand("toggle"); }); } p.update = function (){ var self = this; var list = this.gridData.getRecords(); for (var i = 0; i < list.length ; i++) { var divNode = new EditableView.FreeLayout(); divNode.registParent(this,this.v.replaceView.eq(i),this.pageParam,this.deep +1); divNode.initData(list[i],i); divNode.view.click(function(event){ event.stopPropagation(); event.preventDefault(); InspectView.setPageData(self.pageParam); InspectView.setData("layout.colDiv",$(this),self,$(this),$(this)); }); } DragController.setDrag(this.parent,this.view,DragController.FREE_DROP); this.updateSubData(); } p.updateSubData = function (){ this.parent.updateSubData(); } return c; })();<file_sep>/src/js/cms_storage/Storage.Embed.js Storage.Embed = (function(){ /* ---------- ---------- ---------- */ function checkDirExist(_path,_callback){ var param = {} param.action = "checkDir"; param.dir_name = CMS_Path.SITE.REL + URL_U.getBaseDir(_path); // checkCommon(param,_callback) } function checkFileExist(_path,_callback){ var param = {} param.action = "checkFile"; param.file_name = URL_U.getFileName(_path); param.dir_name = CMS_Path.SITE.REL + URL_U.getBaseDir(_path); // checkCommon(param,_callback) } function checkCommon(param,_callback){ var url = CMS_Path.PHP_EMBED; $.ajax({ scriptCharset : 'utf-8', type : 'GET', url : url, data : Storage.Util.escape_(param), dataType : 'json', success : function(data) { if(API_StatusCheck.checkWeak(data) == false) { _callback(data.message); } else { _callback(""); } }, error : function(data) { _callback(false); CMS_ErrorView.stageIn("NET",url,null,data); } }); } /* ---------- ---------- ---------- */ function loadFile(_path,_callback){ var param = {} param.action = "read"; param.file_name = URL_U.getFileName(_path); param.dir_name = CMS_Path.SITE.REL + URL_U.getBaseDir(_path); var url = CMS_Path.PHP_EMBED; $.ajax({ scriptCharset : 'utf-8', type : 'GET', url : url, data : Storage.Util.escape_(param), dataType : 'text', success : function(data) { if(API_StatusCheck.checkWeak(data) == false) { _callback(false); } else { _callback(true,data); } }, error : function(data) { _callback(false); CMS_ErrorView.stageIn("NET",url,param,data); } }); } /* ---------- ---------- ---------- */ function writeFile(_path,_text,_callback){ if(_text.length > 1000*10){ writeFile_temp(_path,_text,_callback); return; } var param = {} param.action = "write"; param.file_name = URL_U.getFileName(_path); param.dir_name = CMS_Path.SITE.REL + URL_U.getBaseDir(_path); param.text = _text; var url = CMS_Path.PHP_EMBED; $.ajax({ scriptCharset : 'utf-8', type : 'POST', url : url, data : Storage.Util.escape_(param), dataType : 'json', success : function(data) { writeFile_comp(_callback,data); }, error : function(data) { _callback(false); CMS_ErrorView.stageIn("NET",url,param,data); } }); } function writeFile_temp(_path,_text,_callback){ var param = {} param.action = "writeToTemp"; param.file_name = URL_U.getFileName(_path); param.dir_name = CMS_Path.SITE.REL + URL_U.getBaseDir(_path); param.text = _text; var afterParam = {} afterParam.action = "renameTemp"; afterParam.file_name = param.file_name; afterParam.dir_name = param.dir_name; var url = CMS_Path.PHP_EMBED; $.ajax({ scriptCharset : 'utf-8', type : 'POST', url : url, data : Storage.Util.escape_(param), dataType : 'json', success : function(data) { writeFile_rename(_callback,data,afterParam)}, error : function(data) { CMS_ErrorView.stageIn("NET",url,param,data); _callback(false); } }); } function writeFile_rename (_callback,data,param){ var this_ = this; if(API_StatusCheck.checkWeak(data) == false) { _callback(false); return; } var url = CMS_Path.PHP_EMBED; $.ajax({ scriptCharset : 'utf-8', type : 'POST', url : url, data : Storage.Util.escape_(param), dataType : 'json', success : function(data) {writeFile_comp(_callback,data)}, error : function(data) { CMS_ErrorView.stageIn("NET",url,param,data); _callback(false) } }) } function writeFile_comp (_callback,data){ if(API_StatusCheck.checkWeak(data) == false) { _callback(false); } else{ _callback(true); } } /* ---------- ---------- ---------- */ //削除 function deleteFile(_path,_callback){ var param = {} param.action = "delete"; param.file_name = URL_U.getFileName(_path); param.dir_name = CMS_Path.SITE.REL + URL_U.getBaseDir(_path); var url = CMS_Path.PHP_EMBED; $.ajax({ scriptCharset : 'utf-8', type : 'POST', url : url, data : Storage.Util.escape_(param), dataType : 'json', success : function(data) { if(API_StatusCheck.checkWeak(data) == false) { _callback(false); } else { _callback(true); } }, error : function(data) { CMS_ErrorView.stageIn("NET",url,param,data); } }); } return { checkDirExist : checkDirExist, checkFileExist : checkFileExist, loadFile : loadFile, writeFile : writeFile, deleteFile : deleteFile } })(); <file_sep>/src/js/cms_main/CMS_LivePreviewController.js var CMS_LivePreviewController = (function(){ //ページ開いた時にコールされる function openedPage(){ if(! CMS_PageDB.hasCurrent())return; CMS_SidePreview.openedPage(); } //ページ更新があったら、コールされる //ブロック操作時、保存時など function editedPage(_delay){ if(! CMS_PageDB.hasCurrent())return; CMS_SidePreview.editedPage(_delay); } //保存時にコールされる function savedPage(){ if(! CMS_PageDB.hasCurrent())return; CMS_SidePreview.savedPage(); } function publishedPage(){ if(! CMS_PageDB.hasCurrent())return; CMS_SidePreview.publishedPage(); } return { openedPage: openedPage, editedPage: editedPage, savedPage: savedPage, publishedPage: publishedPage } })(); <file_sep>/src/js/cms_model/PageElement.tag.btn.js PageElement.tag.btn = (function(){ var _ = new PageModel.Tag_(); /* ---------- ---------- ---------- */ _.pageInfo = new PageModel.Object_Info({ id : "tag.btn", name : "ボタン", name2 : "<A>", inputs : ["CLASS","CSS"], cssDef : {selector:".cms-btn"} }); /* ---------- ---------- ---------- */ _.getInitData = function(_param){ var o = {}; o.type = _.pageInfo.id; o.data = CMS_AnchorU.getInitData(); o.data.href="#" if(_param){ o.data.href = _param.url; o.data.text = URL_U.getFileName(_param.url); } o.attr = {} return o; } /* ---------- ---------- ---------- */ _.getPreview = function(_o){ var data = _o.data; var attr = _o.attrs; attr = attr.split('class="').join('class="cms-btn '); var tag = "" tag += '<div '+attr+'>' + CMS_AnchorU.getAnchorTag(data,"",false,true) + '</div>'; return tag; } /* ---------- ---------- ---------- */ _.getHTML = function(_o,_tab){ var data = _o.data; var attr = _o.attrs; attr = attr.split('class="').join('class="cms-btn '); var tab = (_tab != undefined) ? _tab:""; var idTag = "" if(_o.id) idTag = ' id="'+_o.id+'"'; var tag = ""; tag += _tab + '<div '+attr+'>' + CMS_AnchorU.getAnchorTag(data , idTag,true,true) + '</div>'; return tag; } /* ---------- ---------- ---------- */ return _; })();<file_sep>/src/js/cms_data/CMS_Data.Sitemap.js /** * サイトマップデータ管理 */ CMS_Data.Sitemap = (function(){ function init(){ createIgnoreList(); } /* ---------- ---------- ---------- */ //初期ロード var callback; function load(_callback){ var param = Dic.SettingList; callback = _callback storage = new Storage.Online(Dic.PageType.SYSTEM,param.id,param.dir,{}) storage.load(function() { load_comp(); }); } var storage; function load_comp(){ var d = storage.getData(); if(d.list == undefined){ storage.setData({list:[]}); } sitemap = storage.getData(); update(); callback(); } /* ---------- ---------- ---------- */ //更新のたびにコールされる var sitemap; var tID; function update(){ if(tID) clearTimeout(tID); tID = setTimeout(function(){ setTreat(); setGloupPath(); toFlat(); },50); } /* ---------- ---------- ---------- */ //サイトマップデータを奇麗にする //ディレクトリにUIDが無い場合、セット。 function setDirUID(_dir){ if(! _dir.uid){ _dir.uid = "dir_" + DateUtil.getFormattedDate(new Date(),"YYYYMMDD_RRR"); } } function setTreat(){ setDirUID(sitemap); setTreat_loop(sitemap.list); } function setTreat_loop(_list){ if(_list == undefined)return; for (var i = 0; i < _list.length ; i++) { if(_list[i]){ if(_list[i].type == Dic.ListType.DIR){ setDirUID(_list[i]); setTreat_loop(_list[i].list) } else if(_list[i].type == Dic.PageType.PAGE) { if(_list[i].dir == undefined) _list[i].dir = "" } } } } /* ! ---------- ---------- ---------- ---------- ---------- */ function getGloup_by_uid(_uid){ var ls = sitemapFlatGloups; for (var i = 0; i < ls.length ; i++) { if(ls[i].uid == _uid){ return ls[i]; } } return null; } /* ! ---------- ---------- ---------- ---------- ---------- */ //グループパスDICを作成 var gloupPathDIC = []; function setGloupPath(){ gloupPathDIC = []; setGloupPath_loop(sitemap.list ,"","") } function setGloupPath_loop(_list,_gid,_gname){ if(_list == undefined)return; for (var i = 0; i < _list.length ; i++) { if(_list[i]){ if(_list[i].type == Dic.ListType.DIR){ var id = _gid + "/" + _list[i].id var na = _gname + "/" + _list[i].name setGloupPath_loop(_list[i].list,id,na); } else if(_list[i].type == Dic.PageType.PAGE) { gloupPathDIC.push([_list[i].id,_list[i].dir, _gid, _gname]); } } } } function getGloup_by_id(_id,_dir){ for (var i = 0; i < gloupPathDIC.length ; i++) { if(gloupPathDIC[i][0] == _id){ if(gloupPathDIC[i][1] == _dir){ return gloupPathDIC[i]; } } } return null } function getGloupPath_by_id(_id,_dir){ var param = getGloup_by_id(_id,_dir); if(param == null)return ""; return param[2]; } function getGloupName_by_id(_id,_dir){ var param = getGloup_by_id(_id,_dir); if(param == null)return ""; return param[3]; } //PageViewのヘッダで使用 function getGloupState_by_id(_currnet){ var s = ""; s +='<span class="_cms_wide _cms_hide_preview">現在のテンプレ:</span><b><span data-id="{TEMPLATE}">{TEMPLATE}</b> <i class="fa fa-caret-down fa-lg"></i>' var sels = CMS_Data.Template.getSelectList(); s += '<div class="_templatesFloat">'; s += '<div class="_read">ページで使用するテンプレートを選択してください。</div>'; for (var i = 0; i < sels.length ; i++) { var icon = (function(_cu,_name){ if(_name == "")_name = Dic.DEFAULT_TEMPLATE; var _s = '<i class="fa fa-square-o"></i> '; if(_cu == _name){ _s = '<i class="fa fa-check-square "></i> '} return _s; })(_currnet,sels[i][0]); var id = CMS_Data.Template.getTemplateName(sels[i][0]); s += '<div class="_item" data-id="' + id + '">' // s += '<span class="_btn_edit_tempalte" data-id="'+ id +'"><i class="fa fa-pencil "></i> 編集</span>' s += icon + sels[i][1]; s += '</div>'; } s += '</div>'; s = s.split("{TEMPLATE}").join(_currnet); return s; } /* ! ---------- ---------- ---------- ---------- ---------- */ //ファイルID入力フォームの候補表示用 var sitemapFlat = [];//ファイルID var sitemapFlatGloups = [];//グループID function toFlat(){ sitemapFlat = []; sitemapFlatGloups = []; sitemapFlatGloups.push(sitemap); toFlatLoop(sitemap.list); if(window["FormCandidates"]){ FormCandidates.setSitemapList(sitemapFlat,sitemapFlatGloups); } } function toFlatLoop(_list){ for (var i = 0; i < _list.length ; i++) { if(_list[i]){ if(_list[i].type==Dic.ListType.DIR){ sitemapFlatGloups.push(_list[i]) } if(_list[i].list){ toFlatLoop(_list[i].list) } else{ if(_list[i].type==Dic.PageType.PAGE){ sitemapFlat.push(_list[i]) } } } } } /* ! ---------- ---------- ---------- ---------- ---------- */ //NGファイルリスト検索 var ignoreList = []; function createIgnoreList(){ ignoreList = []; for (var n in Dic.SettingList) { if($.isArray(Dic.SettingList[n])){ for (var i = 0; i < Dic.SettingList[n].length ; i++) { ignoreList.push(Dic.SettingList[n][i]); } } else{ ignoreList.push(Dic.SettingList[n]) } } } var match; function find(_id,_dir){ if(_dir == undefined) _dir = ""; match = null; var b = false; for (var i = 0; i < ignoreList.length ; i++) { if(_id == ignoreList[i].id){ if(_dir == ignoreList[i].dir){ b = true; } } } if(b)return; find_loop(_id,_dir,sitemap.list,0); } function find_loop(_id,_dir,_list,_deep){ for (var i = 0; i < _list.length ; i++) { if(_list[i]){ if(_list[i].id == _id){ if(_list[i].dir == _dir){ match = _list[i]; } } if(_list[i].list) { find_loop(_id,_dir,_list[i].list,_deep+1) } } } } function getData_by_id(_id,_dir){ find(_id,_dir); return match; } /* ! ---------- ---------- ---------- ---------- ---------- */ //#IO //IDに該当するファイルの更新日を最新にして、保存する var tID_later_save; function saveDateLater(_id,_dir){ saveDate(_id,_dir,1) } function saveDate(_id,_dir,_delayTime){ if(_id == "_sitemap") return; find(_id,_dir); if(! match)return; match.saveDate = CMS_SaveDateU.getDate(); //連続書き込みをさけるため、ディレイ処理 if(tID_later_save) clearTimeout(tID_later_save); if(_delayTime == undefined){ save(); } else{ tID_later_save = setTimeout(function(){ save(); },_delayTime*1000); } } //IDに該当するファイルの公開日を最新にして、保存する //20161202追加 function publicDateInit(_id,_dir){ if(_dir == "_sitemap") return; find(_id,_dir); if(! match) return; if(match.publicDate == "-"){ match.publicDate = CMS_SaveDateU.getDate(); } } var tID_later_public; function publicDateLater(_id,_dir){ publicDate(_id,_dir,1) } function publicDate(_id,_dir,_delayTime){ if(_dir == "_sitemap") return; find(_id,_dir); if(! match) return; match.publicDate = CMS_SaveDateU.getDate(); //連続書き込みをさけるため、ディレイ処理 if(tID_later_public) clearTimeout(tID_later_public); if(_delayTime == undefined){ save(); } else{ tID_later_public = setTimeout(function(){ save(); },_delayTime*1000); } } function unPublicDateLater(_id,_dir){ unPublicDate(_id,_dir,1) } function unPublicDate(_id,_dir,_delayTime){ if(_dir == "_sitemap") return; find(_id,_dir); if(! match)return; match.publicDate = ""; save(); } //save var tID_save; function save(){ //サイトマップを更新すると、同時にリクエストがくるので、1つにしぼる if(tID_save) clearTimeout(tID_save); tID_save = setTimeout(function(){ storage.setData(getData()); storage.save_sitemap(function(){ if(isLog)console.log("list saved.") }); },500); } /* ! ---------- ---------- ---------- ---------- ---------- */ //保存した日付をかえす function getSaveDate(_id,_dir){ find(_id,_dir); if(! match)return ""; return match.saveDate; } //公開した日付をかえす function getPublishDate(_id,_dir){ find(_id,_dir); if(! match)return ""; return match.publicDate; } function getData(){ return sitemap; } function getFilelist() { if(sitemap == undefined) return [] return sitemap.list; } /* ! ---------- ---------- ---------- ---------- ---------- */ //リビジョンを返す function getRevision(_id,_dir){ find(_id,_dir); if(! match) return []; if(match["revision"]) { return match["revision"]; } else{ return []; } } function addRevision(_id,_dir,_date){ find(_id,_dir); if(! match) return []; if(match["revision"] == undefined) match.revision = []; match.revision.unshift(_date); save(); } function removeRevision(_id,_dir,_date){ find(_id,_dir); if(! match) return []; if(match["revision"] == undefined) match.revision = []; var a = []; var b = false; for (var i = 0; i < match.revision.length ; i++) { if(_date != match.revision[i]){ a.push(match.revision[i]); b = true; } } if(match.revision.length != a.length ) match.revision = a; save(); } /* ! ---------- ---------- ---------- ---------- ---------- */ return { init:init, load:load, update:update, getData:getData, getFilelist:getFilelist, save:save, saveDate:saveDate, publicDate:publicDate, publicDateInit:publicDateInit, saveDateLater:saveDateLater, publicDateLater:publicDateLater, unPublicDateLater:unPublicDateLater, getSaveDate:getSaveDate, getPublishDate:getPublishDate, getData_by_id:getData_by_id, getGloupPath_by_id:getGloupPath_by_id, getGloupName_by_id:getGloupName_by_id, getGloupState_by_id:getGloupState_by_id, getGloup_by_uid : getGloup_by_uid, getRevision:getRevision, addRevision:addRevision, removeRevision:removeRevision } })(); <file_sep>/src/js/cms_stage_asset/CMS_Asset_UploaderView2.js var CMS_Asset_UploaderView2 = (function() { /* ---------- ---------- ---------- */ var c = function(_view,_dir,_fileListClass,_callback) { this.init(_view,_dir,_fileListClass,_callback); } var p = c.prototype; /* ---------- ---------- ---------- */ p.view; p.callback; p.v; p.init = function(_view,_dir,_fileListClass,_callback) { CMS_Asset_UploaderState.init(); var this_ = this; this.view = _view; this.dir = _dir; this.callback = _callback; this.fileListClass = _fileListClass; this.v = {} this.createView(); } p.createView= function(_view) { var this_ = this; var tag = ""; tag += '<div class="_list"></div>'; tag += '<div class="_list_btns ">'; tag += ' <div class="_upload_btn_uploads _cms_btn _cms_btn_active"><i class="fa fa-upload "></i> まとめてアップロード</div>'; tag += ' <div class="_upload_btn_deletes _cms_btn "><i class="fa fa-minus-circle " style="color:red"></i> クリア</div>'; tag += '</div>'; tag += '<div class="_dragStage"><i class="fa fa-sign-in "></i> ここにファイルをドラッグ&ドロップしてください。</div>'; tag += '<div class="_notes" style="margin:10px 0">' tag += ' ※ファイル名は、半角英数字小文字でアップロードする必要があります。<br>' tag += ' - 大文字は小文字に自動変換されます<br>' tag += ' - 全角文字の場合は、リネームしてください<br>' tag += ' ※画像ファイルの場合は、最大寸法を超える場合は、収まるようにリサイズされます。<br>' tag += '  最大寸法は、/_cms/setting/setting.jsで設定できます。' tag += '</div>'; this.view.html(tag); this.v.dragStage = this.view.find("._dragStage"); this.v.list = this.view.find("._list"); this.v.list_btns = this.view.find("._list_btns"); this.v.upload_btn_uploads = this.view.find("._upload_btn_uploads"); this.v.upload_btn_uploads.click(function(){ if(window.isLocked(true))return; this_.uploads(); }); this.v.upload_btn_deletes = this.view.find("._upload_btn_deletes"); this.v.upload_btn_deletes.click(function(){ this_.clearAll(); }); this.setEvent() this.checkServer(); } p.setEvent = function() { var this_ = this; var dragStage = this.v.dragStage; dragStage.on('dragenter', function(e) { e.stopPropagation(); e.preventDefault(); $(this).css('border', '1px solid #0B85A1'); CMS_Asset_UploaderState.setCurrentDragStage($(this)) }); dragStage.on('dragover', function(e) { e.stopPropagation(); e.preventDefault(); }); dragStage.on('drop', function(e) { $(this).css('border', '1px dashed #0B85A1'); e.preventDefault(); this_.dragFileCheck(e.originalEvent.dataTransfer.files); }); } p.checkServer = function() { CMS_Asset_UploaderState.checkServer(function(){}); } p.removeFile = function(_id) { var a = [] for (var i = 0; i < this.CMS_Asset_UploadClass.length ; i++) { if(this.CMS_Asset_UploadClass[i].id != _id) a.push(this.CMS_Asset_UploadClass[i]) } this.CMS_Asset_UploadClass = a; this.updateList(); } p.CMS_Asset_UploadClass p.reset = function() { this.CMS_Asset_UploadClass = [] } p.dragFileCheck = function(files) { if(this.CMS_Asset_UploadClass ==undefined) this.reset(); for (var i = 0; i < files.length; i++) { if(isLog) console.log(files[i]); if (CMS_Asset_UploadU.checkUploadableFile(files[i].type)) { if(this.checkSameFile(files[i].name) ==false){ var uid = "_upload" + DateUtil.getRandamCharas(10); this.CMS_Asset_UploadClass.push(new CMS_Asset_UploadClass(this,files[i],this.dir,uid)); } } } this.initStart(); } p.initStart = function() { var this_ = this; var initedCount = 0 var leng = this.CMS_Asset_UploadClass.length for (var i = 0; i < this.CMS_Asset_UploadClass.length ; i++) { this.CMS_Asset_UploadClass[i].initStart(function(){ initedCount ++ if(leng == initedCount){ this_.updateList(); } }) } } p.checkSameFile = function(_s) { for (var i = 0; i < this.CMS_Asset_UploadClass.length ; i++) { if(this.CMS_Asset_UploadClass[i].name == _s)return; } return false; } /* ---------- ---------- ---------- */ p.currentFilenames p.checkFileNameInit = function() { this.currentFilenames = this.fileListClass.getCurrentFilelist(); } p.checkFileName = function(_s) { for (var i = 0; i < this.currentFilenames.length ; i++) { if(_s == this.currentFilenames[i])return true; } return false; } /* ---------- ---------- ---------- */ //ファイルリストが更新された時にコールされる p.updateFileList = function() { if(this.CMS_Asset_UploadClass==undefined) return; this.checkFileNameInit() for (var i = 0; i < this.CMS_Asset_UploadClass.length ; i++) { this.CMS_Asset_UploadClass[i].updateFileList(); } } /* ---------- ---------- ---------- */ p.updateList = function(files) { this.checkFileNameInit(); var a = [] for (var i = 0; i < this.CMS_Asset_UploadClass.length ; i++) { if(this.CMS_Asset_UploadClass[i].state != "comp") a.push(this.CMS_Asset_UploadClass[i]) } this.CMS_Asset_UploadClass = a; if(this.CMS_Asset_UploadClass.length == 0){ this.v.list_btns.hide(); this.v.list.html(""); return; } else{ this.v.list_btns.show(); } var tag = ""; tag += '<table class="_dragList">' tag += '<tr>' tag += '<th width="80" style="">サムネイル</th>' tag += '<th>ファイル名</th>' tag += '<th width="70" style="">画像<br>リサイズ</th>' tag += '<th width="70" style="">リネーム</th>' tag += '<th width="100" style="text-align:center;">更新日時<br>ファイル種類</th>' tag += '<th width="80" style="text-align:right;">ファイルサイズ</th>' tag += '<th width="90" style="text-align:center;">状態</th>' tag += '<th width="25" style="text-align:center;"></th>' tag += '</tr>' for (var i = 0; i < this.CMS_Asset_UploadClass.length; i++) { var info = this.CMS_Asset_UploadClass[i]; tag += '<tr id="'+info.id+'">' tag += '<td class="_thumb"></td>' tag += '<td class="_names">' tag += ' <div class="_name_org"></div>' tag += ' <div class="_name_up"></div>' tag += ' <div class="_name_e _atten"></div>' tag += ' <div class="_size_wh_messe "></div>' tag += '</td>' tag += '<td class="_resize"><div class="_cms_btn-nano _upload_btn_resize">リサイズ</div></td>' tag += '<td class="_rename"><div class="_cms_btn-nano _upload_btn_rename">リネーム</div></td>' tag += '<td class="_date">' tag += ' ' + CMS_SaveDateU.getRelatedDate(new Date(info.raw.lastModifiedDate)) + '<br>' tag += ' ' + info.raw.type tag += '</td>' tag += '<td class="_size">' tag += ' ' +FileU.formatFilesize(info.filesize) tag += ' <div class="_size_e _atten fs10"></div>' tag += '</td>' tag += '<td class="_controllArea">' tag += ' <div class="_progressArea">' tag += ' <div class="_progressText"></div>' tag += ' <div class="_progressBar"><div class="_bar"></div><div class="_bar_comp"></div></div>' tag += ' </div>' tag += ' <div class="_stateBtns">' tag += ' <div class="_upload_btn_upload"><i class="fa fa-upload "></i> </div>' tag += ' <div class="_upload_btn_cancel"><i class="fa fa-pause "></i> </div>' tag += ' <div class="_mark_error"><i class="fa fa-exclamation "></i> </div>' tag += ' <div class="_mark_done"><i class="fa fa-check "></i> </div>' tag += ' </div>' tag += '</td>' tag += '<td class="_delete"><div class="_upload_btn_delete"><i class="fa fa-minus-circle "></i> </div></td>' tag += '</tr>' } tag += "</table>" this.v.list.html(tag); for (var i = 0; i < this.CMS_Asset_UploadClass.length ; i++) { this.CMS_Asset_UploadClass[i].setView(this.v.list); } } p.clearAll = function() { for (var i = 0; i < this.CMS_Asset_UploadClass.length ; i++) { this.CMS_Asset_UploadClass[i].clear_() } this.CMS_Asset_UploadClass = []; this.updateList() } p.uploads = function() { for (var i = 0; i < this.CMS_Asset_UploadClass.length ; i++) { this.CMS_Asset_UploadClass[i].upload() } } p.updateTID p.uploaded = function() { var this_ = this; if(this.updateTID)clearTimeout(this.updateTID); this.updateTID = setTimeout(function(){ this_.uploaded_laater() },500); } p.uploaded_laater = function() { if(this.callback) this.callback(); // this.updateList(); CMS_Asset_UploaderView.stageOut(); } p.remove = function() { this.view.empty(); } return c; })();<file_sep>/src/js/cms_view_modals/Anchor_BtnView.js var Anchor_BtnView = (function(){ var view; var v = {}; function init(){ view = $('#Anchor_BtnView'); stageInit(); } /* ---------- ---------- ---------- */ function createlayout(){ v = ModalViewCreater.createBaseView(Anchor_BtnView,view); var tag = "" tag += '<div class="_guide">'+CMS_GuideU.getGuideTag("window/btn","_BASE_")+'</div>' tag += '<div class="_title">ボタン設定</div>' v.header.html(tag); var tag = ""; tag += '<table class="_layoutTable">'; tag += ' <tr>'; tag += ' <th class="_cellTitle">リンクURL</th>'; tag += ' <td><input class="_editableNode _link_href _colorAnchor _w400"> '; tag += ' <span class="_btn_pages _cms_btn-nano "><i class="fa fa-lg fa-file-text"></i> ページ</span>' tag += ' <span class="_btn_files _cms_btn-nano "><span class="_icon_dir"></span>ファイル</span>' tag += ' <div class="_t_path_preview _input_href_anno">aa</div>' tag += ' </td>'; tag += ' </tr>'; tag += ' <tr>'; tag += ' <th class="_cellTitle">リンク<br>ターゲット</th>'; tag += ' <td><input class="_editableNode _link_tar _colorAnchor _w400" list="">'; tag += ' <span class="_target_ref_btn _cms_btn-nano "><i class="fa fa-lg fa-external-link-square "></i> ターゲット</span></td>'; tag += ' </tr>'; tag += ' <tr>'; tag += ' <th class="_cellTitle">Aタグ属性</th>'; tag += ' <td><input class="_editableNode _link_attr _colorAnchor _w400" list=""></td>'; tag += ' </tr>'; tag += ' <tr>'; tag += ' <th class="_cellTitle">リンクテキスト</th>'; tag += ' <td><input class="_editableNode _link_text _colorName _w500" style="margin:0 0 5px 0"><br>'; tag += ' <span class="_icon_copy _cms_btn-nano "><i class="fa fa-angle-right "></i></span>'; tag += ' <span class="_icon_copy _cms_btn-nano "><i class="fa fa-caret-right "></i></span>'; tag += ' <span class="_icon_copy _cms_btn-nano "><i class="fa fa-arrow-right "></i></span>'; tag += ' <span class="_icon_copy _cms_btn-nano "><i class="fa fa-chevron-circle-right"></i></span>'; tag += ' <span class="_icon_copy _cms_btn-nano "><i class="fa fa-check "></i></span>'; tag += ' <span class="_icon_copy _cms_btn-nano "><i class="fa fa-external-link-square "></i></span>'; tag += ' <span class="_icon_copy _cms_btn-nano "><i class="fa fa-envelope "></i></span>'; tag += ' <span class="_icon_copy _cms_btn-nano "><i class="fa fa-file "></i></span>'; tag += ' <span class="_icon_copy _cms_btn-nano "><i class="fa fa-file-text"></i></span>'; tag += ' <span class="_icon_copy _cms_btn-nano "><i class="fa fa-file-pdf-o"></i></span>'; tag += ' <span class="_icon_ref_btn _cms_btn-nano "><i class="fa fa-book "></i> その他アイコン</span>'; tag += ' </td>' tag += ' </tr>'; tag += ' <tr>'; tag += ' <th class="_cellTitle">画像パス</th>'; tag += ' <td><input class="_editableNode _link_image _colorPath _w500">' tag += ' <span class="_image_ref_btn _cms_btn-nano "><i class="fa fa-book "></i> 画像</span>'; tag += ' <p>画像パスを入力した場合は、リンクテキストの値が上書きされます</p>'; tag += ' </tr>'; tag += ' <tr>'; tag += ' <th class="_cellTitle">デザイン<br>(クラス)</th>'; tag += ' <td>'; tag += ' <input class="_link_class _color-style _w500" style="margin:5px 0;font-size:12px;" value="">'; tag += ' <div class="_selectClass"></div>'; tag += ' <p>文字サイズについては、ブロック情報パネルで設定</p>'; tag += ' </td>'; tag += ' </tr>'; tag += ' <tr>'; tag += ' <th class="_cellTitle">プレビュー</th>'; tag += ' <td><div class="_preview"></div></td>'; tag += ' </tr>'; tag += '</table>'; v.body.html(tag); tag = "" tag += '<div class="_cms_btn _btn_close">閉じる</div> '; tag += '<div class="_cms_btn _cms_btn_red _btn_del">リセット</div> '; tag += '<div class="_cms_btn _cms_btn_active _btn_do" '+TIP_ENTER+'><i class="fa fa-check"></i> 設定する</div> '; v.footer.html(tag); v.previeFrame = view.find('._previeFrame'); v.link_text = view.find('._link_text'); v.link_image = view.find('._link_image'); v.link_class = view.find('._link_class'); v.link_href = view.find('._link_href'); v.link_tar = view.find('._link_tar'); v.link_attr = view.find('._link_attr'); v.preview = view.find('._preview'); v.input_href_anno = view.find('._input_href_anno'); v.selectClass = view.find('._selectClass'); setBtn(); } function setBtn(){ view.find('._bg ,._btn_close').click(function(){ stageOut() }); v.btn_do = view.find('._btn_do'); view.on("click", '._btn_do', function() { compliteEdit() }); v.btn_del = view.find('._btn_del'); v.btn_del.click(function(){ callback(getEmptyData()); stageOut(); }); view.on("keyup",'._link_text',function(){ updateBtnClass() }); view.on("keyup",'._link_image',function(){ updateBtnClass() }); view.on("keyup",'._link_class',function(){ currentClass = $(this).val(); updateBtnClass(); }) view.on("click",'._link_image',function(){ var val = v.link_image.val() var s = prompt("画像URLを入力してください", val); if(s != undefined) s = ""; v.link_image.val(s); updateBtnClass(); }); view.on("click",'._image_ref_btn',function(){ var val = v.link_image.val(); CMS_MainController.openAssetSelectRel("image", val ,function(_val){ v.link_image.val(_val) updateBtnClass(); }); }); view.on("click",'._btn_pages',function(){ Anchor_PageListView.stageIn(function(_val){ v.link_href.val(_val).keyup() }) }); view.on("click",'._btn_files',function(){ var s = v.link_href.val(); CMS_MainController.openAssetSelectRel("link", s ,function(_val){ UpdateDelay.delay(function(){ v.link_href.val(_val).keyup(); updateBtnClass(); }); }); }); view.on("click",'._target_ref_btn',function(){ Anchor_TargetListView.stageIn(function(_val){ v.link_tar.val(_val) }) }); view.on("click",'._icon_ref_btn',function(){ Preset_IconView.stageIn(function(_icon){ var s = v.link_text.val(); v.link_text.val(_icon + " " + s); v.link_text.keyup(); }); }); view.on("click",'._icon_copy',function(){ var s = v.link_text.val(); v.link_text.val($(this).html()+ " " + s); v.link_text.keyup(); }); view.on("change",'._pageList',function(){ var val = $(this).val(); if(val != "") v.link_href.val(val+".html").keyup(); }) view.on("keyup",'._link_href',function(){ updatePathPreview($(this).val()); }); } function updateBtnClass(){ var a = currentClass.split(" "); v.btnCopyMCs.removeClass("_active"); for (var i = 0; i < a.length ; i++) { view.find('._area_' + a[i]).addClass("_active"); } var t = "" if(v.link_image.val().length > 0){ t = '<img src="' + CMS_Path.MEDIA.getImagePath(v.link_image.val(),false) + '">'; } else{ t = defaultVal(v.link_text.val(),v.link_href.val()); } var tag = ""; tag += '<span class="'+v.link_class.val()+'" >'+t+'</span>' v.preview.html(tag) } function update(){ var this_ = this; if(!val) val = {}; var _url = defaultVal(val.href,""); var _tar = defaultVal(val.target,""); var _attr = defaultVal(val.attr,""); var _label = defaultVal(val.text,""); var _class = defaultVal(val.class_,""); var _image = defaultVal(val.image,""); if(_url == "")_url = "#"; if(_label == "")_label = "ボタン名"; if(_image == "")_image = ""; if(_class == "")_class = "" v.link_href.val(_url) v.link_tar.val(_tar) v.link_attr.val(_attr) v.link_text.val(_label) v.link_image.val(_image) getBtnClassTag(); setBtnClass(_class); updateBtnClass(); updatePathPreview() } function updatePathPreview(){ var id = v.link_href.val(); // v.input_href_anno.html(CMS_Path.MEDIA.getAnchorPath(id,false)); v.input_href_anno.html("リンクURLプレビュー:"+CMS_Path.MEDIA.getAnchorPath_deco(id)); } /* ---------- ---------- ---------- */ //class style function getBtnClassTag(){ var list = classList var tag = '<img src="images/btn_select_bg.png?3" width="346" height="166" border="0" alt="" >'; for (var i = 0; i < list.length ; i++) { var temp = '<div class="_btnCopyMC _area_{1}" data="{1}" data-type="{0}" style="left:{2}px;top:{3}px;width:{4}px;height:{5}px;"></div>' temp = temp.split("{0}").join(list[i][0]); temp = temp.split("{1}").join(list[i][1]); temp = temp.split("{2}").join(list[i][2]-2); temp = temp.split("{3}").join(list[i][3]-1); temp = temp.split("{4}").join(list[i][4]); temp = temp.split("{5}").join(list[i][5]); tag += temp; } v.selectClass.html(tag); v.btnCopyMCs = view.find('._btnCopyMC') v.btnCopyMCs.click(function(){ addBtnClass([$(this).attr("data-type"),$(this).attr("data")]); }); } var classList = [ ["type","cms-btn-lightglay" ,41,3,60,21], ["type","cms-btn-flat" ,104,3,60,21], ["type","cms-btn-text-box" ,167,3,50,21], ["type","cms-btn-text-white" ,224,3,49,21], ["type","cms-btn-text-simple" ,280,3,45,21], ["type","cms-btn-black" ,41,27,32,24], ["type","cms-btn-white" ,75,27,32,24], ["type","cms-btn-blue" ,109,27,32,24], ["type","cms-btn-blue2" ,143,27,32,24], ["type","cms-btn-green" ,177,27,32,24], ["type","cms-btn-yellow" ,210,27,32,24], ["type","cms-btn-orange" ,245,27,32,24], ["type","cms-btn-red" ,279,27,32,24], ["type","cms-btn-pink" ,313,27,32,24], ["type","cms-btn-black-f" ,41,27+25,32,24], ["type","cms-btn-white-f" ,75,27+25,32,24], ["type","cms-btn-blue-f" ,109,27+25,32,24], ["type","cms-btn-blue2-f" ,143,27+25,32,24], ["type","cms-btn-green-f" ,177,27+25,32,24], ["type","cms-btn-yellow-f" ,210,27+25,32,24], ["type","cms-btn-orange-f" ,245,27+25,32,24], ["type","cms-btn-red-f" ,279,27+25,32,24], ["type","cms-btn-pink-f" ,313,27+25,32,24], ["round","cms-btn-round-0" ,40,61+25,46,19], ["round","cms-btn-round-5" ,86,61+25,46,19], ["round","cms-btn-round-100" ,132,61+25,46,19], ["size","cms-btn-size-ss" ,46,92+25,27,10], ["size","cms-btn-size-s" ,76,91+25,32,12], ["size","cms-btn-size-m" ,112,90+25,42,14], ["size","cms-btn-size-l" ,158,88+25,52,17], ["size","cms-btn-size-ll" ,214,85+25,62,21], ["shadow","cms-btn-shadow-0" ,43,115+25,27,23], ["shadow","cms-btn-shadow-1" ,73,115+25,27,23], ["shadow","cms-btn-shadow-5" ,103,115+25,27,23], ["shadow","cms-btn-shadow-10" ,133,115+25,27,23], ]; var currentClass = ""; function addBtnClass(_s){ var t = _s[0]; var c = _s[1]; var a = currentClass.split(" "); var types = { type:"", round:"", size:"", shadow:"" } for (var i = 0; i < a.length ; i++) { for (var ii = 0; ii < classList.length ; ii++) { if(a[i] == classList[ii][1]){ var _type = classList[ii][0] types[_type] = a[i] } } } types[t] = c; var ss = ""; for (var n in types) {ss += types[n] + " " } setBtnClass(ss); } function setBtnClass(_c){ currentClass = _c; v.link_class.val(currentClass); updateBtnClass(); } function getData(){ var o = { href : defaultVal(v.link_href.val(),""), target : defaultVal(v.link_tar.val(),""), attr : defaultVal(v.link_attr.val(),""), text : defaultVal(v.link_text.val(),""), class_ : defaultVal(v.link_class.val(),""), image : defaultVal(v.link_image.val(),"") }; return o } function getEmptyData(){ var o = { href : "", target : "", attr : "", text : "", class_ : "", image : "" }; return o } /* ---------- ---------- ---------- */ function compliteEdit(){ callback(getData()); stageOut() } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } var callback var val function stageIn(_val,_callback){ if(! isOpen){ isOpen = true; showModalView(this); val = _val; callback = _callback; if(isFirst){createlayout();} isFirst = false; view.show(); update(); } } function stageOut(){ if(isOpen){ isOpen = false; hideModalView(); view.hide(); } } function resize(){ if(isOpen){ } } return { init:init, stageIn:stageIn, stageOut:stageOut,resize:resize,compliteEdit:compliteEdit } })(); <file_sep>/src/js/cms_view_inspect/InspectView.js var InspectView = (function(){ if(window["sc"] == undefined) window.sc = {} window.sc.duplicateCurrent = function (){ if(_hasTarget()) {duplicateData() }} window.sc.deleteCurrent = function (){ if(_hasTarget()) {deleteData() }} window.sc.copyCurrent = function (){ if(_hasTarget()) {copyData() }} window.sc.cutCurrent = function (){ if(_hasTarget()) {cutData() }} window.sc.pastCurrent = function (){ if(_hasTarget()) {pastData() }} window.sc.pastCurrent2 = function (){ if(_hasTarget()) {pastData2() }} window.sc.moveTopCurrent = function (){ if(_hasTarget()) {moveDataToFirst(0) }} window.sc.moveUpCurrent = function (){ if(_hasTarget()) {moveData(-1) }} window.sc.moveDownCurrent = function (){ if(_hasTarget()) {moveData(1) }} window.sc.moveBottomCurrent = function (){ if(_hasTarget()) {moveDataToLast() }} window.sc.historyBack = function (){ if(_hasTarget()) {historyBack() }} window.sc.selectNodePrev = function (){ if(_hasTarget()) {selectNodeNext(-1) }} window.sc.selectNodeNext = function (){ if(_hasTarget()) {selectNodeNext(1) }} window.sc.dClick = function (){ if(_hasTarget()) {dClick() }} window.sc.editJSON = function (){ if(_hasTarget()) {editJSON() }} window.sc.addToMyBlock = function (){ if(_hasTarget()) {addToMyBlock() }} function _hasTarget(){ return currentNode; } /* ---------- ---------- ---------- */ var view; var v = {}; function init(){ InspectView.FormU.init(); view = $('#InspectView'); var tag = ""; tag += '<div class="_header"><div class="_dragBar"></div><div class="_title"></div></div>'; tag += '<div class="_btn_close"><i class="fa fa-lg fa-times-circle "></i></div>'; tag += '<div class="_tabRow1">'; tag += ' <ul>'; tag += ' <li class="_tabItem _tab_data _current">データ</li>'; tag += ' <li class="_tabItem _tab_design ">デザイン</li>'; tag += ' <li class="_tabItem _tab_view">その他</li>'; // tag += ' <li class="_tabItem _tab_id" style="padding-left:3px;padding-right:3px;">ID</li>'; tag += ' <li class="_tabItem _tab_output">出力</li>'; tag += ' </ul>'; tag += '</div>'; tag += '<div class="_inner">'; tag += ' <div class="_tabRow2">'; tag += ' <ul class="clearfix">'; tag += ' <li class="_tabItemOut _tab_embed">埋込み <i class="fa fa-sign-in fa-lg"></i></li>'; tag += ' <li class="_tabItemOut _tab_export">書出し <i class="fa fa-angle-right "></i> <i class="fa fa-file-text fa-lg"></i></li>'; tag += ' </ul>'; tag += ' </div>'; tag += ' <div class="_body">'; tag += ' <div class="_bodyItem _body_data"></div>'; tag += ' <div class="_bodyItem _body_css"></div>'; tag += ' <div class="_bodyItem _body_view"></div>'; // tag += ' <div class="_bodyItem _body_id"></div>'; tag += ' <div class="_bodyItem _body_output">'; tag += ' <div class="_bodyItemOut _body_export"></div>'; tag += ' <div class="_bodyItemOut _body_embed"></div>'; tag += ' </div>'; tag += ' </div>'; tag += '</div>'; tag += '<div class="_preview"><div class="_miniPreviw"></div></div>'; tag += '<div class="_footer"></div>'; view.html(tag); v.header = view.find('._header'); v.btn_close = view.find('._btn_close'); v.title = view.find('._title'); v.body = view.find('._body'); v.bodyItems = view.find('._bodyItem'); v.bodyOutItems = view.find('._bodyItemOut'); // v.body_data = view.find('._body_data'); // v.body_id = view.find('._body_id'); v.body_css = view.find('._body_css'); v.body_view = view.find('._body_view'); v.body_output = view.find('._body_output'); v.body_export = view.find('._body_export'); v.body_embed = view.find('._body_embed'); // v.preview = view.find('._preview'); v.miniPreviw = view.find('._miniPreviw'); v.footer = view.find('._footer'); v.body_view .append( InspectView.View.init() ); v.body_view .append( InspectView.ID.init() ); v.body_view .append( InspectView.ATTR.init() ); v.body_export .append( InspectView.Export.init() ); v.body_embed .append( InspectView.Embed.init() ); v.footer .append( InspectView.Footer.init() ); initTab(); initTabOut(); //bodyH_init(); stageInit(); setBtn(); openTab("data"); // openTab("design"); } /* ---------- ---------- ---------- */ function setBtn(){ v.miniPreviw.on("click",function(){ showTag()}); view.draggable({distance:5}); view.on("mousedown",function(){ CMS_KeyManager.setType(""); }) v.btn_close.click(function(){ stageOut(); }); } /* ---------- ---------- ---------- */ //タブの管理 function initTab(){ v.tabs = view.find('._tabItem'); v.tab_data = view.find('._tab_data'); v.tab_design = view.find('._tab_design'); v.tab_view = view.find('._tab_view'); // v.tab_id = view.find('._tab_id'); v.tab_output = view.find('._tab_output'); v.tab_data .click(function(){openTab("data")}) v.tab_design .click(function(){openTab("design")}) v.tab_view .click(function(){openTab("view")}) // v.tab_id .click(function(){openTab("id")}) v.tab_output .click(function(){openTab("output")}) } function openTab(_s){ //タブ v.tabs.removeClass("_current"); if(_s == "data") v.tab_data .addClass("_current"); if(_s == "design") v.tab_design.addClass("_current"); if(_s == "view") v.tab_view .addClass("_current"); // if(_s == "id") v.tab_id .addClass("_current"); if(_s == "output") v.tab_output.addClass("_current"); // if(_s == "output"){ v.tabs_outs.show(); if(!currentOutTab) openOutTab("embed"); } else{ v.tabs_outs.hide(); } if(_s == "output"){ v.preview.hide(); } else{ v.preview.show(); } //ボディエリア v.bodyItems .hide(); if(_s == "data") v.body_data .show(); if(_s == "design") v.body_css .show(); if(_s == "view") v.body_view .show(); // if(_s == "id") v.body_id .show(); if(_s == "output") v.body_output .show(); updateBodyH(); } /* ---------- ---------- ---------- */ function initTabOut(){ v.tabs_outs = view.find('._tabRow2'); v.tab_out = view.find('._tabItemOut'); v.tab_export = view.find('._tab_export'); v.tab_embed = view.find('._tab_embed'); v.tab_export .click(function(){openOutTab("export")}) v.tab_embed .click(function(){openOutTab("embed")}) } var currentOutTab; function openOutTab(_s){ currentOutTab = _s; v.tab_out.removeClass("_current"); if(_s == "export") v.tab_export.addClass("_current"); if(_s == "embed") v.tab_embed.addClass("_current"); v.bodyOutItems.hide(); if(_s == "export") v.body_export.show(); if(_s == "embed") v.body_embed.show(); // updateBodyH(); } /* ---------- ---------- ---------- */ var windowMinH = 160; function updateBodyH(){ var h = v.body.height(); if(h < windowMinH) h = windowMinH; view.find("._inner").css({height:h+"px"}); // view.addClass("_maxBodyH"); }<file_sep>/src/js/cms_view_modals/BackupCreateView.js var BackupCreateView = (function(){ var btn_add var btn_add_dis var btn_diff var btn_delete var isAdding = false var v = {} function init() { view = $("#BackupCreateView"); var tag = "" tag += '<div class="_p _h2">2. バックアップファイル ( ZIP ) 作成</div>'; tag += ' <ul class="_tab">'; tag += ' <li>バックアップ用ファイル作成</li>'; tag += ' <li>差分ファイル作成</li>'; tag += ' </ul>'; tag += ' <div class="_backupArea _shadow">'; tag += ' <div class="_p">バックアップファイル( ZIP ) を作成したい場合は、以下のボタンを押してください。数秒から数十秒ほどで、選択したディレクトリをZIPファイルに変換し、保存・ダウンロードできます。</div>'; tag += ' <div class="_notes">CMSにはリストア機能は無いので、バックアップからサイトをリストアするには、ZIPファイルをダウンロード、解凍し、FPTで上書きしてください。</div>'; tag += ' <div class="_zip_selects"></div>'; tag += ' <div class="_p _arrow"><i class="fa fa-arrow-down "></i></div>'; tag += ' <div class="_btns">'; tag += ' <div class="_btn_add">バックアップファイル ( ZIP ) を作成する</div>'; tag += ' <div class="_btn_add_dis">ZIPファイル作成中 (しばらくお待ちください) ...</div>'; tag += ' <div class="_btn_add_done">作成しました (下の履歴からZIPを取得できます) <br><br><i class="fa fa-arrow-down "></i> </div>'; tag += ' </div>'; tag += ' </div>'; tag += ' <div class="_diffArea _shadow ">'; tag += ' <div class="_p">指定した時間から、現在までに更新したファイルリストを取得します。ファイルリストから、ZIPファイルを作成し、ダウンロードできます。</div> '; tag += ' <div class="_diff_selects"></div>'; tag += ' <div class="_p _arrow"><i class="fa fa-arrow-down "></i></div>'; tag += ' <div class="_selectArea">'; tag += ' 更新時間:<span class="_replaceArea"></span>'; tag += ' </div>'; tag += ' <div class="_p _arrow"><i class="fa fa-arrow-down "></i></div>'; tag += ' <textarea class="_diffList"></textarea>'; tag += ' <div class="_btns">'; tag += ' <div class="_btn_diff_none">差分ファイル ( ZIP ) を作成する</div>'; tag += ' <div class="_btn_diff">差分ファイル ( ZIP ) を作成する</div>'; tag += ' <div class="_btn_diff_dis">ZIPファイル作成中 (しばらくお待ちください) ...</div>'; tag += ' <div class="_btn_diff_done">作成しました (下の履歴からZIPを取得できます) <br><br><i class="fa fa-arrow-down "></i> </div>'; tag += ' </div>'; tag += ' </div> '; tag += ' <div class="_p">ZIPファイルの作成が完了すると、下のバックアップ履歴のリストの上に追加されるので、そこからローカルディスクにZIPファイルを保存することもできます。(ファイルをアップロードするには、FTPアカウントが必要)</div>'; view.html(tag); } function main(){ v.btns = view.find('._btns'); v.zip_selects = view.find('._zip_selects'); v.diff_selects = view.find('._diff_selects'); v.btn_add = view.find('._btn_add'); v.btn_add_dis = view.find('._btn_add_dis'); v.btn_add_done = view.find('._btn_add_done'); v.btn_add.click(function(){ createZipFile() }); v.btn_add.show(); v.btn_getDiffList= view.find('._btn_getDiffList'); v.btn_getDiffList.click(function(){ getDiffList() }); v.btn_diff_none = view.find('._btn_diff_none'); v.btn_diff = view.find('._btn_diff'); v.btn_diff_dis = view.find('._btn_diff_dis'); v.btn_diff_done = view.find('._btn_diff_done'); v.btn_diff.click(function(){ createDiffZip() }); createView() } function createView(){ view.find('._selectArea ._replaceArea').html(BackupU.getSelectTag()); $('#hour').change(function(){ selectDiffTime($(this).val()) }); v.tabs = $('._tab > li'); v.BackupArea = $('._backupArea'); v.DiffArea = $('._diffArea'); v.tabs.eq(0).click(function(){ openTab(0)}); v.tabs.eq(1).click(function(){ openTab(1)}); openTab(0); } var isDiffOpen = false function openTab(_n){ v.BackupArea.hide() v.DiffArea.hide() v.tabs.removeClass("_active") v.tabs.eq(_n).addClass("_active") if(_n == 0) { isDiffOpen = false v.BackupArea.show(); } if(_n == 1) { isDiffOpen = true v.DiffArea.show(); } selectDirUpdate(); } /* ---------- ---------- ---------- */ function selectDirUpdate(){ if(isDiffOpen){ updateDiffList(); } else{ resetZipFile(); } } /* ---------- ---------- ---------- */ function selectDiffTime(_m){ v.btn_diff_none.show(); v.btn_diff.hide(); v.btn_diff_dis.hide(); currentDiffTime = _m; $('.replaceText').html(""); updateDiffList(); } var currentDiffTime = 0; function updateDiffList(){ v.diff_selects.html(getSelects ()) var o = {} o.action = "getDiffList"; o.diff = currentDiffTime; o.targetDirs = BackupTargetView.getSelectsFlat(); v.btn_diff_done.hide(); view.find('._diffList').val("検索中..."); var callback = function(json){ var list = json.files; var t = "" if(list.length == 0){ t += "指定時間内に変更したファイルは、見つかりませんでした。" v.btn_diff_none.show(); v.btn_diff.hide(); } else{ t += "●差分ファイル一覧 (ファイル数:" + list.length + ")\n" for (var i = 0; i < list.length ; i++) { t += list[i] + "\n"; } v.btn_diff_none.hide(); v.btn_diff.show(); } v.btn_diff_dis.hide(); v.btn_diff_done.hide(); view.find('._diffList').val(t); }; BackupU.loadAPI(o,callback); } function createDiffZip(){ if(window.isLocked(true))return; if(isAdding)return; var o = {} o.diff = currentDiffTime; o.action = "createDiffZip"; o.targetDirs = BackupTargetView.getSelectsFlat(); var callback = function(json){ v.btn_diff.hide(); v.btn_diff_dis.hide(); v.btn_diff_done.show(); isAdding = false; loadFileList() } isAdding = true; v.btn_diff_none.hide(); v.btn_diff.hide(); v.btn_diff_dis.show(); v.btn_diff_done.hide(); BackupU.loadAPI(o,callback); } function loadFileList(){ BackupListView.update() } function resetZipFile(){ if(isAdding )return; v.btn_add.css("opacity","0.5") setTimeout(function(){ v.btn_add.css("opacity","1") },200); v.zip_selects.html(getSelects ()) v.btn_add.show(); v.btn_add_dis.hide(); v.btn_add_done.hide(); } function getSelects(){ var _se = BackupTargetView.getSelects(); var ds = _se.dirs.split(","); var fs = _se.files.split(","); var tag = "" tag += "<table>"; tag += " <tr>"; tag += " <td>対象ディレクトリ:</td>"; tag += " <td>"; var count = 0 for (var i = 0; i < ds.length ; i++) { if(ds[i] != ""){ count++ tag += '<span class="_icon_dir"></span> ' + ds[i].split("../").join("") + '<br>' } } for (var i = 0; i < fs.length ; i++) { if(fs[i] != ""){ count++ tag += '<i class="fa fa-file-text"></i> ' + fs[i].split("../").join("") + '<br>' } } if(count==0){ v.btns.hide() tag += "選択してください" } else{ v.btns.show() } tag += " </td>"; tag += " </tr>"; tag += "</table>"; return tag; } function createZipFile(){ if(window.isLocked(true))return; if(isAdding)return; var o = {} o.action = "createZip"; o.targetDirs = BackupTargetView.getSelectsFlat(); var callback = function(json){ //v.btn_add.show(); v.btn_add_dis.hide(); v.btn_add_done.show(); isAdding = false; loadFileList() } isAdding = true; v.btn_add.hide(); v.btn_add_dis.show(); BackupU.loadAPI(o,callback); } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } function stageIn(){ if(! isOpen){ isOpen = true; view.show(); if(isFirst){ main() } isFirst = false; } } function stageOut(){ if(isOpen){ isOpen = false; view.hide(); } } return { init: init, stageIn: stageIn, stageOut: stageOut, selectDirUpdate: selectDirUpdate } })(); <file_sep>/src/js/cms_model/PageElement.layout.div.js PageElement.layout.div = (function(){ var _ = new PageModel.Tag_(); /* ---------- ---------- ---------- */ _.pageInfo = new PageModel.Object_Info({ id : "layout.div", name : "コンテナ", name2 : "<DIV>", inputs : ["CLASS","CSS"], // cssDef : {file:"block",key:"[コンテナブロック]"}, cssDef : {selector:".cms-layout"} }); /* ---------- ---------- ---------- */ _.getInitData = function(){ var _p = PageElement_JText.P; var o = {}; o.type = _.pageInfo.id; o.data = [{ type: "tag.p", attr: { "class": "default", css: "default" }, data: _p }]; o.attr = { "class": "default p20 waku", css: "default p20 waku", style: "" } return o; } /* ---------- ---------- ---------- */ _.getPreview = function(_o){ return ""; } /* ---------- ---------- ---------- */ _.getHTML = function(_o,_tab){ return ""; } /* ---------- ---------- ---------- */ return _; })(); <file_sep>/src/js/cms_view_modals/ModalViewCreater.js var ModalViewCreater = (function(){ function createBaseView(_class,_view){ var tag = ""; tag += ' <div class="_bg"></div>'; tag += ' <div class="_modalBox">'; tag += ' <div class="_header"><div class="_replaceArea"></div></div>'; tag += ' <div class="_header_ex"><div class="_replaceArea"></div></div>'; tag += ' <div class="_body _simple-scroll"><div class="_replaceArea"></div></div>'; tag += ' <div class="_footer"><div class="_replaceArea"></div></div>'; tag += ' <div class="_extra"><div class="_replaceArea"></div></div>'; tag += ' </div>'; _view.append(tag); var v = {} v.header = _view.find("._header ._replaceArea"); v.header_ex = _view.find("._header_ex ._replaceArea"); v.body = _view.find("._body ._replaceArea"); v.footer = _view.find("._footer ._replaceArea"); v.extra = _view.find("._extra ._replaceArea"); return v; } return { createBaseView:createBaseView } })();<file_sep>/src/js/cms_view_editable/EditableView.PageView_Revision.js EditableView.PageView_Revision = (function() { /* ---------- ---------- ---------- */ var c = function(_storage,_wapper) { this.init(_storage,_wapper); } var p = c.prototype; /* ---------- ---------- ---------- */ p.init = function(_storage,_wapper) { var self = this; this.stageInit(); this.storage = _storage; this.id = this.storage.id; this.dir = this.storage.dir; this.wapper = _wapper; this.view = this.wapper.find('._page_revision'); this.fuki = this.wapper.find('._float_fuki'); this.wapper.hover( function() { self.stageIn() } , function() { self.stageOut() } ) } p.registEvent = function(_id,_callback) { if(this.cbs == undefined)this.cbs = {} this.cbs[_id] = _callback; } /* ---------- ---------- ---------- */ p.isCreatedPre = false; p.createPre = function() { if(this.isCreatedPre) return; this.isCreatedPre = true; var self = this; var tag = ""; tag += '<div class="_rev_close"><i class="fa fa-angle-down "></i> ページバックアップ</div>'; tag += '<div class="_rev_open"></div>'; this.view.html(tag); this.rev_open = this.view.find('._rev_open'); this.rev_close = this.view.find('._rev_close'); this.rev_close.hover( function() { self.stageIn_core2() }, function(){} ); } /* ---------- ---------- ---------- */ p.isCreatedMain = false; p.create_main = function() { if(this.isCreatedMain) return; this.isCreatedMain = true; var self = this; var revs = CMS_Data.Sitemap.getRevision(this.id,this.dir); this.currentDate = ""; var tag = ""; tag += ' <div class="_rev_title">'; tag += ' <i class="fa fa-3x fa-clock-o"></i>'; tag += ' <div class="_r">※ページバックアップは自動では作成されません。まとまった編集を行う前は、自分でページバックアップを追加してください。</div>'; tag += ' </div>'; tag += ' <div class="_rev_timeline">'; tag += ' <div class="_revision_item">'; tag += ' <div class="_btn_revision_item _btn_revision-currnet" data-id="">' tag += ' <span class="_rev_name">現在の状態</span>'; tag += ' </div>'; tag += ' <span class="_cms_btn_alpha _btn_revision_add _btn_revision_add-now"><span class="_t">バックアップ</span> <i class="fa fa-plus-circle "></i></span> '; tag += ' </div>'; tag += ' <div class="_revision_item" style="margin-top:10px;">'; tag += ' <div class="_btn_revision_item _btn_revision-pre" data-id="pre">' //tag += ' <span class="_rev_name">最後に保存した状態</span>'; tag += ' <span class="_rev_name">編集前の状態</span>'; tag += ' </div>'; tag += ' <span class="_cms_btn_alpha _btn_revision_add _btn_revision_add-pre"><i class="fa fa-plus-circle "></i></span> '; tag += ' </div>'; tag += ' <div class="_t_kako">ページバックアップ一覧</div>'; tag += ' <div class="_rev_add_wapper">'; tag += ' <div class="_rev_add"></div>'; tag += ' </div>'; tag += ' <div class="_revisionArea">'; for (var i = 0; i < revs.length ; i++) { tag += this.getItem(revs[i]) } tag += ' </div>'; tag += ' <div class="_r">※ページバックアップから、過去の編集データを復帰できます。復帰後はページを保存・公開してください。</div>'; tag += ' </div>'; tag += ' <div class="_rev_btn_restore">'; tag += ' <div class="">閉じる</div>'; tag += ' </div>'; this.rev_open.html(tag); this.rev_add = this.view.find('._btn_revision_add'); this.rev_add_arrow = this.view.find('._rev_add'); this.revisionArea = this.view.find('._revisionArea'); this.rev_add.hover( function(){ self.rev_add_arrow.show() }, function(){ self.rev_add_arrow.hide() } ); this.view.find('._btn_revision_add-now').click(function(){ self.addRevision(""); }); this.view.find('._btn_revision_add-pre').click(function(){ self.addRevision("pre"); }); this.btn_restore = this.view.find('._rev_btn_restore'); this.btn_restore.click(function(){ self.clickRestore(); }); // // this.view.on('click','._btn_revision_item',function(){ self.selectRevision( ($(this).data("id")) ); }); this.view.on('click','._btn_revision_remove',function(event){ self.removeRevision( $(this).data("id") ); }); this.currentNode = this.view.find("._btn_revision-currnet") this.currentNodePre = this.view.find("._btn_revision-pre") this.currentNode.addClass("_current"); } /* ---------- ---------- ---------- */ p.getItem = function(_date) { var date = this.getFormattedName(_date); //var cur = CMS_SaveDateU.getDate() //var sa = new Date(cur).getTime() - new Date(date).getTime(); // var cs = (sa/1000 < 2) ? " _rev_now" : ""; var a = date.split(" "); var tag = ""; tag += '<div class="_revision_item">'; tag += ' <div class=" _btn_revision_item" data-id="'+date+'">' tag += ' <span class="_rev_name">'; tag += ' <span class="_rev_date">' +a[0]+ '</span>'; tag += ' <span class="_rev_time">' +a[1]+ '</span>'; tag += ' </span>'; tag += ' </div> '; tag += ' <div class="_btn_revision_remove" data-id="'+date+'" style="padding:0 0 0 20px;"><i class="fa fa-times-circle "></i> </div> '; tag += '</div>'; return tag; } /* ---------- ---------- ---------- */ //select //リビジョン選択 p.isSelect = false; p.currentDate = ""; p.selectRevision = function(_date) { var id = this.getFormattedID(_date); var self = this; var b = false; if(id == ""){ this.selectCurrent(); } else if(id == "pre"){ this.selectCurrentPre(); b = true; } else{ self.storage.loadRevision( id,function(_data){ self.selectHistory(_data); }); b = true; } if(b){ this.btn_restore.addClass("_active")//.hide().fadeIn(200); this.currentDate = _date; this.isSelect = true; } else{ this.btn_restore.removeClass("_active"); this.currentDate = ""; this.isSelect = false; } this.updateSelect(); } p.selectCurrent = function() { this.cbs["selectCurrent"](this.latestData); } p.selectCurrentPre = function() { this.cbs["selectCurrentPre"](); } p.selectHistory = function(_data) { this.cbs["selectHistory"](_data); } p.saved = function() { this.currentDate = ""; this.updateSelect(); } /* ---------- ---------- ---------- */ //add p.tID_add; p.addingTimer; p.addRevision = function(_extra) { var self = this; if(this.tID_add) clearTimeout(this.tID_add); this.addRevisionCore(_extra); this.rev_add.css("opacity",0.5); this.addingTimer = true; this.tID_add = setTimeout(function(){ self.addingTimer = false; self.rev_add.css("opacity",1) },1000); } p.addRevisionCore = function(_extra) { if(this.addingTimer) return; if(window.isLocked(true))return; var self = this; var date = CMS_SaveDateU.getDate(); var id = this.getFormattedID(date); this.storage.addRevision(date,id,function(){ self.addRevisionCore_update( $(self.getItem(date)) ); },_extra); } p.addRevisionCore_update = function(_v) { this.revisionArea.prepend( _v ); _v.hide().delay(500).fadeIn(200) } //remove p.removeRevision = function(_id) { if(window.isLocked(true))return; var self = this; var id = this.getFormattedID(_id); this.items = this.view.find('._btn_revision_item'); for (var i = 0; i < this.items.length ; i++) { if(this.items.eq(i).data("id") == _id) { this.items.eq(i).parent().slideUp(); } } this.storage.removeRevision(_id,id); this.selectRevision(); } /* ---------- ---------- ---------- */ p.updateSelect = function() { if(this.currentNode){ this.currentNode.removeClass("_current"); } this.items = this.view.find('._btn_revision_item'); for (var i = 0; i < this.items.length ; i++) { if(this.items.eq(i).data("id") == this.currentDate) { this.currentNode = this.items.eq(i); this.currentNode.addClass("_current"); } } } /* ---------- ---------- ---------- */ p.getFormattedID = function(_s) { if(!_s)return "" _s = _s.split("/").join(""); _s = _s.split(" ").join("_"); _s = _s.split(":").join(""); return _s; } p.getFormattedName = function(_s) { if(!_s)return "" // _s = _s.split(" ")[0]; return _s; } /* ---------- ---------- ---------- */ p.isFirst = true; p.openFlg = false; p.latestData p.stageInit=function(){ this.openFlg = false } p.tID_stage; p.stageIn = function() { var self = this; if(this.tID_stage) clearTimeout(this.tID_stage); this.tID_stage = setTimeout(function(){ self.stageIn_core() },200); } p.stageIn_core = function( ) { if (! this.openFlg) { this.openFlg = true; this.isFirst = false; this.isSelect = false; this.fuki.fadeIn(50); this.createPre(); } } p.stageIn_core2 = function( ) { var self = this; if(this.tID_stage) clearTimeout(this.tID_stage); this.tID_stage = setTimeout(function(){ self.stageIn_core2_delay() },200); } p.stageIn_core2_delay = function( ) { this.create_main() this.rev_open.fadeIn(200) this.currentDate = ""; this.latestData = this.storage.exportJSON(); this.updateSelect() CMS_MainController.closeInspectView(); } /**/ p.tID_stage; p.stageOut = function( ) { if(this.isSelect)return; var self = this; if(this.tID_stage) clearTimeout(this.tID_stage); this.tID_stage = setTimeout(function(){ self.stageOut_core() },200); } p.stageOut_core = function( ) { if (this.openFlg) { this.openFlg = false; this.fuki.hide() if(this.rev_open){ this.rev_open.hide() } } } p.clickRestore = function( ) { this.stageOut_core(); } return c; })(); <file_sep>/src/js/cms_main/CMS_RootView.js //メインビュー管理 var CMS_RootView = (function() { var view; var v = {}; function init() { view = $('#CMS_RootView'); stageInit(); createlayout(); setBtn(); } function setBtn() {} function createlayout() {} /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit() { view.hide(); } function stageIn() { if (!isOpen) { isOpen = true; view.show(); if (isFirst) { createlayout(); } isFirst = false; } } function stageOut() { if (isOpen) { isOpen = false; view.hide(); } } function resize() { if (isOpen) {} } return { init: init, stageIn: stageIn, stageOut: stageOut } })();<file_sep>/src/js/cms_model/PageElement.setting.js PageElement.setting = {} PageElement.settingU = (function(){ function getTag(id,jquery,data,ss){ var json = JSON.stringify(data, null, "  ") json = json.split("\n").join("<br>") var tag = "" tag += '<div class="_setting_block">' tag += ' <div class="_tag_preview_text">プレビュー</div>' tag += ' <div class="_inner">' tag += ' <div>'+ss+'</div>' tag += ' </div>' if(id != ""){ tag += ' <div class="_tag_preview_text">getFreeData("'+id+'")とJSファイルで記述すると、以下のデータが取得できます</div>' tag += ' <div class="_tag_preview">'+ json +'</div>' } if(jquery != ""){ tag += ' <div class="_tag_preview_text">HTML内の'+jquery+' に該当するノードに対して、以下のテキストが出力されます</div>' tag += ' <div class="_tag_preview">' tag += CMS_TagU.tag_2_t(ss).split("\n").join("<br>") tag += ' </div>' } tag += '</div>' return tag; } return { getTag:getTag } })();<file_sep>/src/js/cms_main/FormCandidates.js var FormCandidates = (function(){ var view; var v = {}; var isInited = false; function init(){ isInited = true; view = $('#FormCandidates'); var tag = '' tag += '<div class="_templateList"></div>' tag += '<div class="_sitemapList"></div>' tag += '<div class="_sitemapList_html"></div>' tag += '<div class="_tagList"></div>' view.append(tag) v.templateList = view.find('._templateList'); v.sitemapList = view.find('._sitemapList'); v.sitemapList_html = view.find('._sitemapList_html'); v.tagList = view.find('._tagList'); } function setTemplateList(_a){ if(!isInited)return; var list = _a; var tag = ""; tag += '<datalist id="templateDatalist">' for (var i = 0; i < list.length ; i++) { tag += '<option value="' + list[i][1] +'"></option>' } tag += '</datalist>'; if(v.templateList){ v.templateList.html(tag); } } function setSitemapList(list,listGloups){ if(!isInited)return; //ページIDリスト var tag = "" tag += '<datalist id="sitemapDatalist">' for (var i = 0; i < list.length ; i++) { tag += '<option value="' + list[i].id +'"></option>' } tag += '</datalist>'; //グループIDリスト tag += '<datalist id="sitemapDatalistGloups">' for (var i = 0; i < listGloups.length ; i++) { tag += '<option value="' + listGloups[i].id +'"></option>' } tag += '</datalist>'; v.sitemapList.html(tag); var tag = "" tag += '<datalist id="sitemapDatalist_html">' for (var i = 0; i < list.length ; i++) { tag += '<option value="' + list[i].id +'.html"></option>' } tag += '</datalist>'; v.sitemapList_html.html(tag); setTagList(); } function setTagList(){ if(!isInited)return; var tags = TreeAPI.getAllTag(CMS_Data.Sitemap.getData()); var tag = ""; tag += '<datalist id="tagDatalist">' for (var i = 0; i < tags.length ; i++) { tag += '<option value="' + tags[i] +'"></option>' } tag += '</datalist>'; v.tagList.html(tag); } return { init:init , setTemplateList:setTemplateList, setSitemapList:setSitemapList } })();<file_sep>/src/js/cms_model/PageElement.object.tree.js PageElement.object.tree = (function(){ var _ = new PageModel.Object_(); /* ---------- ---------- ---------- */ _.pageInfo = new PageModel.Object_Info({ id : "object.tree", name : "ナビゲーション", name2 : "", inputs : ["CLASS","CSS","TREE"], // cssDef : {file:"block",key:"[ナビゲーションブロック]"} cssDef : {selector:".cms-navi"} }); /* ---------- ---------- ---------- */ _.getInitData = function(){ var o = {}; o.type = _.pageInfo.id; o.data = { previewPage: { id: "index", dir: "/" }, targetDir: "", setting: { useToggle: false, onlyCurrent: false, isFlat: false, hasDate: false, isReverse: false, limitSub: "" }, css: { clearfix: false, current: true, ownCurrent: true, hasSub: true, underconst: true, type: true, level: true, no: false, sum: false }, levels: [ { isShow: true, isOpen: true, dir: "<p>{NAME}</p>", page: "<a href=\"{HREF}\" target=\"{TAR}\">{NAME}</a>" }, { isShow: true, isOpen: true, dir: "<p>{NAME}</p>", page: "<a href=\"{HREF}\" target=\"{TAR}\">{NAME}</a>" }, { isShow: true, isOpen: true, dir: "<p>{NAME}</p>", page: "<a href=\"{HREF}\" target=\"{TAR}\">{NAME}</a>" }, { isShow: true, isOpen: true, dir: "<p>{NAME}</p>", page: "<a href=\"{HREF}\" target=\"{TAR}\">{NAME}</a>" }, { isShow: true, isOpen: true, dir: "<p>{NAME}</p>", page: "<a href=\"{HREF}\" target=\"{TAR}\">{NAME}</a>" } ] } o.attr = {css:"default",style:""}; o.attr.class = o.attr.css; return o; } /* ---------- ---------- ---------- */ _.getPreview = function(_o){ var data = _o.data; var attr = _o.attrs; var htmlAbs = CMS_Path.PAGE.ABS; var tree = CMS_Data.Sitemap.getData(); var treeTag = TreeAPI.getTag( htmlAbs, tree , data); //マッチしない時のテキスト var notText = (window["TreeAPI_NOT_MATCH_TEXT"]) ? TreeAPI_NOT_MATCH_TEXT :""; var tag = ""; if(treeTag == TreeAPI_NOT_MATCH_TEXT || treeTag == ""){ tag += '<span class="_no-input-data">条件データを入力...</span>' } else{ var cs = 'class="clearfix cms-navi '; attr = attr.split('class="').join(cs); var tag = ""; tag += '<div class="_cms_preview _cms_preview-mini">' tag += '<div class="_title">ナビゲーションブロック</div>' tag += '<div '+attr+'>\n' tag += treeTag; tag += '</div>\n' tag += '</div>' } return tag; } /* ---------- ---------- ---------- */ _.getHTML = function(_o,_tab){ var data = _o.data; var attr = _o.attrs; var htmlAbs = CMS_Path.PAGE.ABS; var tree = CMS_Data.Sitemap.getData(); var treeTag = TreeAPI.getTag( htmlAbs, tree , data, HTML_ExportState.getCurrent()); treeTag = treeTag.split('target=""').join(""); treeTag = treeTag.split(TreeAPI_SITE_DIR).join(CONST.SITE_DIR); // var cs = 'class="clearfix cms-navi '; attr = attr.split('class="').join(cs); var tag = ""; tag += '<div '+attr+'>\n' tag += treeTag; tag += '</div>\n' return tag; } /* ---------- ---------- ---------- */ return _; })(); <file_sep>/src/js/cms_model/PageElement.tag.html.js PageElement.tag.html = (function(){ var _ = new PageModel.Tag_(); /* ---------- ---------- ---------- */ _.pageInfo = new PageModel.Object_Info({ id : "tag.html", name : "HTML", name2 : "", inputs : [] }); /* ---------- ---------- ---------- */ _.getInitData = function(){ var o = {}; o.type = _.pageInfo.id; var s = "" s += '<b>\n' s += 'HTML\n' s += '</b>\n' s += '<style></style>\n' s += '<script></script>\n' o.data = s o.attr ={preview:""} return o; } /* ---------- ---------- ---------- */ _.getPreview = function(_o){ var data = _o.data; var attr = _o.attrs; var tag = ""; if(data == ""){ tag += '<span class="_no-input-data">HTML,JS,CSSデータを入力...</span>' } else{ if(_o.preview) { tag += '<div class="_element_html">' + data + '</div>'; } else{ tag += '<div class="_element_html_code">'+CMS_TagU.tag_2_t(data).split("\n").join("<br>")+'</div>'; } } return tag; } /* ---------- ---------- ---------- */ _.getHTML = function(_o,_tab){ var data = _o.data; var attr = _o.attrs; var tab = (_tab != undefined) ? _tab:""; var tag = "" tag += data // tag += data; return tag; } /* ---------- ---------- ---------- */ return _; })(); <file_sep>/src/js/cms_main/CMS_AlertView.js var CMS_AlertView = (function(){ var view; var v = {}; function init(){ view = $('#CMS_AlertView'); stageInit(); } /* ---------- ---------- ---------- */ function createlayout(){ v = ModalViewCreater.createBaseView(Anchor_InputView,view); var tag = "" v.header.html(tag); tag = "" v.body.html(tag); tag = "" tag += '<div class="_cms_btn _btn_close">キャンセル</div> '; tag += '<div class="_cms_btn _cms_btn_active _btn_do"><i class="fa fa-check"></i> OK</div> '; v.footer.html(tag); setBtn(); } function setBtn(){ view.find('._bg ,._btn_close').click(function(){ stageOut() }); view.find('._btn_do').click(function(){ callback(); stageOut() }); } /* ---------- ---------- ---------- */ function update(_s,_s2){ var tag = '<div class="_title">'+_s+'</div>' v.header.html(tag); var tag = '<div class="_p">'+_s2+'</div>' v.body.html(tag); } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; var callback; function stageInit(){ view.hide(); } function stageIn(_s,_s2,_callback){ if(!view){ $("body").append('<div id="CMS_AlertView" class="_modalView"></div>'); init(); } if(! isOpen){ isOpen = true; view.show(); if(isFirst){ createlayout(); } isFirst = false; callback = _callback; if(callback ==undefined) callback = function(){} update(_s,_s2); } } function stageOut(){ if(isOpen){ isOpen = false; view.hide(); } } return { init:init, stageIn:stageIn, stageOut:stageOut } })(); <file_sep>/src/js/cms_view_floats/Float_DateInputView.js var Float_DateInputView = (function(){ var view; var v = {}; function init(){ view = $('#Float_DateInputView'); stageInit(); } function createlayout(){ var tag = "" tag += '<div class="_btn_close"></div>'; tag += '<div class="_body"><div class="_date"></div></div>' view.html(tag); v.body = view.find('._body'); v.date = view.find('._date'); // v._btn_close = view.find('._btn_close'); setBtn(); } function setBtn(){ v._btn_close.click(function(){ stageOut() }); } /* ---------- ---------- ---------- */ var curretDate = "" function setValue(_s){ curretDate = _s; v.date.datetimepicker({ value:curretDate, format:'Y/m/d H:i', inline:true, lang:'ja', onChangeDateTime: function( dp,$input ){ updateValue(dp,$input) } }); } function updateValue(dp,$input){ curretDate = $input.val(); callback(curretDate); stageOut(); } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } var callback function stageIn(_s,_callback,_xy){ if(view === undefined) return; callback = _callback; if(isFirst){ createlayout(); isFirst = false; } view.show(); if(CMS_StatusW-300 < _xy[0]){_xy[0] = CMS_StatusW-300} view.css("left",_xy[0]); view.css("top",_xy[1]); setValue(_s); } function stageOut(){ if(view === undefined) return; view.hide(); } return { init:init, stageIn:stageIn, stageOut:stageOut } })();// <file_sep>/src/js/cms_view_imagemap/ImageMap.u1.js ImageMap.State = { //最大サイズ stageW: 800, stageH: 600, //編集サイズ canvasW: 0, canvasH: 0, //オリジナルサイズ imageW: 100, imageH: 100, grid:0 } var ImageMapU = (function(){ /* function resize(_wh,_max,_isFit){ if(_isFit){ var ss1 = _wh.w / _wh.h ; var ss2 = _max.w / _max.h ; if( ss1 > ss2 ) { var z = _max.w / _wh.w _wh.w = _max.w; _wh.h = z *_wh.h } else{ var z = _max.h / _wh.h _wh.h = _max.h; _wh.w = z *_wh.w } } var w = _wh.w; var h = _wh.h; var rate = _wh.w / _wh.h; if(_wh.w > _max.w){ w = _max.w; h = w / rate; } if(h > _max.h){ h = _max.h; w = h * rate; } return {w: Math.round(w), h:Math.round(h)} } */ // function convertPercent_2_Pixel(_rect){ var ssW = 100 / ImageMap.State.canvasW; var ssH = 100 / ImageMap.State.canvasH; return { top : _rect.top / ssH, left : _rect.left / ssW, width : _rect.width / ssW, height : _rect.height / ssH, opacity : _rect.opacity, rotate : _rect.rotate, link : _rect.link, attr : _rect.attr, class : _rect.class, style : _rect.style }; } function convertPixel_2_Percent(_rect){ var ssW = 100 / ImageMap.State.canvasW; var ssH = 100 / ImageMap.State.canvasH; return { left : treat(_rect.left * ssW), top : treat(_rect.top * ssH), width : treat(_rect.width * ssW), height : treat(_rect.height * ssH), opacity : _rect.opacity, rotate : _rect.rotate, link : _rect.link, attr : _rect.attr, class : _rect.class, style : _rect.style } } function adjustW(_s){ var g = ImageMap.State.grid; var ssW = 100 / ImageMap.State.canvasW; var s = Number(_s) * ssW; s = Math.round(s/g)*g; s = s / ssW; return s; } function adjustH(_s){ var g = ImageMap.State.grid; var ssH = 100 / ImageMap.State.canvasH; var s = Number(_s) * ssH; s = Math.round(s/g)*g; s = s / ssH; return s; } //ImageMapU.treat function treat(_n) { return Math.round(_n * 100) / 100; } // function getRatio(_r){ var ratio; if(_r){ if(_r.indexOf(":") != -1){ var a = _r.split(":"); ratio = a[1]/a[0] *100; ratio = treat(ratio); } } return ratio; } function copyRect(_rect){ return { top : _rect.top, left: _rect.left, width: _rect.width, height: _rect.height } } return { // resize: resize, treat:treat, getRatio:getRatio, convertPercent_2_Pixel:convertPercent_2_Pixel, convertPixel_2_Percent:convertPixel_2_Percent, adjustW:adjustW, adjustH:adjustH, copyRect:copyRect } })();<file_sep>/src/js/cms_main/CMS_IntroView.js var CMS_IntroView = (function(){ var view; var v = {}; function init(){ view = $('#CMS_IntroView'); stageInit(); createlayout(); setBtn(); } /* ---------- ---------- ---------- */ function setBtn(){ } function createlayout(){ var tag = '' tag += '<div class="_core">' tag += '<p>←左のメニューから、サイト設定やページ作成・編集などの操作できます</p>' //tag += '<div class="_guide"><i class="fa fa-arrow-up "></i> 初めての方は、ガイドを確認してください。</div>' tag += '</div>' view.append(tag) } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } function stageIn(){ if(! isOpen){ isOpen = true; view.show(); if(isFirst){} isFirst = false; } } function stageOut(){ if(isOpen){ isOpen = false; view.hide(); } } return { init:init, stageIn:stageIn, stageOut:stageOut } })();<file_sep>/src/js/cms_view_inspect/InspectView.Embed_U.js InspectView.Embed_U = (function(){ /* ---------- ---------- ---------- */ //埋込み用チェック function checkFileExist(_path,_callback){ //メモリリストチェック if(checkExistFileList(_path)) { _callback(_path, "" ); return; } //PHPで実際にチェック Storage.Embed.checkFileExist(_path, function(error){ if(error){ _callback(_path,error); } else{ //メモリリストに追加 addExistFileList(_path); _callback(_path,""); } }); } //ファイル確認済みのリスト var existFileList = [] function checkExistFileList(_s){ for (var i = 0; i < existFileList.length ; i++) { if(existFileList[i] == _s) return true; } return false; } function addExistFileList(_s){ if(checkExistFileList(_s) == false){ existFileList.push(_s) } } /* ---------- ---------- ---------- */ //書出し用チェック function checkDirExist(_path,_callback){ //メモリリストチェック if(checkExistDirList(_path)) { _callback(_path, "" ); return; } //PHPで実際にチェック Storage.Embed.checkDirExist(_path, function(error){ if(error){ _callback(_path,error); } else{ //メモリリストに追加 addExistDirList(_path); _callback(_path,""); } }); } //ディレクトリ確認済みのリスト var existDirList = [] function checkExistDirList(_s){ var dir = CMS_Path.SITE.REL + URL_U.getBaseDir(_s); for (var i = 0; i < existDirList.length ; i++) { if(existDirList[i] == dir) return true; } return false; } function addExistDirList(_s){ var dir = CMS_Path.SITE.REL + URL_U.getBaseDir(_s); if(checkExistDirList(dir) == false){ existDirList.push(dir) } } /* ---------- ---------- ---------- */ //ファイルパスをチェック function checkFilePath(_path,_param){ _param = (_param) ? _param : {}; if(_path == ""){ return "-1"; } if(_path.indexOf("_cms") == 0 ){ return "CMSディレクトリ内には埋め込めません"; } if(_path.charAt(_path.length -1) == "/" ){ return "ファイルパスを入力してください"; } if(_path.charAt(0) == "/" ){ return "相対パスで入力してください"; } if(_path.match(/[^0-9a-zA-Z_-¥.¥/]+/) != null){ return "正しいファイルパスを入力してください"; } var ex = URL_U.getExtention(_path); if(_param["isHTML"]){ if(ex == "html" || ex == "htm"){ // } else{ return "HTMLファイル名を入力してください"; } } return ""; } /* ---------- ---------- ---------- */ //埋め込みタグ function getEmbedTag(_id,_b){ if(!_id) return ""; if(_b){ return ["<!-- EMBED:" + _id + " -->", "<!-- \/EMBED:" + _id + " -->"].join(""); } else{ return ["&lt;!-- EMBED:" + _id + " --&gt;", "&lt;!-- \/EMBED:" + _id + " --&gt;"].join(""); } } function replaceEmbedText(_s,_id,_tag){ var es = ["<!-- EMBED:" + _id + " -->", "<!-- \/EMBED:" + _id + " -->"]; var rep = es[0] + "\n" + _tag + "\n" + es[1]; var reg = new RegExp(es[0] + "(\n|.)*?" + es[1] , 'ig'); if(_s.match(reg)){ return _s.replace(reg, rep); } else{ return false; } } return { checkFileExist:checkFileExist, checkDirExist:checkDirExist, checkFilePath:checkFilePath, getEmbedTag:getEmbedTag, replaceEmbedText:replaceEmbedText } })(); <file_sep>/src/js/cms_view_editable/EditableView.BaseTextsU.js EditableView.BaseTextsU = (function() { function getTextsTag (_gridParam,_list){ var nodes = []; for (var i = 0; i < 1 ; i++) { for (var ii = 0; ii < _gridParam.cells.length ; ii++) { var cell = _gridParam.cells[ii]; var val = Treatment.toValue(_list[i][cell.id] ,""); nodes.push({ name:cell.name, node:EditableView.InputFormProvider[cell.type](i,val,cell) }); } } // var fragment = document.createDocumentFragment(); var table = document.createElement('table'); table.setAttribute('class', '_layoutTable'); fragment.appendChild(table); for (var i = 0; i < nodes.length; i++) { var tr = document.createElement('tr'); var th = document.createElement('th'); th.setAttribute('class', '_cellTitle'); th.innerHTML = nodes[i].name; var td = document.createElement('td'); if(nodes[i].node){ td.appendChild(nodes[i].node) } tr.appendChild(th); tr.appendChild(td); table.appendChild(tr); } return fragment; } //マルチグリッドで使用してる //カード検索オブジェクトの、検索条件サマリー表示 function getTextsTagSum(_gridParam,_list){ var tag = '<div class="_editableTextsSum">'; for (var i = 0; i < _list.length ; i++) { for (var ii = 0; ii < _gridParam.cells.length ; ii++) { var cell = _gridParam.cells[ii]; var val = Treatment.toValue(_list[i][cell.id] ,""); if(cell.view == "one") tag += val + '<br>'; } } tag += "</div>"; return tag; } return { getTextsTag:getTextsTag, getTextsTagSum:getTextsTagSum } })(); <file_sep>/src/js/cms_model/PageElement.setting.keyValue.js PageElement.setting.keyValue = (function(){ var _ = new PageModel.Object_(); /* ---------- ---------- ---------- */ _.pageInfo = new PageModel.Object_Info({ id : "setting.keyValue", name : "KV", inputs : ["DETAIL"] }); /* ---------- ---------- ---------- */ _.grids = [ /* ---------- ---------- ---------- */ new PageModel.Object_Grid({ gridType:Dic.GridType.BASE, gridInfo:new PageModel.OG_info({ id : "list", name : "リスト", note : "" }), textData:null, gridData:{ info:new PageModel.OG_SubInfo({ name:"" }), cells:[ new PageModel.OG_Cell({ id: "key", name: "キー", type: "single", style: SS.w300, view: "", def: "{ID}" }), new PageModel.OG_Cell({ id: "value", name: "値", type: "single", style: SS.w300, view: "", def: "値" }), new PageModel.OG_Cell({ id: "disc", name: "説明", type: "single", style: SS.w300, view: "", def: "説明" }), ] } }) /* ---------- ---------- ---------- */ ] _.getInitData = function(){ var o = {}; o.type = _.pageInfo.id; o.data = JSON.parse('{"list": {"texts": {},"grid": [{"publicData": "1","key": "{CMS_HEAD_TITLE}","value": "株式会社サンプル","disc": "&lt;title&gt;タグの内容を登録してください。"},{"publicData": "1","key": "{CMS_HEAD_KEYWORD}","value": "株式会社サンプル,採用,リクルート,グローバル","disc": "&lt;meta keyword&gt;タグの内容を登録してください。"},{"publicData": "1","key": "{CMS_HEAD_DESCRIPTION}","value": "このサイトは、株式会社サンプルの会社案内や、事業の案内を行っています。","disc": "&lt;meta description&gt;タグの内容を登録してください。"}]}}'); // o.data = JSON.parse('{"list": {"texts": {},"grid": []}}'); o.attr = {}; return o; } _.getPreview = function(_o){ var data = _o.data; var attr = _o.attrs; var tag = ""; var list = CMS_U.getPublicList(data.list.grid); //if(gridHasNoData(data)){ var tag = ""; if(list.length == 0) { tag += '<span class="_no-input-data">リストデータを入力...</span>' } else{ var style = "" tag += '<div class="_setting_keyValue">\n' tag += '<div class="_setting_id">'+_o.id+'</div>\n' tag += '<table>\n' tag += '<tr>\n' tag += ' <th>置換えキー</th>\n' tag += ' <th>置換え値</th>\n' tag += ' <th>説明</th>\n' tag += '</tr>\n' for (var i = 0; i < list.length ; i++) { tag += '<tr>\n' tag += ' <td class="key">' + list[i].key + '</td>\n' tag += ' <td class="val">' + list[i].value + '</td>\n' tag += ' <td class="disc">' + list[i].disc + '</td>\n' tag += '</tr>\n' } tag += '</table>\n' tag += '</div>\n' } return tag; } _.getHTML = function(_o){ return ""; } /* ---------- ---------- ---------- */ return _; })(); <file_sep>/src/js/cms_main/DragController.js /** * FreeLayoutと、ファイルリストでドラッグ管理 */ var DragController = (function(){ var isNew = false; var newParam = {}; var currentClass; var currentNo; var targetClass; var targetNo; var this_; function getFileDropTag(_i){ return '<div class="_dropArea _fileDropArea" data-no="'+_i+'"></div>'; } function getDropTag(_i){ return '<div class="_dropArea" data-no="'+_i+'"></div>'; } function setDrag(this_,view,_dropableclass){ view.addClass(_dropableclass) view.draggable({ opacity : 0.5, cursor : 'move', revert : true , start:function(){ isNew = false; draged(Number($(this).attr("data-no")),this_); } }); } function setDrop(this_,view,_dropableclass){ view.droppable({ accept : "."+_dropableclass, activeClass : "drop-active", hoverClass : "drop-hover", tolerance : "pointer", drop : function(ev, ui) { dropped(Number($(this).attr("data-no")),this_); } }) } function draged(_no,_tar){ currentNo = _no; currentClass = _tar; } var isDroping = false; function dropped(_no,_tar){ //二重ドラッグスルー処理 if(isDroping) return; isDroping = true; setTimeout(function(){ isDroping = false; },200); // targetNo = _no; targetClass = _tar; if(isNew){ dropped_new() } else{ dropped_move() } } function dropped_move(){ var b = true; if(currentClass == targetClass){ if(currentNo < targetNo) targetNo = targetNo - 1; if(currentNo == targetNo) b = false; } if(b){ var data = clone(currentClass.getDataAt(currentNo)); if(currentClass == targetClass){ currentClass .removeData(currentNo); targetClass .addDataAt(data,targetNo); } else{ targetClass .addDataAt(data,targetNo); currentClass .removeData(currentNo); } currentClass .update(); targetClass .update(); InspectView.stageOut(); } } function dropped_new(){ var o = PageElement_Util.getInitData(newParam.type,newParam.param); targetClass .addDataAt(o,targetNo); targetClass .update(); } return { getFileDropTag:getFileDropTag, getDropTag:getDropTag, setDrop:setDrop, setDrag:setDrag, draged:draged, dropped:dropped } })(); var DragControllerFileList = (function(){ var isNew = false; var newParam = {}; var currentClass; var currentNo; var targetClass; var targetNo; var this_; function getFileDropTag(_i){ return '<div class="_dropArea _fileDropArea" data-no="'+_i+'"></div>'; } function getDropTag(_i){ return '<div class="_dropArea" data-no="'+_i+'"></div>'; } function setDrag(this_,view,_dropableclass){ view.addClass(_dropableclass) view.draggable({ opacity : 0.5, cursor : 'move', axis:"y", revert : true , distance : 5 , start:function(){ isNew = false; draged(Number($(this).attr("data-no")),this_); startDraging(); }, stop:function(){ stopDraging(); } }); } var _isDraging = false function draged(_no,_tar){ currentNo = _no; currentClass = _tar; } function setDrop(this_,view,_dropableclass){ view.droppable({ accept : "."+_dropableclass, activeClass : "drop-active", hoverClass : "drop-hover", tolerance : "pointer", drop : function(ev, ui) { dropped(Number($(this).attr("data-no")),this_); } }) } function dropped(_no,_tar){ if(window.isLocked(true))return; targetNo = _no; targetClass = _tar; stopDraging(); if(isNew){ dropped_new() } else{ dropped_move() } } function dropped_move(){ var b = true; if(currentClass == targetClass){ if(currentNo < targetNo) targetNo = targetNo - 1; if(currentNo == targetNo) b = false; } if(b){ //var data = currentClass.getDataAt(currentNo); var data = clone(currentClass.getDataAt(currentNo)); if(currentClass == targetClass){ currentClass .removeData(currentNo); targetClass .addDataAt(data,targetNo); } else{ targetClass .addDataAt(data,targetNo); currentClass .removeData(currentNo); } currentClass .update(); targetClass .update(); InspectView.stageOut(); } } function dropped_new(){ var o = PageElement_Util.getInitData(newParam.type,newParam.param); targetClass .addDataAt(o,targetNo); targetClass .update(); } /* ---------- ---------- ---------- */ function startDraging(){ _isDraging = true; } var tID; function stopDraging(){ if(tID) clearTimeout(tID); tID = setTimeout(function(){ _isDraging = false; },100); } function isDraging(){ return _isDraging; } return { getFileDropTag:getFileDropTag, getDropTag:getDropTag, setDrop:setDrop, setDrag:setDrag, draged:draged, dropped:dropped, isDraging:isDraging } })(); DragController.FREE_DROP = "dragClassKey_free"; DragController.FILE_DROP = "dragClassKey_file"; <file_sep>/js_cms/html/js/site.js /* サイト用カスタムJavaScript 自由に編集してください。 デフォルトでは、汎用的なUIパーツが登録されています。 ※編集後はブラウザリロードしてください。 */ //環境調査 UAで判別 var isMobile = false; var ua = navigator.userAgent if(ua.indexOf('iPad') != -1) isMobile = true; if(ua.indexOf('iPhone') != -1) isMobile = true; if(ua.indexOf('Android') != -1) isMobile = true; //環境調査 レスポンシブ用 /* var isWideScreen = function() { var _breakPoint = "(max-width: 768px)"; if (window.matchMedia( _breakPoint ).matches) { return false; } else { return true; } }; */ $(function(){ //スマホ用UI設定 var mUI = $('#MobileUI'); mUI.find('.menuBtn').click(function(){mUI.toggleClass("show");}); mUI.find('.mobileBG').click(function(){mUI.removeClass("show");}); //トグルメニュー設定 $(".cms-toggle").cms_toggle(); //トグルメニュー設定 (サイドメニューやスマホ用UIで使用) $("._type-dir-toggle > p,._type-dir-toggle > a").cms_toggle_menu(); //スクロール時にサイドバー固定(モバイルでは行わない) if(!isMobile) $("#SideArea").stick_in_parent({offset_top:20}); //要素の高さを揃える $('.commonHeight > *').matchHeight( { byRow: true, property: 'height' }); //ダミーイメージサービス初期化 $.cms_dummyImage(); //モーダルウィンドウ作成 $.cms_modal({className:'cms-modal'}); //ページトップボタン作成 $.cms_pagetop({className:'cms-pagetop',icon:'<i class="fa fa-angle-up "></i>'}); //ページ内リンクの生成 (ページ内リンクブロック用) $(".cms-pagelink").cms_createLink(); //ページ内リンクのスムーススクロール設定 $.cms_pagelink({offset:-50}); }); <file_sep>/src/js/cms_model/PageElement.object.list.js PageElement.object.list = (function(){ var _ = new PageModel.Object_(); /* ---------- ---------- ---------- */ _.pageInfo = new PageModel.Object_Info({ id : "object.list", name : "リスト", name2 : "<UL><LI>", inputs : ["CLASS","CSS","DETAIL","CAPTION"], // cssDef : {file:"block",key:"[リストブロック]"} cssDef : {selector:".cms-ul"} }); /* ---------- ---------- ---------- */ _.grids = [ /* ---------- ---------- ---------- */ new PageModel.Object_Grid({ gridType:Dic.GridType.BASE, gridInfo:new PageModel.OG_info({ id : "list", name : "リスト", note : "" }), textData:null, gridData:{ info:new PageModel.OG_SubInfo({ name:"" }), cells:[ new PageModel.OG_Cell({ id: "t1", name: "テキスト", type: CELL_TYPE.MULTI, def: "サンプルの文書ですので、ご注意ください。サンプルの文書ですので、ご注意ください。" }), new PageModel.OG_Cell({ id: "anchor", name: "追加リンク", type: CELL_TYPE.BTN, def: CMS_AnchorU.getInitData() }) ] } }) /* ---------- ---------- ---------- */ ] _.getInitData = function(){ var o = {}; o.type = _.pageInfo.id; var def = { list: { texts: {}, grid: [ { publicData: "1", t1: "サンプルの文書ですので、ご注意ください。サンプルの文書ですので、ご注意ください。", anchor: CMS_AnchorU.getInitData_Blank() }, { publicData: "1", t1: "サンプルの文書ですので、ご注意ください。サンプルの文書ですので、ご注意ください。サンプルの文書ですので、ご注意ください。サンプルの文書ですので、ご注意ください。", anchor: CMS_AnchorU.getInitData_Blank() }, { publicData: "1", t1: "ご注意ください。サンプルの文書ですので、ご注意ください。", anchor: CMS_AnchorU.getInitData_Blank() } ] } } o.data = def; o.attr = {css:"default"}; o.attr.class = o.attr.css; return o; } _.getPreview = function(_o){ var data = _o.data; var attr = _o.attrs; var extra = _o.extra; var tag = ""; attr = attr.split('class="').join('class="cms-ul clearfix '); var list = CMS_U.getPublicList(data.list.grid); if(list.length == 0){ tag += '<span class="_no-input-data">リストデータを入力...</span>' } else{ tag += '<div ' + attr + '>\n'; tag += PageElement_Util.getCaption(extra); tag += '<ul>\n'; for (var i = 0; i < list.length ; i++) { var aTag = CMS_AnchorU.getAnchorTag(list[i].anchor,"",false); if(aTag)aTag = "<br>"+aTag; tag += ' <li>'+CMS_TagU.t_2_tag(list[i].t1)+aTag+'</li>\n'; } tag += '</ul>\n'; tag += '</div>\n'; } return tag; } _.getHTML = function(_o){ var data = _o.data; var attr = _o.attrs; var extra = _o.extra; attr = attr.split('class="').join('class="cms-ul clearfix '); var list = CMS_U.getPublicList(data.list.grid); if(list.length == 0) return ""; var tag = ""; tag += '<div ' + attr + '>\n'; tag += PageElement_Util.getCaption(extra); tag += '<ul>\n'; for (var i = 0; i < list.length ; i++) { var aTag = CMS_AnchorU.getAnchorTag(list[i].anchor,"",true); if(aTag)aTag = "<br>"+aTag; tag += ' <li>'+CMS_TagU.t_2_tag(list[i].t1)+aTag+'</li>\n'; } tag += '</ul>\n'; tag += '</div>\n'; return tag; } /* ---------- ---------- ---------- */ return _; })(); <file_sep>/src/js/cms_view_editable/EditableView.InputFormProviderGrid.js EditableView.InputFormProviderGrid = (function(){ function _brText(_s){ return _s.split("\n").join("<br>"); } /* ---------- ---------- ---------- */ function _td_core(i, val, cell,state,_type) { var s = CMS_TagU.deleteCellAttr(val); s = CMS_TagU.convertCellBR(s); var edited = (state) ? " _edited":""; var td = document.createElement('td'); td.setAttribute('class', "_editableTD" + edited); td.setAttribute('style', cell.style); td.setAttribute('data-no', i); td.setAttribute('data-id', cell.id); td.setAttribute('data-type', cell.type); td.setAttribute('data-input', _type); td.innerHTML = s; return td; } function single (i, val, cell, state) { return _td_core(i, val, cell, state, "input") } function multi (i, val, cell, state) { return _td_core(i, val, cell, state, "textarea") } function table (i, val, cell, state) { return _td_core(i, val, cell, state, "table") } /* ---------- ---------- ---------- */ function _state(i, val, cell,state) { return null; } /* ---------- ---------- ---------- */ function _createTD(state) { var edited = (state) ? " _edited":""; var td = document.createElement('td'); td.setAttribute('class', edited); return td; } /* ---------- ---------- ---------- */ function select(i, val, cell,state) { var input = EditableView.InputFormProvider.select(i, val, cell); var td = _createTD(state); td.appendChild(input); return td; } function checkbox(i, val, cell,state) { var input = EditableView.InputFormProvider.checkbox(i, val, cell); var td = _createTD(state); td.appendChild(input); return td; } function image(i, val, cell,state) { var input = EditableView.InputFormProvider.image(i, val, cell); var td = _createTD(state); td.appendChild(input); return td; } function anchor(i, val, cell,state) { var input = EditableView.InputFormProvider.anchor(i, val, cell); var td = _createTD(state); td.appendChild(input); return td; } function textAnchor(i, val, cell,state) { var input = EditableView.InputFormProvider.textAnchor(i, val, cell); var td = _createTD(state); td.appendChild(input); return td; } function yyyymmdd(i, val, cell,state) { var input = EditableView.InputFormProvider.yyyymmdd(i, val, cell); var td = _createTD(state); td.appendChild(input); return td; } function edited(i, val, cell,state){ var s; switch(cell.type){ case CELL_TYPE.YYYYMMDD : s = '...';break; case CELL_TYPE.SELECT : s = '...';break; case CELL_TYPE.CHECK : s = '...';break; case CELL_TYPE.IMAGE : s = '...画像<';break; case CELL_TYPE.ANCHOR : s = '...リンク';break; case CELL_TYPE.BTN : s = '...ボタン';break; case CELL_TYPE.STATE : break; default : } var edited = (state) ? " _edited":""; var td = document.createElement('td'); if(s){ td.appendChild(document.createTextNode(s)); } else{ td.setAttribute('class', "_editableTDHide"+edited); td.setAttribute('data-no', i); td.setAttribute('data-id', cell.id); td.setAttribute('data-type', cell.type); td.setAttribute('data-input', cell.type); td.appendChild(document.createTextNode(EditableView.InputU.getTenten(val))); } return td; } /* ---------- ---------- ---------- */ return { single: single, multi: multi, table: table, select: select, checkbox: checkbox, image: image, anchor: anchor, textAnchor: textAnchor, yyyymmdd: yyyymmdd, _state:_state, edited:edited } })(); <file_sep>/src/js/cms_view_editable/EditableView.BaseGrid.js /** * グリッド編集 * 設定画面や、オブジェクト編集にて、使用される * * EditableView.BaseBlockでのみ使用される */ EditableView.BaseGrid = (function() { /* ---------- ---------- ---------- */ var c = function(_gridType) { this.init(_gridType); } var p = c.prototype; /* ---------- ---------- ---------- */ p.gridType p.view; p.v p.parent; p.gridData; p.init = function(_gridType) { EditableView.currentGrid = this; this.gridType = _gridType; this.v = {} this.setParam(); } p.setParam = function() { this.gridParam = this.gridType.gridData; } /* ---------- ---------- ---------- */ //#registParent p.registParent = function (_parent){ this.parent = _parent; var tag = ""; tag += '<div class="clearfix">' tag += this.gridParam.info.getHeadTag(); tag += ' <div style="width:100%;">' tag += ' <table class="_editableTableBtns">'; tag += ' <tr>'; tag += ' <td style="padding-left:20px;"><i class="fa fa-level-up fa-rotate-180"></i> '; tag += ' <span class="_cms_btn-mini _cms_btn_active _btn_add">+</span>'; tag += ' <span class="_cms_btn-mini _cms_btn_red _btn_remove">ー</span>'; tag += ' <span class="_cms_btn-mini _cms_btn_edited _btn_stateReset"><i class="fa fa-refresh "></i> <span class="_edited">編集跡</span>リセット</span>'; tag += ' </td>'; tag += ' <td style="text-align:right">'; tag += ' <span class="_cms_btn_alpha _btn_wide_fit_ng"><i class="fa fa-square-o "></i> 画面フィット</span>'; tag += ' <span class="_cms_btn_alpha _btn_wide_fit"><i class="fa fa-check-square "></i> 画面フィット</span>'; tag += ' <span class="_cms_btn-mini _cms_btn_active _btn_restore"><i class="fa fa-reply "></i> 編集前に復帰</span>'; tag += ' <span class="_cms_btn-mini _cms_btn_excel _btn_csv_im"><i class="fa fa-pencil"></i> 表計算ソフトで編集</span>'; tag += ' </td>'; tag += ' </tr>'; tag += ' </table>'; tag += ' <div class="_tableWapper">'; tag += ' <div class="_replaceArea _tableWapperSc"></div>'; tag += ' </div>'; tag += ' <div class="_replaceAreaSummary"></div>'; tag += ' <table class="_editableTableBtns">'; tag += ' <tr>'; tag += ' <td style="padding-left:20px;"><i class="fa fa-level-down fa-rotate-180"></i>'; tag += ' <span class="_cms_btn-mini _cms_btn_active _btn_add2">+</span>'; tag += ' <span class="_cms_btn-mini _cms_btn_red _btn_remove2">ー</span>'; tag += ' </td>'; tag += ' <td style="text-align:right;padding:3px 5px 0 0;">'; tag += CMS_GuideU.getGuideTag("misk/grid","グリッド編集について"); tag += ' </td>'; tag += ' </tr>'; tag += ' </table>'; tag += this.gridParam.info.getFootTag(); tag += ' </div>'; tag += '</div>' this.view = $(tag); this.parent.v.replaceAreaGrid.append(this.view); this.v.head = this.view.find('._head'); this.v.replaceArea = this.view.find('._replaceArea'); this.v.replaceAreaSummary = this.view.find('._replaceAreaSummary'); this.v.tableWapper = this.view.find('._tableWapper'); this.v.btns = this.view.find('._editableTableBtns'); if(this.gridType.isNarrow){ this.view.find("._btn_wide_fit_ng").html("") this.view.find("._btn_wide_fit").html("") this.view.find("._btn_restore").html("").hide() this.view.find("._btn_csv_im").html("").hide() } //イベントアサイン var this_ = this; var U = EditableView.InputU; //グリッド編集アサイン this.view.find('._btn_add') .click(function(){ this_.addDataFirst(); }); this.view.find('._btn_add2') .click(function(){ this_.addData(); }); this.view.find('._btn_remove') .click(function(){ this_.removeAnimTop(); }); this.view.find('._btn_remove2') .click(function(){ this_.removeAnimLast(); }); this.view.find('._btn_restore') .click(function(){ this_.restreData(); }); this.view.find('._btn_stateReset') .click(function(){ this_.resetState(); }); this.view.find('._btn_csv_im') .click(function(){ this_.importCSV(); }); this.view.on("click","._btn_move_up" ,function(){this_.moveData(U.getNo(this),-1);}) this.view.on("click","._btn_move_down" ,function(){this_.moveData(U.getNo(this),1);}) this.view.on("click","._btn_dup" ,function(){this_.duplicateData(U.getNo(this));}) this.view.on("click","._btn_cell_show" ,function(){this_.hideCol(this)}) this.view.on('click',"._btn_wide_fit",function(){this_.setWideFit(false)}) this.view.on('click',"._btn_wide_fit_ng",function(){this_.setWideFit(true)}) //ページ遷移 this.view.on('click',"._gridPager span",function(){ this_.openPage(U.getNo(this)) }) //公開 this.view.on("click","[data-id='publicData']" ,function(){ this_.pubDate(U.getNo(this)) }); //hover時のイベントアサイン this.setBtn_hover() //イベントアサイン EditableView.InputEvent.assign(this.view,this); //CSV編集ボタン非表示 if(this.gridParam.hideGridEdit){ this.view.find('._btn_csv_im').css("visibility","hidden") } //テーブルセル イベントアサイン this.view.on("click","td",function(){ var no = $(this).data("no") if(no != undefined){ var id = $(this).data("id") this_.showCurrentRowClick(no,id) } }); } /* ---------- ---------- ---------- */ p.openPage = function (_n){ this.state.setCurrentPage (_n) this.update(); } p.pubDate = function (_n){ var r = this.state.getRowAtPage(_n); var tar = this.v.trs.eq(r) if(tar.hasClass("_tr-hide")){ tar.removeClass("_tr-hide"); } else{ tar.addClass("_tr-hide"); } } /* ---------- ---------- ---------- */ //#State 現在編集中のセルや、表示列を保持する //initDataよりも先にコールすること p.state; p.initState = function (_state){ this.state = new EditableView.BaseGridState() this.state.setData(_state) } p.getState = function (){ return this.state.getData(); } /* ---------- ---------- ---------- */ //#Data p.initDataS ="" p.initData = function (_array,_isInit){ if(this.state == undefined) this.initState(); _isInit = (_isInit == undefined) ? true : _isInit; if(_isInit) this.initDataS = JSON.stringify(_array) this.gridData = new EditableView.GridClass(); if(_array == null){ this.gridData.initRecords([]); } else{ this.gridData.initRecords(_array); } this.update(); } p.getData = function (){ return this.gridData.getRecords(); } p.addDataFirst = function (){ var o = EditableView.InputU.addData(this.gridParam.cells) this.gridData.addRecordAt(o,0); this.state.setCurrentPage(0); this.update(); this.parent.updateSubData(); } p.addData = function (){ var o = EditableView.InputU.addData(this.gridParam.cells) this.gridData.addRecord(o); this.state.setCurrentPage(this.getLastPage()); this.update(); this.parent.updateSubData(); } p.importCSV = function (){ this.startDirectArea(); } p.changeData = function (data,no){ this.gridData.overrideRecordAt(data,no); this.parent.updateSubData(); } p.removeData = function (no){ this.gridData.removeRecordAt(no); this.state.setCurrentRow(-1); this.update(); this.parent.updateSubData(); } p.removeDataLast = function (){ this.gridData.removeRecordLast(); this.update(); this.parent.updateSubData(); } p.moveData = function (targetNo,_move){ this.gridData.moveRecord(targetNo,targetNo+_move); this.state.setCurrentRow(targetNo + _move); this.update(); this.parent.updateSubData(); } p.duplicateData = function (targetNo){ this.gridData.duplicateAt(targetNo); this.state.setCurrentRow (targetNo +1); this.update(); this.parent.updateSubData(); } p.restreData = function (){ this.initData(JSON.parse(this.initDataS)); } p.resetState = function (){ var list = this.gridData.getRecords(); for (var i = 0; i < list.length ; i++) { list[i]._state = []; } this.update(); this.parent.updateSubData(); } p.getLastPage = function() { return Math.floor((this.gridData.getRecordLeng() - 1) / this.state.maxRow); } p.getLastRowNo = function() { return this.gridData.getRecordLeng() - 1; } /* ---------- ---------- ---------- */ //#update //グリッドを再描画する p.update = function (){ var _param = this.gridParam; var _list = this.gridData.getRecords(); //ページ調整 this.state.adjustPage(_list.length); //var t = new Date() //グリッドタグ取得 var h = this.v.replaceArea.height(); this.v.replaceArea.css("height",h); this.v.replaceArea.empty(); var tag = EditableView.BaseGridU.getGridTag(_param, _list, this.state); try{ this.v.replaceArea.append(tag); }catch( e ){ this.v.replaceArea.append(CMS_E.PARSE_ERROR); } this.v.replaceArea.css("height","auto"); // console.log("Grid " , new Date().getTime() - t.getTime()); this.v.trs = this.v.replaceArea.find("tr") this.showCurrentRow(this.state.currentRow); this.setWideFit(this.state.fitWide); // Float_SimpleInputView.stageOut() } /* ---------- ---------- ---------- */ //行移動、複製ボタンhover処理 p.setBtn_hover = function (){ var this_ = this; var U = EditableView.InputU; this.view.on('click',"._btn_delete",function(){this_.removeAnim(U.getNo(this))}) this.view.on('mouseenter',"._btn_delete",function(){this_.removeAnimHover(U.getNo(this),true) }) this.view.on('mouseleave',"._btn_delete",function(){this_.removeAnimHover(U.getNo(this),false) }) this.view.on('mouseenter',"._btn_move_up",function(){this_.actionAnimUPHover(U.getNo(this),true) }) this.view.on('mouseleave',"._btn_move_up",function(){this_.actionAnimUPHover(U.getNo(this),false) }) this.view.on('mouseenter',"._btn_move_down",function(){this_.actionAnimDownHover(U.getNo(this),true) }) this.view.on('mouseleave',"._btn_move_down",function(){this_.actionAnimDownHover(U.getNo(this),false) }) this.view.on('mouseenter',"._btn_dup",function(){this_.actionAnimDup(U.getNo(this),true) }) this.view.on('mouseleave',"._btn_dup",function(){this_.actionAnimDup(U.getNo(this),false) }) } p.actionAnimUPHover = function(_n, _b) { this.switchClass(_b ,_n ,"_willActionUPHover")} p.actionAnimDownHover = function(_n, _b) { this.switchClass(_b ,_n ,"_willActionDownHover")} p.actionAnimDup = function(_n, _b) { this.switchClass(_b ,_n ,"_willActionDup")} p.removeAnimHover = function(_n, _b) { this.switchClass(_b ,_n ,"_willRemoveHover")} p.getRowTar = function(_n) { return this.v.trs.eq(this.state.getRowAtPage(_n)) } p.switchClass = function(_b,_n,_id) { var tar = this.getRowTar(_n); (_b) ? tar.addClass(_id): tar.removeClass(_id); } //行削除アニメーション p.removeAnim = function (_n){ var this_ = this; var tar = this.v.trs.eq( this.state.getRowAtPage(_n) ) tar.addClass("_willRemove"); setTimeout(function(){ this_.removeData(_n); },100); } //先頭の行削除アニメーション p.removeAnimTop = function (){ this.state.setCurrentPage(0); this.update(); this.removeAnim(0); } //最後の行削除アニメーション p.removeAnimLast = function (){ this.state.setCurrentPage(this.getLastPage()); this.update(); this.removeAnim(this.getLastRowNo()); } /* ---------- ---------- ---------- */ //行選択の強調表示 p.showCurrentRowClick = function (_n,_id){ this.showCurrentRow(_n,_id) } // p.currentPage = 0; // p.currentRow = -1; p.currenID = "" p.showCurrentRow = function (_row,_id){ //remove mark if(this.state.isCurrentPage()){ var r = this.state.getRowAtPage(); if(this.state.currentRow != -1) this.v.trs.eq(r).removeClass("_currentRow") if(this.currenID != "") this.v.trs.eq(r).find("td").removeClass("_currentTD") } this.state.setCurrentRow (_row); this.currenID = _id; //mark current row if(this.state.isCurrentPage()){ var r = this.state.getRowAtPage(); this.v.trs.eq(r).addClass("_currentRow"); this.v.trs.eq(r).find("td[data-id='"+this.currenID+"']").addClass("_currentTD"); } } /* ---------- ---------- ---------- */ //セルの列の表示・非表示きりかえ p.setWideFit = function (_b){ if(_b){ this.state.setFitWide(true) this.view.find('._btn_wide_fit').show() this.view.find('._btn_wide_fit_ng').hide() this.v.tableWapper.removeClass("_wide") } else{ this.state.setFitWide(false) this.view.find('._btn_wide_fit').hide() this.view.find('._btn_wide_fit_ng').show() this.v.tableWapper.addClass("_wide") } } /* ---------- ---------- ---------- */ //セルの列の表示・非表示きりかえ 編集ステートに保持する p.hideCol = function (_this){ var no = $(_this).data("no"); var s = EditableView.BaseGridU.strintState(this.state.hideCols,no); this.state.setHideCols(s); this.update(); } /* ---------- ---------- ---------- */ //直接編集(表計算と連携) p.startDirectArea = function (){ var self = this; // Float_SimpleInputView.stageOut(); var list = this.gridData.getRecords(); var cells = this.gridParam.cells; var s = EditableView.BaseGridU.arrayToText(list,cells); Editer_ExcelView.stageIn(s,function(_s){ setTimeout(function(){ self.initData(EditableView.BaseGridU.textToArray(_s, cells), false); self.parent.updateSubData(); },200); }); } /* ---------- ---------- ---------- */ //#M_GRID時に、タブを開いたときにコールされる p.mGrid_startEditMode = function (){ this.v.head.show(); this.v.replaceArea.show(); this.v.replaceAreaSummary.hide(); this.v.btns.show() } p.mGrid_stopEditMode = function (){ this.v.head.hide(); this.v.replaceArea.hide(); this.v.replaceAreaSummary.show(); this.v.btns.hide(); var list = this.gridData.getRecords(); this.v.replaceAreaSummary.html(EditableView.BaseGridU.getGridTagSum(this.gridParam,list)); } return c; })(); <file_sep>/src/js/cms_view_imagemap/ImageMap.u2.js var ImageMapCode = (function(){ /* ---------- ---------- ---------- */ //ImageMapCode.getUID function getUID (_type) { var s = DateUtil.getFormattedDate(new Date(),_type.split(".")[1]+"_YYYYMMDD_RRR"); return s; } function isRect (_type) { return (_type == "item.rect"); } function isLine (_type) { return (_type == "item.line"); } function isImage (_type) { return (_type == "item.image"); } function isSVG (_type) { return (_type == "item.svg"); } function isText (_type) { return (_type == "item.text"); } function isLink (_type) { return (_type == "item.link"); } function isHTML (_type) { return (_type == "item.html"); } /* ---------- ---------- ---------- */ function createItemView (_type) { var view if(isRect(_type)) { view = $('<div data-defclass="_design-item-rect" class="_design-item-rect"></div>'); } if(isLine(_type)) { view = $('<div data-defclass="_design-item-line" class="_design-item-line"></div>'); } if(isImage(_type)) { view = $('<div data-defclass="_design-item-image" class="_design-item-image"></div>'); } if(isSVG(_type)) { view = $('<div data-defclass="_design-item-svg" class="_design-item-svg"></div>'); } if(isText(_type)) { view = $('<div data-defclass="_design-item-text" class="_design-item-text"></div>'); } if(isLink(_type)) { view = $('<div data-defclass="_design-item-link" class="_design-item-link"></div>'); } if(isHTML(_type)) { view = $('<div data-defclass="_design-item-html" class="_design-item-html"></div>'); } return view; } /* ---------- ---------- ---------- */ //初期データ取得 function getInitData(type,_extra){ var data = { type:type, id:getUID(type), date:0, hide:false, rect: { top: 0, left: 0, width: 30, height: 20, opacity: 1, rotate: 0, link : "", attr : "", class : "", style : "" }, pixel: { top: 0, left: 0, width: 30, height: 20 }, data:{} }; if(isRect(type)){ data.data.color = '#000' data.data.border_color = '#000'; data.data.border_size = ''; data.data.round = ''; } if(isLine(type)){ data.data.color = '#000' data.data.arrow_w = '10' data.data.arrow_l = '' data.data.arrow_r = '' } if(isSVG(type)){ data.data.svg = '<svg width="100%" height="100%" viewBox="0 0 1792 1792" xmlns="http://www.w3.org/2000/svg"><path d="M1412 734q0-28-18-46l-91-90q-19-19-45-19t-45 19l-408 407-226-226q-19-19-45-19t-45 19l-91 90q-18 18-18 46 0 27 18 45l362 362q19 19 45 19 27 0 46-19l543-543q18-18 18-45zm252 162q0 209-103 385.5t-279.5 279.5-385.5 103-385.5-103-279.5-279.5-103-385.5 103-385.5 279.5-279.5 385.5-103 385.5 103 279.5 279.5 103 385.5z"></path></svg>' data.data.color = '#000' } if(isImage(type)){ if(_extra){ data.data.src = CMS_PathFunc.treatRel(_extra.src); // data.data.src = _extra.src.split("../").join(""); } else{ data.data.src = 'width:200,height:140'; } // data.data.image = 'width:200,height:140'; // var sa = [ // "images/img/about2_img_4.png", // "images/img/about3_img_sp.png", // "images/img/about3_img.png", // "images/img/airport_back.jpg", // "images/img/airport_img_1_sp.jpg", // "images/img/airport_img_1.jpg", // "images/img/airport_img_2_sp.jpg", // "images/img/airport_img_2.jpg", // "images/img/airport_img_3_sp.jpg", // "images/img/airport_img_3.jpg", // "images/img/airport_img_4_sp.jpg", // "images/img/airport_img_4.jpg", // "images/img/footer_arr_top.png", // "images/img/jumbotron_back_sp.jpg", // "images/img/jumbotron_back.jpg", // "images/img/jumbotron_campain_sp.png", // "images/img/jumbotron_campain.png" // ] // data.data.src = sa[Math.round(Math.random() * sa.length)]; data.data.round = ''; } if(isText(type,data)){ if(_extra == "multi"){ data.rect.width = 50; data.data.text = "サンプルのタイトル"; data.data.size = "24px"; data.data.line = "1.2"; } else{ data.rect.width = 50; data.data.text = "サンプルの文書ですので、ご注意ください。サンプルの文書ですので、ご注意ください。サンプルの文書ですので、ご注意ください。サンプルの文書ですので、ご注意ください。"; data.data.size = "14px"; data.data.line = "1.6"; } data.data.color = ""; data.data.align = ""; data.data.font = ""; data.data.bold = ""; data.data.sdw = ""; data.data.bmp = ""; } if(isHTML(type,data)){ data.data.html = '<iframe width="100%" height="100%" src="https://www.youtube.com/embed/rrHBFJUNiXk" frameborder="0" allowfullscreen></iframe>' data.data.preview = false; } return data; } /* ---------- ---------- ---------- */ //inputへデータ設定 function setInputValue(_data,in_){ var type = _data.type; var __ = _data.data; if (isRect(type)) { in_.rect_color.val(__.color); in_.rect_border_color.val(__.border_color); in_.rect_border_size.val(__.border_size); in_.rect_round.val(__.round); } if (isLine(type)) { in_.line_color.val(__.color); in_.line_w.val(__.arrow_w); in_.line_l.val(__.arrow_l); in_.line_r.val(__.arrow_r); } if (isImage(type)) { var imgPath = CMS_Path.MEDIA.getImagePath( __.src , false ); in_.image.val(__.src) in_.image_thumb.html('<img src="' + imgPath + '">'); in_.image_path.html(__.src); in_.image_round.val(__.round); in_.image_ratio.val(__.ratio); // in_.image_fix.val(__.fix) in_.image_fix_on.hide() in_.image_fix_off.hide() if(__.fix){ in_.image_fix_on.show() } else{ in_.image_fix_off.show() } } if(isSVG(type)) { in_.svg.val(__.svg); in_.svg_color.val(__.color); } if (isText(type)) { in_.text.val(__.text) in_.text_size.val(__.size) in_.text_color.val(__.color) in_.text_align.val(__.align) in_.text_line.val(__.line) in_.text_font.val(__.font) in_.text_bold.val(__.bold) in_.text_sdw.val(__.sdw) in_.text_bmp.val(__.bmp) in_.text_bmp_on.hide() in_.text_bmp_off.hide() in_.em_box_inner.hide() if(__.bmp){ in_.text_bmp_on.show() in_.em_box_inner.show() } else{ in_.text_bmp_off.show() } } if (isLink(type)) { in_.meta.val(__.meta); // in_.link.val(__.link) } if (isHTML(type)) { in_.html.val(__.html) in_.html_preview.val(__.preview) in_.html_preview_on.hide() in_.html_preview_off.hide() if(__.preview){ in_.html_preview_on.show() } else{ in_.html_preview_off.show() } } return ImageMapExport.getHTML_item(_data,0); } /* ---------- ---------- ---------- */ //inputからデータ取得 function getInputValue(type,in_){ var __ = {} if(isRect(type)){ __.color = in_.rect_color.val(); __.border_color = in_.rect_border_color.val(); __.border_size = in_.rect_border_size.val(); __.round = in_.rect_round.val(); } if(isLine(type)){ __.color = in_.line_color.val(); __.arrow_w = in_.line_w.val(); __.arrow_l = in_.line_l.val(); __.arrow_r = in_.line_r.val(); } if(isImage(type)){ __.src = in_.image.val(); __.round = in_.image_round.val(); __.ratio = in_.image_ratio.val(); __.fix = in_.image_fix.val(); } if(isSVG(type)){ __.svg = in_.svg.val(); __.color = in_.svg_color.val(); } if(isText(type)){ __.text = in_.text.val(); __.size = in_.text_size.val(); __.color = in_.text_color.val(); __.align = in_.text_align.val(); __.line = in_.text_line.val(); __.font = in_.text_font.val(); __.bold = in_.text_bold.val(); __.sdw = in_.text_sdw.val(); __.bmp = in_.text_bmp.val(); } if(isLink(type)){ __.meta = in_.meta.val(); } if(isHTML(type)){ __.html = in_.html.val(); __.preview = in_.html_preview.val(); } return __; } /* ---------- ---------- ---------- */ //レイヤー用データ function getLayerData(_data){ var type = _data.type if(isRect(type)){ return "四角" //+ '<div class="_sub">' + _data.rect.width +' * '+ _data.rect.height + '</div>'; } if(isLine(type)){ return "線" //+ '<div class="_sub">' + _data.rect.width +' * '+ _data.rect.height + '</div>'; } if(isImage(type)){ return "画像"+ '<div class="_sub">' + _data.data.src + '</div>'; } if(isSVG(type)){ return "SVG"; } if(isText(type)){ var s = CMS_TagU.tag_2_t(_data.data.text); if(s.length > 50){ s = s.substr(0,50) + "..."; } return "テキスト"+ '<div class="_sub">' + s + '</div>'; } if(isLink(type)){ var s = ""; if(_data.rect.link){ s += (_data.rect.link.href) ? _data.rect.link.href : ""; } s += (_data.data.meta) ? _data.data.meta : ""; return "リンク"+ '<div class="_sub">' + s + '</div>'; } if(isHTML(type)){ var s = CMS_TagU.tag_2_t(_data.data.html); if(s.length > 50){ s = s.substr(0,50) + "..."; } return "HTML"+ '<div class="_sub">' + s + '</div>'; } return "--" } return { getUID:getUID, isRect:isRect, isLine:isLine, isImage:isImage, isSVG:isSVG, isText:isText, isLink:isLink, isHTML:isHTML, createItemView:createItemView, getInitData:getInitData, setInputValue:setInputValue, getInputValue:getInputValue, getLayerData:getLayerData } })(); <file_sep>/src/js/cms_view_modals/CMS_GuideView.js var CMS_GuideView = (function(){ var view; var v = {}; function init(){ view = $('#CMS_GuideView'); stageInit(); setBtn(); } /* ---------- ---------- ---------- */ function createlayout(_callback){ CMS_GuideU.loadInit(function(){ createlayout_core(_callback) }); } function createlayout_core(_callback){ var tag = ""; tag += '<div class="_btn_close"></div>'; tag += '<div class="_btn_zoom"><i class="fa fa-external-link-square "></i> 別ウィンドウで表示</div>' tag += '<div class="_title _dragBarArea">CMS 利用ガイド</div>' tag += '<div class="_navi guide-scroll"><div class="_inner"></div></div>' tag += '<div class="_body guide-scroll">' tag += ' <div class="_inner">' tag += ' <div class="_h1"></div>' tag += ' <div class="_text"></div>' tag += ' </div>'; tag += '</div>'; view.html(tag) v._btn_close = view.find('._btn_close'); v.dragBarArea = view.find('._dragBarArea'); v.h1 = view.find('._h1'); v.inner = view.find('._body ._inner'); v.text = view.find('._text'); v.navi = view.find('._navi ._inner'); v._btn_zoom = view.find('._btn_zoom'); v._btn_close.click(function(){stageOut();}) v._btn_zoom.click(function(){openEx()}) // try{ view.draggable({handle: view.find('._dragBarArea')}); }catch( e ){} _callback(); } function setBtn(){ $("body").on("click","._btn_guide_block",function(event){ CMS_GuideU.openGuide($(this).data("id")) // stageIn(id); event.stopPropagation(); event.preventDefault(); }) view.on("click","a",function(event){ var type = $(this).data("type"); if(type == "guide"){ var href = $(this).attr("href"); innerMove(href); event.stopPropagation(); event.preventDefault(); } if(type == "cms_link"){ openInner($(this).attr("href")) event.stopPropagation(); event.preventDefault(); } }) view.on("click","._btn_back",function(event){ historyBack() }) view.on("click","._h2-toggle",function(){ if($(this).data("state")){ $(this).next().slideUp() $(this).data("state","") $(this).removeClass("_open") $(this).find("span").html('<i class="fa fa-caret-down "></i>') } else { $(this).next().slideDown() $(this).data("state","1") $(this).addClass("_open") $(this).find("span").html('<i class="fa fa-caret-up "></i>') } }); } function openInner (_s){ if(GUIDE_STANDALONE){ window.open("../index.html#"+_s); } else{ CMS_MainController.openPage_by_hash(_s); } } /* ---------- ---------- ---------- */ function setXML(_xml){ v.text.html(""); var nodes = _xml.find("item"); update_core("",nodes.eq(0)); } /* ---------- ---------- ---------- */ // function getUID(_dir,_page){ return "_guide_" + _dir + '__SP__' + _page.split(".").join("_CC_"); } /* ---------- ---------- ---------- */ /* ---------- ---------- ---------- */ /* ---------- ---------- ---------- */ //ナビ function initNavi(){ var tag = "" var xml = CMS_GuideU.getXML(); var gl = $(xml).find("gloup"); gl.each(function(){ if($(this).attr("type") == "rootext"){ tag += $(this).text(); } else{ tag += getGloupHTML($(this)) } }) v.navi.html(tag); v.naviItems = v.navi.find("a"); } function getGloupHTML(_gloup){ var tag = "" var id = _gloup.attr("id"); var h2 = (function(_s){ if(_s)return '<div class="_h2">' + _s + '</div>'; return "" })(_gloup.attr("name")); if(h2){ var dd = "_h2_" + id; tag += '<div class="_h2-toggle '+dd+'"><span class="icon"><i class="fa fa-caret-down "></i></span>'; tag += h2 tag += '</div>' } if(h2) tag += '<div class="_toggle-body">'; tag += '<ul>'; var items = _gloup.find("> item"); items.each(function(){ var item = $(this); var _id = item.attr("id"); var nn = (function(_node){ var _s = _node.find("name").text() var _s2 = _node.find("navi").text() if(_s2) _s = _s2; if(_s.indexOf("--") != -1){ var a = _s.split("--"); return a[1]; } else{ return _s; } })(item); if(_id == ""){ tag += '</ul><div class="_h4">' + item.attr("name") + '</div><ul>'; } else{ if(nn){ var s = id + '/' + _id; var sid = getUID(id,_id) tag += '<li><a href="' + s + '" id="' + sid + '" data-type="guide">' + nn + '</a></li>'; } } }) tag += '</ul>'; if(h2)tag += '</div>'; return tag; } /* ---------- ---------- ---------- */ function updateDirOpen(_id){ var param = CMS_GuideU.getData(_id); var tar = v.navi.find("._h2_" + param.dir.id); if(tar.data("state") != "1"){ tar.click(); } } /* ---------- ---------- ---------- */ function update(_id){ if(_id =="") _id = "index/index" addHistory(_id); var param = CMS_GuideU.getData(_id); if(param.page == null) { v.h1.html(""); // v.video.html("").hide(); v.text.html("原稿、未作成です"); } else{ update_core(_id, param.page, param.dir); } v.naviItems.removeClass("_current"); var aa = _id.split("/"); v.navi.find("#"+getUID(aa[0],aa[1])).addClass("_current"); updateDirOpen(_id); } function update_core(_id, param, _dir){ setTitle(_id,param.find("name").text() ,_dir ); var idText = '<div style="font-size:10px;color:#888;margin:3em 0 1em 0;">ガイドID:' + _id + '</div>'; var bodyParam = { text: param.find("text").text() + idText, useToggle: (param.attr("useToggle") =="1") ? true : false } v.text.html(""); setTimeout(function(){ v.text.html( CMS_GuideU.getBodyTag(bodyParam)); },100); } function setTitle(_id,_s,_d){ var _s = (function(_s){ if(_s.indexOf("--") != -1){ var a = _s.split("--"); return '<span style="font-size:12px;">' + a[0] + "</span> "+a[1]; } else { return _s; } })(_s); var d = ""; if(_d) d = '<span class="_gloup">' + _d.name + ' </span>'; _s = d + _s; v.h1.html(setHistoryBtn() + _s); } var isInitPos = true; function setRect(){ if(GUIDE_STANDALONE)return; if(isInitPos){ var a = [800,700]; var w = $('body').width(); var h = $('body').height(); if(!isMove){ view.css("left",(w - a[0])/2); view.css("top",(h - a[1])/2); } } isInitPos = false; } /* ---------- ---------- ---------- */ var history = []; var currentID = "" function addHistory(_id){ if(window["GUIDE_DEV"]) return; if(isHistoryMove == false) history.push(_id); isHistoryMove = false; if(GUIDE_STANDALONE){ location.hash = _id; } currentID = _id; } var isHistoryMove = false; function historyBack(){ var id = history[history.length-2]; history.pop() isHistoryMove = true; isMove = true; update(id); } function setHistoryBtn(){ if(history.length == 1){ return "" } else { return '<span class="_btn_back"><i class="fa fa-chevron-circle-left "></i> 戻る </span>' } } function innerMove(_id){ isMove = true; update(_id); } function resetHistory(){ // history = []; } /* ---------- ---------- ---------- */ function openEx(){ // window.open("./guide/index.html#" + currentID,"guide"); window.open(GUIDE_URL + "#" + currentID, "guide"); } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } var isMove function stageIn(_id){ isMove = false; stageOut(); setTimeout(function(){ stageIn_core(_id); },100); } function stageIn_core(_id){ view.show(); if(isFirst){ createlayout(function(){ initNavi(); update(_id); }); setRect(); isFirst = false; } else{ update(_id); } } function stageOut(){ view.hide(); resetHistory(); } /* ---------- ---------- ---------- */ return { init:init, stageIn:stageIn, stageOut:stageOut, setXML:setXML } })(); <file_sep>/src/js/cms_view_editable/EditableView.CustomListData.js EditableView.CustomListData = (function(){ function getPreset(){ var param = {} param.g = 3-1;//絡む param.w = 0;//枠+背景 param.l = 2;//レイアウト param.d = 2;//デザイン param.ww = 1; param.t_ww = 720; param.t_m = 10; param.t_iw = 80; param.t_ih = 120; param.t_m_p = 1; param.t_iw_p = 50; return param; } var _param = (function() { /* ---------- ---------- ---------- */ var c = function() { this.init(); } var p = c.prototype; /* ---------- ---------- ---------- */ p.init = function() { //レイアウト種類 this.type = "T";//TBLR this.design = "designA";//TBLR //LRの場合 this.img_width = "100px";//TB // this.img_height = "120px";//TB this.width = "720px"; this.devide = "3"; this.margin = "15px"; //レスポンシブ this.responsive = false; //枠あり this.enclose = ""; } return c; })(); function getCodes(param){ var param; var isFix = (param.ww == 0) ? true:false; var o = new _param(); if(param.l == 0){ if(param.d == 0) { o.type = "T"; o.design = "designA" } if(param.d == 1) { o.type = "T"; o.design = "designA" } if(param.d == 2) { o.type = "T"; o.design = "designA" } if(param.d == 3) { o.type = "T"; o.design = "designB" } if(param.d == 4) { o.type = "T"; o.design = "designB" } if(param.d == 5) { o.type = "T"; o.design = "designB" } } if(param.l == 1){ if(param.d == 0) { o.type = "B"; o.design = "designA" } if(param.d == 1) { o.type = "B"; o.design = "designA" } if(param.d == 2) { o.type = "B"; o.design = "designA" } if(param.d == 3) { o.type = "B"; o.design = "designB" } if(param.d == 4) { o.type = "B"; o.design = "designB" } if(param.d == 5) { o.type = "B"; o.design = "designB" } } if(param.l == 2){ if(param.d == 0) { o.type = "L"; o.design = "designA" } if(param.d == 1) { o.type = "LT"; o.design = "designA" } if(param.d == 2) { o.type = "LTF"; o.design = "designA" } if(param.d == 3) { o.type = "L"; o.design = "designB" } if(param.d == 4) { o.type = "LT"; o.design = "designB" } if(param.d == 5) { o.type = "LTF"; o.design = "designB" } } if(param.l == 3){ if(param.d == 0) { o.type = "R"; o.design = "designA" } if(param.d == 1) { o.type = "RT"; o.design = "designA" } if(param.d == 2) { o.type = "RTF"; o.design = "designA" } if(param.d == 3) { o.type = "R"; o.design = "designB" } if(param.d == 4) { o.type = "RT"; o.design = "designB" } if(param.d == 5) { o.type = "RTF"; o.design = "designB" } } if(param.l == 4){ if(param.d == 0) { o.type = "Z"; o.design = "designA" } if(param.d == 1) { o.type = "Z"; o.design = "designA" } if(param.d == 2) { o.type = "Z"; o.design = "designA" } if(param.d == 3) { o.type = "Z"; o.design = "designB" } if(param.d == 4) { o.type = "Z"; o.design = "designB" } if(param.d == 5) { o.type = "Z"; o.design = "designB" } } if(param.l == 5){ if(param.d == 0) { o.type = "I"; o.design = "designA" } if(param.d == 1) { o.type = "I"; o.design = "designA" } if(param.d == 2) { o.type = "I"; o.design = "designA" } if(param.d == 3) { o.type = "I"; o.design = "designA" } if(param.d == 4) { o.type = "I"; o.design = "designA" } if(param.d == 5) { o.type = "I"; o.design = "designA" } } // if(isFix){ o.width = param.t_ww + "px"; o.margin = param.t_m + "px"; o.img_width = param.t_iw + "px"; } else{ o.width = "100%"; o.margin = param.t_m_p + "%"; o.img_width = param.t_iw_p + "%"; } // o.img_height = (param.t_ih != undefined) ? param.t_ih + "px" :""; o.devide = param.g + 1; o.enclose = (function(_n){ var a = ["","A","B"]; return a[_n]; })(param.w); return EditableView.CustomListData2.getCode(o); } return { getCodes:getCodes } })(); EditableView.CustomListData2 = (function() { var view; var v = {}; function get_design(_s) { return _s; } function get_isFix(_w) { if(_w.indexOf("px") != -1) { return true; } else{ return false; } } function get_unit(_f) { return (_f) ? "px" :"%"; } function get_li_devide(_d) { if(_d == undefined) return 2; return Number(_d); } function get_li_margin(_m) { var m = _m; m = m.split("px").join(""); m = m.split("%").join(""); return Number(m); } function get_li_width(_w,_isFix,_margin,_devide) { var w = _w; w = w.split("px").join(""); w = w.split("%").join(""); if(_isFix) { var w2 = (w - (_margin * (_devide - 1))); return Math.floor(w2 / _devide); } else{ var w2 = ( w - (_margin * _devide)); return Math.floor(w2 / _devide); } } function getCodeHTML(_temp,_param) { var type = _param.type var start = _temp.ul.start if(_param.li_devide == 1){ start = _temp.ul.startOne } var a = []; a.push(start); a.push(_temp.li.start); a.push(_temp[type].title); if(type == "B"){ a.push(_temp[type].texts); a.push(_temp[type].images); } else{ a.push(_temp[type].images); a.push(_temp[type].texts); } a.push(_temp.li.end); a.push(_temp.ul.end); var html = a.join(""); html = html.split("{UL_CLEARFIX}").join(" clearfix"); html = html.split("{COMMONH}").join(" commonHeight"); return html; } function getCodeCSS(_temp,_param) { var type = _param.type; var design = _param.design; var extra = ""; if(_temp[type][design]){ if(_temp[type][design].extra){ extra = _temp[type][design].extra; } } var enclose = ""; if(_param.enclose){ if(_temp[type]["enclose" + _param.enclose]){ enclose = _temp[type]["enclose" + _param.enclose]; } } var base = _temp[type].base if(_param.li_devide == 1){ base = _temp["One"].base } var a = []; // _temp[One].base a.push(base); a.push(enclose); a.push(_temp[type].images); a.push(_temp[type].texts); a.push(extra); a.push(_temp[design].t1); a.push(_temp[design].t2); a.push(_temp[design].t3); a.push(_temp.res); var u = _param.unit; var css = a.join(""); css = css.split("{UL_MR}" ).join(_param.ul_marginR + u); css = css.split("{LI_W}" ).join(_param.li_width + u); css = css.split("{LI_M}" ).join(_param.li_margin + u); css = css.split("{IMG_W}" ).join(_param.img_width + u); css = css.split("{TEXT_W}" ).join(_param.text_margin + u); // css = css.split("{IMG_H}" ).join(_param.img_h); css = css.split("{IMG_H}" ).join(""); css = css.split("{IMG_M}" ).join(_param.img_m); return css; } function get_ul_marginR(_isFix,_w,_m,_d) { if(_isFix){ return 20; } else{ return 100 - ((_w * _d) + (_m * (_d - 1))); } } function get_img_width(_w) { var w = _w; w = w.split("px").join(""); w = w.split("%").join(""); return Number(w); } // function get_img_height(_h) { // var h = _h; // h = h.split("px").join(""); // h = h.split("%").join(""); // return Number(h); // } function get_text_margin(_isFix,_w) { var w = _w; w = w.split("px").join(""); w = w.split("%").join(""); var ww = Number(w); if(_isFix){ return ww + 10; } else { return ww + 3; } } // function get_img_h(_type,_h) { // if(_h == undefined) return "" // if(_h == "") return "" // var s = ""; // s += ' max-height:'+_h+'px;\n'; // s += ' overflow:hidden;\n'; // return s; // } function get_img_m(_type,_enclose) { var s = "0 0 10px 0"; if(_type == "LTF") s = "0 5px 10px 0"; if(_type == "RTF") s = "0 0 10px 5px"; if(_type == "T") { if(_enclose != 0){ s = "-10px -10px 10px -10px"; } } if(_type == "B") { if(_enclose != 0){ s = "10px -10px -10px -10px"; } } return s; } function getCode(_in) { var p = {} p.type = _in.type; p.design = get_design(_in.design); p.isFix = get_isFix(_in.width); p.unit = get_unit(p.isFix); p.enclose = _in.enclose; p.li_devide = get_li_devide(_in.devide); p.li_margin = get_li_margin(_in.margin); p.li_width = get_li_width(_in.width, p.isFix, p.li_margin, p.li_devide); p.ul_marginR = get_ul_marginR(p.isFix,p.li_width, p.li_margin, p.li_devide); p.img_width = get_img_width(_in.img_width); // p.img_height = get_img_height(_in.img_height); p.text_margin = get_text_margin(p.isFix,_in.img_width); // p.img_h = get_img_h(p.type,p.img_height); p.img_m = get_img_m(p.type,p.enclose); var code = EditableView.CustomListData_Dic; var html = getCodeHTML(code.html,p); var css = getCodeCSS(code.css,p); return { css:css, html:html } } return { getCode: getCode } })(); <file_sep>/src/js/cms_model/PageElement.replace.div.js PageElement.replace.div = (function(){ var _ = new PageModel.Tag_(); /* ---------- ---------- ---------- */ _.pageInfo = new PageModel.Object_Info({ id : "replace.div", name : "Myタグ-コンテナ定義", name2 : "", inputs : [], // cssDef : {file:"block",key:"[コンテナブロック]"}, cssDef : {selector:".cms-replace-div"} }); /* ---------- ---------- ---------- */ _.getInitData = function(){ var _p = PageElement_JText.P; var o = {}; o.type = _.pageInfo.id; o.data = [{ type: "tag.p", attr: { "class": "default", css: "default" }, data: _p }]; o.attr = { "class": "_cms_replace", css: " _cms_replace", style: "", replaceID: "ID名を入力", replaceTitle: "説明を入力" } return o; } /* ---------- ---------- ---------- */ _.getPreview = function(_o){ return ""; } /* ---------- ---------- ---------- */ _.getHTML = function(_o,_tab){ return ""; } /* ---------- ---------- ---------- */ return _; })(); <file_sep>/src/js/cms_view_floats/AddElementsView.js AddElementsView = (function(){ var view; var v = {}; function init(){ view = $('#AddElementsView'); var tag = ""; tag += '<div class="_mouseArea"></div>'; tag += '<div class="_core ss_add_bg"></div>'; tag += '<div class="_text_block_add ">'; tag += ' <div class="_btn"><div class="_cms_btn_alphaS ss_add_misk _00"></div></div>'; tag += ' <div class="_btn" '+TIP("#+1")+'><div class="_cms_btn_alphaS ss_add_misk _h1 _btn_add_h1"></div></div>'; tag += ' <div class="_btn" '+TIP("#+2")+'><div class="_cms_btn_alphaS ss_add_misk _h2 _btn_add_h2"></div></div>'; tag += ' <div class="_btn" '+TIP("#+3")+'><div class="_cms_btn_alphaS ss_add_misk _h3 _btn_add_h3"></div></div>'; tag += ' <div class="_btn" '+TIP("#+4")+'><div class="_cms_btn_alphaS ss_add_misk _h4 _btn_add_h4"></div></div>'; tag += ' <div class="_btn" '+TIP("#+5")+'><div class="_cms_btn_alphaS ss_add_misk _p _btn_add_p"></div></div>'; tag += ' <div class="_btn" '+TIP("#+6")+'><div class="_cms_btn_alphaS ss_add_misk _free _btn_add_markdown"></div></div>'; tag += ' <div class="_btn" '+TIP("#+7")+'><div class="_cms_btn_alphaS ss_add_misk _img _btn_add_img"></div></div>'; tag += ' <div class="_btn" '+TIP("#+8")+'><div class="_cms_btn_alphaS ss_add_misk _margin _btn_add_margin"></div></div>'; tag += '</div>'; tag += '<div class="_help-icon _btn_guide_base"><i class="fa fa-question "></i></div>'; view.html(tag) v.core = view.find('._core'); v.baseBlock = view.find('._00'); // view.find('._btn_guide_base').click(function(){CMS_GuideView.stageIn("block/base"); }); view.find('._btn_guide_base').click(function(){ CMS_GuideU.openGuide("block/base"); }); setBtn(); } /* ---------- ---------- ---------- */ function setBtn(){ var tag = "" tag += '<div class="_btn_add_div ss_add _btn_l_01" ></div>'; tag += '<div class="_btn_add_cols2 ss_add _btn_l_02" ></div>'; tag += '<div class="_btn_add_cols3 ss_add _btn_l_03" ></div>'; tag += '<div class="_btn_add_cols4 ss_add _btn_l_04" ></div>'; tag += '<div class="_btn_add_margin ss_add _btn_margin" ></div>'; tag += '<div class="_btn_add_a ss_add _btn_o_a" ></div>'; tag += '<div class="_btn_add_note ss_add _btn_note" ></div>'; tag += '<div class="_btn_add_place ss_add _btn_place" ></div>'; tag += '<div class="_btn_add_h1 ss_add _btn_h_01" ></div>'; tag += '<div class="_btn_add_h2 ss_add _btn_h_02" ></div>'; tag += '<div class="_btn_add_h3 ss_add _btn_h_03" ></div>'; tag += '<div class="_btn_add_h4 ss_add _btn_h_04" ></div>'; tag += '<div class="_btn_add_markdown ss_add _btn_o_md" ></div>'; tag += '<div class="_btn_add_p ss_add _btn_t_01" ></div>'; tag += '<div class="_btn_add_list ss_add _btn_t_list" ></div>'; tag += '<div class="_btn_add_img ss_add _btn_o_01" ></div>'; tag += '<div class="_btn_add_imgs ss_add _btn_o_images " ></div>'; tag += '<div class="_btn_add_btn ss_add _btn_t_btn" ></div>'; tag += '<div class="_btn_add_btnList ss_add _btn_t_btnlist" ></div>'; tag += '<div class="_btn_add_table2 ss_add _btn_o_fulltable" ></div>'; tag += '<div class="_btn_add_html ss_add _btn_o_html" ></div>'; tag += '<div class="_btn_add_blq ss_add _btn_t_blq" ></div>'; tag += '<div class="_btn_add_code ss_add _btn_t_code" ></div>'; var ade = AddElementsManager.addElement; v.core.html(tag); view.find('._btn_add_div') .click(function(){ade("layout.div","")}); view.find('._btn_add_cols2') .click(function(){ade("layout.cols","2")}); view.find('._btn_add_cols3') .click(function(){ade("layout.cols","3")}); view.find('._btn_add_cols4') .click(function(){ade("layout.cols","4")}); view.find('._btn_add_cols5') .click(function(){ade("layout.cols","5")}); view.find('._btn_add_margin') .click(function(){ade("tag.margin","")}); view.find('._btn_add_note') .click(function(){ade("tag.note","")}); view.find('._btn_add_place') .click(function(){ade("tag.place","")}); view.find('._btn_add_h1') .click(function(){ade("tag.heading","h1")}); view.find('._btn_add_h2') .click(function(){ade("tag.heading","h2")}); view.find('._btn_add_h3') .click(function(){ade("tag.heading","h3")}); view.find('._btn_add_h4') .click(function(){ade("tag.heading","h4")}); view.find('._btn_add_p') .click(function(){ade("tag.p","")}); view.find('._btn_add_list') .click(function(){ade("object.list","")}); view.find('._btn_add_btn') .click(function(){ade("tag.btn","")}); view.find('._btn_add_btnList') .click(function(){ade("object.btnList","")}); view.find('._btn_add_a') .click(function(){ade("tag.anchor","")}); view.find('._btn_add_img') .click(function(){ade("tag.img","")}); view.find('._btn_add_imgs') .click(function(){ade("object.images","")}); view.find('._btn_add_table2') .click(function(){ade("object.table","")}); view.find('._btn_add_html') .click(function(){ade("tag.html","")}); view.find('._btn_add_markdown') .click(function(){ade("tag.markdown","")}); view.find('._btn_add_blq') .click(function(){ade("tag.blockquote","")}); view.find('._btn_add_code') .click(function(){ade("tag.code","")}); v.baseBlock.click( function (){click_()}); view.hover( function(){ hover() }, function(){ hoverOut() } ); window.addBlock = AddElementsManager.addElement; } function click_(){ if(tID) clearTimeout(tID) view.addClass("hover") hideFloatView(); } function hover(){ if(tID) clearTimeout(tID) } var tID function hoverOut(){ if(tID) clearTimeout(tID) tID = setTimeout(function(){ view.removeClass("hover") },500); } /* ---------- ---------- ---------- */ return { init: init } })();<file_sep>/src/js/cms_stage_asset/CMS_Asset_CreateFileView.js var CMS_Asset_CreateFileView = (function(){ var view; var v = {}; /* ---------- ---------- ---------- */ //初期化 function init(){ view = $('#CMS_Asset_CreateFileView'); var tag = '' tag += '<div class="_btn_close"><i class="fa fa-lg fa-times-circle "></i> </div>' tag += '<div class="_body">' tag += ' <div class="_dir_area">' tag += ' <div class="_title"><span class="_icon_dir"></span> ディレクトリを追加</div>' tag += ' <input type="text" placeholder="ディレクトリ名を入力" value="">' tag += ' <div class="_cms_btn _cms_btn_disable _btn_add_dis">追加する</div>' tag += ' <div class="_cms_btn _cms_btn_active _btn_add">追加する</div>' tag += ' <div class="_atten"></div>' tag += ' </div>' tag += ' <div class="_file_area">' tag += ' <div class="_title"><i class="fa fa-fw fa-file-text"></i> ファイルを追加</div>' tag += ' <input type="text" placeholder="ファイル名を入力" value="">' tag += ' <div class="_cms_btn _cms_btn_disable _btn_add_dis">追加する</div>' tag += ' <div class="_cms_btn _cms_btn_active _btn_add">追加する</div>' tag += ' <div class="_atten"></div>' tag += ' </div>' tag += '</div>' view.append(tag); v.btn_close = view.find('._btn_close'); v.file_input = view.find("._file_area input"); v.file_input.keyup(function(){ keyup(); }) v.file_btn_add_dis = view.find("._file_area ._btn_add_dis"); v.file_btn_add = view.find("._file_area ._btn_add"); v.file_atten = view.find('._file_area ._atten'); v.dir_input = view.find("._dir_area input"); v.dir_input.keyup(function(){ keyup(); }) v.dir_btn_add_dis = view.find("._dir_area ._btn_add_dis"); v.dir_btn_add = view.find("._dir_area ._btn_add"); v.dir_atten = view.find('._dir_area ._atten'); stageInit(); createlayout(); setBtn(); } /* ---------- ---------- ---------- */ //レイアウト作成・イベントアサイン function createlayout(){ } function setBtn(){ v.btn_close.click(function(){ stageOut() }); v.file_btn_add.click(function(){ file_add(); }); v.dir_btn_add.click(function(){ dir_add(); }); registAssetFloatView(function(){stageOut()}); } /* ---------- ---------- ---------- */ //個別処理 var callback function update(_fileListClass,_callback){ callback = _callback; checkFileNameInit(_fileListClass); v.file_btn_add.hide() v.file_btn_add_dis.show() v.file_input.val("").keyup(); v.dir_input.val("").keyup(); } function keyup(){ keyup_file() keyup_dir() } function keyup_file(){ var s = v.file_input.val(); var errs = [] var b = false; if(s){ var e = CMS_Asset_UploadU.checkFileName(s); if(e) errs.push(e); if(checkFileName(s)){ errs.push('<i class="fa fa-exclamation "></i> 同名ファイルが存在します。') } else{ b = true; } } if(b){ v.file_btn_add.show() v.file_btn_add_dis.hide() v.file_atten.html(""); } else{ v.file_btn_add.hide() v.file_btn_add_dis.show() } if(errs.length == 0){ v.file_atten.html(""); } else{ v.file_atten.html(errs.join("")); } } function keyup_dir(){ var s = v.dir_input.val(); var errs = [] var b = false; if(s){ var e = CMS_Asset_UploadU.checkFileName(s); if(e) errs.push(e); if(checkFileName(s)){ errs.push('<i class="fa fa-exclamation "></i> 同名ファイルが存在します。') } else{ b = true; } } if(b){ v.dir_btn_add.show() v.dir_btn_add_dis.hide() v.dir_atten.html(""); } else{ v.dir_btn_add.hide() v.dir_btn_add_dis.show() } if(errs.length == 0){ v.dir_atten.html(""); } else{ v.dir_atten.html(errs.join("")); } } /* ---------- ---------- ---------- */ function file_add(){ if(window.isLocked(true))return; var s = v.file_input.val(); if(s){ callback ("file",s); } stageOut(); } function dir_add(){ if(window.isLocked(true))return; var s = v.dir_input.val(); if(s){ callback ("dir",s); } stageOut(); } /* ---------- ---------- ---------- */ var currentFilenames; function checkFileNameInit(_fileListClass){ currentFilenames = _fileListClass.getCurrentFilelist(); } function checkFileName(_s){ for (var i = 0; i < currentFilenames.length ; i++) { if(_s == currentFilenames[i]) return true; } return false; } /* ---------- ---------- ---------- */ //表示・非表示処理 var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } function stageIn(_fileListClass,_callback){ if(! isOpen){ isOpen = true; view.show(); if(isFirst){} isFirst = false; update(_fileListClass,_callback); } } function stageOut(){ if(isOpen){ isOpen = false; view.hide(); } } return { init:init, stageIn:stageIn, stageOut:stageOut } })(); var CMS_Asset_RenameFileView = (function(){ var view; var v = {}; /* ---------- ---------- ---------- */ //初期化 function init(){ view = $('#CMS_Asset_RenameFileView'); var tag = '' tag += '<div class="_btn_close"><i class="fa fa-lg fa-times-circle "></i> </div>' tag += '<div class="_body">' tag += ' <div class="_title">変更後の名称を入力</div>' tag += ' <input type="text" placeholder="ファイル名を入力" value="">' tag += ' <div class="_cms_btn _cms_btn_disable _btn_rename_dis">変更する</div>' tag += ' <div class="_cms_btn _cms_btn_active _btn_rename">変更する</div>' tag += ' <div class="_atten"></div>' tag += '</div>' view.append(tag); v.btn_close = view.find('._btn_close'); v.input = view.find(" input"); v.input.keyup(function(){ keyup(); }) v.btn_rename_dis = view.find(" ._btn_rename_dis"); v.btn_rename = view.find(" ._btn_rename"); v.atten = view.find(' ._atten'); stageInit(); createlayout(); setBtn(); } /* ---------- ---------- ---------- */ //レイアウト作成・イベントアサイン function createlayout(){ } function setBtn(){ v.btn_close.click(function(){ stageOut() }); v.btn_rename.click(function(){ rename(); }); registAssetFloatView(function(){stageOut()}); } /* ---------- ---------- ---------- */ //個別処理 var callback var defName = "" function update(_fileListClass,_name,_callback,_pos){ callback = _callback; checkFileNameInit(_fileListClass); defName = _name; v.btn_rename.hide() v.btn_rename_dis.show() v.input.val(defName).keyup(); if(_pos){ } } function keyup(){ var s = v.input.val(); var errs = [] var b = false; if(s != defName){ if(s){ var e = CMS_Asset_UploadU.checkFileName(s); if(e) errs.push(e); if(checkFileName(s)){ errs.push('<i class="fa fa-exclamation "></i> 同名ファイルが存在します。') } else{ b = true; } } } if(b){ v.btn_rename.show() v.btn_rename_dis.hide() v.atten.html(""); } else{ v.btn_rename.hide() v.btn_rename_dis.show() } if(errs.length == 0){ v.atten.html(""); } else{ v.atten.html(errs.join("")); } } /* ---------- ---------- ---------- */ function rename(){ if(window.isLocked(true))return; var s = v.input.val(); if(s){ callback (s); } stageOut(); } /* ---------- ---------- ---------- */ var currentFilenames; function checkFileNameInit(_fileListClass){ currentFilenames = _fileListClass.getCurrentFilelist(); } function checkFileName(_s){ for (var i = 0; i < currentFilenames.length ; i++) { if(_s == currentFilenames[i]) return true; } return false; } /* ---------- ---------- ---------- */ //表示・非表示処理 var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } function stageIn(_fileListClass,_name,_callback,_pos){ if(! isOpen){ isOpen = true; view.show(); if(isFirst){} isFirst = false; update(_fileListClass,_name,_callback,_pos); } } function stageOut(){ if(isOpen){ isOpen = false; view.hide(); } } return { init:init, stageIn:stageIn, stageOut:stageOut } })(); <file_sep>/src/js/cms_view_inspect/InspectView.FormU.js InspectView.FormU = (function(){ var updateCallback; function init(){ updateCallback = InspectView.updateCallerView; InspectView.FormU_Img.init(); InspectView.FormU_Preset.init() //フォームのイベントアサインは、CMS_FormUで行う } /* ---------- ---------- ---------- */ function assignMainInput(_node,_param){ _node.find("._in_data").keyup(function() { updateMainParam(_param,$(this).val()); }); } function updateMainParam(_param,_v){ if(_param.data == _v)return; _param.data = _v; updateCallback(); } // function assignExtraInput(_node,_param){ _node.find("._in_data_extra").keyup(function(){ updateExtra( _param,$(this).val() ,$(this).data("type")); }); } function updateExtra(_param,val,_tar){ if(_param["extra"] ==undefined) _param.extra = {} _param.extra[_tar] = val; updateCallback(); } // function assignAttrInput(_node,_param){ _node.find("._in_data_attr").keyup(function(){ updateAttr( _param,$(this).val() ,$(this).data("type")); }); } function updateAttr(_param,val,_tar){ InspectView.setAtt(_tar,val); } /* ---------- ---------- ---------- */ function getHeadlineTag(_param){ function _core(_name,_type,_placeholder,_layout){ var s = "" s += ' <tr>'; s += ' <td>{NAME}</td>'; s += ' <td>'; s += ' <div class="_input-with-btns">' s += ' <input class="_in_data_H " data-type="{TYPE}" placeholder="{PH}" value="{DATA}">' s += ' <div class="_btns"><span class="_btn_input _edit_single" data-type="input:text">'+Dic.I.Edit+'</span></div>' s += ' </div>' s += ' </td>'; s += ' <td style="text-align:right;"><div class="_cms_btn_alpha _btn_anchor" data-type="{TYPE}"></div></td>'; s += ' </tr>'; s = s.split("{NAME}").join(_name) s = s.split("{PH}").join(_placeholder) s = s.split("{TYPE}").join(_type) return s; } var tag = "" tag += '<div>' tag += ' <input class="_in_data_H_Type" style="display:none;" value="'+_param.data.heading+'">' tag += ' <div class="_selectArea"></div>'; tag += ' <table class="_mainlayout">'; tag += _core("","main","テキストを入力","main"); tag += ' </table>'; tag += ' <table class="_mainlayout more_detail">'; tag += _core("","right","サブテキストを入力",""); tag += ' </table>'; tag += '</div>' var node = $(tag); node.find("._in_data_H").eq(0).val(_param.data["main"].text); node.find("._in_data_H").eq(1).val(_param.data["right"].text); _setAnchorEvents(node,_param); InspectView.FormU_Heading.setNode(node,_param.data.heading); node.find("._in_data_H") .keyup(function(){ editTextHeader( $(this).val() ,$(this).data("type")); }); node.find("._in_data_H_Type") .keyup(function(){ editTextH_Type( $(this).val()); }); function editTextHeader(val,_tar){ var node = _param.data[_tar] if(node.text == val)return; node.text = val; updateCallback(); } function editTextH_Type(val,_tar){ var node = _param.data; if(node.heading == val)return; node.heading = val; updateCallback(); } return node; } /* ---------- ---------- ---------- */ function getCaptionTag(_param,_extra){ var tag = "" tag += '<table class="_mainlayout" style="margin-bottom:10px;">'; tag += '<tr><th>見出し</th><td>' tag += ' <div class="_input-with-btns">' tag += ' <input class="_in_data_extra" data-type="head" placeholder="キャプション" value="">' tag += ' <div class="_btns"><span class="_btn_input _edit_single" data-type="input:text">'+Dic.I.Edit+'</span></div>' tag += ' </div>' tag += '</td></tr>'; tag += '</table>'; var node = $(tag); node.find("._in_data_extra").val(defaultVal(_extra.head,"")); assignExtraInput(node,_param); return node; } function getAnchor(_param){ var tag = ""; tag += '<table class="_mainlayout">'; tag += '<tr><th>ページ内<br>リンク用ID</th><td><input class="_in_data"></td></tr>'; tag += '</table>'; var node = $(tag); node.find("input").val(_param.data); assignMainInput(node,_param); return node; } function getTextarea(_param){ var tag = "" tag += '<div class="_input-with-btns _input-textarea">' tag += ' <textarea class="_textarea-scroll _in_data" placeholder="テキストを入力"></textarea><br>' tag += ' <div class="_btns">' tag += ' <span class="_btn_input _edit" data-type="textarea:p">'+Dic.I.Edit+' 編集</span> ' tag += ' </div>' tag += '</div>' var node = $(tag); node.find("textarea").val(_param.data); assignMainInput(node,_param); return node; } function getMarkdown(_param){ var tag = ""; tag += '<div class="_input-with-btns _input-textarea">' tag += ' <textarea class="_textarea-scroll _in_data" placeholder="テキストを入力"></textarea><br>' tag += ' <div class="_btns">' tag += ' <span class="_btn_input _edit" data-type="textarea:markdown">'+Dic.I.Edit+' 編集</span> ' tag += ' </div>' tag += '</div>' var node = $(tag); node.find("textarea").val(_param.data); assignMainInput(node,_param); return node; } function getCode(_param){ var tag = ""; tag += '<div class="_input-with-btns _input-textarea">' tag += ' <textarea class="_textarea-scroll _in_data _color-html" placeholder="テキストを入力"></textarea><br>' tag += ' <div class="_btns">' tag += '<span class="_btn_input _edit" data-type="textarea:code">'+Dic.I.Edit+' 編集</span> ' tag += ' </div>' tag += '</div>' var node = $(tag); if(_param) node.find("textarea").val(_param.data); assignMainInput(node,_param); return node; } function getHtml(_param,_preview,_callback){ var tag = ""; tag += '<div>' tag += ' <div class="_input-with-btns _input-textarea">' tag += ' <textarea class="_textarea-scroll _in_data _color-html" placeholder="テキストを入力"></textarea><br>' tag += ' <div class="_btns">' tag += '<span class="_btn_input _edit" data-type="textarea:html">'+Dic.I.Edit+' 編集</span> ' tag += ' </div>' tag += ' </div>' tag += ' <div class="_in_preview_on" style="margin:5px 0;"><i class="fa fa-lg fa-square-o "></i> プレビューする (JSも実行されます)</div>' tag += ' <div class="_in_preview_off" style="margin:5px 0;"><i class="fa fa-lg fa-check-square "></i> プレビューする (JSも実行されます)</div>' tag += '</div>' var node = $(tag); if(_param) node.find("textarea").val(_param.data); assignMainInput(node,_param); function _toggle(_v){ node.find("._in_preview_on").hide(); node.find("._in_preview_off").hide(); if(_v == ""){ node.find("._in_preview_on").show(); } else{ node.find("._in_preview_off").show(); } InspectView.setAttr_preview(_v); } node.find("._in_preview_on").click(function(){ _toggle("1")}) node.find("._in_preview_off").click(function(){ _toggle("")}) _toggle(_preview); return node; } function getJS(_param,_preview,_callback){ var tag = ""; tag += '<div>' tag += ' <div class="_input-with-btns _input-textarea">' tag += ' <textarea class="_textarea-scroll _in_data _color-html" placeholder="JavaScriptを入力"></textarea><br>' tag += ' <div class="_btns">' tag += '<span class="_btn_input _edit" data-type="textarea:js">'+Dic.I.Edit+' 編集</span> ' tag += ' </div>' tag += ' </div>' tag += '</div>' var node = $(tag); if(_param) node.find("textarea").val(_param.data); assignMainInput(node,_param); return node; } function getMargin(_param){ var tag = ""; tag += '<table class="_mainlayout">'; tag += '<tr><th>高さマージン</th><td><input class="_in_data"></td></tr>'; tag += '<tr><td colspan="2">' tag += 'マイナスマージンも設定できます。<br>例:-100px'; tag += '</td></tr>'; tag += '</table>'; var node = $(tag); node.find("input").val(_param.data); assignMainInput(node,_param); return node; } function getNote(_param){ var tag = ""; tag += '<table class="_mainlayout">'; tag += '<tr><th>ノート</th><td>' tag += ' <div class="_input-with-btns _input-textarea">' tag += ' <textarea class="_textarea-scroll _in_data" placeholder="テキストを入力"></textarea><br>' tag += ' <div class="_btns">' tag += ' <span class="_btn_input _edit" data-type="textarea:multi">'+Dic.I.Edit+' 編集</span> ' tag += ' </div>' tag += ' </div>' tag += '</td></tr>'; tag += '</table>'; var node = $(tag); node.find("textarea").val(_param.data); assignMainInput(node,_param); return node; } function getPlace(_param,_extra){ var tag = ""; tag += '<table class="_mainlayout">'; tag += '<tr><th>ノート</th><td>' tag += ' <div class="_input-with-btns _input-textarea">' tag += ' <textarea class="_textarea-scroll _in_data" placeholder="テキストを入力"></textarea><br>' tag += ' <div class="_btns">' tag += ' <span class="_btn_input _edit" data-type="textarea:multi">'+Dic.I.Edit+' 編集</span> ' tag += ' </div>' tag += ' </div>' tag += '</td></tr>'; tag += '<tr><th>サイズ</th><td>'; tag += '幅: <input class="_in_data_extra _w50" data-type="width"><br>'; tag += '高: <input class="_in_data_extra _w50" data-type="height">'; tag += '</td></tr>'; tag += '</table>'; var node = $(tag); node.find("textarea").val(_param.data); node.find("._in_data_extra").eq(0).val(defaultVal(_extra.width,"")); node.find("._in_data_extra").eq(1).val(defaultVal(_extra.height,"")); assignMainInput(node,_param); assignExtraInput(node,_param); return node; } function getBtn(_param){ var tag = ""; tag += '<table class="_mainlayout">'; tag += '<tr><th>リンク</th><td><div class="_btn_TextAnchor _cms_btn_alpha"></div></td></tr>'; tag += '</table>'; var node = $(tag); new InspectView.TextAnchorClass( node.find('._btn_TextAnchor'), defaultVal(_param.data,""), function (_val){ _param.data = _val; updateCallback(); } ); return node; } function _setAnchorEvents(_node,_param){ //リンク設定 var btns = _node.find('._btn_anchor'); btns.each(function (index, dom) { var tar = $(this); var type = tar.data("type"); var _link = (type == "") ? _param.data : _param.data[type]; new InspectView.AnchorClass( tar, defaultVal(_link.link,{}), function (_val){ _link.link = _val; updateCallback(); } ); }); } /* ---------- ---------- ---------- */ function getDetail(_blockType,_currentDiv){ var tag = ""; tag += '<div>' tag += '<span class="_cms_btn _cms_btn_edit" '+TIP_ENTER+'>' tag += Dic.I.Grid+' データの編集</span>'; tag += '</div>' var node = $(tag); node.find("._cms_btn_edit").click(function(){ var id = _blockType.split(".")[1]; var d = PageElement.object[id]; if(d) _currentDiv.showInlineGridEditor(InspectView.getCurrentNo() ,d); }); return node; } function getReload(_blockType,_currentDiv){ var tag = ""; tag += '<div>' tag += '<span class="_cms_btn _cms_btn_reload">' tag += '<i class="fa fa-refresh "></i> プレビュー更新</span>'; tag += '</div>' var node = $(tag); node.find("._cms_btn_reload").click(function(){ // updateCallback(); InspectView.refreshBlock(); }); return node; } function getTree(_param){ var tag = ""; tag += '<div>' tag += '<span class="_cms_btn _cms_btn_edit" '+TIP_ENTER+'>' tag += Dic.I.Grid+' データの編集</span>'; tag += '</div>' var node = $(tag); node.find("._cms_btn_edit").click(function(){ var val = _param.data; var htmlAbs = CMS_Path.PAGE.ABS; var tree = CMS_Data.Sitemap.getData(); TreeViewMakerView.stageIn(htmlAbs,tree,val,function(_s){ _param.data = _s; setTimeout(function(){ updateCallback(); }, 200); }); }); return node; } /* ---------- ---------- ---------- */ //画像リスト // function getImageMap(_param){ // var tag = ""; // tag += '<div>' // tag += '<span class="_cms_btn _cms_btn_edit" '+TIP_ENTER+'>' // tag += Dic.I.Grid+' データの編集</span>'; // tag += '</div>' // var node = $(tag); // node.find("._cms_btn_edit").click(function(){ // ImageMapView.stageIn(_param.data,function(_s){ // _param.data = _s; // setTimeout(function(){ // updateCallback(); // }, 200); // }); // }); // return node; // } function getLayoutCol(){ return $('<div class="ss_guide _inspect"></div>'); } function getReplaceDiv(_param){ var tag = ""; tag += '<table class="_mainlayout">'; tag += '<tr><th>Myタグ<br>ID</th><td><input class="_in_data_attr" data-type="replaceID"></td></tr>'; tag += '<tr><th>説明</th><td><input class="_in_data_attr" data-type="replaceTitle"></td></tr>'; tag += '</table>'; if(_param.attr["replaceID"] ==undefined)_param.attr.replaceID = ""; if(_param.attr["replaceTitle"] ==undefined)_param.attr.replaceTitle = ""; var node = $(tag); node.find("._in_data_attr").eq(0).val(_param.attr.replaceID); node.find("._in_data_attr").eq(1).val(_param.attr.replaceTitle); assignAttrInput(node,_param); return node; } function getGuide(_type){ var s = '<div style="height:5px;"></div>' s += CMS_GuideU.getGuideTag("block/"+_type,PageElement_Util.getTypeName(_type) + "について","dark"); return $(s); } function getDesginGuide(){ var s = '<div style="height:5px;"></div>' s += CMS_GuideU.getGuideTag("inspect/design","デザインタブについて","dark"); return $(s); } /* ---------- ---------- ---------- */ function getDesignTag(_val,_blockType,_extra){ var tag = "" tag += '<div class="_body_css_class">'; tag += 'class="値"<br>'; tag += '<div class="_input-with-btns" style="margin:2px 0;">' tag += ' <input class="_design _color-style _bold" placeholder="クラス名を入力 (例:designA)">'; tag += ' <div class="_btns">' tag += ' <span class="_btn_input _edit_single" data-type="input:class">'+Dic.I.Edit+'</span> ' tag += ' </div>' tag += '</div>' tag += '</div>'; var node = $(tag); node.find("input").val(_val) node.find("input").keyup(function(){ InspectView.setAttr_css($(this).val()); }); InspectView.FormU_Preset.setNode( node,_blockType,_extra ); return node; } function getStyleTag(_val){ var tag = "" tag += '<div class="_body_css_style">'; tag += 'style="値"<br>'; tag += '<div class="_input-with-btns _input-textarea" style="margin:2px 0;">' tag += ' <textarea class="_style _color-style" placeholder="CSSを入力 (例:font-size:12px)"></textarea><br>' tag += ' <div class="_btns">' tag += ' <span class="_btn_input _edit" data-type="textarea:style">'+Dic.I.Edit+'</span> ' tag += ' </div>' tag += '</div>' tag += '</div>' var node = $(tag); node.find("textarea").val(_val) node.find("textarea").keyup(function(){ InspectView.setAttr_style($(this).val()); }); return node; } return { init : init, getHeadlineTag : getHeadlineTag, getCaptionTag : getCaptionTag, getAnchor : getAnchor, getTextarea : getTextarea, getMarkdown : getMarkdown, getCode : getCode, getHtml : getHtml, getJS : getJS, getMargin : getMargin, getNote : getNote, getPlace : getPlace, getBtn : getBtn, getDetail : getDetail, getReload : getReload, getTree : getTree, // getImageMap : getImageMap, getLayoutCol : getLayoutCol, getReplaceDiv : getReplaceDiv, getGuide : getGuide, getDesginGuide : getDesginGuide, getDesignTag : getDesignTag, getStyleTag : getStyleTag } })(); <file_sep>/src/js/cms_stage_asset/CMS_Asset_FilesArea.js var CMS_Asset_FilesArea = (function(){ var view; var v = {}; /* ---------- ---------- ---------- */ //初期化 function init(){ view = $('#CMS_Asset_FilesArea'); stageInit(); createlayout(); setBtn(); } /* ---------- ---------- ---------- */ //レイアウト作成・イベントアサイン function createlayout(){ var tag = ""; tag += '<div id="CMS_Asset_FileListView"></div>'; tag += '<div id="CMS_Asset_FileDetailView"></div>'; tag += '<div id="CMS_Asset_UploaderView"></div>'; tag += '<div id="CMS_Asset_CreateFileView"></div>'; tag += '<div id="CMS_Asset_RenameFileView"></div>'; view.html(tag); CMS_Asset_FileListView.init(); CMS_Asset_FileDetailView.init(); CMS_Asset_UploaderView.init(); CMS_Asset_CreateFileView.init(); CMS_Asset_RenameFileView.init(); } function setBtn(){ } /* ---------- ---------- ---------- */ //個別処理 function openPath(_param){ CMS_Asset_FileListView.openPath(_param); } /* ---------- ---------- ---------- */ //表示・非表示処理 var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } function stageIn(){ if(! isOpen){ isOpen = true; view.show(); if(isFirst){ CMS_Asset_FileListView.stageIn(); } isFirst = false; } } function stageOut(){ if(isOpen){ isOpen = false; view.hide(); } } return { init: init, openPath: openPath, stageIn: stageIn, stageOut: stageOut } })();<file_sep>/src/js/cms_stage_asset/CMS_AssetFileU.js var CMS_AssetFileU = (function(){ function treadExtention(_s){ var exs = [".jpg",".jpeg",".png",".gif",".bmp",".svg"]; for (var i = 0; i < exs.length ; i++) { var ex = exs[i] var cc = ex.length; if(_s.substr(_s.length - cc , cc) == ex){ return _s.substr(0 , _s.length - cc) } } return _s; } function checkIsImage (_s) { var b = false; var ex = _s.toLowerCase(); if (ex.indexOf(".png") != -1) b = true; if (ex.indexOf(".jpeg") != -1) b = true; if (ex.indexOf(".jpg") != -1) b = true; if (ex.indexOf(".gif") != -1) b = true; if (ex.indexOf(".svg") != -1) b = true; if (ex.indexOf(".bmp") != -1) b = true; return b; } var exs = { editable:["html","htm","text","txt","xml","json","js","css","php","rb","as","md"], html:["html","htm"], img:["gif","png","jpg","jpeg","bmp","svg"], text:["text","txt","xml","json","js","css","rb","as","md"], mov:["mp3","mp4","mov"], pdf:["pdf"] } function isExtention(_ex ,_type){ var _a = exs[_type] for (var i = 0; i < _a.length ; i++) { if(_ex.toLowerCase() == _a[i]) return true; } return false; } function isExtentionAll(_ex){ for (var n in exs) { var _a = exs[n] for (var i = 0; i < _a.length ; i++) { if(_ex.toLowerCase() == _a[i]) return true; } } return false; } function getExtention(_s){ return URL_U.getExtention(_s); } function isHeavyImage(_n){ if(_n > 10*1000)return true; return false; } /* ---------- ---------- ---------- */ function getFileIcon(_ex){ var icon = '<i class="fa fa-fw fa-file-o "></i>'; if(isExtention(_ex ,"editable")) icon = '<i class="fa fa-fw fa-file-text-o"></i>'; if(isExtention(_ex ,"html")) icon = '<i class="fa fa-fw fa-file-text"></i>'; // if(isExtention(ex ,"text")) icon = '<i class="fa fa-fw fa-file-text-o "></i>'; if(isExtention(_ex ,"img")) icon = '<i class="fa fa-fw fa-picture-o "></i>'; if(isExtention(_ex ,"mov")) icon = '<i class="fa fa-fw fa-file-movie-o"></i>'; if(isExtention(_ex ,"pdf")) icon = '<i class="fa fa-fw fa-file-pdf-o"></i> '; return icon; } return { treadExtention: treadExtention, checkIsImage: checkIsImage, isExtention: isExtention, isExtentionAll: isExtentionAll, getExtention: getExtention, isHeavyImage:isHeavyImage, getFileIcon:getFileIcon } })(); <file_sep>/src/js/cms_storage/Storage.Memo.js /** * LocalStorageを使用したメモ。状態の永続化で使用する * */ Storage.Memo = (function(){ /* ---------- ---------- ---------- */ //最後に見たページパラメータを記録 var LASTVIEW_PARAM = "JS_CMS_LASTVIEW_PARAM"; function getPageParam(){ if(localStorage[LASTVIEW_PARAM]){ return JSON.parse(localStorage[LASTVIEW_PARAM]); } else{ return null; } } function setPageParam(_param){ localStorage[LASTVIEW_PARAM] = JSON.stringify(_param); } /* ---------- ---------- ---------- */ var IS_PREVIEW_NO = "JS_CMS_IS_PREVIEW_NO_"; function getIsPreviewScNO(){ if(localStorage[IS_PREVIEW_NO]){ return localStorage[IS_PREVIEW_NO]; } else{ return 2; } } function setIsPreviewScNO(_n){ localStorage[IS_PREVIEW_NO] = _n; } /* ---------- ---------- ---------- */ var ZOOM_VAL = "JS_CMS_ZOOM_VAL_"; function getZoomVal(){ if(localStorage[ZOOM_VAL]){ return localStorage[ZOOM_VAL]; } else{ return "1"; } } function setZoomVal(_n){ localStorage[ZOOM_VAL] = _n; } /* ---------- ---------- ---------- */ var SIDEMENU_Y = "JS_CMS_SIDEMENU_Y"; function getSideMenuY(){ if(localStorage[SIDEMENU_Y]){ return localStorage[SIDEMENU_Y]; } else{ return "0"; } } var tID; function setSideMenuY(_n){ if(tID)clearTimeout(); tID = setTimeout(function(){ localStorage[SIDEMENU_Y] = _n; }, 100); } /* ---------- ---------- ---------- */ var PREVIEW_VISIBLE = "JS_CMS_PREVIEW_VISIBLE"; function getPreviewVisible(){ if(localStorage[PREVIEW_VISIBLE]){ return localStorage[PREVIEW_VISIBLE]; } else{ return "0"; } } function setPreviewVisible(_n){ localStorage[PREVIEW_VISIBLE] = _n; } /* ---------- ---------- ---------- */ var PREVIEW_STATE = "JS_CMS_PREVIEW_STATE"; function getPreviewState(){ if(localStorage[PREVIEW_STATE]){ return localStorage[PREVIEW_STATE].split("_"); } else{ return ["33","1000"]; } } function setPreviewState(_n){ localStorage[PREVIEW_STATE] = _n.join("_"); } /* ---------- ---------- ---------- */ var LIST_PREVIEW_FULL = "JS_LIST_PREVIEW_FULL"; function getListPreviewFull(){ var s = "0"; if(localStorage[LIST_PREVIEW_FULL]){ s = localStorage[LIST_PREVIEW_FULL]; } return (s == "1") ? true:false; } function setListPreviewFull(_b){ var s = (_b) ? "1" : "0"; localStorage[LIST_PREVIEW_FULL] = s; } var LIST_PREVIEW_STATE = "JS_LIST_PREVIEW_STATE"; function getListPreviewState(){ if(localStorage[LIST_PREVIEW_STATE]){ return localStorage[LIST_PREVIEW_STATE].split("_"); } else{ return ["33","1000"]; } } function setListPreviewState(_n){ localStorage[LIST_PREVIEW_STATE] = _n.join("_"); } /* ---------- ---------- ---------- */ // /* var PREVIEW_IS_LIVE = "JS_CMS_PREVIEW_IS_LIVE"; function getSideViewIsOpen(){ if(localStorage[PREVIEW_IS_LIVE]){ return localStorage[PREVIEW_IS_LIVE]; } else{ return "1"; } } function setSideViewIsOpen(_n){ localStorage[PREVIEW_IS_LIVE] = _n; } */ /* ---------- ---------- ---------- */ //サイドビューの表示・非表示 var SIDEVIEW_IS_OPEN = "JS_CMS_SIDEVIEW_IS_OPEN"; function getPreviewisLiveTab(){ if(localStorage[SIDEVIEW_IS_OPEN]){ return localStorage[SIDEVIEW_IS_OPEN]; } else{ return "0"; } } function setPreviewisLiveTab(_n){ localStorage[SIDEVIEW_IS_OPEN] = _n; } //サイドビューの表示・非表示 var SIDEVIEW_IS_CHECK = "JS_CMS_SIDEVIEW_IS_CHECK"; function getPreviewisLiveCheck(){ if(localStorage[SIDEVIEW_IS_CHECK]){ return localStorage[SIDEVIEW_IS_CHECK]; } else{ return "1"; } } function setPreviewisLiveCheck(_n){ localStorage[SIDEVIEW_IS_CHECK] = _n; } /* ---------- ---------- ---------- */ //サイドビューの、開閉記録 var SIDEVIEW_OPEN_LIST = "SIDEVIEW_OPEN_LIST"; function getSideViewOpenList(){ if(localStorage[SIDEVIEW_OPEN_LIST]){ return JSON.parse(localStorage[SIDEVIEW_OPEN_LIST]); } else{ return [false,true]; } } function setSideViewOpenList(_param){ localStorage[SIDEVIEW_OPEN_LIST] = JSON.stringify(_param); } /* ---------- ---------- ---------- */ var CUSTOM_BG = "" function initCustomBG(){ if(CUSTOM_BG == ""){ CUSTOM_BG = "CUSTOM_BG_" + CMS_Path.SITE.ABS_PATH } } function getCustomBG(){ initCustomBG(); if(localStorage[CUSTOM_BG]){ return localStorage[CUSTOM_BG]; } else{ return ""; } } function setCustomBG(_n){ initCustomBG(); localStorage[CUSTOM_BG] = _n; } /* ---------- ---------- ---------- */ var BACKUP_LIST = "BACKUP_LIST"; function getBK(){ if(localStorage[BACKUP_LIST]){ return localStorage[BACKUP_LIST]; } else{ return ""; } } function setBK(_param){ localStorage[BACKUP_LIST] = _param; } /* ---------- ---------- ---------- */ //編集幅指定(width:720px) // var EIDT_WIDE = "EIDT_WIDE"; // function getEditWide(){ // if(localStorage[EIDT_WIDE]){ // return JSON.parse(localStorage[EIDT_WIDE]); // } else{ // return "720"; // } // } // function setEditWide(_param){ // localStorage[EIDT_WIDE] = JSON.stringify(_param); // } /* ---------- ---------- ---------- */ return { getPageParam:getPageParam, setPageParam:setPageParam, getIsPreviewScNO:getIsPreviewScNO, setIsPreviewScNO:setIsPreviewScNO, getZoomVal:getZoomVal, setZoomVal:setZoomVal, getSideMenuY:getSideMenuY, setSideMenuY:setSideMenuY, getPreviewVisible:getPreviewVisible, setPreviewVisible:setPreviewVisible, getPreviewState:getPreviewState, setPreviewState:setPreviewState, getListPreviewFull:getListPreviewFull, setListPreviewFull:setListPreviewFull, getListPreviewState:getListPreviewState, setListPreviewState:setListPreviewState, getPreviewisLiveTab:getPreviewisLiveTab, setPreviewisLiveTab:setPreviewisLiveTab, getPreviewisLiveCheck:getPreviewisLiveCheck, setPreviewisLiveCheck:setPreviewisLiveCheck, getSideViewOpenList:getSideViewOpenList, setSideViewOpenList:setSideViewOpenList, getCustomBG:getCustomBG, setCustomBG:setCustomBG, getBK:getBK, setBK:setBK // getEditWide:getEditWide, // setEditWide:setEditWide } })();<file_sep>/src/js/cms_main/CMS_Path.js var CMS_Path = {} //基本パスデータ管理 CMS_PathFunc = (function(){ function init(_location){ if(_location == undefined) _location = window.location.href; var absSett = getAbs(ASSET_DIR_PATH, SITE_DIR_PATH); var absDef = getAbs(DEFAULT_DIR_PATH, SITE_DIR_PATH); //SITE CMS_Path.SITE = {} CMS_Path.SITE.URL = _getBaseDir(_location,SITE_DIR_PATH); CMS_Path.SITE.DIR = URL_U.getCurrentDir(CMS_Path.SITE.URL,1).split("/").join(""); CMS_Path.SITE.DOMAIN = URL_U.getDomain(CMS_Path.SITE.URL) CMS_Path.SITE.REL = SITE_DIR_PATH//CMSからみたサイトルート CMS_Path.SITE.REL_HTML = _getRelTop(DEFAULT_DIR_PATH)//HTMLディレクトリからみたサイトルート CMS_Path.SITE.ABS = "/" CMS_Path.SITE.ABS_PATH = window.location.pathname; //CMS CMS_Path.CMS = {} CMS_Path.CMS.ABS = URL_U.getCurrentDir(_location) +"/"; CMS_Path.CMS.REL = URL_U.treatDirName(CMS_Path.SITE.REL + CMS_Path.CMS.ABS) //UPLOAD CMS_Path.UPLOAD = {} CMS_Path.UPLOAD.REL = UPLOAD_DIR_PATH; CMS_Path.UPLOAD.ABS = getAbs(UPLOAD_DIR_PATH , SITE_DIR_PATH); //BACKUP CMS_Path.BACKUP = {} CMS_Path.BACKUP.REL = BACKUP_DIR_PATH; CMS_Path.BACKUP.ABS = getAbs(BACKUP_DIR_PATH , SITE_DIR_PATH); //htmlファイルからみた、トップディレクトリへのパス CMS_Path.SITE.getTopRelPath_from_html = function (_dir){ var s = "" if(_dir == undefined ) _dir= ""; if(_dir == ""){ s = CMS_Path.SITE.REL_HTML; } else if(_dir == "/"){ s = "./" }else { _dir = _dir.split("//").join("/"); var a = _dir.split("/") for (var i = 0; i < a.length ; i++) { if(a[i] != "") s += "../"; } } return s; } /* ---------- ---------- ---------- */ //MEDIA CMS_Path.MEDIA = {} CMS_Path.MEDIA.getImagePath = function (_path,_isPub,_isPreview){ if(DummyImageService.isMock(_path)){ if(_isPub){ return ""; } else { return DummyImageService.getImage(_path) } } else{ return CMS_Path.MEDIA.getAnchorPath(_path,_isPub,_isPreview) } } CMS_Path.MEDIA.getPreviewImageTag = function (_path){ return '<img src="' + CMS_Path.MEDIA.getImagePath(_path,false) +'">'; } CMS_Path.MEDIA.getAnchorPath = function (_path,_isPub,_isPreview){ if(typeof _path != "string"){ return "" } if(! _path) return ""; if(_isPub == undefined) _isPub = true; if(_isPreview == undefined) _isPreview = false; //#ページ内リンクは、そのまま返す if(_path.charAt(0) == "#") return _path; //httpからの場合は、そのまま返す if(URL_U.isFullPath(_path)) return _path; _path = _path.split("/////").join("/"); _path = _path.split("///").join("/"); _path = _path.split("//").join("/"); function _getPath (_s,_pub){ var base = (_pub) ? CONST.SITE_DIR : CMS_Path.SITE.REL; var s = base + _s; s = s.split(base+"/").join(base); return s; } //絶対パス if(_path.charAt(0) == "/"){ if(! _isPreview) { return _path; } else { //URLプレビュー _path = _path.substr(1,_path.length); if(_isPub){ return CMS_Path.SITE.DOMAIN + _path; } else{ return CMS_Path.SITE.REL + _path; } } } //相対パス if(_path.substr(0,2) == "./"){ if(! _isPreview) { return _getPath(_path,_isPub); } else { //URLプレビュー return URL_U.joinURL(CMS_Path.SITE.URL,_path) } } if(_path.substr(0,2) == ".."){ if(! _isPreview) { return _getPath(_path,_isPub); } else { //URLプレビュー if(_path.substr(0,3) == "../"){ return URL_U.joinURL(CMS_Path.SITE.URL,_path) } return CMS_Path.SITE.URL } } return _getPath(_path,_isPub); } CMS_Path.MEDIA.getAnchorPath_deco = function (_path,_isPub){ var path = CMS_Path.MEDIA.getAnchorPath(_path,true,true); var icon = (path.indexOf(CONST.SITE_DIR) != -1) ? Dic.I.External :""; path = path.split(CONST.SITE_DIR).join(CMS_Path.SITE.URL); var tar = _getTargetName(path); var s = path.split(_path).join("<span>" + _path + "</span>"); return '<a href="'+path+'" target="'+tar+'">' + s + ' ' +icon+ '</a>' } //PAGE CMS_Path.PAGE = {} CMS_Path.PAGE.URL = URL_U.treatURL(CMS_Path.SITE.URL + absDef); CMS_Path.PAGE.REL = DEFAULT_DIR_PATH CMS_Path.PAGE.ABS = absDef; CMS_Path.PAGE.ABS2 = (function(_s){ if(_s == "/")return _s; if(_s.charAt(0) == "/") { return _s.substr(1,_s.length); }else{ return _s; } })(absDef); CMS_Path.PAGE.getAbsDirPath = function(_dir){ _dir = URL_U.treatDirName(_dir) var dir = "" if(_dir !== "") { dir = _dir; } else{ dir = CMS_Path.PAGE.ABS; } return dir; } CMS_Path.PAGE.getRelDirPath = function(_dir){ _dir = URL_U.treatDirName(_dir) var s = "" if(_dir == ""){ s = CMS_Path.PAGE.REL; } else{ s = (CMS_Path.SITE.REL + _dir); s = s.split("//").join("/"); } return s } CMS_Path.PAGE.getURL = function(_id,_dir){ _dir = URL_U.treatDirName(_dir) var u = CMS_Path.SITE.URL + CMS_Path.PAGE.getAbsPath(_id,_dir); return URL_U.treatURL(u); } CMS_Path.PAGE.getAbsPath_deco = function(_id,_dir,_type){ var s = CMS_Path.PAGE.getAbsPath(_id,_dir,_type); var t = '<span class="_icon_dir_mini"></span><a href="{URL}" target="{TAR}">{T}</a>' var u = CMS_Path.PAGE.getRelPath(_id,_dir); t = t.split("{URL}").join(u); t = t.split("{TAR}").join(_getTargetName(u)); t = t.split("{T}").join(URL_U.getBaseDir(s) + '<b>' + URL_U.getFileName(s) + '</b> ' +Dic.I.External) return t; } CMS_Path.PAGE.getAbsPath = function(_id,_dir){ _dir = URL_U.treatDirName(_dir) if(!_id ) return ""; var dir = "" if(_dir !== "") { dir = _dir; } else{ dir = CMS_Path.PAGE.ABS; } var s = "" s = dir + _id + ".html"; s = s.split("//").join("/"); return s; } CMS_Path.PAGE.getAbsPath_reverse = function(_s){ var a = _s.split("/") var dirs = [] for (var i = 0; i < a.length-1 ; i++) { dirs.push(a[i]) } var fileName = URL_U.getFileName(_s) var id = fileName.split(".")[0] var dir = URL_U.treatDirName(dirs.join("/")); var type = Dic.PageType.PAGE; if(dir.indexOf(CMS_Path.PAGE.ABS) == "0") { if(dir == CMS_Path.PAGE.ABS) { dir = "" }else{ if(CMS_Path.PAGE.ABS !="/"){ dir = dir.split(CMS_Path.PAGE.ABS).join("") dir = dir.split("/").join(""); } } } //root if(a.length == 2) dir = "/"; // if(CMS_Path.PAGE.ABS == "/") { if(dir == "/") dir = ""; } return { id: id, dir: dir, type: type }; } CMS_Path.PAGE.getRelPath = function(_id,_dir){ _dir = URL_U.treatDirName(_dir) var s = "" if(_dir == ""){ s = CMS_Path.PAGE.REL + _id + ".html"; } else{ s = CMS_Path.SITE.REL + _dir + _id + ".html"; s = s.split(".//").join("./"); } return s; } //ASSET CMS_Path.ASSET = {} CMS_Path.ASSET.URL = URL_U.treatURL(CMS_Path.SITE.URL + absSett); CMS_Path.ASSET.REL = ASSET_DIR_PATH CMS_Path.ASSET.ABS = absSett; CMS_Path.ASSET.ABS2 = (function(_s){ if(_s == "/")return _s; if(_s.charAt(0) == "/") { return _s.substr(1,_s.length) }else{ return _s; } })(absSett); CMS_Path.ASSET.getAbsDirPath = function(_dir){ _dir = URL_U.treatDirName(_dir) var dir = "" if(_dir !== "") { dir = _dir; } else{ dir = CMS_Path.ASSET.ABS; } return dir; } CMS_Path.ASSET.getRelDirPath = function(_dir){ _dir = URL_U.treatDirName(_dir) var s = "" if(_dir == ""){ s = CMS_Path.ASSET.REL; } else{ s = (CMS_Path.SITE.REL + _dir); s = s.split("//").join("/"); } return s } CMS_Path.ASSET.getURL = function(_id,_dir){ _dir = URL_U.treatDirName(_dir) var u = CMS_Path.SITE.URL + CMS_Path.ASSET.getAbsPath(_id,_dir); return URL_U.treatURL(u); } CMS_Path.ASSET.getAbsPath_deco = function(_id,_dir,_type){ var s = CMS_Path.ASSET.getAbsPath(_id,_dir,_type); var t = '<span class="_icon_dir_mini"></span><a href="{URL}" target="{TAR}">{T} </a>' var u = CMS_Path.ASSET.getRelPath(_id,_dir,_type); t = t.split("{URL}").join(u); t = t.split("{TAR}").join(_getTargetName(u)); t = t.split("{T}").join(URL_U.getBaseDir(s) + '<b>' + URL_U.getFileName(s) + '</b> '+Dic.I.External); return t } CMS_Path.ASSET.getAbsPath_deco_file = function(_id,_dir){ var s = ( _dir + _id).split(CMS_Path.SITE.REL).join("/"); var t = '<span class="_icon_dir_mini"></span><a href="{URL}" target="{TAR}">{T} </a>' var u = _dir + _id; t = t.split("{URL}").join(u); t = t.split("{TAR}").join(_getTargetName(u)); t = t.split("{T}").join(URL_U.getBaseDir(s) + '<b>' + URL_U.getFileName(s) + '</b> '+Dic.I.External); return t } CMS_Path.ASSET.getAbsPath = function(_id,_dir,_type){ if(_type == undefined) _type = Dic.PageType.PAGE; _dir = URL_U.treatDirName(_dir) if(!_id ) return ""; var dir = "" if(_dir !== "") { dir = _dir; } else{ dir = CMS_Path.ASSET.ABS; } var s = "" if(_type == Dic.PageType.PAGE){ s = dir + _id + ".html"; } if(_type.indexOf("_cms_") == 0){ s = CMS_Path.ASSET.ABS + dir + _id + ".json" } if(_type == Dic.PageType.FILE){ s= CMS_Path.ASSET.ABS + dir + _id; } s = s.split("//").join("/"); return s; } CMS_Path.ASSET.getRelPath = function(_id,_dir,_type){ if(_type == undefined) _type = Dic.PageType.PAGE; _dir = URL_U.treatDirName(_dir) var s = ""; if(_type == "file"){ s = CMS_Path.ASSET.REL + _dir + _id; } else { if(_dir == ""){ s = CMS_Path.ASSET.REL + _id + ".html"; } else{ s = CMS_Path.SITE.REL + _dir + _id + ".html"; } } s = s.split("//").join("/"); if(_type.indexOf("_cms_") == 0){ s = CMS_Path.ASSET.REL + _dir + "/" + _id + ".json"; } return s; } //ASSETとPAGE分岐 CMS_Path.ASSET_PAGE = {} CMS_Path.ASSET_PAGE.getAbsPath = function (_id,_dir,_type){ if(_type == Dic.PageType.PAGE){ return CMS_Path.PAGE.getAbsPath(_id,_dir); } else{ return CMS_Path.ASSET.getAbsPath(_id,_dir,_type); } } /* ---------- ---------- ---------- */ CMS_Path.JSON = {} CMS_Path.JSON.URL = CMS_Path.ASSET.URL + Dic.DirName.JSON +"/"; CMS_Path.JSON.REL = CMS_Path.ASSET.REL + Dic.DirName.JSON +"/"; CMS_Path.JSON.ABS = CMS_Path.ASSET.ABS + Dic.DirName.JSON +"/"; CMS_Path.JSON.getRelDirPath = function(_type,_dir){ _dir = URL_U.treatDirName(_dir) var s = "" if(_type == Dic.PageType.PAGE) s = CMS_Path.JSON.REL; var seti = false if(_type == Dic.PageType.PRESET) seti = true; if(_type == Dic.PageType.CMS_MYTAG) seti = true; if(_type == Dic.PageType.SYSTEM) seti = true; if(seti){ if(_dir != ""){ if(_dir.indexOf("/") == -1) _dir += "/" ; s = CMS_Path.ASSET.REL + _dir; s = s.split("//").join("/"); } } return s } CMS_Path.JSON.getURL = function(_id,_dir){ _dir = URL_U.treatDirName(_dir) var u = CMS_Path.SITE.URL + CMS_Path.JSON.getAbsPath(_id,_dir) return URL_U.treatURL(u); } CMS_Path.JSON.getAbsPath = function(_id,_dir){ _dir = URL_U.treatDirName(_dir) if(!_id) return ""; return CMS_Path.JSON.ABS + CMS_Path.JSON.getFileName(Dic.PageType.PAGE,_id,_dir); } CMS_Path.JSON.getRelPath = function(_id,_dir){ _dir = URL_U.treatDirName(_dir) var ff = CMS_Path.JSON.getFileName(Dic.PageType.PAGE,_id,_dir); return CMS_Path.JSON.REL + ff; } CMS_Path.JSON.getFileName = function(_type,_id,_dir){ _dir = URL_U.treatDirName(_dir) var r = CMS_Path.JSON.getFileName_core(_type,_id,_dir) return r } CMS_Path.JSON.getFileName_core = function(_type,_id,_dir){ _dir = URL_U.treatDirName(_dir) var ex = ".json" if(_type == Dic.PageType.PRESET) return _id + ex if(_type == Dic.PageType.CMS_MYTAG) return _id + ex if(_type == Dic.PageType.SYSTEM) return _id + ex //special if(_dir == "") return "_html_." + _id + ex if(_dir == "/")return "" + _id + ex //先頭の/を削除 if(_dir.substr(0,1) == "/") { _dir = _dir.substr(1,_dir.length-1) } //最後に/を追加 if(_dir.substr(_dir.length-1,1) != "/") { _dir += "/" } var s = ""; s += _dir.split("/").join("."); s += _id; return s + ex; } /* ---------- ---------- ---------- */ //JSON_REV 20160429 revision用 CMS_Path.JSON_REV = {} CMS_Path.JSON_REV.URL = CMS_Path.ASSET.URL + Dic.DirName.JSON_REV +"/"; CMS_Path.JSON_REV.REL = CMS_Path.ASSET.REL + Dic.DirName.JSON_REV +"/"; CMS_Path.JSON_REV.ABS = CMS_Path.ASSET.ABS + Dic.DirName.JSON_REV +"/"; CMS_Path.JSON_REV.getRelDirPath = function(_type,_dir,_date){ var s = CMS_Path.JSON.getRelDirPath(_type,_dir); s = s.split("/"+Dic.DirName.JSON).join("/"+Dic.DirName.JSON_REV); return s; } CMS_Path.JSON_REV.getRelPath = function(_id,_dir,_date){ _dir = URL_U.treatDirName(_dir) var ff = CMS_Path.JSON_REV.getFileName(Dic.PageType.PAGE,_id,_dir,_date); return CMS_Path.JSON_REV.REL + ff; } CMS_Path.JSON_REV.getFileName = function(_type,_id,_dir,_date){ var s = CMS_Path.JSON.getFileName(_type,_id,_dir); s = s.split(".json").join("."+_date+".json"); return s; } //PHP CMS_Path.PHP_LOGIN = "login.php"; CMS_Path.PHP_FILEPATH = "storage.php"; CMS_Path.PHP_DIRECTORY = "directory.php"; CMS_Path.PHP_EMBED = "embed.php"; CMS_Path.PHP_UPLOAD = "upload.php"; CMS_Path.PHP_BACKUP = "backup.php"; //その他 CMS_Path.PREVIEW_HTML = "_cms_preview.html"; } /* ---------- ---------- ---------- */ function _getTargetName(_u){ var t = _u; t = t.split("/").join(""); t = t.split(".").join(""); if(t == "") t = "_blank"; return t; } /* ---------- ---------- ---------- */ //サイトトップのフルパス function _getBaseDir(url, _siteroot) { url = url.split("#")[0]; var dir = url.substring(0, url.lastIndexOf("/")); var dd = _siteroot.match(/..\//g) if (dd == null) return dir + "/"; var deep = dd.length; var ss = dir.split("/"); var a = [] for (var i = 0; i < ss.length - deep; i++) { a.push(ss[i]) } return a.join("/") + "/"; } /* ---------- ---------- ---------- */ function _getRelTop(_path){ _path = _path.split("../").join("") _path = _path.split("./").join("") var a = _path.split("/"); var s = "" for (var i = 0; i < a.length ; i++) { if(a[i] != "") s += "../"; } if(s == "") return "./"; return s; } function getAbs(_path,_root){ if(_path.indexOf(_root) == 0){ return _path.substr(_root.length-1 ,_path.length) } return ""; } function treatRel(_path){ _path = _path.split("../").join(""); _path = _path.split("./").join(""); return _path; } function imagePathTreat(_s){ return _s.split("__IMAGE_DIR_SAMPLE__").join(CMS_Path.IMAGE_DIR_SAMPLE) } return { init: init, _getBaseDir: _getBaseDir, _getRelTop: _getRelTop, getAbs: getAbs, treatRel: treatRel, imagePathTreat:imagePathTreat, } })();<file_sep>/src/js/cms_view_editable/EditableView.js var EditableView = {} EditableView.currentGrid = null; <file_sep>/src/js/cms_view_modals/PresetStageView.4.js var PresetStage_PageClass = (function() { /* ---------- ---------- ---------- */ var c = function(_view,_pageModel) { this.init(_view,_pageModel); } var p = c.prototype; /* ---------- ---------- ---------- */ p.init = function(_view,_pageModel) { this.parentView = _view; this.pageModel = _pageModel; this.id = this.pageModel.id; this.dir = this.pageModel.dir; this.type = this.pageModel.type; var this_ = this; this.storageClass = new Storage.Online(this.type, this.id, this.dir, {}); this.storageClass.load(function() { this_.loadData(); }); } p.loadData = function() { this.pageView = new EditableView.PageView (this.pageModel,this.storageClass,this.parentView); this.pageView.stageIn(); } p.saveData =function () { if(this.pageView) this.pageView.saveData() } /* ---------- ---------- ---------- */ p.stageInit = function() {} p.stageIn = function() { if(this.pageView){ this.pageView.stageIn(); } } p.stageOut = function() { if(this.pageView){ this.pageView.stageOut(); } } p.remove = function() { if(this.pageView){ this.isShow = false; this.pageView.remove(); } } return c; })(); <file_sep>/src/js/cms_model/PageElement.layout.js PageElement.layout = {} <file_sep>/src/js/cms_main/CMS_InputView.js var CMS_InputView = (function(){ var view; var v = {}; function init(){ view = $('#CMS_InputView'); stageInit(); } /* ---------- ---------- ---------- */ function createlayout(){ v = ModalViewCreater.createBaseView(Anchor_InputView,view); var tag = "" v.header.html(tag); tag = "" v.body.html(tag); tag = "" tag += '<div class="_cms_btn _btn_close">閉じる</div> '; tag += '<div class="_cms_btn _cms_btn_active _btn_do"><i class="fa fa-check"></i> OK</div> '; v.footer.html(tag); setBtn(); } function setBtn(){ view.find('._bg ,._btn_close').click(function(){ stageOut() }); view.find('._btn_do').click(function(){ done(); stageOut(); }); } /* ---------- ---------- ---------- */ var defParam = {} function update(_param){ defParam = JSON.parse(JSON.stringify(_param)); var tag = '<div class="_title">'+_param.title+'</div>' v.header.html(tag); var tag = ''; tag += '<div class="_read">'+_param.read+'</div>' //single if(_param.type == "single"){ tag +='<input>'; } //single以外は、未実装 tag += '<div class="_notes">'+_param.notes+'</div>' v.body.html(tag); view.find("input").val(_param.val).select(); } /* ---------- ---------- ---------- */ function done(){ var val = view.find("input").val(); callback(val); } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; var callback; function stageInit(){ view.hide(); } function stageIn(_param,_callback){ if(! isOpen){ isOpen = true; showModalView(this); view.show(); if(isFirst){ createlayout(); } isFirst = false; callback = _callback update(_param); } } function stageOut(){ if(isOpen){ isOpen = false; hideModalView(); view.hide(); } } return { init:init, stageIn:stageIn, stageOut:stageOut } })(); <file_sep>/js_cms/_cms/setting/setting.php <?php /* JS CMS ログイン情報設定 ログイン情報は、必ず変更してください。 設定を変更した場合は、保存したあと、ブラウザをリロードしてください。 設定できるアカウントは1つだけです。 */ if (!defined('CMS')) exit; //■ユーザー認証を利用するか define( 'USE_LOGIN', true);//利用する //define( 'USE_LOGIN', false);//利用しない //■ユーザー名を設定してください define( 'USERNAME', 'guest'); //■パスワードを設定してください define( 'PASSWORD', '<PASSWORD>'); //■デモモード (デモでは、保存処理を禁止します) //define('IS_DEMO', true);//デモモード define('IS_DEMO', false);//通常モード <file_sep>/src/js/cms_model/PageElement.tag.markdown.js PageElement.tag.markdown = (function(){ var _ = new PageModel.Tag_(); /* ---------- ---------- ---------- */ _.pageInfo = new PageModel.Object_Info({ id : "tag.markdown", name : "フリーテキスト", name2 : "<Markdown>", inputs : ["CLASS","CSS"], // cssDef : {file:"block",key:"[フリーテキストブロック]"} cssDef : {selector:".cms-markdown"} }); /* ---------- ---------- ---------- */ _.getInitData = function(){ var o = {}; o.type = _.pageInfo.id; var s = this.getInitText(); o.data = s o.attr = { css:"default " } o.attr.class = o.attr.css; return o; } /* ---------- ---------- ---------- */ _.getInitText = function(){ var s = ""; s += '#タイトル\n'; s += '\n'; s += '##大見出し\n'; s += '文書が入ります。文書が入ります。文書が入ります。文書が入ります。文書が入ります。文書が入ります。文書が入ります。文書が入ります。文書が入ります。文書が入ります。文書が入ります。\n'; s += '\n'; s += '###中見出し\n'; s += '文書が入ります。文書が入ります。文書が入ります。文書が入ります。\n'; s += '\n'; s += '####小見出し\n'; s += '文書が入ります。文書が入ります。文書が入ります。\n'; s += '\n'; s += ' * 項目1\n'; s += ' * 項目2\n'; s += ' * 項目3\n'; s += ''; return s } /* ---------- ---------- ---------- */ _.getPreview = function(_o){ var data = _o.data; var attr = _o.attrs; attr = attr.split('class="').join('class="cms-markdown ') var tag = ""; if(data == ""){ tag += '<span class="_no-input-data">マークダウンデータを入力...</span>' } else{ tag += '<div ' + attr + ' >' + marked(data) + '</div>'; } return tag; } /* ---------- ---------- ---------- */ _.getHTML = function(_o,_tab){ var data = _o.data; var attr = _o.attrs; attr = attr.split('class="').join('class="cms-markdown ') var tab = (_tab != undefined) ? _tab:""; var s = marked(data); s = s.split('id="-"').join(""); var tag = "" tag += '<div ' + attr + ' >' + s + '</div>'; return tag; } /* ---------- ---------- ---------- */ return _; })();<file_sep>/src/js/cms_view_modals/Anchor_TargetListView.js var Anchor_TargetListView = (function(){ var view; var v = {}; function init(){ view = $('#Anchor_TargetListView'); stageInit(); } var targeList = [ ["blank" ,"_blank"], ["inner" ,"innerWindow({w:600,h:400})"], ["none" ,""], ["outer" ,"outerWindow({w:600,h:400})"] ]; function createlayout(){ v = ModalViewCreater.createBaseView(Anchor_TargetListView,view); var tag = "" tag += '<div class="_guide">'+CMS_GuideU.getGuideTag("window/btn_target","_BASE_")+'</div>' tag += '<div class="_title">ターゲット選択</div>' v.header.html(tag); list = targeList; var tag = "" for (var i = 0; i < list.length ; i++) { var cb = "" if(list[i][1] != ""){ cb = "_cms_btn_alpha" } tag +='<div class="'+cb+' ss_target ss_target_'+list[i][0]+'" data="'+list[i][1]+'"></div>' } v.body.html(tag); tag = "" tag += '<div class="_cms_btn _btn_close">閉じる</div> '; v.footer.html(tag) v._btn_close = view.find('._btn_close'); setBtn(); } /* ---------- ---------- ---------- */ function setBtn(){ view.find('._bg ,._btn_close').click(function(){ stageOut() }); view.find("._cms_btn_alpha").click(function(){ var type = $(this).attr("data"); clickText(type); }); } function clickText(_s){ if(callback){ UpdateDelay.delay(function(){ callback(_s); }); } else { CMS_CopyView.stageIn(_s,function(){}) } stageOut() } /* ---------- ---------- ---------- */ //dir function update(){ // } /* ---------- ---------- ---------- */ function compliteEdit(){ stageOut() } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; var callback = true; var currentPath = ""; function stageInit(){ view.hide(); //load_dir(); } function stageIn(_callback){ if(! isOpen){ isOpen = true; showModalView(this); callback = _callback; if(isFirst){ createlayout(); } update(); isFirst = false; view.show(); } } function stageOut(){ if(isOpen){ isOpen = false; hideModalView(); view.hide(); } } function resize(){ if(isOpen){ } } return { init:init, stageIn:stageIn, stageOut:stageOut, resize:resize,compliteEdit:compliteEdit} })();//modal<file_sep>/src/js/cms_view_imagemap/ImageMap.02.js var ImageMap = {} ImageMap.MainStage = (function(){ var view; var v = {}; /* ---------- ---------- ---------- */ //初期化 function init(_view){ view = _view; createlayout(); updateWH(); } /* ---------- ---------- ---------- */ //レイアウト作成・イベントアサイン function createlayout(){ var tag = ""; tag += '<div class="_canvas_tools">'; tag += ' <input type="checkbox" class="_in_bg_dark" id="_imagemap_bg_dark" /><label for="_imagemap_bg_dark">プレビュー背景</label>'; tag += '  サイズ:<input type="number" step="10" class="_w50 _in_size_w " />'; tag += ' ☓<input type="number" step="10" class="_w50 _in_size_h" />px'; tag += '  背景色:<input type="text" class="_w60 _in_bg_color _colorPicker" />'; tag += '  文字色:<input type="text" class="_w60 _in_tx_color _colorPicker" />'; tag += '  吸着:<input type="text" class="_w30 _in_grid" />%'; //tag += '  ズーム:<input type="text" class="_w30 _in_zoom" />%'; tag += '  ズーム:'; tag += ' <select class="_in_zoom">'; tag += ' <option value="6.0">600%</option>'; tag += ' <option value="4.0">400%</option>'; tag += ' <option value="2.0">200%</option>'; tag += ' <option value="1.5">150%</option>'; tag += ' <option value="1.0">100%</option>'; tag += ' <option value="0.75">75%</option>'; tag += ' <option value="0.5" >50%</option>'; tag += ' <option value="0.25">25%</option>'; tag += ' </select>'; tag += ' <span class="_move _move_up"><i class="fa fa-arrow-up "></i></span>'; tag += ' <span class="_move _move_down"><i class="fa fa-arrow-down "></i></span>'; tag += ' <span class="_move _move_left"><i class="fa fa-arrow-left "></i></span>'; tag += ' <span class="_move _move_right"><i class="fa fa-arrow-right "></i></span>'; tag += ' <div class="_right_area">'; tag += '  <div class="_btn _btn_reset"><i class="fa fa-trash "></i> リセット</div>'; tag += ' </div>'; tag += ' <div class="_top_area">'; tag += '  <div class="_btn _btn_json">{...} JSON編集</div>'; tag += ' </div>'; tag += '</div>'; tag += '<div class="_add_btns">'; tag += ' <div class="ss_add_image _read"></div>'; tag += ' <div class="_btn_add _cms_btn_alpha ss_add_image _rect" data-type="item.rect" data-extra=""></div>'; tag += ' <div class="_btn_add _cms_btn_alpha ss_add_image _line" data-type="item.line" data-extra=""></div>'; tag += ' <div class="_btn_add _cms_btn_alpha ss_add_image _image" data-type="item.image" data-extra=""></div>'; tag += ' <div class="_btn_add _cms_btn_alpha ss_add_image _svg" data-type="item.svg" data-extra=""></div>'; tag += ' <div class="_btn_add _cms_btn_alpha ss_add_image _text" data-type="item.text" data-extra="multi"></div>'; tag += ' <div class="_btn_add _cms_btn_alpha ss_add_image _text2" data-type="item.text" data-extra=""></div>'; tag += ' <div class="_btn_add _cms_btn_alpha ss_add_image _html" data-type="item.html" data-extra=""></div>'; tag += ' <div class="_btn_add _cms_btn_alpha ss_add_image _link" data-type="item.link" data-extra=""></div>'; tag += '</div>'; tag += '<div class="_layoutView">'; tag += ' <div class="_imageStageWapper">'; tag += ' <div class="_imageStageInner">'; tag += ' <div class="_cms-design-stage _cms_bg_trans"></div>'; tag += ' <div class="_cms-design-mask"></div>'; tag += ' <div class="_cms-design-mask"></div>'; tag += ' <div class="_cms-design-mask"></div>'; tag += ' <div class="_cms-design-mask"></div>'; tag += ' <div class="_cms-design-mask"></div>'; tag += ' <div class="_cms-design-mask"></div>'; tag += ' </div>'; tag += ' </div>'; tag += ' <div class="_layersView"></div>'; // tag += ' <div class="_zoomVal">0</div>'; tag += '</div>'; view.html(tag); ImageMap.InspectView.init(); ImageMap.LayersView.init(view.find("._layersView")); setBtn(); } /* ---------- ---------- ---------- */ //個別処理 var in_ = {} function setBtn(){ v.canvas_tools = view.find("._canvas_tools"); // v.zoomVal = view.find("._zoomVal"); v.all = v.canvas_tools.find("input"); v.all.keyup(function(){ updateState(600)}) v.all.change(function(){ updateState()})//checkbox in_.size_w = v.canvas_tools.find("._in_size_w"); in_.size_h = v.canvas_tools.find("._in_size_h"); in_.bg_color = v.canvas_tools.find("._in_bg_color"); in_.tx_color = v.canvas_tools.find("._in_tx_color"); in_.bg_dark = v.canvas_tools.find("._in_bg_dark"); in_.grid = v.canvas_tools.find("._in_grid"); initZoom() v.designStage = view.find("._cms-design-stage"); v.designMask = view.find("._cms-design-mask"); v.layers = view.find("._layersView"); v.btn_reset = view.find("._btn_reset"); v.btn_json = view.find("._btn_json"); v.btn_add = view.find("._btn_add"); v.btn_reset .click(function(){ resetAll(); }) v.btn_json .click(function(){ editJson(); }) v.btn_add .click(function(){ addItem($(this).data("type"), undefined, $(this).data("extra")); updateViewList(); }) view.on("dblclick","._design-item-image",function(){ ImageMap.InspectView.dClick("image"); }) view.on("dblclick","._design-item-text",function(){ ImageMap.InspectView.dClick("text"); }) view.on("dblclick","._design-item-svg",function(){ ImageMap.InspectView.dClick("svg"); }) view.on("dblclick","._design-item-html",function(){ ImageMap.InspectView.dClick("html"); }) } /* ---------- ---------- ---------- */ //カンバスステート更新 var tID_state; function updateState(_delay){ if(tID_state) clearTimeout(tID_state); tID_state = setTimeout(function(){ updateState_delay() },(_delay) ? _delay :200 ); } function limit(_s,_low,_hight){ if(_s < _low)_s = _low; if(_s > _hight)_s = _hight; return _s; } function updateState_delay(){ var b = false; var cv = canvasData.canvas; if(cv.width != Number(in_.size_w.val()) ) { cv.width = limit(Number(in_.size_w.val()) ,10,2000) b = true; } if(cv.height != Number(in_.size_h.val()) ) { cv.height = limit(Number(in_.size_h.val()) ,10,2000) b = true; } if(cv.background != in_.bg_color.val() ) { cv.background = in_.bg_color.val() b = true; } if(cv.color != in_.tx_color.val() ) { cv.color = in_.tx_color.val() b = true; } if(cv.dark != in_.bg_dark.prop("checked") ) { cv.dark = in_.bg_dark.prop("checked") b = true; } if(cv.grid != Number(in_.grid.val()) ) { cv.grid = limit(Number(in_.grid.val()) ,0,100); ImageMap.State.grid = cv.grid; } if(b){ update(false); } } /* ---------- ---------- ---------- */ //データセット var canvasData; function setData(_data){ canvasData = JSON.parse(JSON.stringify(_data)); resetZoom(); update(true); } function update(_initDate){ if(! _initDate){ canvasData = getData(); } resetItem(); ImageMap.InspectView.reset(); ImageMap.LayersView.reset(); if(canvasData == undefined) { canvasData.list = []; } if(canvasData.list == undefined) { canvasData.list = []; } if(canvasData.canvas == undefined) { canvasData.canvas = { width:"300",height:"200", background:"", grid:"" } } //サイズ var S = ImageMap.State; S.imageW = Number(canvasData.canvas.width); S.imageH = Number(canvasData.canvas.height); S.grid = Number(canvasData.canvas.grid); var ratio = ImageMapU.getRatio(S.imageW+":"+S.imageH); in_.size_w.val(S.imageW); in_.size_h.val(S.imageH); //背景色 in_.bg_color.val(canvasData.canvas.background); in_.tx_color.val(canvasData.canvas.color); if(canvasData.canvas.dark) { in_.bg_dark.prop("checked",true) } //グリッド in_.grid.val(S.grid); /* ---------- ---------- ---------- */ var cs1 = ""; var cv = canvasData.canvas; if(cv.dark){ cs1 = "background:rgba(0,0,0,0.75)!important;"; } if(cv.background){ cs1 = "background:"+cv.background+"!important;"; } var cs2 = ""; if(cv.color){ cs1 += "color:"+cv.color+";"; cs2 += "fill:"+cv.color+";"; } var tag = ""; tag += '<style>'; tag += '._cms-design-stage { position: absolute; width:100%; '+cs1+'}'; tag += '._cms-design-stage svg{'+cs2+'}'; tag += '._cms-design-stage svg{1: #fff;}'; tag += '._cms-design-stage:before { content:""; display: block; padding-top:'+ ratio +'%;}'; tag += '._cms-design-mask {position: absolute; width:100%; background: rgba(51,51,51,0.5);}'; tag += '</style>'; v.designStage.empty(); v.designStage.html(tag); v.inner = v.designStage; //カンバス位置サイズ計算 // var _wh = ImageMapU.resize( { w: S.imageW, h: S.imageH }, { w: S.stageW, h: S.stageH }, false ); S.canvasW = S.imageW * getZoom(); S.canvasH = S.imageH * getZoom(); S.left = (S.stageW - S.canvasW) / 2; S.top = (S.stageH - S.canvasH) / 2; //サイズ・位置・背景指定 v.designStage.width(S.canvasW); v.designStage.height(S.canvasH); v.designStage.css("left",S.left +"px"); v.designStage.css("top",S.top +"px"); //こまごま _updateGrid(); // _updateZoomView(); //組み立てなおし var _list = canvasData.list; for (var i = 0; i < _list.length ; i++) { addItem(_list[i]); } updateViewList(); } function _updateGrid(){ var S = ImageMap.State; //枠作成 var BD = 4; v.designMask.eq(0).width(S.canvasW+(BD*2)); v.designMask.eq(0).height(BD); v.designMask.eq(0).css("left",S.left-BD +"px"); v.designMask.eq(0).css("top",S.top-BD +"px"); v.designMask.eq(1).width(BD); v.designMask.eq(1).height(S.canvasH); v.designMask.eq(1).css("left",S.left+S.canvasW +"px"); v.designMask.eq(1).css("top",S.top +"px"); v.designMask.eq(2).width(S.canvasW+(BD*2)); v.designMask.eq(2).height(BD); v.designMask.eq(2).css("left",S.left-BD +"px"); v.designMask.eq(2).css("top",S.top + S.canvasH +"px"); v.designMask.eq(3).width(BD); v.designMask.eq(3).height(S.canvasH); v.designMask.eq(3).css("left",S.left -BD +"px"); v.designMask.eq(3).css("top",S.top +"px"); v.designMask.eq(4).width(S.canvasW+(BD*2)); v.designMask.eq(4).height(1); v.designMask.eq(4).css("left",S.left +"px"); v.designMask.eq(4).css("top",S.top + (S.canvasH/2) +"px"); v.designMask.eq(4).css("opacity",0.2); v.designMask.eq(5).width(1); v.designMask.eq(5).height(S.canvasH); v.designMask.eq(5).css("left",S.left + (S.canvasW/2) +"px"); v.designMask.eq(5).css("top",S.top +"px"); v.designMask.eq(5).css("opacity",0.2); } /* function _updateZoomView(){ var S = ImageMap.State; var sw = Math.round((S.canvasW/S.imageW)*100); var sh = Math.round((S.canvasH/S.imageH)*100); v.zoomVal.html( (sw > sh) ? sh + "%" : sw + "%" ); } */ /* ---------- ---------- ---------- */ //データ出力 function getData(_updated){ var out_ = JSON.parse(JSON.stringify(canvasData)); out_.list = []; for (var i = 0; i < items.length ; i++) { var data = items[i].getData(); data.rect = ImageMapU.convertPixel_2_Percent(data.rect); if(_updated){ if(data.type == "item.text"){ if(data.data.bmp){ data.data.bmpData = ImageMapBMPText.getImage(data); } else{ data.data.bmpData = ""; } } data.date = new Date().getTime(); } out_.list.push(data); } return out_; } /* ---------- ---------- ---------- */ function resetAll(){ canvasData.list = []; update(true); } /* ---------- ---------- ---------- */ function setJson(_s){ var data try{ data = JSON.parse(_s); } catch( e ){ alert("データ形式が正しくありません。"); return; } if(data){ setData(data); } } function editJson(){ Editer_JSONView.stageIn( JSON.stringify(canvasData, null, " "), function(_s){ setJson(_s) } ); } /* ---------- ---------- ---------- */ var items; //追加 function resetItem(){ if(items){ for (var i = 0; i < items.length ; i++) { items[i].remove(); } } items = []; } function addItem(_data,_pos,_extra){ var data; if(typeof _data == "string"){ data = ImageMapCode.getInitData(_data,_extra); } else{ data = JSON.parse(JSON.stringify(_data)); } data.rect = ImageMapU.convertPercent_2_Pixel(data.rect); var rectView = new ImageMap.RectViewClass(data.type); rectView.setData(data); if(_pos!= undefined){ items.splice(_pos,0,rectView); } else{ items.push(rectView); } return rectView; } //削除 function removeItem(){ if(!currentItem) return; var a = []; for (var i = 0; i < items.length ; i++) { if(items[i] == currentItem) { items[i].remove(); } else{ a.push(items[i]) } } items = a; currentItem = null; // selectLast(); updateViewList(); } function selectLast(){ if(items.length > 0){ items[items.length -1].select(); } } //JSON編集 function editItem(){ if(!currentItem) return; currentItem.editJson(); } /* ---------- ---------- ---------- */ //複製 function dupItem_right(){ if(!currentItem)return; var dup = currentItem.getData(); dup.rect.left += dup.rect.width; dup.rect = ImageMapU.convertPixel_2_Percent(dup.rect); var item = addItem(dup,currentItem.no+1); item.select(); updateViewList(); } function dupItem_bottom(){ if(!currentItem)return; var dup = currentItem.getData(); dup.rect.top += dup.rect.height; dup.rect = ImageMapU.convertPixel_2_Percent(dup.rect); var item = addItem(dup,currentItem.no+1); item.select(); updateViewList(); } /* ---------- ---------- ---------- */ //レイヤー順移動 function swapItem(_items,_from,_to){ var from_ = items[_from]; var to_ = items[_to]; if(from_ ==undefined)return; if(to_ ==undefined)return; _items[_to] = from_; _items[_from] = to_; return _items; } //全面へ function moveFront(){ var n = currentItem.no; swapItem(items,n,n+1); updateViewList(); } function moveBack(){ var n = currentItem.no; swapItem(items,n,n-1); updateViewList(); } function moveFront2(){ var n = currentItem.no; swapItem(items,n,items.length-1); updateViewList(); } function moveBack2(){ var n = currentItem.no; swapItem(items,n,0); updateViewList(); } //ビューの並びを更新 function updateViewList(){ var tag = "" for (var i = 0; i < items.length ; i++) { items[i].setNo(i); items[i].updateImage(); v.inner.append(items[i].getView()); } ImageMap.LayersView.update(items); } function assingText2Image(_src){ var src = CMS_PathFunc.treatRel(_src); var b = false; for (var i = 0; i < items.length ; i++) { var data = items[i].getData(); if(src == data.data.src) b = true; } if(! b){ addItem("item.image",undefined,{ src:_src }); } updateViewList(); } /* ---------- ---------- ---------- */ //選択セット var currentItem function selectItem(_item){ currentItem = _item; ImageMap.InspectView.selectedItem(_item); ImageMap.LayersView.selectedItem(_item); } function hideItem(_no,_b){ items[_no].hideItem(_b) } function lockItem(_no,_b){ items[_no].lockItem(_b) } /* ---------- ---------- ---------- */ function initZoom(){ in_.zoom = v.canvas_tools.find("._in_zoom"); in_.zoom.change(function(){updateZoom()}) in_.move_left = v.canvas_tools.find("._move_left"); in_.move_right = v.canvas_tools.find("._move_right"); in_.move_up = v.canvas_tools.find("._move_up"); in_.move_down = v.canvas_tools.find("._move_down"); in_.move_left .click(function(){moveCanvasLeft(100)}) in_.move_right .click(function(){moveCanvasLeft(-100)}) in_.move_up .click(function(){moveCanvasTop(100)}) in_.move_down .click(function(){moveCanvasTop(-100)}) } var _zoom; function resetZoom(){ in_.zoom.val("1.0"); _zoom = 1; } function updateZoom(){ _zoom = limit(Number(in_.zoom.val()) ,0,10); resize(); } function getZoom(){ return _zoom; } function __moveCanvas(_tar,_d,_n){ var nn = _tar.css(_d).split("px").join(""); _tar.css(_d, Number(nn) + _n); } function moveCanvasLeft(_n){ __moveCanvas(v.designStage, "left", _n); __moveCanvas(v.designMask.eq(0), "left", _n); __moveCanvas(v.designMask.eq(1), "left", _n); __moveCanvas(v.designMask.eq(2), "left", _n); __moveCanvas(v.designMask.eq(3), "left", _n); __moveCanvas(v.designMask.eq(4), "left", _n); __moveCanvas(v.designMask.eq(5), "left", _n); } function moveCanvasTop(_n){ __moveCanvas(v.designStage, "top", _n); __moveCanvas(v.designMask.eq(0), "top", _n); __moveCanvas(v.designMask.eq(1), "top", _n); __moveCanvas(v.designMask.eq(2), "top", _n); __moveCanvas(v.designMask.eq(3), "top", _n); __moveCanvas(v.designMask.eq(4), "top", _n); __moveCanvas(v.designMask.eq(5), "top", _n); } /* ---------- ---------- ---------- */ function resize(){ updateWH(); update(false); } var canvasOffset = 40; var marginW = 30*2; var marginH = 220; var layerW = 180; function updateWH(){ var _w = CMS_StatusW - ( marginW + layerW + canvasOffset ); var _h = CMS_StatusH - ( marginH + canvasOffset ); ImageMap.State.stageW = _w; ImageMap.State.stageH = _h; $("#ImageMapView ._imageStageWapper").width( _w + canvasOffset); $("#ImageMapView ._imageStageWapper").height( _h + canvasOffset); $("#ImageMapView ._layoutView").width( _w + canvasOffset + layerW ); $("#ImageMapView ._layoutView").height( _h + canvasOffset ); } /* ---------- ---------- ---------- */ return { init: init, setData:setData, getData:getData, selectItem:selectItem, hideItem:hideItem, lockItem:lockItem, removeItem:removeItem, editItem:editItem, dupItem_right:dupItem_right, dupItem_bottom:dupItem_bottom, moveFront:moveFront, moveBack:moveBack, moveFront2:moveFront2, moveBack2:moveBack2, addItem:addItem, updateViewList:updateViewList, assingText2Image:assingText2Image, resize:resize } })(); <file_sep>/src/js/cms_view_imagemap/ImageMap.05.js ImageMap.LayersView = (function(){ var view; var v = {}; /* ---------- ---------- ---------- */ //初期化 function init(_view){ view = _view; createlayout(); setBtn(); } /* ---------- ---------- ---------- */ //レイアウト作成・イベントアサイン function createlayout(){ } function setBtn(){ } /* ---------- ---------- ---------- */ function reset(){ } /* ---------- ---------- ---------- */ var items var layers function update(_items){ items = _items; layers = []; view.empty(); var leng = items.length for (var i = leng-1; i >= 0 ; i--) { var layer = new ImageMap.LayerClass(); layer.setData(items[i],i); view.append(layer.getView()); layers.push(layer); } } /* ---------- ---------- ---------- */ var currentLayer; var currentItem; function selectedItem(_select){ if(currentLayer) currentLayer.unselect(); var leng = items.length; for (var i = 0; i < leng ; i++) { if(items[i] == _select){ if(layers[(leng-1)-i]){ currentLayer = layers[(leng-1)-i]; currentLayer.select(); currentItem = _select; currentItem.layer = currentLayer; } } } } return { init:init, reset:reset, update:update, selectedItem:selectedItem } })(); /* ---------- ---------- ---------- */ <file_sep>/src/js/cms_view_floats/Float_Preview.5.js var Float_PreviewFrame = (function() { /* ---------- ---------- ---------- */ var c = function(_type,_parent,_pageModel) { this.init(_type,_parent,_pageModel); } var p = c.prototype; /* ---------- ---------- ---------- */ p.init = function(_type,_parent,_pageModel) { this.type = _type; this.parentView = _parent; this.pageModel = _pageModel; this.id = this.pageModel.id this.dir = this.pageModel.dir this.view = $('<div></div>') this.parentView.append(this.view); } p.prevPub p.resetDate = function() { this.prevPub = DateUtil.getRandamCharas(10); } p.update = function() { if (this.type == Dic.ListType.DIR) this.update_dir() if (this.type == Dic.ListType.PAGE) this.update_page() } p.update_dir = function() { var tag = ''; tag += ' <div class="_title">{NAME}</div>' tag += ' <div><span class="_m">グループID : </span><span class="_gID"><i class="fa fa-folder-open"></i>{ID}</span></div>' var tempP = { name :this.pageModel.name, id :this.id, dir :this.dir, prevPub :"" } this.view.html( Float_Preview.DoTemplate( tag , tempP )); } p.update_page = function() { if(this.prevPub == this.pageModel.publicDate ) return; this.prevPub = this.pageModel.publicDate; this.url = CMS_Path.PAGE.getRelPath(this.id,this.dir);//IDとして利用してるので必要 var tag = ''; tag += '<div class="_infoArea">' tag += ' <div class="_title">{NAME}</div>' tag += ' <div class="_filePath_blue">{URL_ABS}</div>' tag += ' <div class=""><span class="_m">所属グループID\'s : </span>{G}</div>' // tag += ' <div class="_frame"><iframe width="1100" height="1000" src ="{URL_R}" ></iframe></div>' tag += ' <div class="_date _dark"><span class="_m"><i class="fa fa-clock-o"></i> 保存日時:</span>{SAVE_DATE}</div>' tag += ' <div class="_date _dark"><span class="_m"><i class="fa fa-clock-o"></i> 公開日時:</span>{PUB_DATE}</div>' tag += '</div>' tag += this._getIFrames(); var tempP = { name :this.pageModel.name, id :this.id, dir :this.dir, prevPub :this.prevPub } this.view.html( Float_Preview.DoTemplate( tag , tempP )); } p._getIFrames = function() { var currentWs = FloatPreviewState.currentWs var s = FloatPreviewState.currentZoom /100; var ww = 0; for (var i = 0; i < currentWs.length ; i++) { ww += currentWs[i] * s; } var tag = ''; tag += ' <div class="_iframeArea" style="width:'+ww+'px">' for (var i = 0; i < currentWs.length ; i++) { var temp = ''; temp += '<div class="_iframeDiv" style="width:{WW}px;" >'; temp += ' <iframe src="{URL_R}" width="{W}" height="100%" style="{S}"></iframe>'; temp += '</div>'; // temp = temp.split("{U}").join(this.loadURL); temp = temp.split("{WW}").join(currentWs[i]*s); temp = temp.split("{W}").join(currentWs[i]); temp = temp.split("{S}").join(this._getZoomCSS(s)); tag += temp; } tag += ' </div>' return tag; } p._getZoomCSS = function(s) { var ts = ''; ts +="-webkit-transform: scale("+s+");" ts +="-moz-transform: scale("+s+");" ts +="-ms-transform: scale("+s+");" ts +="transform: scale("+s+");" ts += "width:"+(100/s)+"%;"; ts += "height:"+(100/s)+"%;"; return ts; } p.reset = function() { this.prevPub = null; this.view.html("") } p.updateWS_State = function() { this.update(); } /**/ p.openFlg = false; p.stageInit=function(){ this.openFlg = false this.view.hide() } p.stageIn=function( ) { if (! this.openFlg) { this.openFlg = true; this.view.show(); this.update(); } } p.stageOut=function( ) { if (this.openFlg) { this.openFlg = false this.view.hide() } } return c; })(); <file_sep>/src/js/cms_main/TreeViewMakerPreset.js //プリセットデータ var TreeViewMakerPreset = (function(){ var data = {} /* ---------- ---------- ---------- */ var o = {} o.targetDir = "--"; o.targetTag = "--"; o.levels = [ { isShow: true, isOpen: true, dir: '<p>{NAME}</p>', page: '<a href="{HREF}" target="{TAR}">{NAME}</a> ' }, { isShow: true, isOpen: true, dir: '<p>{NAME}</p>', page: '<a href="{HREF}" target="{TAR}">{NAME}</a> ' }, { isShow: true, isOpen: true, dir: '<p>{NAME}</p>', page: '<a href="{HREF}" target="{TAR}">{NAME}</a> ' }, { isShow: true, isOpen: true, dir: '<p>{NAME}</p>', page: '<a href="{HREF}" target="{TAR}">{NAME}</a> ' }, { isShow: true, isOpen: true, dir: '<p>{NAME}</p>', page: '<a href="{HREF}" target="{TAR}">{NAME}</a> ' } ]; o.setting = { hasDate: false, isFlat: false, isReverse: false, limitSub: "", indent: "3", onlyCurrent: false, useToggle: false } o.css = { hasSub: true, underconst: true, clearfix: false, current: true, hasSub: true, level: true, no: false, ownCurrent: true, sum: false, type: true, underconst: true } data.simple = o; /* ---------- ---------- ---------- */ var o = {} o.targetDir = "--"; o.targetTag = "--"; o.levels = [ //第1階層 { isShow: true, isOpen: true, dir: '<a href="{HREF}" target="{TAR}" class="{CSS.B}"><span class="t1">{NAME[0]}</span><span class="t2">{NAME[1]}</span></a>', add: '<a href="{HREF}" target="{TAR}" class="{CSS.B}"><span class="t1">{NAME[0]}</span><span class="t2">{NAME[1]}</span></a>' } ] o.setting = { hasDate: false, isFlat: false, isReverse: false, limitSub: "", indent: "3", onlyCurrent: false, useToggle: false } data.gnavi = o; /* ---------- ---------- ---------- */ var o = {} o.targetDir = "--"; o.targetTag = "--"; o.levels = [ //第1階層 { isShow: true, isOpen: true, add: '<a href="{HREF}" target="{TAR}" class="{CSS.B}"><span class="t1">{NAME[0]}</span><span class="t2">{NAME[1]}</span></a>' } ] o.setting = { hasDate: false, isFlat: false, isReverse: false, limitSub: "", indent: "3", onlyCurrent: false, useToggle: false, add : { list: { texts: {}, grid: [ { publicData: "1", text: "メニュー1", anchor: { href: "index.html", target: "" } }, { publicData: "1", text: "メニュー2", anchor: { href: "index.html", target: "" } }, { publicData: "1", text: "メニュー3", anchor: { href: "index.html", target: "" } }, { publicData: "1", text: "メニュー4", anchor: { href: "index.html", target: "" } } ] }, list2: { texts: {}, grid: [] } } } data.gnavi_c = o; /* ---------- ---------- ---------- */ var o = {} o.targetDir = "--"; o.targetTag = "--"; o.levels = [ //第1階層 { isShow: true, isOpen: true, dir : '<p class="title"><span class="t1">{NAME[0]}</span><span class="t2">{NAME[1]}</span></p>', page: '<a href="{HREF}" target="{TAR}" class="{CSS.B}">{I.P}{NAME}{I.B}</a>', html: '{HTML}' }, //第2階層 { isShow: true, isOpen: true, dir : '<a href="{HREF}" target="{TAR}" class="{CSS.B}">{I.D}{NAME}</a>', page: '<a href="{HREF}" target="{TAR}" class="{CSS.B}">{I.P}{NAME}{I.B}</a>', html: '{HTML}' }, //第3階層 { isShow: true, isOpen: false, dir : '<a href="{HREF}" target="{TAR}" class="{CSS.B}">{I.D}{NAME}</a>', page: '<a href="{HREF}" target="{TAR}" class="{CSS.B}">{I.P}{NAME}{I.B}</a>', html: '{HTML}' }, //第4階層 { isShow: true, isOpen: false, dir : '<a href="{HREF}" target="{TAR}" class="{CSS.B}">{I.D}{NAME}</a>', page: '<a href="{HREF}" target="{TAR}" class="{CSS.B}">{I.P}{NAME}{I.B}</a>', html: '{HTML}' } ] o.setting = { hasDate: false, isFlat: false, isReverse: false, limitSub: "", indent: "3", onlyCurrent: true, useToggle: false } data.snavi = o; /* ---------- ---------- ---------- */ var o = {} o.targetDir = "--"; o.targetTag = "--"; o.levels = [ //第1階層 { isShow: true, isOpen: true, dir: '<a href="{HREF}" target="{TAR}">{NAME[0]}</a>' }, //第2階層 { isShow: true, isOpen: true, dir: '<a href="{HREF}" target="{TAR}">{I.D}{NAME}</a>', page: '<a href="{HREF}" target="{TAR}">{I.P}{NAME}</a>' } ] o.setting = { hasDate: false, isFlat: false, isReverse: false, limitSub: "", indent: "3", onlyCurrent: false, useToggle: false } data.footer = o; /* ---------- ---------- ---------- */ var o = {} o.targetDir = "--"; o.targetTag = "--"; o.levels = [ //第1階層 { isShow: true, isOpen: false, dir: '<a href="{HREF}" target="{TAR}">{I.D} {NAME}</a>', page: '<a href="{HREF}" target="{TAR}">{NAME}</a>', add: '<a href="{HREF}" target="{TAR}">{NAME}</a>' }, //第2階層 { isShow: true, isOpen: false, dir: '<a href="{HREF}" target="{TAR}">{I.D} {NAME}</a>', page: '<a href="{HREF}" target="{TAR}">{NAME}</a>' }, //第3階層 { isShow: true, isOpen: false, dir: '<a href="{HREF}" target="{TAR}">{I.D} {NAME}</a>', page: '<a href="{HREF}" target="{TAR}">{NAME}</a>' }, //第4階層 { isShow: true, isOpen: false, dir: '<a href="{HREF}" target="{TAR}">{I.D} {NAME}</a>', page: '<a href="{HREF}" target="{TAR}">{NAME}</a>' }, //第5階層 { isShow: true, isOpen: false, dir: '<a href="{HREF}" target="{TAR}">{I.D} {NAME}</a>', page: '<a href="{HREF}" target="{TAR}">{NAME}</a>' } ] o.setting = { hasDate: false, isFlat: false, isReverse: false, limitSub: "", indent: "3", onlyCurrent: false, useToggle: true, add: { list: { texts: {}, grid: [] }, list2: { texts: {}, grid: [ { publicData: "1", text: "Facebook", anchor: { href: "#", target: "" } }, { publicData: "1", text: "Twitter", anchor: { href: "#", target: "" } } ] } } } o.css = { hasSub: true, underconst: true, clearfix: false, current: true, hasSub: true, level: true, no: false, ownCurrent: true, sum: false, type: true } data.mobile = o; /* ---------- ---------- ---------- */ return data; })(); <file_sep>/src/js/cms_stage_page/CMS_PageID.js var CMS_PageID = (function(){ function getID(_id,_dir){ if(_dir == undefined) _dir = ""; if(_id == undefined) _id = ""; var dir = _dir.split("/").join("__SP__") var id = _id.split(".").join("") return CMS_PageID.PAGE_PREFIX + dir + "_" + id; } function getID_s(_id,_dir){ if(_dir == undefined) _dir = ""; if(_id == undefined) _id = ""; var dir = _dir.split("/").join("__SP__") var id = _id.split(".").join("") return dir + "_" + id; } function getID_s2(_id){ if(_id == undefined) _id = ""; var _id = _id.split("/").join("__SP__") _id = _id.split(".").join("") return _id; } return { getID: getID, getID_s: getID_s, getID_s2: getID_s2 } })(); CMS_PageID.PAGE_PREFIX = "_SVP_"; <file_sep>/js_cms/_cms/storage.login.php <?php /** * JS_CMS -- realtime website development web application * http://js-cms.jp/ * Copyright 2015 <NAME> - <EMAIL> * licensed under the MIT licenses. */ if (!defined('CMS')) exit; if(USE_LOGIN){ session_start(); if(!isset($_SESSION['jscms_login']) || ! $_SESSION['jscms_login']){ header("Content-Type: application/json; charset=utf-8"); echo( '{"status":-1 , "level":1,"message":"not logined"}'); exit(); } } <file_sep>/src/js/cms_stage_asset/CMS_Asset_FileManageAPI.js var CMS_Asset_FileManageAPI = (function(){ function isImageFile(_s){ var ex = _s.toLowerCase(); var b = false; if(_s == "gif") return true; if(_s == "jpg") return true; if(_s == "jpeg") return true; if(_s == "svg") return true; if(_s == "png") return true; return false; } /* ---------- ---------- ---------- */ function upload(_targetDir,_view,_callback){ var fd = new FormData(_view); // var fd = new FormData($('#uploadFile').get(0)); var u = "?action=upload&upload_dir=" + escape_url(_targetDir); var url = CMS_Path.PHP_FILEPATH + u; $.ajax({ url: url, type: "POST", data: fd, processData : false, contentType : false, dataType : 'json', success : function(data) { _callback(data)}, error : function(data) { CMS_ErrorView.stageIn("NET",url,null,data); } }); } /* ---------- ---------- ---------- */ function addFile(_targetDir,_s,_callback){ var this_ = this; var param = {} param.action = "write"; param.file_name = _s; param.dir_name = escape_url(_targetDir); param.text = ""; var url = CMS_Path.PHP_FILEPATH; $.ajax({ scriptCharset : 'utf-8', type : 'POST', url : url, data : param, dataType : 'json', success : function(data) {_callback(data)}, error : function(data) { CMS_ErrorView.stageIn("NET",url,param,data); } }) } /* ---------- ---------- ---------- */ function deleteFile(_targetDir,_s,_callback){ var this_ = this; var param ={} param.action = "delete"; param.deleteFile = escape_url(_s); var url = CMS_Path.PHP_FILEPATH; $.ajax({ scriptCharset : 'utf-8', type : 'POST', url : url, data : param, dataType : 'json', success : function(data) {_callback(data)}, error : function(data) { CMS_ErrorView.stageIn("NET",url,param,data); } }) } /* ---------- ---------- ---------- */ function rename(_targetDir,_s1,_s2,_callback){ // var newName = (function(){ // // var ex = URL_U.getExtention(_s); // // var nn = URL_U.getFileID(_s); // var s = prompt("ファイル名を入力してください",_s); // if(s == null) return ""; // if(s.match(/[^0-9a-zA-Z_./-]+/) != null ){ // alert("半角英数字 ( 0-9 a-z A-Z _ . )で入力してください。"); // return ""; // } // if(s){ // return s; // } else{ // return ""; // } // })(); // if(newName == "") return; // if(newName == _s) return; var this_ = this; var param ={} param.action = "rename"; param.rename_old = escape_url(_targetDir) + _s1; param.rename_new = escape_url(_targetDir) + _s2; var url = CMS_Path.PHP_FILEPATH; $.ajax({ scriptCharset : 'utf-8', type : 'POST', url : url, data : param, dataType : 'json', success : function(data) {_callback(data)}, error : function(data) { CMS_ErrorView.stageIn("NET",url,param,data); } }) } /* ---------- ---------- ---------- */ function addDir(_targetDir,_s,_callback){ var this_ = this; var param ={} param.action = "createDir"; param.dir_name = escape_url(_targetDir) + _s; var url = CMS_Path.PHP_FILEPATH; $.ajax({ scriptCharset : 'utf-8', type : 'POST', url : url, data : param, dataType : 'json', success : function(data) {_callback(data)}, error : function(data) { CMS_ErrorView.stageIn("NET",url,param,data); } }) } function renameDir(_targetDir,_s1,_s2,_callback){ // var newName = (function(){ // var s = prompt("ディレクトリ名を入力してください",_s); // if(s == null) return ""; // if(s.match(/[^0-9a-zA-Z_/-]+/) != null ){ // alert("半角英数字で入力してください。"); // return ""; // } // if(s){ // return s; // } else{ // return "" // } // })(); // if(newName == "") return; // if(newName == _s) return; var this_ = this; var param ={} param.action = "renameDir"; param.dir_name = escape_url(_targetDir) + _s1; param.dir_rename = escape_url(_targetDir) + _s2; var url = CMS_Path.PHP_FILEPATH; $.ajax({ scriptCharset : 'utf-8', type : 'POST', url : url, data : param, dataType : 'json', success : function(data) {_callback(data)}, error : function(data) { CMS_ErrorView.stageIn("NET",url,param,data); } }) } function deleteDir(_targetDir,_s,_callback){ var this_ = this; var param ={} param.action = "deleteDir"; param.dir_name = escape_url(_s); var url = CMS_Path.PHP_FILEPATH; $.ajax({ scriptCharset : 'utf-8', type : 'POST', url : url, data : param, dataType : 'json', success : function(data) {_callback(data)}, error : function(data) { CMS_ErrorView.stageIn("NET",url,param,data); } }) } // action:write // file_name:aa.txt // dir_name:../_____html/ // text: // CMS_Asset_FileManageAPI.createDir("../_____html/","_01",function(){alert(1)}) /* ---------- ---------- ---------- */ return { isImageFile:isImageFile, upload:upload, addFile:addFile, deleteFile:deleteFile, rename:rename, addDir:addDir, renameDir:renameDir, deleteDir:deleteDir } })(); <file_sep>/src/js/cms_view_modals/Editer_JSONView.js var Editer_JSONView = (function(){ var view; var v = {}; function init(){ view = $('#Editer_JSONView'); stageInit(); } /* ---------- ---------- ---------- */ var codeminerEditor; var codeminerView; function createlayout(){ v = ModalViewCreater.createBaseView(Editer_JSONView,view); var tag = "" tag = '<div class="_title">JSONデータの直接編集</div>' v.header.html(tag); tag = "" tag += '<div class="_read">ページのデータはJSON型式でテキストファイルで保存されています。<br>以下のテキストファイルを直接編集したり、コピーし、他のページにペーストすることにより、ページの複製が可能です。</div>'; tag += '<div class="_texts _text-editor ">' tag += ' <textarea class="codemirror"></textarea>' tag += '</div>'; v.body.html(tag) v.textEditor = view.find('._text-editor'); v.textEditor.addClass(CodeMirrorU.getColorType("json")); var changeFirst = true codeminerEditor = CodeMirrorU.createEditor(view.find("textarea").get(0),"json",true); codeminerEditor.foldCode(CodeMirror.Pos(0,0)); codeminerView = view.find(".CodeMirror"); tag = "" tag += '<div class="_cms_btn _btn_close">キャンセル</div> '; tag += '<div class="_cms_btn _cms_btn_active _btn_do" '+TIP_ENTER+'><i class="fa fa-check"></i> 編集完了</div> '; v.footer.html(tag); v.textarea = view.find('textarea'); setBtn(); } function setBtn(){ view.find('._bg ,._btn_close').click(function(){ stageOut() }); v.btn_do = view.find('._btn_do'); v.btn_do.click(function(){ callback(getData()); stageOut(); }); } function update(_s){ codeminerEditor.setValue(_s); } /* ---------- ---------- ---------- */ //class style function getData(){ return codeminerEditor.getValue(); } /* ---------- ---------- ---------- */ function compliteEdit(){ stageOut(); } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } var callback function stageIn(_s,_callback){ if(! isOpen){ isOpen = true; showModalView(this); callback = _callback; view.show(); if(isFirst){createlayout();} isFirst = false; update(_s); resize(); } } function stageOut(){ if(isOpen){ isOpen = false; hideModalView(); view.hide(); } } function resize(){ if(isOpen){ var h = $(window).height() -250; codeminerView.height(h) } } return { init:init, stageIn:stageIn, stageOut:stageOut,resize:resize,compliteEdit:compliteEdit } })(); <file_sep>/src/js/cms_view_editable/EditableView.TextPageView.js EditableView.TextPageView = (function() { /* ---------- ---------- ---------- */ var c = function(_pageModel,_data,_parentView,_wapper) { this.init(_pageModel,_data,_parentView,_wapper); } var p = c.prototype; /* ---------- ---------- ---------- */ p.init = function(_pageModel,_data,_parentView,_wapper) { this.v = {}; this.v.parentView = _parentView; this.wapperClass = _wapper; this.model = _pageModel; this.type = _pageModel.type; this.name = _pageModel.id; this.dir = _pageModel.dir this.extention = FileU.getExtention(this.name); this.storage = _data; } /* ---------- ---------- ---------- */ p.createView =function (){ var self = this; var tag = (function(_name,_dir){ var s = ""; s += '<div class="_editableSetting">'; s += ' <div class="_header">'; s += ' <div class="_header_inner">'; s += ' <div class="_title"> {TITLE}</div>'; s += ' </div>'; s += ' </div>'; s += ' <div class="_body _asset-scroll">' s += ' {EDITOR}'; s += ' </div>'; s += ' <div class="_footer">'; s += ' <div class="_btns">' s += ' <div class="_btn _btn_search"><i class="fa fa-search "></i> 検索</div>' s += ' <div class="_btn _btn_reload"><i class="fa fa-repeat"></i> リロード</div>' s += ' <div class="_btn _btn_back"><i class="fa fa- "></i> <i class="fa fa-reply "></i> 編集前に戻す</div>' s += ' </div>' s += ' <div class="_page_pubs">'; s += ' <div class="_cms_btn_alpha _btn_save" '+TIP("#+S")+'><i class="fa fa-check "></i> 保存済み</div>'; s += ' <div class="_cms_btn_alpha _btn_save_pre" '+TIP("#+S")+'><i class="fa fa-pencil "></i> 保存する</div>'; s += ' <div class="_btn_saveing"><i class="fa fa-cog fa-spin"></i></div>'; s += ' </div>'; s += ' </div>'; s += ' <div class="_addText">'; s += ' <div class="_btn_close"><i class="fa fa-lg fa-times-circle "></i></div>'; s += ' <div class="_label"></div>'; s += ' <textarea></textarea><br>'; s += ' <div class="_cms_btn _cms_btn_active _btn_embed"><i class="fa fa-level-down fa-rotate-180 "></i> テキストを埋め込む</div>'; s += ' </div>'; s += '</div>'; var _t = CMS_Path.ASSET.getAbsPath_deco_file(_name , _dir); var read_ = (function(_s){ if(_s == Dic.DirName.TEMPLATE) { return "テンプレートHTMLの編集を行えます。" + CMS_GuideU.getGuideTag("setting/template","テンプレートHTMLについて") } return "アセットファイルの編集を行えます。" + CMS_GuideU.getGuideTag("setting/asset","アセットについて") })(this.name, this.dir); var editor = (function(_s){ var ss = "" var extra = self.getExtraTag(); if(extra){ ss += ' <div class="_main">' ss += ' <div class="_text-editor">' ss += ' <textarea class="codemirror"></textarea>' ss += ' </div>'; ss += ' </div>'; ss += ' <div class="_sub">' + self.getExtraTag() + '</div>'; } else{ ss += ' <div class="_text-editor">' ss += ' <textarea class="codemirror"></textarea>' ss += ' </div>'; } return ss; })(); s = s.split("{TITLE}").join('<div class="_fs12 _filePath_wh _cms_btn_alpha">' + _t +'</div>'); s = s.split("{EDITOR}").join(editor); s = s.split("{READ}").join(read_); return s; })(this.name,this.dir); this.view = $(tag); this.v.parentView.append(this.view); this.v._editText = this.view.find('textarea'); this.v.textEditor = this.view.find('._text-editor'); this.setBtn(); this.initAddText(); this.initExtra(); this.initEditor(); this.initData(); // this.initFindCSS(); this.initResize(); // this.stageInit(); } /* ---------- ---------- ---------- */ p.getExtraTag =function (){ var tag = ''; return tag; } p.initExtra =function (){ var self = this; // this.v.cssState = this.view.find("._cssState"); // this.view.find("._btn_designCss").click(function(){ // var u = CSS_DESIGN_URL // var s = self.v.cssState.val(); // if(s) u += "?class=" + s; // window.open(u ,"css_design"); // }); // this.initFindCSS(); } /* ---------- ---------- ---------- */ p.setBtn =function (){ var self = this; this.v.btn_save = this.view.find('._btn_save'); this.v.btn_save_pre = this.view.find('._btn_save_pre'); this.v.btn_saveing = this.view.find('._btn_saveing'); this.v.btn_search = this.view.find('._btn_search'); this.v.btn_reload = this.view.find('._btn_reload'); this.v.btn_back = this.view.find('._btn_back'); this.v.btn_save .click(function(){ self.saveData(); }); this.v.btn_save_pre .click(function(){ self.saveData(); }); this.v.btn_search .click(function(){ self.search() }); this.v.btn_reload .click(function(){ self.reload() }); this.v.btn_back .click(function(){ self.restoreText() }); } /* ---------- ---------- ---------- */ p.codeminerEditor p.codeminerView p.initEditor = function(){ var self = this; // this.v.textEditor.addClass(CodeMirrorU.getColorType(this.extention)); var changeFirst = true this.codeminerEditor = CodeMirrorU.createSettingEditor(this.v._editText.get(0),this.extention,false); this.codeminerEditor.foldCode(CodeMirror.Pos(0,0)); this.codeminerEditor.on("change",function(){ if(changeFirst) { changeFirst = false return; } self.activeSaveBtn(); }) this.codeminerView = this.view.find(".CodeMirror"); } /* ---------- ---------- ---------- */ //テキスト追加 p.initAddText = function(){ var self = this; this.v.addText = this.view.find('._addText'); this.v.btn_close = this.view.find('._addText ._btn_close'); this.v.addText_label = this.view.find('._addText ._label'); this.v.addText_btn_embed = this.view.find('._addText ._btn_embed'); this.v.addText_textarea = this.view.find('._addText textarea'); this.v.addText.hide(); this.v.btn_close.click(function(){ self.v.addText.hide(); }) this.v.addText_btn_embed.click(function(){ self.appendText(self.v.addText_textarea.val()); self.v.addText.hide(); }) } p.openAddTextWin = function(_key){ this.v.addText.show(); this.v.addText_label.html(_key.label) this.v.addText_textarea.val(_key.data) } p.appendText = function(_s){ this.codeminerEditor.replaceSelection(_s,"around"); this.codeminerEditor.focus(); } /* ---------- ---------- ---------- */ //CSS検索 // p.initFindCSS = function(){ // var self = this; // this.v.cssState.keyup(function(){ // self.find($(this).val()); // }); // } p.findCSS = function(_key){ // this.v.cssState.val(_key).keyup(); this.find(_key); } p.tID_delay; p.find = function(_key){ if(!_key)return; var l = this._findRow(this.codeminerEditor.getValue().split("\n"),_key); if(l != false){ this.codeminerEditor.scrollIntoView({line:0,ch:0}); this.codeminerEditor.setSelection( {line:l[0],ch:l[1]}, {line:l[0],ch:l[1] + _key.length } ); this.codeminerEditor.scrollIntoView({line:l[0]+5,ch:0},true); // CodeMirror.commands.find(this.codeminerEditor); } } p._findRow = function(_a,_s){ for (var i = 0; i < _a.length ; i++) { if(_a[i].indexOf(_s) != -1){ return [ i , _a[i].indexOf(_s) ]; } } return false; } p.search =function(){ CodeMirror.commands.find(this.codeminerEditor); } p.reload =function(){ var self = this; this.storage.reload(function(){ self.initData(); }); } p.restoreText =function(){ this.codeminerEditor.setValue(this.initDataText) } /* ---------- ---------- ---------- */ //#データ p.initDataText = ""; p.initData = function (){ this.initDataText = this.storage.text this.codeminerEditor.setValue(this.storage.text); this.initSaveBtn(); //上えコール if(this.wapperClass){ if(this.wapperClass.openedTextPage){ this.wapperClass.openedTextPage(this.model); } } } /* ---------- ---------- ---------- */ //#Save Preview p.initSaveBtn =function(){ this.disableSaveBtn(true); } p.saveData = function (_isPreview){ if(window.isLocked(true))return; var this_ = this; var s = this.codeminerEditor.getValue(); this.storage.save(s,function(){ this_.saveData_comp(); }); this.activeSaveingBtn(); } p.saveData_comp = function (){ this.disableSaveBtn(); //上えコール if(this.wapperClass){ if(this.wapperClass.savedTextPage){ this.wapperClass.savedTextPage(this.model); } } } /* ---------- ---------- ---------- */ //#保存ボタン表示 p.activeSaveBtn =function(){ this.v.btn_save.hide(); this.v.btn_save_pre.show(); } p.activeSaveingBtn =function(){ this.v.btn_saveing.show(); } p.disableSaveBtn =function(_b){ var this_ = this; if(_b){ this.disableSaveBtn_core() } else{ setTimeout(function(){ this_.disableSaveBtn_core() },500); } } p.disableSaveBtn_core =function(){ this.v.btn_save.show(); this.v.btn_save_pre.hide(); this.v.btn_saveing.hide(); } /* ---------- ---------- ---------- */ p.previewData =function (_callback){} /* ---------- ---------- ---------- */ //#Stage p.isOpen = false; p.isFirst = true; p.stageInit = function (){ this.view.hide(); } p.tID p.stageIn = function (_extra){ if(! this.isOpen){ this.isOpen = true; var self = this; if(this.isFirst){ this.createView() this.resize(); } this.isFirst = false; this.view.show(); if(_extra) { if(_extra["find"]){ setTimeout(function(){ self.find(_extra.find); },200); } if(_extra["findCss"]){ setTimeout(function(){ self.findCSS(_extra.findCss); },200); } if(_extra["addText"]){ setTimeout(function(){ self.openAddTextWin(_extra.addText); },200); } } } } p.stageOut = function (){ if(this.isOpen){ this.isOpen = false; this.view.hide(); } } /* ---------- ---------- ---------- */ p.remove = function (){ } /* ---------- ---------- ---------- */ p.initResize = function (){ var self = this; if(this.wapperClass["registResize"]){ this.wapperClass.registResize(function(){ self.resize(); }); } } p.resize = function (){ if(this.isOpen){ if(this.wapperClass["getH"]){ this.codeminerView.height(this.wapperClass.getH() -80); } } } return c; })(); <file_sep>/src/js/cms_view_editable/EditableView.CustomList.js /** * リピートオブジェクトビューの管理 */ EditableView.CustomList = (function() { /* ---------- ---------- ---------- */ var c = function(_gridType) { this.init(_gridType); } var p = c.prototype; /* ---------- ---------- ---------- */ p.init = function (_gridType) { this.gridType = _gridType; this.v = {} this.setParam() this.customList = new EditableView.CustomListClass() } p.setParam = function (){ this.gridInfo = this.gridType.gridInfo; } p.registParent = function (_parent){ this.parent = _parent; this.customList.registParent(_parent); } p.initData = function (_data){ this.customList.initData([_data[0],_data[1],_data[2],_data[3]]); } p.getData = function (){ return this.customList.getData(); } p.updateSubData = function (){} return c; })(); EditableView.CustomListClass = (function() { /* ---------- ---------- ---------- */ var c = function() { this.init(); } var p = c.prototype; /* ---------- ---------- ---------- */ p.init= function () { this.v = {} } p.registParent = function (_parent){ this.parent = _parent; } p.initData = function (_data){ if(_data == null) _data = ["","",null]; var this_ = this; var tag = ''; tag += '<div class="_editableBlock _editableTemplate">'; tag += ' <div class="_left">'; tag += ' <div class="_h2" style="margin-top:0px;">テンプレート</div>'; tag += ' <table>'; tag += ' <tr>'; tag += ' <td><div class="_title">CSS用ID名 {ID}</div></td>'; tag += ' <td><input class="_id _color-style" style="width:150px;margin:0 0 5px 5px;" value=""></td>'; tag += ' </tr>'; tag += ' </table>'; tag += ' <div class="_tabBlock">'; tag += ' <span class="_btn_html ">HTML or JS</span>'; tag += ' <span class="_btn_css ">CSS</span>'; tag += ' </div>'; tag += ' <div class="_htmlArea"></div>'; tag += ' <div class="_cssArea"></div>'; tag += ' </div>'; tag += ' <div class="_main">' tag += ' <div class="_core">' tag += ' <div class="_h2" style="margin-top:0px;">プレビュー<span style="font-weight:normal;"> (リストデータ×テンプレート)</span></div>'; tag += ' <div class="_cms_btn-mini _btn_relaod"><i class="fa fa-repeat"></i> リストデータを反映</div>'; tag += ' <div class="_tabBlock">'; tag += ' <span class="_btn_preview">表示プレビュー</span>'; tag += ' <span class="_btn_code">HTMLプレビュー</span>'; tag += ' </div>'; tag += ' <div class="_previewAreaWapper">' tag += ' <iframe class="_previewArea" src ="blank.html" frameborder="0" ></iframe>' tag += ' <div class="_codeArea"><textarea readonly></textarea></div>' tag += ' </div>'; tag += ' </div>'; tag += ' </div>'; tag += ' <div class="_preset" style="position:relative">' tag += ' </div>'; tag += '</div>'; this.view = $(tag); this.parent.v.replaceArea.append(this.view); this.v.preview = this.view.find('._previewArea'); this.v.code = this.view.find('._codeArea textarea'); // this.v._htmlArea = this.view.find('._htmlArea'); this.v._cssArea = this.view.find('._cssArea'); // this.v._htmlArea.append(CMS_FormU.getTextarea("","html")) this.v._htmlArea.append('<div class="_cms_btn-mini _btn_js">JSでの実装サンプル</div>') this.v._cssArea.append(CMS_FormU.getTextarea("","style")) // this.v.in_html = this.v._htmlArea.find("textarea"); this.v.in_css = this.v._cssArea.find("textarea"); this.v.in_html.css({width:"350px",height:"280px"}).prop("wrap","off"); this.v.in_css.css({width:"350px",height:"280px"}).prop("wrap","off"); this.v._btn_html = this.view.find('._btn_html'); this.v._btn_html.click(function(){ this_.openHTML(true)}); this.v._btn_css = this.view.find('._btn_css'); this.v._btn_css.click(function(){ this_.openHTML(false)}); this.v._btn_js = this.view.find('._btn_js'); this.v._btn_js.click(function(){ this_.addJS()}); this.openHTML(true); // this.v._previewArea = this.v.preview this.v._codeArea = this.view.find('._codeArea'); this.v.btn_preview = this.view.find('._btn_preview'); this.v.btn_preview.click(function(){ this_.openPreview(true)}); this.v._btn_code = this.view.find('._btn_code'); this.v._btn_code.click(function(){ this_.openPreview(false)}); this.openPreview(true); // this.v._btn_relaod = this.view.find('._btn_relaod'); this.v._btn_relaod.click(function(){ this_.updatePreview()}); this.v.temps = [ this.view.find("._id"), this.v.in_html, this.v.in_css ] this.v.temps[0].val(_data[0]) this.v.temps[1].val(_data[1]) this.v.temps[2].val(_data[2]) this.view.find("textarea,input").keyup(function(){ this_.updatePreview(); }); this.updatePreview(); var presetView = new EditableView.CustomListPreset(this.view.find('._preset')); presetView.setData(_data[3]); presetView.stageIn(function(o,_param){ this_.setPreset(o); this_.setSetting(_param); }) this.templateSetting = _data[3]; this.updateiFrameW(); } p.setPreset = function (_o){ this.v.temps[1].val(_o.html); this.v.temps[2].val(_o.css); this.updatePreview(); } p.updateiFrameW = function (){ var p = this.templateSetting; if(p.ww == 0){ this.v.preview.css("width" ,this.templateSetting.t_ww ) } else{ this.v.preview.css("width" ,"100%" ) } } p.setSetting = function (_o){ this.templateSetting = _o; this.updateiFrameW(); } var AC = "_active"; p.openHTML = function (_b){ this.v._btn_html.removeClass(AC) this.v._btn_css.removeClass(AC) this.v._htmlArea.hide() this.v._cssArea.hide() if(_b){ this.v._btn_html.addClass(AC) this.v._htmlArea.show() } else{ this.v._btn_css.addClass(AC) this.v._cssArea.show() } } p.openPreview = function (_b){ this.v.btn_preview.removeClass(AC); this.v._btn_code.removeClass(AC); this.v._previewArea.hide(); this.v._codeArea.hide(); if(_b){ this.v.btn_preview.addClass(AC); this.v._previewArea.show(); } else{ this.v._btn_code.addClass(AC); this.v._codeArea.show(); } } p.getData = function (){ return [ this.v.temps[0].val(), this.v.temps[1].val(), this.v.temps[2].val(), this.templateSetting ]; } p.updatePreview = function (){ var this_ = this; if(this.tID) clearTimeout(this.tID); this.tID = setTimeout(function(){ this_.updatePreview_core() },200); } p.prevHTML = "" p.updatePreview_core= function (){ var list = CMS_U.getPublicList( EditableView.currentGrid.getData() ); var tag = ""; if(ASSET_CSS_DIRS){ for (var i = 0; i < ASSET_CSS_DIRS.length ; i++) { tag += '<link rel="stylesheet" class="asset" type="text/css" href="'+ ASSET_CSS_DIRS[i]+'" />'; } } tag += CMS_TemplateU.doTemplate( { id : this.v.temps[0].val(), htmls : this.v.temps[1].val(), css : this.v.temps[2].val(), // isPub : false, list : list, leng : list.length, isEdit : true }); this.v.preview.contents().find('#REPLACE').html(tag); this.v.code.val(tag); this.updatePreview_jsView(this.v.temps[1].val()); } p.isJS = false; p.updatePreview_jsView = function (_s){ if(CMS_TemplateU.isJS(_s)){ if(this.isJS== false){ var tar = this.v.temps[1]; tar.removeClass("_color-html"); tar.addClass("_color-js"); tar.parent().find("._btn_input").data("type","textarea:js") } this.isJS = true; } else { if(this.isJS){ var tar = this.v.temps[1]; tar.removeClass("_color-js"); tar.addClass("_color-html"); tar.parent().find("._btn_input").data("type","textarea:html") } this.isJS = false; } } p.addJS = function (_o){ this.v.temps[1].val(CMS_Data.CodeDic.getCode("block.replace.js")); this.updatePreview(); } return c; })(); <file_sep>/src/js/cms_storage/Storage.Local.js /** * ページツリーの開閉リストの記憶などで仕様 */ Storage.Local = (function() { /* ---------- ---------- ---------- */ var c = function(_id,_initData) { this.init(_id,_initData); } var p = c.prototype; /* ---------- ---------- ---------- */ p.init = function(_id,_initData) { this.id = _id; this.initData = _initData; this.storeData = {}; this.callback; this.callbackSave; } p.load = function(_callback) { this.callback = _callback; var s; if(!localStorage.hasOwnProperty(this.id)){ s = JSON.stringify(this.initData); localStorage[this.id] = s; } else{ s = localStorage[this.id]; } this.storeData = JSON.parse(s); this.save(function(){}); this.loaded(); } p.loaded = function(){ this.callback(); } p.setData = function(_data){ this.storeData = _data; } p.save = function (_callback){ this.callbackSave = _callback; localStorage[this.id] = JSON.stringify(this.storeData); } p.saved = function (data){ this.callbackSave(); } p.getData = function (){ return this.storeData; } p.reset = function (){ delete localStorage[this.id]; } p.exportJSON = function (){ return JSON.stringify(this.storeData, null, " "); } p.importJSON = function (_s){ try{ this.storeData = JSON.parse(_s); this.save(function(){}); }catch( e ){ alert("入力データが正しくありません。"); } } return c; })(); <file_sep>/js_cms/_cms/login.php <?php /** * JS_CMS -- realtime website development web application * http://js-cms.jp/ * Copyright 2015 <NAME> - <EMAIL> * licensed under the MIT licenses. */ define('CMS', true); require_once("./setting/setting.php"); /* ! ---------- pre ---------- ---------- ---------- ---------- */ header("Content-Type: application/json; charset=utf-8"); /* ! ---------- input ---------- ---------- ---------- ---------- */ if(! isset($_GET['action']))status_off(); $action = $_GET['action']; if(USE_LOGIN){ session_start(); } /* ! ---------- main ---------- ---------- ---------- ---------- */ function createSession(){ $oldSid = session_id(); session_regenerate_id(TRUE); if (version_compare(PHP_VERSION, '5.1.0', '<')) { $path = session_save_path() != '' ? session_save_path() : '/tmp'; $oldSessionFile = $path . '/sess_' . $oldSid; if (file_exists($oldSessionFile)) { unlink($oldSessionFile); } } $_SESSION['jscms_login'] = true; } if($action == 'state'){ if(!USE_LOGIN) status_noLogin(); if(!isset($_SESSION['jscms_login']))status_off(); if($_SESSION['jscms_login']){ createSession(); status_on(); } else{ status_off(); } } else if( $action == 'login'){ if(! isset($_POST['u']))status_off(); if(! isset($_POST['p']))status_off(); if($_POST['u'] == USERNAME && $_POST['p'] == PASSWORD){ createSession(); status_on(); } else{ status_off(); } } else if( $action == 'logout'){ $_SESSION = array(); if (isset($_COOKIE[session_name()])) { setcookie(session_name(), '', time()-42000, '/'); } session_destroy(); status_off(); } function status_on(){ echo( '{"status":1 , "message":"OK"}'); exit(); } function status_noLogin(){ echo( '{"status":2 , "message":""}'); exit(); } function status_off(){ echo( '{"status":0 , "message":""}'); exit(); } <file_sep>/src/js/cms_model/PageElement.object.data_json.js PageElement.object.data_json = (function(){ var _ = new PageModel.Object_(); /* ---------- ---------- ---------- */ _.pageInfo = new PageModel.Object_Info({ id : "object.data_json", name : "データブロックJSON", name2 : "", inputs : ["DETAIL"] }); /* ---------- ---------- ---------- */ var gridSum = GRID_EDIT_MAX_CELL.DATA; _.grids = [ /* ---------- ---------- ---------- */ new PageModel.Object_Grid({ gridType:Dic.GridType.BASE, gridInfo:new PageModel.OG_info({ id : "table", name : "データ", note : "" }), textData:{ info:new PageModel.OG_SubInfo({ name:"設定", note:"", image: "" }), cells:[ new PageModel.OG_Cell({ id: "text_before", name: "データの前に追加するテキスト", style: SS.w400, type: CELL_TYPE.MULTI, view: "", def: "", note: "例: &lt;textarea id=\"data\" style=\"display:none;\"&gt;" }), new PageModel.OG_Cell({ id: "text_after", name: "データの後ろに追加するテキスト", style: SS.w400, type: CELL_TYPE.MULTI, view: "", def: "", note: "例: &lt;/textarea&gt;" }) ] }, gridData:{ info:new PageModel.OG_SubInfo({ name:"データグリッド" }), cells:JSON.parse(JSON.stringify(PageElement_data_gridCell)) } }) ] /* ---------- ---------- ---------- */ _.getInitData = function(){ var o = {}; o.type = _.pageInfo.id; o.data = _.getDefData(3); o.attr = {css:"",style:""}; return o; } /* ---------- ---------- ---------- */ _.getPreview = function(_o){ var data = _o.data; var attr = _o.attrs; var tag = ""; var list = CMS_U.getPublicList(data.table.grid); tag += '<div class="_cms_preview">\n' tag += '<div class="_title">データブロック / JSONデータ</div>' tag += '<div class="_notes">ブロック情報パネルの、[出力]タブよりファイル名を設定し、書出せます。</div>' tag += '<div class="">\n' if(list.length == 0){ tag += '<span class="_no-input-data">データリストを入力...</span>' } else{ var maxLeng = PageElement_Util.getGridMaxLeng(list,gridSum); tag += '<table class="_dataTable">\n' tag += '<tbody>\n' var leng = PageElement_Util.getOmitLeng(list.length,"data"); for (var i = 0; i < leng ; i++) { tag += ' <tr>\n'; for (var ii = 0; ii < maxLeng +1 ; ii++) { var v = CMS_TagU.t_2_tag(list[i]["c"+(ii+1)]); tag += ' <td>' + v + '</td>\n'; } tag += ' </tr>\n'; } tag += "</tbody>\n"; tag += "</table>\n"; tag += PageElement_Util.getOmitPreviewTag(list.length,"data") } tag += "</div>\n"; tag += "</div>\n"; return tag; } /* ---------- ---------- ---------- */ _.getHTML = function(_o,_tab){ var data = _o.data; var attr = _o.attrs; var text_before = data.table.texts.text_before || ""; var text_after = data.table.texts.text_after || ""; var grid = CMS_U.getPublicList(data.table.grid); if(grid.length == 0) return ""; var a = []; var maxLeng = PageElement_Util.getGridMaxLeng(grid,gridSum); for (var i = 0; i < grid.length ; i++) { a[i] = [] for (var ii = 0; ii < maxLeng + 1 ; ii++) { a[i][ii] = CMS_TagU.t_2_tag(grid[i]["c"+(ii+1)]) if(a[i][ii] == null) a[i][ii] = "" } } return text_before + JSON.stringify({list:a}, null, " ") + text_after; } /* ---------- ---------- ---------- */ return _; })(); <file_sep>/src/js/cms_model/PageElement_Dic.js var PageElement_DIC = [] window.PageElement_DIC = PageElement_DIC; <file_sep>/src/js/cms_view_modals/EmbedTagListView.js var EmbedTagListView = (function(){ var view; var v = {}; /* ---------- ---------- ---------- */ //初期化 function init(){ view = $('#EmbedTagListView'); stageInit(); } /* ---------- ---------- ---------- */ //レイアウト作成・イベントアサイン function createlayout(){ v = ModalViewCreater.createBaseView(EmbedTagListView,view); var tag = "" tag += '<div class="_guide">'+CMS_GuideU.getGuideTag("embedtag/","_BASE_")+'</div>' tag += '<div class="_title">{{埋込みタグ}}</div>' tag += '<div class="_tabs">' tag += ' <div class="_tab _tab_my">Myタグ一覧</div>' tag += ' <div class="_tab _tab_page">ページタグ一覧</div>' tag += ' <div class="_tab _tab_file">ファイル埋込み</div>' tag += '</div>' v.header.html(tag); tag = "" tag += '<div class="_cms_btn _btn_close">閉じる</div> '; v.footer.html(tag) view.find("._cms_btn_alpha").click(function(){ var type = $(this).attr("data"); callback(type); stageOut(); }); tag = "" tag += '<div class="_area _area_my">_area_my</div>' tag += '<div class="_area _area_page">_area_page</div>' tag += '<div class="_area _area_file">_area_file</div>' v.body.html(tag); v.tabs = v.header.find("._tab"); v.tab = {} v.tab.my = v.header.find("._tab_my"); v.tab.page = v.header.find("._tab_page"); v.tab.file = v.header.find("._tab_file"); v.tab.my.click(function(){ openTab("my")}); v.tab.page.click(function(){ openTab("page")}); v.tab.file.click(function(){ openTab("file")}); v.areas = v.body.find("._area"); v.area = {} v.area.my = v.body.find("._area_my"); v.area.page = v.body.find("._area_page"); v.area.file = v.body.find("._area_file"); v.areas.hide(); setBtn(); } function setBtn(){ view.find('._bg ,._btn_close').click(function(){ stageOut() }); view.on('click','._rep_id',function(){ selectTag($(this).text()); }); } /* ---------- ---------- ---------- */ // function openTab(_type){ if(!_type)_type = "my"; v.tabs.removeClass("_active"); v.tab[_type].addClass("_active"); v.areas.hide(); v.area[_type].show() if(_type == "my") update_my(); if(_type == "page") update_page(); if(_type == "file") update_file(); } /* ---------- ---------- ---------- */ //個別処理 function update(_type){ openTab(_type); } /* ---------- ---------- ---------- */ //my function update_my(){ var tag = "" tag += '<div class="_guide">'+CMS_GuideU.getGuideTag("embedtag/page","_BASE_")+'</div>' tag +='<br style="clear:both;">' tag +='<div class="_read" style="clear:both;">{{Myタグ設定}}ページで定義したMyタグの一覧です。タグ名をクリックすると、タグを取得できます。</div>' var locals = CMS_Data.MyTagReplace.getLocalMyTagList(); tag += '<div class="_tag_h2">ローカル (このページのみで利用可能)</div>' if(locals){ tag += '<div class="_tag_title"><i class="fa fa-cog"></i> このページのMyタグ</div>' tag += _createMyTable(locals); } else{ tag += '<div>このページでは、ローカルなMyタグの定義はありません。</div>' } tag += '<br><br>' var gloup = CMS_Data.MyTag.getData(); tag += '<div class="_tag_h2">グローバル (サイト全体で利用可能)</div>' for (var n in gloup){ var pm = CMS_Data.MyTag.getParam_by_ID(n); if(pm){ tag += '<div class="_tag_title"><i class="fa fa-cog"></i> ' + pm.name + '</div>' } tag += _createMyTable(gloup[n]); } v.area.my.html(tag); } function _createMyTable(_keys){ var tag = "" tag +="<table>" for (var i = 0; i < _keys.length ; i++) { tag += '<tr>' tag += '<th>' tag += ' <span class="_rep_id">{{' + _keys[i].id + '}}</span>' tag += '</th> '; tag += '<td>' tag += ' <span class="_note">'+_keys[i].label+'</span>' tag += '</td> '; tag += '</tr>' } tag +="</table>" return tag; } /* ---------- ---------- ---------- */ var isFirstPage = true; function update_page(){ if(!isFirstPage)return; isFirstPage = false; // var tag = ""; tag += '<div class="_guide">'+CMS_GuideU.getGuideTag("embedtag/my","_BASE_")+'</div>' tag +='<br style="clear:both;">' tag +='<div class="_read">ページタグは、CMSに用意されているタグです。ページに関する情報を出力します。タグ自体のカスタマイズはできません。</div>' var gloup = CMS_Data.PageTag.getData(); for (var i = 0; i < gloup.length ; i++) { tag += '<div class="_tag_title">' + gloup[i].label + '</div>' tag += _createPageTable(gloup[i].items); } v.area.page.html(tag); } function _createPageTable(_keys){ var tag = "" tag +="<table>" for (var i = 0; i < _keys.length ; i++) { tag += '<tr>' tag += '<th>' tag += ' <span class="_rep_id">{{' + _keys[i].id + '}}</span>' tag += '</th> '; tag += '<td>' tag += ' <div class="_val">例:<span>'+_keys[i].text+'</span></div>' tag += ' <div class="_note">'+_keys[i].label+'</div>' tag += '</td> '; tag += '</tr>' } tag +="</table>" return tag; } /* ---------- ---------- ---------- */ function update_file(){ var tag = "" tag += '<div class="_guide">'+CMS_GuideU.getGuideTag("embedtag/file","_BASE_")+'</div>' tag +='<br style="clear:both;">' tag += '<div class="_read">ファイル埋込みは、外部HTMLやテキストファイルを埋込みます。主にテンプレHTMLの分割に用います。</div>'; tag += '<div class="_note">※ シンプルなテンプレHTMLの構成であれば、分割する必要はありません。</div>'; tag += '<div class="_tag_title">表記</div>'; tag += '<div class="_read">'; tag += 'ファイル埋込みを利用するには、以下の表記でタグを記載します。<br>'; tag += '</div>'; tag += '<div class="_sample">'; tag += '<b>{{FILE:ファイルパス}}</b>'; tag += '</div>'; tag += '<div class="_read">'; tag += 'ページ公開時に、ファイルパスのファイルをロードし埋込みます。<br>'; tag += 'ロードするファイルでは、<mark>ページタグや、Myタグも利用</mark>できます。<br>'; tag += '</div>'; tag += '<div class="_tag_title">基本的な用途...テンプレHTMLでの利用</div>'; tag += '<div class="_read">'; tag += 'htmlディレクトリ/_template/parts/に配置したファイルを、<br>'; tag += 'テンプレートHTML内に埋込むには、以下のように記述します。'; tag += '</div>'; tag += '<div class="_sample">'; tag += '//例:header.html<br>'; tag += '{{FILE:parts/header.html}}<br>'; tag += '</div>'; tag += '<div class="_note">※ 相対パスで記述する場合は、_template/ディレクトリからのパスになります。</div>'; tag += '<div class="_tag_title">別のディレクトリのファイルの埋込</div>'; tag += '<div class="_read">'; tag += 'CMSのサイトルートからの絶対パスを記述してください。<br>'; tag += '<div class="_sample">'; tag += '//例:サイトルート以下の/aa/bb/cc.txt<br>'; tag += '{{FILE:/aa/bb/cc.html}}<br>'; tag += '</div>'; tag += '<div class="_tag_title">テンプレHTML以外での利用</div>'; tag += '<div class="_read">'; tag += '通常のブロック内にも埋め込むことが出来ます。<br>'; tag += '普通に{{FILE:ファイルパス}}を記載してください。<br>'; tag += '<br>'; tag += 'Myタグでも同じようなことができますが、<br>'; tag += 'ブロックを共有する場合はMyタグを利用し、大きめのHTMLコードなどを<br>'; tag += '共有する場合は、ファイル埋め込みを利用するのがおすすめです。<br>'; tag += '<br>'; tag += '別のシステムで生成したHTMLをロードする場合などに利用できます。<br>'; tag += '</div>'; v.area.file.html(tag); } /* ---------- ---------- ---------- */ function selectTag(_s){ if(cb){ if(cb == 1){ UpdateDelay.delay(function(){ $("#SubPageView ._editableNode").eq(0).val(_s).keyup() }); } else{ cb(_s); } stageOut(); } else{ CMS_CopyView.stageIn(_s); } } /* ---------- ---------- ---------- */ //表示・非表示処理 var isOpen = false; var isFirst = true; // var cb = true; function stageInit(){ view.hide(); } function stageIn(_type,_cb){ if(! isOpen){ isOpen = true; view.show(); if(isFirst){ createlayout(); } cb = _cb; update(_type); isFirst = false; } } function stageOut(){ if(isOpen){ isOpen = false; view.hide(); } } return { init:init, stageIn:stageIn, stageOut:stageOut } })(); if(window["_cms"] ==undefined) window._cms = {}; window._cms.openEmbedList = function(_type,_cb){ EmbedTagListView.stageIn(_type,_cb); } // setTimeout(function(){ // window._cms.openEmbedList() // },1000); <file_sep>/src/js/cms_data/CMS_Data.Template.js /** * テンプレートHTMLの管理 */ CMS_Data.Template = (function(){ /* ---------- ---------- ---------- */ //テンプレートHTMLロード function init(){} /* ---------- ---------- ---------- */ var tmp = {} //HTML生成時に、都度コールされる function load(_id, _callback) { id = Dic.DEFAULT_TEMPLATE; if (_id != "") { id = _id; id = id.split(" ").join(""); id = id.split(" ").join(""); } var url = CMS_Path.ASSET.REL + Dic.DirName.TEMPLATE +"/"+ id; var urlR = url + "?" + new Date().getTime(); if (!tmp[id]) { new CMS_Data.TextLoader("TEXT", urlR, function(_text) { tmp[id] = _text; _callback(tmp[id],url); },function(_text){ alert("テンプレートHTMLが見つかりません。URL : " + url); _callback("",url); }); } else { _callback(tmp[id],url); } } /* ---------- ---------- ---------- */ //テンプレートファイル修正時にコールされる。 function update(_id){ if(tmp[_id]){ tmp[_id] = null; } } /* ---------- ---------- ---------- */ //利用できるテンプレート一覧を取得 function loadList(_callback) { var p = "?action=getFileList&dir_name=" + escape_url(CMS_Path.ASSET.REL) + Dic.DirName.TEMPLATE + "/"; var url = CMS_Path.PHP_DIRECTORY + p; $.ajax({ scriptCharset : 'utf-8', type : 'GET', url : url, dataType : 'json', success : function(data) { _loadList_comp(data,_callback)}, error : function(data) { CMS_ErrorView.stageIn("NET",url,null,data); } }) } function _loadList_comp(json,_callback) { if(API_StatusCheck.check(json) == false) return; var files = json.files; var a = []; for (var i = 0; i < files.length ; i++) { var node = files[i]; if(_isFile(node.name)){ // var o = { // dir:this.dirName, // name:node.name // } a.push([this.dirName , node.name ]) } } setTemplateList(a); if(_callback ) _callback(); } function _isFile(_s) { if(_s.indexOf(".") != -1) { return FileU.isEditableFile(_s); } else{ return false; } } //ロードしたリストをセット var templateList = [] function setTemplateList(_a){ templateList = _a; FormCandidates.setTemplateList(_a); } function getList(){ return templateList; } function getSelectList(){ var a = [] a.push(["",Dic.DEFAULT_TEMPLATE+" (デフォルト)",""]) for (var i = 0; i < templateList.length ; i++) { if(templateList[i][1] != Dic.DEFAULT_TEMPLATE){ var ss = templateList[i][1]; a.push([ss,ss,ss]) } } return a } /* ---------- ---------- ---------- */ function treatTemplateName(_o){ var _id = "" try{ _id = _o.template; }catch( e ){} if(_id ==undefined) _id = ""; _id = _id.split(" ").join("") if(_id == ""){ _id = Dic.DEFAULT_TEMPLATE } return _id } /* ---------- ---------- ---------- */ function getTemplateName(_id){ _id = _id.split(" ").join(""); if(_id == undefined) _id = ""; _id = _id.split(" ").join(""); if(_id == ""){ _id = Dic.DEFAULT_TEMPLATE } return _id; } /* ---------- ---------- ---------- */ //ページビューで、テンプレを選択した場合にコールされる function setTemplateName(_o,_tempalte){ if(_o["template"] == undefined){ _o["template"] = "" } _o.template = _tempalte; } /* ---------- ---------- ---------- */ function openTemplate(_data){ if(!_data.meta) _data.meta = {} if(!_data.meta.template) _data.meta.template = Dic.DEFAULT_TEMPLATE; CMS_MainController.openTemplateHTMLFile(_data.meta.template); } /* ---------- ---------- ---------- */ return { init:init, loadList:loadList, load:load, update:update, getList:getList, getSelectList:getSelectList, treatTemplateName:treatTemplateName, getTemplateName:getTemplateName, setTemplateName:setTemplateName, openTemplate:openTemplate } })(); <file_sep>/src/js/cms_util/FileU.js var FileU = (function() { function formatFilesize(_s) { var s = ""; var nn =1000 var sizeKB = _s / nn; if (parseInt(sizeKB) > nn) { var sizeMB = sizeKB / nn; s = "<b>" + sizeMB.toFixed(1) + " MB</b>" ; } else { s = sizeKB.toFixed(1) + " KB"; } return s; } function getFileName(_s){ if(_s.indexOf(".") == -1)return _s; var ss = _s.split(".") ss.pop() return ss.join(".") } function getExtention(_s){ if(_s == null) return ""; var ss = _s.split("."); if(ss.length == 1)return ""; var ex = ss[ss.length-1]; return ex.toLowerCase(); } function isImageFile(_s){ var ex = getExtention(_s.toLowerCase()); if(ex == "gif") return true; if(ex == "jpg") return true; if(ex == "jpeg") return true; if(ex == "png") return true; if(ex == "svg") return true; return false; } // function isEditableFile(_s){ var ex = getExtention(_s.toLowerCase()); if(ex == "html") return true; if(ex == "htm") return true; if(ex == "js") return true; if(ex == "json") return true; if(ex == "css") return true; if(ex == "txt") return true; if(ex == "md") return true; if(ex == "php") return true; if(ex == "shtml") return true; if(ex == "xhtml") return true; if(ex == "xml") return true; if(ex == "rss") return true; if(ex == "pl") return true; if(ex == "asp") return true; if(ex == "cgi") return true; if(ex == "log") return true; return false; } function isPreviewableFile(_s){ var ex = getExtention(_s.toLowerCase()); if(ex == "html") return true; if(ex == "htm") return true; if(ex == "pdf") return true; if(ex == "txt") return true; if(ex == "js") return true; if(ex == "css") return true; return false; } return { formatFilesize: formatFilesize, getFileName:getFileName, getExtention:getExtention, isImageFile:isImageFile, isEditableFile:isEditableFile, isPreviewableFile:isPreviewableFile } })(); <file_sep>/src/js/cms_view_editable/EditableView.BaseTexts.js /** * フォーム入力のリスト * 設定画面や、オブジェクト編集にて、使用される * * EditableView.BaseBlockでのみ使用される * */ EditableView.BaseTexts = (function() { /* ---------- ---------- ---------- */ var c = function(_gridType) { this.init(_gridType); } var p = c.prototype; /* ---------- ---------- ---------- */ this.gridType this.param; // this.view; this.v this.parent; this.gridParam; p.init = function(_gridType) { this.gridType = _gridType; this.v = {} this.setParam(); } p.setParam = function (){ this.gridParam = this.gridType.textData; } /* ---------- ---------- ---------- */ //#registParent p.registParent = function (_parent){ this.parent = _parent; var tag = ''; tag += '<div class="clearfix">'; tag += this.gridParam.info.getHeadTag(); tag += ' <table style="width:100%;"><tr><td width="100%">'; tag += ' <div class="_replaceArea"></div>'; tag += ' <div class="_replaceAreaSummary"></div>'; tag += this.gridParam.info.getFootTag(); tag += ' </td>'; tag += ' <td>' + this.gridParam.info.getGuideImageTag()+ '</td></tr></table>'; tag += '</div>'; this.view = $(tag); this.parent.v.replaceAreaTexts.append(this.view); this.v.head = this.view.find('._head'); this.v.replaceArea = this.view.find('._replaceArea'); this.v.replaceAreaSummary = this.view.find('._replaceAreaSummary'); this.v.replaceAreaSummary.hide(); //イベントアサイン EditableView.InputEvent.assign(this.view,this); } /* ---------- ---------- ---------- */ //#Data p.initData = function(_array) { this.gridData = new EditableView.GridClass(); if (_array == undefined) { this.gridData.initRecords([]); this.addData(); } else { this.gridData.initRecords([_array]); } this.update(); } p.getData = function() { return this.gridData.getRecords()[0]; } p.addData = function() { var o = EditableView.InputU.addData(this.gridParam.cells); this.gridData.addRecord(o); this.update(); this.parent.updateSubData(); } p.changeData = function(data, no) { this.gridData.overrideRecordAt(data, no); this.parent.updateSubData(); } p.removeData = function(no) { // } p.moveData = function(targetNo, _move) { // } /* ---------- ---------- ---------- */ //#update p.update = function (){ var list = this.gridData.getRecords(); this.v.replaceArea.empty().append(EditableView.BaseTextsU.getTextsTag(this.gridParam,list)); } /* ---------- ---------- ---------- */ //#M_GRID時に、タブを開いたときにコールされる p.mGrid_startEditMode = function() { this.v.head.show(); this.v.replaceArea.show(); this.v.replaceAreaSummary.hide(); } p.mGrid_stopEditMode = function() { this.v.head.hide(); this.v.replaceArea.hide(); this.v.replaceAreaSummary.show(); // var list = this.gridData.getRecords(); this.v.replaceAreaSummary.html(EditableView.BaseTextsU.getTextsTagSum(this.gridParam, list)); } return c; })(); <file_sep>/src/js/cms_model/PageModel.OG_Cell.js PageModel.OG_Cell = (function() { /* ---------- ---------- ---------- */ var c = function(_view) { this.init(_view); } var p = c.prototype; /* ---------- ---------- ---------- */ p.param; p.id; p.name; p.type;//入力タイプ p.view; //detail:詳細編集画面の項目, one :マルチグリッド時にサマリーで表示する項目 p.def;//初期値をいれる p.note;//注釈 p.vals;//セレクトボックスのアイテムs p.placeholder; p.list;//候補リスト p.codeType;//フォームのコードの種類。HTML,CSS,JSなど p.style; //p.class_; p.init = function(o) { this.param = o; this.setParam(); } p.setParam = function (){ this.id = defaultVal(this.param.id, "--"); this.name = defaultVal(this.param.name, "-"); this.type = defaultVal(this.param.type, CELL_TYPE.SINGLE); this.view = defaultVal(this.param.view, ""); this.def = defaultVal(this.param.def, ""); this.note = defaultVal(this.param.note, ""); this.list = defaultVal(this.param.list, ""); this.style = defaultVal(this.param.style, ""); //this.class_ = defaultVal(this.param.class_, ""); this.vals = defaultVal(this.param.vals, ["--"]); this.placeholder = defaultVal(this.param.placeholder, ""); // var ts = this.type.split(",") this.type = ts[0] this.codeType = "text"; if(ts[1]){ this.codeType = ts[1]; } } p.getTestTag = function() { var tag = ""; tag += '<tr>'; tag += '<td class="id">' + this.id + '</td>'; tag += '<td class="name">' + this.name + '</td>'; tag += '<td class="type">' + this.type + '</td>'; tag += '<td class="view">' + this.view + '</td>'; tag += '<td class="def">' + this.def + '</td>'; tag += '<td class="note">' + this.note + '</td>'; tag += '<td class="list">' + this.list + '</td>'; tag += '<td class="style">' + this.style + '</td>'; //tag += '<td class="class_">' + this.class_ + '</td>'; tag += '<td class="vals">' + this.vals + '</td>'; tag += '</tr>'; return tag; } return c; })();<file_sep>/src/js/cms_view_imagemap/ImageMap.01.js /* function hideModalView(){ } function showModalView(){ } $(function(){ DummyImageService.init() ImageMapView.init() $(".btn_open").click(function(){ $.ajax({ scriptCharset : 'utf-8', type : 'GET', url : $(this).data("id"), dataType : 'json', success : function(data) { openAA({data:data}) }, error : function(data) {console.log(data);} }) }) $(".btn_open").eq(0).click(); $("._btn_out").click(function(){ window.comp() }) // setTimeout(function(){ // $("._btn_out").click() // },500); }); function openAA(_param){ ImageMapView.stageOut(); ImageMapView.stageIn(_param.data,function(_s){ _param.data = _s; // setTimeout(function(){ // updateCallback(); // }, 200); $(".out").html(ImageMapExport.getHTML(_param.data)); $("#out_html").val(ImageMapExport.getHTML(_param.data)); $("#out_json").val(JSON.stringify(_param.data, null, " ")); }); } */ /* ! ---------- ImageMapView ---------- ---------- ---------- ---------- */ var ImageMapView = (function(){ var view; var v = {}; /* ---------- ---------- ---------- */ //初期化 function init(){ view = $('#ImageMapView'); stageInit(); ImageMapBMPText.init(); } /* ---------- ---------- ---------- */ //レイアウト作成・イベントアサイン var mainStage function createlayout(){ var tag = "" tag += '<div class="_bg"></div>' tag += '<div class="_modalBox">' tag += ' <div class="_header">' tag += ' <div class="_title">イメージブロック / レイアウト編集</div>' tag += ' </div>' tag += ' <div class="_body"></div>' tag += ' <div class="_footer">' tag += ' <div class="_btn_close">閉じる</div> '; tag += ' <div class="_btn_do" '+TIP_ENTER+'><i class="fa fa-check"></i> 編集完了</div> '; tag += ' </div>' tag += '</div>' view.html(tag); v.header = view.find("._header"); v.body = view.find("._body"); v.footer = view.find("._footer"); mainStage = ImageMap.MainStage; mainStage.init(v.body); setBtn(); } /* ---------- ---------- ---------- */ function setBtn(){ view.find('._bg ,._btn_close').click(function(){ stageOut() }); v.btn_do = view.find('._btn_do'); view.on("click", '._btn_do', function() { compliteEdit(); }); } /* ---------- ---------- ---------- */ /* ---------- ---------- ---------- */ /* ---------- ---------- ---------- */ function compliteEdit(){ callback( mainStage.getData(true)); stageOut(); } // window.comp = compliteEdit /* ---------- ---------- ---------- */ //表示・非表示処理 var isOpen = false; var isFirst = true; var callback; function stageInit(){ view.hide(); } function stageIn(_data,_callback){ if(! isOpen){ isOpen = true; showModalView(this); view.show(); callback = _callback; if(isFirst){ createlayout(); CMS_ScreenManager.registResize(function(){ resize(); }); } isFirst = false; // mainStage.setData(_data); resize(); } } function stageOut(){ if(isOpen){ isOpen = false; hideModalView(); view.hide(); ImageMap.InspectView.stageOut() } } function resize(){ if(isOpen){ mainStage.resize(); } } return { init: init, stageIn: stageIn, stageOut: stageOut } })(); <file_sep>/src/js/cms_main/CMS_CheckedView.js var CMS_CheckedView = (function(){ var view; var v = {}; var useLogin = true; function init(){ stageInit(); } /* ---------- ---------- ---------- */ function createlayout(){ //バージョン checkVersion(function(_v){ CMS_ServerStatusFunc.setVersion(_v) //WAFチェック checkWAF(function(){ //書き込み権限チェック checkWritable(function(_s){ if(_s.status == "0")showLoginView(_s); if(_s.status == "1")checked(); }); }) //,function(){ // errorWAF(); // IS_ESCAPE_WAF = true; //}); },function(_s){ errorPHP(_s); }); } function setBtn(){ } function treat(_s){ _s = _s.split("../").join("/"); _s = _s.split("///").join("/"); _s = _s.split("//").join("/"); return _s; } /* ---------- ---------- ---------- */ function errorPHP(_s){ var m = "" m += '<div class="_title">エラーが発生しました<div>' m += '<div>'+_s+'<div>' showError(m); } /* function errorWAF(_s){ var m = '<div class="_title"><i class="fa fa-warning" style="color:red"></i> JS CMS サーバーチェック</div>' m += '<br><div class="_attention">WAF機能はOFFにしてください。</div><br>'; m += 'お使いのウェブサーバーでは、WAF<span class="_small"> (Webアプリケーションファイヤーウォール) </span>機能が有効の可能性があります。<br>'; m += '有効の場合、JS CMSの管理画面は、うまく動作しないため、CMSの設定か、ウェブサーバーの設定を変更していただく必要があります。<br>'; m += '以下の、どちらかの方法で対応してください。<br>' m += '<br>' // m += '<span class="_h">■方法A .haccessを設置</span>'; // m += 'JS CMSの管理画面のみ、WAF機能の一部をOFFにします。<br>'; // m += 'アップロードした_cms/ディレクトリ内の以下のファイルをリネームしてください。<br>'; // m += ' ・変更前:_.htaccess<br>'; // m += ' ・変更後:.htaccess<br>'; // m += '<br>' m += '<span class="_h">■方法A ―― CMS設定ファイルを変更</span>'; m += '設定ファイル <b>/_cms/setting/setting.js</b> の 300行目あたりを以下のように変更してください。<br>'; m += '<div class="_box-sett">'; m += 'var IS_ESCAPE_WAF = false;<br>'; m += ' ↓ 変更<br>'; m += 'var IS_ESCAPE_WAF = true;<br>'; m += '</div>' m += '<span class="_h">■方法B ―― サーバー管理画面で設定</span>'; m += 'レンタルサーバーを利用であれば、各サーバー会社さまの管理画面より、WAF機能をOFFにしてください。<br>'; m += '( OFFにしても、反映されるまで5分〜1時間程度、時間がかかります )<br>'; m += '独自サーバーの場合は、サーバー管理者に相談してください。<br>'; m += '<br>' m += 'JS CMS紹介サイトでは、各レンタルサーバー会社さまごとの、情報を掲載してますので、そちらも参考にしてください。<br>'; m += '<br>' m += '- '+CMS_LINKs.waf; showError(m); } */ function showLoginView(_s) { var m = '<div class="_title"><i class="fa fa-warning color:red"></i> JS CMS サーバーチェック</div>' if(_s.message == CMS_E.DIR_ERROR) { m += 'サイトルート、およびHTML書き出し用ディレクトリに、書き込み権限がありません。<br>' m += 'FTPソフトなどで、以下のディレクトリに対して、<span class="_attention">書き込み権限(707など)</span>を設定してください。<br>' m += '以下のディレクトリが無い場合は、作成してください。<br>' m += 'HTML書き出し用のサブディレクトリも同様に設定してください。' m += '<ul class="_errorList">' var files = _s.extra.split(",") for (var i = 0; i < files.length ; i++) { files[i] = treat( files[i]+"/" ); if(files[i] == "/"){ m += '<li><span class="_icon_dir"></span>/ (サイトディレクトリ)</li>' } else{ m += '<li><span class="_icon_dir"></span>' + files[i] + '</li>' } } m += '</ul>' } showError(m); } function showError(_s) { var tag = ""; tag += '<div id="CMS_CheckedView">'; tag += _s tag += '</div>'; $("body").html(tag); view = $('#CMS_CheckedView'); view.show(); } function checked() { callback(); } function checkVersion(_callback,_callback_e) { $.ajax({ scriptCharset : 'utf-8', type : 'GET', url : "check.php?action=checkVersion" , dataType : 'json', success : function(data) { _callback(data); }, error : function(data) { _callback_e(data.responseText); } }); } function checkWritable(_callback) { var r = "&publish_dir=" + escape_url(ASSET_DIR_PATH); $.ajax({ scriptCharset : 'utf-8', type : 'GET', url : "check.php?action=checkEditable" + r, dataType : 'json', success : function(data) { _callback(data); }, error : function(data) { _callback_e(data.responseText); } }); } function checkWAF(_callback,_callback_e) { var param = {} param.action = 'waf'; param.text = '<script type="text/javascript" src=""></script>' $.ajax({ scriptCharset : 'utf-8', type : 'POST', url : "check.php", data : param, dataType : 'json', success : function(data) { _callback(data); }, error : function(data) { window.IS_ESCAPE_WAF = true; _callback(data); // _callback_e(data.responseText); } }); } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit(){ } var callback = true; function stageIn(_callback){ if(window.IS_CHECK_ENV != true){ _callback(); return; } if(! isOpen){ isOpen = true; callback = _callback if(isFirst){ createlayout(); setBtn(); } isFirst = false; } } function stageOut(){ if(isOpen){ isOpen = false; } } return { init: init, stageIn: stageIn, stageOut: stageOut } })(); <file_sep>/js_cms/_cms/setting/setting.js /* CMS 動作設定 各種ディレクトリパスの変更や、CMSの動作設定が行えます。 設定を変更した場合は、保存したあと、ブラウザをリロードしてください。 ログインアカウントの変更は、setting.phpで設定してください。 */ /* ! ---------- サイト名・リンク設定 ---------- ---------- ---------- ---------- */ /** * 管理画面上でのサイト名 * * 管理画面のヘッダロゴ下に、表示されます。 * 管理するサイトの名称を設定してください。 */ var SITE_NAME = 'サンプルサイト'; /** * 管理画面ヘッダの機能ボタン * * 以下のボタンの表示を設定できます。 * "UPLOAD"...アップロード画面表示 * "BACKUP"...バックアップ画面表示 * "ICON"...アイコン一覧表示 * "EMBED_TAG"...埋め込みタグ一覧表示 * "GRID"...グリッドプレビュー */ var HEADER_TOOL_BTNS = ["UPLOAD", "BACKUP", "ICON", "EMBED_TAG", "GRID"] /** * 管理画面ヘッダのリンク * * 管理画面ヘッダのログアウトボタン横に、自由にテキストやリンクを設定できます。 * 管理するサイト名を表示したり、リンクを設定したりと、汎用的に利用できます。 */ //var HEADER_EXTRA_BTNS = []; var HEADER_EXTRA_BTNS = [ { label:"関連リンク", items:[ '<a href="http://www.yahoo.co.jp" target="_blank">Yahooサイトへ</a>', '<a href="http://www.google.co.jp/" target="_blank">Googleサイトへ</a>' ] } ]; /* ! ---------- ファイルリストリスト設定 ---------- ---------- ---------- ---------- */ /** * Myタグリスト設定 */ var MYTAG_PAGE_LIST = [ {id:"01_template" , name:"UI用(ヘッダなど)"}, {id:"02_parts" , name:"パーツ用"} ]; /** * プリセットリスト設定 */ var PRESET_PAGE_LIST = [ { name:"オリジナル", list:[ { id:"mt_1" , name:"オリジナル"} ] }, { name:"基本ブロック", list:[ { id:"tag_h1" , name:"見出しブロック"}, { id:"tag_p" , name:"文書ブロック"}, { id:"tag_img" , name:"イメージブロック"}, { id:"tag_imgs" , name:"イメージリストブロック"}, { id:"tag_list" , name:"リストブロック"}, { id:"tag_table" , name:"表組みブロック"}, { id:"tag_btn" , name:"ボタンブロック"}, { id:"tag_btns" , name:"ボタンリストブロック"} ] }, { name:"コンテナレイアウト", list:[ { id:"layout_1col_a" , name:"基本コンテナ"}, { id:"layout_1col_b" , name:"画像とテキスト/左"}, { id:"layout_1col_c" , name:"画像とテキスト/右"} ] }, { name:"2段組レイアウト", list:[ { id:"layout_2col_a" , name:"パターンA"}, { id:"layout_2col_b" , name:"パターンB"}, { id:"layout_2col_c" , name:"パターンC"}, { id:"layout_2col_d" , name:"パターンD"} ] }, { name:"3段組レイアウト", list:[ { id:"layout_3col_a" , name:"パターンA"}, { id:"layout_3col_b" , name:"パターンB"}, { id:"layout_3col_c" , name:"パターンC"} ] }, { name:"4段組レイアウト", list:[ { id:"layout_4col_a" , name:"パターンA"}, { id:"layout_4col_b" , name:"パターンB"} ] }, { name:"12分割<br>グリッドレイアウト", list:[ { id:"grid_1" , name:"1分割パターン"}, { id:"grid_2" , name:"2分割パターン"}, { id:"grid_3" , name:"3分割パターン"}, { id:"grid_4" , name:"4分割パターン"}, { id:"grid_5" , name:"均等分割パターン"} ] } ]; /* ! ---------- ディレクトリ・ファイル設定 ---------- ---------- ---------- ---------- */ /** * 公開サイトの各種アセットディレクトリパス * * 共通のJSや、CSS、CMS関連ファイルが配置されているディレクトリを指定します。 * このディレクトリ、およびそのサブディレクトリには、書き込み権限が必要(707など) 。 * ディレクトリ名を変更した場合は、以下のパスも変更してください。 * CMS上の指定で、別のディレクトリにHTMLを書き出すことも可能です。 */ var ASSET_DIR_PATH = "../html/"; /** * 公開ページのデフォルトのディレクトリパス * * 新規ページ作成時に、デフォルトで設定される書出しディレクトリを指定します。 * 値を指定しない場合は、ASSET_DIR_PATHと同じパスが設定されます。 * 例:トップディレクトリに設定する場合 "../" * 例:companyディレクトリに設定する場合 "../company/" */ var DEFAULT_DIR_PATH = "../html/"; /** * デフォルトのファイルアップロードのディレトリパス * * パスを指定し、ディレクトリを作成してください。 * アップロードボタンを押した時に、デフォルトで表示されるディレクトリです。 */ var UPLOAD_DIR_PATH = "../images/"; /** * 管理画面でロードするCSSファイルファイルパス * * 公開サイトで利用している、ページ部分に関係するCSSファイルを指定します。 * 指定すれば、管理画面でもロードを行い、CSSの表示を確認することができます。 * なお、body { color:red; } のような、サイトデザインに影響するCSSファイルを指定すると、 * 管理画面の表示がくずれることがあるので、注意してください。 */ var ASSET_CSS_DIRS = [ "../html/css/cms.css", "../html/css/free.css" ]; /** * バックアック機能の、バックアップファイル(ZIP)のアップロード先のディレトリパス * * パスを指定し、ディレクトリを作成してください。 * ディレクトリには、書き込み権限が必要(707など)です。 * バックアック機能が必要ない場合は、コメントアウトしてください。 */ var BACKUP_DIR_PATH = "../_backup/"; /* ! ---------- そのほか設定 ---------- ---------- ---------- ---------- */ /** * ファイルマネージャを使用する */ var USE_SITE_MANAGER = true; //var USE_SITE_MANAGER = false; /** * 更新ロックを使用する * * 作業ミスで間違えて更新しないように、更新ロックをかけることができます。 * 更新ロックをかけない場合は、falseとします。 */ var USE_EDIT_LOCK = true; //var USE_EDIT_LOCK = false; /** * ページコンテンツ幅の選択値とデフォルト * * ページ編集時のページ横幅の選択値を設定します。 * 配列で設定し、1つめの値がデフォルトとなります。 */ var DEFAULT_PAGE_WIDES = [ 720 , 940 ]; /** * ファイルマネージャ画像サムネイル表示するファイルサイズ上限 * * ファイルマネージャにおいて、画像サムネイル表示を自動で行う時の、上限ファイルサイズの設定です。 * 0.5と指定した場合は、0.5MB以上の画像ファイルは、自動ではプレビューされません。 * ※重い画像をプレビューせず、表示を高速化するための設定です。 */ var FILEMANAGER_PREVIEW_LIMIT_MB = 0.5; /** * ファイルマネージャ画像アップロード最大サイズ * * アップロードする最大サイズ(画像幅と、高さ)のデフォルトを指定します。 * サイズを超える場合は、指定したサイズにリサイズされます。 */ var UPLOAD_IMAGE_MAX_W = 800; var UPLOAD_IMAGE_MAX_H = 600; /** * ビットマップテキスト解像度 * * イメージブロック/レイアウトモードで、テキストアイテムを * ビットマップで出力する場合の解像度を指定。 */ var IMAGE_BLOCK_BMP_ZOOM = 1.5; /** * グリッド編集時のセルの数 * * 指定した数のセルを作成します。 * 数を多くすると、動作が重くなるので注意。最大で20〜30くらいまでが目安です。 */ var GRID_EDIT_MAX_CELL = { TABLE : 15 ,//表組ブロック DATA : 15 //データブロック } /** * グリッド編集時の1ページに表示する最大行数 * * 指定した値を超える場合は、ページネーション ( 1 , 2 , 3 ... ) が追加されます。 * 数を多くすると、動作が重くなるので注意。最大で100くらいまでが目安です。 */ var GRID_EDIT_MAX_ROW = 50; /** * グリッドデータのプレビュー表示時の最大件数 * * 表組みブロックやニュースブロックなどで、編集プレビュー時に * 最大何件まで表示するかを指定します。公開さるページには影響ありません。 */ var GRID_PREVIEW_MAX_ROW = { NEWS : 10, //ニュースブロック TABLE : 20, //表組みブロック CUSTOM : 20, //カスタムリストブロック DATA : 50 //データブロック } /** * まとめて公開で、一度に書き出すファイル件数 * * まとめて書き出し時に、一度のリクエストで公開するファイル件数を設置。 * 1以上の値を設定してください。大きい数を設定すれば、その分、早く書き出せますが、 * 一度に送信できるファイルサイズの上限(ウェブサーバーの設定による)に、ひっかかる場合もあります。 */ var BATCH_EXPORT_COUNT = 5; /** * 使い方ガイドのURLを指定 */ var GUIDE_URL = "http://www.js-cms.jp/"; /** * CSSデザインライブラリのURLを指定 */ var CSS_DESIGN_URL = "http://pixelimage.github.io/js-cms-asset/css/"; /** * SVGライブラリのURLを指定 */ var SVG_LIB_URL = "http://pixelimage.github.io/js-cms-asset/svg/"; /** * ビットマップテキスト一覧のURLを指定 */ var BMP_TEXT_URL = "http://pixelimage.github.io/js-cms-asset/font/"; /** * 管理画面の動作チェック * * 管理画面を表示するにあたり、PHPのバージョンチェック、ディレクトリへの書込み権限チェック、 * WAF機能の有無のチェックを行います。通常はtrueです。 */ var IS_CHECK_ENV = true; //var IS_CHECK_ENV = false; /** * デモモード * * デモモードを設定すると、管理画面で操作しても、データの保存は行われません。 * デモモードにするには、PHP側もデモモード設定する必要があります。 */ //var IS_DEMO = true; var IS_DEMO = false; <file_sep>/src/js/cms_model/PageModel.Object_.js PageModel.Object_ = (function() { /* ---------- ---------- ---------- */ var c = function() { this.init(); } var p = c.prototype; /* ---------- ---------- ---------- */ p.param p.pageType p.pageInfo p.grids p.init = function() { } p.getInitData = function() { //overrdie } p.getPreview = function() { //overrdie return ""; } p.getHTML = function() { //overrdie return ""; } p.getDefData = function(_n) { var _param = {} for (var i = 0; i < this.grids.length ; i++) { this.grids[i].getInitData(_param,_n); } return _param; } p.getTestTag = function() { var infoTag = this.pageInfo.getTestTag(); var gridTag = "" var list = this.grids; for (var i = 0; i < list.length; i++) { gridTag += list[i].getTestTag() } var tag = "" tag += infoTag tag += gridTag return tag; } return c; })(); <file_sep>/src/js/cms_stage_asset/CMS_AssetStageResizeView.js var CMS_AssetStageResizeView = (function(){ var view; var v = {}; /* ---------- ---------- ---------- */ //初期化 function init(){ view = $('#CMS_AssetStageResizeView'); view.hide(); var tag = "" tag += '<div class="_bar"></div>' tag += '<div class="_bar2"></div>' view.html(tag); view.draggable({ axis: "y" }); view.on( "drag", function( event, ui ) { resizeH(ui.position.top); }); CMS_AssetStage.registResize(function(){ view.css("top", CMS_StatusH - CMS_AssetStage.getH()); }) } var tID_resizeW; function resizeWindow(){ if(tID_resizeW) clearTimeout(tID_resizeW); tID_resizeW = setTimeout(function(){ view.css("top", CMS_StatusH - CMS_AssetStage.getH()); },100); } var tID_resizeH; function resizeH(_y){ if(tID_resizeH) clearTimeout(tID_resizeH); tID_resizeH = setTimeout(function(){ CMS_StageController.offsetY(_y); },33); } /* ---------- ---------- ---------- */ //表示・非表示処理 var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } function stageIn(){ if(! isOpen){ isOpen = true; view.show(); if(isFirst){} isFirst = false; resizeWindow(); } } function stageOut(){ if(isOpen){ isOpen = false; view.hide(); } } return { init: init, stageIn: stageIn, stageOut: stageOut } })();<file_sep>/src/js/cms_model/PageElement.object.js PageElement.object = {} <file_sep>/js_cms/_cms/check.php <?php /** * JS_CMS -- realtime website development web application * http://js-cms.jp/ * Copyright 2015 <NAME> - <EMAIL> * licensed under the MIT licenses. */ define('CMS', true); require_once("./setting/setting.php"); require_once("./storage.funcs.php"); /* ! ---------- pre ---------- ---------- ---------- ---------- */ if($_GET["action"] == "info"){ phpinfo(); exit(); } /* ! ---------- pre ---------- ---------- ---------- ---------- */ header("Content-Type: application/json; charset=utf-8"); /* ! ---------- input ---------- ---------- ---------- ---------- */ $action = getVAL("action","",""); if($action == "") status_error("invalid action name"); if(! is_action($action)) status_error("invalid action name"); /* ! ---------- ---------- ---------- ---------- ---------- */ if($action == "checkVersion"){ echo('{"phpversion":"'.phpversion().'"}'); exit(); } if($action == "waf"){ echo('{"result":"' + $_POST["text"] + '"}'); exit(); } if($action == "checkEditable"){ $publish_dir = getVAL("publish_dir","","dir"); $eList = array(); if(isWritableDir("../") == false){ array_push($eList ,"../"); } if(isWritableDir($publish_dir) == false){ array_push($eList ,$publish_dir); } $dir = opendir($publish_dir); while($filename = readdir($dir)){ if($filename == '.' || $filename == '..') continue; $path = $publish_dir.$filename; if(is_dir($path)){ if(isWritableDir($path) == false) { array_push($eList ,$path); } } } closedir($dir); if(count($eList) == 0){ status_success(); } else { status_error_dir(implode(",", $eList)); } } status_error(""); exit(); <file_sep>/src/js/cms_main/NO_CMSView.js var NO_CMS = (function(){ var view; var v = {}; function init(){ stageInit(); } /* ---------- ---------- ---------- */ function createlayout(){ var tag = ""; tag += '<div id="NO_CMS">'; tag += ' <div class="_title">'+ SITE_NAME +'</div>'; tag += ' <div>お使いのブラウザでは、CMSの管理画面はご利用いただけません。</div>'; tag += ' <div>管理画面を利用するには、以下のブラウザをお使いください。</div>'; tag += ' <div>※モバイル端末は対応していません。</div>'; tag += ' <div class="_h2">対応ブラウザ</div>'; tag += ' <ul>'; tag += ' <li><span style="font-size:24px;"><b>Google Chrome</b></span> <i class="fa fa-caret-right "></i> <a href="http://www.google.co.jp/chrome">ダウンロード画面へ</a></li>'; tag += ' <li><span style="font-size:24px;"><b>Internet Explorer 9,10,11</b></span></li>'; tag += ' </ul><br><br>'; tag += ' <div><i class="fa fa-info-circle"></i> <a href="http://js-cms.jp/" target="_blank">JS CMSの紹介サイト</a></div>' tag += '</div>'; $("body").html(tag); } function setBtn(){ } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit(){ } function stageIn(){ if(! isOpen){ isOpen = true; if(isFirst){ createlayout(); setBtn(); } isFirst = false; } } function stageOut(){ if(isOpen){ isOpen = false; } } return { init:init, stageIn:stageIn, stageOut:stageOut } })();<file_sep>/src/js/cms_stage_asset/CMS_Asset_FileListClass_List.js var CMS_Asset_FileListClass_List = (function() { /* ---------- ---------- ---------- */ var c = function(_parent,_view,_path) { this.init(_parent,_view,_path); } var p = c.prototype; /* ---------- ---------- ---------- */ p.view; p.v; p.init = function(_parent,_view,_path) { this.parent = _parent; this.view = _view; this.targetDir = _path; this.v = {} this.createlayout() this.stageInit() } /* ---------- ---------- ---------- */ p.createlayout=function(){ var self = this; var tag = ""; tag += '<div class="_replaceArea"></div>' // tag += '<div class="_update"></div>' this.view.append(tag) this.v.replaceArea = this.view.find('._replaceArea'); this.v.update = this.view.find('._update'); this.view.on("click","._btn_file",function(){ self.clickFile($(this).data("name")); }) this.view.on("dblclick","._btn_file",function(){ self.dClickFile($(this).data("name")); }) // this.view.on("click","._btn_add",function(){ // self.addFile2page($(this).data("name")); // }) } /* ---------- ---------- ---------- */ p.list p.updateTime p.updateViewTime p.update = function(_list,_updateTime) { var self = this; if(_list == undefined) return; this.updateTime = _updateTime; this.list = _list; if (!this.openFlg) return; if (!this.updateTime) return; if(this.updateTime == this.updateViewTime) return; this.updateViewTime = this.updateTime; this.v.update.html(CMS_Asset_FileListU.getUpdateTime(this.updateTime)); var tag = "" tag += '<table class="_filelist">' if(this.list["nodes"]){ var dirs = this.list.nodes.nodes; dirs.sort(function(a, b){ return ( a.name > b.name ? 1 : -1); }); for (var i = 0; i < dirs.length ; i++) { var node = dirs[i] var cnt = Number(node.dirCount) + Number(node.fileCount); var temp = ''; temp += '<tr class="_row_dir">' temp += ' <td><div class="_btn_dir" data-path="{PATH_ABS}" data-path_rel="{PATH}"><span class="{DIR_ICON}"></span> {NAME}{CNT}</div></td>'; temp += ' <td width="50" class="_hideNarrow _date">{UPDATE}</td>' temp += ' <td width="50" class="_hideNarrow _size"></td>' temp += ' <td width="100" class="_hideNarrow">'; temp += ' <div class="_btn_rename _btn_rename_dir" data-path="{PATH}" data-name="{NAME}"><i class="fa fa-wrench "></i> リネーム</div>' temp += ' <div class="_btn_del _btn_del_dir" data-path="{PATH}"><i class="fa fa-trash "></i></div>' temp += ' </td>'; temp += '</tr>' temp = temp.split("{DIR_ICON}").join((Number(node.dirCount)) ? '_icon_dir_has_sub':'_icon_dir_no_sub'); temp = temp.split("{CNT}").join( (cnt == 0) ? "" : '<span class="_cnt">'+ cnt+'</span>'); temp = temp.split("{NAME}").join(node.name); temp = temp.split("{PATH}").join(node.path); temp = temp.split("{PATH_ABS}").join(node.path.split("../").join("")); temp = temp.split("{UPDATE}").join(CMS_SaveDateU.getRelatedDate(node.filemtime)); tag += temp } } if(this.list["files"]){ var files = this.list.files; files.sort(function(a, b){ return ( a.name > b.name ? 1 : -1); }); if(files.length > 0){ for (var i = 0; i < files.length ; i++) { var node = files[i]; var name_ = node.name; var ex = CMS_AssetFileU.getExtention(name_); var cs = ["_btn_file"] ; // var isClickable = CMS_AssetFileU.isExtentionAll(ex); // var isEdtable = CMS_AssetFileU.isExtention(ex,"editable"); // if(isClickable) cs.push("_btn_file"); var temp = ''; temp += '<tr class="_row_file" id="{ID}">' temp += ' <td><div class="{CLASS}" data-name="{NAME}">{ICON} {NAME}</div></td>' // temp += ' <td width="50" class="_hideNarrow" ><div class="_btn_add" data-name="{NAME}"><i class="fa fa-arrow-up"></i> 配置</div></td>' temp += ' <td width="50" class="_hideNarrow _date">{UPDATE}</td>' temp += ' <td width="50" class="_hideNarrow _size">{SIZE}</td>' temp += ' <td width="100" class="_hideNarrow">'; temp += ' <div class="_btn_rename _btn_rename_file" data-path="{PATH}" data-name="{NAME}"><i class="fa fa-wrench "></i> リネーム</div>' temp += ' <div class="_btn_del _btn_del_file" data-path="{PATH}"><i class="fa fa-trash "></i></div>' temp += ' </td>'; temp += '</tr>' temp = temp.split("{ID}").join( this.getID( node.name )); temp = temp.split("{NAME}").join(node.name); temp = temp.split("{PATH}").join(node.path); temp = temp.split("{PATH_ABS}").join(node.path.split("../").join("")); temp = temp.split("{UPDATE}").join(CMS_SaveDateU.getRelatedDate(node.filemtime)); temp = temp.split("{SIZE}").join(FileU.formatFilesize(node.filesize)); temp = temp.split("{CLASS}").join(cs.join(" ")); temp = temp.split("{ICON}").join(CMS_AssetFileU.getFileIcon(ex)); tag += temp; } tag += "</table>" tag += '<div class="_note">ダブルクリックすると、ファイルをボタンブロックとして、ページへ配置できます。<br>画像の場合は、画像ブロックとして配置されます。</div>' } } this.v.replaceArea.html(tag); this.isLoaded = this; if(this.loadedCallback) { this.loadedCallback(); this.loadedCallback = null; } } /* ---------- ---------- ---------- */ p.loadedCallback p.isLoaded = false; p.selectFile = function(_param){ this.loadedCallback = null var self = this; if(this.isLoaded){ self.selectFile_core(_param); } else{ this.loadedCallback = function(){ self.selectFile_core(_param); } } } p.selectFile_core = function(_param){ var files = this.list.files; for (var i = 0; i < files.length ; i++) { if(files[i].path == _param.dir + _param.id ){ if(_param.extra){ this.clickFile(files[i].name,_param.extra); } else { this.clickFile(files[i].name); } } } } // p.addFile2page = function(_id){ // CMS_AssetStage.addFile2page(this.targetDir + _id); // } p.clickFile = function(_id,_extra){ var param = { dir: this.targetDir, id: _id } if(_extra) param.extra = _extra; CMS_Asset_FileDetailView.stageIn(param); CMS_Asset_FileListView.resetSelect(param); this.view.find("#" + this.getID(_id)).addClass("_current"); } p.dClickFile = function(_id,_extra){ CMS_AssetStage.addFile2page(this.targetDir + _id); } /* ---------- ---------- ---------- */ p.getID = function(_id){ return "_asset_" + CMS_AssetDB.getID( _id,this.targetDir ); } /* ---------- ---------- ---------- */ /**/ p.openFlg = false; p.stageInit=function(){ this.openFlg = false this.view.hide() } p.stageIn=function( ) { if (! this.openFlg) { this.openFlg = true; this.view.show(); this.loadedCallback = null; this.update(this.list,this.updateTime); } } p.stageOut=function( ) { if (this.openFlg) { this.openFlg = false this.view.hide() } } return c; })();<file_sep>/src/js/cms_main/CMS_History.js var CMS_History = (function(){ var view; var v = {}; function init(){ document.title = SITE_NAME; try{ window.addEventListener('popstate', function(e) { if(e.state == null )return; openPage(e.state); },false); window.addEventListener('hashchange', function() { if(!openBlock){ var state = window.location.hash; CMS_MainController.openPage_by_hash(state); } },false); }catch( e ){} } function getInitParam(){ var state = window.location.hash; state = "/" + state.split("#").join(""); return CMS_Path.PAGE.getAbsPath_reverse(state); } var openBlock = false function openPage(_state){ if(openBlock == false){ openBlock = true; openPage_core(_state); setTimeout(function(){ openBlock = false; },100); } } function openPage_core(_state){ var state = CMS_Path.PAGE.getAbsPath_reverse(_state); var param = CMS_Data.Sitemap.getData_by_id(state.id,state.dir); if(param){ CMS_MainController.openPage(param,false); } } function addPage(_param){ var dir = "" var id = _param.id if(_param["dir"] != undefined) dir = _param.dir; var state = CMS_Path.PAGE.getAbsPath(id,dir); var name = _param.name; //myタグページ調整 if(_param.type == Dic.PageType.CMS_MYTAG){ state = CMS_Path.PAGE.ABS + state; state = state.split("//").join("/"); name = "{{Myタグ設定}} " + name; } var hash = state; if(hash.charAt(0) == "/") hash = state.substr(1,state.length) document.title = (function(_param){ if(name == undefined){ return CMS_INFO.name + " : " + _param.id; // return CMS_INFO.name + " : " + _param.id; } else{ return SITE_NAME + " : " + name; } })(_param); if(history["pushState"]){ history.pushState(state, null, "#" +hash); } } return { init: init, getInitParam: getInitParam, addPage: addPage } })(); <file_sep>/src/js/cms_view_modals/BatchQueueControllClass.js //バッチ用のキューコントローラ var BatchQueueControllClass = (function() { /* ---------- ---------- ---------- */ var c = function(_a,_row) { this.init(_a,_row); } var p = c.prototype; /* ---------- ---------- ---------- */ p.max p.current p.callback p.interval p.init = function(_a,_row){ this.list = []; var row = _row; var pages = [] this.max = Math.ceil(_a.length / row); for(var i = 0; i < this.max; i++) { var n = i * row; var p = _a.slice(n, n + row); pages.push(p); } for (var i = 0; i < pages.length ; i++) { this.list.push(new BatchPublishPagesQueueClass(i,pages[i])) } } p.isLive p.stop = function() { clearInterval(this.tID); this.isLive = false; } p.start = function(_interval,_callbackOne,_callbackAll) { this.callbackOne = _callbackOne; this.callbackAll = _callbackAll; this.interval = _interval; this.isLive = true; this.current = 0; this.next() } p.next = function() { if(this.isLive == false) return; var this_ = this; this.callbackOne(this.current,this.list[this.current]); this.list[this.current].queue(function(){ this_.nexted() }) } p.nexted = function() { this.current++; if(this.current > this.max-1){ this.callbackAll(); } else{ this.next_pre() } } p.tID p.next_pre = function() { var this_ = this; if(this.interval == 0){ this.next() } else{ this.tID = setTimeout(function(){ this_.next() },this.interval); } } return c; })(); <file_sep>/src/js/cms_util/CMS_TemplateU.js var CMS_TemplateU = (function(){ function getTemplateHTML(_s){ if(!_s)return ["","",""] var a = _s.split("{REPEAT_START}") if (a.length == 1) return ["", "", ""]; var b = a[1].split("{REPEAT_END}") if (b.length == 1) return ["", "", ""]; return [a[0], b[0], b[1]]; } /* ---------- ---------- ---------- */ function doTemplate(_param){ var list = _param.list; var leng = _param.leng; var isPub = _param.isPub; var isEdit = _param.isEdit; var id,htmls,css; try{ id = _param.id; htmls = CMS_TemplateU.getTemplateHTML(_param.htmls.split("{ID}").join(id) ); css = _param.css.split("{ID}").join(id); }catch( e ){} var tag = ""; //CSS if(isEdit){ tag += getDefCSSTag(); } tag += getStyleTag(css); //HTML or JS if(isJS(_param.htmls)){ //JS try{ tag += eval(_param.htmls)(list,id,isPub); }catch( e ){ return "JavaScriptの構文エラーです。" } } else { //HTML tag += htmls[0]+"\n" for (var i = 0; i < leng ; i++) { var tempText = htmls[1]; for (var ii = 0; ii < 10 ; ii++) { var data = CMS_TagU.t_2_tag(list[i]["a"+ii]); if(!data) data = ""; tempText = tempText.split("{"+ii+"}").join(data); } if(isEdit){ tempText = tempText.split(CONST.SITE_DIR).join(""); } if(list[i]["anchor"]){ tempText = replaceLinkTag(list[i].anchor,tempText); } tempText = removeLinkTag(tempText); var img = list[i]["image"]; var imgTag = CMS_ImgBlockU.getImageTag({ path : img.path, isPub : isPub, // width : "100%", width : img.width,//20161220 ratio : img.ratio, alt : "", attr : "" }); tempText = tempText.split("{IMG}").join(imgTag); tag += tempText; } tag += htmls[2]+"\n"; } return tag; } /* ---------- ---------- ---------- */ function getDefCSSTag(){ var tag = "" for (var i = 0; i < ASSET_CSS_DIRS.length ; i++) { tag +=('<link rel="stylesheet" class="asset" type="text/css" href="'+ ASSET_CSS_DIRS[i]+'" />\n'); } return tag; } function getStyleTag(_css){ var tag = ""; if(_css != ""){ tag += '<style type="text/css">\n' tag += _css + "\n"; tag += '</style>\n\n'; } return tag; } function replaceLinkTag(anchor,s){ if(anchor){ if(isFilledText(anchor)){ s = s.split("{LINK}").join(CMS_TagU.getLinkTag_data(anchor)); // if(isFilledText(anchor.href)){ s = s.split("{LINK.href}").join(CMS_Path.MEDIA.getAnchorPath(anchor.href)) } if(isFilledText(anchor.target)){ s = s.split("{LINK.target}").join(anchor.target) } } } return s; } function removeLinkTag(s){ s = s.split("{LINK}").join(""); s = s.split("{LINK.href}").join(""); s = s.split("{LINK.target}").join(""); return s; } function isJS(_s){ if(_s.indexOf("(function") == 0){ return true; } else{ return false; } // if(_param.htmls.indexOf("(function") == 0){ } return { getTemplateHTML:getTemplateHTML, doTemplate:doTemplate, isJS:isJS } })(); if(window._cms == undefined) window._cms = {} window._cms.getImageTag = function(_data,_isPub){ var img = _data.image return CMS_ImgBlockU.getImageTag({ path : img.path, isPub : _isPub, width : "100%", ratio : img.ratio, alt : "", attr : "" }); } <file_sep>/src/js/cms_view_editable/EditableView.PageView.js EditableView.PageView = (function() { /* ---------- ---------- ---------- */ var c = function(_pageModel,_data,_parentView) { this.init(_pageModel,_data,_parentView); } var p = c.prototype; /* ---------- ---------- ---------- */ p.init = function(_pageModel,_data,_parentView) { this.v = {}; this.v.parentView = _parentView; this.id = _pageModel.id; this.dir = _pageModel.dir; this.gloupPath = _pageModel.gloupPath; this.name = _pageModel.name; this.type = _pageModel.type; this.storage = _data; this.restoreJsonData = this.storage.exportJSON(); } /* ---------- ---------- ---------- */ p.createView =function(){ var this_ = this; //メインビュー var param = { id : this.id, dir : this.dir, name : this.name ,type:this.type}; this.view = EditableView.PageView_U.getMainView(param); this.v.parentView.append(this.view); this.v.replaceArea = this.view.find('> ._page_inner ._replaceRootArea'); this.v.pageStateArea = this.view.find('._page_state'); this.v.footerF1 = this.view.find('._page_footer ._f1'); this.v.footerF2 = this.view.find('._page_footer ._f2'); this.v._page_zooms = this.view.find('._page_zooms'); this.v._page_zooms.show(); if(this.type == Dic.PageType.PRESET){ CMS_PresetView_ZoomManager.setView(this.v._page_zooms); } else{ CMS_PagesView_ZoomManager.setView(this.v._page_zooms); } //データ・セット this.freeLayout = new EditableView.FreeLayout(); this.freeLayout.registParent(this, this.v.replaceArea, param, 0); this.stageInit(); this.setBtn(); this.initData(); } /* ---------- ---------- ---------- */ p.setBtn =function (){ var this_ = this; this.v.page_header = this.view.find('._page_header'); this.v.saveDate = this.view.find('._page_header ._saveDate span'); this.v.publicDate = this.view.find('._page_header ._publicDate span'); this.v.f_saveDate = this.view.find('._page_footer ._saveDate span'); this.v.f_publicDate = this.view.find('._page_footer ._publicDate span'); this.v.btn_preview = this.view.find('._btn_preview'); this.v.btn_preview_more = this.view.find('._btn_preview_more'); this.v.btn_previewing = this.view.find('._btn_previewing'); this.v.btn_save = this.view.find('._btn_save'); this.v.btn_save_pre = this.view.find('._btn_save_pre'); this.v.btn_saveing = this.view.find('._btn_saveing'); this.v.btn_public = this.view.find('._btn_public'); this.v.btn_publishing = this.view.find('._btn_publishing'); this.v.btn_public_more = this.view.find('._btn_public_more'); this.v.btn_preview .click(function(){ this_.previewDataEx(); }); this.v.btn_preview_more .click(function(){ this_.windowOpenPreview(); }); this.v.btn_save .click(function(){ this_.saveData(); }); this.v.btn_save_pre .click(function(){ this_.saveData(); }); this.v.btn_public .click(function(){ this_.publicData(); }); this.v.btn_public_more .click(function(){ this_.openURL()}); this.v.btn_save_pre.hide(); this.v.btn_template_edit = this.view.find('._btn_template_edit'); this.v.btn_template_edit.click(function(){ CMS_Data.Template.openTemplate(this_.storage.getData()); }); this.v.btn_import = this.view.find('._btn_import'); this.v.btn_import.click(function(){ this_.importJSON()}); this.v.btn_tagAll = this.view.find('._btn_tagAll'); this.v.btn_tagAll.click(function(){ HTMLService.generateHTML( this_.storage.getData(), { id : this_.id, dir : this_.dir, gloupPath: this_.gloupPath }, function(_s){ Editer_TAGView.stageIn(_s), function(){} }) }); this.v.btn_tag = this.view.find('._btn_tag'); this.v.btn_tag.click(function(){ var s = this_.storage.getData().body.free[0]; if(s.data.length == 0 ){ alert("要素が見当たりません"); return; } Editer_TAGView.stageIn( PageElement_HTMLService.getTag(s,"",0), function(_s){} ) }); //ホバーサブメニュー new CMS_UtilClass.HoverMenu(this.view.find('._page_header ._page_state'),"._templatesFloat"); new CMS_UtilClass.HoverMenu(this.view.find('._page_header ._float_item'),"._float_fuki"); //new CMS_UtilClass.HoverMenu(this.view.find('._page_header ._save_wapper'),"._float_fuki"); new CMS_UtilClass.HoverMenu(this.view.find('._page_header ._float_pub'),"._float_fuki"); // //コンテナ開閉 this.v.btn_open_all = this.view.find('._btn_open_all'); this.v.btn_open_all.click(function(){ this_.view.find("._block_toggle_close").click(); }); this.v.btn_close_all = this.view.find('._btn_close_all'); this.v.btn_close_all.click(function(){ this_.view.find("._block_toggle:not(._block_toggle_close)").click(); }); this.v.pageSideBtnsArea = this.view.find('._page_side_btns'); //extra menu this.initRevision(); this.pageResetInit(); this.pageCopyInit(); } /* ---------- ---------- ---------- */ p.openURL =function (_type){ if(_type == undefined) _type = ""; var u = CMS_Path.PAGE.getRelPath(this.id,this.dir,_type); CMS_U.openURL_blank(u); } /* ---------- ---------- ---------- */ //#データ p.initData =function (){ this.v.replaceArea.html("");//IO用にリセット this.rootData = this.storage.getData(); if(this.rootData.head == undefined){ this.rootData = { meta:{} , head:{} , body:{} } } this.headData = this.rootData.head; this.gridsData = this.rootData.body; var list; if(! this.gridsData["free"]){ list = JSON.parse(JSON.stringify(PageTypeList.page.grids[0].gridInfo.def)); // try{ // list[0].data[0].data.main.text = this.name; // }catch( e ){} } else{ list = this.gridsData["free"]; } this.freeLayout.initData(list[0],0); this.isInited = true; this.updateMetaView(); this.updateDateView(); this.initSaveBtn(); this.initPubingBtn(); this.historyInit(); } /* ---------- ---------- ---------- */ p.updateMetaView =function (){ var self = this; if(!this.rootData.meta) this.rootData.meta = {} var _current = CMS_Data.Template.treatTemplateName(this.rootData.meta); var _tag = CMS_Data.Sitemap.getGloupState_by_id(_current); if(_tag != this.currentStateTag){ this.v.pageStateArea.html(_tag); this.currentStateTag = _tag; this.v.pageStateArea.find("._item").click(function(){ CMS_Data.Template.setTemplateName(self.rootData.meta,$(this).data("id")); self.updateMetaView(); self.activeSaveBtn(); }); } } p.currentSaveDateText = ""; p.currentPubDateText = ""; p.currentStateTag = ""; p.updateDateView =function (_isAutoUpdate){ var sd = CMS_Data.Sitemap var _save = sd.getSaveDate(this.id,this.dir); var _saveS = CMS_SaveDateU.getRelatedDate(_save) if(this.currentSaveDateText != _saveS){ this.v.saveDate .html(_saveS); this.v.f_saveDate .html(_save); this.currentSaveDateText = _saveS } var _pub = sd.getPublishDate(this.id,this.dir); var _pubS = CMS_SaveDateU.getRelatedDate(_pub) if(this.currentPubDateText != _pubS){ this.v.publicDate .html(_pubS); this.v.f_publicDate .html(_pub); this.currentPubDateText = _pubS } if(!_isAutoUpdate){ if(!this.rootData.meta)this.rootData.meta = {} var _template = CMS_Data.Template.treatTemplateName(this.rootData.meta); var o = { save : _save, pub : _pub, dir : this.dir, id : this.id, template: _template } this.v.footerF1.html(EditableView.PageView_U.updateFooterTag1(o)); this.v.footerF2.html(EditableView.PageView_U.updateFooterTag2(o)); } } /* ---------- ---------- ---------- */ //リビジョン p.initRevision =function (){ var self = this; this.revision = new EditableView.PageView_Revision( this.storage, this.view.find('._page_header ._save_wapper') ); this.revision.registEvent("selectCurrent" , function(_d){ self.selectRevision(_d); }); this.revision.registEvent("selectCurrentPre", function( ){ self.selectCurrentPreRev(); }); this.revision.registEvent("selectHistory" , function(_d){ self.selectRevision(_d); }); } p.selectCurrentPreRev = function (){ this.v.replaceArea.hide().fadeIn(200); this.restoreJSON(); } p.selectRevision = function (_s){ this.v.replaceArea.hide().fadeIn(200); this.setJSONData(_s); } p.saved_revision = function (){ this.revision.saved(); } /* ---------- ---------- ---------- */ /* ---------- ---------- ---------- */ /* ---------- ---------- ---------- */ //#Save Preview p.isSaveingProccess = false; p.saveData =function (_isPreview){ if(window.isLocked(true))return; // if(this.isSaveingProccess)return; this.isSaveingProccess = true; // this.activeSaveingBtn(); this.updateRootData(); var this_ = this; this.storage.setData(this.rootData); this.storage.save(function(){ this_.saveData_comp() }); } p.saveData_comp = function (){ this.updateDateView(); this.disableSaveBtn(); CMS_MainController.savedPage(this.id,this.dir); // this.saved_revision(); } /**/ p.isPublicProccess = false; p.publishData =function (){ this.publicData(); } p.publicData =function (){ if(window.isLocked(true))return; // if(this.isPublicProccess)return; this.isPublicProccess = true; // this.activePubingBtn(); var this_ = this; this.storage.publicData(function(){ this_.publicData_comp() }); } p.publicData_comp = function (){ this.updateDateView(); this.disablePubingBtn(); //this.pageModel.published(); CMS_MainController.publishedPage(this.id,this.dir); } p.unPublicData =function (){ if(window.isLocked(true))return; var this_ = this; this.storage.unPublicData(function(){ CMS_MainController.unPublishedPage(this.id,this.dir); }); this.updateDateView(); } p.updateRootData=function (){ this.rootData.body.free = [{ type: "layout.div", attr: {}, data: this.freeLayout.getData() }] } /* ---------- ---------- ---------- */ //#livePreview //なにかしらビューを操作したらコールされる p.tID p.isPreviewed p.previewData =function (_callback){ var this_ = this this.previeCallback = _callback this.updateRootData(); this.storage.setData(this.rootData); this.storage.previewData(function(){ this_.previeCallback(); }); } p.isPreviewProccess = false; p.previewDataEx =function (){ if(this.isPreviewProccess)return; var this_ = this; this.isPreviewProccess = true; this_.v.btn_previewing.show(); this.previewData(function(){ this_.previewDataEx_comp(); }) } p.previewDataEx_comp =function (){ var this_ = this; setTimeout(function(){ this_.isPreviewProccess = false; this_.v.btn_previewing.hide(); this_.v.btn_preview_more.addClass("_hilight"); setTimeout(function(){ this_.v.btn_preview_more.removeClass("_hilight"); },200); },200); } p.windowOpenPreview =function (){ var url = CMS_Path.PAGE.getRelPath(this.storage.id,this.storage.dir); var f = CMS_Path.ASSET.REL + CMS_Path.PREVIEW_HTML; var p = "" p += "?p=" + DateUtil.getRandamCharas(10); p += "&url=" + url; CMS_U.openURL_blank(f + p,f); } /* ---------- ---------- ---------- */ //#JSON p.pageResetInit =function (){ var this_ = this this.v.btn_undo = this.view.find('._btn_undo'); this.v.btn_reset = this.view.find('._btn_reset'); this.v.btn_restore = this.view.find('._btn_restore'); // this.v.btn_restore_ng = this.view.find('._btn_restore_ng'); this.v.btn_undo.click(function(){ this_.historyBack()}); this.v.btn_reset.click(function(){ this_.resetJSON()}); this.v.btn_restore.click(function(){ this_.restoreJSON()}); // this.v.btn_restore.hide(); } p.setJSON =function (_s){ var s = _s; try{ JSON.parse(_s); }catch( e ){ alert("データ形式が正しくありません。") s = PageElement_JText.resetJSON }; this.storage.importJSON(s); this.refreshAllData(); this.disableSaveBtn(); // this.v.btn_restore.hide() // this.v.btn_restore_ng.show() } p.restoreJSON =function (){ var s = this.restoreJsonData; this.setJSON(s) } p.resetJSON =function (){ var o = JSON.parse(PageElement_JText.resetJSON); try{ o.meta = this.rootData.meta; o.head = this.rootData.head; }catch( e ){} this.storage.importJSON(JSON.stringify(o)); this.refreshAllData(); this.activeSaveBtn(); } p.importJSON =function (){ var this_ = this; Editer_JSONView.stageIn( this.getJSONData(), function(_s){ this_.setJSONData(_s) } ); } p.getJSONData =function (){ return this.storage.exportJSON() } p.getJSONDataFlat =function (){ return this.storage.exportJSON_flat() } p.setJSONData =function (_s){ try{ var d = JSON.parse(_s); }catch( e ){ alert("データ形式が正しくありません。") return false; }; if(_s != null){ this.storage.importJSON(_s); this.refreshAllData(); this.activeSaveBtn(); return true; } } /* ---------- ---------- ---------- */ p.refreshAllData =function (){ this.initData(); } p.updateSubData =function(){ if(this.isInited == undefined)return; if(this.isInited == false)return; this.activeSaveBtn(); CMS_MainController.editedPage(this.id,this.dir); this.setHistory(); // this.v.btn_restore.show() // this.v.btn_restore_ng.hide() } /* ---------- ---------- ---------- */ //ショートカットキー用 p.current = ""; p.history = ""; p.historyInit =function(){ var s = this.getJSONDataFlat(); this.current = s; this.history = s; } p.historyTID p.setHistory =function(){ var self = this; if(this.historyTID) clearTimeout(this.historyTID); this.historyTID = setTimeout(function(){ self.setHistory_core(); },400); } p.setHistory_core =function(){ var s = this.getJSONDataFlat(); if(this.current != s){ this.history = this.current; this.current = s; } } p.historyBack =function(){ this.setJSONData(this.history); } /* ---------- ---------- ---------- */ //#保存ボタン表示 p.initSaveBtn =function(){ this.disableSaveBtn(true) } p.activeSaveBtn =function(){ this.v.btn_save.hide(); this.v.btn_save_pre.show(); this.v.btn_saveing.hide(); } p.activeSaveingBtn =function(){ this.v.btn_saveing.show(); // this.v.btn_saveingF.show(); } p.disableSaveBtn =function(_b){ var this_ = this; if(_b){ this.disableSaveBtn_core() } else{ setTimeout(function(){ this_.disableSaveBtn_core() },500); } } p.disableSaveBtn_core =function(){ this.isSaveingProccess = false; this.v.btn_save.show(); this.v.btn_save_pre.hide(); this.v.btn_saveing.hide(); } //pub p.initPubingBtn =function(){ this.disablePubingBtn(true) } p.activePubingBtn =function(){ this.v.btn_publishing.show() } p.disablePubingBtn =function(_b){ var this_ = this; if(_b){ this_.disablePubingBtn_core(false); } else{ setTimeout(function(){ this_.disablePubingBtn_core(true); },500); } } p.disablePubingBtn_core =function(_b){ var this_ = this; this.isPublicProccess = false; this.v.btn_publishing.hide(); if(_b){ this_.v.btn_public_more.addClass("_hilight"); setTimeout(function(){ this_.v.btn_public_more.removeClass("_hilight"); },200); } } /* ---------- ---------- ---------- */ //ページコピペ p.pageCopyTID p.pageCopyInit =function (){ var this_ = this this.v.btn_pageUnPub = this.view.find('._btn_pageUnPub'); this.v.btn_pageCopy = this.view.find('._btn_pageCopy'); this.v.btn_pagePaste = this.view.find('._btn_pagePaste'); this.v.btn_pageCopy_message = this.view.find('._btn_pageCopy_message'); this.v.btn_pagePaste_message = this.view.find('._btn_pagePaste_message'); this.v.btn_pageUnPub.click(function(){ this_.unPublicData()}); this.v.btn_pageCopy.click(function(){ this_.pageCopy()}); this.v.btn_pagePaste.click(function(){ this_.pagePaste()}); } p.pageCopy =function (){ var this_ = this CMS_Status.clipBordPage = this.getJSONData(); // $("body").addClass("_copyPage"); // this.v.btn_pageCopy_message.html("コピーしました") // this.v.btn_pageCopy_message.show() if(this.pageCopyTID) clearTimeout(this.pageCopyTID) this.pageCopyTID = setTimeout(function(){ this_.hideMenuMessage() $("body").removeClass("_copyPage"); },200); } p.pagePaste =function (){ var this_ = this if(CMS_Status.clipBordPage == ""){ this.v.btn_pagePaste_message.html("データがありません") this.v.btn_pagePaste_message.show(); } if(this.setJSONData(CMS_Status.clipBordPage)){ this.v.btn_pagePaste_message.html("ペーストしました") this.v.btn_pagePaste_message.show() this.pageCopyTID = setTimeout(function(){ this_.hideMenuMessage() },2000); } } p.hideMenuMessage =function (){ this.v.btn_pageCopy_message.html("") this.v.btn_pageCopy_message.hide() this.v.btn_pagePaste_message.html("") this.v.btn_pagePaste_message.hide() } /* ---------- ---------- ---------- */ /* ---------- ---------- ---------- */ //ADDボタンのターゲットを保持するため、ルートフリーレイアウトを保持しておく p.rootFreeLayout p.setFreeLayout =function (_rootFreeLayout){ this.rootFreeLayout = _rootFreeLayout; } /* ---------- ---------- ---------- */ //#Stage p.isOpen = false; p.isFirst = true; p.stageInit = function (){ this.view.hide(); } p.tID p.stageIn = function (){ if(! this.isOpen){ this.isOpen = true; if(this.isFirst){ this.createView() } this.isFirst = false; // AddElements.setVisible(true); InspectView.stageOut(); this.view.show(); //追加ブロックの配置先を、このフリーレイアウトに if(this.rootFreeLayout) { AddElementsManager.setData( this.rootFreeLayout , 0); } var this_ = this; this.tID = setInterval(function(){this_.updateDateView(true)}, 1000*10); EditableView.PageViewState.setCurretPage(this); this.selectCurrent(); } } p.stageOut = function (){ if(this.isOpen){ this.isOpen = false; this.view.hide(); if(this.tID){ clearInterval(this.tID)} } } p.remove = function (){ this.view.remove(); this.currentSelect = null; } //現在の選択ノード保持用 p.currentSelect; p.setCurrentSelect = function (_node){ this.currentSelect = _node; } p.selectCurrent = function (){ if(this.currentSelect){ this.currentSelect.trigger("click"); InspectView.updateScrollPos(false); } } return c; })(); <file_sep>/src/js/cms_model/PageElement.tag.anchor.js PageElement.tag.anchor = (function(){ var _ = new PageModel.Tag_(); /* ---------- ---------- ---------- */ _.pageInfo = new PageModel.Object_Info({ id : "tag.anchor", name : "ページ内リンク", name2 : "<A>", inputs : [] }); /* ---------- ---------- ---------- */ _.getInitData = function(){ var o = {}; o.type = _.pageInfo.id; o.data = "anchor_id"; o.attr = {}; return o; } /* ---------- ---------- ---------- */ _.getPreview = function(_o){ var data = _o.data; var attr = _o.attrs; var tag = "" if(data == ""){ tag += '<span class="_no-input-data">IDを入力...</span>' } else{ tag += '<div class="_element_anchor"> ' + data + '</div>'; } return tag; } /* ---------- ---------- ---------- */ _.getHTML = function(_o,_tab){ var data = _o.data; var attr = _o.attrs; var tab = (_tab != undefined) ? _tab:""; var tag = "" tag += tab+'<div class="_element_anchor" id="'+data+'"> </div>'; return tag; } /* ---------- ---------- ---------- */ return _; })();<file_sep>/src/js/cms_model/PageElement.tag.blockquote.js PageElement.tag.blockquote = (function(){ var _ = new PageModel.Tag_(); /* ---------- ---------- ---------- */ _.pageInfo = new PageModel.Object_Info({ id : "tag.blockquote", name : "引用", name2 : "<BLOCKQUOTE>", inputs : ["TEXTAREA","CLASS","CSS"], // cssDef : {file:"block",key:"[引用ブロック]"} cssDef : {selector:".cms-bq"} }); /* ---------- ---------- ---------- */ _.getInitData = function(){ var o = {}; o.type = _.pageInfo.id; o.data = '文書が入ります。文書が入ります。文書が入ります。文書が入ります。文書が入ります。文書が入ります。文書が入ります。文書が入ります。\n<small>文書が入ります。文書が入ります。文書が入ります。</small>' o.attr = { css:"default" } o.attr.class = o.attr.css; return o; } /* ---------- ---------- ---------- */ _.getPreview = function(_o){ var data = _o.data; var attr = _o.attrs; attr = attr.split('class="').join('class="cms-bq '); var tag = ""; if(data == "") { tag += '<span class="_no-input-data">テキストを入力...</span>'; } else{ tag += '<blockquote ' + attr + '>' + data.split("\n").join("<br>\n") + '</blockquote>'; } return tag; } /* ---------- ---------- ---------- */ _.getHTML = function(_o,_tab){ var data = _o.data; var attr = _o.attrs; attr = attr.split('class="').join('class="cms-bq '); var tab = (_tab != undefined) ? _tab:""; var tag = "" tag += tab + '<blockquote ' + attr+'>' + data.split("\n").join("<br>\n" + tab) + '</blockquote>\n' ; return tag; } /* ---------- ---------- ---------- */ return _; })(); <file_sep>/src/js/cms_main/CMS_KeyManager.js //ショートカットキー管理 var CMS_KeyManager = (function(){ var view; var v = {}; var CK = 91;//17 /* ---------- ---------- ---------- */ function tooltip(_s,_d){ var cmd = (Env_.isWin) ? "Ctrl": "Cmd"; _s = _s.split("#").join(cmd); if(!_d){ return ' data-ks-bottom="'+_s+'" '; } if(_d == "R"){ return ' data-ks-right="'+_s+'" '; } if(_d == "T"){ return ' data-ks-top="'+_s+'" '; } return ' '; } function tooltipT(_s){ var cmd = (Env_.isWin) ? "Cmd": "Ctrl"; return '<kbd>' + _s.split("#").join(cmd) + '</kbd>'; } /* ---------- ---------- ---------- */ function init(){ window.TIP = tooltip; window.TIP2 = tooltipT; window.TIP_ENTER = TIP("#+Enter") // if(Env_.isWin ) CK = 17; window.isPressCommandKey = false; window.isPressShiftKey = false; $(document).keydown(function(event) { var KC = event.keyCode; //console.log(KC); var b = false; if(isPressCommandKey && isPressShiftKey){ if(KC == 86){ b= true; do_("S_C_v");}//ペースト } if(isPressCommandKey && isPressShiftKey ==false){ //ブロック操作のショートカットは、モーダルが表示されてないときだけ if(CMS_ModalManager.isNotModal()){ if(editType == "" || editType == "preset"){ if(KC == 68){ b= true; do_("C_d");}//複製 if(KC == 67){ b= true; do_("C_c");}//コピー if(KC == 86){ b= true; do_("C_v");}//ペースト if(KC == 88){ b= true; do_("C_x");}//カット if(KC == 90){ b= true; do_("C_z");}//取り消し if(KC == 8 ){ b= true; do_("C_dell");}//削除 if(KC == 73){ b= true; do_("C_i");}//プレビュートグル if(KC == 72){ b= true; do_("C_h");}//縮小表示 if(KC == 37){ b= true; do_("C_left");} if(KC == 38){ b= true; do_("C_up");} if(KC == 39){ b= true; do_("C_right");} if(KC == 40){ b= true; do_("C_down");} if(KC == 109){ b= true; do_("C_minus");} if(KC == 107){ b= true; do_("C_plus");} if(KC == 13){ b= true; do_("C_Enter");} //保存とかはいつでも可能 if(KC == 79){ b= true; do_("C_o");}//別ウィンドウで開く if(KC == 80){ b= true; do_("C_p");}//公開 if(KC == 70){ b= true; do_("C_f");}//一覧ワイド表示 //0,1-9 if(KC == 49){ b= true; addBlock("tag.heading" ,"h1");} if(KC == 50){ b= true; addBlock("tag.heading" ,"h2");} if(KC == 51){ b= true; addBlock("tag.heading" ,"h3");} if(KC == 52){ b= true; addBlock("tag.heading" ,"h4");} if(KC == 53){ b= true; addBlock("tag.p");} if(KC == 54){ b= true; addBlock("tag.markdown");} if(KC == 55){ b= true; addBlock("tag.img");} if(KC == 56){ b= true; addBlock("tag.margin");} if(KC == 57){ b= true; addBlock("tag.btn");} if(KC == 48){ b= true; addBlock("layout.div");} } } else if( CMS_ModalManager.isModal() ){ if(KC == 13){ b= true; do_("C_Enter_modal");} } //13...ENTER if(editType == "setting"){ if(KC == 83){ b= true; do_("Se.C_s");}//保存 } else if(editType == "preset"){ if(KC == 83){ b= true; do_("Pre.C_s");}//保存 } else { if(KC == 83){ b= true; do_("C_s");}//保存 } if(KC == 76){ b= true; do_("C_l");}//更新ロック // if(KC == 91){ b= true; do_("C_t");}//タブ切り替え } // if(KC == 33){ b= true; do_("PAGE_UP");} // if(KC == 34){ b= true; do_("PAGE_DOWN");} if(!b){ if(CMS_ModalManager.isNotModal()){ if(editType == "" || editType == "preset"){ if(KC == 38){ b= true; do_("up");} if(KC == 40){ b= true; do_("down");} } } } if(b){ event.stopPropagation(); event.preventDefault(); } if(KC == CK){ isPressCommandKey = true; if(CMS_ModalManager.isNotModal()){ $("body").addClass("_pressCommandPage") } } if(event.shiftKey){ isPressShiftKey = true; } if(KC == 122){ do_("C_Full"); return false; } }); $(document).keyup(function(event) { var KC = event.keyCode; if(KC == CK){ isPressCommandKey = false; $("body").removeClass("_pressCommandPage"); } if(event.shiftKey == false){ isPressShiftKey = false; } }); registKey("PAGE_UP",function(){ }) registKey("PAGE_DOWN",function(){ }) registKey("Se.C_s" ,function(){ CMS_AssetStage.save(); }) registKey("Pre.C_s" ,function(){ PresetStageView.save(); }) registKey("C_s" ,function(){ CMS_PagesView.save(); }) registKey("C_p" ,function(){ CMS_PagesView.publish(); }) registKey("C_d" ,function(){ window.sc.duplicateCurrent(); }) registKey("C_c" ,function(){ window.sc.copyCurrent(); }) registKey("C_v" ,function(){ window.sc.pastCurrent(); }) registKey("S_C_v" ,function(){ window.sc.pastCurrent2(); }) registKey("C_x" ,function(){ window.sc.cutCurrent();}) registKey("C_dell" ,function(){ window.sc.deleteCurrent(); }) registKey("C_o" ,function(){ CMS_PagesView.openURL(); }) registKey("C_i" ,function(){ CMS_PagesView.editMeta(); }) registKey("C_z" ,function(){ CMS_PagesView.historyBack() }) registKey("C_l" ,function(){ CMS_LOCK.setIsLocked_toggle() }) registKey("C_left" ,function(){ CMS_PagesView_ZoomManager.zoomOut() }) registKey("C_up" ,function(){ window.sc.moveUpCurrent() }) registKey("C_right" ,function(){ CMS_PagesView_ZoomManager.zoomIn() }) registKey("C_down" ,function(){ window.sc.moveDownCurrent() }) registKey("up" ,function(){ window.sc.selectNodePrev() }) registKey("down" ,function(){ window.sc.selectNodeNext() }) registKey("C_Enter" ,function(){window.sc.dClick() }) registKey("C_Enter" ,function(){enter();window.sc.dClick() }) registKey("C_Enter_modal",function(){CMS_ModalManager.closeModal() }) registKey("C_minus" ,function(){ }) registKey("C_plus" ,function(){ }) registKey("C_Full" ,function(){ window.editFullScreen() }) } var keyOs = {} function registKey(_s,_callback){ keyOs[_s] = _callback; } function do_(_s){ if(keyOs[_s]){ keyOs[_s](); } } function enter(){ window.isFireEnterClick = true; var tID; if(tID) clearTimeout(tID); tID = setTimeout(function(){ window.isFireEnterClick = false; },100); } var editType = "" var isF = true; function setType(_s){ editType = _s; // if(isF){ // v.log = $('<div style="position:fixed;top:0;left:0;background:#fff;padding:5px;z-index:200000;">_cms_log</div>') // $("body").append(v.log) // isF = false; // } // v.log.html(editType); } return { init:init, registKey:registKey, tooltip:tooltip, setType:setType } })(); <file_sep>/src/js/cms_main/CMS_CopyView.js var CMS_CopyView = (function(){ var view; var v = {}; function init(){ view = $('#CMS_CopyView'); stageInit(); $("body").on("click","._cms_btn_copy_text",function(){ var s = $(this).data("text"); CMS_CopyView.stageIn(s); }) $("body").on("click","._cms_btn_copy_page_id",function(){ var s = $(this).text(); CMS_CopyView.stageIn(s); }); } /* ---------- ---------- ---------- */ function createlayout(){ v = ModalViewCreater.createBaseView(Anchor_InputView,view); var tag = "" v.header.html(tag); tag = "" v.body.html(tag); tag = "" tag += '<div class="_cms_btn _btn_close">閉じる</div> '; v.footer.html(tag); setBtn(); } function setBtn(){ view.find('._bg ,._btn_close').click(function(){ stageOut() }); // view.find('._btn_do').click(function(){ callback(); stageOut() }); } /* ---------- ---------- ---------- */ function update(_s){ var tag = '<div class="_title">コピーしてください</div>' v.header.html(tag); var tag = ''; tag +='<textarea>'+_s+'</textarea>'; v.body.html(tag); view.find("textarea").select() } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; var callback; function stageInit(){ view.hide(); } function stageIn(_s,_callback){ if(! isOpen){ isOpen = true; showModalView(this); view.show(); if(isFirst){ createlayout(); } isFirst = false; callback = _callback update(_s); } } function stageOut(){ if(isOpen){ isOpen = false; hideModalView(); view.hide(); } } return { init:init, stageIn:stageIn, stageOut:stageOut } })(); <file_sep>/src/js/cms_util/CMS_AnchorListU.js var CMS_AnchorListU = (function(){ function getViewTag(val,_isPub){ if(_isPub == undefined) _isPub = true; var tag = '<b>リンク未設定</b>'; if(val == "") return tag; if(val == undefined) return tag; if(val["list"] == undefined) return tag; var list = CMS_U.getPublicList(val.list.grid); var tag = ""; if(list.length == 0) { tag += '<span class="_no-input-data">リストデータを入力...</span>' } else{ tag += '<ul>\n' for (var i = 0; i < list.length ; i++) { tag += '<li>' +CMS_AnchorU.getAnchorTag(list[i].anchor,"",_isPub) + '</li>\n' } tag += '</ul>\n' } return tag; } return { getViewTag:getViewTag } })(); <file_sep>/src/js/cms_main/TreeViewMakerViewEditor.js var TreeViewMakerViewEditor = (function(){ var view; var v = {}; function init(){ view = $('#TreeViewMakerViewEditor'); stageInit(); // stageIn("test",function(){},[800,200]); } var ids = [ ["{ID}","IDに置き換えられます"], ["{NAME}","ラベル名に置き換えられます"], ["{NAME[0]}","ラベル名にカンマ区切り(,)が入ってる場合、1つめのラベル名に置き換えられます"], ["{NAME[1]}","ラベル名にカンマ区切り(,)が入ってる場合、2つめのラベル名に置き換えられます"], ["{NAME[2]}","ラベル名にカンマ区切り(,)が入ってる場合、3つめのラベル名に置き換えられます"], ["{NAME[3]}","ラベル名にカンマ区切り(,)が入ってる場合、4つめのラベル名に置き換えられます"], ["{NAME[4]}","ラベル名にカンマ区切り(,)が入ってる場合、5つめのラベル名に置き換えられます"], ["{NAME.noTag}","ラベル名にタグが入ってる場合、タグを取り除いた値に置き換えられます"], ["{HREF}" ,"リンク先に置き換えられます"], ["{TAR}" ,"リンクターゲットに置き換えられます"], ["{TAG}" ,"タグに置き換えられる予定です"], ["{READ}" ,"ページ説明に置き換えられる予定です"], ["{DATE}" ,"日付に置き換えられる予定です"], ["{SUM}" ,"グループ配下のページ数を表示する"], ["{NO}" ,"階層内での連番に置き換えられます"], ["{LEVEL}" ,"階層のレベルに置き換えられます"], ["{CSS.B}" ,"CMSでデフォルトで設定されているボタンクラス ( _btn_default ) に置き換えられます"], ["{HOME}" ,"ホームページのリンクパスに置き換えられます"], ["{I.D}" ,'<i class="fa fa-lg fa-folder "></i> アイコンに置き換えられます'], ["{I.D2}" ,'<i class="fa fa-lg fa-folder-open "></i> アイコンに置き換えられます'], ["{I.P}" ,'<i class="fa fa-lg fa-caret-right "></i> アイコンに置き換えられます'], ["{I.P2}" ,'<i class="fa fa-lg fa-chevron-circle-right "></i> アイコンに置き換えられます'], ["{I.P3}" ,'<i class="fa fa-lg fa-angle-right "></i> アイコンに置き換えられます'], ["{I.T}" ,'<i class="fa fa-lg fa-tag "></i> アイコンに置き換えられます'], ["{I.B}" ,'<i class="fa fa-lg fa-external-link-square "></i> リンクターゲットが_blankの場合、別ウィンドウアイコンに置き換えられます'], ] var ids2 = [ ["{HTML}","見出しテンプレで使用し、HTMLに置き換えられます"] ] function createlayout(){ var tag = "" tag += '<div class="_btn_close"></div>'; tag += '<div class="_body"></div>' tag += '<div class="_cms_anno"></div>' tag += '<div class="_typeDef">' tag += ' <div class="_presets">' tag += ' <div class="_btn_preset" data-id="reset"><i class="fa fa-times "></i> リセット</div>' tag += ' <div class="_btn_preset" data-id="link1"><i class="fa fa-code "></i> リンク1</div>' tag += ' <div class="_btn_preset" data-id="link2"><i class="fa fa-code "></i> リンク2</div>' tag += ' </div>' tag += ' <div class="_snippets">' tag += ' <div class="_title"><i class="fa fa-caret-down "></i> 置き換えキー</div>' tag += ' <div class="_inner">' tag += ' <div class="_p">グループ、ページ設定画面で設定した値などを取得できます。</div>' for (var i = 0; i < ids.length ; i++) { tag += '<div class="_btn_rep_id">'+ids[i][0]+'</div>' } tag += ' <div class="_p _disc"></div>' tag += ' </div>' tag += ' </div>' tag += '</div>' tag += '<div class="_typeHtml">' tag += ' <div class="_presets">' tag += ' <div class="_btn_preset" data-id="reset"><i class="fa fa-times "></i> リセット</div>' tag += ' </div>' tag += ' <div class="_snippets">' tag += ' <div class="_title"><i class="fa fa-caret-down "></i> 置き換えキー</div>' tag += ' <div class="_inner">' for (var i = 0; i < ids2.length ; i++) { tag += '<div class="_btn_rep_id" >'+ids2[i][0]+'</div>' } tag += ' </div>' tag += ' </div>' tag += '</div>' view.html(tag); v.body = view.find('._body'); v.body.html(CMS_FormU.getTextarea("","html")) v.textarea = view.find('textarea'); v._btn_close = view.find('._btn_close'); v.cms_anno = view.find('._cms_anno'); v.typeDef = view.find('._typeDef'); v.typeHtml = view.find('._typeHtml'); v.btn_rep_id = view.find('._btn_rep_id'); v.btn_rep_id.click(function(){ appendID($(this).text())}); v.btn_rep_id.hover(function(){ showPresetDisc( $(this).text() )}); v.disc = view.find('._disc'); v.btn_preset = view.find('._btn_preset'); v.btn_preset.click(function(){ presetText($(this).data("id"))}); setBtn(); } function setBtn(){ v._btn_close.click(function(){ stageOut() }); v.textarea.keyup(function(){ getData(); }); } /* ---------- ---------- ---------- */ function showPresetDisc(_s1){ var desc = "" for (var i = 0; i < ids.length ; i++) { if(_s1 == ids[i][0]) desc = ids[i][1]; } v.disc.html('<b>' + _s1 + '</b>' + " : " + desc); } function presetText(_s){ var s = "" if(_s =="link1"){ s = '<a href="{HREF}" target="{TAR}">{NAME}</a>' } if(_s =="link2"){ s = '<a href="{HREF}" target="{TAR}" class="{CSS.B}"><span class="t1">{NAME.1}</span><span class="t2">{NAME.2}</span></a>' } v.textarea.val(s).keyup(); } function appendID(_s){ var s = v.textarea.val(); v.textarea.val(s + _s).keyup(); } /* ---------- ---------- ---------- */ // var defS = "" function setValue(_s,_type){ v.textarea.focus().val(_s); // v.typeDef.hide(); v.typeHtml.hide(); if(_type == "html"){ v.typeHtml.show(); } else{ v.typeDef.show(); } } function getData(){ var s = v.textarea.val(); callback_main(s); } var tID function callback_main(s){ if(tID)clearTimeout(tID); tID = setTimeout(function(){ callback(s); },200); } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } var callback function stageIn(_s,_callback,_xy,_type){ if(view === undefined) return; if(isFirst){ createlayout(); isFirst = false; } callback = _callback view.show(); // if(CMS_StatusW-300 < _xy[0]){_xy[0] = CMS_StatusW-300} view.css("left",_xy[0]+25); view.css("top",_xy[1]+15); setValue(_s,_type) } function stageOut(){ if(view === undefined) return; view.hide(); } return { init:init, stageIn:stageIn, stageOut:stageOut } })();//<file_sep>/src/js/cms_view_editable/__EditableView.InputTagProvider.js __EditableView.InputTagProvider = (function(){ function _brText(_s){ return _s.split("\n").join("<br>"); } //グリッド編集 function editableTD (i,val,cell,_wap){ var tag = ""; tag += '<td '; tag += ' class="{EDIT_STATE} _editable" '; tag += ' data-no="' + i + '" '; tag += ' data-id="' + cell.id + '" '; tag += ' data-type="' + cell.type + '" '; tag += ' style="'+cell.style + '"'; tag += '>'+ _brText(val)+'</td>'; return _wapTag(_wap,tag); } //グリッド編集 属性が入力できるTabelタグ用 function editableTD_Table(i,val,cell,_wap){ var tag = ""; tag += '<td '; tag += ' class="{EDIT_STATE} _editableTable" '; tag += ' data-no="' + i + '" '; tag += ' data-id="' + cell.id + '" '; tag += ' data-type="' + cell.type + '" '; tag += '>'+CMS_TagU.deleteCellAttr(_brText(val)) +'</td>'; return _wapTag(_wap,tag); } //グリッド編集 HTMLタグをそのまま表示 function editableTD_HTML (i,val,cell,_wap){ var tag = ""; tag += '<td '; tag += ' class="{EDIT_STATE} _editableHTML" '; tag += ' data-no="' + i + '" '; tag += ' data-id="' + cell.id + '" '; tag += ' data-type="' + cell.type + '" '; tag += '><textarea ' tag += ' style="'+cell.style + '"'; tag += ' >' + val + '</textarea></td>'; return _wapTag(_wap,tag); } //テキスト編集用(グリッドの場合は、_editableTD) function singleline(i,val,cell,_wap){ var tag = ""; tag += '<input'; tag += ' data-no="' + i + '" '; tag += ' data-id="' + cell.id + '" '; tag += ' style="'+cell.style + '"'; tag += ' class="_editableNode"'; if(cell.list) tag += ' list="'+cell.list+'"'; tag += ' value="'+ val +'">'; tag += _getNoteTag(cell.note); //cell return _wapTag(_wap,tag); } //テキスト編集用(グリッドの場合は、editableTD) function multiline(i,val,cell,_wap){ var cs = CMS_FormU.getCSS_Class(cell.codeType); var tag = ""; tag += '<div class="_input-with-btns ">' tag += '<textarea'; tag += ' data-no="' + i + '" '; tag += ' data-id="' + cell.id + '" '; tag += ' style="'+cell.style + '"'; tag += ' class="_editableNode '+ cell.class_ + " " + cs + '"'; tag += '>'+ val +'</textarea>'; //拡大編集ボタン追加 tag += '<div class="_btns">' tag += '<span class="_btn_input _edit" data-type="'+cell.codeType+'"><i class="fa fa-bars"></i></span> ' tag += '</div>' tag += '</div>' tag += _getNoteTag(cell.note); return _wapTag(_wap,tag); } function table (i,val,cell,_wap){ alert("エラー:getInputTag.table") } function image(i,val,cell,_wap){ var imgTag = '<div class="_no-photo">画像未設定</div>' if(val != ""){ imgTag = CMS_Path.MEDIA.getPreviewImageTag(val); } var uid = DateUtil.getRandamCharas(10); InputTagTempDatas.addData(uid, val); var tag = ""; tag += '<div class="_image_set {EDIT_STATE}"'; tag += ' data-val="' + uid + '" '; tag += ' data-no="' + i + '" '; tag += ' data-id="' + cell.id + '" '; tag += '>' tag += ' <div class="_btn_image _image_thumb _cms_btn_alphaS">'+ imgTag + '</div>'; tag += ' <div class="_image_extra">'; tag += ' <div class="_cms_btn_alphaS _btn_image_t">' + val+'</div>'; tag += ' <div class="_cms_btn_alpha _btn_image_list ss_img_select img_select2_img"></div>'; tag += ' <div class="_cms_btn_alpha _btn_image_mock ss_img_select img_select2_dummy"></div>'; tag += ' <div class="_cms_btn_alpha _btn_delete ss_img_select img_select2_remove"></div>'; tag += ' </div>'; tag += '</div>'; tag += _getNoteTag(cell.note); return _wapTag(_wap,tag); } function anchor(i,val,cell,_wap){//a var aTag = CMS_AnchorU.getViewTag(val,false); var uid = DateUtil.getRandamCharas(10); InputTagTempDatas.addData(uid, val) var tag = ""; tag += '<div class="{EDIT_STATE} _btn_anchor _cms_btn_alpha"'; tag += ' data-val="' + uid + '" '; tag += ' data-no="' + i + '" '; tag += ' data-id="' + cell.id + '" '; tag += '>'; tag += aTag; tag += '</div>'; tag += _getNoteTag(cell.note); return _wapTag(_wap,tag); } function textAnchor(i,val,cell,_wap){//a var aTag = CMS_AnchorU.getViewTag(val,false); var uid = DateUtil.getRandamCharas(10); InputTagTempDatas.addData(uid, val) var tag = ""; tag += '<div class="{EDIT_STATE} _btn_textAnchor _cms_btn_alpha"'; tag += ' data-val="' + uid + '" '; tag += ' data-no="' + i + '" '; tag += ' data-id="' + cell.id + '" '; tag += '>'; tag += aTag; tag += '</div>'; tag += _getNoteTag(cell.note); return _wapTag(_wap,tag); } //20150415 function btnList(i,val,cell,_wap){ if(val == false) val = {} var uid = DateUtil.getRandamCharas(10); var aTag = CMS_AnchorListU.getViewTag(val,false); InputTagTempDatas.addData(uid, val) var tag = ""; tag += '<div class="{EDIT_STATE} _btn_btnList _cms_btn_alpha"'; tag += ' data-val="' + uid + '" '; tag += ' data-no="' + i + '" '; tag += ' data-id="' + cell.id + '" '; tag += '>'; tag += aTag; tag += '</div>'; tag += _getNoteTag(cell.note); return _wapTag(_wap,tag); } //20150418 function tree(i,val,cell,_wap){ if(val == false) val = {} var uid = DateUtil.getRandamCharas(10); // var htmlAbs = CMS_Path.PAGE.ABS; var tree = CMS_Data.Sitemap.getData(); var aTag = TreeAPI.getTag( htmlAbs, tree , val); aTag = aTag.split(TreeAPI_SITE_DIR).join(""); InputTagTempDatas.addData(uid, val) var tag = ""; tag += '<div class="{EDIT_STATE} _btn_tree _previewTreeView _cms_btn_alpha"'; tag += ' data-val="' + uid + '" '; tag += ' data-no="' + i + '" '; tag += ' data-id="' + cell.id + '" '; tag += '>'; tag += aTag; tag += '</div>'; tag += _getNoteTag(cell.note); return _wapTag(_wap,tag); } /* ---------- ---------- ---------- */ function select(i,val,cell,_wap){ var tag = ""; tag += '<select'; tag += ' data-no="'+ i +'" '; tag += ' data-id="' + cell.id + '" '; tag += '>'; var vs = cell.vals if(typeof cell.vals == "function") vs = cell.vals(); var m = false; for (var g = 0; g < vs.length ; g++) { var option = vs[g]; tag += '<option ' if( val == option[0]){ tag += ' selected';m = true; } tag += ' value="'+option[0]+'">'+option[1]+'</option>'; } if(!m){ tag += '<option value="'+val+'" selected>'+val+' ( 未定義の値です ) </option>'; } tag += '</select>'; tag += _getNoteTag(cell.note); return _wapTag(_wap,tag); } function checkbox(i, val, cell, _wap) { var s = cell.name; if(s == "公開") s = ""; var uid = DateUtil.getRandamCharas(10); var tag = ""; tag += '<input class="checkbox" '; tag += ' type="checkbox"'; tag += ' id="' + uid + '" '; tag += ' data-no="' + i + '" '; tag += ' data-id="' + cell.id + '" '; tag += (val == "1") ? " checked " : ""; tag += '><label for="' + uid + '"> ' + s + '</label>'; tag += _getNoteTag(cell.note); /// return _wapTag(_wap, tag); } function yyyymmdd(i, val, cell, _wap) { var tag = ""; tag += '<div class="_editYYYYMMDD" '; tag += ' data-no="' + i + '" '; tag += ' data-id="' + cell.id + '" '; tag += ' data-type="' + cell.type + '" '; tag += '>' + val + '</div>'; return _wapTag(_wap,tag); } /* ---------- ---------- ---------- */ function _wapTag(_wap,_t){ var tag = _t; if(_wap != ""){ tag = '<' + _wap + ' class="{EDIT_STATE}">' + tag +'</' +_wap+'>' } return tag; } function _getNoteTag (_s){ var tag = "" if(_s != ""){ if(_s != undefined){ tag += '<p class="_note">'+_s +'</p>' } } return tag; } return { editableTD: editableTD, editableTD_Table: editableTD_Table, editableTD_HTML: editableTD_HTML, singleline: singleline, multiline: multiline, table: table, image: image, anchor: anchor, textAnchor: textAnchor, btnList: btnList, tree: tree, select: select, checkbox: checkbox, yyyymmdd: yyyymmdd } })(); <file_sep>/src/js/cms_stage_asset/CMS_Asset_UploaderState.js var CMS_Asset_UploaderState = (function(){ var isInited = false function init(){ if(isInited == false){ setEvent(); } isInited = true; } /* ---------- ---------- ---------- */ var isChecked = false function checkServer(_callback){ if(isChecked)return; isChecked = true; var url = CMS_Path.PHP_UPLOAD + "?action=check"; $.ajax({ scriptCharset : 'utf-8', type : 'GET', url : url, dataType : 'json', success : function(data) { checkServer_comp(data)}, error : function(data) { CMS_ErrorView.stageIn("NET",url,null,data); } }) } var maxSize = -1; function getMaxSize(){return maxSize} function getMaxSizeMB(){return maxMB} function getN(_s){ var n = parseInt(_s.split("M").join("")); if(isNaN(n)) { return defMAX; } else{ return n; } } var defMAX = 32; //var defMAX = 1; var maxMB = -1 function checkServer_comp(json){ var m1 = getN(json.post_max_size) var m2 = getN(json.upload_max_filesize) var m3 = getN(json.memory_limit) maxMB = Math.min(Math.min(defMAX,m1),Math.min(m2,m3)); maxSize = maxMB * 1024*1024; } function checkFileSize(_s){ if(_s < maxSize) return true; return false; } /* ---------- ---------- ---------- */ function setEvent(){ $(document).on('dragenter', function(e) { e.stopPropagation(); e.preventDefault(); }); $(document).on('dragover', function(e) { e.stopPropagation(); e.preventDefault(); if(currentDragStage){ currentDragStage.css('border', '1px dashed #0B85A1'); } }); $(document).on('drop', function(e) { e.stopPropagation(); e.preventDefault(); }); } var currentDragStage function setCurrentDragStage(_d){ currentDragStage = _d; } /* ---------- ---------- ---------- */ return { init: init, checkServer: checkServer, getMaxSize: getMaxSize, getMaxSizeMB: getMaxSizeMB, checkFileSize: checkFileSize, setCurrentDragStage: setCurrentDragStage }})();<file_sep>/src/js/cms_view_inspect/InspectView.p2.js /* ---------- ---------- ---------- */ /* ---------- ---------- ---------- */ /* ---------- ---------- ---------- */ //#要素選択 var currentNode; var replaceNode; var replacePropNode; var currentDiv; var currentNo; var param; var blockType; /* ---------- ---------- ---------- */ //要素ダブルクリック時にコール function setData_DoubleClick(_type,_this,this_,_rep,_repProp){ setData(_type,_this,this_,_rep,_repProp); dClick(); } function dClick(){ var t = blockType; if(t.indexOf("object.") == 0){ view.find("._cms_btn_edit").click();} if(t == "tag.heading") { view.find("._input-with-btns ._edit_single").eq(0).click();} if(t == "tag.p") { view.find("._input-with-btns ._edit").eq(0).click();} if(t == "tag.html") { view.find("._input-with-btns ._edit").eq(0).click();} if(t == "tag.js") { view.find("._input-with-btns ._edit").eq(0).click();} if(t == "tag.markdown") { view.find("._input-with-btns ._edit").eq(0).click();} if(t == "tag.code") { view.find("._input-with-btns ._edit").eq(0).click();} if(t == "tag.note") { view.find("._input-with-btns ._edit").eq(0).click();} if(t == "tag.place") { view.find("._input-with-btns ._edit").eq(0).click();} if(t == "tag.blockquote") { view.find("._input-with-btns ._edit").eq(0).click();} if(t == "tag.btn") { view.find("._btn_TextAnchor").eq(0).click();} if(t == "tag.img") { //シンプル or レイアウトモード var b = false; if(param.data){ b = param.data.isLayoutMode; } if(b){ view.find("._cms_btn_edit").eq(0).click(); } else{ view.find("._in_data_img").eq(0).click(); } } } function doCommand(_command,_extra){ if(_command == "delete") { deleteData()}; if(_command == "toggle") { toogleDivView()}; if(_command == "openDetail") { dClick()}; if(_command == "export") { window.sc.inspect_export(); } if(_command == "export_link") { CMS_U.openURL_blank(_extra); } if(_command == "embed") { window.sc.inspect_embed(); } if(_command == "embed_link") { CMS_U.openURL_blank(_extra); } } /* ---------- ---------- ---------- */ //要素選択時にコール //InspectView.setData var pageParam; function setPageData(_pageParam){ pageParam = _pageParam; } //InspectView.setData function setData(_type,_this,this_,_rep,_repProp){ //同じノードの場合は、スルー if(currentNode){if(currentNode.get(0)==_this.get(0))return;} // prevClickNode = currentNode; currentNode = _this; currentDiv = this_; replaceNode = _rep; replacePropNode = _repProp; currentNo = Number($(_this).attr("data-no")); param = currentDiv.gridData.getRecordAt(currentNo); blockType = param.type; var _attr = param.attr; //ノードの順番情報をアップデート updateNodeNo(); //現在の選択ノード保持用 EditableView.PageViewState.setCurretSelect(currentNode); //ブロック位置により、ページスクロールを調整する; updateTagPreview(); //ページプリセット用 _select_select_target(); //colsのlayout.divの場合は、layout.colDivに if(_type == "layout.colDiv") blockType = _type; var _has = PageElement_Util.hasInputType; var _FU = InspectView.FormU; var _FUIMG = InspectView.FormU_Img; //属性取得 var style = CMS_BlockAttrU.get_style(_attr); var css_ = CMS_BlockAttrU.get_css(_attr); var id_ = CMS_BlockAttrU.get_id(_attr); var attr_ = CMS_BlockAttrU.get_attr(_attr); var preview = CMS_BlockAttrU.get_preview(_attr); var extra = defaultVal(param["extra"] , {} ); /* ---------- ---------- ---------- */ //タイトル設定 v.title.html(PageElement_Util.getTypeName(blockType) /*+ ' <span class="_t0">ブロック</span>'*/); /* ---------- ---------- ---------- */ //入力の組み立て var nodes = (function(){ var a = []; if(blockType == "tag.anchor") { a.push(_FU.getAnchor (param)); } if(blockType == "tag.html") { a.push(_FU.getHtml (param,preview)); } if(blockType == "tag.js") { a.push(_FU.getJS (param)); } if(blockType == "tag.code") { a.push(_FU.getCode (param)); } if(blockType == "tag.markdown") { a.push(_FU.getMarkdown (param)); } if(blockType == "tag.margin") { a.push(_FU.getMargin (param)); } if(blockType == "tag.note") { a.push(_FU.getNote (param)); } if(blockType == "tag.place") { a.push(_FU.getPlace (param,extra)); } if(blockType == "tag.btn") { a.push(_FU.getBtn (param)); } if(blockType == "tag.img") { a.push(_FUIMG.getIMG (param,extra,"IMG")); } if(blockType == "layout.div") { a.push(_FUIMG.getBGIMG (param,extra)); } if(blockType == "layout.cols") { a.push(_FU.getLayoutCol ()); } if(blockType == "replace.div") { a.push(_FU.getReplaceDiv (param)); } if(_has(blockType,"CAPTION")) { a.push(_FU.getCaptionTag (param,extra)); } if(_has(blockType,"TEXTAREA")) { a.push(_FU.getTextarea (param)); } if(_has(blockType,"TREE")) { a.push(_FU.getTree (param)); } // if(_has(blockType,"IMGMAP")) { a.push(_FU.getImageMap (param)); } if(_has(blockType,"DETAIL")) { a.push(_FU.getDetail (blockType,currentDiv)); } if(_has(blockType,"RELOAD")) { a.push(_FU.getReload (blockType,currentDiv)); } if(_has(blockType,"HEADLINE")) { a.push(_FU.getHeadlineTag (param)); } if(blockType == "object.images"){ a.push(_FUIMG.getImages (param,extra )); } a.push(_FU.getGuide(blockType)); return a; })(); v.body_data.empty(); for (var i = 0; i < nodes.length ; i++) { v.body_data.append(nodes[i]); } //CSS var nodes = (function(){ //tag.headingの場合は、現在のh1,h2,,,を取得 var _extra = (function(_type,_param){ var s = ""; if(_type == "tag.heading" && _param["data"]){ if(_param.data["heading"]) s = _param.data["heading"]; } return s; })(blockType,param); // var a = []; if(_has(blockType,"CLASS")) a.push( _FU.getDesignTag(css_,blockType,_extra)); if(_has(blockType,"CSS")) a.push( _FU.getStyleTag( style )); a.push(_FU.getDesginGuide()); return a; })(); v.body_css.empty(); for (var i = 0; i < nodes.length ; i++) { v.body_css.append(nodes[i]); } //表示・非表示 InspectView.View.setData( blockType, CMS_BlockAttrU.get_narrow(_attr), CMS_BlockAttrU.get_hide(_attr), CMS_BlockAttrU.get_hidePC(_attr), CMS_BlockAttrU.get_hideMO(_attr) ); //ID InspectView.ID.setData( blockType, id_ ); InspectView.ATTR.setData( blockType, attr_ ); //書き出し InspectView.Export.setData( blockType, CMS_BlockAttrU.get_pubFileName(_attr), param ); //埋め込み InspectView.Embed.setData( blockType, CMS_BlockAttrU.get_embedName(_attr), CMS_BlockAttrU.get_embedID(_attr), param ); /* ---------- ---------- ---------- */ setSelected(); updateBodyH(); } <file_sep>/src/js/cms_model/PageElement.setting.btnList.js PageElement.setting.btnList = (function(){ var _ = new PageModel.Object_(); /* ---------- ---------- ---------- */ _.pageInfo = new PageModel.Object_Info({ id : "setting.btnList", name : "ボタンリスト", inputs : ["DETAIL"] }); /* ---------- ---------- ---------- */ _.grids = [ /* ---------- ---------- ---------- */ new PageModel.Object_Grid({ gridType:Dic.GridType.BASE, gridInfo:new PageModel.OG_info({ id : "list", name : "リスト", note : "" }), textData:null, gridData:{ info:new PageModel.OG_SubInfo({ name:"" }), cells:[ new PageModel.OG_Cell({ id: "anchor", name: "リンク", type: CELL_TYPE.BTN, style: SS.w300, view: "", def:CMS_AnchorU.getInitData() }), ] } }) /* ---------- ---------- ---------- */ ] _.getInitData = function(){ var o = {}; o.type = _.pageInfo.id; var def = { list: { texts: {}, grid: [ { publicData: "1", anchor: { href: "index.html", target: "", text: "リンク", class_: "btn_lightglay btn_size_M", image: "" } }, { publicData: "1", anchor: { href: "index.html", target: "", text: "リンク", class_: "btn_lightglay btn_size_M", image: "" } }, { publicData: "1", anchor: { href: "index.html", target: "", text: "リンク", class_: "btn_lightglay btn_size_M", image: "" } } ] } } o.data = def o.attr = {}; return o; } _.getPreview = function(_o){ var data = _o.data; var attr = _o.attrs; var id = _o.id var jquery = _o.jquery; var list = CMS_U.getPublicList(data.list.grid); var tag = ""; if(list.length == 0) { tag += '<span class="_no-input-data">リストデータを入力...</span>' } else{ var ss = ''; ss += ' <ul>\n' for (var i = 0; i < list.length ; i++) { var aTag = CMS_AnchorU.getAnchorTag(list[i].anchor,"",false) ss += ' <li>' ss += aTag ; ss += '</li>\n' } ss += ' </ul>\n' // var ss_s = CMS_TagU.tag_2_t(ss).split("\n").join("<br>"); // ss_s += CMS_TagU.tag_2_t(JSON.stringify(_o.data.list.grid, null, "  ")).split("\n").join("<br>"); tag += PageElement.settingU.getTag(id,jquery,data,ss); } return tag; } _.getHTML = function(_o){ return ""; } /* ---------- ---------- ---------- */ return _; })(); <file_sep>/src/js/cms_main/CMS_ErrorView.js var CMS_ErrorView = (function(){ var view; var v = {}; function init(){ view = $('#CMS_ErrorView'); stageInit(); } /* ---------- ---------- ---------- */ function createlayout(){ v = ModalViewCreater.createBaseView(Anchor_InputView,view); var tag = "" v.header.html(tag); tag = "" v.body.html(tag); tag = "" tag += '<div class="_cms_btn _btn_close">閉じる</div> '; v.footer.html(tag); setBtn(); } function setBtn(){ view.find('._bg ,._btn_close').click(function(){ stageOut() }); } /* ---------- ---------- ---------- */ function update(_type,_url,_req,_res){ var title = '<div class="_title">エラー</div>'; var tag = ""; if(_type == "NET"){ title = '<div class="_p _title"><i class="fa fa-warning"></i> ネットワークエラー</div>'; tag += '<div class="_p _h">●リクエストURL</div>'; tag += '<div class="_p _path">'+_url+'</div>'; if(_req){ tag += '<div class="_p _h">●リクエストデータ</div>'; tag += '<textarea>' + JSON.stringify(_req, null, " ") + '</textarea>'; } if(_res){ tag += '<div class="_p _h">●リザルトステート</div>'; tag += '<div class="_p _res_error">'; tag += _res["status"] + " " + _res["statusText"]; tag += '</div>'; if(_res["status"] == "403"){ tag += '<div class="_p">403の場合は、ウェブサーバーのWAF機能が有効になっている可能性があります。詳しくは'+CMS_LINKs.waf+'のページで</div>'; } } } else{ tag = '<div class="_p">'+_res+'</div>' } v.header.html(title); v.body.html(tag); } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; // var callback; function stageInit(){ view.hide(); } var tID; if(tID) clearTimeout(tID); function stageIn(_type,_url,_req,_res){ if(!view){ $("body").append('<div id="CMS_ErrorView" class="_modalView"></div>'); init(); } if(! isOpen){ isOpen = true; tID = setTimeout(function(){ stageIn_core(_type,_url,_req,_res) },200); } } function stageIn_core(_type,_url,_req,_res){ view.show(); if(isFirst){ createlayout(); } isFirst = false; update(_type,_url,_req,_res); } function stageOut(){ if(isOpen){ isOpen = false; view.hide(); } } return { init:init, stageIn:stageIn, stageOut:stageOut } })(); <file_sep>/src/js/cms_view_editable/EditableView.InputEvent.js EditableView.InputEvent = (function(){ //イベントアサイン まとめて行う function assign (v,this_){ EditableView.InputEventText.assign(v,this_); EditableView.InputEventImg.assign(v,this_); } return { assign:assign } })(); EditableView.InputEventImg = (function(){ //イベントアサイン まとめて行う function assign (v,this_){ //画像 v.on("click","._btn_image" ,function(){ _changeImage( $(this).closest("._image_set"),this_) }); v.on("click","._btn_image_t" ,function(){ _changeImage_t( $(this).closest("._image_set"),this_) }); v.on("click","._btn_image_list" ,function(){ _changeImage_list( $(this).closest("._image_set"),this_) }); v.on("click","._btn_image_mock" ,function(){ _changeImage_mock( $(this).closest("._image_set"),this_) }); v.on("click","._btn_image_delete" ,function(){ _changeImage_remove($(this).closest("._image_set"),this_) }); v.on("click","._btn_image_layout" ,function(){ _changeImage_layout($(this).closest("._image_set"),this_) }); v.on("click","._btn_mode_simple" ,function(){ _changeImage_Mode($(this),"simple") }); v.on("click","._btn_mode_layout" ,function(){ _changeImage_Mode($(this),"layout") }); v.on("keyup","._in_image_width" ,function(){ _changeImage_input($(this),$(this).closest("._image_set"),this_,"width") }); v.on("keyup","._in_image_ratio" ,function(){ _changeImage_input($(this),$(this).closest("._image_set"),this_,"ratio") }); // v.on("click","._btn_image_tag_ng" ,function(){ _changeImage_onlyImg($(this).closest("._image_set"),this_,false) }); // v.on("click","._btn_image_tag_ac" ,function(){ _changeImage_onlyImg($(this).closest("._image_set"),this_,true) }); // v.on("keyup","._in_image_ratio" ,function(){ _changeImage_input($(this),$(this).parent().parent().parent().parent().eq(0),this_,"ratio") }); } //画像の変更。モーダル function _changeImage (_this,this_){ var uid = _getDataVal(_this,this_); var val = InputTagTempDatas.getData(uid); if(val.mode == "simple"){ _changeImage_list(_this,this_); } else{ _changeImage_layout(_this,this_); } } function _changeImage_list(_this,this_){ var no = _getDataNo(_this,this_); var id = _getDataID(_this,this_); var o = _getRecord(_this,this_,no); // var uid = _getDataVal(_this,this_); var val = InputTagTempDatas.getData(uid); if(DummyImageService.isMock(val.path)) val.path = CMS_Path.UPLOAD.ABS; // CMS_MainController.openAssetSelectRel("image", val.path ,function(_s){ UpdateDelay.delay(function(){ o[id].mode = "simple"; o[id].path = _s; this_.changeData(o,no); // InputTagTempDatas.addData(uid, o[id]) _changeImage_update(_this, o, id, o[id]); }); }); } function _changeImage_mock(_this,this_){ var no = _getDataNo(_this,this_); var id = _getDataID(_this,this_); var o = _getRecord(_this,this_,no); // var uid = _getDataVal(_this,this_); var val = InputTagTempDatas.getData(uid); if(DummyImageService.isMock(val.path) == false) val.path = ""; DummyImageView.stageIn(val.path,function(_s){ o[id].mode = "simple"; o[id].path = _s; this_.changeData(o,no); // InputTagTempDatas.addData(uid, o[id]) _changeImage_update(_this, o, id, o[id]); }); } //画像の変更。prompt function _changeImage_t(_this,this_){ var no = _getDataNo(_this,this_); var id = _getDataID(_this,this_); var o = _getRecord(_this,this_,no); // var uid = _getDataVal(_this,this_); var val = InputTagTempDatas.getData(uid); var _s = prompt("画像URLを入力してください", val.path); if(_s == val.path) return; if(_s == null) return; // o[id].path = _s; this_.changeData(o,no); // InputTagTempDatas.addData(uid, o[id]); _changeImage_update(_this, o, id, o[id]); } function _changeImage_remove(_this,this_){ var no = _getDataNo(_this,this_); var id = _getDataID(_this,this_); var o = _getRecord(_this,this_,no); // var uid = _getDataVal(_this,this_); o[id].mode = "simple"; o[id].path = "width:100,height:100"; this_.changeData(o,no); // InputTagTempDatas.addData(uid, o[id]); _changeImage_update(_this, o, id, o[id]); } //レイアウト function _changeImage_layout(_this,this_){ var no = _getDataNo(_this,this_); var id = _getDataID(_this,this_); var o = _getRecord(_this,this_,no); // var uid = _getDataVal(_this,this_); var val = InputTagTempDatas.getData(uid); if(val.mode != "layout"){ val.path = {}; } ImageMapView.stageIn(val.path,function(_s){ o[id].mode = "layout"; o[id].path = _s; this_.changeData(o,no); // InputTagTempDatas.addData(uid, o[id]) _changeImage_update(_this, o, id, o[id]); }); } //画像変更後の共通処理 function _changeImage_update(_this,_o,_id,_s){ var imgTag = '<div class="_no-photo">画像未設定</div>' if(_s.path != ""){ imgTag = CMS_ImgBlockU.getImageTag({ path : _s.path, isPub : false, width : "100%", ratio : _s.ratio, alt : "", attr : "" }); } $(_this).find("._btn_image").html(imgTag); $(_this).find("._btn_image_t").html(_s.path); _setEdited($(_this).parent(),_o,_id); } //幅とratio function _changeImage_input(_in,_this,this_,_type){ var no = _getDataNo(_this,this_); var id = _getDataID(_this,this_); var o = _getRecord(_this,this_,no); // var uid = _getDataVal(_this,this_); var val = InputTagTempDatas.getData(uid); var _s = _in.val(); o[id][_type] = _s; this_.changeData(o,no); InputTagTempDatas.addData(uid, o[id]); _changeImage_update(_this, o, id, o[id]); } //モード切り替え(表示だけ) function _changeImage_Mode(_this,_mode){ var parent = _this.parent().parent(); if(_mode == "simple"){ parent.find("._btn_mode_simple").addClass("_current") parent.find("._btn_mode_layout").removeClass("_current") parent.find("._body_img_simple").slideDown(); parent.find("._body_img_layout").slideUp(); } else{ parent.find("._btn_mode_simple").removeClass("_current") parent.find("._btn_mode_layout").addClass("_current") parent.find("._body_img_simple").slideUp(); parent.find("._body_img_layout").slideDown(); } } //IMGタグのみ表示 /* function _changeImage_onlyImg(_this,this_,_b){ var no = _getDataNo(_this,this_); var id = _getDataID(_this,this_); var o = _getRecord(_this,this_,no); var parent = _this.parent().parent(); if(_b){ parent.find('._btn_image_tag_ac').hide(); parent.find('._btn_image_tag_ng').show(); } else{ parent.find('._btn_image_tag_ac').show(); parent.find('._btn_image_tag_ng').hide(); } o[id].onlyImgTag = _b; this_.changeData(o,no); }*/ /* ! ---------- 共通 ---------- ---------- ---------- ---------- */ //セルを編集したら、背景を黄色くする function _setEdited (_view,_o,_id) { _view.addClass("_edited"); //編集ステートをアップデートする グリッド再描画時に、編集ステートを引き継ぐ if(_o[CELL_TYPE.STATE] === undefined) _o[CELL_TYPE.STATE] = []; var editState = _o[CELL_TYPE.STATE] var b = false; for (var i = 0; i < editState.length ; i++) { if(editState[i] == _id)b = true; } if(b == false) editState.push(_id); } function _getXY (_this){ return [ $(_this).offset().left +20, $(_this).offset().top - $(window).scrollTop() +20 ] } function _getDataNo (_this,this_){ return Number($(_this).attr("data-no")) } function _getDataID (_this,this_){ return $(_this).attr("data-id") } function _getDataVal (_this,this_){ return $(_this).attr("data-val") } function _getRecord (_this,this_,no){ return this_.gridData.getRecordAt(no) } return { assign:assign } })(); EditableView.InputEventText = (function(){ //イベントアサイン まとめて行う function assign (v,this_){ //リンク v.on("click","._btn_anchor" ,function(event){ _changeA(this,this_,event) }); v.on("click","._btn_textAnchor" ,function(event){ _changeBtn(this,this_,event) }); //基本UI v.on("keyup","textarea" ,function(){ _changeInput(this,this_) }); v.on("keyup","input" ,function(){ _changeInput(this,this_) }); v.on("change","select" ,function(){ _changeInput(this,this_) }); v.on("change","input.checkbox" ,function(){ _changeCheck(this,this_,$(this).prop("checked")) }); //テーブルセル v.on("click","._editYYYYMMDD" ,function(){ _changeYYYYMMDD(this,this_) }); v.on("click","._editableTD" ,function(){ _changeTableText(this,this_) }); v.on("click","._editableTDHide" ,function(){ _changeTableText(this,this_,true) }); v.on("click","._editableTD a" ,function(event){ event.preventDefault(); }); } /* ---------- ---------- ---------- */ /* ---------- ---------- ---------- */ /* ---------- ---------- ---------- */ //リンクの変更。モーダル function _changeA(_this,this_,event){ event.stopPropagation(); event.preventDefault(); // var no = _getDataNo(_this,this_); var id = _getDataID(_this,this_); var o = _getRecord(_this,this_,no); // var uid = _getDataVal(_this,this_); var val = InputTagTempDatas.getData(uid); // Anchor_InputView.stageIn(val,function(_s){ o[id] = _s; this_.changeData(o,no); InputTagTempDatas.addData(uid, _s) $(_this).html(CMS_AnchorU.getViewTag(_s,false)); _setEdited($(_this).parent(),o,id); }) } //ボタンの変更。モーダル function _changeBtn(_this,this_,event){ event.stopPropagation(); event.preventDefault(); var no = _getDataNo(_this,this_); var id = _getDataID(_this,this_); var o = _getRecord(_this,this_,no); // var uid = _getDataVal(_this,this_); var val = InputTagTempDatas.getData(uid); // Anchor_BtnView.stageIn(val,function(_s){ o[id] = _s; this_.changeData(o,no); InputTagTempDatas.addData(uid, _s) $(_this).html(CMS_AnchorU.getViewTag(_s,false)); _setEdited($(_this).parent(),o,id); }) } /* ---------- ---------- ---------- */ /* ---------- ---------- ---------- */ /* ---------- ---------- ---------- */ //<input>で値を変更 function _changeInput(_this,this_){ var no = _getDataNo(_this,this_); var id = _getDataID(_this,this_); var o = _getRecord(_this,this_,no); // try{ o[id] = $(_this).val(); this_.changeData(o,no); }catch( e ){} } //checkboxで値を変更 function _changeCheck(_this,this_,_checked){ var no = _getDataNo(_this,this_); var id = _getDataID(_this,this_); var o = _getRecord(_this,this_,no); // var val = ""; if(_checked) val = "1"; try{ o[id] = val; this_.changeData(o,no); _setEdited($(_this).parent(),o,id); }catch( e ){} } /* ---------- ---------- ---------- */ /* ---------- ---------- ---------- */ /* ---------- ---------- ---------- */ function _changeYYYYMMDD(_this,this_,_isHideCell){ var no = _getDataNo(_this,this_); var id = _getDataID(_this,this_); var o = _getRecord(_this,this_,no); // var def = o[id]; // Float_DateInputView.stageIn(def,function(_s){ setTimeout(function(){ o[id] = _s; this_.changeData(o,no); // _updateHTML($(_this),_s,_isHideCell); _setEdited($(_this).parent(),o,id); },200); },_getXY(_this) ); } /* ---------- ---------- ---------- */ /* ---------- ---------- ---------- */ /* ---------- ---------- ---------- */ //グリッドセルの編集時の動作 //tdで編集した場合(普通のセル) 改行は<BR>へ function _changeTableText(_this,this_,_isHideCell){ var no = _getDataNo(_this,this_); var id = _getDataID(_this,this_); var o = _getRecord(_this,this_,no); // var inputType = $(_this).attr("data-input"); // var def = o[id]; var type = inputType+ ":" + $(_this).attr("data-type"); MiniEditer.stageIn(def,function(_s){ o[id] = _s; this_.changeData(o,no); // var s = _s; s = CMS_TagU.deleteCellAttr(s); s = CMS_TagU.convertCellBR(s); _updateHTML($(_this),s,_isHideCell); _setEdited($(_this),o,id); }, type); } /* ---------- ---------- ---------- */ //セルを編集したら、表示をアップデートする function _updateHTML (_view,_val,_isHideCell) { var s = ""; if(! _isHideCell) { s = _val; } else{ s = EditableView.InputU.getTenten(_val); } try{ _view.html(s); }catch( e ){ _view.html(CMS_E.PARSE_ERROR); } } /* ! ---------- 共通 ---------- ---------- ---------- ---------- */ //セルを編集したら、背景を黄色くする function _setEdited (_view,_o,_id) { _view.addClass("_edited"); //編集ステートをアップデートする グリッド再描画時に、編集ステートを引き継ぐ if(_o[CELL_TYPE.STATE] === undefined) _o[CELL_TYPE.STATE] = []; var editState = _o[CELL_TYPE.STATE]; var b = false; for (var i = 0; i < editState.length ; i++) { if(editState[i] == _id)b = true; } if(b == false) editState.push(_id); } function _getXY (_this){ return [ $(_this).offset().left +20, $(_this).offset().top - $(window).scrollTop() +20 ] } function _getDataNo (_this,this_){ return Number($(_this).attr("data-no")) } function _getDataID (_this,this_){ return $(_this).attr("data-id") } function _getDataVal (_this,this_){ return $(_this).attr("data-val") } function _getRecord (_this,this_,no){ return this_.gridData.getRecordAt(no) } return { assign:assign } })(); //グリッド編集時に、オブジェクトのような値を一時的に保存しておく var InputTagTempDatas = (function(){ var data = {}; function addData(_id,_val){ data[_id] = _val } function getData(_id){ return data[_id] } function reset(){ data = {} } function trace(){ console.log(data); } return { addData : addData, getData : getData, reset : reset, trace:trace } })(); <file_sep>/js_cms/_cms/js/cms.free.js /* オリジナルブロックの定義 オリジナルブロックの定義をする場合は、このファイルに記述してください。 */ /* ! ---------- ---------- ---------- ---------- ---------- */ var __f = {} __f.getImage = CMS_ImgBlockU.getSimpleImageTag; __f.hasLink = CMS_TagU.hasLink; __f.getLink = CMS_TagU.getLinkTag; __f.getTagText = CMS_TagU.t_2_tag; __f.getBtn = CMS_AnchorU.getAnchorTag; __f.def = defaultVal; /* ! ---------- ---------- ---------- ---------- ---------- */ PageElement.object.inputSampleBlock = (function(){ var _ = new PageModel.Object_(); /* ---------- ---------- ---------- */ //ブロック定義 _.pageInfo = new PageModel.Object_Info({ id : "object.inputSampleBlock", custom : true, name : "入力タイプ一覧サンプル", name2 : "入力タイプの一覧を確認できます。カスタマイズの際に利用してください", inputs : ["CLASS","CSS","DETAIL"] }); /* ---------- ---------- ---------- */ //入力の設定 var defImage = { mode:"simple" , path: "width:150,height:100", width: "", ratio: "" } _.grids = [ /* ---------- ---------- ---------- */ new PageModel.Object_Grid({ gridType:Dic.GridType.BASE, gridInfo:new PageModel.OG_info({ id : "setting", name : "設定", note : "サンプルの文書ですので、ご注意ください。サンプルの文書ですので、ご注意ください。" }), textData:{ info: new PageModel.OG_SubInfo({ name: "設定", note: "サンプルの文書ですので、ご注意ください。サンプルの文書ですので、ご注意ください。" }), cells:[ new PageModel.OG_Cell({ id: "text_single", name: "テキスト(single)", type: CELL_TYPE.SINGLE, style: "width:400px;", note: "テキスト入力(1行タイプ)をおこなえます。", def: "" }), new PageModel.OG_Cell({ id: "text_multi", name: "テキスト(multi)", type: CELL_TYPE.MULTI, style: "width:400px;height:100px;", note: "テキスト入力(複数行タイプ)をおこなえます。", def: "" }), new PageModel.OG_Cell({ id: "select", name: "選択YN", type: CELL_TYPE.SELECT, vals: [ ["1","YES"], ["0","NO"] ], note: "セレクト入力をおこなえます。", def: "1" }), new PageModel.OG_Cell({ id: "checkbox", name: "チェック", type: CELL_TYPE.CHECK, note: "チェックボックス入力をおこなえます。", def: "1" }), new PageModel.OG_Cell({ id: "image", name: "イメージ", type: CELL_TYPE.IMAGE, style: "width:100px;", note: "イメージ選択をおこなえます。", def: defImage }), new PageModel.OG_Cell({ id: "anchor", name: "リンク", type: CELL_TYPE.ANCHOR, note: "リンク先設定をおこなえます。", def: CMS_AnchorU.getInitDataS() }), new PageModel.OG_Cell({ id: "btn", name: "ボタン", type: CELL_TYPE.BTN, note: "ボタン設定をおこなえます。", def: CMS_AnchorU.getInitDataS() }) ] }, gridData:null }), /* ---------- ---------- ---------- */ new PageModel.Object_Grid({ gridType:Dic.GridType.BASE, gridInfo:new PageModel.OG_info({ id : "list", name : "リスト", note : "サンプルの文書ですので、ご注意ください。サンプルの文書ですので、ご注意ください。" }), textData:null, gridData:{ info: new PageModel.OG_SubInfo({ name: "リスト", note: "サンプルの文書ですので、ご注意ください。サンプルの文書ですので、ご注意ください。" }), cells:[ new PageModel.OG_Cell({ id: "text_single", name: "テキスト(シングル)", type: CELL_TYPE.SINGLE, style: SS.w100, def: "テキスト" }), new PageModel.OG_Cell({ id: "text_multi", name: "テキスト(複数行)", type: CELL_TYPE.MULTI, style: "", def: "サンプルの文書ですので、ご注意ください。サンプルの文書ですので、ご注意ください。" }), new PageModel.OG_Cell({ id: "select", name: "選択YN", type: CELL_TYPE.SELECT, vals: [ ["1","YES"], ["0","NO"] ], def: "1" }), new PageModel.OG_Cell({ id: "checkbox", name: "チェック", type: CELL_TYPE.CHECK, def: "1" }), new PageModel.OG_Cell({ id: "image", name: "イメージ", type: CELL_TYPE.IMAGE, def: defImage }), new PageModel.OG_Cell({ id: "anchor", name: "リンク", type: CELL_TYPE.ANCHOR, style: SS.w300, def: CMS_AnchorU.getInitDataS() }), new PageModel.OG_Cell({ id: "btn", name: "ボタン", type: CELL_TYPE.BTN, style: SS.w300, def: CMS_AnchorU.getInitDataS() }) ] } }) /* ---------- ---------- ---------- */ ] /* ---------- ---------- ---------- */ //初期データ _.getInitData = function(){ var o = {}; o.type = _.pageInfo.id; o.data = _.getDefData(3); o.attr = {}; return o; } /* ---------- ---------- ---------- */ //プレビュー用のタグを返す (管理画面での表示) _.getPreview = function(_o,_isPub){ var data = _o.data; var attr = _o.attrs; var tag = ""; attr = attr.split('class="').join('class="inputSampleBlock '); tag += '<div '+attr+'>\n'; tag += '<h2 class="cms-h default ">入力タイプ一覧サンプル</h2>\n'; { var seti = data.setting.texts; tag += '<h3 class="cms-h default ">■設定</h3>\n'; tag += '<table class="cms-table default narrow">\n'; tag += ' <tr><th>テキスト(single)</th><td>' + __f.getTagText(seti.text_single) + '</td></tr>\n'; tag += ' <tr><th>テキスト(multi)</th><td>' + __f.getTagText(seti.text_multi) + '</td></tr>\n'; tag += ' <tr><th>選択YN</th><td>' + __f.def(seti.select,"") + '</td></tr>\n'; tag += ' <tr><th>チェック</th><td>' + __f.def(seti.checkbox,"") + '</td></tr>\n'; tag += ' <tr><th>イメージ</th><td><div style="width:200px;">\n'; if(_isPub) { tag += __f.getImage({image:seti.image,isPub:_isPub}); } else{ tag += __f.getImage({image:seti.image,isPub:_isPub,width:"100px"}); } tag += ' </div></td></tr>\n'; tag += ' <tr><th>リンク</th><td>\n'; if(__f.hasLink(seti.anchor)){ tag += '<a '+__f.getLink(seti.anchor)+'>リンク</a>'; } tag += ' </td></tr>\n'; tag += ' <tr><th>ボタン</th><td>' + __f.getBtn(seti.btn) + '</td></tr>\n'; tag += '</table>\n'; } { var list = CMS_U.getPublicList(data.list.grid); tag += '<h3 class="cms-h default ">■リスト</h3>\n'; tag += '<table class="cms-table default narrow">\n'; tag += ' <tr>\n'; tag += ' <th>no</th>\n'; tag += ' <th>テキスト(single)</th>\n'; tag += ' <th>テキスト(multi)</th>\n'; tag += ' <th>選択YN</th>\n'; tag += ' <th>チェック</th>\n'; tag += ' <th>イメージ</th>\n'; tag += ' <th>リンク</th>\n'; tag += ' <th>ボタン</th>\n'; tag += ' </tr>\n'; for (var i = 0; i < list.length ; i++) { var row = list[i]; tag += ' <tr>\n'; tag += ' <th>' + (i+1) + '</th>\n'; tag += ' <td>' + __f.getTagText(row.text_single) + '</td>\n'; tag += ' <td>' + __f.getTagText(row.text_multi) + '</td>\n'; tag += ' <td>' + __f.def(row.select,"") + '</td>\n'; tag += ' <td>' + __f.def(row.checkbox,"") + '</td>\n'; tag += ' <td style="width:50px;">\n'; if(_isPub){ tag += __f.getImage({image:row.image,isPub:_isPub}); } else{ tag += __f.getImage({image:row.image,isPub:_isPub,width:"100px"}); } tag += '\n </td>\n'; tag += ' <td>\n'; if(__f.hasLink(row.anchor)){ tag += '<a '+__f.getLink(row.anchor)+'>リンク</a>\n'; } tag += ' </td>\n'; tag += ' <td>' + __f.getBtn(row.btn) + '</td>\n'; tag += ' </tr>\n'; } tag += '</table>\n'; } tag += '</div>'; return tag; } /* ---------- ---------- ---------- */ //公開HTML用のタグを返す _.getHTML = function(_o){ return this.getPreview(_o,true); } /* ---------- ---------- ---------- */ return _; })(); /* ! ---------- ---------- ---------- ---------- ---------- */ PageElement.object.sampleTable = (function(){ var _ = new PageModel.Object_(); /* ---------- ---------- ---------- */ //ブロック定義 _.pageInfo = new PageModel.Object_Info({ id : "object.sampleTable", custom : true, name : "サンプル表組み", name2 : "サンプル表組みです。カスタマイズのベースとして利用してください。", inputs : ["CLASS","CSS","DETAIL"] }); /* ---------- ---------- ---------- */ //入力の設定 var defImage = { mode:"simple" , path: "width:150,height:100", width: "", ratio: "" } _.grids = [ /* ---------- ---------- ---------- */ new PageModel.Object_Grid({ gridType:Dic.GridType.BASE, gridInfo:new PageModel.OG_info({ id : "list", name : "リスト", note : "サンプルの文書ですので、ご注意ください。サンプルの文書ですので、ご注意ください。" }), textData:null, gridData:{ info: new PageModel.OG_SubInfo({ name: "リスト", note: "サンプルの文書ですので、ご注意ください。サンプルの文書ですので、ご注意ください。" }), cells:[ new PageModel.OG_Cell({ id: "t1", name: "テキスト1", type: CELL_TYPE.MULTI, def: "サンプルの文書ですので、ご注意ください。" }), new PageModel.OG_Cell({ id: "t2", name: "テキスト2", type: CELL_TYPE.MULTI, def: "サンプルの文書ですので、ご注意ください。" }), new PageModel.OG_Cell({ id: "t3", name: "テキスト3", type: CELL_TYPE.MULTI, def: "サンプルの文書ですので、ご注意ください。" }), new PageModel.OG_Cell({ id: "t4", name: "テキスト4", type: CELL_TYPE.MULTI, def: "サンプルの文書ですので、ご注意ください。" }) ] } }) /* ---------- ---------- ---------- */ ] /* ---------- ---------- ---------- */ //初期データ _.getInitData = function(){ var o = {}; o.type = _.pageInfo.id; o.data = _.getDefData(3); o.attr = {}; return o; } /* ---------- ---------- ---------- */ //プレビュー用のタグを返す (管理画面での表示) _.getPreview = function(_o,_isPub){ var data = _o.data; var attr = _o.attrs; var tag = ""; attr = attr.split('class="').join('class="sampleTable '); tag += '<div '+attr+'>\n'; tag += '<h2 class="cms-h default ">表組みサンプル</h2>'; var list = CMS_U.getPublicList(data.list.grid); if(list.length == 0){ tag += '<span class="_no-input-data">データリストを入力...</span>' } else{ tag += '<table class="cms-table default narrow">\n'; for (var i = 0; i < list.length ; i++) { var row = list[i]; tag += '<tr>\n'; tag += '<th>' + (i+1) + '</th>\n'; tag += '<td>' + __f.getTagText(row.t1) + '</td>\n'; tag += '<td>' + __f.getTagText(row.t2) + '</td>\n'; tag += '<td>' + __f.getTagText(row.t3) + '</td>\n'; tag += '<td>' + __f.getTagText(row.t4) + '</td>\n'; tag += '</tr>\n'; } tag += '</table>\n'; } tag += '</div>\n'; return tag; } /* ---------- ---------- ---------- */ //公開HTML用のタグを返す _.getHTML = function(_o){ return this.getPreview(_o,true); } /* ---------- ---------- ---------- */ return _; })(); /* ! ---------- ---------- ---------- ---------- ---------- */ <file_sep>/src/js/cms_data/CMS_Data.MyTag.p2.js CMS_Data.MyTagReplace = (function(){ /* ---------- ---------- ---------- */ //テキスト置き換え function replaceHTML(_temp){ if(_temp.indexOf("{{") == -1) { return _temp; } //外部の置換リストとマージ var repKeys = (function(_a1,_a2){ if(!_a2) return _a1; if(_a2.length == 0) return _a1; return CMS_U.meargeGrid(_a1, _a2); })( CMS_Data.MyTag.getDataFlat() , getLocalMyTagList() ); //置換え実行 return CMS_Data.MyTagU.getReplaceTag(_temp, repKeys); } /* ---------- ---------- ---------- */ //雛形ブロック処理 //ひな形ブロック置換え処理 function replaceHinagata(_id,_list){ //MyタグIDから値を取得 var _data = getMyTagData(_id); if(!_data) return "-----"; //tag.js処理用に一時的に保持 CMS_Data.HinagataSearvice.setState(_list); //Myタグ値のノードごとに処理 var s = ""; if(_data.type == "text"){ s += replaceHinagata_one(_data.val); } else if(_data.type == "image"){ s += "※ Myタグリスト / イメージでは、ひな形は利用できません。"; } else if(_data.type == "link"){ s += "※ Myタグリスト / リンクでは、ひな形は利用できません。"; } else{ var vals = _data.val; for (var n = 0; n < vals.length ; n++) { s += replaceHinagata_one(vals[n]); } } CMS_Data.HinagataSearvice.reset(); return s; } function replaceHinagata_one(_val){ //リスト系のブロックに最大件数を追加 _val = JSON.parse(JSON.stringify(_val)); for (var n in _val.data) { if(_val.data[n]){ if(_val.data[n].texts){ var ts = _val.data[n].texts; for (var g in ts) { ts[g] = CMS_Data.HinagataSearvice.replace(ts[g]); } } } } var s = PageElement_HTMLService.getTag(_val); s = CMS_Data.HinagataSearvice.replace(s); return s; } function getMyTagData(_id){ //グローバルMyタグリストから探す var _tmp = CMS_Data.MyTag.getData() for (var n in _tmp){ var ls = _tmp[n]; for (var i = 0; i < ls.length ; i++) { if(_isMatch(_id,ls[i].id)) { return ls[i]; } } } //ローカルMyタグリストから探す var ls = getLocalMyTagList(); if(ls){ for (var i = 0; i < ls.length ; i++) { if(_isMatch(_id,ls[i].id)) { return ls[i]; } } } return null; } function _isMatch(_id,_key){ return (_id == "{{" + _key + '}}'); } /* ---------- ---------- ---------- */ //ローカルでMyタグ+ひな形ブロックを使うための前処理 //ページ公開時にセットされる var _localMyTagList; function getLocalMyTagList(){ updateLocalMyTagList(); return _localMyTagList; } function updateLocalMyTagList(){ if(isPublising) return; // _localMyTagList = null; var currentData = CMS_PageDB.getCurrentPageStoreData(); if(currentData){ _localMyTagList = _parseData(currentData); } } //ページ公開時(バッチ公開時に必要な処理) var isPublising = false; function startPublish(_pageData){ _localMyTagList = null; if(_pageData){ _localMyTagList = _parseData(_pageData); } isPublising = true; } function endPublish(){ isPublising = false; } /* ---------- ---------- ---------- */ function _parseData(_json){ return CMS_Data.MyTagU.parseData(_json); } /* ---------- ---------- ---------- */ return { replaceHTML:replaceHTML, replaceHinagata:replaceHinagata, getLocalMyTagList:getLocalMyTagList, startPublish:startPublish, endPublish:endPublish } })();<file_sep>/src/js/cms_storage/Storage.SimpleIO.js /** * TemplateFileEdi..で使用するIOクラス */ Storage.SimpleIO = (function(_filename,_dir) { /* ---------- ---------- ---------- */ var c = function(_filename,_dir) { this.init(_filename,_dir); } var p = c.prototype; /* ---------- ---------- ---------- */ p.filename; p.text; p.init = function(_filename,_dir) { this.dir = _dir; // if(this.dir.indexOf("/") == -1) this.dir = this.dir+ "/"; this.filename = _filename; this.text = ""; } p.reload = function(_callback) { this.load(_callback); } p.load = function(_callback) { var this_ = this; var path = this.dir+"/"+ this.filename; var url = CMS_Path.PHP_FILEPATH + '?action=read&path=' + path; $.ajax({ scriptCharset : 'utf-8', type : 'GET', url : url, dataType : 'text', success : function(data) {this_.text = data;_callback(data)}, error : function(data) { CMS_ErrorView.stageIn("NET",url,null,data); // alert("ファイルのロードに失敗しました。"); } }); if(isLog)console.log( ["Storage.SimpleIO.load ", path]); } p.preview = function(_callback) { } p.save = function(_t,_callback) { var param ={} param.action = "write"; param.dir_name = this.dir; param.file_name = this.filename; param.text = _t; var url = CMS_Path.PHP_FILEPATH; $.ajax({ scriptCharset : 'utf-8', type : 'POST', url : url, data : Storage.Util.escape_(param), dataType : 'json', success : function(data) { if(API_StatusCheck.check(data) == false) return; _callback(data) }, error : function(data) { CMS_ErrorView.stageIn("NET",url,param,data); } }); if(isLog)console.log( ["Storage.SimpleIO.save ", param.file_name , param]); } return c; })(); <file_sep>/src/js/cms_model/PageElement_Util.js var PageElement_Util = (function(){ function _traceElementInfo(){ var a = ["layout","replace","tag","object"]; for (var i = 0; i < a.length ; i++) { var tar = PageElement[a[i]]; for (var m in tar) { console.log([tar[m].pageInfo.id,tar[m].pageInfo.name]); } } } //現在登録されているブロックを調べる。開発用。 window.traceElementInfo = _traceElementInfo; /* ---------- ---------- ---------- */ function getElementInfo(_type){ var o = {} if(!_type) return o; if(_type == "replace.div"){ o = PageElement.replace.div;} if(_type == "layout.div"){ o = PageElement.layout.div;} if(_type == "layout.cols"){ o = PageElement.layout.cols;} if(_type == "layout.colDiv"){ o = PageElement.layout.colDiv;} if(isElement(_type)){ var t = _type.split(".")[1]; if (_type.indexOf("tag.") == 0) { o = PageElement.tag[t]; } if (_type.indexOf("object.") == 0) { o = PageElement.object[t]; } } return o; } window.getElementInfo = getElementInfo; /* ---------- ---------- ---------- */ //初期データ取得 function getInitData(_type,_param){ var tar = getElementInfo(_type) var o = tar.getInitData(_param); o["class"] = o.css; return o; } /* ---------- ---------- ---------- */ //プレビューHTMLデータ取得 function getPreview(param){ // var attr = (function(_p){ var s = defaultVal(_p.attr["style"],""); var c = defaultVal(_p.attr["class"],""); return ' class="' + c + '" style="' + s + '" '; })(param); var o = createParam(param); o.attrs = attr; o.extra = (param["extra"]) ? param.extra : {}; if(isElement(param.type)){ var ts = param.type.split("."); if(PageElement[ts[0]]){ var tar = PageElement[ts[0]][ts[1]]; if(tar) return tar.getPreview(o); } } return ""; } /* ---------- ---------- ---------- */ //HTMLデータ取得 function getHTML(param,attr,tab){ var o = createParam(param) o.attrs = attr; o.extra = (param["extra"]) ? param.extra : {}; if(isElement(param.type)){ var tar; var t = param.type.split(".")[1]; if (param.type.indexOf("tag.") == 0) tar = PageElement.tag[t]; if (param.type.indexOf("object.") == 0) tar = PageElement.object[t]; if(tar) return tar.getHTML(o,tab); } return ""; } /* ---------- ---------- ---------- */ function createParam(param){ var o = {} o.type = param.type; o.data = param.data; o.link = defaultVal(param.attr["link"], ""); o.preview = defaultVal(param.attr["preview"], "");//HTMLのプレビュ o.id = defaultVal(param.attr["id"], ""); return o; } /* ---------- ---------- ---------- */ //tabもしくはobjectか? function isElement(_type){ var b = false if (_type.indexOf("tag.") == 0) b = true; if (_type.indexOf("object.") == 0) b = true; return b; } /* ---------- ---------- ---------- */ function hasAttr(_attr){ var s = _attr; s = s.split(" ").join(""); s = s.split('class=""').join(''); s = s.split('style=""').join(''); if(s == "") return false; return true; } /* ---------- ---------- ---------- */ //インスペクタビューでの名前取得 function getTypeName(_type){ var list = PageElement_DIC; var n = ""; for (var i = 0; i <list.length ; i++) { if(_type == list[i].type){ n = '<span class="_t1">'+ list[i].name + "ブロック</span>" // n += '<span class="_t2">'+ list[i].name2 + "</span>" } } n = n.split("<br>").join("") return n; } function getTypeName_t1(_type){ var list = PageElement_DIC; var n = ""; for (var i = 0; i <list.length ; i++) { if(_type == list[i].type){ return list[i].name; } } return ""; } /* ---------- ---------- ---------- */ //インスペクタビューの入力可能タイプの取得 function hasInputType(_type,_input){ var list = PageElement_DIC; var n = ""; for (var i = 0; i <list.length ; i++) { if(_type == list[i].type){ var inputs = list[i].inputs; for (var ii = 0; ii <inputs.length ; ii++) { if(inputs[ii] == _input) return true; } } } return false; } /* ---------- ---------- ---------- */ //データグリッドでの値の範囲を取得 function getGridMaxLeng(_a,_leng){ var max = 0 for (var i = 0; i < _a.length ; i++) { for (var ii = 0; ii < _leng ; ii++) { if(_a[i]["c"+(ii+1)]){ if(max < ii){ max = ii } } } } return max; } /* ---------- ---------- ---------- */ /* ---------- ---------- ---------- */ function _getMaxLeng(_type){ var n; if(window["GRID_PREVIEW_MAX_ROW"]){ var o = GRID_PREVIEW_MAX_ROW; if(_type == "news") n = o["NEWS"]; if(_type == "table") n = o["TABLE"]; if(_type == "custom") n = o["CUSTOM"]; if(_type == "data") n = o["DATA"]; } if(isNaN(n)) n = 50; return n; } function getOmitLeng(_n,_type,_isPub){ if (_isPub) return _n; var max = _getMaxLeng(_type); if(max < _n){ return max; } return _n; } function getOmitPreviewTag(_n,_type,_isPub){ if (_isPub) return ""; var max = _getMaxLeng(_type); if(max < _n){ return '<div class="_cms_blockAnno">※ページ編集画面では、'+max+"件以上は、省略して表示されます。</div>" ; } return ""; } function getListLeng(_data,_leng){ if(!_data.setting) _data.setting = {} if(!_data.setting.texts) _data.setting.texts = {} if(!_data.setting.texts.max) _data.setting.texts.max = _leng; var max = _data.setting.texts.max; if(max){ if(!isNaN(max)){ _leng = (_leng < max) ? _leng : max; } } return _leng; } /* ---------- ---------- ---------- */ function isReplaceTag(_type){ if(!_type) return false; if(_type == "object.replaceTexts") return true; if(_type == "replace.div")return true; return false; } /* ---------- ---------- ---------- */ function getCaption(_extra){ var tag = ""; if(_extra){ if(_extra.head){ tag += '<div class="caption">' +_extra.head+ '</div>\n' } } return tag; } /* ---------- ---------- ---------- */ return { getElementInfo: getElementInfo, getInitData: getInitData, getPreview: getPreview, getHTML: getHTML, isElement: isElement, hasAttr: hasAttr, getTypeName: getTypeName, getTypeName_t1: getTypeName_t1, hasInputType: hasInputType, getGridMaxLeng: getGridMaxLeng, getOmitLeng:getOmitLeng, getOmitPreviewTag:getOmitPreviewTag, getListLeng:getListLeng, isReplaceTag:isReplaceTag, getCaption: getCaption } })(); window.PageElement_Util = PageElement_Util; <file_sep>/gulpfile.js var gulp = require("gulp"); var exec = require('gulp-exec'); var dir = require( 'require-dir' ); dir( './tasks', { recurse: true } ); gulp.task('watch', function() { gulp.watch('./src/js/**/*', ['concat:js']); gulp.watch('./src/sass/**/*', ['concat:css']); }); <file_sep>/src/js/cms_main/CMS_Status.js var CMS_Status = { sitemapDirOpens: null, W: 1000, H: 1000, mouseX: 0, mouseY: 0, //現在編集中の情報 // currentPage:null, // currentPage_preview:null, //フリーレイアウトで、コピペで使う clipBord: "", clipBordPage: "" } var CMS_StatusFunc = (function() { function setSitemapDirOpens(_a) { CMS_Status.sitemapDirOpens = _a } function checkSitemapDirOpens_by_id(_id) { var openList = CMS_Status.sitemapDirOpens for (var i = 0; i < openList.length; i++) { if ("sitemap_" + _id == openList[i][0]) { if (openList[i][1] == 1) { return true; } } } return false; } return { setSitemapDirOpens: setSitemapDirOpens, checkSitemapDirOpens_by_id: checkSitemapDirOpens_by_id } })();<file_sep>/src/js/cms_stage_sidepreview/CMS_SidePreviewClose.js var CMS_SidePreviewClose = (function(){ var view; var v = {}; function init(){ view = $('#CMS_SidePreviewClose'); //stageInit(); createlayout(); setBtn(); } /* ---------- ---------- ---------- */ function createlayout(){ var tag = '' tag += '<div class="_header">'; tag += ' <div class="_cms_btn_alpha _btn_open"><i class="fa fa-caret-left "></i> <i class="fa fa-desktop "></i> </div>'; tag += '</div>'; // tag += '<div class="_bottom"><div class="_core"></div></div>'; // tag += '<div class="_bottom _b1"><div class="_core">+</div></div>'; // tag += '<div class="_bottom _b2"><div class="_core">-</div></div>'; view.append(tag); v.btn_open = view.find('._btn_open'); v.btn_open.click(function() { CMS_StageController.openPreviewStage(true); }); } function setBtn(){ } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } function stageIn(){ if(! isOpen){ isOpen = true; view.show(); if(isFirst){} isFirst = false; } } function stageOut(){ if(isOpen){ isOpen = false; view.hide(); } } return { init:init, stageIn:stageIn, stageOut:stageOut } })(); <file_sep>/src/js/cms_model/PageElement.object.btnList.js PageElement.object.btnList = (function(){ var _ = new PageModel.Object_(); /* ---------- ---------- ---------- */ _.pageInfo = new PageModel.Object_Info({ id : "object.btnList", name : "ボタンリスト", name2 : "<UL><LI><A>", inputs : ["CLASS","CSS","DETAIL","CAPTION"], // cssDef : {file:"block",key:"[ボタンリストブロック]"} cssDef : {selector:".cms-btns"} }); /* ---------- ---------- ---------- */ _.grids = [ /* ---------- ---------- ---------- */ new PageModel.Object_Grid({ gridType:Dic.GridType.BASE, gridInfo:new PageModel.OG_info({ id : "list", name : "リスト", note : "" }), textData:null, gridData:{ info:new PageModel.OG_SubInfo({ name:"" }), cells:[ new PageModel.OG_Cell({ id: "anchor", name: "リンク", type: CELL_TYPE.BTN, def: CMS_AnchorU.getInitData() }), new PageModel.OG_Cell({ id: "t1", name: "テキスト", type: CELL_TYPE.MULTI, def: "キャプションがはいります" }) ] } }) /* ---------- ---------- ---------- */ ] _.getInitData = function(){ var o = {}; o.type = _.pageInfo.id; var def ={ list: { texts: {}, grid: [ { publicData: "1", anchor: { href: "http://www.google.com", target: "", text: "{{(-)}} リンクボタン", class_: "", image: "" }, t1: "キャプションがはいります" }, { publicData: "1", anchor: { href: "http://www.google.com", target: "", text: "{{(-)}} リンクボタン", class_: "", image: "" }, t1: "キャプションがはいります" }, { publicData: "1", anchor: { href: "http://www.google.com", target: "", text: "{{(-)}} リンクボタン", class_: "", image: "" }, t1: "キャプションがはいります" }, { publicData: "1", anchor: { href: "http://www.google.com", target: "", text: "{{(-)}} リンクボタン", class_: "", image: "" }, t1: "キャプションがはいります" }, { publicData: "1", anchor: { href: "http://www.google.com", target: "", text: "{{(-)}} リンクボタン", class_: "", image: "" }, t1: "キャプションがはいります" } ] } } o.data = def o.attr = {css:"default",style:""}; o.attr.class = o.attr.css; return o; } _.getPreview = function(_o){ var data = _o.data; var attr = _o.attrs; var extra = _o.extra; var tag = ""; attr = attr.split('class="').join('class="cms-btns clearfix '); var list = CMS_U.getPublicList(data.list.grid); if(list.length == 0) { tag += '<span class="_no-input-data">リストデータを入力...</span>' } else{ var style = "" tag += '<div ' + attr + '>\n'; tag += PageElement_Util.getCaption(extra); tag += '<ul>\n' for (var i = 0; i < list.length ; i++) { var aTag = CMS_AnchorU.getAnchorTag(list[i].anchor,"",false) tag += ' <li>' tag += aTag ; if(list[i].t1){ tag += '<span class="btn-caption">' + list[i].t1 + '</span>'; } tag += '</li>\n' } tag += '</ul>\n' tag += '</div>\n' } return tag; } _.getHTML = function(_o){ var data = _o.data; var attr = _o.attrs; var extra = _o.extra; var tag = "" attr = attr.split('class="').join('class="cms-btns clearfix ') var list = CMS_U.getPublicList(data.list.grid); if(list.length == 0) return; { var style = "" tag += '<div ' + attr + '>\n'; tag += PageElement_Util.getCaption(extra); tag += '<ul>\n' for (var i = 0; i < list.length ; i++) { var aTag = CMS_AnchorU.getAnchorTag(list[i].anchor,"",true) tag += ' <li>' tag += aTag ; if(list[i].t1){ tag += '<span class="btn-caption">' + list[i].t1 + '</span>'; } tag += '</li>\n' } tag += '</ul>\n' tag += '</div>\n' } return tag; } /* ---------- ---------- ---------- */ return _; })(); <file_sep>/src/js/cms_util/StringU.js var StringU = (function(){ function z2h(s){ return s.replace(/[A-Za-z0-9]/g, function(s) { return String.fromCharCode(s.charCodeAt(0) - 0xFEE0); }); } function h2z(s){ return s.replace(/[A-Za-z0-9]/g, function(s) { return String.fromCharCode(s.charCodeAt(0) + 0xFEE0); }); } function zen2han(s){ s = z2h(s) return s; } function han2zen(s){ s = h2z(s); var res = (s.match(/<("[^"]*"|'[^']*'|[^'">])*>/g)); if(res){ for (var i = 0; i < res.length ; i++) { s = s.split(res[i]).join(z2h(res[i])); } } return s; } function deleteTag(s){ return s.replace(/<("[^"]*"|'[^']*'|[^'">])*>/g,'') } return { zen2han:zen2han, han2zen:han2zen, deleteTag:deleteTag } })(); var NumberU = (function(){ //NumberU.defaultNumber function defaultNumber(_n,_def){ _def = ( isNaN(_def) ) ? 0 : _def; var n = Number(_n); if(isNaN(n)){ return _def } return n } return { defaultNumber:defaultNumber } })(); <file_sep>/src/js/cms_view_inspect/InspectView.FormU_Preset.js //CSSデザインプリセット InspectView.FormU_Preset = (function(){ function init(){ //CSSファイルを更新したら、更新 CMS_Data.InspectCSS.registUpdateCallback(function(){ setNode_core(); }) } /* ---------- ---------- ---------- */ var view var v = {} var extra; var blockType; //ノードをセットし、プリセット関係のHTMLを返す function setNode(_view,_blockType,_extra){ view = _view; extra = _extra; blockType = _blockType; prevVal = "" if(CMS_Data.InspectCSS.hasData() == false){ hasNoData(); return; } v.input = _view.find("input"); v.input.keyup(function(){ keyup()}) v.wapper = $('<div class="_presetArea"></div>'); view.append(v.wapper) setNode_core(); } function hasNoData(){ var tag = "" tag += '<div class="_presetError">CSSプリセットファイルが見つからないか、未設定です。<br>'; tag += ASSET_CSS_DIRS[0]; tag += '</div>'; view.append(tag); } function setNode_core(){ v.wapper.empty(); initPreset(blockType,extra); v.presets = $(getTag()); v.items = v.presets.find("._item"); v.subWapper = v.presets.find("._presetSubWapper"); v.wapper.append(v.presets); assignEvent(); updateSelect(); } /* ---------- ---------- ---------- */ function assignEvent(){ //プリセットクリック v.presets.find("._btn_add").click(function(){ openDesignLibPage(); }); v.presets.find("._btn_item").click(function(){ selectItem($(this)); }); //編集クリック v.presets.find("._btn_edit").click(function(){ var id = $(this).parent().data("node"); CMS_MainController.openPresetCSSFile(id); }); v.presets.find("._btn_preset").click(function(){ CMS_MainController.openPresetCSSFile(""); }); v.preset_tabs = v.presets.find("._preset_tab"); v.preset_tabs.click(function(){ openTab($(this).data("no")) }) v.preset_tab_bodys = v.presets.find("._preset_tab_body"); openTab(currentTab); } var currentTab = 0 function openTab(_no){ currentTab = _no; v.preset_tabs.removeClass("_current").eq(currentTab).addClass("_current"); v.preset_tab_bodys.hide().eq(currentTab).show(); // v.preset_tab_bodys.show(); InspectView.updateBodyH(); } function openDesignLibPage(){ var s = "?class=" + currentType + "._new_"; window.open(CSS_DESIGN_URL + s ,"cms_asset"); } /* ---------- ---------- ---------- */ var tID; function keyup(){ if(tID) clearTimeout(tID); tID = setTimeout(function(){ updateSelect(); },200); } function getVal(){ var s = "" if(v.input) s = v.input.val(); return s; } function setVal(_s){ if(!_s)_s = "" if(v.input) { v.input.val(_s).keyup(); } } /* ---------- ---------- ---------- */ var currentPresetList = []; var presetsTagList = []; var presetsCommonList = []; var currentType = ""; function initPreset(_blockType,_extra){ var model = PageElement_Util.getElementInfo(_blockType); try{ currentType = model.pageInfo.cssDef.selector; }catch( e ){ currentType = ""; return; } //見出しの場合は、特別に処理 if(_blockType == "tag.heading"){ currentType = currentType.split("{h1-h6}").join(_extra); } presetsTagList = CMS_Data.InspectCSS.getList(currentType); presetsCommonList = CMS_Data.InspectCSS.getList("","common"); //がっちゃんこ currentPresetList = []; _toFlat(currentPresetList , presetsTagList); _toFlat(currentPresetList , presetsCommonList); } function _toFlat (_list,_defs){ for (var i = 0; i < _defs.length ; i++) { if(_defs[i].subs.length > 0){ for (var ii = 0; ii < _defs[i].subs.length ; ii++) { _list.push(_defs[i].subs[ii]); } } else{ _list.push(_defs[i]); } } } /* ---------- ---------- ---------- */ var itemCount = 0; function getTag(){ itemCount = 0; var tag = ""; tag += '<div class="_presetTitle">CSSプリセット <span class="_btn_preset"><i class="fa fa-pencil"></i> 編集</span></div>' tag += '<div class="_preset_tabs">' tag += ' <div class="_preset_tab" data-no="0">ブロックごと</div>' tag += ' <div class="_preset_tab" data-no="1">汎用クラス</div>' tag += '</div>' tag += '<div class="_presetItems">'; tag += ' <div class="_preset_tab_body">' tag += ' <div style="min-height:50px;">' tag += getTag_core(presetsTagList); tag += ' </div>'; if(presetsTagList.length == 0){ tag += ' <div>このブロックに対応するプリセットはありません。</div>'; } tag += ' <div class="_btn_add">デザインライブラリへ <i class="fa fa-external-link-square "></i></div>'; tag += ' </div>'; tag += ' <div class="_preset_tab_body">'; tag += getTag_core(presetsCommonList) tag += '<div style="line-height:1.4;margin:5px 0 0 0;">※ 汎用クラスでは、先頭に<span style="color:#ff0">sp-</span>とつけると、スマホ向け指定できます。</div>' tag += ' </div>'; tag += '</div>' return tag; } function getTag_core(pres){ var tag = ""; for (var i = 0; i < pres.length ; i++) { var hasSub = false; if(pres[i].subs){ if(pres[i].subs.length > 0) hasSub = true; } if(hasSub){ tag += '<div class="_presetSubWapper">'; tag += ' <div class="_presetSubTitle"><i class="fa fa-bars "></i> '+pres[i].label+' <i class="fa fa-angle-right "></i></div>'; tag += ' <div class="_presetSubs">' for (var ii = 0; ii < pres[i].subs.length ; ii++) { tag += getTagItem(pres[i].subs[ii]); } tag += ' </div>'; tag += '</div>'; } else{ tag += getTagItem(pres[i]); } } return tag; } //個別プリセット function getTagItem(_o){ var temp = ""; if(_o.class == "---") { temp += '<div class="_item _hr"></div>' } else{ temp += '<div class="_item" data-node="{NODE}" data-id="{CLASS}">'; temp += ' <span class="_btn_item">{ICON_ON}{ICON_OFF} {NAME} <span class="_cssName">{CLASS}</span></span>'; temp += ' <span class="_btn_edit"><i class="fa fa-pencil"></i> 編集</span>'; temp += '</div>'; temp = temp.split("{NO}").join(itemCount); temp = temp.split("{ICON_ON}").join('<i class="fa fa-check-square _checked"></i>'); temp = temp.split("{ICON_OFF}").join('<i class="fa fa-square-o _not_checked"></i>'); temp = temp.split("{NAME}").join(_o.label); temp = temp.split("{NODE}").join(_o.selector); temp = temp.split("{CLASS}").join(_o.class); itemCount++; } return temp; } /* ---------- ---------- ---------- */ /* ---------- ---------- ---------- */ /* ---------- ---------- ---------- */ //選択時 function selectItem(_node){ var _val = _node.parent().data("id") var isSelected = _node.parent().hasClass("_current"); var a = _treat( getVal() ).split(" "); if(! isSelected){ //追加 a.push(_val); } else{ //削除 var pres = currentPresetList; var _a = []; for (var i = 0; i < a.length ; i++) { var has = true; for (var ii = 0; ii < pres.length ; ii++) { if(a[i] == pres[ii].class){ if(_val == a[i]){ has = false; } } } if(has)_a.push(a[i]); } a = _a; } setVal(a.join(" ")); updateSelect(); } //_currentアップデート var CURRENT = "_current" var prevVal = ""; function updateSelect(){ if(prevVal == getVal()) return; prevVal = getVal(); var a = _treat(prevVal).split(" "); var pres = currentPresetList; var _currents = []; for (var n = 0; n < a.length ; n++) { var name = a[n]; for (var i = 0; i < pres.length ; i++) { if(name == pres[i].class){ _currents.push(i); } } } v.items.removeClass(CURRENT); for (var i = 0; i < _currents.length ; i++) { var n = _currents[i]; v.items.eq(n).addClass(CURRENT); } v.subWapper.removeClass(CURRENT); v.subWapper.each(function (index, dom) { if($(this).find("." + CURRENT).size() > 0){ $(this).addClass(CURRENT); } }); } /* ---------- ---------- ---------- */ function _treat(_s){ if(_s == undefined) return "" _s = _s.split(" ").join(" "); _s = _s.split(" ").join(" "); _s = _s.split(" ").join(" "); return _s; } return { init:init, setNode:setNode } })(); <file_sep>/src/js/cms_model/PageElement.object.data_csv.js if(window["GRID_EDIT_MAX_CELL"] == undefined){ window.GRID_EDIT_MAX_CELL = {} GRID_EDIT_MAX_CELL.DATA = 15; } var PageElement_data_gridCell = (function(_max){ var a = []; var defs = [ "サンプルの文書。", "サンプルの文書ですので、ご注意ください。" , "サンプルの文書ですので、ご注意ください。" ]; for (var i = 0; i < _max ; i++) { var def = (defs.length > i) ? defs[i] :""; a.push( new PageModel.OG_Cell({ id: "c" + (i+1), name: (i+1), type: CELL_TYPE.MULTI, def: def }) ); } return a; })(GRID_EDIT_MAX_CELL.DATA); PageElement.object.data_csv = (function(){ var _ = new PageModel.Object_(); /* ---------- ---------- ---------- */ _.pageInfo = new PageModel.Object_Info({ id : "object.data_csv", name : "データブロックCSV", name2 : "", inputs : ["DETAIL"] }); /* ---------- ---------- ---------- */ var gridSum = GRID_EDIT_MAX_CELL.DATA; _.grids = [ /* ---------- ---------- ---------- */ new PageModel.Object_Grid({ gridType:Dic.GridType.BASE, gridInfo:new PageModel.OG_info({ id : "table", name : "データ", note : "" }), textData:{ info:new PageModel.OG_SubInfo({ name:"設定", note:"", image: "" }), cells:[ new PageModel.OG_Cell({ id: "spliter", name: "区切り文字", type: CELL_TYPE.SINGLE, style: SS.w50, view: "", def: ",", note: "データの区切り文字を入力してください。一般的には、カンマやタブを使用します。<br>なにも入力しない場合は、タブが使用されます。" }), new PageModel.OG_Cell({ id: "text_before", name: "データの前に追加するテキスト", style: SS.w400, type: CELL_TYPE.MULTI, view: "", def: "", note: "例: &lt;textarea id=\"data\" style=\"display:none;\"&gt;" }), new PageModel.OG_Cell({ id: "text_after", name: "データの後ろに追加するテキスト", style: SS.w400, type: CELL_TYPE.MULTI, view: "", def: "", note: "例: &lt;/textarea&gt;" }) ] }, gridData:{ info: new PageModel.OG_SubInfo({ name: "データグリッド", note: "セル内の改行は、出力時には無視されます。" }), cells:JSON.parse(JSON.stringify(PageElement_data_gridCell)) } }) ] /* ---------- ---------- ---------- */ _.getInitData = function(){ var o = {}; o.type = _.pageInfo.id; o.data = _.getDefData(3); o.attr = {css:"",style:""}; return o; } /* ---------- ---------- ---------- */ _.getPreview = function(_o){ var data = _o.data; var attr = _o.attrs; var tag = ""; var list = CMS_U.getPublicList(data.table.grid); tag += '<div class="_cms_preview">\n' tag += '<div class="_title">データブロック / CSVデータ</div>' tag += '<div class="_notes">ブロック情報パネルの、[出力]タブよりファイル名を設定し、書出せます。</div>' if(list.length == 0){ tag += '<span class="_no-input-data">データリストを入力...</span>' } else{ var maxLeng = PageElement_Util.getGridMaxLeng(list,gridSum); tag += '<table class="_dataTable">\n' tag += '<tbody>\n' var leng = PageElement_Util.getOmitLeng(list.length,"data"); for (var i = 0; i < leng ; i++) { tag += ' <tr>\n'; for (var ii = 0; ii < maxLeng +1 ; ii++) { var s = CMS_TagU.tag_2_t(list[i]["c"+(ii+1)]); s = s.split("\n").join(""); tag += ' <td>' + s + '</td>\n'; } tag += ' </tr>\n'; } tag += "</tbody>\n"; tag += "</table>\n"; tag += PageElement_Util.getOmitPreviewTag(list.length ,"data") } tag += "</div>\n"; return tag; } /* ---------- ---------- ---------- */ _.getHTML = function(_o,_tab){ var data = _o.data; var attr = _o.attrs; var sep = data.table.texts.spliter || "\t"; var text_before = data.table.texts.text_before || ""; var text_after = data.table.texts.text_after || ""; var grid = CMS_U.getPublicList(data.table.grid); if(grid.length == 0) return ""; var a = []; var maxLeng = PageElement_Util.getGridMaxLeng(grid,gridSum); var lines = [] for (var i = 0; i < grid.length ; i++) { var row = [] for (var ii = 0; ii < maxLeng + 1 ; ii++) { var s = grid[i]["c"+(ii+1)]; if(s ==undefined) s = ""; s = s.split("\n").join(""); row.push(s); } lines.push(row.join(sep)) } return text_before + lines.join("\n") + text_after; } /* ---------- ---------- ---------- */ return _; })(); <file_sep>/src/js/cms_view_inspect/InspectView.p3.js /* ---------- ---------- ---------- */ //#選択要素へ、選択クラスをアサイン var prevClickNode; var _SN = "_selected"; function setSelected(){ $(prevClickNode).removeClass(_SN); $(currentNode).addClass(_SN); stageIn(); } function unselect(){ if(currentNode) $(currentNode).removeClass(_SN); _unselect_select_target(); } /* ---------- ---------- ---------- */ //選択ブロックを操作 //次のブロック選択 function selectNodeNext(_n){ if(currentDiv){ if(currentDiv["selectNodeNext"]){ currentDiv.selectNodeNext(currentNo+_n); } } updateScrollPos(); } window.selectNodeNext = selectNodeNext; //ブロックの複製 function duplicateData(){ currentDiv.duplicateData(currentNo); updateNodeNo(); updateScrollPos(); hilightElement(); } //ブロックの移動 function historyBack(){ currentDiv.historyBack(); } function moveData(_n){ if(! currentDiv.canMove(currentNo,currentNo + _n))return; currentDiv.moveData(currentNo,currentNo + _n); currentNo += _n; updateNodeNo(); updateScrollPos(); } function moveDataToFirst(){ currentDiv.moveDataToFirst(currentNo); currentNo = 0; updateNodeNo(); updateScrollPos(); } function moveDataToLast(){ var _move = currentDiv.moveDataLast(currentNo); currentNo = _move; updateNodeNo(); updateScrollPos(); } //画面スクロール位置の調整 function updateScrollPos(_b){ if(currentNode){ CMS_ScreenManager.updatePageScroll($(currentNode).offset().top,_b); } } /* ---------- ---------- ---------- */ //attr function setAttr_attr (val){ setAtt("attr",val); } function setAttr_id (val){ setAtt("id",val); } function setAttr_css (val){ setAtt("css",val); } function setAttr_style (val){ setAtt("style",val); } function setAttr_preview (val){ setAtt("preview",val); } function setAttr_pubFileName(val){ setAtt("pubFileName",val); } function setAttr_embedName (val){ setAtt("embedName",val); } function setAttr_embedID (val){ setAtt("embedID",val); } function setAttr_narrow (val){ setAtt("narrow",val); } function setAttr_hide (val){ setAtt("hide",val); } function setAttr_hidePC (val){ setAtt("hidePC",val); } function setAttr_hideMO (val){ setAtt("hideMO",val); } function setAttr_replaceID (val){ setAtt("replaceID",val); } // function setAttr_hidePC (val){ (val) ? setAtt("hidePC",val) : delAtt("hidePC"); } // function setAttr_hideMO (val){ (val) ? setAtt("hideMO",val) : delAtt("hideMO"); } /* ---------- ---------- ---------- */ //#タグのattributeを計算 function setAtt(_s,_v){ if(param.attr[_s] == _v)return; CMS_BlockAttrU.setAttr(param.attr,_s,_v); var t = blockType; //コンテナの背景対応 if(t == "layout.div" && _s == "style") { _v = CMS_ImgBlockU.getBgStyle(param.extra) +_v; } replacePropNode.attr(_s,_v); if(t == "layout.cols"){ replacePropNode.attr("class","cms-column " + CMS_BlockAttrU.clucuCss(param.attr)); updateTagPreview(); } else if( t == "layout.div" || t == "replace.div"){ replacePropNode.attr("class","cms-layout " + CMS_BlockAttrU.clucuCss(param.attr)); updateTagPreview(); } else if( t == "layout.colDiv"){ replacePropNode.attr("class","cms-column-col " + CMS_BlockAttrU.clucuCss(param.attr)); updateTagPreview(); } else { updateCallerView(); } //レイアウトDIVのIDを変更した場合は、 //_block_infoを探して上書きする。 if(CMS_BlockAttrU.isMarkAttr(_s)){ if(t == "layout.cols" || t == "layout.div" || t == "replace.div"){ var tar = currentNode.find("> ._block_info"); tar.html(CMS_BlockAttrU.getMarkTag(param.attr)); updateTagPreview(); } } currentDiv.updateSubData(); } /* function delAtt(_s){ if(param.attr[_s]){ delete param.attr[_s]; updateTagPreview(); currentDiv.updateSubData(); } }*/ /* ---------- ---------- ---------- */ //#選択元の要素をアップデート var tID_update function updateCallerView(){ var cs = "_updating_block"; if(blockType=="layout.div"){ replacePropNode.attr("style", CMS_ImgBlockU.getBgStyle(param.extra) + param.attr["style"]); return; } var tar = replaceNode.find(' > *').eq(0); tar.addClass(cs); // if(tID_update) clearTimeout(tID_update) tID_update = setTimeout(function(){ tar.removeClass(cs); updateCallerView_core(); },200); } function updateCallerView_core(){ updateTagPreview(); //プレビュー更新 var tar = replaceNode.find(' > *').eq(0); var tag = PageElement_Util.getPreview(param); tag = HTMLServiceU.getReplacedHTML(tag,pageParam,"",false); try{ tar.replaceWith(tag); }catch( e ){ tar.replaceWith(CMS_E.PARSE_ERROR); } //マーク更新 var tar = replaceNode.find(' > ._block_info'); var tag = CMS_BlockAttrU.getMarkTag(param.attr); tar.html(tag); currentDiv.updateSubData(); } /* ---------- ---------- ---------- */ //#タグプレビュー アップデート function updateTagPreview(){ var s = "" if(JSON.stringify(param).length > 10000){ //データが多い場合は、時間がかかるのでプレビューしない s = "選択ブロックのデータ量が多く、プレビューに時間がかかるため、このブロックはHTMLプレビューできません。" } else{ s = PageElement_HTMLService.getTag(param); s = HTMLServiceU.getReplacedHTML(s,{},"",false); s = s.split("\n").join(""); s = CMS_TagU.tag_2_t(s); } v.miniPreviw.html(s.substr(0,200)); } /* ---------- ---------- ---------- */ //ハイライト表示 var hilght_tID; function hilightElement(){ $("body").addClass("_copyBlock"); if(hilght_tID) clearTimeout(hilght_tID); hilght_tID = setTimeout(function(){ $("body").removeClass("_copyBlock"); },200); } /* ---------- ---------- ---------- */ //#コンテナ開閉トグル function toogleDivView(){ InspectView.View.toggleNarrow(); } /* ---------- ---------- ---------- */ //#コピペ function deleteData(){ currentDiv.removeData(currentNo); updateNodeNo(); } function copyData(){ CMS_Status.clipBord = JSON.stringify(param); hilightElement(); } function cutData(){ copyData(); deleteData(); } function pastData(){ param = JSON.parse(CMS_Status.clipBord) AddElementsManager.addElement_by_object(param); updateNodeNo(); updateScrollPos(); hilightElement(); } function pastData2(){ param = JSON.parse(CMS_Status.clipBord) currentDiv.changeData(param,currentNo); if(currentDiv.parent.update != undefined){ currentDiv.parent.update(); } else{ currentDiv.update(); } updateNodeNo(); updateScrollPos(); hilightElement(); } //ノードの順番情報をアップデート function updateNodeNo(){ $(currentNode).data("no",currentNo); AddElementsManager.setData( currentDiv , currentNo); } function getCurrentNo(val) { return currentNo; } /* ---------- ---------- ---------- */ //#タグ表示 function showTag(){ var this_ = this; var s = PageElement_HTMLService.getTag(param) s = HTMLServiceU.getReplacedHTML(s,{},"",false); Editer_TAGView.stageIn(s,function(_s){}); } /* ---------- ---------- ---------- */ //#JSON表示と編集 function editJSON(){ Editer_JSONView.stageIn( JSON.stringify(param, null, " "), function(_s){ editJSON_core(_s); } ) } function editJSON_core(_s){ try{ var d = JSON.parse(_s); }catch( e ){ alert("データ形式が正しくありません。"); return false; }; if(_s != null){ UpdateDelay.delay(function(){ var o = JSON.parse(_s); param = o; currentDiv.changeData(param,currentNo); if(currentDiv.parent.update != undefined){ currentDiv.parent.update(); } else{ currentDiv.update(); } }); } } /* ---------- ---------- ---------- */ //#JSON表示と編集 function addToMyBlock(){ } /* ---------- ---------- ---------- */ //#Stage var isOpen = false; var isFirst = true; function stageInit() { view.hide(); } function stageIn() { if(isFirst){ var w = view.width(); var h = view.height(); var offsetX = 70; var offsetY = 160; if(CMS_StatusW > 1300) { offsetX = 140; } view.css("left",( CMS_StatusW - w - offsetX ) +"px"); view.css("top", offsetY + "px"); isFirst = false; } updatePosition() view.show(); } function updatePosition() { var W = CMS_StatusW var H = CMS_StatusH var l = Number(view.css("left").split("px").join("")); var t = Number(view.css("top").split("px").join("")); var w = view.width(); var h = view.height(); if(l + 50 > W) view.css("left",(W - w -50) +"px"); if(t + 50 > H) view.css("top",(H - h -20) +"px"); } function stageOut() { unselect(); currentNode = null; view.hide(); } function stageOut_core() { view.hide(); } /* ---------- ---------- ---------- */ //ひな形ブロックリロードのみで使用 function refreshBlock(){ hilightElement(); setTimeout(function(){ currentDiv.update(); },100); } /* ---------- ---------- ---------- */ //プリセットステージで使用。 //ブロックが選択されたら、コールする var select_target; function addSelectCallback(_tar){ select_target = _tar; } function resetSelectCallback(){ select_target = null; } function _select_select_target(){ if(select_target){ if(select_target.select) select_target.select(); } } function _unselect_select_target(){ if(select_target){ if(select_target.unselect) select_target.unselect(); } } /* ---------- ---------- ---------- */ return { init: init, stageIn: stageIn, stageOut: stageOut, doCommand: doCommand, setPageData: setPageData, setData: setData, setData_DoubleClick: setData_DoubleClick, setAtt : setAtt, setAttr_attr : setAttr_attr, setAttr_id : setAttr_id, setAttr_css : setAttr_css, setAttr_style : setAttr_style, setAttr_preview : setAttr_preview, setAttr_pubFileName : setAttr_pubFileName, setAttr_embedName : setAttr_embedName, setAttr_embedID : setAttr_embedID, setAttr_narrow : setAttr_narrow, setAttr_hide : setAttr_hide, setAttr_hidePC : setAttr_hidePC, setAttr_hideMO : setAttr_hideMO, setAttr_replaceID : setAttr_replaceID, updateScrollPos: updateScrollPos, updateCallerView: updateCallerView, getCurrentNo: getCurrentNo, updateBodyH: updateBodyH, refreshBlock: refreshBlock, addSelectCallback:addSelectCallback, resetSelectCallback:resetSelectCallback } })(); <file_sep>/src/js/cms_stage_page/CMS_PageList_StateManager.js //ページ編集ステートを管理する。サイトマップのDate更新用 var CMS_PageList_StateManager = (function() { var list = [] function hasData(_id,_dir) { _dir = _dir || ""; for (var i = 0; i < list.length; i++) { if (_id == list[i][0]) { if (_dir == list[i][1]) { return true; } } } return false; } /* ---------- ---------- ---------- */ function isEdited(_id,_dir){ var b = hasData(_id,_dir); // console.log([b,_id,_dir]); return b; } /* ---------- ---------- ---------- */ function openedPage(_page){ // } var lastEeditID; var lastEeditDIR; function editedPage(_id,_dir){ _dir = _dir || ""; if (hasData(_id,_dir) == false) { list.push([_id,_dir]); } var b = true if(lastEeditID == _id){ if(lastEeditDIR == _dir){ b = false; } } if(b)CMS_PageList_PageDB.updateEditState(); lastEeditID = _id; lastEeditDIR = _dir; } function savedPage(_id,_dir){ _dir = _dir || ""; var a = [] for (var i = 0; i < list.length; i++) { var b = true; if (_id == list[i][0]) { if (_dir == list[i][1]) { b = false; } } if(b)a.push(list[i]); } list = a; CMS_PageList_PageDB.updateEditState(); lastEeditID = false; lastEeditDIR = false; } function publishedPage(_id,_dir){ _dir = _dir || ""; CMS_PageList_PageDB.updateEditState(); } function unPublishedPage(_id,_dir){ _dir = _dir || ""; CMS_PageList_PageDB.updateEditState(); } /* ---------- ---------- ---------- */ return { openedPage:openedPage, editedPage:editedPage, savedPage:savedPage, publishedPage:publishedPage, unPublishedPage:unPublishedPage, isEdited:isEdited } })();<file_sep>/src/js/cms_view_inspect/InspectView.FormU_Img.js InspectView.FormU_Img = (function(){ var updateCallback; function init(_updateCallback){ updateCallback = InspectView.updateCallerView; } /* ---------- ---------- ---------- */ function assignExtraInput(_node,_param){ _node.find("._in_data_extra").keyup(function(){ updateExtra( _param,$(this).val() ,$(this).data("type")); }); } function updateExtra(_param,val,_tar){ if(_param["extra"] ==undefined) _param.extra = {} _param.extra[_tar] = val; updateCallback(); } /* ---------- ---------- ---------- */ //画像ブロック function getIMG(_param,_extra){ var tag = ""; tag += '<div class="_mode_switch">'; // tag += ' <div class="_cms_btn_alpha _btn_mode _btn_mode_simple">' tag += ' <i class="fa fa-lg fa-circle-o"></i><i class="fa fa-lg fa-dot-circle-o "></i>'; tag += ' シンプルモード'; tag += ' <span class="ss_inspect3 _img_simple"></span>' tag += ' </div>'; tag += ' <div class="_mode_switch_body _body_img_simple">'; tag += ' <table class="_mainlayout">'; tag += ' <tr><td>'; tag += ' <span class="_in_data_img_t">' + _param.data.img + '</span>' tag += ' <table style="width:auto">'; tag += ' <tr><td>'; tag += ' <div class="_cms_btn_alphaS _in_data_img _cms_bg_trans">' tag += CMS_ImgBlockU.getImageTag({ path : _param.data.img, isPub : false, width : "100%", ratio : "", alt : "", attr : "" }); tag += ' </div>' tag += ' </td><td>'; tag += ' <span class="_cms_btn_alpha _in_data_img_list ss_img_select img_select_img"></span>' tag += ' <span class="_cms_btn_alpha _in_data_img_mock ss_img_select img_select_dummy"></span>' tag += ' </td></tr></table>'; tag += ' <div class="_cms_btn_alpha _btn_image_tag_ng "><i class="fa fa-check-square "></i> IMGタグのみ出力</div>' tag += ' <div class="_cms_btn_alpha _btn_image_tag_ac "><i class="fa fa-square-o "></i> IMGタグのみ出力</div>' tag += ' </td></tr>'; tag += ' </table>'; // tag += ' <div class="_wide_preset">'; // tag += ' <span class="_btn_w">100%</span> <span class="_btn_w">400px</span><br>'; // tag += ' <span class="_btn_w"> 50%</span> <span class="_btn_w">200px</span><br>'; // tag += ' <span class="_btn_w"> 25%</span> <span class="_btn_w">100px</span><br>'; // tag += ' </div>'; tag += ' </div>' // tag += ' <div class="_mode_switch_body_hr"></div>'; // tag += ' <div class="_cms_btn_alpha _btn_mode _btn_mode_layout">' tag += ' <i class="fa fa-lg fa-circle-o"></i><i class="fa fa-lg fa-dot-circle-o "></i>'; tag += ' レイアウトモード'; tag += ' <span class="ss_inspect3 _img_layout"></span>' tag += ' </div>'; tag += ' <div class="_mode_switch_body _body_img_layout">'; tag += ' <div>' tag += ' <span class="_cms_btn _cms_btn_edit" '+TIP_ENTER+'>' tag += ' <i class="fa fa-object-ungroup "></i> レイアウト編集</span>'; tag += ' </div>' tag += ' </div>' // tag += ' <div class="_mode_switch_body_hr"></div>'; tag += ' <table class="_mainlayout">'; tag += ' <tr>'; tag += ' <td> 幅:<span><input class="_in_data_extra _in_data_w _sub _w50" data-type="width" placeholder="100px" data-candidate="_cms_image_width"></span></td>'; tag += ' <td>ALT:<span><input class="_in_data_extra _in_data_alt _sub _w50" data-type="alt" placeholder="代替テキストを入力"></span></td>'; tag += ' </tr>'; tag += ' <tr>'; tag += ' <td>比率:<span><input class="_in_data_extra _in_data_h _sub _w50" data-type="height" placeholder="3:2" data-candidate="_cms_image_ratio"></span></td>'; tag += ' <td>注釈:<span><input class="_in_data_extra _in_data_cap _sub _w50" data-type="caption" placeholder="キャプションを入力"></span></td>'; tag += ' </tr>'; tag += ' </table>'; tag += ' <table class="_mainlayout">'; tag += ' <tr>'; tag += ' <td>'; tag += ' <div class="_cms_btn_alpha _btn_image_check_ng " style="margin-bottom:5px"><i class="fa fa-check-square "></i> クリックで拡大</div>' tag += ' <div class="_cms_btn_alpha _btn_image_check_ac " style="margin-bottom:5px"><i class="fa fa-square-o "></i> クリックで拡大</div>' tag += ' </td>'; tag += ' <td><div class="_cms_btn_alpha _btn_anchor" data-type=""></div></td>'; tag += ' </tr>'; tag += ' </table>'; tag += '</div>' var node = $(tag); assignEvent_simple(node,_param,_extra); assignEvent_layout(node,_param,_extra); assignExtraInput(node,_param); return node; } //シングルイメージ function assignEvent_simple(node,_param,_extra){ node.find("._body_img_simple ._in_data_img") .click(function(){ clickImageThumb(); }); node.find("._body_img_simple ._in_data_img_t") .click(function(){ editImagePath($(this).html()); }); node.find("._body_img_simple ._in_data_img_list") .click(function(){ showImageList(); }); node.find("._body_img_simple ._in_data_img_mock") .click(function(){ showImageMock(); }); // node.find("._body_img_simple ._wide_preset ._btn_w") .click(function(){ setImageWide($(this).html()) }); /* ---------- ---------- ---------- */ //タグのみ出力 var tag_ng = node.find('._btn_image_tag_ng'); var tag_ac = node.find('._btn_image_tag_ac'); function _updateOnlyBtn(_update){ if(_param.data.onlyImgTag){ tag_ng.show(); tag_ac.hide(); } else{ tag_ng.hide(); tag_ac.show(); } if(_update) updateCallback(); } tag_ng.click(function(){ _param.data.onlyImgTag = false;_updateOnlyBtn(true); }); tag_ac.click(function(){ _param.data.onlyImgTag = true;_updateOnlyBtn(true) }); _updateOnlyBtn(); // /* ---------- ---------- ---------- */ node.find("._in_data_alt") .val(defaultVal(_extra["alt"],"")); node.find("._in_data_cap") .val(defaultVal(_extra["caption"],"")); node.find("._in_data_w") .val(defaultVal(_extra["width"],"")); node.find("._in_data_h") .val(defaultVal(_extra["height"],"")); function updateImageView(_s){ _param.data.img = _s; setTimeout(function(){ setImage(_s); updateCallback(); }, 200); } function setImage(_s){ node.find("._body_img_simple ._in_data_img").html(CMS_Path.MEDIA.getPreviewImageTag(_s)); node.find("._body_img_simple ._in_data_img_t").html(_s); } function clickImageThumb(){ showImageList(); } function showImageList(){ var s = _param.data.img; if(DummyImageService.isMock(_param.data.img) ) s = CMS_Path.UPLOAD.ABS; //パスを相対パスに変換して、コールする CMS_MainController.openAssetSelectRel("image", s ,function(_s){ updateImageView(_s); }); } function showImageMock(){ var s = _param.data.img; if(DummyImageService.isMock(_param.data.img) == false) s = ""; DummyImageView.stageIn(s,function(_s){ updateImageView(_s); }); } function editImagePath(_val){ var _s = prompt("画像URLを入力してください", _val); if(_s != null){ if(_val != _s){ updateImageView(_s); }} } /* ---------- ---------- ---------- */ //リンクボタン var zoom_ng = node.find('._btn_image_check_ng'); var zoom_ac = node.find('._btn_image_check_ac'); var libtn = node.find('._btn_anchor'); function _updateBtn(_update){ if(_param.data.isZoom){ zoom_ng.show(); zoom_ac.hide(); libtn.hide(); } else{ zoom_ng.hide(); zoom_ac.show(); libtn.show(); } if(_update) updateCallback(); } zoom_ng.click(function(){ _param.data.isZoom = false;_updateBtn(true); }); zoom_ac.click(function(){ _param.data.isZoom = true;_updateBtn(true) }); new InspectView.AnchorClass( node.find('._btn_anchor'), defaultVal(_param.data.link,{}), function (_val){ _param.data.link = _val; updateCallback(); } ); _updateBtn(); } //レイアウトモード function assignEvent_layout(node,_param,_extra){ node.find("._cms_btn_edit").click(function(){ if(_param.data["layout"] == undefined) _param.data.layout = {} ImageMapView.stageIn(_param.data.layout,function(_s){ _param.data.layout = _s; _param.data.isLayoutMode = true; setTimeout(function(){ updateCallback(); }, 200); }); }); //モード切り替え var btn_off = node.find('._btn_mode_simple'); var btn_on = node.find('._btn_mode_layout'); var body_01 = node.find('._body_img_simple'); var body_02 = node.find('._body_img_layout'); function _updateBtn(_update){ if(_param.data.isLayoutMode){ btn_off.removeClass("_current"); btn_on.addClass("_current"); if(_update) { body_01.slideUp();body_02.slideDown(); } else{ body_01.hide();body_02.show(); } } else{ btn_off.addClass("_current"); btn_on.removeClass("_current"); if(_update) { body_01.slideDown();body_02.slideUp(); } else{ body_01.show();body_02.hide(); } } if(_update) { updateCallback(); } } btn_off.click(function(){ _param.data.isLayoutMode = false;_updateBtn(true); }); btn_on.click(function(){ _param.data.isLayoutMode = true;_updateBtn(true) }); _updateBtn(); return node; } /* ---------- ---------- ---------- */ //コンテナブロック用背景画像設定 function getBGIMG(_param,_extra){ if(!_param.extra) _param.extra = {} if(!_param.extra.bg) _param.extra.bg = {}; if(!_param.extra.bg.img) _param.extra.bg.img = ""; if(!_param.extra.bg.color) _param.extra.bg.color = ""; if(!_param.extra.bg.use) _param.extra.bg.use = false; var param = _param.extra.bg; var tag = "" tag += '<div style="margin:20px 0;">'; tag += ' <div>'; tag += ' <div class="_cms_btn_alpha _btn_image_on " style="margin-bottom:5px"><i class="fa fa-check-square "></i> 背景画像を設定する</div>' tag += ' <div class="_cms_btn_alpha _btn_image_off " style="margin-bottom:5px"><i class="fa fa-square-o "></i> 背景画像を設定する</div>' tag += ' </div>'; tag += ' <div class="_setting_bg" style="margin:0 0 0 10px;">'; tag += ' <table class="_mainlayout ">'; tag += ' <tr><td>'; tag += ' <span class="_in_data_img_t">' + param.img + '</span>' tag += ' <table style="width:auto">'; tag += ' <tr><td>'; tag += ' <div class="_cms_btn_alphaS _in_data_img">' if(param.img){ tag += CMS_ImgBlockU.getImageTag({ path : param.img, isPub : false, width : "100%", ratio : "", alt : "", attr : "" }); } tag += ' </div>' tag += ' </td><td>'; tag += ' <span class="_cms_btn_alpha _in_data_img_list ss_img_select img_select_img"></span>' // tag += ' <span class="_cms_btn_alpha _in_data_img_mock ss_img_select img_select_dummy"></span>' tag += ' </td></tr></table>'; tag += ' </td></tr>'; tag += ' </table>'; tag += ' <p>※ デザインタブのstyle設定で直接CSSで指定するのと同じです。</p>'; tag += ' </div>'; tag += '</div>'; var node = $(tag); node.find("._in_data_img") .click(function(){ clickImageThumb(); }); node.find("._in_data_img_t") .click(function(){ editImagePath($(this).html()); }); node.find("._in_data_img_list") .click(function(){ showImageList(); }); // node.find("._in_data_img_mock") .click(function(){ showImageMock(); }); function updateImageView(_s){ param.img = _s; setTimeout(function(){ setImage(_s); updateCallback(); }, 200); } function setImage(_s){ if(_s){ node.find("._in_data_img").html(CMS_Path.MEDIA.getPreviewImageTag(_s)); node.find("._in_data_img_t").html(_s); } else{ node.find("._in_data_img").html("--"); node.find("._in_data_img_t").html("--"); } } function clickImageThumb(){ showImageList(); } function showImageList(){ var s = param.img; if(DummyImageService.isMock(param.img) ) s = CMS_Path.UPLOAD.ABS; //パスを相対パスに変換して、コールする CMS_MainController.openAssetSelectRel("image", s ,function(_s){ updateImageView(_s); }); } // function showImageMock(){ // var s = param.img; // if(DummyImageService.isMock(_param.data.img) == false) s = ""; // DummyImageView.stageIn(s,function(_s){ updateImageView(_s); }); // } function editImagePath(_val){ var _s = prompt("画像URLを入力してください", _val); if(_s != null){ if(_val != _s){ updateImageView(_s); }} } var on_ = node.find('._btn_image_on'); var off_ = node.find('._btn_image_off'); var bgs = node.find("._setting_bg"); function _updateBtn(_update){ if(_param.extra.bg.use){ on_.show(); off_.hide();bgs.show(); } else{ on_.hide(); off_.show();bgs.hide(); } if(_update) updateCallback(); } on_.click(function(){ _param.extra.bg.use = false;_updateBtn(true); }); off_.click(function(){ _param.extra.bg.use = true;_updateBtn(true) }); _updateBtn(); return node; } /* ---------- ---------- ---------- */ //画像リスト function getImages(_param,_extra){ var tag = ""; tag += '<div>'; tag += ' <table class="_mainlayout">'; tag += ' <tr><td> 幅:<input class="_in_data_extra _in_data_w _sub _w60" data-type="width" placeholder="100px" data-candidate="_cms_image_width"></td></tr>'; // tag += ' <tr><td>比率:<input class="_in_data_extra _in_data_h _sub _w60" data-type="height" placeholder="3:2" data-candidate="_cms_image_ratio"></td></tr>'; tag += ' </table>'; tag += ' <table class="_mainlayout">'; tag += ' <tr><td>マージン<br>(上右下左)</td><td><input class="_in_data_extra _in_data_mg _sub _w100" data-type="margin" placeholder="0 10px 10px 0" data-candidate="_cms_images_margin"></td></tr>'; tag += ' </table>'; tag += ' <div class="_row">'; tag += ' <div class="_in_check_extra">'; tag += ' <div class="_off"><i class="fa fa-lg fa-check-square "></i> 横に並べる</div>'; tag += ' <div class="_on" style="display:none;"><i class="fa fa-lg fa-square-o "></i> 横に並べる</div>'; tag += ' </div>'; tag += ' </div>'; tag += '</div>'; var node = $(tag); node.find("._in_data_w").val(defaultVal(_extra["width"],"")); // node.find("._in_data_h").val(defaultVal(_extra["height"],"")); node.find("._in_data_mg").val(defaultVal(_extra["margin"],"")); // function toggle(_s,_update){ if(_s == "1"){ _on.hide(); _off.show(); if(_update)updateExtra(_param,"1","float"); } else{ _on.show(); _off.hide(); if(_update)updateExtra(_param,"","float"); } updateCallback(); } var _off = node.find("._in_check_extra ._off"); var _on = node.find("._in_check_extra ._on"); _off.click(function(){ toggle("",true) }); _on.click(function(){ toggle("1",true) }); toggle(defaultVal(_extra["float"],""),false); assignExtraInput(node,_param); return node; } return { init:init, getIMG : getIMG, getBGIMG : getBGIMG, getImages : getImages } })(); <file_sep>/src/js/cms_main/CMS_ServerStatus.js var CMS_ServerStatus = { version: "" } var CMS_ServerStatusFunc = (function() { var versionNumber function setVersion(_v) { var vs = _v.phpversion.split(".") if (vs.length != 3) return; CMS_ServerStatus.version = _v.phpversion; versionNumber = convert(CMS_ServerStatus.version) } function convert(_s) { var vs = _s.split(".") if (vs.length != 3) return 0; return vs[0] * 1000000 + vs[1] * 1000 + vs[2] * 1; } function checkCoverVersion(_v) { var vv = convert(_v) if (vv <= versionNumber) { return true; } else { return false; } } return { setVersion: setVersion, checkCoverVersion: checkCoverVersion } })(); <file_sep>/src/js/cms_util/Treatment.js var Treatment = (function() { function toValue(_n, _s) { if (_n == undefined) return _s; if (_n == "") return _s; return _n; } return { toValue: toValue } })();<file_sep>/src/js/cms_view_editable/EditableView.SubPageView.js EditableView.SubPageView = (function() { /* ---------- ---------- ---------- */ var c = function() { this.init(); } var p = c.prototype; /* ---------- ---------- ---------- */ p.editCheckData = "" p.init = function () { this.subs = []; this.v = {}; } p.setObjectType = function (_objectType){ this.type = _objectType; } p.className = "" p.setStyle = function (_s){ this.className = _s; } p.registParent = function (_parent){ var this_ = this; this.parent = _parent; this.parentView = $('#SubPageView'); this.subs = []; //分岐 var grids = this.type.grids; for (var i = 0; i < grids.length ; i++) { switch(grids[i].gridType){ case Dic.GridType.BASE: this.subs.push(new EditableView.BaseBlock(grids[i])); break; case Dic.GridType.M_GRID: this.subs.push(new EditableView.M_Grid(grids[i])); break; case Dic.GridType.TEMPLATE: this.subs.push(new EditableView.CustomList(grids[i])); break; } } var tag = (function(_param,_class){ var s = ""; s += '<div class="_modalBox ' + _class + '">' s += ' <div class="_header">' s += ' <div style="float:right;">' + _param.getGuideTag() + '</div>' s += ' <div class="_title">' + _param.name + '</div>' s += ' </div>' s += ' <div class="_body _simple-scroll"><div class="_replaceArea"></div></div>' s += ' <div class="_footer">' s += ' <div class="_cms_btn _btn_close">キャンセル</div>' s += ' <div class="_cms_btn _cms_btn_active _btn_do" '+TIP_ENTER+'><i class="fa fa-check"></i> 編集完了</div>' s += ' </div>' s += '</div>' return s; })(this.type.pageInfo,this.className); this.v.bg = $('<div class="_bg"></div>'); this.view = $(tag); this.parentView.empty(); this.parentView.append(this.v.bg); this.parentView.append(this.view); this.v.replaceArea = this.view.find('._replaceArea:first'); this.stageInit(); this.setBtn(); this.v.bg .click(function(){ this_.stageOut() }); this.view.find('._btn_close') .click(function(){ this_.stageOut() }); this.view.find('._btn_do') .click(function(){ this_.compliteEdit(); }); } p.compliteEdit = function(){ var this_ = this; UpdateDelay.delay(function(){ var b = (JSON.stringify(this_.getData()) != this_.editCheckData); this_.parent.hideInlineGridEditor(b); }); this_.stageOut(); } p.createView = function(){ var this_ = this; for (var i = 0; i < this.subs.length ; i++) { this.subs[i].registParent(this_,this_.v.replaceArea); } } p.setBtn = function (){ var this_ = this; } /* ---------- ---------- ---------- */ //#データ p.initData = function (_data,_no){ this.v.replaceArea.html(""); this.editCheckData = JSON.stringify(_data); this.gridsData = JSON.parse(this.editCheckData); if(this.gridsData == undefined) this.gridsData = {} for (var i = 0; i < this.subs.length ; i++) { var list = this.gridsData[this.subs[i].gridInfo.id]; this.subs[i].initData(list); } } p.getData = function (){ var o = {}; for (var i = 0; i < this.subs.length ; i++) { o[this.subs[i].gridInfo.id] = this.subs[i].getData() } this.gridsData = o; return this.gridsData; } p.updateSubData = function (){} /* ---------- ---------- ---------- */ //#Stage p.isOpen = false; p.isFirst = true; p.stageInit = function (){ this.view.hide(); } p.stageIn = function (){ if(! this.isOpen){ this.isOpen = true; showModalView(this); this.view.show(); this.parentView.delay(50).show(); CMS_ScreenManager.setSubView(this); this.resize(); } } p.stageOut = function (){ if(this.isOpen){ this.isOpen = false; hideModalView(); this.view.hide(); this.parentView.hide(); } } p.resize = function (){} return c; })();<file_sep>/src/js/cms_main/CMS_Header.js var CMS_Header = (function(){ var view; var v = {}; function init(){ var toolBtns = (function(_a){ var tag = ""; for (var i = 0; i < _a.length ; i++) { if(_a[i] == "UPLOAD"){ tag += ' <div class="_cms_btn_alpha _btn_file"><span class="ss_icon _file"></span><span class="_t">アップロード</span></div>'; } if(_a[i] == "BACKUP"){ tag += ' <div class="_cms_btn_alpha _btn_zip"></span><span class="_t"><i class="fa fa-download "></i> サイトバックアップ</span></div>'; } if(_a[i] == "ICON"){ tag += ' <div class="_cms_btn_alpha _btn_icon"><span class="_t"><i class="fa fa-leaf "></i> アイコン</span></div>'; } if(_a[i] == "EMBED_TAG"){ tag += ' <div class="_cms_btn_alpha _btn_embedtag"><span class="_t">{{ 埋込みタグ }}</span></div>'; } if(_a[i] == "GRID"){ tag += ' <div class="_cms_btn_alpha _btn_grid"><span class="_t"><i class="fa fa-th "></i> グリッド</span></div>'; } } return tag; })(HEADER_TOOL_BTNS); var gudieTag = CMS_GuideU.getGuideTag("","利用ガイド","header") + " "; var loginTag = (function(_b){ var tag = ""; tag += '<div class="_menuset">'; if(_b){ tag += '<div class="_menu">設定・ログアウト <i class="fa fa-caret-down "></i></div>'; // tag += '<div class="_menu _cms_btn_alpha _btn_logout"><i class="fa fa-user "></i> ログアウト <i class="fa fa-caret-down "></i></div>'; } else{ tag += '<div class="_menu">CMS設定 <i class="fa fa-caret-down "></i></div>'; } tag += ' <div class="_float">'; tag += ' <div class="_item _cms_btn_alpha _btn_setting"><i class="fa fa-lg fa-cog "></i> CMS設定</div>'; tag += ' <div class="_item _cms_btn_alpha _btn_setting_php"><i class="fa fa-lg fa-cog "></i> ログイン設定</div>'; tag += ' <div class="_item _cms_btn_alpha _btn_sever"><i class="fa fa-lg fa-globe "></i> サーバー情報</div>'; if(_b){ tag += ' <div class="_item _cms_btn_alpha _btn_logout"><i class="fa fa-lg fa-user "></i> ログアウト</div>'; } tag += ' <div class="_item _cms_btn_alpha">'+gudieTag+'</div>'; tag += ' <div class="_item _cms_btn_alpha _btn_cms">Powered by<br>JS CMS<br>version '+CMS_INFO.version+'</div>'; tag += ' </div>' tag += ' </div>' return tag; })(CMS_LoginView.getLogout()); var extraBtns = (function(_a){ if(!_a)return; var tag = ""; for (var i = 0; i < _a.length ; i++) { var ls = _a[i] tag += '<div class="_menuset">'; tag += ' <div class="_menu ">'+ls.label+' <i class="fa fa-caret-down "></i></div>'; tag += ' <div class="_float">'; for (var u = 0; u < ls.items.length ; u++) { tag += ' <div class="_item _cms_btn_alpha">' + ls.items[u] + '</div>' } tag += ' </div>'; tag += '</div>'; } return tag; })(HEADER_EXTRA_BTNS); /* ---------- ---------- ---------- */ view = $('#CMS_Header'); var tag = ""; tag += '<div class="_sitename _cms_ellipsis _cms_btn_alpha">' + SITE_NAME + '</div>'; tag += '<div class="_header_btns">' + toolBtns + '</div>'; tag += '<div class="_cmsBlock">' + loginTag + '</div>' tag += '<div class="_freeBlock">' + extraBtns + '</div>'; view.html(tag) stageInit(); stageIn(); createlayout(); setBtn(); } /* ---------- ---------- ---------- */ function setBtn(){ view.find('._sitename').click(function(){ CMS_U.openURL_blank(CMS_Path.SITE.REL); }); view.find('._btn_icon').click(function(){ openIcon()}); view.find('._btn_file').click(function(){ CMS_MainController.openUploadDir(); }); view.find('._btn_zip').click(function(){ BackupView.stageIn(); }); view.find('._btn_embedtag').click(function(){ openEmbed(); }); view.find('._btn_grid').click(function(){ openGrid(); }); view.find('._btn_setting').click(function(){ CMS_MainController.openCMSSetting("setting.js"); }); view.find('._btn_setting_php').click(function(){ CMS_MainController.openCMSSetting("setting.php"); }); view.find('._btn_sever').click(function(){ ServerInfoView.stageIn(); }); view.find('._btn_logout').click(function(){CMS_LoginView.logout()}); view.find('._btn_cms').click(function(){ window.open(CMS_INFO.url); }); new CMS_UtilClass.HoverMenu(view.find('._menuset'),"._float"); } function createlayout(){ } /* ---------- ---------- ---------- */ function openIcon(){ Preset_IconView.stageIn(); // Preset_IconView.stageIn(function(_s){ // CMS_MainController.addTextToPage(_s); // }); } function openEmbed(){ EmbedTagListView.stageIn(); // EmbedTagListView.stageIn("my",function(_s){ // CMS_MainController.addHinagataToPage(_s); // // CMS_MainController.addTextToPage(_s); // }); } function openGrid(){ window.open("./grid/","grid_preview"); } /* ---------- ---------- ---------- */ //表示・非表示処理 var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } function stageIn(){ if(! isOpen){ isOpen = true; view.show(); if(isFirst){} isFirst = false; } } function stageOut(){ if(isOpen){ isOpen = false; view.hide(); } } return { init:init, stageIn:stageIn, stageOut:stageOut } })(); <file_sep>/src/js/cms_view_modals/BackupU.js var BackupU = (function(){ function loadAPI(param,_callback) { param.zipDir = escape_url(CMS_Path.BACKUP.REL); param.siteDir = escape_url(SITE_DIR_PATH); if(param["targetDirs"]){ param.targetDirs = escape_url(param.targetDirs); } var url = CMS_Path.PHP_BACKUP; $.ajax({ scriptCharset : 'utf-8', type : 'GET', data : param, url : url, dataType : 'json', success : function(data) { setTimeout(function(){ _callback(data) },200); }, error : function(data) { // if(isLog) console.log(data); CMS_ErrorView.stageIn("NET",url,param,data); // alert("ネットワークエラーが発生しました。"); } }) } function getSelectTag(){ var a = [ [5 ,"5分"], [20 ,"20分"], [1*60 ,"1時間"], [3*60 ,"3時間"], [12*60 ,"12時間"], [1*24*60 ,"1日"], [2*24*60 ,"2日"], [4*24*60 ,"4日"], [7*24*60 ,"1週"], [14*24*60 ,"2週"], [1*31*24*60 ,"1月"], [2*31*24*60 ,"2月"], [4*31*24*60 ,"4月"], [12*365*60 ,"1年"], [24*365*60 ,"2年"] ] var tag = "" tag += '<select id="hour">' tag += '<option value="0">選択してください</option>' for (var i = 0; i < a.length ; i++) { tag += '<option value='+ a[i][0] +'>'+ a[i][1] +"以内</option> " } tag += '</select>' return tag } function getDistanceTimeColor(old){ /* var s = [ old.substr(0,4), old.substr(4,2), old.substr(6,2) ] var s2 = [ old.substr(9,2), old.substr(11,2), old.substr(13,2), ] var oldDate = new Date(s.join("/") +" " + s2.join(":")); */ var newDate = new Date(); var sa = (newDate.getTime()/1000)-old; var min = sa /60; var cols = [ [2 ,"min2","数分以内"], [10 ,"min10","10分以内"], [60 ,"hour","1時間以内"], [60*6 ,"hour6","6時間以内"], [60*24 ,"day","1日以内"], [60*24*2 ,"day2","2日以内"], [60*24*7 ,"day7","7日以内"], [60*24*30 ,"month","1月以内"], [60*24*30*2 ,"month2","2月以内"], [60*24*30*4 ,"month4","4月以内"], [60*24*30*12 ,"year","1年以内"], [60*24*30*12*2 ,"year2","2年以内"] ] var s = [0,"year_",""] for (var i = 0; i < cols.length ; i++) { if(cols[i][0] > min){ s = cols[i] break; } } return s; } return { loadAPI: loadAPI, getSelectTag: getSelectTag, getDistanceTimeColor: getDistanceTimeColor } })(); <file_sep>/js_cms/_cms/storage.php <?php /** * JS_CMS -- realtime website development web application * http://js-cms.jp/ * Copyright 2015 <NAME> - <EMAIL> * licensed under the MIT licenses. */ //usleep(500*1000);//test define('CMS', true); require_once("./setting/setting.php"); require_once("./storage.funcs.php"); require_once("./storage.login.php"); /* ! ---------- info ---------- ---------- ---------- ---------- */ if($_GET["action"] == "info"){ phpinfo(); exit(); } /* ! ---------- pre ---------- ---------- ---------- ---------- */ if($_GET['outType'] == "text"){ header("Content-Type: text/plain; charset=utf-8"); } else{ header("Content-Type: application/json; charset=utf-8"); } /* ! ---------- input ---------- ---------- ---------- ---------- */ $action = getVAL("action","",""); if($action == "") status_error("invalid action name"); if(! is_action($action)) status_error("invalid action name"); $file_name = getVAL("file_name","",""); $dir_name = getVAL("dir_name","","dir"); $dir_rename = getVAL("dir_rename","","dir"); $text = getVAL("text","",""); $waf_escape = getVAL('waf_escape',"","boolean"); if($waf_escape){ if($text){ $text = str_replace("~", "",$text); $text = str_replace("__TILDE__", "~",$text); } } if(! is_fileName($file_name)) status_error("invalid name"); if(! is_filePath($dir_name)) status_error("invalid path"); $notWrite = IS_DEMO; if($file_name == "_cms_preview.html"){ $notWrite = false; } /* ! ---------- main ---------- ---------- ---------- ---------- */ $file_path = $dir_name.$file_name; $file_path_temp = $dir_name.'__temp_'.$file_name; //main process if( $action == "write"){ if($notWrite){ status_success(); } else{ if(!file_exists($dir_name)) status_error_dir($dir_name); if(file_exists($file_path)) unlink ($file_path); if($text == "") $text = "\n"; if(file_put_contents($file_path, $text)){ status_success(); } else { status_error("failed to write file."); } } } if( $action == "writeAll"){ if($notWrite){ status_success(); } else{ $paths = getVAL("paths","","paths"); $texts = explode($_POST["sep"],$text); for ($count = 0; $count < count($paths); $count++){ $text = $texts[$count]; $path = $paths[$count]; if(file_exists($path)) unlink ($path); if(file_put_contents($path, $text)){ // } else{ status_error("failed to write file."); } } status_success(); exit(); } } if( $action == "writeToTemp"){ if($notWrite){ status_success(); } else{ if(!file_exists($dir_name)) status_error_dir($dir_name); if(file_exists($file_path_temp)) unlink ($file_path_temp); if($text == "") $text = "\n"; if(file_put_contents($file_path_temp, $text)){ status_success(); } else { status_error("failed to write temp file."); } } } if( $action == "renameTemp"){ if($notWrite){ status_success(); } else{ if(file_exists($file_path_temp)){ if(rename($file_path_temp,$file_path)){ status_success(); } else{ status_error("failed to rename temp file."); } } else{ status_success(); } } } if($action == "read"){ $read_path = getVAL("path","","path"); if(is_filePath($read_path)){ if(file_exists($read_path)){ echo file_get_contents($read_path); exit(); } } echo(""); exit(); } if($action == "readAll"){ $paths = getVAL("paths","","paths"); $outs = array(); for ($count = 0; $count < count($paths); $count++){ array_push($outs, ""); } for ($count = 0; $count < count($paths); $count++){ $path = $paths[$count]; if(is_filePath($path)){ if(file_exists($path)){ $outs[$count] = file_get_contents($path); } } } //var_dump( $_GET['sep']); echo(implode( $_GET['sep'] , $outs )); exit(); } if(IS_DEMO) status_success(); if($action == "renameAll"){ //renameAll $files1 = getVAL("rename_olds","","paths2"); $files2 = getVAL("rename_news","","paths2"); for ($count = 0; $count < count($files1); $count++){ if(! rename( $files1[$count] , $files2[$count]) ){ // status_error("failed to rename file."); } touch($files2[$count]); } status_success(); } if($action == "rename"){ //rename $rename_old = getVAL("rename_old","","path"); $rename_new = getVAL("rename_new","","path"); if(! is_filePath($rename_old)) status_error("invalid path"); if(! is_filePath($rename_new)) status_error("invalid path"); // checkFileExist_weak($rename_old); if(! rename( $rename_old , $rename_new) ){ status_error("failed to rename file."); } touch($rename_new); status_success(); } if($action == "delete"){ $deleteFile = getVAL("deleteFile","","path"); if(! is_filePath($deleteFile)) status_error("invalid path"); // checkFileExist_weak($deleteFile); if(! unlink ($deleteFile)){ status_error("failed to delete file."); } status_success(); } if($action == "deleteFiles"){ $files = getVAL("file_names","","paths2"); for ($count = 0; $count < count($files); $count++){ unlink( $files[$count]); } status_success(); } if($action == "upload"){ $upload_dir = getVAL("upload_dir","","dir"); if(! is_filePath($upload_dir)) status_error("invalid path"); if(isWritableDir($upload_dir) == false){ status_error("can not write to directory"); } $uploadtempPath = $_FILES["upfile"]["tmp_name"]; $path_parts = pathinfo($_FILES["upfile"]["name"]); $uploadPath = $upload_dir.date("Ymd_His").".".$path_parts['extension']; if (is_uploaded_file($uploadtempPath)) { if (move_uploaded_file($uploadtempPath, $uploadPath)) { status_success(); } else { status_error("failed to upload file"); } } else { status_error("can not find upload file."); } } if($action == "createDir"){ if(!file_exists($dir_name)){ if(! mkdir($dir_name)){ status_error("failed to create new directory."); } else{ chmod($dir_name,0707); status_success(); } } else{ status_error("failed to create new directory."); } } if($action == "renameDir"){ checkFileExist($dir_name); if(! rename( $dir_name, $dir_rename )){ status_success(); } else{ status_error("failed to rename directory."); } } if($action == "deleteDir"){ checkFileExist($dir_name); removeAllDirectory($dir_name); status_success(); } <file_sep>/src/js/cms_view_modals/DirListView.js var DirListView = (function(){ var view; var v = {}; var baseDir = ""; var targetDir = "" function init(){ view = $('#DirListView'); stageInit(); } function createlayout(){ v = ModalViewCreater.createBaseView(DirListView,view); var tag = "" tag = '<div class="_title">ディレクトリ選択</div>' v.header.html(tag); tag = "" tag += '<div class="_read">HTMLファイルの書き出し先ディレクトリを選択してください。</div>' tag += '<div style="text-align:right;">' tag += ' <div class="_cms_btn-mini _btn_rootDir_reload" style="margin:0 0 10px 0;"><i class="fa fa-repeat "></i> リスト更新</div>' tag += '</div>' tag += '<div class="_replaceDir _dirTreeView "></div>' v.body.html(tag); v.replaceDir = view.find('._replaceDir'); v.tagetPath = view.find('._tagetPath'); tag = "" tag += '<div class="_cms_btn _btn_close">閉じる</div> '; v.footer.html(tag) v._btn_close = view.find('._btn_close'); setBtn(); } /* ---------- ---------- ---------- */ function setBtn(){ view.find('._bg ,._btn_close').click(function(){ stageOut() }); v.btn_rootDir_reload = view.find('._btn_rootDir_reload'); v.btn_rootDir_reload.click(function(){ reload_dir() }); v.btn_rootDir_reload.hide() } /* ---------- ---------- ---------- */ //dir var reload_tID function reload_dir(){ v.btn_rootDir_reload.hide() if(dirTree){ dirTree.remove(); dirTree = null; v.replaceDir.empty() } if(reload_tID)clearTimeout(reload_tID); reload_tID = setTimeout(function(){ load_dir() if(currentPath){ openCurrent(currentPath); } },200); } var dirTree; function load_dir(){ dirTree = new DirTreeViewNode( v.replaceDir,null,0, { initDeep :1, def :{ path: "", name: ""}, showCMSDir :true, showWriteDir :true, isClickNGDir :false, currentSelect :null, extentions :"", settingDirs :[ {path:CMS_Path.CMS.REL ,label:"CMS管理画面"}, {path:CMS_Path.UPLOAD.REL ,label:"アップロード"}, {path:CMS_Path.BACKUP.REL ,label:"バックアップ"}, {path:CMS_Path.ASSET.REL ,label:"サイト設定"} ], callback:function(s){}, showSelectBtn:true, callback_select:function(s){ openDir(s.path); } } ); v.btn_rootDir_reload.show() } var currentSelectFile var tID; var currentPath; function openCurrent(_currentDir){ currentPath = _currentDir var s = CMS_Path.SITE.REL + _currentDir; s = URL_U.getBaseDir(s.split("//").join("/")); dirTree.setCurrent({dir:s,id:""},false); } function openDir(_d){ var _dir = URL_U.treatDirName(_d.split("../").join("/")) UpdateDelay.delay(function(){ stageOut(); UpdateDelay.delay(function(){ callback(_dir); }); }); } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; var callback; function stageInit(){ view.hide(); } function stageIn(_val,_callback){ if(! isOpen){ isOpen = true; showModalView(this); callback = _callback; if(isFirst){ createlayout(); load_dir(); } openCurrent(_val); isFirst = false; view.show() resize(); } } function stageOut(){ if(isOpen){ isOpen = false; hideModalView(); view.hide(); } } function resize(){ if(isOpen){ } } return { init:init, stageIn:stageIn, stageOut:stageOut, resize:resize } })();//modal<file_sep>/src/js/cms_view_modals/Anchor_PageListView.js var Anchor_PageListView = (function(){ var view; var v = {}; function init(){ view = $('#Anchor_PageListView'); stageInit(); } function createlayout(){ v = ModalViewCreater.createBaseView(Anchor_PageListView,view); var tag = "" tag = '<div class="_title">ページ選択</div>' v.header.html(tag); tag = "" v.body.html(tag); tag = "" tag += '<div class="_cms_btn _btn_close">閉じる</div> '; v.footer.html(tag) v._btn_close = view.find('._btn_close'); setBtn(); } /* ---------- ---------- ---------- */ function setBtn(){ view.find('._bg ,._btn_close').click(function(){ stageOut() }); view.on("click",'._hasData',function(){ clickText($(this).data("url")); }); view.on("click",'._btn_link',function(event){ var u = $(this).data("url"); CMS_U.openURL_blank(u); event.stopPropagation(); event.preventDefault(); }); } /* ---------- ---------- ---------- */ //dir function update(){ v.body.html(createPagelistBox); } var sitemapSelTag = "" function createPagelistBox(){ sitemapSelTag = "" sitemapSelTag += "<table>" sitemapSelTag += "<tr>" sitemapSelTag += '<th>ページ名</th>' sitemapSelTag += '<th width="200">ファイル名</th>' sitemapSelTag += '<th width="70">リンク</th>' sitemapSelTag += "<tr>" createPagelistBox_core(CMS_Data.Sitemap.getFilelist(),0); sitemapSelTag += "</table>" return sitemapSelTag; } function createPagelistBox_core(_list,_deep){ var dd = "" for (var i = 0; i < _deep ; i++) dd += "│ "; for (var i = 0; i < _list.length ; i++) { if(_list[i].list){ if(_deep == 0) sitemapSelTag += '<tr><td>'+dd+'│ </td><td></td></tr>'; var n = _list[i].name.split("<br>").join(" "); sitemapSelTag += '<tr class="_dirrow"><td colspan="3">'+dd+'├ <span class="_dir">'+ n +'</span></td></tr>' createPagelistBox_core(_list[i].list,_deep+1) } else{ if(_list[i].type == Dic.ListType.PAGE){ var n = _list[i].name.split("<br>").join(" "); var path = CMS_Path.PAGE.getAbsPath(_list[i].id,_list[i].dir); var pathRel = CMS_Path.PAGE.getRelPath(_list[i].id,_list[i].dir); path = path.substr(1,path.length) sitemapSelTag += '<tr class="_hasData" data-url="'+path+'">' sitemapSelTag += '<td class="_name">'+dd+"├ "+n+'</td>' sitemapSelTag += '<td class="_url">'+path+'</td>' sitemapSelTag += '<td class="_link"><div class="_cms_btn-nano _btn_link" data-url="'+pathRel+'"><i class="fa fa-external-link-square "></i> 開く</div></td>' sitemapSelTag += '</tr>' } } } } function clickText(_s){ if(callback){ UpdateDelay.delay(function(){ callback(_s); }); } else { CMS_CopyView.stageIn(_s,function(){}) } stageOut() } /* ---------- ---------- ---------- */ function compliteEdit(){ stageOut() } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; var callback = true; function stageInit(){ view.hide(); //load_dir(); } function stageIn(_callback){ if(! isOpen){ isOpen = true; showModalView(this); callback = _callback; if(isFirst){ createlayout(); } update(); isFirst = false; view.show(); } } function stageOut(){ if(isOpen){ isOpen = false; hideModalView(); view.hide(); } } function resize(){ if(isOpen){ } } return { init:init, stageIn:stageIn, stageOut:stageOut,resize:resize,compliteEdit:compliteEdit } })();//modal<file_sep>/src/js/cms_main/CMS_UtilClass.js var CMS_UtilClass = {} CMS_UtilClass.HoverMenu = (function() { /* ---------- ---------- ---------- */ var c = function(_view,_float) { this.init(_view,_float); } var p = c.prototype; /* ---------- ---------- ---------- */ p.view; p.v; p.init = function(_view,_float) { this.view = _view; this.view.each(function (index, dom) { new CMS_UtilClass.HoverMenuClass($(this),_float); }); } return c; })(); CMS_UtilClass.HoverMenuClass = (function() { /* ---------- ---------- ---------- */ var c = function(_view,_float) { this.init(_view,_float); } var p = c.prototype; /* ---------- ---------- ---------- */ p.view; p.v; p.init = function(_view,_float) { this.view = _view; this.float = _float; var self = this; this.view.hover(function(){ self.show($(this)); },function(){ self.hide($(this)); }) } p.tID; p.show = function(_tar){ var self = this; if(self.tID) clearTimeout(self.tID); self.tID = setTimeout(function(){ _tar.find(self.float).show(); },200); } p.hide = function(_tar){ var self = this; if(self.tID) clearTimeout(self.tID); self.tID = setTimeout(function(){ _tar.find(self.float).hide(); },200); } return c; })(); <file_sep>/src/js/cms_stage_asset/CMS_Asset_FileDetailView.js var CMS_Asset_FileDetailView = (function(){ var view; var v = {}; function init(){ view = $('#CMS_Asset_FileDetailView'); view.append($('<div id="CMS_Asset_FileEditorView"></div>')); view.append($('<div id="CMS_Asset_FilePreviewView"></div>')); CMS_Asset_FileEditorView.init(); CMS_Asset_FilePreviewView.init(); } /* ---------- ---------- ---------- */ function save (){ CMS_Asset_FileEditorView.save(); } /* ---------- ---------- ---------- */ var _ps = []; var _current; function openPage (_param){ var ex = CMS_AssetFileU.getExtention(_param.id); var isClickable = CMS_AssetFileU.isExtentionAll(ex); var isEdtable = CMS_AssetFileU.isExtention(ex,"editable"); if(isEdtable){ CMS_Asset_FileEditorView.stageIn(_param); CMS_Asset_FilePreviewView.stageOut(); } else { CMS_Asset_FileEditorView.stageOut(); CMS_Asset_FilePreviewView.stageIn(_param); } CMS_AssetStage.openedDetailPage(_param); } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } function stageIn(_param){ // if(! isOpen){ isOpen = true; view.show(); if(_param) openPage(_param); // } } function stageOut(){ // if(isOpen){ isOpen = false; view.hide(); // } } return { init: init, stageIn: stageIn, stageOut: stageOut, save: save } })();<file_sep>/src/js/cms_stage_page/CMS_PageDB.js /** * 表示済みのページを管理する */ var CMS_PageDB = (function(){ var observer = [] function registerObserver(_v){ observer.push(_v) } /* ---------- ---------- ---------- */ //パラメータがフォーマットにそってるか function isPageParam(_pageModel){ if(_pageModel.type == "")return false; if(_pageModel.id == "")return false; return true; } /* ---------- ---------- ---------- */ var pages = []; //ページ追加 function addPage(_pageModel){ if(hasPages(_pageModel) == false){ pages.push(_pageModel); updatedList(); } } //ページ削除 function removePage(_id,_dir){ for (var i = 0; i < pages.length ; i++) { if(pages[i].id == _id){ if(pages[i].dir == _dir){ pages[i] = null; pages.splice(i,1); updatedList(); } } } } function updatedList(){ for (var i = 0; i < observer.length ; i++) { observer[i].updateList(); } } function updatedCurrent(){ for (var i = 0; i < observer.length ; i++) { observer[i].updatedCurrent(); } } //ページにDBに存在するか function hasPages (_pageModel){ for (var i = 0; i < pages.length ; i++) { if(pages[i].id == _pageModel.id) { if(pages[i].dir == _pageModel.dir) { return true; } } } return false; } /* ---------- ---------- ---------- */ function setCurrent(_page){ addPage(_page.pageModel); currentPage = _page; currentPage_preview = _page; updatedCurrent() } /* ---------- ---------- ---------- */ function getList(){ return pages; } /* ---------- ---------- ---------- */ var currentPage var currentPage_preview //現在のページを取得 function getCurrentPage() { return currentPage; } function getCurrentPageModel() { return currentPage.pageModel; } function getCurrentPageStoreData() { if(currentPage){ if(currentPage.storageClass) { return currentPage.storageClass.storeData; } } return null; } var prevCurrent; function getPreviewPageModel() { var param = getCurrentPageModel(); if(Dic.PageType.CMS_MYTAG == param.type){ return prevCurrent; } else{ prevCurrent = param; return param; } } //現在のプレビュページを取得 //設定系のページは、はいらない。フリーページのみ入る function getLivePreviewPage() { return currentPage_preview; } function getLivePreviewPageModel() { return currentPage_preview.pageModel; } function hasCurrent() { if(currentPage == undefined) return false; return true; } /* ---------- ---------- ---------- */ function editedPage(){} function savedPage(){} function publishedPage(){ } /* ---------- ---------- ---------- */ function updateSitemap(){ CMS_Data.Sitemap.update(); } /* ---------- ---------- ---------- */ return { registerObserver : registerObserver, isPageParam : isPageParam, addPage : addPage, removePage : removePage, hasPages : hasPages, setCurrent : setCurrent, getCurrentPage : getCurrentPage, getCurrentPageModel : getCurrentPageModel, getCurrentPageStoreData : getCurrentPageStoreData, getPreviewPageModel : getPreviewPageModel, getLivePreviewPage : getLivePreviewPage, getLivePreviewPageModel : getLivePreviewPageModel, hasCurrent : hasCurrent, editedPage : editedPage, savedPage : savedPage, publishedPage : publishedPage, getList : getList, updateSitemap : updateSitemap } })(); <file_sep>/src/js/cms_main/CMS_InitController.js var CMS_InitController = (function(){ function init(){ //ブラウザ分岐 if( Env_.isIE9) $("body").addClass("_ie9"); if(Env_.isChrome || Env_.isIE9|| Env_.isIE10 || Env_.isIE11){ CMS_PathFunc .init(); CMS_KeyManager .init(); CMS_History .init(); CMS_CheckedView .init(); CMS_CheckedView .stageIn(login); } else{ NO_CMS.init() NO_CMS.stageIn(); } } /* ! ---------- ---------- ---------- ---------- ---------- */ //ログイン function login(){ CMS_LoginView.init() CMS_LoginView.stageIn(logined); } function logined(){ //設定データでダミー処理がはいるので、先に初期化 DummyImageService.init(); //設定データロード CMS_Data.Loader.start(checked); } /* ! ---------- ---------- ---------- ---------- ---------- */ //ログイン後処理 function checked(){ var tag = ""; tag += '<div id="CMS_RootView">'; //コアビュー tag += ' <div id="CMS_SidePreview" ></div>'; tag += ' <div id="CMS_SidePreviewClose"></div>'; tag += ' <div id="CMS_Header"></div>'; tag += ' <div id="CMS_HeaderRight"></div>'; tag += ' <div id="CMS_PageStage"></div>'; tag += ' <div id="CMS_AssetStageSideBG"><span></span></div>'; tag += ' <div id="CMS_AssetStageBG"></div>'; tag += ' <div id="CMS_AssetStage"></div>'; tag += ' <div id="CMS_AssetStageCloseBG"></div>'; tag += ' <div id="CMS_AssetStageClose"></div>'; tag += ' <div id="CMS_AssetStageResizeView"></div>'; tag += ' <div id="CMS_PagesView_DisableView"></div>'; tag += ' <div id="CMS_LOCK"></div>'; //ダイアログ系 tag += ' <div id="CMS_AlertView" class="_modalView"></div>'; tag += ' <div id="CMS_AlertLockView" class="_modalView"></div>'; tag += ' <div id="CMS_ConfirmView" class="_modalView"></div>'; tag += ' <div id="CMS_CopyView" class="_modalView"></div>'; tag += ' <div id="CMS_InputView" class="_modalView"></div>'; tag += ' <div id="CMS_ProccessView" class="_modalView"></div>'; tag += ' <div id="CMS_ErrorView" class="_modalView"></div>'; //編集画面 tag += ' <div id="GridDetailView" class="_modalView"></div>'; tag += ' <div id="SubPageView" class="_modalView"></div>'; //フロート tag += ' <div id="InspectView"></div>'; tag += ' <div id="Float_Preview"></div>'; tag += ' <div id="SimpleToolTip"></div>'; tag += ' <div id="Float_DateInputView"></div>'; tag += ' <div id="FreeLayoutInfoView"></div>'; //エディター tag += ' <div id="MiniEditer"></div>'; tag += ' <div id="Editer_JSONView" class="_modalView"></div>'; tag += ' <div id="Editer_TAGView" class="_modalView"></div>'; tag += ' <div id="Editer_TextView" class="_modalView"></div>'; tag += ' <div id="Editer_ExcelView" class="_modalView"></div>'; tag += ' <div id="Editer_CodeCopyView" class="_modalView"></div>'; tag += ' <div id="Anchor_InputView" class="_modalView"></div>'; tag += ' <div id="Anchor_BtnView" class="_modalView"></div>'; tag += ' <div id="Anchor_PageListView" class="_modalView"></div>'; tag += ' <div id="Anchor_TargetListView" class="_modalView"></div>'; tag += ' <div id="Preset_IconView" class="_modalView"></div>'; tag += ' <div id="ServerInfoView" class="_modalView"></div>'; tag += ' <div id="DirListView" class="_modalView"></div>'; tag += ' <div id="DirTreeViewTest" class="_modalView"></div>'; tag += ' <div id="BackupView" class="_modalView"></div>'; tag += ' <div id="DummyImageView" class="_modalView"></div>'; tag += ' <div id="SitemapEditView" class="_modalView"></div>'; tag += ' <div id="FileInfoView" class="_modalView _modalView-nomargin"></div>'; tag += ' <div id="GadgetListView" class="_modalView"></div>'; tag += ' <div id="PresetStageView" ></div>'; tag += ' <div id="EmbedTagListView" class="_modalView"></div>'; tag += ' <div id="ImageMapView"></div>'; tag += ' <div id="ImageMapInspectView"></div>'; tag += ' <div id="CMS_GuideView" ></div>'; // tag += ' <div id="TreeViewMakerView" class="_modalView"></div>'; tag += ' <div id="TreeViewMakerViewEditor" ></div>'; tag += ' <div id="BatchPublishView" class="_modalView"></div>'; tag += ' <div id="InputCnadidate"></div>'; tag += ' <div id="ColorPickerView"></div>'; tag += ' <div id="FormCandidates"></div>'; // tag += ' <div id="SelectingBlockView"></div>'; tag += ' <div id="CMS_DemoView">デモモード<span>保存・公開はできません</span></div>'; tag += '</div>'; $("body").append(tag); $("._loading").hide(); if(Env_.isWin){ $("body").addClass("_windows"); } initViews(); } //各ビューの初期化 function initViews(){ if(IS_DEMO)$('#CMS_DemoView').show(); // var cs = [ CMS_RootView, CMS_Header, CMS_AlertView, CMS_AlertLockView, CMS_ConfirmView, CMS_CopyView, CMS_InputView, CMS_ProccessView, CMS_ErrorView, CMS_LOCK, CMS_ScreenManager, CMS_SizeManager, CMS_SidePreview, CMS_SidePreviewClose, CMS_Data, FormCandidates, /* ---------- ---------- ---------- */ CMS_PageStage, CMS_AssetStage, /* ---------- ---------- ---------- */ FileInfoView, GadgetListView, PresetStageView, EmbedTagListView, ImageMapView, // InspectView, Float_Preview, SimpleToolTip, Float_DateInputView, FreeLayoutInfoView, // MiniEditer, Editer_TAGView, Editer_JSONView, Editer_ExcelView, Editer_CodeCopyView, Anchor_InputView, Anchor_BtnView, Anchor_PageListView, Anchor_TargetListView, Preset_IconView, ServerInfoView, SitemapEditView, DirListView, BackupView, DirTreeViewTest, CMS_GuideView, DummyImageView, TreeViewMakerView, TreeViewMakerViewEditor, BatchPublishView, InputCnadidate, ColorPickerView, CMS_FormU, CMS_StageController, ]; //初期化 for (var i = 0; i < cs.length ; i++) { cs[i].init(); } //サイトマップロードあとに、メインコントローラ呼び出し CMS_Data.Sitemap.load(function(){ CMS_MainController.init(); }); if(window.location.hash == "#publish_all"){ if(USE_EDIT_LOCK) CMS_LOCK.setIsLocked(false); setTimeout(function(){ $("._btn_publish_all").eq(0).click();$('._btn_start').click(); },1000); } } return { init: init } })(); <file_sep>/src/js/cms_model/PageElement_HTMLService.js var PageElement_HTMLService = (function(){ var tag = ""; function getExportTag(o, _extra, _deep) { return getTag(o, "export", _deep); } /* ---------- ---------- ---------- */ function getTag(o, _extra, _deep) { if(typeof o == "string")return o; var tag = ""; if (_extra == undefined) _extra = ""; if (_deep == undefined) _deep = 1; // tag = _core(o, _extra, _deep); tag = tagTreatment(tag); tag = tag.split("_narrow-element").join("") return tag; } function _core(o,_extra,_deep){ var tag = "" //if (o.attr == undefined) return; if(o == null) return tag; if (o.attr.hide) return tag; if(_extra == "export"){ // } else{ if (o.attr["embedName"])return tag; if (o.attr["pubFileName"])return tag; } var tb = getTab(_deep); var attr = CMS_BlockAttrU.getHTMLArrs(o.attr); //基本的なタグや、Objectを処理 if(PageElement_Util.isElement(o.type)){ var t = PageElement_Util.getHTML(o,attr,tb); if(t != undefined){ tag += t; } return tag; } //レイアウトタグ生成 /* ---------- ---------- ---------- */ var type = o.type; var data = o.data; /* ---------- ---------- ---------- */ if (_extra == "td") { attr = attr.split('class="').join('class="cms-column-col '); tag += tb + '<div ' + attr + '>\n'; for (var i = 0; i < data.length; i++) { tag += _core(data[i], "", _deep + 1); } if(data.length == 0) tag += "<br>"; tag += "\n" + tb + "</div>\n"; /* ---------- ---------- ---------- */ } else if (type == "replace.div") { tag += "" /* ---------- ---------- ---------- */ } else if (type == "layout.div") { attr = attr.split('class="').join('class="cms-layout '); if(o.extra){ var bg = CMS_ImgBlockU.getBgStyle(o.extra,true); if(attr.indexOf("style=") == -1){ attr = attr.split('class="').join('style="" class="'); } attr = attr.split('style="').join('style="' + bg); } if (_deep != 0) tag += tb + '<div ' + attr + ' >\n'; for (var i = 0; i < data.length; i++) { tag += _core(data[i], "", _deep + 1); //コンポジット } if (_deep != 0) tag += tb + "</div>\n"; /* ---------- ---------- ---------- */ } else if (type == "layout.cols") { var _d = o.attr.devide; if (o.attr.devide == undefined) _d = ",,,,,,,,,,,,,,,"; d = _d.split(","); // attr = attr.split('class="').join('class="cms-column '); tag += tb + '<div ' + attr + '>\n'; for (var i = 0; i < data.length; i++) { tag += _core(data[i], "td", _deep + 1); //コンポジット } tag += tb + "</div>\n"; /* ---------- ---------- ---------- */ //h1など、上記にでてこなかったタグを処理する } else { try { var ss = data.split("\n").join("<br>\n" + tb); tag += tb + '<' + type + attr + '>' + ss + '</' + type + '>\n'; } catch (e) {} } return tag; } /* ---------- ---------- ---------- */ function getTab(_deep){ var s = "" for (var i = 1; i < _deep; i++) { s += " "; } return s; } /* ---------- ---------- ---------- */ function tagTreatment(_s){ _s = _s.split(" ").join(" "); _s = _s.split('=" ').join('="'); _s = _s.split('class="" ').join(''); _s = _s.split(' >').join('>'); return _s; } /* ---------- ---------- ---------- */ return { getExportTag: getExportTag, getTag: getTag } })(); window.PageElement_HTMLService = PageElement_HTMLService; <file_sep>/js_cms/_cms/embed.php <?php /** * JS_CMS -- realtime website development web application * http://js-cms.jp/ * Copyright 2015 <NAME> - <EMAIL> * licensed under the MIT licenses. */ define('CMS', true); require_once("./setting/setting.php"); require_once("./storage.funcs.php"); require_once("./storage.login.php"); /* ! ---------- input ---------- ---------- ---------- ---------- */ // sleep(1); if(IS_DEMO){ status_success(); exit(); } $action = getVAL("action","",""); if($action == "") status_error("invalid action name"); if(! is_action($action)) status_error("invalid action name"); $file_name = getVAL("file_name","",""); $dir_name = getVAL("dir_name","","dir"); if(! is_fileName($file_name)) status_error("invalid name"); if(! is_filePath($dir_name)) status_error("invalid path"); $file_path = $dir_name.$file_name; $text = getVAL("text","",""); $waf_escape = getVAL('waf_escape',"","boolean"); if($waf_escape){ if($text){ $text = str_replace("~", "",$text); $text = str_replace("__TILDE__", "~",$text); } } /* ! ---------- main ---------- ---------- ---------- ---------- */ if(!file_exists($dir_name)) status_error_dir($dir_name); if($action == "checkDir"){ status_success(); } if($action == "checkFile"){ if(file_exists($file_path)){ status_success(); } else { status_fileNotFound(); } } if($action == "read"){ if(file_exists($file_path)){ echo file_get_contents($file_path); exit(); } else { status_fileNotFound(); } } if( $action == "write"){ if(!file_exists($file_path)) unlink ($file_path); if($text == "") $text = "\n"; if(file_put_contents($file_path, $text)){ status_success(); } else { status_error("failed to write file."); } } if( $action == "writeToTemp"){ $file_path_temp = $file_path .'.temp'; if(file_exists($file_path_temp)) unlink ($file_path_temp); if($text == "") $text = "\n"; if(file_put_contents($file_path_temp, $text)){ status_success(); } else { status_error("failed to write temp file."); } } if( $action == "renameTemp"){ $file_path_temp = $file_path .'.temp'; if(rename($file_path_temp,$file_path)){ status_success(); } else { status_error("failed to write file."); } } if( $action == "delete"){ if(file_exists($file_path)) { if(unlink ($file_path)){ status_success(); } } status_error("failed to delete file."); } <file_sep>/src/js/cms_view_floats/AddElementsBtnSet.js AddElementsBtnSet = (function(){ var view; var v = {}; var _delay function init(){ view = $('#AddElementsBtnSet'); var tag = ""; tag += '<div class="_btn"><div class="_cms_btn_alphaS ss_add_misk _01"></div><div class="_help-icon _btn_guide_01"><i class="fa fa-question "></i></div></div>'; tag += '<div class="_btn"><div class="_cms_btn_alphaS ss_add_misk _02"></div><div class="_help-icon _btn_guide_02"><i class="fa fa-question "></i></div></div>'; // tag += '<div class="_btn"><div class="_cms_btn_alphaS ss_add_misk _01"></div></div>'; // tag += '<div class="_btn"><div class="_cms_btn_alphaS ss_add_misk _02"></div></div>'; view.html(tag) // stageInit(); setBtn(); } /* ---------- ---------- ---------- */ function setBtn(){ v._01 = view.find('._01') v._02 = view.find('._02') v._01.click(function(){ openGadgetList() }); v._02.click(function(){ openMyPreset() }); view.find('._btn_guide_01').click(function(){CMS_GuideU.openGuide("block/gadget"); }); view.find('._btn_guide_02').click(function(){CMS_GuideU.openGuide("block/preset"); }); } function openGadgetList(){ GadgetListView.stageIn(function(_type,_param){ setTimeout(function(){ if(_type == "_repeat"){ AddElementsManager.addElement_by_object(_param); } else{ AddElementsManager.addElement(_type,""); } },200); }) } function openMyPreset(){ PresetStageView.stageIn() } function addElement(_param){ setTimeout(function(){ AddElementsManager.addElement_by_object(_param); },200); } return { init: init } })();<file_sep>/src/js/cms_main/TreeViewMakerView.js var TreeViewMakerView = (function(){ var view; var v = {}; var LEVEL_MAX = 5; var dirListView; var tagListView; var pageListView; var presetBtns = [ ["simple","ページ一覧"], ["gnavi","グローバルナビ"], ["gnavi_c","カスタムナビ"], ["snavi","ローカルナビ"], ["footer","フッターリンク"], ["mobile","スマホメニュー"] ] function init(){ view = $('#TreeViewMakerView'); dirListView = TreeViewMakerView_DirList; tagListView = TreeViewMakerView_TagList; pageListView = TreeViewMakerView_PageList; stageInit(); } /* ---------- ---------- ---------- */ function createlayout(){ v = ModalViewCreater.createBaseView(TreeViewMakerView,view); var tag = "" tag += '<div class="clearfix">'; tag += ' <div class="_p _title">ナビゲーション編集 </div>' tag += '<div style="position:absolute;left:200px;top:15px;">' + CMS_GuideU.getGuideTag("window/navigation","_BASE_") + '</div>'; tag += ' <div class="_dirSelectArea clearfix">'; tag += ' <div class="_floatLeft "><b><i class="fa fa-sitemap "></i> ターゲットページ数:</b><span class="_matchPageCount">0</span> / <span class="_allPageCount">0</span></div>'; tag += ' <div class="_floatLeft _selectSet clearfix">'; tag += ' <div class="_targetDir">グループ:</div>'; tag += ' <div class="_dirListArea">'; tag += ' <div class="_dirListBtn"><i class="fa fa-folder "></i> <i class="fa fa-caret-down "></i> </div>'; tag += ' <div class="_dirListFuki _simple-scroll"></div>'; tag += ' </div>'; tag += ' </div>'; tag += ' <div class="_floatLeft _selectSet clearfix">'; tag += ' <div class="_targetTag">タグ : <b>選択なし</b></div>'; tag += ' <div class="_tagListArea">'; tag += ' <div class="_tagListBtn"><i class="fa fa-tags "></i> <i class="fa fa-caret-down "></i> </div>'; tag += ' <div class="_tagListFuki _simple-scroll"></div>'; tag += ' </div>'; tag += ' </div>'; tag += ' </div>'; tag += '</div>'; v.header.html(tag); tag = ""; tag += '<div class="_cms_btn _btn_close">キャンセル</div> '; tag += '<div class="_cms_btn _cms_btn_active _btn_do" '+TIP_ENTER+'><i class="fa fa-check"></i> 編集完了</div> '; v.footer.html(tag); var tag = ""; tag += '<div class="_previewArea">'; tag += ' <div class="_pageSelectArea clearfix">'; tag += ' <div class="_p _pageURL"></div>'; tag += ' <div class="_pageListArea">'; tag += ' <div class="_pageListBtn"><i class="fa fa-file-text "></i> プレビューページを選択 <i class="fa fa-caret-down "></i> </div>'; tag += ' <div class="_pageListFuki _simple-scroll"></div>'; tag += ' </div>'; tag += ' </div>'; tag += ' <div class="_p _previewViewTitle">プレビュー</div>'; tag += ' <div class="_p _previewTextTitle">HTMLプレビュー</div>'; tag += ' <div class="_inner _simple-scroll">'; tag += ' <div class="_previewView _previewTreeView">'; tag += ' <div class="_previewView_inner"></div>'; tag += ' </div>'; tag += ' <div class="_previewText">'; tag += ' <textarea wrap="off" readonly ></textarea>'; tag += ' </div>'; tag += ' </div>'; tag += '</div>'; // tag += '<div class="_editerArea">'; tag += '<div class="_inner">'; tag += ' <div class="_presets">'; tag += ' <div class="_p"><b>プリセット</b> </div>'; for (var i = 0; i < presetBtns.length ; i++) { tag += '<div class="_cms_btn-mini _btn_preset preset" data-id="'+presetBtns[i][0]+'"><i class="fa fa-list "></i> '+presetBtns[i][1]+'</div> '; } tag += ' </div>'; tag += ' <div class="_p _h3">■階層ごとのテンプレートタグ指定</div>'; tag += ' <table class="_levelTable">'; tag += ' <tr>'; tag += ' <th>階層</th>'; tag += ' <th>出力</th>'; tag += ' <th><i class="fa fa-2x fa-folder "></i> グループ</th>'; tag += ' <th><i class="fa fa-2x fa-file-text "></i> ページ</th>'; tag += ' <th><i class="fa fa-2x fa-file-text "></i> 追加メニュー</th>'; tag += ' <th><i class="fa fa-2x fa-font "></i> 見出し</th>'; tag += ' <th>初期表示</th>'; tag += ' </tr>'; tag += ' <tr class="_level l1">'; tag += ' <th class="_tree"><br>第1階層<br>│ </th>'; tag += ' <td class="_pd"><input type="checkbox" class="_show" checked></td>'; tag += ' <td><input type="text" class="_dir"></td>'; tag += ' <td><input type="text" class="_page"></td>'; tag += ' <td><input type="text" class="_add"></td>'; tag += ' <td><input type="text" class="_html"></td>'; tag += ' <td class="_pd"><input type="checkbox" class="_open" checked></td>'; tag += ' </tr>'; tag += ' <tr class="_level l2">'; tag += ' <th class="_tree">│ <br>├ 第2<br>│ │</th>'; tag += ' <td class="_pd"><input type="checkbox" class="_show" checked></td>'; tag += ' <td><input type="text" class="_dir"></td>'; tag += ' <td><input type="text" class="_page"></td>'; tag += ' <td><input type="text" class="_add" style="display:none"></td>'; tag += ' <td><input type="text" class="_html"></td>'; tag += ' <td class="_pd"><input type="checkbox" class="_open" checked></td>'; tag += ' </tr>'; tag += ' <tr class="_level l3">'; tag += ' <th class="_tree">│ │ <br>│ ├ 第3<br>│ │ │ </th>'; tag += ' <td class="_pd"><input type="checkbox" class="_show" checked></td>'; tag += ' <td><input type="text" class="_dir"></td>'; tag += ' <td><input type="text" class="_page"></td>'; tag += ' <td><input type="text" class="_add" style="display:none"></td>'; tag += ' <td><input type="text" class="_html"></td>'; tag += ' <td class="_pd"><input type="checkbox" class="_open" checked></td>'; tag += ' </tr>'; tag += ' <tr class="_level l4">'; tag += ' <th class="_tree">│ │ │ <br>│ │ ├ 第4<br>│ │ │ │ </th>'; tag += ' <td class="_pd"><input type="checkbox" class="_show" checked></td>'; tag += ' <td><input type="text" class="_dir"></td>'; tag += ' <td><input type="text" class="_page"></td>'; tag += ' <td><input type="text" class="_add" style="display:none"></td>'; tag += ' <td><input type="text" class="_html"></td>'; tag += ' <td class="_pd"><input type="checkbox" class="_open" checked></td>'; tag += ' </tr>'; tag += ' <tr class="_level l5">'; tag += ' <th class="_tree">│ │ │ │ <br>│ │ │ ├ 第5<br>│ │ │ │ │ </th>'; tag += ' <td class="_pd"><input type="checkbox" class="_show" checked></td>'; tag += ' <td><input type="text" class="_dir"></td>'; tag += ' <td><input type="text" class="_page"></td>'; tag += ' <td><input type="text" class="_add" style="display:none"></td>'; tag += ' <td><input type="text" class="_html"></td>'; tag += ' <td class="_pd"><input type="checkbox" class="_open" checked></td>'; tag += ' </tr>'; tag += ' </table>'; tag += ' <div class="_p _h3">■第1階層 追加メニュー</div>'; tag += ' <table class="">'; tag += ' <tr>'; tag += ' <td><div class="_cms_btn _btn_add">メニュー編集</div></td>'; tag += ' <td><i class="fa fa-angle-right " style="margin:10px;"></i></td>'; tag += ' <td><div class="_area_addMenu"></div></td>'; tag += ' </tr>'; tag += ' </table>'; tag += ' <div class="_p _h3">■オプション</div>'; tag += ' <table class="_optionTable">'; tag += ' <tr><th><input type="checkbox" class="_setting _useToggle" ></th><td>開閉メニュー</td><td class="sm">トルグメニューを作成できます。グループノードに(+)(-)アイコンが追加されます。</td></tr>'; tag += ' <tr><th><input type="checkbox" class="_setting _onlyCurrent" ></th><td>現在のツリーだけ表示</td><td class="sm">サイドナビなど、特定のノード以下のみ表示。第1階層のみ</td></tr>'; tag += ' <tr><th><input type="checkbox" class="_setting _isFlat" ></th><td>フラットにする</td><td class="sm">グループの階層構造を解除してフラットなページ一覧に</td></tr>'; tag += ' <tr><th><input type="checkbox" class="_setting _hasDate" ></th><td>日付指定のあるページのみ</td><td class="sm">ページ設定で日付を設定しているページのみを表示します</td></tr>'; tag += ' <tr><th></th><td><input type="checkbox" class="_setting _isReverse" > 日付の古い順に並べる</td><td class="sm">日付の古い順に並べます</td></tr>'; tag += ' </table>'; tag += ' <table class="_optionTable">'; tag += ' <tr><td>表示ページ数制限</td><td><input type="number" class="_setting _limitSub" style="width:40px"></td><td class="sm">グループ内のページ数を制限することができます。<br>空欄の場合は、すべて表示されます。</td></tr>'; tag += ' </table>'; tag += ' <table class="_optionTable">'; tag += ' <tr><td>字下げ</td><td><input type="number" class="_setting _indent" style="width:40px"></td><td class="sm">字下げするタブの数を入力できます。</td></tr>'; tag += ' </table>'; tag += ' <div class="_p _h3">■各ノードに設定されるクラス</div>'; tag += ' <div class="_p _read">各ノードには、そのノードの情報がクラスとして設定され、自身でCSSをカスタマイズしたり、新規に記述することにより、自由にデザインすることができます。</div>'; tag += ' <table class="_optionTable">'; tag += ' <tr><th><input type="checkbox" class="_setting _clearfix" ></th><td>clearfix</td><td class="sm">clearfixが指定されます</td></tr>'; tag += ' <tr><th><input type="checkbox" class="_setting _current" ></th><td>_current</td><td class="sm">現在開いているページとノードが同じ場合に指定されます</td></tr>'; tag += ' <tr><th><input type="checkbox" class="_setting _ownCurrent" ></th><td>_ownCurrent</td><td class="sm">現在開いているページを含むノードの場合に指定されます</td></tr>'; tag += ' <tr><th><input type="checkbox" class="_setting _hasSub" ></th><td>_hasSub</td><td class="sm">サブノードを持ってる場合に指定されます</td></tr>'; tag += ' <tr><th><input type="checkbox" class="_setting _underconst" ></th><td>_underconst</td><td class="sm">工事中のノードに指定されます</td></tr>'; tag += ' <tr><th><input type="checkbox" class="_setting _type" ></th><td>_type-...</td><td class="sm">ノードの種別が指定されます<br>( _type-dir , _type-page , _type-html )</td></tr>'; tag += ' <tr><th><input type="checkbox" class="_setting _level" ></th><td>_level-...</td><td class="sm">現在の階層の深さが指定されます</td></tr>'; tag += ' <tr><th><input type="checkbox" class="_setting _no" ></th><td>_no-...</td><td class="sm">ノード番号が順が指定されます</td></tr>'; tag += ' <tr><th><input type="checkbox" class="_setting _sum" ></th><td>_sum-...</td><td class="sm">サブノードの合計が指定されます</td></tr>'; tag += ' </table>'; tag += ' <br>' tag += ' <div class="_p _cms_btn _btn_direct_edit">設定データを直接編集する</div>' tag += '</div>'; tag += '</div>'; v.body.html(tag); v.previewArea = view.find('._previewArea') v.editerArea = view.find('._editerArea') initView(); v.previewView = view.find("._previewView_inner"); v.previewText = view.find("._previewText textarea"); v.pageURL = view.find("._pageURL"); view.on("click","._previewView a",function(event){ pageListView.select_by_href($(this).attr("href")); event.stopPropagation(); event.preventDefault(); }) v.levelInput = view.find("._levelTable :text"); v.levelInput.click(function(){ var tar = $(this); TreeViewMakerViewEditor.stageIn( tar.val(), function(_s){ tar.val(_s).change() }, [tar.offset().left,tar.offset().top], tar.attr("class") ); }); //input v.input = view.find("input"); v.input.keyup(function(){update_delay()}); v.input.change(function(){update_delay()}); v.checks = view.find(":checkbox"); v.allPageCount = view.find("._allPageCount"); v.matchPageCount = view.find("._matchPageCount"); //preset v.btn_preset = view.find("._btn_preset"); v.btn_preset.click(function(){setPreset($(this).data("id"))}); dirListView.init(view.find("._dirListArea")); dirListView.update(sitemap); tagListView.init(view.find("._tagListArea")); tagListView.update(sitemap); pageListView.init(view.find("._pageListArea")); //preset v.btn_direct_edit = view.find("._btn_direct_edit"); v.btn_direct_edit.click(function(){openDirectEdit()}); //preset v.area_addMenu = view.find("._area_addMenu"); v.btn_add = view.find("._btn_add"); v.btn_add.click(function(){showInlineGridEditor()}); setBtn(); } /* ---------- ---------- ---------- */ function setBtn(){ v.bg = view.find("._bg"); v.bg.click(function(){ stageOut() }); v._btn_close = view.find("._btn_close"); v._btn_close.click(function(){ stageOut() }); v.btn_do = view.find('._btn_do'); v.btn_do.click(function(){ callback(getParam()); stageOut(); }); } /* ---------- ---------- ---------- */ //直接編集 function openDirectEdit(){ var _s = JSON.stringify(getParam(), null, " "); Editer_JSONView.stageIn(_s,function(_param){ try{ setData(JSON.parse(_param)); }catch( e ){ alert("データ形式が正しくありません。"); } }); } /* ---------- ---------- ---------- */ //プリセット function setPreset(_s){ var _s = TreeViewMakerPreset[_s]; setData(JSON.parse(JSON.stringify(_s))) } function initView(){ // v.targetDir = view.find("._targetDir"); v.targetTag = view.find("._targetTag"); // v.setting = {} v.setting.useToggle = view.find("._setting._useToggle") v.setting.onlyCurrent = view.find("._setting._onlyCurrent"); v.setting.isFlat = view.find("._setting._isFlat"); v.setting.hasDate = view.find("._setting._hasDate"); v.setting.isReverse = view.find("._setting._isReverse"); v.setting.limitSub = view.find("._setting._limitSub"); v.setting.indent = view.find("._setting._indent"); // v.css = {} v.css.clearfix = view.find("._setting._clearfix"); v.css.current = view.find("._setting._current"); v.css.ownCurrent = view.find("._setting._ownCurrent"); v.css.hasSub = view.find("._setting._hasSub"); v.css.underconst = view.find("._setting._underconst"); v.css.type = view.find("._setting._type"); v.css.level = view.find("._setting._level"); v.css.no = view.find("._setting._no"); v.css.sum = view.find("._setting._sum"); // v.trs = view.find("._level"); v.ls = []; for (var i = 0; i < LEVEL_MAX ; i++) { var s = ".l" + (i+1); v.ls.push({ show:view.find(s + " ._show"), open:view.find(s +" ._open"), dir :view.find(s +" ._dir"), page:view.find(s +" ._page"), add:view.find(s +" ._add"), html:view.find(s +" ._html") }) } } /* ! ---------- ---------- ---------- ---------- ---------- */ var targetDir; function selectDir(_s,_name){ targetDir = _s; v.targetDir.html(_name); updatePageList(); } var targetTag; function selectTag(_s,_name){ targetTag = _s; v.targetTag.html(_name); updatePageList(); } function updatePageList(){ pageListView.update(TreeAPI.getSubTree(sitemap, targetDir, targetTag)); pageListView.show(); } var previewParam = {} function selectPage(_o){ previewParam.id = _o.id; previewParam.dir = _o.dir; v.pageURL.html('HTMLプレビュー : <b><i class="fa fa-file-text "></i> ' + TreeViewU.roundText(_o.name) + '</b>'); update_delay(); } /* ! ---------- ---------- ---------- ---------- ---------- */ /* ! ---------- ---------- ---------- ---------- ---------- */ /* ! ---------- ---------- ---------- ---------- ---------- */ var addMenu function setData(_param){ if(_param ==undefined) _param = {}; v.allPageCount.html('<b>' + TreeAPI.getPageSum(sitemap) + '</b>'); //入力リセット v.input.val(""); v.checks.prop("checked",false); //現在値をセット dirListView.setCurrent(_param.targetDir); tagListView.setCurrent(_param.targetTag); pageListView.setCurrent(_param.previewPage); if(_param.setting ==undefined) _param.setting = {} if(_param.setting.useToggle) v.setting.useToggle.prop("checked",true); if(_param.setting.onlyCurrent) v.setting.onlyCurrent.prop("checked",true); if(_param.setting.isFlat) v.setting.isFlat.prop("checked",true); if(_param.setting.hasDate) v.setting.hasDate.prop("checked",true); if(_param.setting.isReverse) v.setting.isReverse.prop("checked",true); v.setting.limitSub.val(_param.setting.limitSub); v.setting.indent.val(_param.setting.indent); if(_param.setting.add == undefined){ _param.setting.add = {} } addMenu = _param.setting.add; //クラス初期値 if(_param.css == undefined){ _param.css = {} _param.css.clearfix = true; _param.css.current = true; _param.css.ownCurrent = true; _param.css.hasSub = true; _param.css.underconst = true; _param.css.type = true; _param.css.level = true; _param.css.no = true; _param.css.sum = true; } //inputに値をセット if(_param.css.clearfix) v.css.clearfix.prop("checked",true); if(_param.css.current) v.css.current.prop("checked",true); if(_param.css.ownCurrent) v.css.ownCurrent.prop("checked",true); if(_param.css.hasSub) v.css.hasSub.prop("checked",true); if(_param.css.underconst) v.css.underconst.prop("checked",true); if(_param.css.type) v.css.type.prop("checked",true); if(_param.css.level) v.css.level.prop("checked",true); if(_param.css.no) v.css.no.prop("checked",true); if(_param.css.sum) v.css.sum.prop("checked",true); //階層テーブルに値をセット var ls = _param.levels; if(ls ==undefined) ls = [] for (var i = 0; i < LEVEL_MAX ; i++) { if(ls[i] == undefined){ ls[i] = {} ls[i].isShow = false ls[i].isOpen = false ls[i].dir = "" ls[i].page = "" ls[i].add = "" ls[i].html = "" } v.ls[i].show.prop("checked",ls[i].isShow) v.ls[i].open.prop("checked",ls[i].isOpen) v.ls[i].dir.val(ls[i].dir); v.ls[i].page.val(ls[i].page); v.ls[i].add.val(ls[i].add); v.ls[i].html.val(ls[i].html); } update_delay(); } var tID; function update_delay(){ if(tID) clearTimeout(tID); tID = setTimeout(function(){ update(); },100); } /* ---------- ---------- ---------- */ function update(){ v.matchPageCount.html('<b>' + pageListView.getPageSum() + '</b>'); var _param = getParam(); var tag = TreeAPI.getTag(htmlDir, sitemap , _param); tag = tag.split(TreeAPI_SITE_DIR).join(""); // v.previewView.html(tag); v.previewText.val(tag); // updateAddMenuView(_param.setting); updateLevelView(_param.levels); TreeAPI.setToggleMenu(view); } function updateAddMenuView(_setting){ var tag = ""; tag += ' <table class="_optionTable">'; tag += ' <tr>'; tag += ' <td><b>●先頭に追加</b><br>{TOP}</td>'; tag += ' <td><br></td>'; tag += ' <td><b>●最後に追加</b><br>{BOTTOM}</td>'; tag += ' </tr>'; tag += ' </table>'; var tagT = ""; var tagB = ""; if(_setting.add){ try{ var adds = _setting.add.list.grid; for (var i = 0; i < adds.length ; i++) { tagT += adds[i].text + '<br>' } var adds = _setting.add.list2.grid; for (var i = 0; i < adds.length ; i++) { tagB += adds[i].text + '<br>' } }catch( e ){} } if(tagT=="")tagT = "--"; if(tagB=="")tagB = "--"; tag = tag.split("{TOP}").join(tagT); tag = tag.split("{BOTTOM}").join(tagB); v.area_addMenu.html(tag); } function updateLevelView(_ls){ v.trs.removeClass("_disable"); for (var i = 0; i < LEVEL_MAX ; i++) { var b = false; if(_ls[i]){ if(_ls[i].isShow ) b = true; } if(b == false) v.trs.eq(i).addClass("_disable"); } } /* ---------- ---------- ---------- */ function getParam(){ return { previewPage : _getPreviewPage(), targetTag : _getTragetTagVal(), targetDir : _getTragetDirVal(), setting : _getSettingVal(), css : _getCSSVal(), levels : _getLevelListVal() } } function _getPreviewPage(){ return {id:previewParam.id,dir:previewParam.dir}; } function _getTragetTagVal(){ return targetTag; } function _getTragetDirVal(){ return targetDir; } function _getSettingVal(){ var _o = {} _o.useToggle = v.setting.useToggle.prop("checked") ? true:false; _o.onlyCurrent = v.setting.onlyCurrent.prop("checked") ? true:false; _o.isFlat = v.setting.isFlat.prop("checked") ? true:false; _o.hasDate = v.setting.hasDate.prop("checked") ? true:false; _o.isReverse = v.setting.isReverse.prop("checked") ? true:false; _o.limitSub = v.setting.limitSub.val(); _o.indent = v.setting.indent.val(); _o.add = addMenu; return _o; } function _getCSSVal(){ var _o = {} _o.clearfix = v.css.clearfix.prop("checked") ? true:false; _o.current = v.css.current.prop("checked") ? true:false; _o.ownCurrent = v.css.ownCurrent.prop("checked") ? true:false; _o.hasSub = v.css.hasSub.prop("checked") ? true:false; _o.underconst = v.css.underconst.prop("checked") ? true:false; _o.type = v.css.type.prop("checked") ? true:false; _o.level = v.css.level.prop("checked") ? true:false; _o.no = v.css.no.prop("checked") ? true:false; _o.sum = v.css.sum.prop("checked") ? true:false; return _o; } function _getLevelListVal(){ var _a = []; var temp = [] for (var i = 0; i < LEVEL_MAX ; i++) { temp[i] = {} temp[i].isShow = v.ls[i].show.prop("checked") ? true:false; temp[i].isOpen = v.ls[i].open.prop("checked") ? true:false; if(v.ls[i].dir.val()) temp[i].dir = v.ls[i].dir.val(); if(v.ls[i].page.val()) temp[i].page = v.ls[i].page.val(); if(v.ls[i].add.val()) temp[i].add = v.ls[i].add.val(); if(v.ls[i].html.val()) temp[i].html = v.ls[i].html.val(); _a.push(temp[i]); } return _a; } /* ---------- ---------- ---------- */ var detailView; function showInlineGridEditor(){ detailView = null; detailView = new EditableView.SubPageView(); detailView.setObjectType(PageTypeList.tree); detailView.registParent(TreeViewMakerView); detailView.createView(); detailView.initData(addMenu); detailView.stageIn(); } window.showInlineGridEditor = showInlineGridEditor; function hideInlineGridEditor(){ addMenu = detailView.getData(); update_delay(); } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } var callback; var htmlDir; function stageIn(_htmlDir, _sitemap,_param,_callback){ if(! isOpen){ isOpen = true; showModalView(this); view.show(); callback = _callback; htmlDir = _htmlDir; sitemap = _sitemap; if(isFirst){ createlayout(); isFirst = false; } setData(_param); } } function stageOut(){ if(isOpen){ isOpen = false; hideModalView(); view.hide(); TreeViewMakerViewEditor.stageOut() } } return { init: init, stageIn: stageIn, stageOut: stageOut, selectDir:selectDir, selectTag:selectTag, selectPage:selectPage, update_delay:update_delay, hideInlineGridEditor:hideInlineGridEditor } })(); var TreeViewU = (function(){ //TreeViewU.roundText(_s,10) function roundText(_s ,_n) { _n = _n || 15; if(_s.length > _n) _s = _s.substr(0,_n) + "..." return _s; } return { roundText:roundText } })(); <file_sep>/js_cms/_cms/grid/js/grid.js /** * GRID PREVIEW * Copyright 2016 <NAME> - <EMAIL> * licensed under the MIT licenses. */ var GRID_INFO = { name:"GRID PREVIEW", lastUpdate:"2016/12/10 17:40:39", version:"1.0.0.0" } $(function() { if (window.IS_UNITTEST)return; GRID.MainController.init(); }); // var DATA_DIR_PHP = '../data/'; // var DATA_DIR_HTML = './data/'; // var PHP_FILE = './lib/storage.php'; // var PHP_FILE_IO = './lib/fileIO.php'; // var PHP_FEACH = './lib/storage.fetch.php'; var parentFrame = this; function keyUp_(_key) { GRID.MainController.keyUp_(_key); } function openPreview(_u, _n) { GRID.MainController.openPreview(_u, _n); } var frames = []; function bodyElement() { return $('html,body'); } function getInputNumber(_abs, _n, _def) { var n; if (_abs === 'abs') { if (_n === undefined) { n = prompt('', _def); if (n === undefined)return _def; n = Number(n); if (isNaN(Number(n)))return _def; } else { n = _n; } } else { n = _def + _n; } return n; } function setLimitNumber(n, _leng) { if (n < _leng[0]) n = _leng[0]; if (n > _leng[1]) n = _leng[1]; return n; } var GPCommon = {}; GPCommon.aray_hasData = function(_a, _s) { var b = false; for (var i = 0; i < _a.length; i++) { if (_a[i] == _s)b = true; } return b; }; GPCommon.cssUpdate = function(node) { var u = $(node).attr('href'); u = u.split('?')[0]; u = u + '?' + new Date().getTime(); $(node).attr('href', u); }; GPCommon.jsUpdate = function(node) { /*var u = $(node).attr("src"); u = u.split("?")[0]; u = u + "?" + new Date().getTime(); $(node).attr("src",u);*/ }; GPCommon.setDom_for_css = function(_doms) { //domからCSSノードを抽出する try { _doms[0].contentWindow.location.href; }catch (e) { return [[], [], []]; } function core(_list) { var a = $(''); var leng = _list.size(); for (var i = 0; i < leng; i++) { var d = _list.eq(i); if (d.attr('rel') == 'stylesheet') { a = a.add(d); } } return a; } var cssNodes = []; var cssUrls = []; var taiouMap = []; for (var i = 0; i < _doms.length; i++) { var list = $(_doms[i].contentWindow.document).find('link'); cssNodes.push(core(list)); } var baseURL = URL_.getBaseDir(_doms[0].contentWindow.location.href); for (var i = 0; i < cssNodes.length; i++) { var leng = cssNodes[i].size(); for (var ii = 0; ii < leng; ii++) { var s = cssNodes[i].eq(ii).attr('href'); s = s.split('?')[0]; var u = URL_.joinURL(baseURL, s); if (u != '') { taiouMap.push({'url': u, 'node': cssNodes[i].eq(ii)}); cssUrls.push(u); } } } return [cssNodes, cssUrls, taiouMap]; }; GPCommon.setDom_for_js = function(_doms) { //domからCSSノードを抽出する try { _doms[0].contentWindow.location.href; }catch (e) { return [[], [], []]; } function core(_list) { var a = $(''); var leng = _list.size(); for (var i = 0; i < leng; i++) { var d = _list.eq(i); //if(d.attr("rel") == "stylesheet"){ a = a.add(d); //} } return a; } var jsNodes = []; var jsUrls = []; var taiouMap = []; for (var i = 0; i < _doms.length; i++) { var script = $(_doms[i].contentWindow.document).find('script'); jsNodes.push(core(script)); } var baseURL = URL_.getBaseDir(_doms[0].contentWindow.location.href); for (var i = 0; i < jsNodes.length; i++) { var leng = jsNodes[i].size(); for (var ii = 0; ii < leng; ii++) { if (jsNodes[i].eq(ii).attr('src') != null) { var s = jsNodes[i].eq(ii).attr('src'); s = s.split('?')[0]; var u = URL_.joinURL(baseURL, s); if (u != '') { taiouMap.push({'url': u, 'node': jsNodes[i].eq(ii)}); jsUrls.push(u); } } } } return [jsNodes, jsUrls, taiouMap]; }; GPCommon.arrayToTable = function(_array) { var tag = ''; tag += '<table>'; for (var i = 0; i < _array.length; i++) { var cell = _array[i]; tag += '<tr>'; for (var ii = 0; ii < cell.length; ii++) { tag += '<td>' + cell[ii] + '</td>'; } tag += '</tr>'; } tag += '</table>'; return tag; }; /* ---------- ---------- ---------- ---------- ---------- ---------- ---------- */ var GRID = {}; GRID.API = (function() { function error() { alert('ネットワークエラーが発生しました。'); } function feach(_p, _callback) { var u = PHP_FEACH + '?url='+ _p; $.ajax({ scriptCharset: 'utf-8', type: 'GET', url: u, dataType: 'text', success: function(data) { _callback(data); }, error: function(s) {error()} }); } function fileIO(_p, _callback) { $.ajax({ scriptCharset: 'utf-8', type: 'POST', data: _p, url: PHP_FILE_IO, dataType: 'text', success: function(data) { _callback(data); }, error: function(s) {error()} }); } function loadFile(_f, _callback) { $.ajax({ scriptCharset: 'utf-8', type: 'GET', url: _f, dataType: 'text', success: function(data) { _callback(data); }, error: function(s) {error()} }); } function loadFile_r(_f, _callback, _callback_e) { $.ajax({ scriptCharset: 'utf-8', type: 'GET', url: _f + '?u='+ new Date().getTime(), dataType: 'text', success: function(data) { _callback(data); }, error: function(data) { _callback_e(data); } }); } function saveFile(_p, _callback) { $.ajax({ scriptCharset: 'utf-8', type: 'POST', url: PHP_FILE, data: _p, dataType: 'text', success: function(data) { _callback(data); }, error: function(s) {error()} }); } return { feach: feach, fileIO: fileIO, loadFile: loadFile, loadFile_r: loadFile_r, saveFile: saveFile }; })(); GRID.Data = {}; GRID.Data.title; GRID.Data.list; GRID.Data.pageSum = 0; GRID.Data.gloupSum = 0; // GRID.Data.saveDir;//データディレクトリ // GRID.Data.saveDir_php;//データディレクトリ GRID.Data.iframes = []; GRID.App = { app: { domain: '', url: '', dataUrl: '' }, baseUrls: { items: [], current: 0, url: '' } }; GRID.StateCommon = { viewType: 'preview',//{preview,list,edit} currentRect: 0, currentGloup: 0, preview: { url: '', no: 0 }, split: { display: false, widths: [1200], scale: 50 }, search: { preview: { text: '', isHide: false }, list: { text: '', isHide: false } } } GRID.StateCommonManager = (function(){ var view; var v = {}; /* ---------- ---------- ---------- */ //初期化 var pageID = ""; var storage; function init(){ pageID = "GRID_COM_v2" + URL_.getABSDir(location.href); storage = localStorage; if (storage[pageID] == null) { // } else { GRID.StateCommon = JSON.parse(storage[pageID]); } } function update(){ storage[pageID] = JSON.stringify(GRID.StateCommon); } function setCurrentRect(_n){ GRID.StateCommon.currentRect = _n; update(); } function setCurrentGloup(_n){ GRID.StateCommon.currentGloup = _n; update(); } function setPreviewNo(_n){ GRID.StateCommon.preview.no = _n; update(); } function setPreviewUrl(_u){ GRID.StateCommon.preview.url = _u; update(); } function setViewType(_s){ GRID.StateCommon.viewType = _s; update(); } /**/ function setDisplay(_b){ GRID.StateCommon.split.display = _b; update(); } function setWidths(_a){ GRID.StateCommon.split.widths = _a; update(); } function setScale(_s){ GRID.StateCommon.split.scale = _s; update(); } return { init: init, update: update, setCurrentRect: setCurrentRect, setCurrentGloup: setCurrentGloup, setPreviewNo: setPreviewNo, setPreviewUrl: setPreviewUrl, setViewType: setViewType, setDisplay: setDisplay, setWidths: setWidths, setScale: setScale } })(); GRID.CurrentRect = {} GRID.StateSet = {} GRID.StateSetManager = (function(){ var view; var v = {}; /* ---------- ---------- ---------- */ //初期化 var pageID = ""; var storage; function init(){ pageID = "GRID_v2" + URL_.getABSDir(location.href); storage = localStorage; if (storage[pageID] == null) { GRID.StateSet.current = 0; GRID.StateSet.list = getInitData(); } else { GRID.StateSet = JSON.parse(storage[pageID]); } GRID.StateSet.current = GRID.StateCommon.currentRect; GRID.CurrentRect = GRID.StateSet.list[GRID.StateSet.current]; } function getStateSet(){ return GRID.StateSet.list } // function getState(){ return GRID.StateSet.list[GRID.StateSet.current] } function getStateNo(){ return GRID.StateSet.current } function changeNo(_n){ GRID.StateSet.current = _n; GRID.StateCommonManager.setCurrentRect(_n); if(GRID.StateSet.list == ""){ GRID.StateSet.list = getInitData(); } GRID.CurrentRect = GRID.StateSet.list[_n]; } function save(){ storage[pageID] = JSON.stringify(GRID.StateSet); } function reset(){ GRID.StateSet.list = getInitData(); GRID.CurrentRect = GRID.StateSet.list[GRID.StateSet.current]; } var tID; function update(){ if(tID) clearTimeout(tID); tID = setTimeout(function(){ var n = GRID.StateSet.current; GRID.StateSet.list[n] = GRID.CurrentRect; },10); } var DEF = { widths : [ 1200 ], height : 2000, scale : 25, pagesW : 1200, background: '#666', color : '#ccc', margin : 1, noBR : false, notitle : false }; function getInitData(){ var a = [] var ls = GRID_PRESETs; for (var i = 0; i < ls.length ; i++) { var dd = ls[i] var o = JSON.parse(JSON.stringify(DEF)) o.widths = dd.widths; o.height = dd.height; o.scale = dd.scale; o.pagesW = (function(_ws){ var w = 0; for (var i = 0; i < _ws.length ; i++) { w += _ws[i]; } return _ws; })(o.widths); a.push(o) } return a; } return { init: init, save: save, reset: reset, getStateSet: getStateSet, getState: getState, getStateNo: getStateNo, update: update, changeNo: changeNo } })(); // GRID.StateReval = { text: '', jq: '', isHide: false, isIso: false, isLine: true, isBK: true, showSelector: false, showLink: false, showImg: false }; GRID.StatePageManager = (function(){ var pageID = ''; var storage; function init(){ pageID = "GRID_LAST_" + URL_.getABSDir(location.href); } function getListData(){ if(localStorage[pageID]){ return JSON.parse(localStorage[pageID]); } else{ return {}; } } function setListData(_s){ localStorage[pageID] = JSON.stringify(_s, null, " "); } return { init: init, getListData:getListData, setListData:setListData } })(); GRID.URL_Manager = (function() { function init() {} function setBaseUrl(_s) { var base = GRID.App.baseUrls; base.items = URL_.getBaseUrls_from_text(_s); base.current = (function() { var n = Number(window.location.hash.split('#')[1]); if (isNaN(n))n = 0; return n; })(); base.url = base.items[base.current]; } function getSimplePath(_s) { var base = GRID.App.baseUrls.url; return _s.split(base).join(''); } function getFullPath(_s) { return GRID.App.baseUrls.url + _s; } return { init: init, setBaseUrl: setBaseUrl, getSimplePath: getSimplePath, getFullPath: getFullPath }; })(); GRID.V = {}; GRID.V.mainFrame; GRID.V.subStage; GRID.V.subPreviews; GRID.M = {}; GRID.M.GloupData = (function() { var c = function() { this.init(); }; var p = c.prototype; sum = 0; p.type; p.no; p.id; p.name; p.isMemori; p.list; p.init = function() { this.type = 'gloup'; this.no = sum; this.id = this.type + '_' + sum; this.name = ''; this.isMemori = false; this.list = []; sum++; }; p.setServer = function(_s) { for (var i = 0; i < this.list.length; i++) { this.list[i].setServer(_s); } }; return c; })(); GRID.M.SubGloupData = (function() { var c = function() { this.init(); }; var p = c.prototype; sum = 0; p.type; p.no; p.id; p.name; p.list; p.init = function() { this.type = 'sub-gloup'; // this.no = sum; // this.id = this.type + '_' + sum; this.name = ''; this.list = []; // sum++; }; p.setServer = function(_s) { }; p.isSelectable = function() { return false; }; return c; })(); GRID.M.PageData = (function() { var c = function() { this.init(); }; var p = c.prototype; var count = 1; p.id; p.type; p.name; p.isMemori; p.deep; p.url;//http://192.168.1.23:1000/01_work/2013/20130809_maruo/www/test_grid/html/ir_lib.html p.url_origin;///html/ir_lib.html p.url_and_base; //<span class="base_url">__BASE_URL__</span>/html/ir_lib.html p.listTexts; p.init = function() { this.id = 'page_'+ DateUtil.getRandamCharas(10); this.type = 'page'; this.name = ''; this.url = ''; this.deep = 0; this.isMemori =false; this.no = count; count++; GRID.M.PageDataManager.addData(this); }; p.setServer = function(_s) { this.url_origin = this.url; this.url_and_base = this.url; if (_s != '') { var s = URL_.getDecoParamText(this.url); this.url_and_base = '<span class="base_url">__BASE_URL__</span>' + s; } if(URL_.isDomain(this.url)){ // } else{ this.url = URL_.joinURL(_s, this.url); } // http:// var tag = '<a href="{URL}" target="_blank">{URL_V} <i class=" fa fa-external-link-square "></i></a>'; tag = tag.split('{URL}').join(this.url); tag = tag.split('{URL_V}').join(this.url_and_base); this.listTexts = {}; this.listTexts.url = tag; this.listTexts.name = '<i class="fa fa-reply "></i> ' + this.decoDir(this.name); // }; /* ! ---------- ---------- ---------- ---------- ---------- */ p.decoDir = function(_s) { var ss = _s.split('/'); var a = []; for (var i = 0; i < ss.length; i++) { if (i == ss.length - 1) { a.push(ss[i]); } else { if (ss[ss.length - 1] == '') { a.push(ss[i]); } else { a.push('<span class="dir">' + ss[i] + '</span>'); } } } return a.join('<span class="dir_slash">/</span>'); }; p.isMatch = function(_s) { if (_s == '') return false; if (_s == null) return false; var b = false; var keys = _s.split(','); for (var i = 0; i < keys.length; i++) { if (this.isMatch_core(keys[i], this.url_origin) != -1) b = true; if (this.isMatch_core(keys[i], this.name) != -1) b = true; } return b; }; p.isMatch_core = function(_s1, _s2) { var _b = false; var s1 = _s1.toLowerCase(); var s2 = _s2.toLowerCase(); return s2.indexOf(s1); }; p.getMatchText_url = function(_s) { var keys = _s.split(','); var tag = ''; for (var i = 0; i < keys.length; i++) { if (this.isMatch_core(keys[i], this.url_origin) != -1) { if (tag == '') tag = this.getMatchText_url_core(keys[i]); } } if (tag == '')tag = this.listTexts.url; return tag; }; p.getMatchText_url_core = function(_s) { var b = false; var orijin = this.url_origin; var s = this.isMatch_core(_s, orijin); if (s == -1)return orijin; var matchText = orijin.substr(s, _s.length); var a = orijin.split(matchText).join('__em__' + matchText + '__end_em__'); var tag = '<a href="{URL}" target="_blank">{URL_V} <i class=" fa fa-external-link-square "></i></a>'; tag = tag.split('{URL}').join(this.url); tag = tag.split('{URL_V}').join(a); tag = tag.split('__em__').join('<em>'); tag = tag.split('__end_em__').join('</em>'); return tag; }; p.getMatchText_name = function(_s) { var keys = _s.split(','); var tag = ''; for (var i = 0; i < keys.length; i++) { if (this.isMatch_core(keys[i], this.name) != -1) { if (tag == '')tag = this.getMatchText_name_core(keys[i]); } } if (tag == '')tag = this.listTexts.name; return tag; }; p.getMatchText_name_core = function(_s) { var b = false; var orijin = this.name; var s = this.isMatch_core(_s, orijin); if (s == -1)return orijin; var matchText = orijin.substr(s, _s.length); var a = orijin.split(matchText).join('__em__' + matchText + '__end_em__'); var tag = '<i class="fa fa-reply "></i> ' + this.decoDir(a); tag = tag.split('__em__').join('<em>'); tag = tag.split('__end_em__').join('</em>'); return tag; }; /* ---------- ---------- ---------- */ p.isMatchSearch_; p.isMatchSearch = function(_b) { this.isMatchSearch_ = _b; }; p.isMatchTag_; p.isMatchTag = function(_b) { this.isMatchTag_ = _b; }; p.isSelectable = function() { if (this.isMatchSearch_ == null) this.isMatchSearch_ = true; if (this.isMatchTag_ == null) this.isMatchTag_ = true; var b = false; if (this.isMatchSearch_ && this.isMatchTag_) b = true; return b; }; return c; })(); GRID.M.PageDataManager = (function() { var pages = []; function addData(_p) { pages.push(_p); } function getData_by_id(_id) { for (var i = 0; i < pages.length; i++) { if (pages[i].id == _id)return pages[i]; } return false; } return { addData: addData, getData_by_id: getData_by_id }; })(); GRID.DataManager = (function() { var list = []; function setData(_t, _callback) { if(GRID_DATA_TYPE == "json"){ return GRID.DataManagerJSON.setData(_t, _callback); } else{ return GRID.DataManagerHTML.setData(_t, _callback); } } return { setData: setData }; })(); GRID.DataManagerJSON = (function() { function setData(_t, _callback) { _callback( setTitle(), setMemo(), setParam(), setList(_t), pageSum ); } /* ---------- ---------- ---------- */ var list = []; function setTitle() { return "title"; } /* ---------- ---------- ---------- */ function setMemo() { return "memo"; } /* ---------- ---------- ---------- */ function setParam() { var ss = GRID_SITEMAP_JSON.split("../"); var bs = ""; for (var i = 0; i < ss.length-1 ; i++) { bs += "../"; } var base = URL_.getDomain_and_dir(location.href); base = URL_.joinURL(base ,bs); return { baseUrls: base } } /* ---------- ---------- ---------- */ function _getPageData(_node,_id ,_deep){ var dir = "html/" if(_node.dir) dir = _node.dir; var o = new GRID.M.PageData(); o.deep = _deep; o.name = _node.name; o.gloup = _id; o.url = dir + _node.id + '.html'; pageSum++; return o; } function _getGloupData(_model,_node,_deep){ _deep++; for (var ii = 0; ii < _node.list.length ; ii++) { // if(ii > 3)return; if(_node.list[ii].type == "page"){ _model.list.push(_getPageData( _node.list[ii] , _model.id,_deep, 1 )); } if(_node.list[ii].type == "dir"){ var g = new GRID.M.SubGloupData(); g.name = _node.list[ii].name; g.gloup = _model.id; _model.list.push(g); _getGloupData(_model ,_node.list[ii] , _deep ); } } } var pageSum = 0; function setList(_s) { var sitemap = JSON.parse(_s); var roots = []; var siemapID = "_sitemap_" var g = new GRID.M.GloupData(); g.id = siemapID + "root" g.name = "ルート" g.no = 0; roots.push(g); for (var i = 0; i < sitemap.list.length ; i++) { if(sitemap.list[i].type == "page"){ g.list.push(_getPageData(sitemap.list[i] , g.id, 0 )); } } for (var i = 0; i < sitemap.list.length ; i++) { if(sitemap.list[i].type == "dir"){ var subG = new GRID.M.GloupData(); subG.id = siemapID + sitemap.list[i].id; subG.name = sitemap.list[i].name; subG.no = 0; roots.push(subG); _getGloupData(subG ,sitemap.list[i],0); } } // return roots.concat(_getMemoriList()); } function _getMemoriList(){ var a = [] var myList = GRID.StatePageManager.getListData(); var tabs = GRID_MY_TAB; var s = [] for (var i = 0; i < tabs.length ; i++) { var g = new GRID.M.GloupData(); g.isMemori = true; g.id = tabs[i]; g.name = tabs[i]; g.list = []; if(myList[i]){ for (var ii = 0; ii < myList[i].length ; ii++) { var o = new GRID.M.PageData(); o.isMemori = true; o.deep = 1; o.name = myList[i][ii][1]; o.gloup = g.id; o.url = myList[i][ii][0]; pageSum++; g.list.push(o) } } a.push(g); } return a; } return { setData: setData }; })(); GRID.DataManagerHTML = (function() { function setData(_t, _callback) { _callback( setTitle(_t), setMemo(_t), setParam(_t), setList(_t), pageSum ); } /* ---------- ---------- ---------- */ var list = []; function setTitle(_t) { return "title"; } /* ---------- ---------- ---------- */ function setMemo(_t) { return "memo"; } /* ---------- ---------- ---------- */ function setParam(_t) { var base = URL_.getDomain_and_dir(_t.split("\n")[0]); if(base.charAt(0) == "."){ base = URL_.joinURL(location.href,base) } return { baseUrls: base } } /* ---------- ---------- ---------- */ function hasData(_s){ _s = _s.split(' ').join(''); _s = _s.split(' ').join(''); if (_s != '') return true; return false; } var pageSum = 0; function setList(_t) { var currentGloupID = ''; var roots = []; var ls = _t.split('\n'); for (var ii = 1; ii < ls.length; ii++) { if (hasData(ls[ii])) { if (ls[ii].charAt(0) == '#') { roots.push(new _h3(ls[ii])); } else { var gn = roots.length - 1; if(roots[gn]){ roots[gn].list.push(new _pre_line(ls[ii])); } } } } function _h3(_s) { var g = new GRID.M.GloupData(); g.name = _s; currentGloupID = g.id; return g; } function _pre_line(_s) { var name = _s; var url = _s; if (url.indexOf(',') != -1) { var ee = url.split(','); name = ee[0]; url = ee[1]; } var o = new GRID.M.PageData(); o.name = name; o.url = url; o.id = 'frame_' + pageSum; o.gloup = currentGloupID; pageSum++; return o; } return roots.concat(_getMemoriList()); } function _getMemoriList(){ var a = [] var myList = GRID.StatePageManager.getListData(); var tabs = GRID_MY_TAB; var s = [] for (var i = 0; i < tabs.length ; i++) { var g = new GRID.M.GloupData(); g.isMemori = true; g.id = tabs[i]; g.name = tabs[i]; g.list = []; if(myList[i]){ for (var ii = 0; ii < myList[i].length ; ii++) { var o = new GRID.M.PageData(); o.isMemori = true; o.deep = 1; o.name = myList[i][ii][1]; o.gloup = g.id; o.url = myList[i][ii][0]; pageSum++; g.list.push(o) } } a.push(g); } return a; } return { _test_setParam: setParam, _test_setList: setList, setData: setData }; })(); var GRID_DATA_TYPE = "json" GRID.MainController = (function() { v = {}; function init() { GRID.App.app.url = location.href; GRID.App.app.domain = URL_.getDomain(location.href); var file = "" if(window["GRID_SITEMAP_TXT"]) { GRID_DATA_TYPE = "txt"; file = GRID_SITEMAP_TXT; } if(window["GRID_SITEMAP_JSON"]) { GRID_DATA_TYPE = "json"; file = GRID_SITEMAP_JSON; } if(!file){ alert("grid_setting.jsの設定が正しくありません。") return; } GRID.StateCommonManager.init(); GRID.StateSetManager.init(); GRID.StatePageManager.init(); GRID.Data.fileName = file; GRID.API.loadFile(GRID.Data.fileName, function(data) { loaded(data); }); } var rowtext = ''; function loaded(_o) { rowtext = _o; GRID.DataManager.setData(rowtext, function(_t, _m, _p, _a, pageSum) { GRID.URL_Manager.setBaseUrl(_p.baseUrls); for (var i = 0; i < _a.length; i++) { _a[i].setServer(GRID.App.baseUrls.url); } GRID.Data.title = _t; GRID.Data.memo = _m; GRID.Data.list = _a; GRID.Data.pageSum = pageSum; GRID.Data.gloupSum = GRID.Data.list.length + 1; // document.title = GRID.Data.title; }); var u = 'grid_body.html?r=' + Math.round(Math.random() * 10000000); var tag = '<iframe id="SubFrame" class="" src="' + u + '" ></iframe>'; $('#GridView').html(tag); GRID.V.mainFrame = $('#SubFrame'); GRID.V.subStage = document.getElementById('SubFrame').contentWindow; GRID.V.subStage.onload = function() { createLayout() }; } var subPreviews; function createLayout() { GRID.V.subStage.setParent(this); GRID.V.subPreviews = GRID.V.subStage.getMainController(); setState(); GRID.GridView.init(); GRID.ListView .init(); GRID.V.subPreviews .setGloups(GRID.Data.list); GRID.ListView .setGloups(GRID.Data.list); GRID.ViewSelectView .init(); GRID.TabListView .init(); GRID.SettingEditView .init(); GRID.SettingEditView .setData(rowtext); GRID.SlideController .init(); GRID.SlideController .setGloups(GRID.Data.list); GRID.RevalView .init(); GRID.ScrollView .init(); GRID.FloatPanelView .init(); GRID.StateRectsView .init(); GRID.PreviewViewHeader .init(); GRID.PreviewView .init(); GRID.SplitViewController.init(); GRID.SplitViewController.update(); subPreviews = GRID.V.subPreviews; setEvent(); initGloup(); update(); selectViewType(); setTimeout(function() { openPreview(); },100); } var stopEventKeyList = [ /*32, 37,38,39,40,41,42, 49,50,51, 96,97, 101,103,104, 107, 109*/ 38, 40 ]; function setEvent() { $('body').bind('keydown', function(event) { if (GRID.SettingEditView.isOpen_())return; if (GRID.RevalView.isOpen_())return; keyUp_(event); var c = event.keyCode; var b = false; for (var i = 0; i < stopEventKeyList.length; i++) { if (c == stopEventKeyList[i]) b = true; } if (b) { event.stopPropagation(); event.preventDefault(); } }); $(window).resize(function() { updateStageHeight(); }); }; function keyUp_(_key) { var tar = GRID.FloatPanelView; var c = _key.keyCode; //if(c == 32) openNextGloup(); if (c == 37) openPrevGloup(); if (c == 38) slidePrev(); if (c == 39) openNextGloup(); if (c == 40) slideNext(); $('#LogView').html(c); } /* ! ---------- 更新 ---------- ---------- ---------- ---------- */ //なにかしら更新があったら呼ばれる function update() { setState(); GRID.V.subPreviews.update(); GRID.FloatPanelView.updated(); GRID.SlideController.updated(); updateStageHeight(); } function updateReval() { GRID.V.subPreviews.updateReval(); } //ステートをiframeに伝える function setState() { GRID.StateSetManager.update(); GRID.V.subPreviews.setState( GRID.StateSetManager.getState(), GRID.StateReval, GRID.App ); } function callCommand(_c, _a) { GRID.V.subPreviews.callCommand(_c, _a); } /* ! ---------- 高さやスクロールなど ---------- ---------- ---------- ---------- */ //iFrameの高さを設定する var stageHeight = 0; function updateStageHeight() { var state = GRID.StateSetManager.getState(); var stageH = GRID.V.subStage.getScrollH() * state.scale/100; stageH += 100; var wH = $(window).height(); if (wH > stageH) stageH = wH; stageHeight = stageH; GRID.V.mainFrame.height(stageH); } //画面全体のスクロール function setScroll(_abs, _n) { var tarY = 0; if (_abs == 'abs') { tarY = _n; } else { tarY = bodyElement().scrollTop() + _n; } bodyElement().animate({ scrollTop: tarY },{ duration: 200, ease: 'swing' }); GRID.V.subStage.scrollTo_('abs', 0); } //個別フレームごとのスクロール function setScroll_grid(_abs, _n) { GRID.V.subPreviews.setScroll(_abs, _n); } function resetScroll() { setScroll('abs', 0); setScroll_grid('abs', 0); } /* ! ---------- タブを開く ---------- ---------- ---------- ---------- */ function openGloup(_n) { if (_n == null) { _n = GRID.StateCommon.currentGloup; } gloupLotation.setN(_n); GRID.StateCommonManager.setCurrentGloup(_n); GRID.StateCommonManager.setPreviewNo(-1); GRID.TabListView.openGloup(_n); subPreviews.openGloup(_n); update(); slideReset(); resetScroll(); } var gloupLotation; function initGloup() { gloupLotation = new Lib_.Type_.RotationInt(0, [0, GRID.Data.gloupSum - 1]); } function isPreview() { return (GRID.StateCommon.viewType == 'preview'); } function openPrevGloup() { if (!isPreview())return; gloupLotation.add_(-1); openGloup(gloupLotation.getN()); } function openNextGloup() { if (!isPreview())return; gloupLotation.add_(1); openGloup(gloupLotation.getN()); } /* ! ---------- スライドショー ---------- ---------- ---------- ---------- */ function slideReset() { } function slidePrev() { GRID.SlideController.slidePrev(); } function slideNext() { GRID.SlideController.slideNext(); } /* ! ---------- ---------- ---------- ---------- ---------- */ function openPreview(_u, _n) { var _state = GRID.StateCommon; if (_u == null) { _u = _state.preview.url; } else { GRID.StateCommonManager.setPreviewUrl(_u); } if (_n != null) { GRID.StateCommonManager.setPreviewNo(_n); } if (_state.preview.url == '')return; GRID.PreviewViewHeader.openPreview(); GRID.SlideController.updated(); subPreviews.selectPage(_state.preview.url); GRID.ListView.selectPage(_state.preview.url); } /* function updatePreview(_u) { GRID.PreviewViewHeader.updatePreview(_u); }*/ /* ! ---------- ---------- ---------- ---------- ---------- */ function selectViewType(_s) { var _state = GRID.StateCommon; if (_s == null) { _s = _state.viewType; } else { GRID.StateCommonManager.setViewType(_s) } GRID.StateSetManager.update(); GRID.ListView .stageOut(); GRID.GridView .stageOut(); GRID.SettingEditView .stageOut(); GRID.ScrollView .stageOut(); GRID.FloatPanelView .stageOut(); GRID.TabListView .stageOut(); GRID.RevalView .stageOut(); GRID.StateRectsView .stageOut(); if (_state.viewType == 'list') { GRID.ListView.stageIn(); } if (_state.viewType == 'preview') { GRID.GridView .stageIn(); GRID.ScrollView .stageIn(); GRID.FloatPanelView .stageIn(); GRID.TabListView .stageIn(); GRID.RevalView .stageIn(); GRID.StateRectsView .stageIn(); } // if (_state.viewType == 'edit') { // GRID.SettingEditView.stageIn(); // } GRID.ViewSelectView.update(); } /* ! ---------- ---------- ---------- ---------- ---------- */ function openServer(_s) { window.location.hash = _s; window.location.reload(); } /* ! ---------- ---------- ---------- ---------- ---------- */ return { init: init, keyUp_: keyUp_, update: update, updateReval: updateReval, callCommand: callCommand, setScroll: setScroll, setScroll_grid: setScroll_grid, openGloup: openGloup, slideReset: slideReset, slidePrev: slidePrev, slideNext: slideNext, openPreview: openPreview, //updatePreview:updatePreview, selectViewType: selectViewType, openServer: openServer }; })(); GRID.ViewSelectView = (function() { var view; var v = {}; function init() { view = $('#ViewSelectView'); //stageInit(); createlayout(); setBtn(); } /* ---------- ---------- ---------- */ function setBtn() { v._btn_list = view.find('._btn_list'); v._btn_preview = view.find('._btn_preview'); v._btn_list.click(function() {selectViewType('list')}); v._btn_preview.click(function() {selectViewType('preview')}); setServers(); } function setServers() { var ss = GRID.App.baseUrls.items; var tag = ''; for (var i = 0; i < ss.length; i++) { tag += '<div class="item" data-no="' + i + '"><i class="fa fa-globe" ></i> ' + ss[i] + '</div>'; } } function selectViewType(_s) { GRID.MainController.selectViewType(_s); } function createlayout() { } function update() { v._btn_list.removeClass('active'); v._btn_preview.removeClass('active'); if (GRID.StateCommon.viewType == 'list') { v._btn_list.addClass('active'); } if (GRID.StateCommon.viewType == 'preview') { v._btn_preview.addClass('active'); } } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit() { view.hide(); } function stageIn() { if (! isOpen) { isOpen = true; view.fadeIn(500); if (isFirst) {} isFirst = false; } } function stageOut() { if (isOpen) { isOpen = false; view.fadeOut(200); } } return { init: init, stageIn: stageIn, stageOut: stageOut, update: update }; })(); GRID.GridView = (function() { var view; var v = {}; function init() { view = $('#GridView'); stageInit(); setBtn(); } /* ---------- ---------- ---------- */ function setBtn() { } function createlayout() { GRID.MainController.openGloup(); } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit() { view.hide(); } function stageIn() { if (! isOpen) { isOpen = true; view.show(); if (isFirst) { createlayout(); } isFirst = false; } } function stageOut() { if (isOpen) { isOpen = false; view.hide(); GRID.FloatPanelView.stageOut(); GRID.TabListView.stageOut(); } } return { init: init, stageIn: stageIn, stageOut: stageOut }; })(); GRID.ListView = (function() { var view; var v = {}; var stateCom; function init() { stateCom = GRID.StateCommon; view = $('#ListView'); v.inner = view.find('.inner'); stageInit(); createlayout(); setBtn(); } /* ---------- ---------- ---------- */ function setGloups(_data) { var cnt = 0; var gloups = []; var temp = ''; //header var tag = ''; // tag += '<div class="h1">' + GRID.Data.title + '</div>'; if (GRID.App.baseUrls.url != '') { var base = GRID.App.baseUrls.url; tag += '<div class="base">__BASE_URL__ : <a href="' + base + '" target="_blank">' + base + ' <i class=" fa fa-external-link-square "></i> </a></div>'; } tag += '<div class="header"> '; tag += ' <div class="searchArea" style="float:right"> '; tag += ' 絞り込み : <input class="in_search" >'; tag += ' <span class="_btn btn_search_hide_on"><i class=" fa fa-square-o "></i> 非表示</span> '; tag += ' <span class="_btn btn_search_hide_off"><i class=" fa fa-check-square "></i> 非表示</span> '; tag += ' </div>'; tag += ' <div class="h2">データリスト</div>'; tag += '</div>'; //body tag += '<table>'; tag += '<tr>'; tag += '<td></td>'; tag += '<td></td>'; tag += '<td></td>'; tag += '<td></td>'; tag += '<td>' tag += ' <table class="mylist">'; tag += ' <tr>'; var tabs = GRID_MY_TAB; for (var i = 0; i < tabs.length ; i++) { tag += ' <td>'+tabs[i]+'</td>'; } tag += ' </tr>'; tag += ' </table>'; tag += '</td>'; tag += '</tr>'; var pageCount = 0; //var ids = [] for (var i = 0; i < _data.length; i++) { var gl = _data[i]; if(!gl.isMemori){ tag += '<tr>'; tag += '<td class="gloup" colspan="5">' + gl.name + '</td>'; tag += '</tr>'; for (var ii = 0; ii < gl.list.length; ii++) { var pageData = gl.list[ii]; if(pageData.type == "sub-gloup"){ var temp = ''; temp += '<tr>'; temp += '<td></td>'; temp += '<td class="sub-gloup" colspan="4">' + pageData.name + '</td>'; temp += '</tr>'; temp += '</tr>'; tag += temp; } else{ var temp = ''; temp += '<tr id="' + pageData.id + '" class="pageItem">'; temp += '<td class="no"></td>'; temp += '<td class="name"></td>'; temp += '<td class="date"></td>'; temp += '<td class="url"></td>'; temp += '<td class="checks"></td>'; temp += '</tr>'; tag += temp; } } } } tag += '<tr>'; tag += ' <td></td>'; tag += ' <td></td>'; tag += ' <td></td>'; tag += ' <td></td>'; tag += ' <td><div class="_btn btn_setMemori">保存・リロード</div></td>'; tag += '</tr>'; tag += '</table>'; tag += '<textarea id="listData" style="display:none;width:500px;height:200px;"></textarea>'; tag += ''; //footer // tag += '<div class="h2">メモ</div>'; // tag += '<div class="memo">' + GRID.Data.memo + '</div>'; v.inner.html(tag); v.pageItem = view.find('.pageItem'); v.pageItem.each(function(index, dom) { var p = new GRID.ListViewPage(dom); pages.push(p); }); initSearch(); initCheck(); } var pages = []; function setBtn() { } function createlayout() { } /* ! ---------- ---------- ---------- ---------- ---------- */ function initCheck() { v.in_checks = v.inner.find("input"); v.btn_setMemori = view.find('.btn_setMemori'); v.btn_setMemori.click(function(){ setListMemori() }); var myList = GRID.StatePageManager.getListData(); for (var i = 0; i < myList.length ; i++) { for (var ii = 0; ii < myList[i].length ; ii++) { var id = myList[i][ii][0]; v.inner.find('[data-id="'+id+'"]').eq(i).prop("checked",true); } } } function setListMemori() { var leng = v.in_checks.size(); var checks = [[],[],[],[],[]] for (var i = 0; i < leng ; i++) { var tar = v.in_checks.eq(i) if(tar.prop("checked")){ var id = tar.data("id"); var name = tar.data("name"); var no = tar.data("no"); checks[no].push([id,name]) } } $("#listData").val(JSON.stringify(checks, null, " ")); GRID.StatePageManager.setListData(checks); setTimeout(function(){ window.location.reload(); },200); } /* ! ---------- ---------- ---------- ---------- ---------- */ function selectPage(_u) { for (var i = 0; i < pages.length; i++) { pages[i].selectPage(_u); } } /* ! ---------- ---------- ---------- ---------- ---------- */ //search function initSearch() { v.in_search = view.find('.in_search'); v.in_search.keyup(function() { search($(this).val()); }); v.btn_search_hide_on = view.find('.btn_search_hide_on'); v.btn_search_hide_off = view.find('.btn_search_hide_off'); v.btn_search_hide_on.click(function() { searchMath_is_hide(true)}); v.btn_search_hide_off.click(function() { searchMath_is_hide(false)}); if (stateCom.search.list.isHide) { searchMath_is_hide(true); } else { searchMath_is_hide(false); } var ser = stateCom.search.list.text; if (ser != '') { v.in_search.val(ser); v.in_search.keyup(); } } function searchMath_is_hide(_b) { if (_b) { v.btn_search_hide_on.hide(); v.btn_search_hide_off.show(); view.addClass('hide_matched'); } else { v.btn_search_hide_on.show(); v.btn_search_hide_off.hide(); view.removeClass('hide_matched'); } // stateCom.search.list.isHide = _b; GRID.StateCommonManager.update(); } var prevSearchText = ''; var searchTID; function search(_s) { if (prevSearchText == _s)return; prevSearchText = _s; if (searchTID != null)clearTimeout(searchTID); searchTID = setTimeout(function() { search_core(_s); },200); // stateCom.search.list.text = prevSearchText; GRID.StateCommonManager.update(); } function search_core(_s) { for (var i = 0; i < pages.length; i++) { pages[i].search(_s); } } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit() { view.hide(); } function stageIn() { if (! isOpen) { isOpen = true; view.show(); if (isFirst) {} isFirst = false; } } function stageOut() { if (isOpen) { isOpen = false; view.hide(); } } return { init: init, stageIn: stageIn, stageOut: stageOut, setGloups: setGloups, selectPage: selectPage, search: search }; })(); GRID.ListViewPage = (function() { /* ---------- ---------- ---------- */ var c = function(_dom) { this.init(_dom); }; var p = c.prototype; /* ---------- ---------- ---------- */ p.view; p.v; p.data; p.init = function(_dom) { this.view = $(_dom); this.id = this.view.attr('id'); this.v = {}; this.data = GRID.M.PageDataManager.getData_by_id(this.id); var a_tag = '<a href="{URL}" target="_blank">{URL_V} <i class=" fa fa-external-link-square "></i></a>'; a_tag = a_tag.split('{URL}').join(this.data.url); a_tag = a_tag.split('{URL_V}').join(this.data.url_and_base); this.v.tds = this.view.find('td'); this.v.no = this.v.tds.eq(0); this.v.name = this.v.tds.eq(1); this.v.date = this.v.tds.eq(2); this.v.url = this.v.tds.eq(3); this.v.checks = this.v.tds.eq(4); var __ = (function(_deep){ var s = "" for (var i = 0; i < _deep ; i++) { s += '<span class="wide"> </span>' } return s; })(this.data.deep); this.v.no.html(this.data.no); this.v.name.html(__ + this.data.listTexts.name); this.v.url.html(this.data.listTexts.url); var uu = this.data.url_origin var tabs = GRID_MY_TAB; var tag = "" tag += '<div>' for (var i = 0; i < tabs.length ; i++) { tag += ' <input type="checkbox" data-no="'+i+'" data-id="' + uu + '" data-name="' + this.data.name + '">' } tag += '</div>' this.v.checks.html(tag); // } this.setBtn(); }; p.setBtn = function() { var this_ = this; this.v.name.click(function() { GRID.MainController.openPreview(this_.data.url, this_.data.no - 1); }); }; /* ---------- ---------- ---------- */ /* p.upadteLastModified = function() { if (!this.isAccesable)return; var this_ = this; $.ajax({ scriptCharset: 'utf-8', type: 'GET', url: this.data.url, dataType: 'text', success: function(data, status, xhr) { var d = new Date(xhr.getResponseHeader('Last-Modified')); var s = DateUtil.getRelatedDate(d); var ss = ''; ss += '<i class="date_icon fa fa-clock-o"></i> '; ss += s; this_.v.date.html(ss); } }); }; */ /* ---------- ---------- ---------- */ p.selectPage = function(_u) { if (this.data.url == _u) { this.view.addClass('selected'); } else { this.view.removeClass('selected'); } }; p.search = function(_s) { var b = this.data.isMatch(_s); if (_s == '') b = false; if (b) { this.data.isMatchSearch(true); this.setMatchedText(_s); } else { this.setDefaultText(); if (_s == '') { this.data.isMatchSearch(true); this.view.removeClass('notMatchSearch'); } else { this.data.isMatchSearch(false); this.view.addClass('notMatchSearch'); } } }; p.isDefText; p.setMatchedText = function(_s) { this.isDefText = false; this.v.name.html(this.data.getMatchText_name(_s)); this.v.url.html(this.data.getMatchText_url(_s)); this.view.removeClass('notMatch'); }; p.setDefaultText = function() { if (this.isDefText == null) this.isDefText = false; if (this.isDefText)return; this.isDefText = true; this.v.name.html(this.data.listTexts.name); this.v.url.html(this.data.listTexts.url); }; return c; })(); GRID.SettingEditView = (function() { var view; var v = {}; function init() { view = $('#SettingEditView'); v.textarea = view.find('textarea'); v.btn_save = view.find('.btn_save'); //v.btn_close = view.find(".btn_close"); stageInit(); createlayout(); setBtn(); } /* ---------- ---------- ---------- */ function setBtn() { v.btn_save.click(function() { save(); }); /*v.btn_close.click(function(){ stageOut(); });*/ } function save() { // var param = {}; // param.action = 'write'; // param.dir_name = GRID.Data.saveDir_php; // param.file_name = GRID.Data.fileName; // param.text = v.textarea.val(); // GRID.API.saveFile(param, function() { // save_comp(); // }); } function save_comp() { window.location.reload(); } function createlayout() { } function setData(_t) { v.textarea.val(_t); } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit() { view.hide(); } function stageIn() { if (! isOpen) { isOpen = true; view.show(); if (isFirst) {} isFirst = false; } } function stageOut() { if (isOpen) { isOpen = false; view.hide(); } } function isOpen_() { return isOpen; } return { init: init, stageIn: stageIn, stageOut: stageOut, setData: setData, isOpen_: isOpen_ }; })(); GRID.SlideController = (function() { var view; var v = {}; function init() { v.listView = GRID.Slide_at_List; v.previewView = GRID.Slide_at_Preview; v.listView.init(); v.previewView.init(); } function setGloups(_data) { v.previewView.setGloups(_data); } function isList() { return (GRID.StateCommon.viewType == 'list'); } function updated() { //if(isList){ v.listView.updated(); //} else{ v.previewView.updated(); //} } function selectPage(_n) { if (isList()) { v.listView.selectPage(_n); } else { v.previewView.selectPage(_n); } } function slideReset() { if (isList()) { v.listView.slideReset(); } else { v.previewView.slideReset(); } } function slidePrev() { if (isList()) { v.listView.slidePrev(); } else { v.previewView.slidePrev(); } } function slideNext() { if (isList()) { v.listView.slideNext(); } else { v.previewView.slideNext(); } } return { init: init, setGloups: setGloups, updated: updated, selectPage: selectPage, slidePrev: slidePrev, slideNext: slideNext }; })(); GRID.Slide_at_List = (function() { var view; var v = {}; var cnt; var rotationInt; var _state; function init() { _state = GRID.StateCommon; cnt = GRID.Data.pageSum; rotationInt = new Lib_.Type_.RotationInt(0, [0, cnt - 1]); createlayout(); setBtn(); } /* ---------- ---------- ---------- */ function setBtn() { } /* ---------- ---------- ---------- */ function setGloups() { } /* ---------- ---------- ---------- */ function updated() { } function slideReset() { } function slidePrev() { if (_state.preview.no == -1) { rotationInt.setN(0); rotationInt.add_(-1); } else { rotationInt.setN(_state.preview.no); rotationInt.add_(-1); } //for search if (isSelecttablePage(rotationInt.getN())) { selectPage(rotationInt.getN()); } else { _state.preview.no--; if (_state.preview.no <= 0) _state.preview.no = cnt - 1; slidePrev(); } } function slideNext() { if (_state.preview.no == -1) { rotationInt.setN(0); } else { rotationInt.setN(_state.preview.no); rotationInt.add_(1); } //for search if (isSelecttablePage(rotationInt.getN())) { selectPage(rotationInt.getN()); } else { _state.preview.no++; if (_state.preview.no >= cnt) _state.preview.no = 0; slideNext(); } } /* ! ---------- ---------- ---------- ---------- ---------- */ function createlayout() { } function isSelecttablePage(_n) { return frames[_n].isSelectable(); } function selectPage(_n) { var d = frames[_n].url; GRID.MainController.openPreview(d, _n); } return { init: init, setGloups: setGloups, selectPage: selectPage, slidePrev: slidePrev, slideNext: slideNext, updated: updated }; })(); GRID.Slide_at_Preview = (function() { var view; var v = {}; var _state function init() { _state = GRID.StateCommon view = $('#Slide_at_Preview'); stageInit(); stageIn(); createlayout(); setBtn(); } /* ---------- ---------- ---------- */ function setBtn() { v.btn_prev = view.find('.btn_prev'); v.btn_next = view.find('.btn_next'); v.pagenation = view.find('.pagenation'); v.btn_prev.click(function() { slidePrev();}); v.btn_next.click(function() { slideNext();}); v.pagenation.html(''); } /* ---------- ---------- ---------- */ var gloups = []; var rotationInt; var isAll; function setGloups(_data) { for (var i = 0; i < _data.length; i++) { var g = new GRID.Slide_at_P_Gloup(_data[i]); gloups.push(g); } var cnt = GRID.Data.pageSum; rotationInt = new Lib_.Type_.RotationInt(0, [0, cnt - 1]); } /* ---------- ---------- ---------- */ var currentGroup = -1; function updated() { if (currentGroup != _state.currentGloup) { currentGroup = _state.currentGloup; slideReset(); } else { setCurrentPage(); } } var pageMax = 0; function updatePageMax() { if (isAll) { pageMax = frames.length; } else { pageMax = gloups[currentGroup].pages.length; } v.pagenation.html(pageMax + ' page'); } function setCurrentPage() { v.pagenation.html(_state.preview.no + 1 + ' / ' + pageMax); } function slideReset() { isAll = (gloups.length == currentGroup) ? true : false; isSlideModeFirst = true; rotationInt.setN(0); for (var i = 0; i < gloups.length; i++) { gloups[i].slideReset(); } updatePageMax(); } function slidePrev() { if (isAll) { slidePrevWhenALl(); } else { gloups[currentGroup].slidePrev(); } } function slideNext() { if (isAll) { slideNextWhenALl(); } else { gloups[currentGroup].slideNext(); } } /* ! ---------- ---------- ---------- ---------- ---------- */ function slidePrevWhenALl() { if (_state.preview.no == -1) { rotationInt.setN(0); rotationInt.add_(-1); } else { rotationInt.setN(_state.preview.no); rotationInt.add_(-1); } slideWhenALl(rotationInt.getN()); } function slideNextWhenALl() { if (_state.preview.no == -1) { rotationInt.setN(0); } else { rotationInt.setN(_state.preview.no); rotationInt.add_(1); } slideWhenALl(rotationInt.getN()); } function slideWhenALl(_n) { selectPageAll(_n); } /* ! ---------- ---------- ---------- ---------- ---------- */ function createlayout() { } function selectPage(_n) { var d = gloups[GRID.StateCommon.currentGloup].pages[_n].url; GRID.MainController.openPreview(d, _n); } function selectPageAll(_n) { var d = frames[_n].url; GRID.MainController.openPreview(d, _n); } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit() { view.hide(); } function stageIn() { if (! isOpen) { isOpen = true; view.fadeIn(500); if (isFirst) {} isFirst = false; } } function stageOut() { if (isOpen) { isOpen = false; view.fadeOut(200); } } return { init: init, stageIn: stageIn, stageOut: stageOut, setGloups: setGloups, selectPage: selectPage, slidePrev: slidePrev, slideNext: slideNext, updated: updated }; })(); GRID.Slide_at_P_Gloup = (function() { var c = function(_data) { this.init(_data); }; var p = c.prototype; /* ---------- ---------- ---------- */ var GLOUP_NO = 0; p.parentView; p.pages; p.init = function(_data) { this.data = _data; this.createLayout_pre(); }; p.createLayout_pre = function() { this.pages = []; var list = this.data.list; for (var ii = 0; ii < list.length; ii++) { var o = list[ii]; //page if (o.type == 'page') { frames.push(o); this.pages.push(o); } } this.pageCount = this.pages.length; this.rotationInt = new Lib_.Type_.RotationInt(0, [0, this.pageCount - 1]); }; p.slideReset = function() { if (this.pages == null) return; this.rotationInt.setN(0); this.isSlideModeFirst = true; }; p.slidePrev = function() { if (GRID.StateCommon.preview.no == -1) { this.rotationInt.setN(0); this.rotationInt.add_(-1); } else { this.rotationInt.setN(GRID.StateCommon.preview.no); this.rotationInt.add_(-1); } this.slide(this.rotationInt.getN()); }; p.isSlideModeFirst; p.slideNext = function() { if (GRID.StateCommon.preview.no == -1) { this.rotationInt.setN(0); } else { this.rotationInt.setN(GRID.StateCommon.preview.no); this.rotationInt.add_(1); } this.slide(this.rotationInt.getN()); }; p.slide = function(_n) { GRID.SlideController.selectPage(_n); }; return c; })(); GRID.TabListView = (function() { var view; var v = {}; function init() { view = $('#TabListView'); stageInit(); createlayout(); setBtn(); stageIn(); } /* ---------- ---------- ---------- */ function setBtn() {} var count = 0; function createlayout() { view.html('<div class="core"></div>'); v.core = view.find('.core'); var tabs = GRID_MY_TAB; var gs = GRID.Data.list; var tag = ''; tag += '<ul>'; // if (gs.length > 1) { for (var i = 0; i < gs.length; i++) { var b = false var cs = []; if(gs[i].list.length == 0){ cs.push("noData") } var t = "" if(gs[i].name == tabs[0]){ if(gs[i].isMemori){ t = '<li style="margin-left:10px;" class="{CS}">' + gs[i].name + '</li>'; b = true; } } if(!b){ t = '<li class="{CS}">' + gs[i].name + '</li>'; } t = t.split("{CS}").join(cs.join(" ")); tag += t; } // } tag += '<li style="margin-left:10px;">すべて表示</li>'; tag += '</ul>'; v.core.html(tag); v.btns = v.core.find('li'); v.btns.each(function(index, domEle) { $(this).click(function() { GRID.MainController.openGloup(index); }); }); count = v.btns.size(); } function openGloup(_n) { var all = count - 1; if (_n == all) { for (var i = 0; i < count; i++) { v.btns.eq(i).removeClass('active'); } v.btns.eq(all).addClass('active'); } else { for (var i = 0; i < count; i++) { v.btns.eq(i).removeClass('active'); } v.btns.eq(_n).addClass('active'); v.btns.eq(all).removeClass('active'); } } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit() { view.hide(); } function stageIn() { if (! isOpen) { isOpen = true; view.show(); if (isFirst) {} isFirst = false; } } function stageOut() { if (isOpen) { isOpen = false; view.hide(); } } return { init: init, stageIn: stageIn, stageOut: stageOut, openGloup: openGloup }; })(); GRID.RevalView = (function() { var view; var v = {}; var revalState; function init() { revalState = GRID.StateReval; view = $('#RevalView'); createlayout(); setBtn(); setBtn2(); stageInit(); } function createlayout() { } /* ---------- ---------- ---------- */ function setBtn() { v.t1 = view.find('input.t1'); v.t1.keyup(function() { changeText_pre() }); v.t1.focus(function() { focus_() }); v.t1.blur(function() { blur_() }); v.t2 = view.find('input.t2'); v.t2.keyup(function() { changeText2_pre() }); v.t2.focus(function() { focus_() }); v.t2.blur(function() { blur_() }); initHover(); } /* ---------- ---------- ---------- */ function initHover() { view.hover( function(){ hoverIn(); },function(){ hoverOut(); } ); } var tID; function hoverIn(){ if(tID) clearTimeout(tID); view.addClass('hover') } function hoverOut(){ tID = setTimeout(function(){ view.removeClass('hover') },1000); } /* ---------- ---------- ---------- */ var tId; function changeText_pre() { if (tId) clearTimeout(tId); tId = setTimeout(function() { changeText() },200); } function changeText() { revalState.text = v.t1.val(); update(); } function changeText2_pre() { if (tId) clearTimeout(tId); tId = setTimeout(function() { changeText2() },200); } function changeText2() { revalState.jq = v.t2.val(); update(); } /* ---------- ---------- ---------- */ function setBtn2() { v.t2 = view.find('input.t2'); v.t2.keyup(function() { changeText2_pre() }); v.reval_hide = view.find('.reval_hide'); v.reval_iso = view.find('.reval_iso'); v.reval_line = view.find('.reval_line'); v.reval_bk = view.find('.reval_bk'); v.reval_show = view.find('.reval_show'); v.reval_link = view.find('.reval_link'); v.reval_img = view.find('.reval_img'); v.reval_hide .change(function() {changeReval_Hide()}); v.reval_iso .change(function() {changeReval_Iso()}); v.reval_line .change(function() {changeReval_Line()}); v.reval_bk .change(function() {changeReval_BK()}); v.reval_show .change(function() {changeReval_show()}); v.reval_link .change(function() {changeReval_Link()}); v.reval_img .change(function() {changeReval_Img()}); } function changeReval_Hide() { revalState.isHide = v.reval_hide.prop('checked'); update(); } function changeReval_Iso() { revalState.isIso = v.reval_iso.prop('checked'); update(); } function changeReval_Line() { revalState.isLine = v.reval_line.prop('checked'); update(); } function changeReval_BK() { revalState.isBK = v.reval_bk.prop('checked'); update(); } function changeReval_show() { revalState.showSelector =v.reval_show.prop('checked'); update(); } function changeReval_Link() { revalState.showLink = v.reval_link.prop('checked'); update(); } function changeReval_Img() { revalState.showImg = v.reval_img.prop('checked'); update(); } function update() { GRID.MainController.updateReval(); } function updated() { } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit() { view.hide(); } function stageIn() { if (! isOpen) { isOpen = true; if (isFirst) {} isFirst = false; view.show(); } } function stageOut() { if (isOpen) { isOpen = false; view.hide(); } } /* ---------- ---------- ---------- */ var focus = false; function focus_() { focus = true; } function blur_() { focus = false; } function isOpen_() { return focus; } return { init: init, stageIn: stageIn, stageOut: stageOut, isOpen_: isOpen_ }; })(); GRID.FloatPanelView = (function() { var view; var v = {}; var current; function init() { current = GRID.StateSetManager.getState(); view = $('#FloatPanelView'); createlayout(); setBtn(); } /* ---------- ---------- ---------- */ function setBtn() { v.b_zoom_100 = view.find('.b_zoom_100'); v.b_zoom_50 = view.find('.b_zoom_50'); v.b_zoom_33 = view.find('.b_zoom_33'); v.b_zoom_25 = view.find('.b_zoom_25'); v.b_zoom_15 = view.find('.b_zoom_15'); v.b_zoom_up = view.find('.b_zoom_up'); v.b_zoom_down = view.find('.b_zoom_down'); v.b_misc_01 = view.find('.b_misc_01'); v.b_misc_01_ng = view.find('.b_misc_01_ng'); v.b_misc_02 = view.find('.b_misc_02'); v.b_misc_02_ng = view.find('.b_misc_02_ng'); v.b_mar_left = view.find('.b_mar_left'); v.b_mar_right = view.find('.b_mar_right'); v.b_h_up = view.find('.b_h_up'); v.b_h_down = view.find('.b_h_down'); v.b_w_left = view.find('.b_w_left'); v.b_w_right = view.find('.b_w_right'); v.b_w_320 = view.find('.b_w_320'); v.b_w_768 = view.find('.b_w_768'); v.b_w_1024 = view.find('.b_w_1024'); v.b_w_1200 = view.find('.b_w_1200'); v.b_w_2000 = view.find('.b_w_2000'); v.b_w_320_1024 = view.find('.b_w_320-1024'); v.b_h_500 = view.find('.b_h_500'); v.b_h_1000 = view.find('.b_h_1000'); v.b_h_2000 = view.find('.b_h_2000'); v.b_h_3000 = view.find('.b_h_3000'); v.b_h_4000 = view.find('.b_h_4000'); v.b_h_6000 = view.find('.b_h_6000'); v.b_h_16000 = view.find('.b_h_16000'); //v.b_slide_prev = view.find('.b_slide_prev'); //v.b_slide_next = view.find('.b_slide_next'); v.b_bg = view.find('.b_bg'); v.b_col = view.find('.b_col'); v.b_bg_col = view.find('.b_bg_col'); v.b_col_col = view.find('.b_col_col'); v.b_zoom_100 .click(function() { setZoom('abs', 100); }); v.b_zoom_50 .click(function() { setZoom('abs', 50); }); v.b_zoom_33 .click(function() { setZoom('abs', 33.3); }); v.b_zoom_25 .click(function() { setZoom('abs', 25); }); v.b_zoom_15 .click(function() { setZoom('abs', 15); }); v.b_zoom_up .click(function() { setZoom('rel', 10); }); v.b_zoom_down .click(function() { setZoom('rel', -10); }); v.b_misc_01 .click(function() { noBR(); }); v.b_misc_02 .click(function() { noTitle(); }); v.b_misc_01_ng .click(function() { noBR(); }); v.b_misc_02_ng .click(function() { noTitle(); }); v.b_mar_left .click(function() { setMargin('rel', -1); }); v.b_mar_right .click(function() { setMargin('rel', 1); }); v.b_h_up .click(function() { setH('rel', -500); }); v.b_h_down .click(function() { setH('rel', 500); }); v.b_h_500 .click(function() { setH('abs', 500); }); v.b_h_1000 .click(function() { setH('abs', 1000); }); v.b_h_2000 .click(function() { setH('abs', 2000); }); v.b_h_3000 .click(function() { setH('abs', 3000); }); v.b_h_4000 .click(function() { setH('abs', 4000); }); v.b_h_6000 .click(function() { setH('abs', 8000); }); v.b_h_16000 .click(function() { setH('abs', 16000); }); v.b_w_left .click(function() { setW('rel', -100); }); v.b_w_right .click(function() { setW('rel', 100); }); v.b_w_320 .click(function() { setW('abs', [320]); }); v.b_w_768 .click(function() { setW('abs', [768]); }); v.b_w_1024 .click(function() { setW('abs', [1024]); }); v.b_w_1200 .click(function() { setW('abs', [1200]); }); v.b_w_2000 .click(function() { setW('abs', [2000]); }); v.b_w_320_1024 .click(function() { setW('abs', [1024, 320]); }); //v.b_slide_prev .click(function(){ }); //v.b_slide_next .click(function(){ }); v.b_bg .click(function() { setBK(); }); v.b_col .click(function() { setCol(); }); v.b_bg_col .click(function() { setBK(); }); v.b_col_col .click(function() { setCol(); }); v.current_s = view.find('.current_s'); v.current_w = view.find('.current_w'); v.current_h = view.find('.current_h'); v.current_m = view.find('.current_m'); v.current_s .click(function() { setZoom('abs'); }); v.current_w .click(function() { setW('abs'); }); v.current_h .click(function() { setH('abs'); }); v.current_m .click(function() { setMargin('abs'); }); v.btn_memori_save = view.find('.btn_memori_save'); v.btn_memori_save .click(function() { save() }); v.btn_memori_reset = view.find('.btn_memori_reset'); v.btn_memori_reset .click(function() { reset() }); resetMemoriBtn() initHover(); } /* ! ---------- hover ---------- ---------- ---------- ---------- */ function initHover() { view.hover( function(){ hoverIn(); },function(){ hoverOut(); } ); } var tID; function hoverIn(){ if(tID) clearTimeout(tID); view.addClass('hover') GRID.StateRectsView.hoverIn(); } function hoverOut(){ tID = setTimeout(function(){ view.removeClass('hover') },500); GRID.StateRectsView.hoverOut(); } /* ! ---------- memori ---------- ---------- ---------- ---------- */ function resetMemoriBtn() { v.btn_memori_save.addClass("disable"); } function activeMemoriBtn() { v.btn_memori_save.removeClass("disable"); } function save() { GRID.StateSetManager.save(); resetMemoriBtn(); } function reset() { GRID.StateSetManager.reset(); changeMemoriNo(0); activeMemoriBtn(); } function changeMemoriNo(_n) { current = GRID.StateSetManager.getState(); update(); } /* ! ---------- ---------- ---------- ---------- ---------- */ function createlayout() {} function update() { GRID.MainController.update(); } function update_and_active() { activeMemoriBtn(); GRID.MainController.update(); } function updated() { v.current_s.text(current.scale + '%'); v.current_w.text(current.widths.join(',') + 'px'); v.current_h.text(current.height + 'px'); v.current_m.text(current.margin + 'px'); v.b_bg_col.css('background', current.background); v.b_col_col.css('background', current.color); v.b_misc_01.hide(); v.b_misc_01_ng.hide(); if (current.noBR) { v.b_misc_01_ng.show(); } else { v.b_misc_01.show(); } // v.b_misc_02.hide(); v.b_misc_02_ng.hide(); if (current.noTitle) { v.b_misc_02_ng.show(); } else { v.b_misc_02.show(); } $("#StateMemoriView .inner").width(current.scale*10); $("#StateMemoriView .inner span").html("1,000px ("+current.scale + "%)"); GRID.StateRectsView.update() } /* ---------- ---------- ---------- */ function setZoom(_abs, _n) { var n = getInputNumber(_abs, _n, current.scale); if (n == null) return; current.scale = setLimitNumber(n, [10, 100]); update_and_active(); } function setW(_abs, _a) { var a; if (_abs == 'abs') { if (_a == null) { var p = prompt('', current.widths.join(',')); a = p.split(','); for (var i = 0; i < a.length; i++) { if (isNaN(Number(a[i]))) return; a[i] = Number(a[i]); } } else { a = _a; } } else { a = current.widths; /*for (var i = 0; i < a.length ; i++) { a[i] += _a }*/ a[0] += _a; } var ws = 0; for (var i = 0; i < a.length; i++) { a[i] = setLimitNumber(a[i], [100, 5000]); ws += a[i]; } current.pagesW = ws; current.widths = a; update_and_active(); } function setH(_abs, _n) { if (_abs == 'fit') { current.height = 'fit'; } else if (_abs == 'abs') { var n = getInputNumber(_abs, _n, current.height); if (n == null) return; //current.pagesH = _n; current.height = n; } else { current.height += _n; } current.height = setLimitNumber(current.height, [100, 99999]); update_and_active(); } function setMargin(_abs, _n) { var n = getInputNumber(_abs, _n, current.margin); //current.margin = setLimitNumber(n,[0,10]); current.margin = n; update_and_active(); } function setBK(_s) { var s; if (_s == null) { s = prompt('', current.background); if (s == undefined) return; } else { s = _s; } current.background = s; update_and_active(); } function setCol(_s) { var s; if (_s == null) { s = prompt('', current.color); if (s == undefined) return; } else { s = _s; } current.color = s; update_and_active(); } function setScroll(_abs, _n) { var s; if (_n == null) { s = Number(prompt('', 0)); } else { s = _n; } if (s == undefined) return; GRID.MainController.setScroll_grid(_abs, s); } function noBR() { current.noBR = (current.noBR) ? false : true; update_and_active(); } function noTitle() { current.noTitle = (current.noTitle) ? false : true; update_and_active(); } function setBK(_s) { var s; if (_s == null) { s = prompt('', current.background); if (s == undefined) return; } else { s = _s; } current.background = s; update_and_active(); } function setCol(_s) { var s; if (_s == null) { s = prompt('', current.color); if (s == undefined) return; } else { s = _s; } current.color = s; update_and_active(); } /* ! ---------- ---------- ---------- ---------- ---------- */ function callCommand(_c, _a) { GRID.MainController.callCommand(_c, _a); } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit() { view.hide(); } function stageIn() { if (!isOpen) { isOpen = true; view.show(); if (isFirst) {} isFirst = false; } } function stageOut() { if (isOpen) { isOpen = false; view.hide(); } } return { init: init, hoverIn: hoverIn, hoverOut: hoverOut, stageIn: stageIn, stageOut: stageOut, updated: updated, setW: setW, setH: setH, setZoom: setZoom, changeMemoriNo: changeMemoriNo }; })(); GRID.ScrollView = (function() { var view; var v = {}; /* ---------- ---------- ---------- */ //初期化 function init(){ view = $('#ScrollView'); stageInit(); createlayout(); } function createlayout(){ v.b_all_sc_top = view.find('.b_all_sc_top'); v.b_all_sc_m500 = view.find('.b_all_sc_m500'); v.b_all_sc_m100 = view.find('.b_all_sc_m100'); v.b_all_sc_100 = view.find('.b_all_sc_100'); v.b_all_sc_500 = view.find('.b_all_sc_500'); v.b_all_sc_bottom = view.find('.b_all_sc_bottom'); v.b_all_sc_top .click(function() { gridScrollTo_('abs', 0); }); v.b_all_sc_m500 .click(function() { gridScrollTo_('rel', -500); }); v.b_all_sc_m100 .click(function() { gridScrollTo_('rel', -100); }); v.b_all_sc_100 .click(function() { gridScrollTo_('rel', 100); }); v.b_all_sc_500 .click(function() { gridScrollTo_('rel', 500); }); v.b_all_sc_bottom .click(function() { gridScrollTo_('abs', 99999); }); // v.b_page_sc_top = view.find('.b_page_sc_top'); // v.b_page_sc_m500 = view.find('.b_page_sc_m500'); // v.b_page_sc_m100 = view.find('.b_page_sc_m100'); // v.b_page_sc_100 = view.find('.b_page_sc_100'); // v.b_page_sc_500 = view.find('.b_page_sc_500'); // v.b_page_sc_bottom = view.find('.b_page_sc_bottom'); // // // v.b_page_sc_top .click(function() { gridScrollTo_('abs', 0); }); // v.b_page_sc_m500 .click(function() { gridScrollTo_('rel', -500); }); // v.b_page_sc_m100 .click(function() { gridScrollTo_('rel', -100); }); // v.b_page_sc_100 .click(function() { gridScrollTo_('rel', 100); }); // v.b_page_sc_500 .click(function() { gridScrollTo_('rel', 500); }); // v.b_page_sc_bottom .click(function() { gridScrollTo_('abs', 99999); }); } /* ! ---------- ---------- ---------- ---------- ---------- */ function scrollTo_(_abs, _n) { GRID.MainController.setScroll(_abs, _n); } function gridScrollTo_(_abs, _n) { GRID.MainController.setScroll_grid(_abs, _n); } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } function stageIn(){ if(! isOpen){ isOpen = true; view.show(); if(isFirst){} isFirst = false; } } function stageOut(){ if(isOpen){ isOpen = false; view.hide(); } } return { init:init, stageIn:stageIn, stageOut:stageOut } })(); GRID.StateRectsView = (function(){ var view; var v = {}; /* ---------- ---------- ---------- */ //初期化 function init(){ view = $("#StateRectsView"); var states = GRID.StateSetManager.getStateSet() var tag = ""; for (var i = 0; i < states.length ; i++) { tag += '<div class="rect" data-id="'+i+'"></div>'; } view.html(tag); v.rect = view.find(".rect") v.rect.click(function(){ var id = Number($(this).data("id")) changeNo(id); }); update(); current = GRID.StateSetManager.getStateNo(); v.rect.eq(current).addClass("current") initHover(); stageInit(); } /* ---------- ---------- ---------- */ function initHover() { view.hover( function(){ hoverIn(); //GRID.FloatPanelView.hoverIn(); },function(){ hoverOut(); //GRID.FloatPanelView.hoverIn(); } ); } var tID; function hoverIn(){ if(tID) clearTimeout(tID); view.addClass('hover') } function hoverOut(){ tID = setTimeout(function(){ view.removeClass('hover') },500); } /* ---------- ---------- ---------- */ //レイアウト作成・イベントアサイン var Z = 25; function update(){ var states = GRID.StateSetManager.getStateSet(); var ww = 0; for (var i = 0; i < states.length ; i++) { var cr = states[i]; var ws = cr.widths; var h = cr.height; var tag = ""; for (var ii = 0; ii < ws.length ; ii++) { var cs = 'width:'+ (ws[ii]/Z) +'px;height:'+ (h/Z) +'px;'; var hh = (cr.scale/100)*5; // console.log(hh); // cs +='border-top: '+hh+'px solid #fff;' tag += '<div class="item" style="'+ cs +'"></div>'; ww += Number(ws[ii])/Z; ww += 5; } tag += '<div class="num">'+ws.join(",")+'px<br>'+cr.scale+'%<div>'; var tar = v.rect.eq(i); tar.html(tag); } view.width(ww+20); } var current = 0 function changeNo(_n){ current = _n; GRID.StateSetManager.changeNo(_n); GRID.FloatPanelView.changeMemoriNo(_n); v.rect.removeClass("current") v.rect.eq(_n).addClass("current") } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit() { view.hide(); } function stageIn() { if (!isOpen) { isOpen = true; view.show(); if (isFirst) {} isFirst = false; } } function stageOut() { if (isOpen) { isOpen = false; view.hide(); } } return { init:init, hoverIn: hoverIn, hoverOut: hoverOut, stageIn: stageIn, stageOut: stageOut, update:update } })(); GRID.SplitViewController = (function() { var view; var v = {}; var _split; function init() { _split = GRID.StateCommon.split; view = $('#SplitViewController'); stageInit(); createlayout(); setBtn(); v.PreviewArea = $('#PreviewArea'); v.MainArea = $('#MainArea'); v.HeaderView = $('#HeaderView'); v.PreviewViewHeader = $('#PreviewViewHeader'); v.PreviewViewHeaderTitle = $('#PreviewViewHeader .title_url'); } /* ---------- ---------- ---------- */ function setBtn() { } function createlayout() { } function setDisplay(_b) { GRID.StateCommonManager.setDisplay(_b); if (_split.display == false) { GRID.StateCommonManager.setPreviewNo(0); GRID.StateCommonManager.setPreviewUrl(""); } update(); } function setW() { var p = prompt('', _split.widths.join(',')); a = p.split(','); for (var i = 0; i < a.length; i++) { if (isNaN(Number(a[i]))) return; a[i] = Number(a[i]); } for (var i = 0; i < a.length; i++) { a[i] = setLimitNumber(a[i], [100, 5000]); } GRID.StateCommonManager.setWidths(a); update(); } function setScale(_s) { var n = getInputNumber('abs', _s, _split.scale); GRID.StateCommonManager.setScale(setLimitNumber(n, [10, 100])); update(); } function update() { GRID.StateSetManager.update(); var b = _split.display; if (b) { v.PreviewArea.show(); v.PreviewViewHeader.show(); var ws = _split.widths.concat([]); var totalW = 0; for (var i = 0; i < ws.length; i++) { ws[i] = ws[i] * (_split.scale / 100); totalW += ws[i]; } //w = setLimitNumber(w,[300,2000]); v.PreviewArea.width(totalW); GRID.PreviewView.setW(ws); v.PreviewViewHeader.width(totalW); v.PreviewViewHeaderTitle.width(totalW - 140); v.MainArea.css('left', totalW + 'px'); v.HeaderView.css('left', totalW + 'px'); } else { v.PreviewArea.hide(); v.PreviewViewHeader.hide(); v.MainArea.css('left', '0px'); v.HeaderView.css('left', '0px'); } GRID.PreviewView.update(); GRID.PreviewViewHeader.update(); } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit() { //view.hide(); } function stageIn() { if (! isOpen) { isOpen = true; if (isFirst) {} isFirst = false; view.show(); } } function stageOut() { if (isOpen) { isOpen = false; view.hide(); } } return { init: init, stageIn: stageIn, stageOut: stageOut, setDisplay: setDisplay, setW: setW, setScale: setScale, update: update }; })(); GRID.PreviewView = (function() { var view; var v = {}; function init() { view = $('#PreviewView'); v.inner = view.find('.inner'); v.btns = view.find('.btns'); iframes = GRID.Data.iframes; createlayout(); setBtn(); } /* ---------- ---------- ---------- */ function setBtn() { } function createlayout() { } var iframes; var iframeDoms = []; var urls = []; function openPage(_u) { var tag = ''; if (! hasData(_u)) { urls.push(_u); var p = new GRID.PreviewViewPage(_u, v.inner); iframes.push(p); } showIFrame(_u); } function reload() { for (var i = 0; i < iframes.length; i++) { iframes[i].reload(); } } function showIFrame(_u) { for (var i = 0; i < iframes.length; i++) { if (iframes[i].url == _u) { iframes[i].stageIn(); } else { iframes[i].stageOut(); } } } function hasData(_s) { var b = false; for (var i = 0; i < urls.length; i++) { if (urls[i] == _s) b = true; } return b; } function setW(_w) { for (var i = 0; i < iframes.length; i++) { iframes[i].setW(_w); } } function update() { for (var i = 0; i < iframes.length; i++) { iframes[i].update(); } } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit() { view.hide(); } function stageIn() { if (! isOpen) { isOpen = true; view.show(); if (isFirst) {} isFirst = false; } } function stageOut() { if (isOpen) { isOpen = false; view.hide(); } } return { init: init, stageIn: stageIn, stageOut: stageOut, openPage: openPage, reload: reload, setW: setW, update: update }; })(); GRID.PreviewViewPage = (function() { /* ---------- ---------- ---------- */ var c = function(_u, _parentView) { this.init(_u, _parentView); }; var p = c.prototype; /* ---------- ---------- ---------- */ p.view; p.parentView; p.v; p.url; p.pages; p.isCreated; p.isAccesable;//iframeにアクセス可能か p.init = function(_u, _parentView) { this.isCreated = false; this.parentView = _parentView; this.url = _u; this.v = {}; this.iframeDoms = []; this.pages = []; this.isAccesable = URL_.isSameDomain(this.url, GRID.App.app.domain); var this_ = this; var id = 'f_'+ Math.round(Math.random() * 10000000); var tag = ''; tag += '<div class="pageSet clearfix" id="set_' + id + '" ></div>'; this.parentView.append(tag); this.view = $('#set_' + id); var ws = [1000]; for (var ii = 0; ii < ws.length; ii++) { this.addPage(ii, ws[ii]); } this.stageInit(); }; p.iframeDoms; p.iframeURL; p.addPage = function(i, w) { this.isCreated = true; var this_ = this; var fID = 'f' + Math.round(Math.random() * 100000000); var temp = ''; temp += '<div class="page">'; temp += '<div class="iframeView"><iframe id="' + fID + '" src="{URL}" frameborder="0" ></iframe></div>'; temp += '</div>'; temp = temp.split('{URL}').join(this.url); this.view.append(temp); this.iframeDoms.push(document.getElementById(fID)); this.v.iframeView = this.view.find('.iframeView'); this.iframeURL = this.url; }; p.updateW = function(_ws) { var r = this.iframeDoms.length; if (_ws.length > r) { for (var i = r; i < _ws.length; i++) { this.addPage(i, _ws[i]); } } }; p.setW = function(_ws) { if (!this.isCreated) return; this.updateW(_ws); var pages = this.view.find('.page'); for (var i = 0; i < _ws.length; i++) { pages.eq(i).width(_ws[i]); } }; /* ---------- ---------- ---------- */ p.reload = function() { if (!this.isAccesable)return; for (var i = 0; i < this.iframeDoms.length; i++) { this.iframeDoms[i].contentWindow.document.location.reload(); } }; /* ---------- ---------- ---------- */ p.update = function() { }; /* ---------- ---------- ---------- */ p.isFirst = true; p.openFlg = false; p.stageInit = function() { this.openFlg = false; this.view.hide(); }; p.stageIn = function() { if (! this.openFlg) { this.openFlg = true; this.view.show(); if (! this.isFirst) { } this.isFirst = false; } }; p.stageOut = function() { if (this.openFlg) { this.openFlg = false; this.view.hide(); } }; return c; })(); GRID.PreviewViewHeader = (function() { var view; var v = {}; var current; function init() { current = GRID.StateCommon.split; view = $('#PreviewViewHeader'); //stageInit(); createlayout(); setBtn(); } /* ---------- ---------- ---------- */ function setBtn() {} function createlayout() { v.title = view.find('.title_url'); v.btn_zoom = view.find('.btn_zoom'); v.btn_width = view.find('.btn_width'); v.btn_edit = view.find('.btn_edit'); v.btn_reload = view.find('.btn_reload'); v.btn_globe = view.find('.btn_globe'); v.btn_close = view.find('.btn_close'); v.btn_globe.click(function() { openURL() }); v.btn_zoom.click(function() { setScale() }); v.btn_width.click(function() { setW() }); v.btn_edit.click(function() { edit() }); v.btn_reload.click(function() { reload() }); v.btn_close.click(function() { setDisplay(false) }); v.title.hover( function() { $(this).html(titleTexts.url_over); },function() { $(this).html(titleTexts.url_mini); } ); } function openURL() { window.open(titleTexts.url); } function edit() { GRID.PreviewView.edit(); } function reload() { GRID.PreviewView.reload(); } function setDisplay(_b) { GRID.SplitViewController.setDisplay(_b); } function setW(_n) { GRID.SplitViewController.setW(_n); } function setScale(_s) { GRID.SplitViewController.setScale(_s); } function update() { var s = current.scale / 100; var sW = s; var sH = s; v.iframe = $('#PreviewView iframe'); var tar = v.iframe; tar.css('-webkit-transform', 'scale(' + sW + ',' + sH + ')'); tar.css('-moz-transform', 'scale(' + sW + ',' + sH + ')'); tar.css('-ms-transform', 'scale(' + sW + ',' + sH + ')'); tar.css('transform', 'scale(' + sW + ',' + sH + ')'); tar.css('width', 100 / sW + '%'); tar.css('height', 100 / sW + '%'); } var titleTexts = {}; function openPreview() { function __aa(_s) { var u = GRID.App.baseUrls.url; if (u == '') return _s; return _s.split(u).join('<small>__BASE__URL__/</small>'); } function __bb(_s) { var out = ''; var protcolList = ['http://', 'https://', '//']; var url = _s.split('?'); for (var i = 0; i < protcolList.length; i++) { var ss = protcolList[i]; if (_s.substr(0, ss.length) == ss) { var cc = ''; var a = url[0].split(ss)[1].split('/'); out += ss; for (var ii = 0; ii < a.length; ii++) { out += cc + '/' + a[ii] + '<br>'; cc += ' '; } } } out = out.split('///').join('//'); if (url.length > 1) { var param = url[1]; var s = ''; out += '<br><br>?'; var grid = []; var line = param.split('&'); for (var i = 0; i < line.length; i++) { grid.push(line[i].split('=')); } out += GPCommon.arrayToTable(grid); } return out; } var _u = GRID.StateCommon.preview.url; titleTexts.url = _u; titleTexts.url_mini = __aa(_u); titleTexts.url_over = __bb(_u); v.title.html(titleTexts.url_mini); GRID.PreviewView.openPage(_u); setDisplay(true); } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit() { view.hide(); } function stageIn() { if (! isOpen) { isOpen = true; view.show(); if (isFirst) {} isFirst = false; } } function stageOut() { if (isOpen) { isOpen = false; view.hide(); } } return { init: init, stageIn: stageIn, stageOut: stageOut, openPreview: openPreview, update: update }; })(); /* ---------- ---------- ---------- ---------- ---------- ---------- ---------- */ var U_ = (function(){ function int_(_v){ if(_v == null) return 0; if(_v == "") return 0; var s = 0 var n = Number(_v); if(! isNaN(n)){ if(n > 0){ s = Math.floor(n) } else { s = Math.ceil(n) } } return s } function number_(_v){ if(_v == null) return 0; if(_v == "") return 0; if(_v == "") return 0; var s = 0 var n = Number(_v); if(isNaN(n))n = 0; return n } function defInt(_v,_def){ _def = int_(_def); if( _v == null || _v == "" || isNaN(Number(_v)) ){ _v = _def; } var n = int_(_v); var s = _def; if(! isNaN(n)){ s = n; } return s; } function defNumber(_v,_def){ _def = number_(_def); if( _v == null || _v == "" || isNaN(Number(_v)) ){ _v = _def; } var s = _def; var n = number_(_v); if(! isNaN(n)){ s = n; } return s; } return { int_:int_, number_:number_, defInt:defInt, defNumber:defNumber } })(); var URL_ = (function(){ function treatInputUrl(_s){ if(_s == null) return "" _s = _s.split(" ").join(""); _s = _s.split(" ").join(""); return _s; } function treatDirUrl(_s){ if(_s ==null)return ""; if(_s.charAt(_s.length-1) != "/"){ _s = _s + "/" } return _s; } function treatURL(_s){ if(_s ==null) return ""; var out = ""; for (var i = 0; i < protcolList.length ; i++) { var ss = protcolList[i] if(_s.substr(0, ss.length) == ss){ var a = _s.split(ss); out += ss + a[1].split("//").join("/"); } } return out; } function isTextFile(_s){ if(_s == null) return false; var b = false; var ext = getExtention(_s) if(ext == "") b = true; if(ext == "html") b = true; if(ext == "htm") b = true; if(ext == "css") b = true; if(ext == "js") b = true; if(ext == "json") b = true; if(ext == "xml") b = true; if(ext == "csv") b = true; if(ext == "tsv") b = true; if(ext == "as") b = true; if(ext == "php") b = true; return b; } function getExtention(_s){ if(_s == null)return ""; var p1 = _s.split("#")[0]; var p2 = p1.split("?")[0]; var ss = p2.split("."); if(ss.length == 1)return ""; var ex = ss[ss.length-1]; if(ex.indexOf("/") != -1) return ""; return ex; } function getURLParam(_s){ if(_s ==null)return {}; var url = _s; var p1 = url.split("#")[0]; var p2 = p1.split("?")[1]; if(p2.length == 0) return; var ps = p2.split("&"); var o = {} for (var i = 0; i < ps.length ; i++) { var s = ps[i].split("=") o[s[0]] = s[1] } return o } function getBaseDir(_s){ _s = _s.split("?")[0]; var a = _s.split("/"); var u = ""; for (var i = 0; i < a.length -1 ; i++) { u += a[i] + "/" } return u } function getABSDir(_s){ if(_s ==null)return ""; var out = ""; _s = _s.split("?")[0] var a = _s.split("/"); for (var i = 3; i < a.length-1 ; i++) { out += a[i] + "/" } return out; } var protcolList = ["http://","https://","//"]; //現在のHTMLの絶対パス、相対パスのCSSなどのファイルから、 //絶対パスを生成する。 function getDomain(_s){ if(_s ==null)return ""; var out = "" if(_s ==null) return out; for (var i = 0; i < protcolList.length ; i++) { var ss = protcolList[i] if(_s.substr(0, ss.length) == ss){ var a = _s.split(ss); var a = a[1].split("/"); out += ss + a[0] + "/"; } } return out; } function getDomain_and_dir(_s){ if(_s ==null)return ""; var out = ""; _s = _s.split("?")[0] var a = _s.split("/"); if(a.length < 4) return _s for (var i = 0; i < a.length-1 ; i++) { out += a[i] + "/" } return out; } function isSameDomain(_s,_s2){ if(_s ==null)return false; if(_s2 ==null)return false; var s = getDomain(_s); var s2 = getDomain(_s2); return (s == s2); } function isDomain(_s){ if(_s == null) return false; var b = false; _s = _s.split(" ").join("") _s = _s.split(" ").join("") if(_s == "") return false; if(_s.substr(0, 5) == "http:") b = true; if(_s.substr(0, 6) == "https:") b = true; if(_s.substr(0, 2) == "//") b = true; return b } function joinURL(_s,_s2){ if(_s ==null)return ""; if(_s2 ==null)return ""; if(! isDomain(_s)) return _s2; if(isDomain(_s2)) return _s2; var a = _s2.split("../"); var ss =_s.split("/"); var u = "" var leng = ss.length - a.length for (var i = 0; i < leng ; i++) { u += ss[i] + "/" } var g = _s2.split("../").join(""); g = g.split("./").join(""); return treatURL(u + g); } function trimDomain(_s){ if(_s ==null)return ""; var d = getDomain(_s); return _s.split(d).join("") } function getRelativePath(_s,_s2){ if(_s == null)return ""; if(_s2 == null)return ""; var out = ""; if(! isSameDomain(_s,_s2)) return ""; _s = trimDomain(_s); _s2 = trimDomain(_s2); var g = _s.split("?")[0].split("/"); var ps = ""; for (var i = 0; i < g.length-1 ; i++) { if(g[i] != ""){ ps += "../"; } } return ps + _s2; } function getBaseUrls_from_text(_s){ if(_s == null)return [""]; if(! isDomain(_s)) return [""]; _s = _s.split(" ").join("") _s = _s.split(" ").join("") _s = _s.split(" ").join("") if(_s == "")return [""]; var a = _s.split(",") for (var i = 0; i < a.length ; i++) { a[i] = treatDirUrl(a[i]) } return a } function getDecoParamText(_s) { if(_s == null) return ""; var ss = _s.split("?") var tag = "" if(ss.length > 1){ tag += ss[0] + '<span class="param_hatena">?</span>' var param = ss[1].split("&") for (var i = 0; i < param.length ; i++) { var pp = param[i].split("="); if(i!=0){ tag += '<span class="param_and">&</span>'; } tag += '<span class="param_name">'+pp[0]+'</span>'; tag += '<span class="param_eq">=</span>'; tag += '<span class="param_val">'+pp[1]+'</span>'; } } else{ tag = _s; } return tag; } return { treatInputUrl:treatInputUrl, treatDirUrl:treatDirUrl, isTextFile:isTextFile, getExtention:getExtention, getURLParam:getURLParam, getDomain:getDomain, getDomain_and_dir:getDomain_and_dir, isDomain:isDomain, isSameDomain:isSameDomain, getBaseDir:getBaseDir, getABSDir:getABSDir, joinURL:joinURL, getRelativePath:getRelativePath, getBaseUrls_from_text:getBaseUrls_from_text, getDecoParamText:getDecoParamText } })(); var DateUtil = (function(){ /* DateUtil.getFormattedDate(new Date(),"YYYYMMDD_hhmmss"); */ var lang = 1; var week = [ ["日","月","火","水","木","金","土"], ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"], ["Sun.","Mon.","Tue.","Wed.","Thu.","Fri.","Sat."] ] var month = [ ["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月",], ["January","February","March","April","May","June","July","August","September","October","November","December"], ["Jan.","Feb.","Mar.","Apr.","May","Jun.","Jul.","Aug.","Sep.","Oct.","Nov.","Dec."] ] var charas = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" //var charas = "0123456789abcdefghijklmnopqrstuvwxyz" function getFormattedDate(_d,_format){ var t = _format; var d = _d; // t = t.split("YYYY").join(d.getFullYear()) t = t.split("MM").join(formatDigit(d.getMonth()+1,2)); t = t.split("DD").join(formatDigit(d.getDate(),2)); // t = t.split("hh").join(formatDigit(d.getHours(),2)); t = t.split("mm").join(formatDigit(d.getMinutes(),2)); t = t.split("ss").join(formatDigit(d.getSeconds(),2)); t = t.split("ms").join(formatDigit(d.getMilliseconds(),3)); t = t.split("month").join(month[lang][d.getMonth()]); t = t.split("week").join(week[lang][d.getDay()]); // t = t.split("RRRRRRRRRR").join(getRandamCharas(10)); t = t.split("RRRRR").join(getRandamCharas(5)); t = t.split("RRRR").join(getRandamCharas(4)); t = t.split("RRR").join(getRandamCharas(3)); t = t.split("RR").join(getRandamCharas(2)); t = t.split("R").join(getRandamCharas(1)); return t; } function getRandamCharas(_n){ var rr = ""; for (var i = 0; i < _n ; i++) { rr += charas[Math.floor(Math.random()*charas.length)]; } return rr; } function formatDigit(_n,_s){ var s = String(_n); if(s.length<_s){ for (var i = 0; i < _s ; i++) { if(s.length <= i)s ="0" + s; } } return s; } function getDate(){ return new Date().toString(); } function getRelatedDate(_d,_today){ var d = _d; //var c = new Date(" Tue Dec 25 2013 0:57:46 GMT+0900 (JST)"); var c = new Date(); if(_today != null){ c = _today; } var sec = (c.getTime()- d.getTime()) / (1000); var min = sec/60; var hour = min/60; var day = hour/24; var ss = ""; if(sec < 20){ ss = '<span class="_time-sec_00-10">' + Math.floor(sec) +"秒前" + '</span>'; } else if(sec < 60){ ss = '<span class="_time-sec_10-60">' +Math.floor(sec) +"秒前" + '</span>' } else if(min < 10){ ss = '<span class="_time-min_00-10">' +Math.floor(min) +"分前" + '</span>'; } else if(min < 60){ ss = '<span class="_time-min_10-60">' +Math.floor(min) +"分前" + '</span>'; } else if(hour < 6){ ss = '<span class="_time-hour_01-06">' +Math.floor(hour) +"時間前" + '</span>'; } else if(hour < 12){ ss = '<span class="_time-hour_06-12">' +Math.floor(hour) +"時間前" + '</span>'; } else if(hour < 24){ ss = '<span class="_time-hour_12-24">' +Math.floor(hour) +"時間前" + '</span>'; } else if(hour < 24*7){ ss = '<span class="_time-day_01-07">' +Math.floor(day) +"日前" + '</span>'; } else if(hour < 24*30){ ss = '<span class="_time-day_07-31">' +Math.floor(day) +"日前" + '</span>'; } else{ ss = '<span class="_time-day_31-99">' +Math.floor(day) +"日前" + '</span>'; } return ss; } return { getFormattedDate:getFormattedDate, getRandamCharas:getRandamCharas, getDate:getDate, getRelatedDate:getRelatedDate } })(); //functions function limitArray(_a,_s,_max){ for (var i = 0; i < _a.length ; i++) { if(_a[i] == _s) _a.splice(i,1); } if(_a.length > _max) _a.splice( _max-1 , _a.length); _a.unshift(_s); } function getUrlVars(){ var vars = [], hash; var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for(var i = 0; i < hashes.length; i++) { hash = hashes[i].split('='); vars.push(hash[0]); vars[hash[0]] = hash[1]; } return vars; } /*function getFilePathTag(u){ var a = u.split("/"); var tag = "" for (var i = 0; i < a.length ; i++) { if(a.length-1 == i){ tag += "<em>" +a[i] + "</em>" } else{ tag += a[i] + "/ " } } return tag; }*/ function getFilePathTag(u){ var a = u.split("/"); var tag = ""; var round = 8 for (var i = 0; i < a.length ; i++) { if(a.length-1 == i){ tag += "<em>" +a[i] + "</em>" } else{ var s = a[i]; if(a.length-2 !=i){ if(s.length > round) s = s.substr(0,round) + "..." } tag += '<span class="dir">'+s+'<i>/</i> </span>' } } return tag; } function getR(){ return new Date().getTime(); } function getInputNumber(_abs,_n,_def){ var n; if(_abs == "abs"){ if(_n == null){ n = prompt("", _def); if(n == null)return _def; n = Number(n); if(isNaN( Number(n) ))return _def; } else{ n = _n; } } else{ n = _def + _n; } return n; } function setLimitNumber(n,_leng){ if(n < _leng[0]) n = _leng[0]; if(n > _leng[1]) n = _leng[1]; return n; } var Lib_ = (function (){ var _ = {}; _.init = function(){} /* ---------- ---------- ---------- ---------- ---------- ---------- ---------- */ _.Type_ = {} _.Type_.LimitInt = function(_defN,_leng) { /* var limitInt = new Lib_.Type_.LimitInt(0,[-2,5]); limitInt.add_(1); limitInt.getN(); */ this.defN = _defN; this.n_ = _defN; this.lengS = _leng[0]; this.lengE = _leng[1]+1; this.sw = (this.lengS < this.lengE)? true:false; } _.Type_.LimitInt.prototype = { add_:function(_n) { this.n_ += _n; if (this.sw) { if(this.n_ < this.lengS) this.n_ = this.lengS; if(this.n_ > this.lengE - 1) this.n_= this.lengE-1; } else { if(this.n_ > this.lengS) this.n_ = this.lengS; if(this.n_ < this.lengE - 1) this.n_ = this.lengE-1; } }, getN:function() {return this.n_;}, setN:function(_n) {this.n_ = _n;this.add_(0);}, getMax:function() {return this.lengE}, isMax:function() {return (this.n_ ==this.lengE-1) ? true : false}, isMin:function() {return (this.n_ ==this.lengS) ? true : false} } _.Type_.RotationInt = function(_defN,_leng) { /* var rotationInt = new Lib_.Type_.RotationInt(0,[-2,5]); rotationInt.add_(1); rotationInt.getN(); */ this.defN = _defN; this.n_ = _defN; this.lengS = _leng[0]; this.lengE = _leng[1]; this.sw = (this.lengS < this.lengE)? true:false; } _.Type_.RotationInt.prototype = { add_:function(_n) { this.n_ += _n; if (this.sw) { if(this.n_ < this.lengS) this.n_ = this.lengE; if(this.n_ > this.lengE ) this.n_= this.lengS; } else { if(this.n_ > this.lengS) this.n_ = this.lengE; if(this.n_ < this.lengE ) this.n_ = this.lengS; } }, getN:function() {return this.n_;}, setN:function(_n) {this.n_ = _n;this.add_(0);}, getMax:function() {return this.lengE}, isMax:function() {return (this.n_ ==this.lengE-1) ? true : false}, isMin:function() {return (this.n_ ==this.lengS) ? true : false} } return _; })(); <file_sep>/src/js/cms_view_editable/EditableView.M_Grid.js EditableView.M_Grid = (function() { /* ---------- ---------- ---------- */ var c = function(_gridType) { this.init(_gridType); } var p = c.prototype; /* ---------- ---------- ---------- */ p.gridType p.view; p.v p.parent; p.gridData; p.detailView; p.detailNo; p.subGrids p.init = function(_gridType) { this.gridType = _gridType; // this.v = {} this.subGrids = [] this.setParam(); } p.setParam = function (){ this.gridInfo = this.gridType.gridInfo; this.repeat = this.gridType.multiGridRepeat; } p.registParent = function (_parent){ this.parent = _parent; } p.openTab = function (_n){ for (var i = 0; i < this.subGrids.length ; i++) { this.subGrids[i].mGrid_stopEditMode() } this.subGrids[_n].mGrid_startEditMode(); } /* ---------- ---------- ---------- */ //#Data p.initData = function (_array){ this.subGrids = []; var tag = ""; tag += '<div class="_editableBlock">'; tag += this.gridInfo.getHeadTag(); tag += ' <div class="_replaceArea_MGRID"></div>'; tag += '</div>'; this.view = $(tag); this.parent.v.replaceArea.append(this.view); this.v.replaceArea = this.view.find('._replaceArea_MGRID'); if(_array == null){ _array = []; for (var i = 0; i < this.repeat ; i++) { _array.push(null); } } for (var i = 0; i < _array.length ; i++) { this.addData(_array[i],i); } this.openTab(0); } p.getData = function (){ var a = []; for (var i = 0; i < this.subGrids.length ; i++) { a.push(this.subGrids[i].getData()) } return a; } p.addData = function (_o,_n){ var o = _o; var g = new EditableView.BaseBlock(this.gridType,1,_n); g.registParent(this); g.initData(o); this.subGrids.push(g); this.parent.updateSubData(); } /* ---------- ---------- ---------- */ //#update p.updateSubData = function (){ this.parent.updateSubData(); } return c; })();<file_sep>/src/js/cms_view_inspect/InspectView.View.js InspectView.View = (function(){ var view; var v = {}; function init(_view){ view = $("<div>"); var tag = "" tag += '<div class="_notes">■表示設定</div>'; tag += '<div class="_view_active">'; tag += ' <div class="ss_inspect_views">'; tag += ' <div class="_cms_btn_alpha _btn_hide ss_inspect _btn_hide" ></div>'; tag += ' <div class="_cms_btn_alpha _btn_hide_ac ss_inspect _btn_hide_ac"></div>'; tag += ' <div class="_cms_btn_alpha _btn_pc ss_inspect _btn_pc"></div>'; tag += ' <div class="_cms_btn_alpha _btn_pc_ac ss_inspect _btn_pc_ac"></div>'; tag += ' <div class="_cms_btn_alpha _btn_mo ss_inspect _btn_mo"></div>'; tag += ' <div class="_cms_btn_alpha _btn_mo_ac ss_inspect _btn_mo_ac"></div>'; tag += ' </div>'; // tag += ' <br>'; // tag += CMS_GuideU.getGuideTag("inspect/view","表示について","dark"); tag += '</div>'; tag += '<div class="_view_negative">'; tag += '<div class="_dont_use _notes">このブロックでは利用できません。<br><br></div>'; tag += '</div>'; view.html(tag); v.view_active = view.find("._view_active").hide(); v.view_negative = view.find("._view_negative").hide(); setBtn(); return view; } function setBtn(){ v._btn_hide = view.find("._btn_hide"); v._btn_hide_ac = view.find("._btn_hide_ac"); v._btn_pc = view.find("._btn_pc"); v._btn_pc_ac = view.find("._btn_pc_ac"); v._btn_mo = view.find("._btn_mo"); v._btn_mo_ac = view.find("._btn_mo_ac"); var update = true; v._btn_hide .on("click",function(){setHide (false,update)}); v._btn_hide_ac .on("click",function(){setHide (true,update)}); v._btn_pc .on("click",function(){setHidePC(false,update)}); v._btn_pc_ac .on("click",function(){setHidePC(true,update)}); v._btn_mo .on("click",function(){setHideMO(false,update)}); v._btn_mo_ac .on("click",function(){setHideMO(true,update)}); } /* ---------- ---------- ---------- */ var narrow = ""; var hide = ""; var hidePC = ""; var hideMO = ""; function setData(_blockType,_narrow,_hide,_hidePC,_hideMO){ if(_blockType == "layout.colDiv") { v.view_active.hide() v.view_negative.show() return; } v.view_active.show() v.view_negative.hide() // narrow = _narrow; hide = _hide; hidePC = _hidePC; hideMO = _hideMO; setNarrow ( narrow , false); setHide ( hide , false); setHidePC ( hidePC , false); setHideMO ( hideMO , false); } function toggleNarrow(){ setNarrow(isNarrow ? false:true , true) } var isNarrow = false function setNarrow(_b,_update){ isNarrow = _b; if(_b){ if(_update) InspectView.setAttr_narrow(true); } else{ if(_update) InspectView.setAttr_narrow(""); } } function setHide(_b,_update){ v._btn_hide.hide(); v._btn_hide_ac.hide(); if(_b){ v._btn_hide.show(); if(_update) InspectView.setAttr_hide(true); } else{ v._btn_hide_ac.show(); if(_update) InspectView.setAttr_hide(""); } } function setHidePC(_b,_update){ v._btn_pc.hide(); v._btn_pc_ac.hide(); if(_b){ v._btn_pc.show(); if(_update) InspectView.setAttr_hidePC(true); } else{ v._btn_pc_ac.show(); if(_update) InspectView.setAttr_hidePC(""); } } function setHideMO(_b,_update){ v._btn_mo.hide(); v._btn_mo_ac.hide(); if(_b){ v._btn_mo.show(); if(_update) InspectView.setAttr_hideMO(true); } else{ v._btn_mo_ac.show(); if(_update) InspectView.setAttr_hideMO(""); } } return { init:init, setData:setData , toggleNarrow:toggleNarrow } })(); <file_sep>/src/js/cms_view_modals/MiniEditer.CodeView.js MiniEditer.CodeView = (function() { /* ---------- ---------- ---------- */ var c = function(_view,_type) { this.init(_view,_type); } var p = c.prototype; /* ---------- ---------- ---------- */ p.init = function(_view,_type) { var self = this; this.v = {} this.parentView = _view; this.type = _type; var tag = ""; tag += '<div class="_text-editor">'; tag += ' <div class="_name">' +_type+ '</div>'; tag += ' <div>'; tag += ' <div class="_presetBtns clearfix"></div>'; tag += ' <textarea class="codemirror"></textarea>'; tag += ' </div>'; tag += ' <div class="_footer clearfix">'; tag += ' <div class="_status"></div>'; tag += ' </div>'; tag += ' <div class="_option clearfix"></div>'; tag += '</div>'; this.view = $(tag); this.textarea = this.view.find("textarea"); this.parentView.append(this.view); this.cmEditor = this.createCMEditor(this.textarea,this.type); this.v.codemirrorView = this.view.find(".CodeMirror"); this.v.footer = this.view.find('._footer'); this.v.status = this.view.find('._status'); this.option = new MiniEditer.CodeViewOption(this.view.find("._option"),this.type); this.preset = new MiniEditer.PresetClass( this, this.view.find("._presetBtns"), this.type, function(_s){self.assignTag(_s)} ); } /* ---------- ---------- ---------- */ p.search = function() { CodeMirror.commands.find(this.cmEditor); } p.assignTag = function(tags) { var r = this.cmEditor.getSelection(); r = (r == "") ? (tags[0] + tags[1] + tags[2]) : (tags[0] + r + tags[2]); this.cmEditor.replaceSelection(r,"around"); this.cmEditor.focus(); } p.createCMEditor = function(_view,_type) { var self = this; this.view.addClass(CodeMirrorU.getColorType(_type)); var e = CodeMirrorU.createEditor(_view.get(0),_type,true); e.on("change",function(){ self.update(); }) return e; } p.update = function() { this.currentVal = this.option.getData() + this.cmEditor.getValue(); this.callback(this.currentVal); this.updateState(); } p.restore = function() { this.cmEditor.setValue(this.defVal); } p.setData = function(_s,_callback) { var self = this; this.defVal = this.currentVal = _s; this.callback = _callback; _s = this.option.setData(_s,function(){ self.update(); }); this.cmEditor.setValue(_s); this.cmEditor.focus(); // this.cmEditor.setCursor(99999); this.updateState(); } p.resize = function(_h) { if(_h< 100) _h = 100; this.v.codemirrorView.height(_h); this.cmEditor.refresh(); } p.updateState = function() { var s = (function(_s1,_s2){ var s = ""; // s += "行数 : "+_s1.split("\n").length + ' <i class="fa fa-long-arrow-right"></i> ' + '<b>' + _s2.split("\n").length + '行</b>' s += "文字数 : "+_s1.length + ' <i class="fa fa-long-arrow-right"></i> ' + '<b>' +_s2.length + '文字</b>' return s; })(this.defVal,this.currentVal); this.v.status.html(s); this.updateRestoreBtn(); } p.updateRestoreBtn = function (){ this.preset.setRestoreBtn(this.defVal == this.currentVal); } /* ---------- ---------- ---------- */ p.stageInit=function(){ // } p.stageIn=function( ) { this.view.show() } p.stageOut=function( ) { this.view.hide() } return c; })(); <file_sep>/src/js/cms_main/CMS_StageController.js //全体のレイアウトを管理する var CMS_StageController = (function(){ var v = {}; function init(){ v.body = $("body"); v.mainStage = $("#CMS_PageStage"); v.mainStageC = $("#CMS_PagesView_DisableView"); v.header = $("#CMS_Header"); v.headerR = $('#CMS_HeaderRight'); v.right = $("#CMS_SidePreview"); v.asset = $("#CMS_AssetStage"); v.assetSBG = $("#CMS_AssetStageSideBG"); v.assetC = $("#CMS_AssetStageClose"); v.preBottom = $("#CMS_SidePreviewClose ._bottom"); var state = Storage.Memo.getPreviewState(); currentS = parseInt(state[0]); currentWs = state[1].split(","); var ww = 0 for (var i = 0; i < currentWs.length ; i++) { ww += Number(currentWs[i])*(currentS/100); } setSideW(ww); initView(); CMS_ScreenManager.registResize(function(){resize();}) } /* ---------- ---------- ---------- */ function initView(){ if(Storage.Memo.getPreviewVisible() == "1"){ openPreviewStage(true); } else{ openPreviewStage(false); } } var isOpenPreviewStage = false // function openPreviewStageToggle(){ // openPreviewStage((isOpenPreviewStage) ? false: true); // } function openPreviewStage(_b){ if(_b){ // v.body.addClass("_sidePreview"); isOpenPreviewStage = true; CMS_SidePreview.stageIn(); CMS_SidePreviewClose.stageOut(); Storage.Memo.setPreviewVisible("1"); } else{ // v.body.removeClass("_sidePreview"); isOpenPreviewStage = false; CMS_SidePreview.stageOut(); CMS_SidePreviewClose.stageIn(); Storage.Memo.setPreviewVisible("0"); } update(); } /* ---------- ---------- ---------- */ //アセット var isOpenAssetStage = false function openAssetStage(_b){ isOpenAssetStage = _b; isAssetFull = false; update(); } var isSettingSelectStage = false; function openSettingSelectStage(_b){ isSettingSelectStage = _b; isOpenAssetStage = _b; update(); } var isAssetFull = false; var isPrevAssetOpen = false // var isPrevPreviewOpen = false function openSettingFull(_b){ isAssetFull = _b; //アセットひらいてたか if(_b) { isPrevAssetOpen = isOpenAssetStage; isOpenAssetStage = true; } else{ isOpenAssetStage = isPrevAssetOpen; } //サイドプレビュー開いてたか // if(_b) { // isPrevPreviewOpen = isOpenPreviewStage; // isOpenPreviewStage = false; // } else{ // isOpenPreviewStage = isPrevPreviewOpen; // } update(); } var asset_update_cb; function registAssetCallback(_cb){ asset_update_cb = _cb; } /* ---------- ---------- ---------- */ function setSideW(_w){ currentSideW = _w update() } function update(){ updateAssetView(); updateW(); updateH(); resize(); if(asset_update_cb) asset_update_cb(isAssetFull); } function updateAssetView(){ if(isOpenAssetStage){ CMS_AssetStage.stageIn(); } else{ CMS_AssetStage.stageOut(); } } //幅 var currentSideW = 250; var minW = 250; function updateW(){ var w = 0; if(isOpenPreviewStage){ if(currentSideW < minW ) currentSideW = minW; w = currentSideW; } else { w = 40; } v.header.css("right",w); v.headerR.css("width",w); v.mainStage.css("right",w); v.right.css("width",currentSideW); // if(isSettingSelectStage){ v.asset.css("right",0); v.assetC.css("right",0); } else{ v.asset.css("right",w); v.assetC.css("right",w); } } //高さ var currentSettingH = 500; var minH = 100; function updateH(){ var h = 0; if(isOpenAssetStage){ if(currentSettingH < minH ) currentSettingH = minH; h = currentSettingH; } else { h = 40; } if(isAssetFull){ v.body.addClass("_assetStageFull"); v.mainStage.css("bottom","0"); v.mainStageC.css("bottom","0"); v.asset.css("height","auto"); v.assetSBG.css("height","auto"); v.preBottom.css("height","auto"); } else{ v.body.removeClass("_assetStageFull"); v.mainStage.css("bottom",h); v.mainStageC.css("bottom",h); v.asset.css("height",h); v.assetSBG.css("height",h); v.preBottom.css("height",h); } } var prevHeight = 500; /* ---------- ---------- ---------- */ function offsetY(_y){ currentSettingH = CMS_StatusH - ( _y ); update(); } /* ---------- ---------- ---------- */ var cbs = [] function registResize(_cb){ cbs.push(_cb); } /* ---------- ---------- ---------- */ var tID; function resize(){ if(tID) clearTimeout(tID); tID = setTimeout(function(){ resize_core() },200); } function resize_core(){ for (var i = 0; i < cbs.length ; i++) { cbs[i](); } } /* ---------- ---------- ---------- */ return { init: init, // openPreviewStageToggle: openPreviewStageToggle, openPreviewStage: openPreviewStage, openAssetStage: openAssetStage, openSettingFull: openSettingFull, openSettingSelectStage: openSettingSelectStage, registAssetCallback: registAssetCallback, setSideW: setSideW, offsetY: offsetY, registResize: registResize } })(); <file_sep>/src/js/cms_view_editable/EditableView.InputU.js EditableView.InputU = (function(){ function getNo(_s){ return Number($(_s).attr("data-no")); } function addData(_type){ var cellTypes = _type; var o = {}; for (var i = 0; i < cellTypes.length ; i++) { var cell = cellTypes[i]; var val = ""; val = cell.def; if(typeof cell.def == "function") { val = cell.def() } //2017-08-28 19:12:47 if(typeof cell.def == "object") { val = JSON.parse(JSON.stringify(cell.def)); } if(val == ""){ if(cell.type == CELL_TYPE.SELECT){ for (var g = 0; g < cell.vals.length ; g++) { if(cell.vals[g][2] == "1")val = cell.vals[g][0]; } } } if(val=="DATE_ID"){ val = DateUtil.getFormattedDate(new Date(),"YYYYMMDD_RRRRR"); } o[cell.id] = val; } o._state = ["publicData"]; return o; } function getTenten(_s){ var s = ""; if(_s){ s = "."; var gg = Math.floor(_s.length/5); for (var i = 0; i < gg ; i++) { s += "."; } } else{ s = ""; } return s.split(".....").join("..... "); } return { getNo:getNo, addData:addData, getTenten:getTenten } })(); <file_sep>/src/js/cms_main/CMS_ProccessView.js var CMS_ProccessView = (function(){ var view; var v = {}; function init(){ view = $('#CMS_ProccessView'); stageInit(); } /* ---------- ---------- ---------- */ function createlayout(){ var tag = ""; tag += ' <div class="_bg"></div>'; tag += ' <div class="_modalBox">'; tag += ' <div class="_process"></div>'; tag += ' </div>'; view.html(tag) v.process = view.find("._process") } /* ---------- ---------- ---------- */ function update(_s){ if(!_s){ v.process.html('<i class="fa fa-refresh fa-spin"></i> 処理中...') } else{ v.process.html(_s) } } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } function stageIn(){ if(! isOpen){ isOpen = true; showModalView(this); view.show(); if(isFirst){ createlayout(); } isFirst = false; update(); } } function stageOut(){ if(isOpen){ isOpen = false; hideModalView(); view.hide(); } } return { init:init, update:update, stageIn:stageIn, stageOut:stageOut } })(); <file_sep>/src/js/cms_stage_page/CMS_PageList_ListDB.js var CMS_PageList_ListEditNo = 0; var CMS_PageList_ListDB = (function(){ var list =[] function add_(a){ list.push(a) } function closeAll(){ for (var i = 0; i < list.length ; i++) { list[i].trigger("_closeAll"); } CMS_PageListViewTree.saveDirManager(); } function openAll(){ for (var i = 0; i < list.length ; i++) { list[i].trigger("_openAll"); } CMS_PageListViewTree.saveDirManager(); } return { add_: add_, closeAll: closeAll, openAll: openAll } })(); <file_sep>/src/js/cms_stage_page/CMS_PageListView.js var CMS_PageListView = (function(){ var view; var v = {}; function init(){ view = $('#CMS_PageListView'); var tag = ""; tag += '<div class="_header">'; tag += ' <div class="_header_visual"><span class="_btn_edit"><i class="fa fa-pencil "></i> 変更</span></div>'; tag += ' <div class="_header_btns">'; tag += ' <div class="_left">'; tag += ' <span class="_cms_btn_alpha _btn_closeAll _fs12"><i class="fa fa-folder "></i> <span class="_hide_S">すべて</span>閉じる</span>'; tag += ' <span class="_cms_btn_alpha _btn_openAll _fs12"><i class="fa fa-folder-open "></i> <span class="_hide_S">すべて</span>開く</span>'; tag += ' </div>'; tag += ' <div class="_right">'; tag += ' <div class="_table" style="padding:0 20px 0 0;">'; tag += ' <div class="_cell" style="padding:0 180px 0 0;">'; tag += ' <div class="_wideShow _cms_btn_alpha _btn_editSubFiles"><i class="fa fa-level-up fa-rotate-180 "></i> まとめて設定</div>' tag += ' </div>'; tag += ' <div class="_cell">'; tag += ' <div class="_wideShow _cms_btn_alpha _btn_publish_all"><i class="fa fa-level-up fa-rotate-180 "></i> まとめて公開</div>' tag += ' </div>'; tag += ' </div>'; tag += ' </div>'; tag += ' </div>'; tag += ' <div class="_btn_close"><i class="fa fa-caret-right "></i></div>'; tag += '</div>'; tag += '<div class="_body _sideAera-scroll">'; tag += ' <div class="_asset_list _asset_list_setting">' tag += ' <div class="_mytag_title">{{ Myタグ設定 }}</div>'; var kyes = Dic.MyTagList; for (var i = 0; i < kyes.length ; i++) { tag += '<div id="_SVP__mytag_' + kyes[i].id + '" class="_btn_page _btn_doc_keys" data-no="'+i+'">'; tag += '<i class="fa fa-lg fa-cog" style="margin:2px 2px 0 2px;"></i> <span class="_rep">' + kyes[i].name + '</span>'; tag += '</div>'; } tag += ' </div>' tag += ' <div id="CMS_PageListViewTree" class="_listItem"></div>'; tag += ' <div id="CMS_PageListViewSearchBody" class="_listItem">'; tag += ' <div class="_status"></div>' tag += ' <div class="_replaceView"></div>' tag += ' </div>'; tag += CMS_GuideU.getGuideTag("page/pages","ガイド","blue"); tag += ' <div style="height:50px"></div>'; tag += '</div>'; tag += '<div id="CMS_PageListViewSearch" class="_listItem"></div>'; view.append(tag); view.find('._btn_doc_keys').click(function(){ var no = $(this).data("no"); CMS_MainController.openPageSetting(no); }); view.find('._header_visual ._btn_edit').click(function() { CMS_PageListBgView.stageIn($(this)); }); //すべて開閉ボタン view.find('._btn_closeAll') .click(function(){ CMS_PageList_ListDB.closeAll()}); view.find('._btn_openAll') .click(function(){ CMS_PageList_ListDB.openAll()}); v.btn_editSubFiles = view.find('._btn_editSubFiles') v.btn_editSubFiles.click(function(){ CMS_PageListViewTree.editSubFiles()}); v.btn_editSubFiles.hover( function(){ $("#sitemap_sitemap_root").addClass("_hoverSetAll") }, function(){ $("#sitemap_sitemap_root").removeClass("_hoverSetAll") } ); v.btn_publish_all = view.find('._btn_publish_all') v.btn_publish_all.click(function(){ CMS_PageListViewTree.publishAll()}); v.btn_publish_all.hover( function(){ $("#sitemap_sitemap_root").addClass("_hoverPubAll") }, function(){ $("#sitemap_sitemap_root").removeClass("_hoverPubAll") } ); initToggle(); CMS_PageListViewTree .init(); CMS_PageListViewSearch .init(); stageInit(); } /* ---------- ---------- ---------- */ var isWide = false var stageLeft = 0; function initToggle(){ v.btn_toggle =view.find('._header ._btn_close') v.body = $("body") v.stage = $("#CMS_PageStage") v.btn_toggle.click(function(){ toggle(); }); $("#CMS_PagesView_DisableView").click(function(){ toNormal(); }) } function toggle(){ if(isWide){ toNormal(); } else{ toWide() } } function toNormal(){ if(!isWide)return; v.btn_toggle.html('<i class="fa fa-caret-right "></i>'); v.stage.css("right",stageLeft+"px"); v.body.removeClass("_wideNavi"); v.body.removeClass("_wideNaviCore"); isWide = false; } function toWide(){ if(isWide)return; v.btn_toggle.html('<i class="fa fa-caret-left "></i>'); stageLeft = v.stage.css("right").split("px").join(""); v.stage.css("right","-10px"); v.body.addClass("_wideNavi"); setTimeout(function(){ v.body.addClass("_wideNaviCore"); },200); isWide = true; } /* ---------- ---------- ---------- */ //#Stage var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } function stageIn(){ if(! isOpen){ isOpen = true; view.show(); if(isFirst){} isFirst = false; // CMS_PageListViewTree .stageIn(); CMS_PageListViewSearch .stageIn(); } } function stageOut(){ if(isOpen){ isOpen = false; view.hide(); } } return { init:init, stageIn:stageIn, stageOut:stageOut } })(); var CMS_PageListBgView = (function(){ var view; var v = {}; /* ---------- ---------- ---------- */ //初期化 function init(){ view = $('#CMS_PageListBgView'); v.target = $('#CMS_PageListView ._header_visual'); stageInit(); createlayout(); setBG( Storage.Memo.getCustomBG() ); } /* ---------- ---------- ---------- */ //レイアウト作成・イベントアサイン function createlayout(){ var tag = ""; tag += '<div class="_inner">'; tag += ' <div class="_read">好きなテーマ写真を選択できます。この設定は、サーバーごと、ブラウザごとに設定出来ます。</div>'; tag += ' <div class="_items">'; for (var i = 0; i < 4*10 ; i++) { tag += '<div class="_item _item_a _btn_bg" data-id="a-'+i+'" style="background-position: left -'+(i*50)+'px;"></div>'; } for (var i = 0; i < 4*3 ; i++) { tag += '<div class="_item _item_b _btn_bg" data-id="b-'+i+'" style="background-position: left -'+(i*50)+'px;"></div>'; } tag += ' </div>'; tag += ' <div class="_read">/_cms/images/custom_bg_a.jpg , /_cms/images/custom_bg_b.png を編集すれば、好きな画像を管理画面へ設定できます。</div>'; tag += '</div>'; view.html(tag); v.item = view.find("._item"); v.item_a = view.find("._item_a"); v.item_b = view.find("._item_b"); setBtn(); } function setBtn(){ view.find("._btn_bg").click(function(){ var id = $(this).data("id"); Storage.Memo.setCustomBG(id); setBG(id); }); view.hover( function(){ if(tID) clearTimeout(tID); }, function(){ stageOut_delay() } ) } /* ---------- ---------- ---------- */ //個別処理 function setBG(_id){ if(_id.indexOf("-") == -1){ _id = "a-0" }; var a = _id.split("-"); var ty = a[0]; var no = Number(a[1]); v.target.removeClass("_image_a"); v.target.removeClass("_image_b"); v.item_a.removeClass("_current"); v.item_b.removeClass("_current"); if(ty == "a"){ v.target.addClass("_image_a"); v.item_a.eq(no).addClass("_current"); } else{ v.target.addClass("_image_b"); v.item_b.eq(no).addClass("_current"); } v.target.css("background-position", "0 -" + (no * 50) + "px"); } /* ---------- ---------- ---------- */ //表示・非表示処理 var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } function stageIn(){ if(! isOpen){ isOpen = true; view.show(); // if(isFirst){ // createlayout(); // } isFirst = false; } } var tID; function stageOut_delay(){ if(tID) clearTimeout(tID); tID = setTimeout(function(){ stageOut(); },200); } function stageOut(){ if(isOpen){ isOpen = false; view.hide(); } } return { init:init, stageIn:stageIn, stageOut:stageOut } })(); <file_sep>/src/js/cms_main/CMS_ModalManager.js function showModalView(_v){ CMS_ModalManager.showModalView(_v) } function hideModalView(){ CMS_ModalManager.hideModalView() } function hideFloatView(){ CMS_ModalManager.hideFloatView() } //ショートカットキーで、モーダル時にはスルーするように管理 var CMS_ModalManager = (function() { var modalStac = 0; var isFocus = false; function init() { var tar = "#InspectView textarea, #InspectView input"; $(document).on("focus" ,tar,function(){ isFocus = true; update() }) $(document).on("blur" ,tar,function(){ isFocus = false; update() }) } // var currentPageType = "" // function setEditPageType(_type) { // currentPageType = _type; // } /* ---------- ---------- ---------- */ var currents = []; function showModalView(_view) { currents.push(_view); hideFloatView(); modalStac++; update(); } function hideModalView() { hideFloatView() modalStac--; currents.pop(); update(); } function update() { } function isModal() { return(modalStac > 0) } function isNotModal() { if(modalStac == 0){ if(isFocus == false){ return true; } } return false; } function closeModal() { if(currents.length == 0)return; if (!currents[currents.length-1]) return; var currentView = currents[currents.length-1] if(currentView["compliteEdit"]) { currentView.compliteEdit(); return; } if(currentView["stageOut"]) { currentView.stageOut(); return; } } function hideFloatView() { if (window["Float_DateInputView"]) Float_DateInputView.stageOut(); if (window["CMS_GuideView"]) CMS_GuideView.stageOut(); if (window["FreeLayoutInfoView"]) FreeLayoutInfoView.stageOut(); } /* ---------- ---------- ---------- */ return { init: init, // setEditPageType: setEditPageType, showModalView: showModalView, hideModalView: hideModalView, hideFloatView: hideFloatView, isModal: isModal, isNotModal: isNotModal, closeModal: closeModal } })(); <file_sep>/src/js/cms_view_modals/CMS_GuideView.p2.js var GUIDE_STANDALONE = false; // var tID; // if(tID) clearTimeout(tID); // tID = setTimeout(function(){ // CMS_GuideView.stageIn("") // },500); var CMS_GuideU = (function(){ function loadInit(_calback){ _calback(); /* var u = "./guide.php?" + "url=" + GUIDE_URL + "/guide.xml" $.ajax({ scriptCharset: 'utf-8', type : 'GET', url : u, dataType : 'xml', success : function(s) { setData(s); _calback(); } }) */ } function openGuide(_id){ if(window.location.href.indexOf("http://192.168.1.23:999/develop") != -1){ window.GUIDE_URL = "http://192.168.1.23:1000/server/www.js-cms.jp.v4/www/" } window.open(window.GUIDE_URL + "gateway.html#" + _id , "cms_guide"); } //CMS_GuideU.getGuideTag("inspect/view","_BASE_","dark"); function getGuideTag(_id,_s,_type){ // return "" _s = _s.split("_BASE_").join("ガイド") if(_type == "dark"){ return '<span class="_btn_guide_block _btn_guide_block_dark" data-id="'+_id+'"><i class="fa fa-lg fa-question-circle"></i> ' + _s + "</span>" } else if(_type == "header"){ return '<span class="_btn_guide_block _btn_guide_block_header _big" data-id="'+_id+'"><i class="fa fa-lg fa-question-circle"></i> ' + _s + "</span>" } else if(_type == "big"){ return '<span class="_btn_guide_block _btn_guide_block_light _big" data-id="'+_id+'"><i class="fa fa-lg fa-question-circle"></i> ' + _s + "</span>" } else if(_type == "blue"){ return '<span class="_btn_guide_block _btn_guide_block_light _blue" data-id="'+_id+'"><i class="fa fa-lg fa-question-circle"></i> ' + _s + "</span>" } else{ return '<span class="_btn_guide_block _btn_guide_block_light" data-id="'+_id+'"><i class="fa fa-lg fa-question-circle"></i> ' + _s + "</span>" } } function setData(_xml){ xml = _xml; } var xml; function getXML(_xml){ return xml; } function getData(_id){ if(!_id) return; var a = _id.split("/") var dir = $(xml).find("gloup#"+a[0]); var tar = { dir : {}, page : null }; tar.dir.id = a[0]; tar.dir.name = dir.attr("name"); var items = dir.find("item"); items.each(function(){ var fullID = a[0]+"/"+$(this).attr("id"); if(fullID == _id){ tar.page = $(this); } }) return tar; } function getBodyTag(_param){ var _s = ajastSRC(_param.text); _s = _s.split("\n\n\n\n\n").join("\n\n"); _s = _s.split("\n\n\n\n").join("\n\n"); _s = _s.split("\n\n\n").join("\n\n"); if(_s.charAt(0) == "\n") _s = _s.substr(1,_s.length) var a = _s.split("\n"); var a2= [] for (var i = 0; i < a.length ; i++) { var s = a[i]; var b = false if(s.substr(0,4) == "####") { s = s.split("####").join('<div class="_h4">') + '</div>' b = true; } if(s.substr(0,3) == "###") { s = s.split("###").join('<div class="_h3">') + '</div>' b = true; } if(s.substr(0,3) == "##+") { if(_param.useToggle){ s = s.split("##+").join('<div class="_h2-toggle"><span class="icon"><i class="fa fa-caret-down "></i></span>') + '</div>' } else{ s = s.split("##+").join('<div class="_h2">') + '</div>' } b = true; } if(s.substr(0,3) == "##!") { s = '<div class="_h2-midashi"><i class="fa fa-level-up fa-rotate-180"></i> ここから上級者・制作者向け</div>' b = true; } if(s.substr(0,2) == "##") { s = s.split("##").join('<div class="_h2">') + '</div>' b = true; } if(s.substr(0,2) == "//") { s = "" b = true; } if(s.indexOf("<<<") == 0) { if(_param.useToggle){ s = '<div class="_toggle-body">' } else{ s = ""; } b = true; } if(s.indexOf(">>>") == 0) { if(_param.useToggle){ s = '</div>' } else{ s = ""; } b = true; } if(s.charAt(s.length-1) == ">") { b = true; } if(b == false){ s += '<br>' } a2.push(s) } return a2.join("\n"); } function ajastSRC(_s){ _s = replaceText(_s); if(window["GUIDE_STANDALONE"]){ return _s; } else { // _s = _s.split("img src").join("img src"); // return _s.split('img src="').join('img src="guide/'); _s = _s.split("img src").join("img src"); return _s.split('img src="').join('img src="'+GUIDE_URL); } } function ajastPath(_s){ if(window["GUIDE_STANDALONE"]){ return _s; } else { return "guide/" + _s } } var ICON_FILE = ' <i class="fa fa-file-text _color-file"></i> ' var CMS_GuideDIC = [ ['[[設定:CMS置換えタグ]]' ,'html/_setting/doc_keys.json' ,"サイト設定:ページ情報タグへ"], ['[[設定:置換えタグ登録]]' ,'html/_setting/keys.json' ,"サイト設定:UIタグ登録へ"], ['[[設定:共通パーツ]]' ,'html/_setting/replace.json' ,"サイト設定:パーツ・ひな形登録へ"] ]; function replaceText(_s){ var DIC = CMS_GuideDIC; for (var i = 0; i < DIC.length ; i++) { if(_s.indexOf(DIC[i][0]) != -1){ var rep = ""; rep += '<div>' + ICON_FILE + '<a href="' + DIC[i][1] + '" data-type="cms_link">' rep += DIC[i][2] rep += '</a></div>' _s = _s.split(DIC[i][0]).join(rep) } } var ms = _s.match(/\[\[{.*?\}]\]/g); if(ms){ for (var i = 0; i < ms.length ; i++) { var id = ms[i] id = id.split("[[{").join(""); id = id.split("}]]").join(""); var rep = "" rep += ICON_FILE+'<a href="' + id + '" data-type="cms_link">' + id + '</a>' _s = _s.split(ms[i]).join(rep); } } var ms = _s.match(/\[\[.*?\]\]/g); if(ms){ for (var i = 0; i < ms.length ; i++) { var id = ms[i] id = id.split("[[").join("") id = id.split("]]").join("") var rep = "" var param = CMS_GuideU.getData(id); if(param.page){ var nn = param.page.find("name").text(); rep += '<div class="_color-help"><i class="fa fa-lg fa-question-circle "></i> ' rep += '<a href="' + id + '" data-type="guide">' + nn + '</a></div>' } _s = _s.split(ms[i]).join(rep); } } return _s; } return { loadInit:loadInit , openGuide:openGuide , getGuideTag:getGuideTag , getXML:getXML , getData:getData , getBodyTag:getBodyTag, ajastPath:ajastPath } })(); <file_sep>/src/js/cms_model/PageModel.Tag_.js PageModel.Tag_ = (function() { /* ---------- ---------- ---------- */ var c = function() { this.init(); } var p = c.prototype; /* ---------- ---------- ---------- */ p.param p.pageType p.pageInfo p.grids p.init = function() { } p.getInitData = function() { //overrdie } p.getPreview = function() { //overrdie return ""; } p.getHTML = function() { //overrdie return ""; } p.getTestTag = function() { return "--"; } return c; })();<file_sep>/src/js/cms_stage_asset/CMS_Asset_FileListU.js var CMS_Asset_FileListU = (function(){ function getUpdateTime(_time){ return "ファイルリスト更新時間:<br>"+ DateUtil.getFormattedDate(_time,"YYYY/MM/DD hh:mm:ss"); } // function getImagePreviewTag(_size){ var s = "" if(_size > (FILEMANAGER_PREVIEW_LIMIT_MB * 1000 * 1000)){ s += ' <div class="_img _img_big _btn_file_img_hover"><i class="fa fa-2x fa-hand-o-up "></i><br>'; s += FILEMANAGER_PREVIEW_LIMIT_MB; s += 'MB〜</div>'; } else{ s += ' <div class="_img"><img src="{SRC}" class="_cms_bg_trans"></div>'; } return s } return { getUpdateTime: getUpdateTime, getImagePreviewTag: getImagePreviewTag } })(); window.registAssetFloatView = function(_callback){ var vs = [ "#CMS_Asset_DirArea", "#CMS_Asset_FileListView", "#CMS_Asset_FileDetailView" ] $(vs.join(",")).on("mousedown",function(){ _callback(); }) }<file_sep>/src/js/cms_main/TreeAPI.js var TreeAPI_SITE_DIR = "_*_"; var TreeAPI_NOT_MATCH_TEXT = "未定義"; //TreeAPI var TreeAPI = (function(){ //ノード種類 var TYPE = { DIR : "dir", PAGE : "page", ADD : "add", HTML : "html" }; //置き換えタグ定義 var ReplaceData = [ { id: "{HOME}", text:function(){return ROOT + 'index.html'} }, { id: "{ID}", text: function(_o){ return _o.id }}, { id: "{NAME}", text: function(_o){ return _o.name }}, { id: "{NAME[0]}", text: function(_o){ return U_.getSplitTextAt(_o.name,0)}}, { id: "{NAME[1]}", text: function(_o){ return U_.getSplitTextAt(_o.name,1)}}, { id: "{NAME[2]}", text: function(_o){ return U_.getSplitTextAt(_o.name,2)}}, { id: "{NAME[3]}", text: function(_o){ return U_.getSplitTextAt(_o.name,3)}}, { id: "{NAME[4]}", text: function(_o){ return U_.getSplitTextAt(_o.name,4)}}, { id: "{NAME.noTag}", text: function(_o){ return treatTag(U_.getSplitTextAt(_o.name,0)) }}, { id: "{HTML}", text: function(_o){ return _o.html }}, { id: "{HREF}", text: function(_o){ return _o.href }}, { id: "{TAR}", text: function(_o){ return _o.target }}, { id: "{TAG}", text: function(_o){ return _o.tag }}, { id: "{READ}", text: function(_o){ return _o.read }}, { id: "{DATE}", text: function(_o){ return _o.date }}, { id: "{LEVEL}", text: function(_o){ return _o.level }}, { id: "{SUM}", text: function(_o){ return _o.sum }}, { id: "{NO}", text: function(_o){ return _o.no }}, { id: "{CSS.B}", text: ' _btn_default ' }, { id: "{I.D}", text: '<i class="fa fa-folder "></i> ' }, { id: "{I.D2}", text: '<i class="fa fa-folder-open "></i> ' }, { id: "{I.P}", text: '<i class="fa fa-caret-right "></i> ' }, { id: "{I.P2}", text: '<i class="fa fa-chevron-circle-right "></i> ' }, { id: "{I.P3}", text: '<i class="fa fa-angle-right "></i> ' }, { id: "{I.T}", text: '<i class="fa fa-tag "></i> ' }, { id: "{I.B}", text:function(_o){ var s = ' <i class="fa fa-external-link-square "></i> '; if(_o.target != "_blank") s = ""; return s; }} ] //タグ削除 function treatTag(_s){ return _s.replace(/<("[^"]*"|'[^']*'|[^'">])*>/g,''); } //テンプレートテキスト var Template = {}; Template.Tag = { parent_start :"<ul {}>\n", child_start :"<li {}>", child_end :"</li>\n", parent_end :"</ul>\n" }; //パラーメータで、ClassNameの有無を指定し、取得 Template.ClassName = (function(){ var def = { clearfix : "clearfix", current : "_current", ownCurrent : "_ownCurrent", hasSub : "_hasSub", underconst : "_underconst", toggle : "_type-dir-toggle", type : "_type-{}", level : "_level-{}", no : "_no-{}", sum : "_sum-{}" }; var state function setState(_state){ state = _state; } function getList(){ var o = {} for (var n in def) { o[n] = def[n] } if(state){ if(state.clearfix === false) o.clearfix = ""; if(state.current === false) o.current = ""; if(state.ownCurrent === false) o.ownCurrent = ""; if(state.hasSub === false) o.hasSub = ""; if(state.underconst === false) o.underconst = ""; if(state.type === false) o.type = ""; if(state.level === false) o.level = ""; if(state.no === false) o.no = ""; if(state.sum === false) o.sum = ""; } return o; } return { setState: setState, getList: getList } })(); //デフォルトのPAGEノードの拡張子 var Extension = ".html" //メインクラス var TreeData = (function() { /* ---------- ---------- ---------- */ var c = function(_def,b_) { this.init(_def,b_); }; var p = c.prototype; /* ---------- ---------- ---------- */ p.init = function(_def,b_) { if(_def === undefined) _def = {}; this._isRoot = false; if(b_ === undefined) this._isRoot = true; this.state = ""; this.isHide = false; this.isHideMenu = false; this.isUnderConst = false; this.isNotPublic = false; this.type = TYPE.DIR; this.id = ""; this.tag = "";//タグ カンマで区切る this.read = "";//リード this.date = "";//日付 this.name = ""; this.html = ""; this.url = ""; this.dir = ""; this.dir_rel = ""; this.href = "";//最終的なリンクパス this.target = ""; this.custom_a = ""; this._isCurrent = false;//現在のノード this._ownCurrent = false;//現在のノードを含む、上位のノード this._isOpenMenu = false;//メニューを開いておくか this._isToggleMenu = false;//トルグメニューにしておくか this._level = 0;//階層 this._no = 0;//階層 this._path = "";//currentを特定するときに使う this._path_dir = "";//currentを特定するときに使う this._template = ""//テンプレート //後処理 this.setInitData(_def); this.update(); }; /* ---------- ---------- ---------- */ //初期値セット p.setInitData = function(_def) { //初期値セット for (var n in _def) { var b = true; if(n === "list") b = false; if(b) this[n] = _def[n]; }; //リンクセット if(this["custom_a"] !== undefined){ if(this.custom_a.indexOf(",")!= -1){ var us = this.custom_a.split(","); this.url = us[0]; this.target = us[1]; } else{ this.url = this.custom_a; } } //ディレクトリセット this.dir = URL_U.treatDirName(this.dir); this.dir_rel = this.dir; if(this.dir == ""){ this.dir = html_dir_abs; this.dir_rel = html_dir; } else{ this.dir_rel = ROOT + this.dir_rel; if(this.dir_rel == "..//") this.dir_rel = "../"; if(this.dir_rel.charAt(this.dir_rel.length-1) != "/") this.dir_rel = this.dir_rel +"/" } //公開ステート if(this.state == undefined ) this.state = "0,0,0"; var ss = this.state.split(","); this.isHide = (ss[0] == "1")? true:false; this.isHideMenu = (ss[1] == "1")? true:false; this.isUnderConst = (ss[2] == "1")? true:false; //公開出力してなければ、非表示に if(this.type ==TYPE.PAGE){ if(this["publicDate"] !== undefined){ if(this.publicDate == "-") { this.isNotPublic = true; } } //isHideではなく、プレビューでは表示できるように、isHideMenu if(this.isNotPublic) { //外部リンク設定してたら表示 if(this.custom_a == ""){ this.isHide = true; } } } //リンクセット if(this.url === ""){ if(this.type != TYPE.DIR){ this.url = this.id + Extension; } else{ this.url = DIR_CODE; } } //下階層セット if(_def["list"] !== undefined){ this.list = []; var _l = _def["list"]; for (var i = 0; i < _l.length ; i++) { if(_l[i] !== undefined){ var nn = new TreeData( _l[i],true); if(nn.isHide === false){ this.list.push(nn); } } } } this._sum = 0; if(this.type ==TYPE.DIR){ var cc = 0 for (var i = 0; i < this.list.length ; i++) { if(this.list[i].type == TYPE.PAGE){ if(this.list[i].isHideMenu === false){ cc ++ } } } this._sum = cc; } }; /* ---------- ---------- ---------- */ /* ---------- ---------- ---------- */ /* ---------- ---------- ---------- */ //upadte p.update = function(){ this.clucuURL(); this.setTreePath(); }; /* ---------- ---------- ---------- */ //ディレクトリのリンクセット var DIR_CODE = "__DIR__"; p.clucuURL = function(){ if(this.type !== TYPE.DIR) return; if(this["list"] === undefined)return; node = this; for (var i = 0; i < this.list.length ; i++) { var tree = this.list[i]; if(tree.url === DIR_CODE){ if(tree.list.length > 0){ var a = this._findURL(tree.list); if(a === null){ tree.url = "" tree.dir_rel = "" } else{ tree.url = a[0]; tree.dir_rel = a[1]; } } else{ tree.url = "" tree.dir_rel = "" } } //最終的なパスの生成 tree.href = U_.meargePath(tree.url,tree.dir_rel); if(tree.href == "") tree.href = "#"; } } p._findURL = function(list){ //if(list === undefined) return; var u = null; for (var i = 0; i < list.length ; i++) { if(list[i].url === DIR_CODE ){ if(list[i].list.length > 0){ var a = this._findURL(list[i].list); list[i].url = a[0]; list[i].dir_rel = a[1]; } } var b = true; if(u !== null) b = false; if(list[i].url === "") b = false; if(list[i].isUnderConst) b = false; //if(list[i].isHideMenu) b = false; if(list[i].type == TYPE.HTML) b = false; if(b) u = [list[i].url,list[i].dir_rel]; } return u; }; //ツリーパスの設定 p.setTreePath = function(_path) { _path = (_path !== undefined) ? _path :""; if(this._isRoot){ this._setTreePath_core(_path); this._setTreePathDir_core(_path); } }; p._setTreePath_core = function(_path) { this._path = _path+"/"+this.id; if(this["list"] !== undefined){ for (var i = 0; i < this.list.length ; i++) { var tree = this.list[i]; tree._setTreePath_core(this._path); } } }; p._setTreePathDir_core = function(_path) { this._path_dir = _path+" "+this.id + ":" + this.dir; if(this["list"] !== undefined){ for (var i = 0; i < this.list.length ; i++) { var tree = this.list[i]; tree._setTreePathDir_core(this._path_dir); } } }; /* ---------- ---------- ---------- */ //Tree操作 // p.getTreeByID = function(_id,_def) { // return DataU.getTreeByID(this , _id,_def); // }; //Treeを追加 p.addSubTree = function(_tree) { this.initList(); this.list.push(_tree); this.update() }; //listに追加 p.addList = function(_tree) { if(_tree == undefined) return; this.initList(); this.list = this.list.concat(_tree.list); this.update(); }; p.initList = function() { if(this["list"] === undefined) this.list =[]; }; //IDで指定したノードの親グループIDを返す /* p.getCurrentGloupID = function(_id) { var tree = DataU.getTreeAliasByID(this , _id); if(tree === null) return ""; var ps = tree._path.split("/"); for (var i = 0; i < ps.length ; i++) { if(ps[i] !== "") { return ps[i]; } } return ""; }*/ /* ---------- ---------- ---------- */ /* ---------- ---------- ---------- */ /* ---------- ---------- ---------- */ //メニュータグ取得 p.getMenuTag = function(_op, _deep) { _op.clucu(); this.setCSS(_op.css); this.setCurrent(_op.currentID,_op.currentDIR); return this._getMenuTag_core(_op); }; p._getMenuTag_core = function(_op) { if(_op === undefined) _op = new MenuOption(); var tag = ""; var tb = DataU.getTab(this._level); var list = this.list; var leng = list.length; var _TG = Template.Tag; var child_s = _TG.child_start; var child_e = _TG.child_end; var parent_s = _TG.parent_start; var parent_e = _TG.parent_end; var bodyTag = ""; var count = 0; for (var i = 0; i < leng; i++) { var tree = list[i]; tree._level = this._level + 1; tree._no = count+1; //ディレクトリの深さで制限 var b = true; if(_op.onlyCurrent === true){ if(tree._ownCurrent === false) { if(this._level === 0) b = false; } } if( _op.isMatchType(this._level,tree.type) === false) { b = false; } //メニュー非表示 if(tree.isHideMenu) b = false; if(tree.type == "page" && count >= _op.limitSub) b = false; if (b) { tree._isOpenMenu = (_op._isOpenMenu(this._level, "isOpen")) ? false : true; tree._isToggleMenu = _op.useToggle; bodyTag += tb + child_s.split("{}").join(DataU.getLI_Attr(count, tree)); bodyTag += tree._getMenuTagTree(_op); //下層をレンダリングするか if(! DataU.isHideDir(tree) || tree._isToggleMenu){ bodyTag += tree._getMenuTagDir(_op); } if (tree.hasSubTree()) bodyTag += tb; bodyTag += child_e; count++; } } tag += "\n" + tb + parent_s.split("{}").join(DataU.getUL_Attr(this,count) ); tag += bodyTag; tag += tb + parent_e; tag = tag.split(TreeAPI_SITE_DIR+"/").join(TreeAPI_SITE_DIR) //</UL> return tag; }; //下階層のタグ取得 p._getMenuTagDir = function(_op) { var tag = ""; if (!this.hasSubTree()) return tag; //どの階層までレンダリングするか var b = false; // if (_op.isOpenCurrentTree) { // if (this._isCurrent) b = true; // if (this._ownCurrent) b = true; // } if (_op.isOverLevelEnd(this._level) === false) { b = true; } if (b) tag += this._getMenuTag_core(_op); return tag; } //ノードのタグ取得 p._getMenuTagTree = function(_op) { var tag = ""; if (this._level >= 1) { var t = this.type; this._template = _op.getLevelVal(this._level - 1,this.type,null); tag += DataU.doTemplate(this); } return tag; } /* ---------- ---------- ---------- */ p.setCSS = function(_css) { Template.ClassName.setState(_css); } /* ---------- ---------- ---------- */ //パンくずタグ p.getBreadList = function(_id,_dir,_o) { var b = false; if(_id == "") b = true; if(_id == "index" && _dir == "/") b = true; this._template = _o.home; if(b) return DataU.doTemplate(this); if(_dir == undefined) _dir = ""; if(_dir == "") _dir = html_dir_abs; var _tree = DataU.getTreeAliasByID(this,_id,_dir); if(_tree === null) return "" var s = _tree._path_dir; var breds = []; var add = ""; var list = s.split(" "); for (var i = 0; i < list.length ; i++) { if(list[i] !== ""){ var dd = list[i].split(":"); var id = dd[0]; var dir = dd[1]; var res = DataU.getTreeAliasByID(this,id,dir) if(res !== null){ breds.push(DataU.getTreeAliasByID(this,id,dir)) } } } // var tags = []; this._template = _o.home; tags.push(DataU.doTemplate(this)); for (var i = 0; i < breds.length ; i++) { var temp = "" if(_id === breds[i].id){ temp = _o.current; } else{ temp = _o.node; } breds[i]._template = temp; tags.push(DataU.doTemplate(breds[i])); } var tag = tags.join(_o.delimiter); tag = tag.split(TreeAPI_SITE_DIR+"/").join(TreeAPI_SITE_DIR) return tag; } /* ---------- ---------- ---------- */ //パスを指定すると、マッチするノードをisCurrentとして設定する var currentPath = ""; p.setCurrent = function(_currentID,_currentDIR) { currentPath = ""; this._setCurrent_core(_currentID,_currentDIR); this._setOwnCurrent(_currentID); } p._setCurrent_core = function(_currentID,_currentDIR) { this._isCurrent = false; var b = false; if (this.id === _currentID && this.dir === _currentDIR) b = true; if (this.type == TYPE.DIR) b = false;// ディレクトリの場合は、スルー if (this.id === "") b = false; if (_currentID === "") b = false; if (b) { currentPath = this._path; this._isCurrent = true; } if (this.hasSubTree()) { for (var i = 0; i < this.list.length; i++) { this.list[i]._setCurrent_core(_currentID,_currentDIR); } } } p._setOwnCurrent = function(_current) { var b = false if(this.type === TYPE.DIR) b = true; if(this.type === TYPE.PAGE) b = true; if(b == false) return; // var b = false; if (currentPath.indexOf(this._path + "/") === 0) { //階層が違う場合にown設定 var r1 = currentPath.split("/").length; var r2 = this._path.split("/").length; if(r1 != r2) b = true; //完全一致であれば、true if(currentPath === this._path) b = true; } this._ownCurrent = b; // if (this.hasSubTree()) { for (var i = 0; i < this.list.length; i++) { this.list[i]._setOwnCurrent(_current); } } } /* ---------- ---------- ---------- */ p.hasSubTree = function () { if (this.type === TYPE.DIR){ //if(this.list === undefined) return false; if (this.list.length > 0){ return true; } } return false; } return c; })(); var BreadListOption = (function() { /* ---------- ---------- ---------- */ var c = function() { this.init(); }; var p = c.prototype; /* ---------- ---------- ---------- */ p.home; p.node; p.current; p.delimiter; p.init = function() { this.home = '<a href="{HOME}">HOME</a>'; this.node = '<a href="{URL}">{NAME}</a>'; this.current = '<b>{NAME}</b>'; this.delimiter = ' &gt; '; }; return c; })(); var MenuOption = (function() { /* ---------- ---------- ---------- */ var c = function() { this.init(); }; var p = c.prototype; /* ---------- ---------- ---------- */ p.init = function() { //curren this.currentID = ""; this.currentDIR = ""; //開閉メニューにするか this.useToggle = false; //currentのディレクトリを開いておくか // this.isOpenCurrent = false; //currentのディレクトリのみ表示するか //他のディレクトリは、表示しない this.onlyCurrent = false; // this.limitSub = ""; //20150416 this.css = {}; this.css.clearfix = true; this.css.current = true; this.css.ownCurrent = true; this.css.hasSub = true; this.css.underconst = true; this.css.type = true; this.css.level = true; this.css.no = true; this.css.sum = true; //階層ごと this.levels = null; }; p.clucu = function (){ var cnt = 0; var ls = this.levels; var b = true; if(ls == undefined) ls = []; for (var i = 0; i < ls.length; i++) { if (b) { if (ls[i].isShow) { cnt++; } else { b = false; } } } // this.levelEnd = this.levels.length; this.levelEnd = cnt; if (this.currentDIR == "") this.currentDIR = html_dir_abs; this.currentDIR = URL_U.treatDirName(this.currentDIR); }; /* ---------- ---------- ---------- */ p._isOpenMenu = function (_level){ var b = false; if(this.levels[_level] === undefined) return b; if(this.levels[_level]["isOpen"] === undefined) return b; b = this.getLevelVal(_level,"isOpen",false); return b; }; p.isMatchType = function (_level,_type){ if(this.levels[_level] === undefined) return false; if(this.levels[_level][_type] === undefined) return false; return true; }; p.getLevelVal = function(_lv,_type,_def){ var _levels = this.levels; var lv = _lv; var s = _def; if(_levels.length > lv){ s = _levels[lv][_type]; } else{ s = _levels[_levels.length-1][_type]; } return s; }; p.isOverLevelEnd = function (_l){ if(this.levelEnd <= _l) { return true; } else{ return false; } }; return c; })(); /* ---------- ---------- ---------- */ var DataU = (function(){ var TAB = " "; /* ---------- ---------- ---------- */ function getTab(_deep) { var s = ""; for (var i = 0; i < _deep; i++) { s += TAB; } return s; } /* ---------- ---------- ---------- */ function isHideDir(_tree) { var b = false; if(_tree._isOpenMenu) b = true; if(_tree._isCurrent) b = false; if(_tree._ownCurrent) b = false; return b; } function getUL_Attr(_tree, _leng) { var _CN = Template.ClassName.getList(); var st = ""; if(isHideDir(_tree)) st += "display:none;"; var cs = []; if(_CN.clearfix !== "") cs.push(_CN.clearfix); if(_CN.level !== "") { cs.push(_CN.level.split("{}").join(_tree._level+1)); } if(_CN.sum !== "") { cs.push(_CN.sum.split("{}").join(_leng)); } var t1 = ""; var t2 = ""; if(cs.length !== 0) t1 = 'class="' + cs.join(" ") + '"'; if(st !== "") t2 = ' style="' + st + '"'; return t1 + t2; } function getLI_Attr(_i,_tree) { var _CN = Template.ClassName.getList(); var st = ""; // var cs = []; if(_CN.no !== ""){ cs.push(_CN.no.split("{}").join(_i + 1)); } if(_CN.current !== ""){ if(_tree._isCurrent) cs.push(_CN.current); } if(_CN.ownCurrent !== ""){ if(_tree._ownCurrent) cs.push(_CN.ownCurrent); } if(_CN.hasSub !== ""){ if(_tree.hasSubTree()) cs.push(_CN.hasSub); } if(_CN.type !== "") { cs.push(_CN.type.split("{}").join(_tree.type)); } if(_tree.type == TYPE.DIR){ if(_tree._isToggleMenu){ cs.push(_CN.toggle); } } if(_tree.isUnderConst){ //_tree.url = "javascript:void(0);"; _tree.href = "javascript:void(0);"; _tree.target = ""; cs.push(_CN.underconst); } var t1 = ""; var t2 = ""; if(cs.length !== 0) t1 = 'class="' + cs.join(" ") + '"'; if(st !== "") t2 = ' style="' + st + '"'; return t1 + t2; } /* ---------- ---------- ---------- */ //IDでツリーを取得し、そのエイリアスを返す function getTreeAliasByID(_tree, _id, _dir) { return getTreeAliasByID_core(_tree.list, _id, _dir) } function getTreeAliasByID_core(_tree, _id, _dir) { if(_dir == undefined) _dir = ""; if(_tree === undefined) return null; for (var i = 0; i < _tree.length; i++) { var b = false; if (_tree[i].id === _id) { if (_tree[i].dir === _dir) b = true; } if (b) { return _tree[i]; } else { var list = getTreeAliasByID_core(_tree[i].list, _id, _dir); if (list != null) { return list; } } } return null; } /* ---------- ---------- ---------- */ function doTemplate(_tree) { if(_tree === null) return; var temp = _tree._template; //var callback = _tree.callback; //オリジナルを変更しないように、パラメータ用意 var o = {} o.type = _tree.type; o.id = _tree.id; o.name = _tree.name; o.html = _tree.html; o.level = _tree._level; o.no = _tree._no; o.sum = _tree._sum; o.url = _tree.url; o.href = _tree.href; o.target = _tree.target; o.class_ = _tree.class_; o.tag = _tree.tag; o.read = _tree.read; o.date = _tree.date; //個別処理 if(typeof (temp) == "string"){ // } else if(typeof (temp) === "function"){ var res = temp(o); if(res !== null) temp = res; } else{ return ""; } //ReplaceData if(ReplaceData !== undefined){ temp = _replaceExtra(o,temp,ReplaceData) } //Treeのカスタム if(_tree["extra"] !== undefined){ temp = _replaceExtra(o,temp,_tree.extra); } //置換えの無かった{...}を削除 temp = temp.replace(/{.*?}/g,""); return temp; } function _replaceExtra(_o,_s,_extra){ for (var i = 0; i < _extra.length ; i++) { var s = ""; if(typeof (_extra[i].text) == "string"){ s = _extra[i].text; } else{ s = _extra[i].text(_o); } _s = _s.split(_extra[i].id).join(s); } return _s; } /* ---------- ---------- ---------- */ return { getTab:getTab, isHideDir:isHideDir, getUL_Attr:getUL_Attr, getLI_Attr:getLI_Attr, // getAllTag: getAllTag, getTreeAliasByID: getTreeAliasByID, // getTreeByID: getTreeByID, // doTemplate:doTemplate } })(); var GetTagU = (function(){ /* ---------- ---------- ---------- */ // function getSubTree(_tree,_dir,_tag){ //ターゲットディレクトリ取得 if(_dir != false){ tar == null; _coreDir(_dir, _tree); if (tar == null) tar = _tree; } else { tar = _tree; } //タグ構造化 if(_tag) return _getTagTree(tar,_tag); // return tar; } var tar; //dir function _coreDir(id,a){ var ls = a.list for (var i = 0; i < ls.length ; i++) { if(ls[i].type == "dir" ){ if(ls[i].id == id ){ tar = ls[i]; } else{ _coreDir(id,ls[i]); } } } } //tag function _getTagTree(_tree,_tag){ var tree = {} tree.list = []; if(_tag == false) return _tree; if(_tag == "__ALL__") _tag = getAllTag(_tree).join(",") var tags = _tag.split(","); for (var i = 0; i < tags.length ; i++) { var list = []; var name = tags[i]; _core_tag(name, _tree, list); tree.list[i] = { type : "dir", id : name, name : name, list : list } } if(tree.list.length == 1) return tree.list[0] return tree; } function _core_tag(_tag,_tree,_list){ var ls = _tree.list; for (var i = 0; i < ls.length ; i++) { var node = ls[i]; if(node["tag"]){ var tags = node["tag"].split(","); for (var n = 0; n < tags.length ; n++) { if(tags[n] == _tag ){ _list.push(node); } } } if(node.type == "dir"){ _core_tag(_tag,node,_list); } } } /* ---------- ---------- ---------- */ //TAGでリストを取得 //空白の場合は、スルーする function getAllTag(_a) { var tags = []; _getAllTag_core(_a, tags); return tags; } function _getAllTag_core(_tree,_tags) { var list = _tree.list; for (var i = 0; i < list.length; i++) { var tree = list[i]; if(tree){ if(tree.tag){ _setTag( _tags,tree.tag ); } if(tree.type == TYPE.DIR){ _getAllTag_core(tree, _tags); } } } } function _setTag(_tags,_val) { var a = _val.split(","); for (var i = 0; i < a.length ; i++) { var b = true; for (var n = 0; n < _tags.length ; n++) { if(_tags[n] == a[i]) b = false; } if(b) _tags.push(a[i]); } } /* ---------- ---------- ---------- */ function sortDate(_node,_sort){ var o = JSON.parse(JSON.stringify(_node, null, " ")); sortDate_core(o,_sort); return o; } function sortDate_core(_node,_sort){ var ls = _node.list for (var i = 0; i < ls.length ; i++) { if(ls[i].type == "dir"){ sortDate_core(ls[i],_sort) } else{ if(! ls[i].date) ls[i] = null; } } var a = [] for (var i = 0; i < ls.length ; i++) { if(ls[i] != null){ a.push(ls[i]) } } if (_sort) { a.sort(sortDateFuncOld); } else { a.sort(sortDateFuncNew); } _node.list = a; } //ソート function sortDateFuncOld(a, b){ var x = a.date; var y = b.date; if (x > y) return 1; if (x < y) return -1; return 0; } function sortDateFuncNew(a, b){ var x = a.date; var y = b.date; if (x > y) return -1; if (x < y) return 1; return 0; } /* ---------- ---------- ---------- */ var _flats; function toFlat(_node){ _flats = []; toFlat_core(_node); return _flats; } function toFlat_core(_node){ var ls = _node.list for (var i = 0; i < ls.length ; i++) { if(ls[i].type == "dir"){ toFlat_core(ls[i]); } else{ _flats.push(ls[i]); } } } return { getSubTree:getSubTree, getAllTag:getAllTag, sortDate: sortDate, toFlat: toFlat } })(); var U_ = (function(){ function defaultVal(_v,_def){ var s = _def if(_v != undefined){ s = _v ; } return s; } function treatArray(_list) { var str = []; var list = []; var i = 0; var n = 0; for (var i = 0; i < _list.length ; i++) { if (str[String(_list[i])]) { // } else { str[String(_list[i])] = 1; list[n] = _list[i]; n++; } i++; } return list; } function treatTag(_s){ return _s.replace(/<("[^"]*"|'[^']*'|[^'">])*>/g,''); } function meargePath(_s,_add){ if(_s.indexOf("/") == 0)return _s; if(_s.indexOf("./") == 0)return _add + _s.substr(2, _s.length) if(_s.indexOf("#")==0)return _s; if(_s.indexOf("http://")==0)return _s; if(_s.indexOf("https://")==0)return _s; if(_s.indexOf("mailto:")==0)return _s; var p = _add + _s; p = p.split(".//").join("./"); return p; } function getSplitTextAt(_s,_n){ if(!_s)return ""; if(_n == undefined )return _s; if(_s.indexOf(",") == 0) return _s; var a = _s.split(","); if(a.length > _n){ return a[_n] } else{ return ""; } /* equal (f("0",0),"0"); equal (f("0",1),""); equal (f("0",2),""); equal (f("0",3),""); equal (f("0,1,2",0),"0"); equal (f("0,1,2",1),"1"); equal (f("0,1,2",2),"2"); equal (f("0,1,2",3),""); */ } return { defaultVal:defaultVal, treatArray:treatArray, treatTag:treatTag, meargePath:meargePath, getSplitTextAt:getSplitTextAt } })(); /* ---------- ---------- ---------- */ var ROOT = "" var html_dir = "" var html_dir_abs = "" function setCMS_URL(_dir){ ROOT = TreeAPI_SITE_DIR; html_dir = TreeAPI_SITE_DIR + _dir; html_dir_abs = _dir; } /* ---------- ---------- ---------- */ function getAllTag(_sitemap){ return GetTagU.getAllTag(_sitemap) } /* ---------- ---------- ---------- */ function getSubTree(_s,_d,_tag){ return GetTagU.getSubTree(_s,_d,_tag); } /* ---------- ---------- ---------- */ // function getTag(_htmlDir, _sitemap, _param , _previewPage) { if(_param == undefined) return TreeAPI_NOT_MATCH_TEXT; if(_param.setting == undefined) return TreeAPI_NOT_MATCH_TEXT; var page; if(_param.previewPage != undefined) page = _param.previewPage; if(_previewPage != undefined) page = _previewPage; if(page == undefined) page = {id:"",dir:""} // var o = new MenuOption(); o.currentID = page.id; o.currentDIR = page.dir; o.useToggle = _param.setting.useToggle; o.onlyCurrent = _param.setting.onlyCurrent; o.limitSub = Number(_param.setting.limitSub); o.indent = Number(_param.setting.indent); o.css = _param.css; o.levels = _param.levels; //リスト数制限 if(isNaN(o.limitSub)) o.limitSub = 99999; if(o.limitSub == 0) o.limitSub = 99999; if(isNaN(o.indent)) o.indent = 0; //HTMLディレクトリ setCMS_URL(_htmlDir); //20160926 //追加メニューがあれば、sitemap.listに追加 _sitemap = JSON.parse(JSON.stringify(_sitemap)); if(_param.setting.add){ _sitemap.list = mergeAddMenu(_sitemap.list , _param.setting.add) } var node = _sitemap; //絞り込み、タグ分類 if(_param.targetDir || _param.targetTag){ node = GetTagU.getSubTree(_sitemap , _param.targetDir , _param.targetTag ); } //フラット化 if(_param.setting.isFlat){ node = { name:"list", type:"dir", list:GetTagU.toFlat(node) } } //時別 if(_param.setting.hasDate){ node = GetTagU.sortDate(node, _param.setting.isReverse); } // var tree = new TreeData(node); var s = tree.getMenuTag(o); var tab = (function(_n){ var s = ""; for (var i = 0; i < _n ; i++) { s += "\t"; } return s; })(o.indent); if(tab !="") s = s.split('\n').join("\n" + tab); return s; } /* ---------- ---------- ---------- */ //20160926 function mergeAddMenu(_list,_add) { try{ var ls = _add.list.grid; var a = []; for (var i = 0; i < ls.length ; i++) { a.push(mergeAddMenu_core(ls[i])); } _list = a.concat(_list); // var ls = _add.list2.grid; var a = []; for (var i = 0; i < ls.length ; i++) { a.push(mergeAddMenu_core(ls[i])); } _list = _list.concat(a); }catch( e ){} return _list; } function mergeAddMenu_core(_list) { var s = _list.text; var u = ""; if(_list.anchor){ u = _list.anchor.href; //20170316 追加 if(_list.anchor.target){ u +=","+_list.anchor.target; } // } var _o = {} _o.type = TYPE.ADD; _o.name = s; if(URL_U.isFullPath(u)){ _o.dir = "/"; _o.custom_a = u; } else if(u == "#") { _o.dir = "/"; _o.custom_a = u; } else{ _o.dir = URL_U.getBaseDir(u); if(_o.dir == "") _o.dir = "/"; _o.id = URL_U.getFileID(u); } return _o; } /* ---------- ---------- ---------- */ // function getBreadListTag(_htmlDir, _sitemap , _previewPage) { var tree = new TreeData(_sitemap); setCMS_URL(_htmlDir); var o = new BreadListOption(); o.home = '<i class="fa fa-home"></i> <a href="{HOME}">HOME</a>' o.node = '<a href="{HREF}">{NAME.noTag}</a>'; o.current = '<b>{NAME.noTag}</b>'; return tree.getBreadList(_previewPage.id,_previewPage.dir,o); } /* ---------- ---------- ---------- */ function setToggleMenu(_view){ var parentView = (_view) ? _view :$("body"); var mark_open = '<span>+</span>'; var mark_close = '<span style="opacity:0.5;">-</span>'; var markArea = '<div class="_toggle-icon" style="float:right;">'; setTimeout(function(){ var tar = parentView.find("._type-dir-toggle > p,._type-dir-toggle > a"); tar.each(function (index, dom) { var tar = $(this); tar.css("cursor","pointer") var state = tar.parent().find("> ul").css("display") if(state == "block"){ tar.prepend( markArea + mark_close + '</div>') } else { tar.prepend( markArea + mark_open + '</div>') } tar.click(function(){ var icon = $(this).find("._toggle-icon"); if(icon.html() == mark_open){ icon.html(mark_close) } else{ icon.html(mark_open) } $(this).parent().find("> ul").slideToggle(200); event.stopPropagation(); event.preventDefault(); }); }); },200); } /* ---------- ---------- ---------- */ var sumCnt; function getPageSum(_tree){ sumCnt = 0; getPageSum_core(_tree) return sumCnt; } function getPageSum_core(_tree,_cnt){ var ls = _tree.list for (var i = 0; i < ls.length ; i++){ if(ls[i].type == "dir" ){ getPageSum_core(ls[i]); } if(ls[i].type == "page"){ sumCnt ++; } } } return { setToggleMenu:setToggleMenu, getSubTree:getSubTree, getAllTag:getAllTag, getTag:getTag, getBreadListTag:getBreadListTag, getPageSum:getPageSum }; })(); <file_sep>/src/js/cms_model/PageElement.object.table.js PageElement.object.table = (function(){ var _ = new PageModel.Object_(); /* ---------- ---------- ---------- */ _.pageInfo = new PageModel.Object_Info({ id : "object.table", name : "表組", name2 : "<TABLE>", inputs : ["CLASS","CSS","DETAIL","CAPTION"], // cssDef : {file:"block",key:"[表組ブロック]"} cssDef : {selector:".cms-table"} }); /* ---------- ---------- ---------- */ //セルの準備。設定でデフォルトセル数を設定 var maxCellLeng = 15; var tableCells = []; if (window["GRID_EDIT_MAX_CELL"]) maxCellLeng = GRID_EDIT_MAX_CELL["TABLE"]; for (var i = 0; i < maxCellLeng ; i++) { var n = i+1; var def = ""; if(i == 0) def = "サンプルの文書"; if(i == 1) def = "サンプルの文書ですので、ご注意ください"; var p = new PageModel.OG_Cell({ id: "c" + n, name: n, type: CELL_TYPE.TABLE, style: "", view: "", def: def }); tableCells.push(p); } _.grids = [ /* ---------- ---------- ---------- */ new PageModel.Object_Grid({ gridType:Dic.GridType.BASE, gridInfo:new PageModel.OG_info({ id : "setting", name : "基本設定", note : "", }), textData:{ info:new PageModel.OG_SubInfo({ name:"", image : '<div class="ss_guide _table"></div>' }), cells:[ new PageModel.OG_Cell({ id: "row1", name: "1行目を<br>見出し<TH>にする", type: CELL_TYPE.CHECK }), new PageModel.OG_Cell({ id: "row2", name: "2行目...", type: CELL_TYPE.CHECK }), new PageModel.OG_Cell({ id: "row3", name: "3行目...", type: CELL_TYPE.CHECK }), new PageModel.OG_Cell({ id: "col1", name: "1列目を<br>見出し<TH>にする", type: CELL_TYPE.CHECK }), new PageModel.OG_Cell({ id: "col2", name: "2列目...", type: CELL_TYPE.CHECK }), new PageModel.OG_Cell({ id: "col3", name: "3列目...<br><br><br>", type: CELL_TYPE.CHECK }), new PageModel.OG_Cell({ id: "swipe", name: "スマホで<br>スワイプ化する", type: CELL_TYPE.CHECK }) ] }, gridData:null }), /* ---------- ---------- ---------- */ new PageModel.Object_Grid({ gridType:Dic.GridType.BASE, gridInfo:new PageModel.OG_info({ id : "table", name : "テーブルデータ", style : "", note : "空のセルは、出力されません。空のセルを表示したい場合は、-(ハイフン)を入力してください。" }), textData:null, gridData:{ info:new PageModel.OG_SubInfo({}), cells:tableCells } }), /* ---------- ---------- ---------- */ new PageModel.Object_Grid({ gridType:Dic.GridType.BASE, gridInfo:new PageModel.OG_info({ id : "cols", name : "列(縦方向のセル)設定", note : "", }), textData:{ info:new PageModel.OG_SubInfo({ name:"" }), cells:[ new PageModel.OG_Cell({ id: "wides", name: "幅リスト", type: CELL_TYPE.SINGLE, note:"列のセル &lt;col&gt; ごとの幅属性 ( width= ) を , (カンマ区切り)で入力。無指定の場合は * (アスタリスク)。例:[ 20%,20%,*,* ]" }), new PageModel.OG_Cell({ id: "attrs", name: "属性リスト", type: CELL_TYPE.SINGLE, style : "width:500px", note:"列のセル &lt;col&gt; ごとの属性を , (カンマ区切り)で入力。無指定の場合は * (アスタリスク)。例:[style=\"width:20%\",style=\"width:20%\";,*,* ]" }) ] }, gridData:null }) ] _.getInitData = function(){ var o = {}; o.type = _.pageInfo.id; o.data = { "setting": { "texts": { "row1": "1", "col1": "1", "wides": "20%,*,*,*,*" }, "grid": [] }, "cols": { "texts": { "wides": "20%,*,*,*,*" }, "grid": [] }, "table": { "texts": {}, "grid": [ { "publicData": "1", "c1": "項目名", "c2": "項目名" }, { "publicData": "1", "c1": "項目名", "c2": "サンプルの文書ですので、ご注意ください\n <a href='http://www.google.<EMAIL>'><i class='fa fa-caret-right '></i> リンク</a> " }, { "publicData": "1", "c1": "項目名", "c2": "サンプルの文書ですので、ご注意ください" }, { "publicData": "1", "c1": "項目名", "c2": "サンプルの文書ですので、ご注意ください" } ], "_state": { "currentRow": 0, "currentPage": 0, "fitWide": true, "hideCols": "" } } } o.attr = {css:"default w100p",style:""}; o.attr.class = o.attr.css; return o; } _.getPreview = function(_o){ var data = _o.data; var attr = _o.attrs; var extra = _o.extra; var tag = ""; attr = attr.split('class="').join('class="cms-table '); var list = CMS_U.getPublicList(data.table.grid); if(list.length == 0){ tag += '<span class="_no-input-data">表データを入力...</span>' } else{ var leng = PageElement_Util.getOmitLeng(list.length,"table"); var row1 = data.setting.texts.row1; var row2 = data.setting.texts.row2; var row3 = data.setting.texts.row3; var col1 = data.setting.texts.col1; var col2 = data.setting.texts.col2; var col3 = data.setting.texts.col3; tag += '<div>\n' tag += '<table '+attr+'>\n' tag += this.getCaption(extra) tag += this.getColTags(data); tag += '<tbody>\n' for (var i = 0; i < leng ; i++) { tag += ' <tr>\n'; for (var ii = 1; ii < maxCellLeng ; ii++) { if(list[i]["c"+ii]){ var v = list[i]["c"+(ii)]; if(v == "-") v = ""; var att = CMS_TagU.getCellAttr(v); v = CMS_TagU.deleteCellAttr(v); var b = false; if(row1 == "1" && i == 0) b= true; if(row2 == "1" && i == 1) b= true; if(row3 == "1" && i == 2) b= true; if(col1 == "1" && ii == 1) b= true; if(col2 == "1" && ii == 2) b= true; if(col3 == "1" && ii == 3) b= true; var tname = (b) ? "th" : "td"; tag += ' <'+tname+' '+att+'>' + CMS_TagU.t_2_tag(v) + '</'+tname+'>\n'; } } tag += ' </tr>\n'; } tag += "</tbody>\n"; tag += "</table>\n"; tag += PageElement_Util.getOmitPreviewTag(list.length,"table") tag += '</div>\n' } return tag; } _.getHTML = function(_o){ var data = _o.data; var attr = _o.attrs; var extra = _o.extra; var tag = ""; attr = attr.split('class="').join('class="cms-table '); var list = CMS_U.getPublicList(data.table.grid); if(list.length == 0) return ""; var swipe = data.setting.texts.swipe; var swipeTag = (function(_b){ if(_b == "1") return { start:'<div class="tableWapper">\n',end: "</div>\n"}; return { start:"", end:"" } })(swipe); tag += swipeTag.start; var leng = list.length; var row1 = data.setting.texts.row1; var row2 = data.setting.texts.row2; var row3 = data.setting.texts.row3; var col1 = data.setting.texts.col1; var col2 = data.setting.texts.col2; var col3 = data.setting.texts.col3; tag += '<table '+attr+'>\n' tag += this.getCaption(extra); tag += this.getColTags(data); tag += ' <tbody>\n' for (var i = 0; i < leng ; i++) { tag += ' <tr>\n'; for (var ii = 1; ii < maxCellLeng ; ii++) { if(list[i]["c"+ii]){ var v = list[i]["c"+(ii)]; if(v == "-") v = ""; var att = CMS_TagU.getCellAttr(v); v = CMS_TagU.deleteCellAttr(v); var b = false; if(row1 == "1" && i == 0) b= true; if(row2 == "1" && i == 1) b= true; if(row3 == "1" && i == 2) b= true; if(col1 == "1" && ii == 1) b= true; if(col2 == "1" && ii == 2) b= true; if(col3 == "1" && ii == 3) b= true; var tname = (b) ? "th" : "td"; tag += ' <'+tname+' '+att+'>' + CMS_TagU.t_2_tag(v) + '</'+tname+'>\n'; } } tag += ' </tr>\n'; } tag += " </tbody>\n"; tag += "</table>\n"; tag += swipeTag.end return tag; } /* ---------- ---------- ---------- */ _.getColTags = function(_data){ var tag = ""; if(_data.cols){ if(_data.cols.texts){ var wides = []; var attrs = []; function __core(_val){ var a = [] var vals = _val.split(" ").join("").split(","); for (var i = 0; i < vals.length ; i++) { a.push(vals[i]); } return a; } if(_data.cols.texts.wides){ wides = __core(_data.cols.texts.wides); } if(_data.cols.texts.attrs){ attrs = __core(_data.cols.texts.attrs); } tag += ' <colgroup>\n' for (var i = 0; i < maxCellLeng ; i++) { var ts = "" if(wides[i]) ts+= 'width="'+wides[i]+'" '; if(wides[i] == "") ts+= 'width="" '; if(attrs[i]) ts+= attrs[i]+' '; if(ts) tag +=' <col ' + ts + '>\n'; } tag += ' </colgroup>\n' } } return tag; } /* ---------- ---------- ---------- */ _.getCaption = function(_extra){ var tag = "" if(_extra){ if(_extra.head){ tag += ' <caption>' +_extra.head+ '</caption>\n' } } return tag; } /* ---------- ---------- ---------- */ return _; })(); <file_sep>/src/js/cms_stage_asset/CMS_Asset_FileListClass_ThumbList.js var CMS_Asset_FileListClass_ThumbList = (function() { /* ---------- ---------- ---------- */ var c = function(_parent,_view,_path) { this.init(_parent,_view,_path); } var p = c.prototype; /* ---------- ---------- ---------- */ p.view; p.v; p.init = function(_parent,_view,_path) { this.parent = _parent; this.view = _view; this.targetDir = _path; this.v = {} this.createlayout() this.stageInit() } /* ---------- ---------- ---------- */ p.createlayout=function(){ var self = this; var tag = ""; tag += '<div class="_replaceArea"></div>' // tag += '<div class="_update"></div>' this.view.append(tag) this.v.replaceArea = this.view.find('._replaceArea'); // this.v.update = this.view.find('._update'); this.view.on("click","._btn_file",function(){ self.clickFile($(this).data("name")); }) this.view.on("dblclick","._btn_file",function(){ self.dClickFile($(this).data("name")); }) // this.view.on("click","._btn_add",function(){ // self.addFile2page($(this).data("name")); // }) } /* ---------- ---------- ---------- */ p.list p.updateTime p.updateViewTime p.update = function(_list,_updateTime) { var self = this; if(_list == undefined) return; this.updateTime = _updateTime; this.list = _list; if (!this.openFlg) return; if (!this.updateTime) return; if(this.updateTime == this.updateViewTime) return; this.updateViewTime = this.updateTime; // this.v.update.html(CMS_Asset_FileListU.getUpdateTime(this.updateTime)); var tag = "" // tag += '<br><br><div>画像リスト</div>' tag += '<div class="_imagelist">' var imageCount = 0; if(this.list["files"]){ var files = this.list.files; files.sort(function(a, b){ return ( a.name > b.name ? 1 : -1); }); for (var i = 0; i < files.length ; i++) { var node = files[i] var name_ = node.name var ns = name_.split("."); if(CMS_Asset_FileManageAPI.isImageFile(ns[ns.length-1])){ var temp = '<div id="{ID}" class="_btn_file " data-name="{NAME}" data-path="{PATH_ABS}" data-path_rel="{PATH}">' temp += CMS_Asset_FileListU.getImagePreviewTag(node.filesize); // temp += ' <div class="_btn_add" data-path="{PATH}" data-name="{NAME}"><i class="fa fa-arrow-up"></i> 配置</div>' temp += ' <div class="_name">{NAME}</div>' temp += ' <div>' temp += ' <span class="_date">{DATE}</span>' temp += ' <span class="_size">{SIZE}</span>' temp += ' </div>'; temp += ' <div class="_thumb_btns">' temp += ' <div class="_cms_btn-nano-icon _btn_rename_file" data-path="{PATH}" data-name="{NAME}"><i class="fa fa-wrench "></i> </div>' temp += ' <div class="_cms_btn-nano-icon-red _btn_del_file" data-path="{PATH}"><i class="fa fa-times "></i> </div>' temp += ' </div>'; temp += '</div>'; temp = temp.split("{ID}").join( this.getID( node.name )); temp = temp.split("{SRC}").join(this.targetDir + name_); temp = temp.split("{PATH}").join(node.path); temp = temp.split("{PATH_ABS}").join(node.path.split("../").join("")); temp = temp.split("{NAME}").join(name_); temp = temp.split("{DATE}").join(CMS_SaveDateU.getRelatedDate(node.filemtime)); temp = temp.split("{SIZE}").join(FileU.formatFilesize(node.filesize)); tag += temp; imageCount ++; } } } if(imageCount == 0){ tag += '<div class="_anno">このディレクトリには、画像ファイル(PNG,GIF,JPG,SVG)画像がありません。</div>' } else{ tag += '<div class="_note">ダブルクリックすると、画像ブロックとして、ページへ配置できます。</div>' } tag += '</div>'; if(this.list["nodes"]){ tag += '<table class="_filelist">' var dirs = this.list.nodes.nodes; dirs.sort(function(a, b){ return ( a.name > b.name ? 1 : -1); }); for (var i = 0; i < dirs.length ; i++) { var node = dirs[i] var cnt = Number(node.dirCount) + Number(node.fileCount); var temp = ''; temp += '<tr class="_row_dir">'; temp += '<td><div class="_btn_dir" data-path="{PATH_ABS}" data-path_rel="{PATH}"><span class="{DIR_ICON}"></span> {NAME}{CNT}</div></td>'; temp += '</tr>'; temp = temp.split("{DIR_ICON}").join((Number(node.dirCount)) ? '_icon_dir_has_sub':'_icon_dir_no_sub'); temp = temp.split("{CNT}").join( (cnt == 0) ? "" : '<span class="_cnt">'+ cnt+'</span>'); temp = temp.split("{NAME}").join(node.name); temp = temp.split("{PATH}").join(node.path); temp = temp.split("{PATH_ABS}").join(node.path.split("../").join("")); tag += temp } tag += '</table>'; } this.v.replaceArea.html(tag); this.isLoaded = this; if(this.loadedCallback) { this.loadedCallback(); this.loadedCallback = null; } } /* ---------- ---------- ---------- */ p.loadedCallback p.isLoaded = false; p.selectFile = function(_param){ this.loadedCallback = null; var self = this; if(this.isLoaded){ self.selectFile_core(_param); } else{ this.loadedCallback = function(){ self.selectFile_core(_param); } } } p.selectFile_core = function(_param,_cnt){ var files = this.list.files; var self = this; var b = false; for (var i = 0; i < files.length ; i++) { if(files[i].path == _param.dir + _param.id ){ var id = files[i].name; if(_param.extra){ this.clickFile(id,_param.extra); } else { this.clickFile(id); } this.updateCurrentPath(id); this.scrollCurrentPos(id); b = true; } } //該当ファイルがなければ、リトライ if(!b){ if(_cnt == undefined){ this.parent.update(); setTimeout(function(){ self.selectFile_core(_param,1); },500); } } } p.selectFile_core2 = function(_param){ } // this.view.find("#" + this.getID(_id)) p.clickFile = function(_id,_extra){ var param = { dir: this.targetDir, id: _id } if(_extra) param.extra = _extra; CMS_Asset_FileDetailView.stageIn(param); CMS_Asset_FileListView.resetSelect(param); var tar = this.view.find("#" + this.getID(_id)); tar.addClass("_current"); } p.dClickFile = function(_id,_extra){ CMS_AssetStage.addFile2page(this.targetDir + _id); } //画像URLリロード p.updateCurrentPath = function(_id){ var tar = this.view.find("#" + this.getID(_id)).find("img"); var rr = DateUtil.getRandamCharas(5); var src = tar.attr("src").split("?")[0]+"?"+rr; tar.attr("src",src); } //選択中のファイルへスクロール p.scrollCurrentPos = function(_id){ var tar = this.view.find("#" + this.getID(_id)); var y = tar.offset().top; var paY = tar.parent().offset().top; tar.closest("._body").scrollTop(y- paY); } /* ---------- ---------- ---------- */ p.getID = function(_id){ return "_assetThumb_" + CMS_AssetDB.getID( _id , this.targetDir ); } /* ---------- ---------- ---------- */ /**/ p.openFlg = false; p.stageInit=function(){ this.openFlg = false this.view.hide() } p.stageIn=function( ) { if (! this.openFlg) { this.openFlg = true; this.view.show(); this.loadedCallback = null; this.update(this.list,this.updateTime); } } p.stageOut=function( ) { if (this.openFlg) { this.openFlg = false this.view.hide() } } return c; })();<file_sep>/src/js/cms_view_inspect/InspectView.ID.js InspectView.ID = (function(){ var view; var v = {}; function init(_view){ view = $("<div>"); var tag = "" tag += '<div class="_notes">■ID設定</div>'; tag += '<div class="_view_active">'; tag += '<table class="_mainlayout">'; tag += '<tr><th>id="値"</th><td><input class="_in_data_id _color-style _bold" placeholder="IDを入力" value=""></td></tr>'; tag += '</table>'; // tag += CMS_GuideU.getGuideTag("inspect/id","IDについて","dark"); tag += '</div>'; tag += '<div class="_view_negative">'; tag += '<div class="_dont_use _notes">このブロックでは利用できません。<br><br></div>'; tag += '</div>'; view.html(tag); v.view_active = view.find("._view_active").hide(); v.view_negative = view.find("._view_negative").hide(); v.in_data_id = view.find("._in_data_id"); v.in_data_id.keyup(function(){ InspectView.setAttr_id($(this).val()); }); setBtn(); return view; } function setBtn(){ } function setData(_blockType,_id){ if(_blockType == "layout.colDiv") { v.view_active.hide() v.view_negative.show() return; } v.view_active.show() v.view_negative.hide() v.in_data_id.val(_id) } return { init:init, setData:setData } })(); InspectView.ATTR = (function(){ var view; var v = {}; function init(_view){ view = $("<div>"); var tag = "" tag += '<div class="_notes">■タグ属性設定 </div>'; tag += '<div class="_view_active">'; tag += '<table class="_mainlayout">'; tag += '<tr><td>' tag += '<div class="_input-with-btns">' tag += ' <input class="_in_data_attr _color-style _bold" placeholder="タグ属性を入力" value="">'; tag += ' <div class="_btns">' tag += ' <span class="_btn_input _edit_single" data-type="input:class">'+Dic.I.Edit+'</span> ' tag += ' </div>' tag += '</td></tr>'; tag += '</table>'; tag += '<div class="_notes">※class,style,id属性以外を指定できます。汎用的な用途で利用できます。</div>'; tag += '</div>'; tag += '<div style="height:5px;"></div>'; tag += CMS_GuideU.getGuideTag("inspect/id","その他タブについて","dark"); view.html(tag); v.in_data_attr = view.find("._in_data_attr"); v.in_data_attr.keyup(function(){ InspectView.setAttr_attr($(this).val()); }); setBtn(); return view; } function setBtn(){ } function setData(_blockType,_id){ v.in_data_attr.val(_id) } return { init:init, setData:setData } })(); <file_sep>/src/js/cms_view_editable/EditableView.BaseGridState.js EditableView.BaseGridState = (function() { /* ---------- ---------- ---------- */ var c = function() { this.init(); } var p = c.prototype; /* ---------- ---------- ---------- */ p.init = function() { } p.maxRow = (window["GRID_EDIT_MAX_ROW"]) ? GRID_EDIT_MAX_ROW :50; p.currentRow = -1 p.currentPage = 0 p.fitWide = true p.hideCols = "" p.setData = function(_state) { var o = _state; if(o == undefined) o = {} if(o["currentRow"] === undefined ) o.currentRow = -1; if(o["currentPage"] === undefined ) o.currentPage = 0; if(o["fitWide"] === undefined ) o.fitWide = true; if(o["hideCols"] === undefined ) o.hideCols = ""; this.currentRow = o.currentRow; this.currentPage = o.currentPage; this.fitWide = o.fitWide; this.hideCols = o.hideCols; } p.getData = function() { return { currentRow: this.currentRow, currentPage: this.currentPage, fitWide: this.fitWide, hideCols: this.hideCols }; } //setter p.setCurrentPage = function(_n) { this.currentPage = _n; } p.setCurrentRow = function(_n) { this.currentRow = _n; } p.setFitWide = function(_n) { this.fitWide = _n; } p.setHideCols = function(_n) { this.hideCols = _n; } //ページにおける現在の行を取得 p.getRowAtPage = function(_r) { if(_r === undefined) _r = this.currentRow var s = this.currentPage * this.maxRow; var r = (_r - s) + 1; return r; } //指定行は、現在の表示ページに含まれるか p.isCurrentPage = function(_r) { if(_r == undefined) _r = this.currentRow var s = this.currentPage * this.maxRow; var e = s + this.maxRow; if(s <= _r){ if(e > _r) return true; } return false; } //ページ調整 p.adjustPage = function(_pageLeng) { if (_pageLeng <= this.maxRow * this.currentPage) { this.currentPage = Math.floor(_pageLeng / this.maxRow) - 1; } //-1などになる場合は、0にまるめる if(this.currentPage < 0) this.currentPage = 0; } return c; })();<file_sep>/src/js/cms_stage_page/CMS_PageList_ListClass.js var CMS_PageList_ListClass = (function() { /* ---------- ---------- ---------- */ var c = function(_view) { this.init(_view); } var p = c.prototype; /* ---------- ---------- ---------- */ p.init = function(_view) { this.type = Dic.ListType.DIR; this.v = {}; } /* ---------- ---------- ---------- */ p.path = "" p.registParent = function (_parent,_parentView,_deep,_n){ this.parent = _parent; this.parentView = _parentView; this.deep = (_deep == null) ? 0:_deep; this.numb = (_n == null) ? 0:_n; if(_parent.path == undefined)_parent.path = ""; this.path += _parent.path + this.numb + "_"; } /* ---------- ---------- ---------- */ //#Data p.getData = function (){ return this.gridData.getRecords(); } p.getDataAt = function (_n){ return this.gridData.getRecordAt(_n); } p.addData = function (_param){ this.gridData.addRecord(_param); this.update(); } p.addDataAt = function (data,_n){ this.gridData.addRecordAt(data,_n); } p.changeData = function (data,no){ this.gridData.overrideRecordAt(data,no); } p.removeData = function (no){ this.gridData.removeRecordAt(no); this.update(); } p.removeDataAll = function (no){ Storage.Util.deleteSubFiles(this.gridData.getRecordAt(no)); this.gridData.removeRecordAt(no); this.update(); } p.moveData = function (targetNo,_move){ this.gridData.moveRecord(targetNo,_move); this.update(); } p.initData = function (_data,_no){ this.no = _no; this.data = _data; this.gloupUID = _data.uid; this.gloupID = _data.id; this.gloupName = _data.name; this.gridData = new EditableView.GridClass(); this.gridData.initRecords(_data.list); this.setInitView(); this.update(); } /* ---------- ---------- ---------- */ //#setInitView var btnsCount = 0; p.setInitView = function (){ var this_ = this; var tag = ''; if(this.data.id == undefined) this.data.id = "sitemap_root"; this.uid = "sitemap_" +this.data.id; if(this.deep > 0){ var pubText = CMS_PateStateU.getStateText(this.data.state); var pubClass = CMS_PateStateU.getPubClass(this.data.state); var cmsClass = CMS_PateStateU.getCMSClass(this.data.stateCMS); tag += '<div class="_subDir '+pubClass + " " + cmsClass +'" data-no="'+this.no+'" id="'+this.uid+'" data-isOpen="1" >'; tag += ' <div class="_table _btn_dir ">'; tag += ' <div class="_cell">'; tag += ' <span data-no="'+this.no+'" class="_btn_dir_text" data-id="'+this.uid+'" data-name="'+this.data.name+'" data-myid="'+this.data.id+'">' tag += ' <span class="_icon"><i class="fa fa-folder-open fa-lg"></i> </span>'+this.data.name+pubText+'</span>'; tag += ' </div>'; tag += ' <div class="_cell _settingTD _pdt5">' tag += ' <span data-no="'+this.no+'" class=" _btn_dir_setting"><i class="fa fa-exclamation"></i> 設定</span>' tag += ' </div>'; tag += ' <div class="_cell _wideShow _cell_edit">' tag += ' <div class="_right _pdt5"><div class="_cms_btn_alpha _btn_setting_all"><i class="fa fa-level-up fa-rotate-180 "></i> まとめて設定</div></div>'; tag += ' </div>'; tag += ' <div class="_cell _wideShow _cell_pub">' tag += ' <div class="_right _pdt5"><div class="_cms_btn_alpha _btn_publish_all"><i class="fa fa-level-up fa-rotate-180 "></i> まとめて公開</div></div>'; tag += ' </div>'; tag += ' </div>'; } else{ tag += '<div id="'+this.uid+'">'; } //置換えエリア tag += ' <div class="_replaceAreaClose">'+this.getState()+'</div>'; tag += ' <div class="_replaceArea"></div>'; if(this.deep <= 1){ tag += '<div class="_btnInfo clearfix" >' tag += ' <div class="_btnAdd _btn_add _btn_add_file ss_icon _file_add2" data-tooltip2="ページ追加"></div>'; tag += '</div>'; } tag += ' <div class="clearfix _btns _btns_'+ this.path +' _show">'; tag += ' <span class="_label">先頭に追加</span>'; tag += ' <span class="_cms_btn_alpha _btn_add_t _btn_add_dir_t ss_icon _dir_add" data-tooltip="グループ追加"></span>'; tag += ' <span class="_cms_btn_alpha _btn_add_t _btn_add_html_t ss_icon _html_add" data-tooltip="見出し追加"></span>'; tag += ' <span class="_cms_btn_alpha _btn_add_t _btn_add_file_t ss_icon _file_add" data-tooltip="ページ追加"></span>'; tag += ' <span class="_label" style="margin:0 0 0 20px;">最後に追加</span>'; tag += ' <span class="_cms_btn_alpha _btn_add _btn_add_dir ss_icon _dir_add" data-tooltip="グループ追加"></span>'; tag += ' <span class="_cms_btn_alpha _btn_add _btn_add_html ss_icon _html_add" data-tooltip="見出し追加"></span>'; tag += ' <span class="_cms_btn_alpha _btn_add _btn_add_file ss_icon _file_add" data-tooltip="ページ追加"></span>'; tag += ' </div>'; tag += '</div>'; this.view = $(tag); this.parentView.append(this.view); this.v.replaceAreaClose = this.view.find('> ._replaceAreaClose'); this.v.replaceView = this.view.find('> ._replaceArea'); this.v.replaceView.append(DragControllerFileList.getDropTag(this.no)); this.v._btnInfoBtn = this.view.find('._btnInfo ._btn_add'); this.v._btnInfoBtn.click(function(){ this_.openEditFileInfo_NewFile("LAST") }); this.v.btn_setting_all = this.view.find('._btn_setting_all'); this.v.btn_setting_all.click(function(){ this_.editSubFiles() }); this.v.btn_setting_all.hover( function(){ this_.view.addClass("_hoverSetAll") }, function(){ this_.view.removeClass("_hoverSetAll") } ); this.v.btn_publish_all = this.view.find('._btn_publish_all'); this.v.btn_publish_all.click(function(){ this_.publishAll() }); this.v.btn_publish_all.hover( function(){ this_.view.addClass("_hoverPubAll") }, function(){ this_.view.removeClass("_hoverPubAll") } ); this.v.btn_dir = this.view.find('._btn_dir_text'); this.v.btn_dir.click(function(){ this_.openCloseSubDir(this_.view) }); this.v.btn_dir.bind("_closeAll",function(){ this_.closeSubDir(this_.view) }); this.v.btn_dir.bind("_openAll" ,function(){ this_.openSubDir(this_.view) }); // this.v.btn_dir.hover( // function(event){this_.showFlowtPreview(this); event.stopPropagation();}, // function(){Float_Preview.stageOut();} // ); CMS_PageList_ListDB.add_(this.v.btn_dir); //初期開閉の判別 if(this.data.id == "sitemap_root"){ this.isInitOpen = true; } else{ if(CMS_StatusFunc.checkSitemapDirOpens_by_id(this.data.id)){ this.isInitOpen = true; } else{ this.isInitOpen = false; this.closeSubDir(this.view); } } if(this.isInitOpen){ this.v.replaceAreaClose.hide(); } this.v.btn_add_t = this.view.find('._btn_add_t'); this.v.btn_add_t.hover( function(){this_.firstDrops.addClass("_active")}, function(){this_.firstDrops.removeClass("_active")} ); this.v.btn_add = this.view.find('._btn_add'); this.v.btn_add.hover( function(){this_.lastDrops.addClass("_active")}, function(){this_.lastDrops.removeClass("_active")} ); this.v.btn_setting = this.view.find('._btn_dir_setting'); this.v.btn_setting.click(function(){ this_.showSetting(this); }); this.v.add_dir_t = this.view.find('> ._btns > ._btn_add_dir_t'); this.v.add_dir = this.view.find('> ._btns > ._btn_add_dir'); this.v.add_dir_t .click( function(){ this_.openEditFileInfo_NewDir("FIRST") }); this.v.add_dir .click( function(){ this_.openEditFileInfo_NewDir("LAST") }); this.v.add_file_t = this.view.find('> ._btns > ._btn_add_file_t'); this.v.add_file = this.view.find('> ._btns > ._btn_add_file'); this.v.add_file_t .click( function(){ this_.openEditFileInfo_NewFile("FIRST") }); this.v.add_file .click( function(){ this_.openEditFileInfo_NewFile("LAST") }); if(this.deep > 0){ DragControllerFileList.setDrag(this.parent,this.view,DragController.FILE_DROP); } this.v._btn_add_html_t = this.view.find('> ._btns > ._btn_add_html_t'); this.v._btn_add_html = this.view.find('> ._btns > ._btn_add_html'); this.v._btn_add_html_t .click( function(){ this_.openEditFileInfo_NewHTML("FIRST") }); this.v._btn_add_html .click( function(){ this_.openEditFileInfo_NewHTML("LAST") }); } p.getState = function(){ return ""; } p.showSetting = function(_tar){ var no = Number($(_tar).attr("data-no")); CMS_PageList_ListEditNo = no; this.openEditFileInfo_EditDir(no); } // p.showFlowtPreview = function(_tar){ // var tar = $(_tar); // var param = { id: tar.data("myid"), name: tar.data("name") } // var xy= { x:tar.offset().left, y:tar.offset().top } // Float_Preview.stageIn(Dic.ListType.DIR,xy,param); // } /* ---------- ---------- ---------- */ p.isInitOpen /* ---------- ---------- ---------- */ //#メニュー開閉 ディレクトリクリック時にコール p.openCloseSubDir = function (tar){ //ファイルドラッグ後にコールされるので、そのときはブロック if(DragControllerFileList.isDraging())return; // if(tar.attr("data-isOpen") == "1"){ this.closeSubDir(tar); } else { this.openSubDir(tar); } CMS_PageListViewTree.saveDirManager(); } p.closeSubDir = function (tar){ tar.addClass("_close"); tar.find("._replaceAreaClose:first").show(); tar.find("._replaceArea:first").hide(); tar.find("._btns:last").removeClass("_show"); tar.find("._icon:first").html('<i class="fa fa-folder fa-lg"></i> '); tar.attr("data-isOpen","0"); } p.openSubDir = function (tar){ if(this.isInitOpen == false){ this.isInitOpen = true; this.update(); } tar.removeClass("_close"); tar.find("._replaceAreaClose:first").hide(); tar.find("._replaceArea:first").slideDown(200); tar.find("._btns:last").addClass("_show"); tar.find("._icon:first").html('<i class="fa fa-folder-open fa-lg"></i> '); tar.attr("data-isOpen","1"); } /* ---------- ---------- ---------- */ //#フォルダ・ファイルの作成・編集・削除 //新規フォルダ p.openEditFileInfo_NewDir = function (_pos){ if(window.isLocked(true))return; this.openEditFileInfo_comp("dir_new",FileInfoView_U.getParam("dir_new"),"",_pos); } p.openEditFileInfo_NewFile = function (_pos){ if(window.isLocked(true))return; var extra = { uid : this.gloupUID } // var ss = FileInfoView_U.getParam("file_new",{ uid : this.gloupUID }); // console.log([ss.id,ss.dir,ss.name]); // return this.openEditFileInfo_comp("file_new",FileInfoView_U.getParam("file_new",extra),"",_pos); } p.openEditFileInfo_NewHTML = function (_pos){ if(window.isLocked(true))return; this.openEditFileInfo_comp("html_new",FileInfoView_U.getParam("html_new"),"",_pos); } //それぞれ編集 p.openEditFileInfo_EditDir = function (_no){ FileInfoView.stageIn("dir_edit",this.parent,this.parent.getDataAt(_no)); } p.openEditFileInfo_EditFile = function (_no){ editOriginData = clone(this.getDataAt(_no)); FileInfoView.stageIn("file_edit",this,this.getDataAt(_no)); } p.openEditFileInfo_EditHTML = function (_no){ editOriginData = clone(this.getDataAt(_no)); FileInfoView.stageIn("html_edit",this,this.getDataAt(_no)); } //それぞれのコールバック p.openEditFileInfo_comp = function (_action,_param,_extra,_pos){ var this_ = this; //自動テスト用 window._lastAddFile = _param; //new if(_pos == "FIRST"){ if (_action == "dir_new") this.addDataAt(_param,0); if (_action == "file_new") this.addDataAt(_param,0); if (_action == "html_new") this.addDataAt(_param,0); } else { if (_action == "dir_new") this.addData(_param); if (_action == "file_new") this.addData(_param); if (_action == "html_new") this.addData(_param); } //edit if(_action == "dir_edit"){ if(_extra =="delete"){ var s1 = "削除の確認" var s2 = "グループ内のページも削除されますが、削除しますか?" CMS_ConfirmView.stageIn(s1,s2,function(){ this_.removeDataAll(CMS_PageList_ListEditNo); },"DELL") } else{ this.changeData(_param,CMS_PageList_ListEditNo); } } if(_action == "file_edit" || _action == "html_edit"){ //ファイル編集削除の場合は、出力ファイル名の変更を行う editedData = clone(this.getDataAt(CMS_PageList_ListEditNo)); if(_extra =="delete"){ CMS_PageListViewTree.deleteFile(editedData); this.removeData(CMS_PageList_ListEditNo); } else{ CMS_PageListViewTree.changeFileName(editedData,editOriginData); this.changeData(_param,CMS_PageList_ListEditNo); } } this.update(); } /* ---------- ---------- ---------- */ //#Update p.tID; p.update = function (){ //ドラッグ時になんどもコールされるので、ディレイ var this_ = this; if(this.tID) clearTimeout(this.tID); this.tID = setTimeout(function(){ this_.update_delay(); },50); } p.update_delay = function (){ //初期に開いてないディレクトリは、レンダリングしない //開いたときに、レンダリング if(this.isInitOpen == false) return; // var this_ = this; var list = this.gridData.getRecords(); if(this.nodeList != undefined){ for (var i = 0; i < this.nodeList.length ; i++) { this.nodeList[i].remove(); this.nodeList[i] = null; } } this.nodeList = []; this.v.replaceView.html(""); this.v.replaceView.append(DragControllerFileList.getDropTag(0)); var dirCount = 0; for (var i = 0; i < list.length ; i++) { if(list[i]){ var type = list[i].type; var name = list[i].name; var name15 = CMS_U.roundText(list[i].name,15); if(type == Dic.ListType.DIR ){ var filelist = new CMS_PageList_ListClass(); filelist.registParent(this_,this_.v.replaceView,this.deep+1,dirCount++); filelist.initData(list[i],i); this.nodeList.push(filelist); } if(type == Dic.ListType.PAGE){ var page = new CMS_PageList_PageClass(this, this.v.replaceView , list[i],i); this.nodeList.push(page); } if(type == Dic.ListType.HTML){ var tag = '<div class="_table _btn_html" data-no="'+i+'">' tag += ' <div class="_cell" style="width:17px;"><i class="fa fa-lg fa-font" style="margin:0px 2px 0 2px;"></i></div>'; tag += ' <div class="_cell"><span class="_btn_file_text">'+name15+'</span></div>'; // tag += ' <div class="_cell _settingTD " ><span data-no="'+i+'" class="_btn_html_setting ss_icon _fileinfo2"></span></div>'; tag += ' <div class="_cell _settingTD " ><span data-no="'+i+'" class="_btn_html_setting"><i class="fa fa-exclamation"></i> 設定</span></div>'; tag += ' <div class="_cell _wideShow " style="width:400px;"></div>'; tag += '</div>'; this.v.replaceView.append(tag); } this.v.replaceView.append(DragControllerFileList.getFileDropTag(i+1)); } } // var drops = this.v.replaceView.find("._dropArea"); this.firstDrops = drops.eq(0); this.lastDrops = drops.eq(drops.length-1); //ドラッグイベントアサイン DragControllerFileList.setDrag(this,this.v.replaceView.find(' > ._btn_page'),DragController.FILE_DROP) DragControllerFileList.setDrag(this,this.v.replaceView.find(' > ._btn_html'),DragController.FILE_DROP) DragControllerFileList.setDrop(this,this.v.replaceView.find(' > ._dropArea'),DragController.FILE_DROP); //HTMLの[i]ボタン this.v.btn_html_setting = this.v.replaceView.find(' > ._table > ._cell > ._btn_html_setting'); this.v.btn_html_setting.click( function(event){ this_.clickHTML(this);event.stopPropagation(); }); this.isRemoved = false; CMS_PageListViewTree.updatedSitemap(); CMS_PageDB.updateSitemap(); } //HTML設定クリック p.clickHTML = function(_tar){ var no = Number($(_tar).attr("data-no")); CMS_PageList_ListEditNo = no; this.openEditFileInfo_EditHTML(no); } p.remove = function(){ this.isRemoved = true; if(this.nodeList){ for (var i = 0; i < this.nodeList.length ; i++) { this.nodeList[i].remove(); } } this.nodeList = null; } /* ---------- ---------- ---------- */ //まとめて編集 p.editSubFiles = function(){ var this_ = this; SitemapEditView.stageIn(this.data,function(_list,_changeNameList){ this_.update(); this_.renameAll(_changeNameList); }); } p.renameAll = function(_a){ if(_a == undefined) return; if(_a.length == 0) return; Storage.Util.renameAll(_a); } //まとめて書き出し p.publishAll = function(){ if(window.isLocked(true))return; // this.subPages = []; this.getAllPage(this.gridData.getRecords()); BatchPublishView.stageIn(this.subPages); } p.getAllPage = function(_list){ for (var i = 0; i < _list.length ; i++) { if(_list[i].type == Dic.ListType.DIR){ this.getAllPage(_list[i].list); } if(_list[i].type == Dic.ListType.PAGE){ this.subPages.push(_list[i]) } } } return c; })();<file_sep>/src/js/cms_view_inspect/InspectView.Footer.js InspectView.Footer = (function(){ var view; var v = {}; function init(_view){ view = $("<div>"); var tag = "" tag += '<table>'; tag += ' <tr>'; tag += ' <td><span class="_cms_btn_alpha _btn_json_im ss_inspect2 _edit"></span></td>'; //tag += ' <td>' // tag += ' <div class="_hoverSet">' // tag += ' <span class="_cms_btn_alpha _btn_json_im ss_inspect2 _edit"></span>' // tag += ' <div class="_hoverItems">' // tag += ' <span class="_cms_btn_alpha _btn_json_im ss_inspect2 _edit"></span>' // tag += ' <span class="_cms_btn_alpha _btn_addPreset ss_inspect2 _my"></span>' // tag += ' </div>' // tag += ' </div>' //tag += ' </td>'; // tag += ' <td><span class="_cms_btn_alpha _btn_json_im ss_inspect2 _edit"></span></td>'; // tag += ' <td><span class="_cms_btn_alpha _btn_addPreset ss_inspect2 _my"></span></td>'; tag += ' <td>' tag += ' <div class="_hoverSet">' tag += ' <span class="_cms_btn_alpha _btn_copy ss_inspect2 _copipe"></span>' tag += ' <div class="_hoverItems">' tag += ' <span class="_cms_btn_alpha _btn_copy ss_inspect2 _copipe_copy" '+TIP("#+C","R")+'></span>' tag += ' <span class="_cms_btn_alpha _btn_cut ss_inspect2 _copipe_cut" '+TIP("#+X","R")+'></span>' tag += ' <span class="_cms_btn_alpha _btn_past ss_inspect2 _copipe_past" '+TIP("#+V","R")+'></span>' tag += ' <span class="_cms_btn_alpha _btn_past2 ss_inspect2 _copipe_past2" '+TIP("#+Shift+V","R")+'></span>' tag += ' </div>' tag += ' </div>' tag += ' </td>'; // tag += ' <td>' // tag += ' <div class="_hoverSet">' // tag += ' <span class="_cms_btn_alpha _btn_dup ss_inspect2 _dup" '+TIP("#+D")+'></span>' // tag += ' <div class="_hoverItems">' // tag += ' <span class="_cms_btn_alpha _btn_dup ss_inspect2 _dup" '+TIP("#+D")+'></span>' // tag += ' </div>' // tag += ' </div>' // tag += ' </td>'; tag += ' <td><span class="_cms_btn_alpha _btn_dup ss_inspect2 _dup" '+TIP("#+D")+'></span></td>'; // tag += ' <td><span class="_cms_btn_alpha ss_inspect2 _dup" '+TIP("#+D")+'></span></td>'; tag += ' <td><span class="_cms_btn_alpha _btn_del ss_inspect2 _del" '+TIP("#+DELL")+'></span></td>'; tag += ' <td>' tag += ' <div class="_hoverSet">' tag += ' <span class="_cms_btn_alpha _btn_next ss_inspect2 _move"></span>' tag += ' <div class="_hoverItems" style="top:-65px;">' tag += ' <span class="_cms_btn_alpha _btn_prev2 ss_inspect2 _move_top2"></span>' tag += ' <span class="_cms_btn_alpha _btn_prev ss_inspect2 _move_top" '+TIP("#+↑","R")+'></span>' tag += ' <span class="_cms_btn_alpha _btn_next ss_inspect2 _move_bottom" '+TIP("#+↓","R")+'></span>' tag += ' <span class="_cms_btn_alpha _btn_next2 ss_inspect2 _move_bottom2"></span>' tag += ' </div>' tag += ' </div>' tag += ' </td>'; tag += ' </tr>'; tag += '</table>'; view.html(tag); setBtn(); return view; } function setBtn(){ view.find("._btn_dup") .on("click",function(){ clickAnim(this);window.sc.duplicateCurrent()}); view.find("._btn_del") .on("click",function(){ clickAnim(this);window.sc.deleteCurrent();}); view.find("._btn_copy") .on("click",function(){ clickAnim(this);window.sc.copyCurrent(); }); view.find("._btn_cut") .on("click",function(){ clickAnim(this);window.sc.cutCurrent(); }); view.find("._btn_past") .on("click",function(){ clickAnim(this);window.sc.pastCurrent()}); view.find("._btn_past2") .on("click",function(){ clickAnim(this);window.sc.pastCurrent2()}); view.find("._btn_prev2") .on("click",function(){ clickAnim(this);window.sc.moveTopCurrent()}); view.find("._btn_prev") .on("click",function(){ clickAnim(this);window.sc.moveUpCurrent()}); view.find("._btn_next") .on("click",function(){ clickAnim(this);window.sc.moveDownCurrent()}); view.find("._btn_next2") .on("click",function(){ clickAnim(this);window.sc.moveBottomCurrent()}); view.find("._btn_json_im") .on("click",function(){ clickAnim(this);window.sc.editJSON()}); view.find("._btn_addPreset") .on("click",function(){ clickAnim(this);window.sc.addToMyBlock()}); } function clickAnim(_this){ var tar = $(_this); tar.css("opacity","0.25"); setTimeout(function(){ tar.css("opacity","1"); },100); } return { init:init } })(); <file_sep>/js_cms/_cms/backup.php <?php /** * JS_CMS -- realtime website development web application * http://js-cms.jp/ * Copyright 2015 <NAME> - <EMAIL> * licensed under the MIT licenses. */ define('CMS', true); require_once("./setting/setting.php"); require_once("./storage.funcs.php"); require_once("./storage.login.php"); /* ! ---------- setting ---------- ---------- ---------- ---------- */ header("Content-Type: application/json; charset=utf-8"); /* ! ---------- input ---------- ---------- ---------- ---------- */ $action = getVAL("action","",""); $diff = getVAL("diff","",""); $zipDir = getVAL("zipDir","","dir"); $siteDir = getVAL("siteDir","","dir"); $targetDirs = getVAL("targetDirs","","paths2"); /* ! ---------- functions ---------- ---------- ---------- ---------- */ function isTarget($tars,$key){ $b = false; for ($i = 0 ; $i < count($tars); $i++) { if(strpos($key,$tars[$i]) === 0) $b = true; } if(strpos($key,"/.") !== false){ $b =false; } if(strpos($key,"/..") !== false){ $b =false; } return $b; } /* ! ---------- readFileList ---------- ---------- ---------- ---------- */ if( $action == "readFileList" ){ $dir = opendir($zipDir); $dirs = array(); $files = array(); while( $file_name = readdir( $dir ) ){ if (substr($file_name, 0,1) !=".") { if(! is_dir($zipDir.$file_name)){ array_push($files,$file_name); } } } $json = ""; $json.='{"files":['; $a = array(); for ($i = 0 ; $i < count($files); $i++) { $s = '{'; $s .= '"name":"'.$files[$i].'",'; $s .= '"time":"'.filemtime($zipDir.$files[$i]).'",'; $s .= '"size":"'.filesize($zipDir.$files[$i]).'"'; $s .= '}'; array_push($a,$s); } $json .= join(",",$a); $json.=']}'; echo($json); closedir($dir); } /* ! ---------- readDirList ---------- ---------- ---------- ---------- */ if( $action == "readDirList" ){ $dir_name = getVAL("dir_name","","dir"); if(! is_filePath($dir_name)) status_error("invalid path"); function getList($dir_path,$isDir,$isFile){ $list = array(); $dir = opendir($dir_path); while($filename = readdir($dir)){ if($filename == '.' || $filename == '..') continue; if(substr($filename ,0 ,1) == ".") continue; $path = $dir_path.$filename; if(is_dir($path)){ if($isDir){ echo('"'.$path.'",'); } } else { if($isFile){ echo('"'.$path.'",'); } } } closedir($dir); } echo('{'); echo('"dirs":['); getList($dir_name,true,false); echo('""],'); echo('"files":['); getList($dir_name,false,true); echo('""]'); echo('}'); } /* ! ---------- getDiffList ---------- ---------- ---------- ---------- */ if( $action == "getDiffList" ){ $matchList = array(); $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($siteDir)); $today = date("U"); $json = ""; $json.='{"files":['; foreach ($iterator as $key=>$value) { if(isTarget($targetDirs,$key)){ $sabun = ($today-filemtime($key)) / 60; if($sabun < $diff){ $s = '"'.$key.'" '; array_push($matchList,$s); } } } $json .= join(",",$matchList); $json .= ']}'; echo($json); } /* ! ---------- createDiffZip ---------- ---------- ---------- ---------- */ if( $action == "createDiffZip" ){ if(IS_DEMO) status_success(); $zipFileName= $zipDir.date("Ymd_His")."_".getR(5)."_diff.zip"; ini_set("max_execution_time", 600); ini_set('memory_limit','64M'); $zip = new ZipArchive(); if ($zip->open($zipFileName, ZIPARCHIVE::CREATE) !== TRUE) { die ("Could not open archive"); } //$matchList = array(); $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($siteDir)); $today = date("U"); foreach ($iterator as $key=>$value) { if(isTarget($targetDirs,$key)){ $sabun = ($today-filemtime($key)) / 60; if($sabun < $diff){ $key2 = $key; $key2 = str_replace("../","",$key); $key2 = str_replace("./","",$key2); $zip->addFile(realpath($key), $key2) or die ("ERROR: Could not add file: $key"); } } } $zip->close(); status_success(); } /* ! ---------- createZip ---------- ---------- ---------- ---------- */ if( $action == "createZip" ){ if(IS_DEMO) status_success(); $zipFileName = $zipDir.date("Ymd_His")."_".getR(5).".zip"; ini_set("max_execution_time", 600); ini_set('memory_limit','64M'); $zip = new ZipArchive(); if ($zip->open($zipFileName, ZIPARCHIVE::CREATE) !== TRUE) { die ("Could not open archive"); } $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($siteDir)); foreach ($iterator as $key=>$value) { if(isTarget($targetDirs,$key)){ $key2 = $key; $key2 = str_replace("../","",$key); $key2 = str_replace("./","",$key2); $zip->addFile(realpath($key), $key2) or die ("ERROR: Could not add file: $key"); } } $zip->close(); status_success(); } /* ! ---------- deleteFile ---------- ---------- ---------- ---------- */ if( $action == "deleteFile" ){ if(IS_DEMO) status_success(); $n = $zipDir.getVAL("filename","","path"); if(unlink($n)){ status_success(); } else{ status_error("failed to delete file"); } } <file_sep>/src/js/cms_data/CMS_Data.MyTag.p1.js //テンプレート用の置換えキー登録 //一回だけでなく、設定ファイルを編集した場合は、何度かロードされる CMS_Data.MyTag = (function(){ function init(){ } var tmp = {} function getURL(ss){ var r = "?r=" + DateUtil.getFormattedDate(new Date(), "YYYYMMDD_hhmmss"); return CMS_Path.ASSET.REL + ss.dir + "/" + ss.id + ".json" + r; } /* ---------- ---------- ---------- */ //利用できるMyタグファイル一覧を取得 function loadList(_callback) { var files = MYTAG_PAGE_LIST; Dic.MyTagList = (function(_list){ var dir = Dic.DirName.MYTAG; var o = [] if(_list.length == 0){ o.push(Dic.MyTagListDef); } else{ for (var i = 0; i < _list.length ; i++) { o.push({ dir: dir, id: _list[i].id, type: Dic.PageType.CMS_MYTAG, name: _list[i].name }); } } return o; })(files); load(_callback); } function _isFile(_s) { if(_s.indexOf(".") != -1) { return FileU.isEditableFile(_s); } else{ return false; } } /* ---------- ---------- ---------- */ function getParam_by_ID(_id) { var ls = Dic.MyTagList; for (var i = 0; i < ls.length ; i++) { if(ls[i].id == _id){ return ls[i]; } } return null; } /* ---------- ---------- ---------- */ //Myタグファイルをロードする function load(_callback) { var kyes = Dic.MyTagList; loadCount = 0; loadSum = kyes.length; for (var i = 0; i < kyes.length ; i++) { var ts = new CMS_Data.TextLoader("JSON", getURL(kyes[i]), function(_json) { setInitData(_json,this.myid); loaded(_callback); }, function() { setInitData({},this.myid); loaded(_callback); } ); ts.myid = kyes[i].id; } } var loadCount; var loadSum; function loaded(_callback) { loadCount++; if(loadCount == loadSum){ if(_callback) _callback(); } } //データ登録 function setInitData(_json,_myid) { if (!tmp) tmp = {}; var name = ""; if(!_json.meta)_json.meta = {}; if(!_json.meta.name)_json.meta.name = ""; setName(_json.meta.name,_myid); tmp[_myid] = _parseData(_json); } //JSONファイルから、meta.nameを取得し、名称にセットする function setName(_name,_myid) { var kyes = Dic.MyTagList; for (var i = 0; i < kyes.length ; i++) { if(kyes[i].id == _myid){ if(_name){ kyes[i].name = _name; } } } } /* ---------- ---------- ---------- */ //ファイル保存したときに、リロードする function loadAt(_id) { var pr = { id : _id, dir : Dic.DirName.MYTAG } var ts = new CMS_Data.TextLoader("JSON", getURL(pr), function(_json) { setInitData(_json,this.myid); }, function() { setInitData({},this.myid); } ); ts.myid = _id; } /* ---------- ---------- ---------- */ function _parseData(_json) { return CMS_Data.MyTagU.parseData(_json); } if(window["_cms"] ==undefined) window._cms = {}; window._cms.showsMyTags = function(){ console.log(tmp); } /* ---------- ---------- ---------- */ //各ページ保存時にコールされ、keyだったら、データをリロードする function savedPage(_id,_dir){ var ss = Dic.MyTagList; var id = ""; for (var i = 0; i < ss.length ; i++) { if(ss[i].id == _id){ if(ss[i].dir == _dir){ id = ss[i].id; } } } if(id){ update(id); loadAt(_id); } } function update(_id){ tmp[_id] = null; } function getData() { return tmp; } //フラットなリストを返す function getDataFlat() { var a = []; for (var n in tmp){ a = a.concat(tmp[n]); } return a; } return { init:init, loadList:loadList, getParam_by_ID:getParam_by_ID, savedPage:savedPage, getData:getData, getDataFlat:getDataFlat } })();<file_sep>/src/js/cms_util/AnimU.js var AnimU = (function(){ var func_; function attention(_param){ var v = _param.v; var d = (_param.d) ? _param.d/1000:0; if(func_)func_.remove(); func_ = new serial_([ d , function () { v.addClass("_current"); } ,0.15, function () { v.removeClass("_current"); } ]); func_.start(); } var serial_ = (function() { var c = function(_args) { this.args = _args; this.currentNo = 0; this.playingFlg = false; this.isPause = false; } var p = c.prototype; p.start = function( ) { if(! this.playingFlg){ this.playingFlg = true; this.execute_core(); } } p.execute_core = function ( ) { if (this.playingFlg) { if (this.currentNo < this.args.length) { var command = this.args[this.currentNo]; if (typeof(command) != "number") { command(); this.execute_next(); }else { var this_ = this; setTimeout(function(){ this_.execute_next() },command * 1000); } } else { this.funish(); } } } p.execute_next = function ( ) { if(this.isPause) return; if(this.playingFlg){ this.currentNo++; this.execute_core(); } } p.funish = function ( ) { this.playingFlg = false; this.init(); } p.pause = function ( ) { this.isPause = true; } p.restart = function ( ) { this.isPause = false; this.execute_next(); } p.jump = function ( _n) { this.currentNo = _n-1; } p.init = function ( ) { this.playingFlg = false; this.currentNo = 0; } p.remove = function ( ) { this.currentNo = 0; this.playingFlg = false; } return c; })(); return { attention: attention, serial_: serial_ }})(); <file_sep>/js_cms/_cms/upload.php <?php /** * JS_CMS -- realtime website development web application * http://js-cms.jp/ * Copyright 2015 <NAME> - <EMAIL> * licensed under the MIT licenses. */ define('CMS', true); require_once("./setting/setting.php"); require_once("./storage.funcs.php"); require_once("./storage.login.php"); //usleep(1000000/2); /* ! ---------- pre ---------- ---------- ---------- ---------- */ header("Content-Type: application/json; charset=utf-8"); /* ! ---------- input ---------- ---------- ---------- ---------- */ $action = getVAL("action","",""); if($action == "") status_error("invalid action name"); if(! is_action($action)) status_error("invalid action name"); if($action=="check"){ $s = ""; $s .= "{"; $s .= '"post_max_size":"'.ini_get("post_max_size").'",'; $s .= '"upload_max_filesize":"'.ini_get("upload_max_filesize").'",'; $s .= '"memory_limit":"'.ini_get("memory_limit").'"'; $s .= "}"; // $s .= "{"; // $s .= '"post_max_size":"8M",'; // $s .= '"upload_max_filesize":"2M",'; // $s .= '"memory_limit":""'; // $s .= "}"; echo($s); exit(); } if($action=="checkDir"){ $upload_dir = getVAL("upload_dir","","dir"); if(! is_filePath($upload_dir)) status_error("invalid path"); if(isWritableDir($upload_dir)){ status_success(); }else{ status_error("can not write to directory"); } } if($action == "upload64"){ if(IS_DEMO){ status_success(); } $canvas = $_POST["base64"]; $canvas = preg_replace("/data:[^,]+,/i","",$canvas); $canvas = base64_decode($canvas); $image = imagecreatefromstring($canvas); imagesavealpha($image, TRUE); // $fileName = getVAL('fileName',"",""); if($fileName == "") status_error("invalid name"); $upload_dir = getVAL("upload_dir","","dir"); if(! is_filePath($upload_dir)) status_error("invalid path"); if(isWritableDir($upload_dir) == false){ status_error("can not write to directory"); } $uploadPath = $upload_dir.$fileName; if (imagepng($image ,$uploadPath)) { status_success(); } else { status_error("Failed to move uploaded file"); } } if($action=="upload"){ if(IS_DEMO){ status_success(); } //error check if (!isset($_FILES['upfile']['error']) || is_array($_FILES['upfile']['error']) ) { status_error("Invalid parameters"); } switch ($_FILES['upfile']['error']) { case UPLOAD_ERR_OK: break; case UPLOAD_ERR_NO_FILE: status_error("No file sent"); case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: status_error("Exceeded filesize limit"); default: status_error("Unknown errors"); } // $fileName = getVAL('fileName',"",""); if($fileName == "") status_error("invalid name"); $upload_dir = getVAL("upload_dir","","dir"); if(! is_filePath($upload_dir)) status_error("invalid path"); if(isWritableDir($upload_dir) == false){ status_error("can not write to directory"); } $uploadtempPath = $_FILES["upfile"]["tmp_name"]; $uploadPath = $upload_dir.$fileName; if (is_uploaded_file($uploadtempPath)) { if (move_uploaded_file($uploadtempPath, $uploadPath)) { status_success(); } else { status_error("Failed to move uploaded file"); } } else { status_error("Unknown errors."); } } exit(); <file_sep>/src/js/cms_main/CMS_ScreenManager.js /** * スクリーン情報管理 * カンバスのリサイズや、高、幅などの管理を行う */ var CMS_StatusW; var CMS_StatusH; var CMS_ScreenManager = (function(){ var MAX_W = 800 var currentSubPageView; var v = {} function init(){ CMS_StatusW = $(window).width(); CMS_StatusH = $(window).height(); if(CMS_StatusW < MAX_W)CMS_StatusW = MAX_W; //リアルタイムにマウス位置取得 $(window).mousemove(function(e){ CMS_Status.mouseX =e.clientX; CMS_Status.mouseY =e.clientY; }); //リサイズ時に、画面サイズを更新 $(window).resize(resize); v.stageView = $("#CMS_PagesView"); v.sideView = $("#CMS_PageListView"); v.sideView.scroll(function () { Storage.Memo.setSideMenuY(v.sideView.scrollTop()); }); } /* ---------- ---------- ---------- */ //リサイズイベント //CMS_ScreenManager.registResize var _winds = [] function registResize(_f){ _winds.push(_f) } function setSubView(_view){ currentSubPageView = _view } /* ---------- ---------- ---------- */ var tID_re; function resize(e){ //jqのresizableイベントに、windowリサイズも反応するため、 //フィルターをかける if (e.target == window){ if(tID_re) clearTimeout(tID_re); tID_re = setTimeout(function(){ resize_core() },200); } } function resize_core(){ CMS_StatusW = $(window).width(); CMS_StatusH = $(window).height(); if(CMS_StatusW < MAX_W)CMS_StatusW = MAX_W; if(currentSubPageView != null){ currentSubPageView.resize(); } for (var i = 0; i < _winds.length ; i++) { if(_winds[i]){ _winds[i](); } } } /* ---------- ---------- ---------- */ /* ページに要素を追加、削除するときに、要素が一回リセットされ。 ページ高さが0になるので、それを回避するため、 一定作業ごとに、min-heigithを設定し、最低限の高さをほしょうする。 ページ移動で、リセット */ var scrollView; function initCanvas(){ scrollView = $('#CMS_PagesView'); } var current; function memoryCurrentScroll(){ if(!current) return; var c = _getScrollPage(current); c[1] = scrollView.scrollTop(); } function setCurrentScroll(_param){ if(!scrollView) initCanvas(); var id = CMS_Path.PAGE.getAbsPath(_param.id,_param.dir); current = id; var r = _getScrollPage(id)[1]; scrollView.scrollTop(r); } var scrolls = []; function _getScrollPage(_id){ var b = false; var tar; for (var i = 0; i < scrolls.length ; i++) { if(scrolls[i][0] == _id) { tar = scrolls[i]; b = true; } } if(!b){ tar = [_id,0]; scrolls.push(tar); } return tar; } /* ---------- ---------- ---------- */ //ページのブロックを選択したとコールされる //スクロール位置の調整 function updatePageScroll(_top,_smooth){ if(_smooth == undefined) _smooth = true; var H = CMS_StatusH; var SC = v.stageView.scrollTop(); var tarY = _top + SC; var currentY = H + SC; var b = false; if (tarY > currentY - 100) b = true; if (tarY < SC) b = true; if (b){ tarY2 = tarY - (H / 2) if(_smooth){ v.stageView.animate( { scrollTop:tarY2 }, { duration: 100}); } else{ v.stageView.scrollTop(tarY2); } } } /* ---------- ---------- ---------- */ return { init:init, setSubView:setSubView, registResize:registResize, memoryCurrentScroll:memoryCurrentScroll, setCurrentScroll:setCurrentScroll, updatePageScroll:updatePageScroll } })();<file_sep>/src/js/cms_util/URL_U.js var URL_U = (function(){ function trimSS(_u){ if(!_u)return ""; _u = _u.split("///////").join("/"); _u = _u.split("/////").join("/"); _u = _u.split("///").join("/"); _u = _u.split("//").join("/"); return _u } function treatURL(_u){ if(isMailTo(_u))return _u; if(isFullPath(_u)){ var sep = "://" var s = _u.split(sep); _u = s[0] + sep + trimSS(s[1]) } else{ _u = trimSS(_u); } return _u; } function treatDirName(_dir){ if(_dir == undefined) return "" if(_dir == "") return "" if(_dir == "/") return "/"; if(_dir.indexOf("//") != -1){ _dir = trimSS(_dir); } if(_dir.indexOf("../") == 0 ){ // } else{ if(_dir.charAt(0) != "/") _dir = "/" + _dir } if(_dir.charAt(_dir.length-1) != "/") _dir = _dir + "/" return _dir; } function isMailTo (_u){ if(_u.indexOf("mailto:") == 0) return true; return false; } function isFullPath (_u){ if(_u.indexOf("http://") == 0) return true; if(_u.indexOf("https://") == 0) return true; if(_u.indexOf("mailto:") == 0) return true; if(_u.indexOf("javascript:") == 0) return true; return false; } function isTextFile(_s){ if(_s == null) return false; var b = false; var ext = getExtention(_s) if(ext == "") b = true; if(ext == "html") b = true; if(ext == "htm") b = true; if(ext == "css") b = true; if(ext == "js") b = true; if(ext == "json") b = true; if(ext == "xml") b = true; if(ext == "csv") b = true; if(ext == "tsv") b = true; if(ext == "as") b = true; if(ext == "php") b = true; return b; } function getCurrentDir(_s,_deep){ if(_deep == undefined) _deep = 1; if(_deep == 0) return "/" _s = _s.split("#")[0]; var ss = _s.split("/"); var a = [] for (var i = 0; i < _deep ; i++) { a.push( ss[ss.length - (2 + i)]) } return "/" + a.reverse().join("/") } function getFileID(_s){ var s = getFileName(_s) return s.split(".")[0] } function getFileName(_s){ var ss = _s.split("/") var fn = ss[ss.length-1] fn = fn.split("#")[0] fn = fn.split("?")[0] return fn //http://192.168.1.23:1000/release/_cms/index.html } function getExtention(_s){ if(_s == null)return ""; if(typeof _s == "number") _s = String(_s); var p1 = _s.split("#")[0]; var p2 = p1.split("?")[0]; var ss = p2.split("."); if(ss.length == 1)return ""; var ex = ss[ss.length-1]; if(ex.indexOf("/") != -1) return ""; return ex.toLowerCase(); } function getURLParam(_s){ if(_s ==null)return {}; var url = _s; var p1 = url.split("#")[0]; var p2 = p1.split("?")[1]; if(p2.length == 0) return; var ps = p2.split("&"); var o = {} for (var i = 0; i < ps.length ; i++) { var s = ps[i].split("=") o[s[0]] = s[1] } return o } function getBaseDir(_s){ _s = _s.split("?")[0]; var a = _s.split("/"); var u = ""; for (var i = 0; i < a.length -1 ; i++) { u += a[i] + "/" } return u } var protcolList = ["http://","https://","//"]; //現在のHTMLの絶対パス、相対パスのCSSなどのファイルから、 //絶対パスを生成する。 function getDomain(_s){ if(_s ==null)return ""; var out = "" if(_s ==null) return out; for (var i = 0; i < protcolList.length ; i++) { var ss = protcolList[i] if(_s.substr(0, ss.length) == ss){ var a = _s.split(ss); var a = a[1].split("/"); out += ss + a[0] + "/"; } } return out; } function getDomain_and_dir(_s){ if(_s ==null)return ""; var out = ""; _s = _s.split("?")[0] var a = _s.split("/"); if(a.length < 4) return _s; for (var i = 0; i < a.length-1 ; i++) { out += a[i] + "/" } return out; } function isSameDomain(_s,_s2){ if(_s ==null)return false; if(_s2 ==null)return false; var s = getDomain(_s); var s2 = getDomain(_s2); return (s == s2); } function isDomain(_s){ if(_s == null) return false; var b = false; _s = _s.split(" ").join("") _s = _s.split(" ").join("") if(_s == "") return false; if(_s.substr(0, 5) == "http:") b = true; if(_s.substr(0, 6) == "https:") b = true; if(_s.substr(0, 2) == "//") b = true; return b } // function joinURL(_s,_s2){ if(_s ==null)return ""; if(_s2 ==null)return ""; if(! isDomain(_s)) return _s2; if(isDomain(_s2)) return _s2; var a = _s2.split("../"); var ss =_s.split("/"); var u = "" var leng = ss.length - a.length for (var i = 0; i < leng ; i++) { u += ss[i] + "/" } var g = _s2.split("../").join(""); g = g.split("./").join(""); return treatURL(u + g); } function trimDomain(_s){ if(_s ==null)return ""; var d = getDomain(_s); return _s.split(d).join("") } function getRelativePath(_s,_s2){ if(_s == null)return ""; if(_s2 == null)return ""; var out = ""; if(! isSameDomain(_s,_s2)) return ""; _s = trimDomain(_s); _s2 = trimDomain(_s2); var g = _s.split("?")[0].split("/"); var ps = ""; for (var i = 0; i < g.length-1 ; i++) { if(g[i] != ""){ ps += "../"; } } return ps + _s2; } // function getHash(){ var path = window.location.hash; path = path.split("#").join(""); path = path.split("*").join(""); return path; } //URL_U.getParentDir function getParentDir(_dir){ if(_dir.charAt(_dir.length-1) != "/"){ _dir = _dir + "/"; } var a = _dir.split("/"); var s = [] for (var i = 0; i < a.length - 2; i++) { s.push(a[i]) } return s.join("/") + "/"; } /* equal(getParentDir("/aa"),"/"); equal(getParentDir("/aa/bb"),"/aa/"); equal(getParentDir("/aa/"),"/"); equal(getParentDir("/aa/bb/"),"/aa/"); equal(getParentDir("../"),"/"); equal(getParentDir("../aa/"),"../"); equal(getParentDir("../aa/bb/"),"../aa/"); */ function getPageObject(_s){ var o = {} o.dir = getBaseDir(_s); o.id = getFileName(_s); return o; } return { trimSS:trimSS, treatURL:treatURL, isMailTo:isMailTo, isFullPath:isFullPath , treatDirName:treatDirName , isTextFile:isTextFile, getCurrentDir:getCurrentDir, getFileID:getFileID, getFileName:getFileName, getExtention:getExtention, getURLParam:getURLParam, getDomain:getDomain, getDomain_and_dir:getDomain_and_dir, isSameDomain:isSameDomain, getBaseDir:getBaseDir, joinURL:joinURL, getRelativePath:getRelativePath, getHash:getHash, getParentDir:getParentDir, getPageObject:getPageObject } })(); <file_sep>/src/js/cms_main/HTMLService.js /** * JSONをHTMLにコンバートするサービス * コンバートには、設定JSONや、テンプレHTMLなども必要 */ var HTMLService = (function(){ var pageData; var param; var callback; /* ---------- ---------- ---------- */ function generateHTML(_pageData,_param,_callback){ param = _param; pageData = _pageData; callback = _callback; loadTemplate(); } var templateFileName = ""; //テンプレHTMLロード function loadTemplate(){ //JSONにされてるテンプレHTMLファイルが入る if(!pageData.meta) pageData.meta = {} var _id = CMS_Data.Template.treatTemplateName(pageData.meta); CMS_Data.Template.load(_id,function (_s,_id){ _s = setUniqueCSSFile(_s); templateFileName = _id; convert(_s); }); } //テンプレHTML内の、CSSパスにランダムパラメータをつける //キャッシュしないように function setUniqueCSSFile(_s) { _s = CMS_Data.AssetFile.overridePath(_s) return _s; } /* ---------- ---------- ---------- */ //メインのコンバート処理 function convert(_s){ //現在の書き出しページ情報をセット HTML_ExportState.setCurrent(param); //フリーレイアウト部分の初期データセット _setInitData(); //現在のページのMyタグリストをセット CMS_Data.MyTagReplace.startPublish(pageData); //メインのjson > html 変換処理 var html = _convert_main(_s); //{{FILE:sample.txt}}置換え CMS_Data.FreeFile.replace(html,function (_s){ convert_done(_s); }); } function convert_done(_s){ callback( HTMLServiceU.getReplacedHTML(_s,param) ); CMS_Data.MyTagReplace.endPublish(); } /* ---------- ---------- ---------- */ function _setInitData(){ if(pageData["body"] == undefined){ if(window["FREEPAGE_DEF_DATA"]){ var list = JSON.parse(JSON.stringify(FREEPAGE_DEF_DATA)); pageData = { meta: {}, head: {}, body: { free: [ { type: "layout.div", attr: {}, data: list }] } } } } } //JSON > HTML変換処理 var tag = ""; function _convert_main(_s){ tag = ""; for (var n in pageData.body) { if(n.indexOf("free")!= -1){ tag += "\n" tag += PageElement_HTMLService.getTag(pageData.body[n][0],"",0,true); tag += "\n" } } tag = tag.split(" ").join(" "); _s = _s.split("{{PAGE_CONTENTS}}") .join(tag); return _s; } return { generateHTML:generateHTML } })(); var HTMLServiceU = (function(){ /** * テンプレート置換えタグ * _param ... {id:"" , dir:"" , siteRoot:""} */ function getReplacedHTML(_temp,_param,_type,_isPub){ _isPub = (_isPub == undefined) ? true:_isPub; //置き換えタグチェック if(_temp.indexOf("{{") == -1) { return _temp; } //Myタグ定義ブロック関連はスルー if(PageElement_Util.isReplaceTag(_type)) return _temp; //現在の書き出しページ情報をセット HTML_ExportState.setCurrent(_param); //サイト置換えタグと、個別ページ置換えタグをマージして置換え var _temp = CMS_Data.MyTagReplace.replaceHTML(_temp); _temp = CMS_Data.MyTagReplace.replaceHTML(_temp);//置換えの置換え //ページ情報タグを書き換えて、返す return _replacedCMSTag( _temp,_isPub ); } /* ---------- ---------- ---------- */ //ページ情報タグで書き換える function _replacedCMSTag(_temp,_isPub){ if(_temp.indexOf("{{") == -1) { return _temp; } var _split = CMS_U.getSplitTextAt; var __ = getCurrentReplaceTags(); _temp = _temp.split("{{PAGE_BREADLIST}}") .join(_replaceBredList()); _temp = _temp.split("{{PAGE_DIR}}") .join(__.PAGE_DIR); _temp = _temp.split("{{PAGE_ID}}") .join(__.PAGE_ID); _temp = _temp.split("{{PAGE_NAME}}") .join(__.PAGE_NAME); _temp = _temp.split("{{PAGE_NAME.TAG}}") .join(__.PAGE_NAME_TAG); _temp = _temp.split("{{PAGE_NAME[0]}}") .join(_split(__.PAGE_NAME,0)); _temp = _temp.split("{{PAGE_NAME[1]}}") .join(_split(__.PAGE_NAME,1)); _temp = _temp.split("{{PAGE_NAME[2]}}") .join(_split(__.PAGE_NAME,2)); _temp = _temp.split("{{PAGE_NAME[3]}}") .join(_split(__.PAGE_NAME,3)); _temp = _temp.split("{{PAGE_NAME[4]}}") .join(_split(__.PAGE_NAME,4)); _temp = _temp.split("{{PAGE_TAG}}") .join(__.PAGE_TAG); _temp = _temp.split("{{PAGE_DATE}}") .join(__.PAGE_DATE); _temp = _temp.split("{{PAGE_READ}}") .join(__.PAGE_READ); _temp = _temp.split("{{PAGE_GROUP_IDS}}") .join(__.PAGE_GROUP_IDS); _temp = _temp.split("{{PAGE_GROUP_IDS[0]}}").join(_split(__.PAGE_GROUP_IDS,0," ")); _temp = _temp.split("{{PAGE_GROUP_IDS[1]}}").join(_split(__.PAGE_GROUP_IDS,1," ")); _temp = _temp.split("{{PAGE_GROUP_IDS[2]}}").join(_split(__.PAGE_GROUP_IDS,2," ")); _temp = _temp.split("{{PAGE_GROUP_NAMES}}") .join(__.PAGE_GROUP_NAMES); _temp = _temp.split("{{PAGE_PUB_DATE}}") .join(__.PAGE_PUB_DATE); _temp = _temp.split('{{DEF_DIR}}') .join(__.DEF_DIR); _temp = _temp.split('{{ASSET_DIR}}') .join(__.ASSET_DIR); _temp = _temp.split(CONST.SITE_DIR) .join((_isPub) ? __.SITE_DIR : CMS_Path.SITE.REL ); //使ってないキーを削除 _temp = _temp.replace(/{{.*?}}/g,""); return _temp; } /* ---------- ---------- ---------- */ //ぱんくず function _replaceBredList( _fileID, _dir) { var htmlAbs = CMS_Path.PAGE.ABS; var tree = CMS_Data.Sitemap.getData(); var tag = TreeAPI.getBreadListTag(htmlAbs, tree ,HTML_ExportState.getCurrent() ); tag = tag.split(TreeAPI_SITE_DIR).join(CONST.SITE_DIR); return tag; } /* ---------- ---------- ---------- */ //現在ページのページ情報タグのリストを返す function getCurrentReplaceTags(){ var pageParam = HTML_ExportState.getCurrent(); var _id = pageParam.id; var _dir = pageParam.dir; var _siteRoot = pageParam.siteRoot; if(_siteRoot == "") _siteRoot = CMS_Path.SITE.getTopRelPath_from_html(_dir); var groupIDs = CMS_Data.Sitemap.getGloupPath_by_id(_id,_dir).split("/").join(" "); var groupNAMEs = CMS_Data.Sitemap.getGloupName_by_id(_id,_dir).split("/").join(" "); var pageName = ""; var tagName = ""; var dateName = ""; var readName = ""; var current = CMS_Data.Sitemap.getData_by_id(_id,_dir); if(current != null) { pageName = current.name || ""; tagName = current.tag || ""; dateName = current.date || ""; readName = current.read || ""; } var pageName_noTag = CMS_TagU.treatTag(pageName); var o = {} o.PAGE_DIR = CMS_Path.PAGE.getAbsDirPath(_dir); o.PAGE_ID = _id; o.PAGE_NAME = pageName_noTag; o.PAGE_NAME_TAG = pageName; o.PAGE_TAG = tagName; o.PAGE_DATE = dateName; o.PAGE_READ = readName; o.PAGE_GROUP_IDS = groupIDs; o.PAGE_GROUP_NAMES = groupNAMEs; o.PAGE_PUB_DATE = CMS_SaveDateU.getDate(); o.DEF_DIR = CMS_Path.PAGE.ABS2; o.ASSET_DIR = CMS_Path.ASSET.ABS2; o.SITE_DIR = _siteRoot; return o; } /* ---------- ---------- ---------- */ //ブロック書き出しで使用。{{SITE_DIR}}を書き換える function setSiteRoot(_s,_path){ function _core (_path){ var s = ""; if(_path.substr(0,2) =="./"){ _path = _path.substr(2,_path.length-1); } var dir = URL_U.getBaseDir(_path); if( dir == "") return s; // var a = dir.split("/"); var path = ""; for (var i = 0; i < a.length ; i++) { if(a[i] != "") path+="../"; } //2017-07-27 調整 if(dir.substr(0,3) == "../"){ if(path.substr(path.length-3,3) =="../"){ path = path.substr(0,path.length-3) + CMS_Path.SITE.DIR + "/"; } } return path; } return _s.split(CONST.SITE_DIR).join(_core(_path)); } /* ---------- ---------- ---------- */ return { getReplacedHTML: getReplacedHTML, getCurrentReplaceTags: getCurrentReplaceTags, setSiteRoot:setSiteRoot } })(); //書きだそうとしてるページの情報を保持する //ブロックや機能によっては、現在のページ情報が必要なため var HTML_ExportState = (function(){ var id = ""; var dir = ""; var siteRoot = ""; function setCurrent(_param){ if(!_param) _param = {} id = (_param.id) ? _param.id : ""; dir = (_param.dir) ? _param.dir : ""; siteRoot = (_param.siteRoot) ? _param.siteRoot : ""; } function getCurrent(){ return { id : id, dir : dir, siteRoot : siteRoot }; } return { setCurrent:setCurrent, getCurrent:getCurrent } })(); <file_sep>/src/js/cms_data/CMS_Data.TextLoader.js CMS_Data.TextLoader = (function() { /* ---------- ---------- ---------- */ var c = function(_type,_url,_callback,_callback_e) { this.init(_type,_url,_callback,_callback_e); } var p = c.prototype; /* ---------- ---------- ---------- */ p.init = function(_type,_url,_callback,_callback_e) { this.type = _type; this.url = _url; this.callback = _callback; this.callback_e = _callback_e; this.data; this.load(); } p.load = function() { var this_ = this; $.ajax({ scriptCharset : 'utf-8', type : 'GET', url : this.url, dataType : 'text', success : function(data) { this_.load_comp(data); }, error : function(data) { if(this_.callback_e){ this_.callback_e({}); } } }) } p.load_comp = function(_data) { if(isLog) console.log("HTMLService.loadTemplate : "+this.url); if(this.type == "TEXT"){ this.data = _data; } if(this.type == "JSON"){ try{ this.data = JSON.parse(_data); }catch( e ){ this.data = {} } } if(this.type == "XML"){ this.data = _data} this.callback(this.data); } return c; })(); <file_sep>/src/js/cms_view_editable/EditableView.GridClass.js EditableView.GridClass = (function() { /* ---------- ---------- ---------- */ var c = function() { this.init(); } var p = c.prototype; /* ---------- ---------- ---------- */ this.grid = []; p.init = function () { this.grid = []; } p.initRecords = function (_grid){ this.grid = _grid; if(this.grid ==undefined)this.grid = []; }, p.addRecord = function (_item){ this.grid.push(_item); }, p.addRecordAt = function (_item,_index){ this.grid.splice(_index,0,_item); }, p.moveRecord = function (_indexFrom,_indexTo){ this.swapRecord(_indexFrom,_indexTo); return; }, p.moveRecordToFirst = function (_indexFrom){ var n = this.grid[_indexFrom]; this.grid.splice(_indexFrom,1); this.grid.unshift(n); return 0; }, p.moveRecordToLast = function (_indexFrom){ var n = this.grid[_indexFrom]; this.grid.splice(_indexFrom,1); this.grid.push(n); return this.grid.length -1; }, p.swapRecord = function (_indexFrom,_indexTo){ if(! this.isValidArge(_indexFrom,_indexTo))return false; // var from_ = this.grid[_indexFrom]; var to_ = this.grid[_indexTo]; this.grid[_indexTo] = from_; this.grid[_indexFrom] = to_; }, p.isValidArge = function (_indexFrom,_indexTo){ if(_indexFrom < 0)return false; if(_indexFrom > this.grid.length-1)return false; if(_indexTo < 0)return false; if(_indexTo > this.grid.length-1)return false; return true; }, p.overrideRecordAt = function (_item,_index){ this.grid[_index] = _item; }, p.removeRecordAt = function (_index){ this.grid.splice(_index,1); }, p.removeRecordLast = function (){ var n = this.grid.length-1 this.grid.splice(n,1); }, p.duplicateAt = function (_index){ var c = JSON.parse(JSON.stringify(this.grid[_index])) this.addRecordAt(c,_index); }, p.reset = function (){ this.grid = []; }, p.getRecords = function (){ return this.grid }, p.getRecordAt = function (_index){ return this.grid[_index] } p.getRecordLeng = function (_index){ return this.grid.length } return c; })();<file_sep>/src/js/cms_view_editable/EditableView.BaseGridU.js EditableView.BaseGridU = (function() { function getGridTag(_gridParam,_list,_state){ if(_state == undefined)_state = { hideCols:""} var _startPage = _state.currentPage; var _hideCols = _state.hideCols.split(","); var maxRow = _state.maxRow; var listLeng = _list.length; //テーブル作成 var fragment = document.createDocumentFragment(); var table = document.createElement('table'); table.setAttribute('class', '_editableGridTable'); table.appendChild(_getHeadNode(_gridParam.cells, _hideCols)); fragment.appendChild(_createPager(listLeng,maxRow,_startPage)); fragment.appendChild(table); fragment.appendChild(_createPager(listLeng,maxRow,_startPage)); //データ0の場合 if(listLeng == 0){ table.appendChild(_getEmptyNode()); return fragment; } // var t = new Date(); //各行追加 for (var g = 0; g < maxRow ; g++) { var i = (_startPage * maxRow) + g; if(i >= listLeng) break; table.appendChild( _getGridTagRow(_gridParam,i,_list,_hideCols)); } return fragment; } function _getGridTagRow(_gridParam,i,_list,_hides){ var tr = document.createElement('tr'); tr.setAttribute('data-no', i); tr.setAttribute('class', (_list[i].publicData != "1") ? "_tr-hide" : ""); var td = document.createElement('td'); td.setAttribute('class', "_no"); td.appendChild(document.createTextNode(i+1)); tr.appendChild(td); var _state = _initEditState(_list[i]); for (var ii = 0; ii < _gridParam.cells.length ; ii++) { var cell = _gridParam.cells[ii]; var val = Treatment.toValue(_list[i][cell.id] ,""); var node; var prov = EditableView.InputFormProviderGrid; var state = _getEditState(_state, cell.id); if(_isVisible(_hides,ii)){ node = prov[cell.type](i, val, cell,state); } else{ node = prov.edited(i, val, cell,state); }; if(node) tr.appendChild(node); } var editNode1 = (function(){ var s = "" s += '<span class="_btn_visi _cms_btn_alpha _btn_move_up" data-no="'+i+'"><i class="fa fa-arrow-up"></i> </span><br>'; s += '<span class="_btn_visi _cms_btn_alpha _btn_move_down" data-no="'+i+'"><i class="fa fa-arrow-down"></i> </span>' var td = document.createElement('td'); td.setAttribute('class', "_edit"); td.innerHTML = s; return td; })(); var editNode2 = (function(){ var s = "" s += '<span class="_btn_visi _cms_btn_alpha _btn_dup" data-no="'+i+'"><i class="fa fa-files-o"></i> </span><br>' s += '<span class="_btn_delete" data-no="'+i+'"></span>'; var td = document.createElement('td'); td.setAttribute('class', "_edit"); td.innerHTML = s; return td; })(); tr.appendChild(editNode1); tr.appendChild(editNode2); return tr; } function _createPager(_leng, _maxRow, _start) { var div = document.createElement('div'); if (_leng <= _maxRow) return div; var pages = Math.ceil(_leng / _maxRow); var div = document.createElement('div'); div.setAttribute('class', '_gridPager'); var s = "" for (var i = 0; i < pages; i++) { var cs = "" if (_start == i) cs += "_current" s += '<span class="' + cs + '" data-no="' + i + '">' + (i + 1) + '</span> ' } div.innerHTML = s; return div; } function _getHeadNode(_cells,_hides){ var tr = document.createElement('tr'); var th = document.createElement('th'); th.innerHTML = "no"; tr.appendChild(th); for (var i = 0; i < _cells.length ; i++) { var cell = _cells[i]; var th = document.createElement('th'); if(i == 0){ th.innerHTML = cell.name; tr.appendChild(th); } else{ if(cell.type != CELL_TYPE.STATE){ if(_isVisible(_hides,i)){ th.innerHTML = '<i class="fa fa-caret-down "></i>' + cell.name; th.setAttribute("class","_btn_cell_show"); th.setAttribute("data-no",i); } else{ th.innerHTML = '<i class="fa fa-caret-right "></i> <br>' th.setAttribute("class","_btn_cell_show _btn_cell_show-hide"); th.setAttribute("style","width:10px"); th.setAttribute("data-no",i); } tr.appendChild(th); } } } var th = document.createElement('th'); th.innerHTML = "移<br>動"; tr.appendChild(th); var th = document.createElement('th'); th.setAttribute("style","width:35px"); th.innerHTML = "複<br>製"; tr.appendChild(th); return tr; } function _getEmptyNode(){ var tr = document.createElement('tr'); var s = ""; s += "<tr>"; s += '<td colspan="100" class="_nodata"><i class="fa fa-plus-square "></i> ボタンを押して、データを入力してください</td>'; s += '</tr>'; tr.innerHTML = s; return tr; } function _isVisible (_s,_i){ if(_s == undefined) return true; if(_s.length == 0) return true; if(_s.length <= _i) return true; return (_s[_i] === "0") ? false:true; } function _initEditState(_o){ if(_o[CELL_TYPE.STATE] === undefined) _o[CELL_TYPE.STATE] = []; return _o[CELL_TYPE.STATE] } function _getEditState(_a,_id){ var b = false; for (var g = 0; g < _a.length ;g++) { if(_a[g] == _id) b = true; } return b; } /* ---------- ---------- ---------- */ //マルチグリッドで使用してる //カード検索オブジェクトの、検索条件サマリー表示 function getGridTagSum(_gridParam,_list){ var tag = '<table class="_editableGridSum">'; for (var i = 0; i < _list.length ; i++) { tag += "<tr>"; for (var ii = 0; ii < _gridParam.cells.length ; ii++) { var cell = _gridParam.cells[ii]; var val = Treatment.toValue(_list[i][cell.id] ,""); if(cell.view == "one") tag += '<td>' + val + '</td>'; } tag += "</tr>"; } tag += "</table>"; return tag; } // "0110"のように、テキストで配列をあつかう function strintState(_s,_no){ if(_s === undefined) _s = "1" if(_s === "")_s = "1" var a = _s.split(",") var leng = a.length; for (var i = 0; i <= _no ; i++) { if(leng <= i)a[i] = "1" } a[_no] = (a[_no] == "1") ? "0" : "1"; return a.join(","); } function textToArray (csv,cellTypes){ var lines = csv.split("\n"); var list = []; for (var i = 1; i < lines.length ; i++) { var o = {}; var d = BR_2_N(lines[i]).split(" "); if(d.length === 1 && d[0] === ""){ // }else{ var count = 0; for (var ii = 0; ii < cellTypes.length ; ii++) { d[count] = TAB_2_N(d[count]); var cell = cellTypes[ii]; switch (cell.type) { case CELL_TYPE.ANCHOR : //このタイプは、2セルデータを使用 o[cell.id] = { href : d[count+0], target : d[count+1] }; if(o[cell.id].href ===undefined)o[cell.id].href = ""; if(o[cell.id].target ===undefined)o[cell.id].target = ""; count++; break; case CELL_TYPE.BTN : // //このタイプは、4セルデータを使用 o[cell.id] = { href : d[count+0], target : d[count+1], text : d[count+2], class_ : d[count+3], image : "" }; if(o[cell.id].href ===undefined) o[cell.id].href = ""; if(o[cell.id].target ===undefined) o[cell.id].target = ""; if(o[cell.id].text ===undefined) o[cell.id].text = ""; if(o[cell.id].class_ ===undefined) o[cell.id].class_ = ""; count++; count++; count++; break; case CELL_TYPE.IMAGE : o[cell.id] = { mode : getImageMode( d[count] ), path : getImageLayoutDB( d[count] ), width : getExelString( d[count+1] ), ratio : getExelString( d[count+2] ) }; count++; count++; break; default : if(d[count] != ""){ o[cell.id] = d[count]; } } count++ } list.push(o); } } return list; } function arrayToText (list,cellTypes){ var csv = []; var a = []; //見出し(1行目) for (var i = 0; i < cellTypes.length ; i++) { var cell = cellTypes[i]; switch (cell.type) { case CELL_TYPE.ANCHOR : a.push("●"+cell.name) a.push("●リンクターゲット") break; case CELL_TYPE.BTN : a.push("●"+cell.name) a.push("●リンクターゲット") a.push("●リンクラベル名") a.push("●リンククラス名") break; case CELL_TYPE.IMAGE : a.push("●"+cell.name) a.push("●画像幅") a.push("●画像比率") break; case CELL_TYPE.STATE : break; default : a.push("●"+cell.name); } } csv.push(a.join(" ")); //データ(2行目〜) for (var i = 0; i < list.length ; i++) { var row = []; for (var ii = 0; ii < cellTypes.length ; ii++) { var b = true; if(cellTypes[ii].type === CELL_TYPE.STATE) b = false;//編集ステートは書き出さない // if(b){ var cell = cellTypes[ii]; var val = list[i][cell.id]; if(val){ if(cell.type == CELL_TYPE.ANCHOR){ val = val.href + " " + val.target; } else if(cell.type == CELL_TYPE.BTN){ val = [ val.href, val.target, val.text, val.class_ ].join(" "); } else if(cell.type == CELL_TYPE.IMAGE){ val = [ setImageLayoutDB(val.path), "["+val.width+"]", "["+val.ratio+"]" ].join(" "); } else{ val = N_2_TAB(val); } val = N_2_BR(val); } row.push(val); } } csv.push(row.join(" ")); } return csv.join("\n"); } /* ---------- ---------- ---------- */ //画像ブロックに、レイアウトモードを追加したので、 //表計算出力に対応させる (IDを発行し、IO対応) var ImageLayoutDB = {} function setImageLayoutDB(_val){ if(typeof _val == "string") return _val; var uid = DateUtil.getRandamCharas(10); ImageLayoutDB[uid] = _val; return "{IMAGE_ID:" + uid + "}"; } window.ImageLayoutDB = ImageLayoutDB; function getExelString(_s){ _s = _s.split("[").join(""); _s = _s.split("]").join(""); return _s; } function getImageMode(_uid){ if(_uid.indexOf("{IMAGE_ID:") != -1) return "layout"; return "simple"; } function getImageLayoutDB(_uid){ if(_uid.indexOf("{IMAGE_ID:") == -1){ return _uid; } _uid = _uid.split("{IMAGE_ID:").join("") _uid = _uid.split("}").join(""); if(ImageLayoutDB[_uid]){ return ImageLayoutDB[_uid]; } return {}; } /* ---------- ---------- ---------- */ var BR = "{_BR}"; function N_2_BR(_s){ if (_s == undefined) return ""; _s = _s.split("<br />").join("&lt;br&gt;"); _s = _s.split("<br>").join("&lt;br&gt;"); _s = _s.split("\n").join(BR); return _s; } function BR_2_N(_s){ if (_s == undefined) return ""; _s = _s.split("&lt;br&gt;").join("<br>"); _s = _s.split(BR).join("\n"); return _s; } var TAB = "{_T}"; function N_2_TAB(_s){ if (_s == undefined) return ""; if(_s == "\t") _s = ""; _s = _s.split("\t").join(TAB); return _s; } function TAB_2_N(_s){ if (_s == undefined) return ""; _s = _s.split(TAB).join("\t"); return _s; } return { textToArray:textToArray, arrayToText:arrayToText, getGridTag:getGridTag, getGridTagSum:getGridTagSum, strintState:strintState } })(); <file_sep>/src/js/cms_view_floats/Float_Preview.3.js var Float_PreviewMini = (function(){ var view; var v = {}; function init(){ view = $('#Float_PreviewMini'); stageInit(); createlayout(); setBtn(); } /* ---------- ---------- ---------- */ function createlayout(){ var tag = ""; tag += '<div class="_arrow"></div>'; tag += '<div class="_fuki">'; tag += ' <div class="_inner"></div>'; tag += ' <div class="_cms_btn_alpha _btn_preview_open"><i class="fa fa-caret-down "></i> プレビューを開く</div>'; tag += '</div>'; view.html(tag) v.arrow = view.find('._arrow'); v.inner = view.find('._inner'); } function setBtn(){ view.hover(function(){ if(tID) clearTimeout(tID) } , function(){ stageOut(); }) v.btn_preview_open = view.find('._btn_preview_open'); v.btn_preview_open.click(function(){ Float_Preview.switchPreview(true); }); } /* ---------- ---------- ---------- */ function update(_type,_xy,_param){ updatePos(_xy); var tag = ''; if(_type == Dic.ListType.DIR){ // tag += ' <div class="_title">{NAME}</div>' tag += ' <div><span class="_m">グループID : </span><span class="_gID"><i class="fa fa-folder-open"></i>{ID}</span></div>' v.btn_preview_open.hide() } if(_type == Dic.ListType.PAGE){ tag += ' <div class="_title">{NAME}</div>' tag += ' <div class="_filePath">{URL_ABS}</div>' // tag += ' <div class=""><span class="_m">所属グループID\'s : </span>{G}</div>' v.btn_preview_open.show() } var tempP = { name :_param.name, id :_param.id, dir :_param.dir, prevPub :"" } v.inner.html( Float_Preview.DoTemplate( tag , tempP )); } /* ---------- ---------- ---------- */ var prevY = -1; var currentY = -1; function updatePos(_xy){ var tarY = _xy.y -25; view.css("top", tarY + "px"); } /* ---------- ---------- ---------- */ function updateSitemapDate(){ } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } function stageIn(_type,_xy,_param){ // if(! isOpen){ isOpen = true; if(isFirst){} if(tID) clearTimeout(tID) tID = setTimeout(function(){ view.show(); isFirst = false; update(_type,_xy,_param) },50); // } } var tID function stageOut(){ if(tID) clearTimeout(tID) tID = setTimeout(function(){ view.hide(); prevY = -1 },300); } function stageOut_core(){ if(tID) clearTimeout(tID) view.hide(); prevY = -1 } return { init: init, stageIn: stageIn, stageOut: stageOut, stageOut_core: stageOut_core, updateSitemapDate: updateSitemapDate } })(); <file_sep>/src/js/cms_model/PageModel.Object_Info.js PageModel.Object_Info = (function() { /* ---------- ---------- ---------- */ var c = function(o) { this.init(o); } var p = c.prototype; /* ---------- ---------- ---------- */ p.param p.id; p.name; p.def; p.cssDef; p.init = function(o) { this.param = o; this.setParam(); } p.setParam = function (){ this.id = defaultVal(this.param.id, ""); this.custom = defaultVal(this.param.custom, false); this.name = defaultVal(this.param.name, ""); this.name2 = defaultVal(this.param.name2, ""); this.guide = defaultVal(this.param.guide, ""); this.def = defaultVal(this.param.def, ""); this.cssDef = defaultVal(this.param.cssDef, {file:"block",key:""}); this.inputs = defaultVal(this.param.inputs, []); var o = {} o.type = this.id; o.custom = this.custom; o.name = this.name; o.name2 = (this.name2) ? this.name2 :""; o.inputs = this.inputs; PageElement_DIC.push(o); } p.getHeadTag = function (){ var tag = "" tag += '<div class="_head">' tag += '</div>' return tag; } p.getGuideTag = function (){ var tag = "" if(this.guide){ if(window["CMS_GuideU"]){ tag = CMS_GuideU.getGuideTag(this.guide,"_BASE_"); } } return tag; } p.getFootTag = function (){ var tag = "" tag += '<div class="_head">' tag += '</div>' return tag; } p.getTestTag = function (){ var tag = ""; tag += '<div class="_ut_object_info">' tag += '<span class="_t1">id</span><span class="_t2">'+this.id +'</span>'; tag += '<span class="_t1">name</span><span class="_t2">'+this.name +'</span>'; tag += '<span class="_t1">def</span><span class="_t2">'+this.def +'</span>'; tag += '</div>' return tag; } p.getGuideImageTag = function (){ return ""; } return c; })();<file_sep>/src/js/cms_model/PageElement.object.dl.js PageElement.object.dl = (function(){ var _ = new PageModel.Object_(); /* ---------- ---------- ---------- */ _.pageInfo = new PageModel.Object_Info({ id : "object.dl", name : "Q&Aリスト", name2 : "", inputs : ["CLASS","CSS","DETAIL"], // cssDef : {file:"block",key:"[Q&Aリストブロック]"} cssDef : {selector:".cms-qa"} }); /* ---------- ---------- ---------- */ _.grids = [ /* ---------- ---------- ---------- */ new PageModel.Object_Grid({ gridType:Dic.GridType.BASE, gridInfo:new PageModel.OG_info({ id : "setting", name : "設定", note : "" }), textData:{ info:new PageModel.OG_SubInfo({ name:"", note:"", image : '<div class="ss_guide _qa"></div>' }), cells:[ new PageModel.OG_Cell({ id:"accordion", name:"アコーディオンにするか?", type:CELL_TYPE.SELECT , vals:SS.SelectVals.YN, view:"", def:"0", note:"開閉メニュースタイルにすることができます" }), ] }, gridData:null }), new PageModel.Object_Grid({ gridType:Dic.GridType.BASE, gridInfo:new PageModel.OG_info({ id : "list", name : "リスト", note : "" }), textData:null, gridData:{ info:new PageModel.OG_SubInfo({}), cells:[ new PageModel.OG_Cell({ id: "t1", name: "質問", type: CELL_TYPE.MULTI, def: "Q.サンプルの文書です?" }), new PageModel.OG_Cell({ id: "t2", name: "解答", type: CELL_TYPE.MULTI, def: "サンプルの文書ですので、ご注意ください。サンプルの文書ですので、ご注意ください。" }), new PageModel.OG_Cell({ id: "anchor", name: "追加リンク", type: CELL_TYPE.BTN, def: CMS_AnchorU.getInitDataS() }) ] } }) /* ---------- ---------- ---------- */ ] _.getInitData = function(){ var o = {}; o.type = _.pageInfo.id; var def = { setting: { texts: { accordion: "0" }, grid: [] }, list: { texts: {}, grid: [ { publicData: "1", t1: "Q.サンプルの文書です?", t2: "サンプルの文書ですので、ご注意ください。サンプルの文書ですので、ご注意ください。サンプルの文書ですので、ご注意ください。サンプルの文書ですので、ご注意ください。サンプルの文書ですので、ご注意ください。", anchor: { "href": "#", "target": "_blank", "text": "さらに詳しく <i class='fa fa-arrow-right'></i>", "class_": "cms-btn-text-box cms-btn-size-m", "image": "" } }, { publicData: "1", t1: "Q.サンプルの文書ですので、ご注意ください。?", t2: "サンプルの文書ですので、ご注意ください。サンプルの文書ですので、ご注意ください。", anchor: CMS_AnchorU.getInitData_Blank() }, { publicData: "1", t1: "Q.サンプルの文書ですので、ご注意ください。サンプルの文書ですので、ご注意ください。?", t2: "サンプルの文書ですので、ご注意ください。サンプルの文書ですので、ご注意ください。サンプルの文書ですので、ご注意ください。サンプルの文書ですので、ご注意ください。サンプルの文書ですので、ご注意ください。", anchor:CMS_AnchorU.getInitData_Blank() }, { publicData: "1", t1: "Q.サンプルの文書ですので、ご注意ください。?", t2: "サンプルの文書ですので、ご注意ください。サンプルの文書ですので、ご注意ください。サンプルの文書ですので、ご注意ください。", anchor:CMS_AnchorU.getInitData_Blank() } ] } } o.data = def; o.attr = {css:"default",style:""}; o.attr.class = o.attr.css; return o; } _.getPreview = function(_o){ var data = _o.data; var attr = _o.attrs; var tag = ""; attr = attr.split('class="').join('class="cms-qa '); var list = CMS_U.getPublicList(data.list.grid); if(list.length == 0){ tag += '<span class="_no-input-data">Q&Aデータを入力...</span>' } else { tag += '<dl '+attr+'>\n'; for (var i = 0; i < list.length ; i++) { var aTag = CMS_AnchorU.getAnchorTag(list[i].anchor,"",false); if(aTag)aTag = "<br>"+aTag; tag += ' <dt>'+CMS_TagU.t_2_tag(list[i].t1)+'</dt>\n'; tag += ' <dd>'+CMS_TagU.t_2_tag(list[i].t2)+aTag+'</dd>\n'; } tag += '</dl>\n'; } return tag; } _.getHTML = function(_o){ var data = _o.data; var attr = _o.attrs; var tag = "" attr = attr.split('class="').join('class="cms-qa '); var list = CMS_U.getPublicList(data.list.grid); if(list.length == 0) return ""; if(data.setting.texts.accordion == "1"){ attr = attr.split('class="').join('class="cms-accordion '); } { tag += '<dl '+attr+'>\n'; for (var i = 0; i < list.length ; i++) { var aTag = CMS_AnchorU.getAnchorTag(list[i].anchor,"",true); if(aTag)aTag = "<br>"+aTag; tag += ' <dt>'+CMS_TagU.t_2_tag(list[i].t1)+'</dt>\n'; tag += ' <dd>'+CMS_TagU.t_2_tag(list[i].t2)+aTag+'</dd>\n'; } tag += '</dl>\n'; tag += '<script>\n' tag += '$(function(){\n'; tag += ' $(".cms-accordion dt").cms_accordion();\n'; tag += '});\n'; tag += '</script>\n'; } return tag; } /* ---------- ---------- ---------- */ return _; })(); <file_sep>/src/js/cms_view_inspect/InspectView.TextAnchorClass.js InspectView.TextAnchorClass = (function(){ /* ---------- ---------- ---------- */ var c = function(_a,_b,_c,_d) { this.init(_a,_b,_c,_d); } var p = c.prototype; /* ---------- ---------- ---------- */ p.type p.view p.val p.callback p.init = function(_view,_val,_callback) { if(_view.size() == 0)return; this.view = _view; this.val = _val; this.callback = _callback; this.setData(); this.update(this.val); } p.setData = function() { var this_ = this; //ボタン設定の場合 this.view.click(function(event){ event.stopPropagation(); event.preventDefault(); Anchor_BtnView.stageIn(this_.val,function(_val){ this_.val = _val this_.update(this_.val); this_.callback(this_.val); }) }); } p.update = function(_val) { var tag = CMS_AnchorU.getViewTag(_val,false) this.view.html(tag); } return c; })(); <file_sep>/src/js/cms_stage_sidepreview/CMS_SidePreviewPage.js var CMS_SidePreviewPage = (function() { /* ---------- ---------- ---------- */ var c = function(_parent,_pageModel) { this.init(_parent,_pageModel); } var p = c.prototype; /* ---------- ---------- ---------- */ p.init = function(_parent,_pageModel) { this.parentView = _parent; this.pageModel = _pageModel; this.url = CMS_Path.PAGE.getRelPath(_pageModel.id,_pageModel.dir); var tag = '<div>'; tag += '<div class="_frame_pub"></div>'; tag += '<div class="_frame_live"></div>'; tag += '</div>'; this.view = $(tag); this.parentView.append(this.view); this.v = {} this.v.frame_pub = this.view.find("._frame_pub"); this.v.frame_live = this.view.find("._frame_live"); this.v.frame_live.hide() this.viewURL = this.pageModel.id + ".html" this.stageInit(); this.initViewPub = false; // this.lastEditDateTime = new Date().getTime(); this.lastLivePreviewTime = 0; // this.lastPublishDate = new Date().getTime(); } /* ---------- ---------- ---------- */ p.reset = function() { this.initViewPub = false; this.lastLivePreviewTime = 0; this.v.frame_pub.html("") this.v.frame_live.html("") } p.updateWS_State = function() { if(this.isLiveTab){ this.update_liveView(); } else{ this.update_pubView(); } } p.reload = function() { if(this.isLiveTab){ this.lastLivePreviewTime = 0; this.update_liveView(); } else{ this.initViewPub = false; this.update_pubView(); } } p.updateTabState = function() { this.showLive(CMS_SidePreviewState.isLiveTab); } /* ---------- ---------- ---------- */ p.isLiveTab = false; //タブきりかえ p.showLive = function(_b) { if(this.isLiveTab == _b)return ; this.isLiveTab = CMS_SidePreviewState.isLiveTab; this.v.frame_pub.hide(); this.v.frame_live.hide(); if(this.isLiveTab){ this.v.frame_live.show(); this.update_liveView(); } else{ this.v.frame_pub.show(); this.update_pubView(); } } /* ---------- ---------- ---------- */ //公開ページ p.initViewPub; p.update_pubView = function() { if(this.initViewPub)return; this.initViewPub = true; this.v.frame_pub.html(this.update_common(false)); } //ライブプレビュー p.lastLivePreviewTime; p.update_liveView = function() { if(this.isLiveTab == false) return; var this_ = this; // var page = CMS_PageDB.getLivePreviewPage(); if(page == undefined ) return; var d = this.lastEditDateTime; if(this.lastLivePreviewTime == d) return; this.lastLivePreviewTime = d; page.previewData(function(){ this_.v.frame_live.html(this_.update_common(true)); }) } /* ---------- ---------- ---------- */ p.update_common = function(_isLiveTab) { var currentWs = CMS_SidePreviewState.currentWs var s = CMS_SidePreviewState.currentZoom /100; var tag = ""; var ww = 0; if(_isLiveTab){ this.loadURL = CMS_Path.ASSET.REL + CMS_Path.PREVIEW_HTML; this.loadURL += "?p=" + DateUtil.getRandamCharas(10); this.loadURL += "&url=" + this.url; } else{ this.loadURL = this.url; this.loadURL += "?p=" + DateUtil.getRandamCharas(10) } for (var i = 0; i < currentWs.length ; i++) { var ts = ''; ts +="-webkit-transform: scale("+s+");" ts +="-moz-transform: scale("+s+");" ts +="-ms-transform: scale("+s+");" ts +="transform: scale("+s+");" ts += "width:"+(100/s)+"%;"; ts += "height:"+(100/s)+"%;"; var temp = ''; temp += '<div class="_iframeDiv" style="width:{WW}px;">'; temp += ' <iframe src="{U}" width="{W}" style="{S}"></iframe>'; temp += '</div>'; // if(CMS_PageDB.isCurrent_is_Setting()){ // //外部JSONファイルを、キャッシュなしで読み込むように // this.loadURL += "&c=noChash"; // } temp = temp.split("{U}").join(this.loadURL); temp = temp.split("{WW}").join(currentWs[i]*s); ww += currentWs[i] * s; temp = temp.split("{W}").join(currentWs[i]); temp = temp.split("{S}").join(ts); tag += temp; } return tag; } //p.c = 0 p.openedPage = function() { this.updateTabState(); if(this.isLiveTab){ this.update_liveView(); } else{ this.update_pubView(); } } p.editedPage = function() { if(!this.isLiveTab) return; if(CMS_SidePreviewState.isLiveCheck == false) return; var this_ = this; var page = CMS_PageDB.getLivePreviewPage(); if(page == undefined ) return; // this.lastEditDateTime = new Date().getTime(); page.previewData(function(){ this_.update_liveView() }) } p.savedPage = function() { var this_ = this; if(CMS_SidePreviewState.isLiveCheck == false) return; // if(CMS_PageDB.isFreePage() ) { // // // } else{ var page = CMS_PageDB.getLivePreviewPage() if(page == undefined ) return; page.previewData(function(){ this_.lastLivePreviewTime = 0; this_.v.frame_live.html(this_.update_common(true)); // this_.update_liveView(); }) // } } p.lastPublishDate p.publishedPage = function() { if(this.isLiveTab) return; var currentDate = new Date().getTime(); if(currentDate - this.lastPublishDate < 1000) return; this.lastPublishDate = currentDate; // this.initViewPub = false; this.update_pubView() } /* ---------- ---------- ---------- */ p.getPageTitle = function() { return this.viewURL; } p.openExternal = function() { var u = "" var p = "" if(this.isLiveTab){ p = u = CMS_Path.ASSET.REL + CMS_Path.PREVIEW_HTML; p += "?p=" + DateUtil.getRandamCharas(10); p += "&url=" + this.url; } else{ p = u = this.url; p += "?p=" + DateUtil.getRandamCharas(10) } CMS_U.openURL_blank(p,u); } /* ---------- ---------- ---------- */ /**/ p.openFlg = false; p.stageInit = function() { this.openFlg = false //this.view.hide() } p.stageIn = function() { if (!this.openFlg) { this.openFlg = true; this.view.show(); this.openedPage(); } } p.stageOut = function() { if (this.openFlg) { this.openFlg = false this.view.hide() } } return c; })(); <file_sep>/src/js/cms_model/PageElement.replace.js PageElement.replace = {} <file_sep>/js_cms/html/php/mail.php <?php echo( '{ "result":"error" , "text":"サーバー側プログラムが未設定です" }' ); exit();<file_sep>/src/js/cms_model/PageElement.object.data_text.js PageElement.object.data_text = (function(){ var _ = new PageModel.Tag_(); /* ---------- ---------- ---------- */ _.pageInfo = new PageModel.Object_Info({ id : "object.data_text", name : "生データ", name2 : "", inputs : ["TEXTAREA"] }); /* ---------- ---------- ---------- */ _.getInitData = function(){ var o = {}; o.type = _.pageInfo.id; var s = "サンプルの文書ですので、ご注意ください。" o.data = s o.attr = {css:"",style:""} return o; } /* ---------- ---------- ---------- */ _.getPreview = function(_o){ var data = _o.data; var attr = _o.attrs; var tag = ""; tag += '<div class="_cms_preview">\n' tag += '<div class="_title">データブロック / TEXTデータ</div>' tag += '<div class="_notes">データブロックは、[公開する]でHTML公開しても、書出されません。<br>ブロック情報パネルの、[出力]タブよりファイル名を設定し、書出せます。</div>' tag += '<div class="">\n' if(data == ""){ tag += '<span class="_no-input-data">データリストを入力...</span>' } else{ tag += '<table class="_dataTable">\n' tag += '<tbody>\n' tag += '<tr>\n' tag += '<td>\n' tag += CMS_TagU.tag_2_t(data).split("\n").join("<br>"); tag += "</td>\n"; tag += "</tr>\n"; tag += "</tbody>\n"; tag += "</table>\n"; } tag += "</div>\n"; tag += "</div>\n"; return tag; } /* ---------- ---------- ---------- */ _.getHTML = function(_o,_tab){ var data = _o.data; var attr = _o.attrs; // var tab = (_tab != undefined) ? _tab:""; var tag = "" tag += data; return tag; } /* ---------- ---------- ---------- */ return _; })();<file_sep>/src/js/cms_view_floats/AddElements.js var AddElements = (function(){ var view; var v = {} function init(){ view = $('#AddElements'); var tag = ""; tag += '<div id="AddElementsArrow">'; tag += ' <span class="_icon"><i class="fa fa-plus "></i>'; tag += ' <span class="_text">ブロック追加</span>'; tag += '</div>'; tag += '<div id="AddElementsArrowClose">'; tag += ' <span class="_icon"><i class="fa fa-minus "></i></span>'; tag += '</div>'; tag += '<div id="AddElementsView"></div>'; tag += '<div id="AddElementsBtnSet"></div>'; view.html(tag); v.arrow = $('#AddElementsArrow'); v.arrowClose = $('#AddElementsArrowClose'); v.arrow.click(function() { show(); }); v.arrowClose.click(function() { hide(); }); update(); AddElementsView .init(); AddElementsBtnSet .init(); stageInit(); } var prevY = -1; function update(){ } var isShow = false; function show(){ $("body").addClass("_showAddPanel"); } var tID; function hide(){ $("body").removeClass("_showAddPanel"); } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } function stageIn(){ if(! isOpen){ isOpen = true; view.show(); if(isFirst){} isFirst = false; } } function stageOut(){ if(isOpen){ isOpen = false; view.hide(); } } function setVisible(_b){ if(_b){ stageIn() } else{ stageOut(); } } return { init: init, stageIn:stageIn, stageOut:stageOut, update: update, setVisible:setVisible } })(); <file_sep>/src/js/cms_view_floats/AddElementsManager.js /** * エレメントの新規挿入時の位置の管理や、挿入を行う */ AddElementsManager = (function() { var currentTar; var currentNo; function setData(_tar, _no) { currentTar = _tar; currentNo = _no; } function addElement(_type, _param) { hideFloatView(); var o = PageElement_Util.getInitData(_type, _param); currentTar.addDataAt(o, currentNo + 1); if (_type == "object.tabList") { currentTar.addDataAt(JSON.parse(PageElement_JText.tabListData01), currentNo + 2); currentTar.addDataAt(JSON.parse(PageElement_JText.tabListData02), currentNo + 2); currentTar.addDataAt(JSON.parse(PageElement_JText.tabListData03), currentNo + 2); } currentTar.update(); currentTar.select(currentNo + 1); } function addElement_by_object(_param) { hideFloatView(); currentTar.addDataAt(_param, currentNo + 1); currentTar.update(); currentTar.select(currentNo + 1); } return { setData: setData, addElement: addElement, addElement_by_object: addElement_by_object } })(); <file_sep>/src/js/cms_data/CMS_Data.InspectCSS.js //インスペクトビューのCSSプリセット管理 CMS_Data.InspectCSS = (function(){ var css = "" var url = "" var _hasData = false; function load(_callback) { url = ASSET_CSS_DIRS[0]; var urlR = url + "?" + new Date().getTime(); new CMS_Data.TextLoader( "TEXT", urlR, function(_text) { _hasData = true; css = parse(_text); if(_callback)_callback(url); },function(_text){ css = parse(""); if(_callback)_callback(url); } ); } var listCommon; var listTag; function hasData() { return _hasData; } function parse(_text) { listCommon = []; listTag = []; // var re = new RegExp('\\/\\*.*{.*?}.*\\*\\/' ,"ig"); var re = new RegExp('\\/\\*.*\\[.*?\\].*\\*\\/' ,"ig"); var ss = _text.match(re); if(!ss ) return {}; listTag = []; for (var i = 0; i < ss.length ; i++) { var _vs = getPresetVal(ss[i]).split(","); if(_vs.length>1){ var selc = _vs[0] var label = _vs[1] if(selc.charAt(0) == "." && selc.split(".").length == 2){ if(isOwnPreset(listCommon,selc) == false){ listCommon.push({ selector:selc, label:label }); } } if(selc.split(".").length > 1){ if(isOwnPreset(listTag,selc) == false){ listTag.push({ selector:selc, label:label }); } } } } listCommon = _cluc(listCommon); listTag = _cluc(listTag); // console.log(listCommon); // console.log(listTag); } function _cluc (_defs){ var _list = []; for (var i = 0; i < _defs.length ; i++) { var l = _defs[i].label; var sel = _defs[i].selector; if(l.indexOf("/") != -1){ var gp = l.split("/")[0]; if(! _hasItem(_list,gp)){ _list.push({label:gp,selector:sel,subs:[]}); } _addSubItem(_list,gp,l,sel); } else{ _list.push({label:l,selector:sel,subs:[]}); } } return _list; } function _hasItem(_list,_g){ var b = false; for (var i = 0; i < _list.length ; i++) { if(_list[i].label == _g){ b = true; } } return b; } function _addSubItem(_list,_g,_s,_sel){ for (var i = 0; i < _list.length ; i++) { if(_list[i].label == _g){ var s = _s.split(_g+"/")[1]; _list[i].subs.push({label:s,selector:_sel}); } } } /* ---------- ---------- ---------- */ function getPresetVal(_s) { _s = _s.split(" ").join(""); _s = _s.split(" ").join(""); _s = _s.split("/*").join(""); _s = _s.split("*/").join(""); _s = _s.split("[").join(""); _s = _s.split("]").join(""); return _s; } function isOwnPreset(_list,_s) { var b = false; if(_s.indexOf("---") != -1) return false; for (var i = 0; i < _list.length ; i++) { if(_list[i].selector == _s) b = true; } return b; } function getList(_base,_type){ var ls = []; if(_type == "common"){ var _list = listCommon; for (var i = 0; i < _list.length ; i++) { _list[i].class = _list[i].selector.split(".").join(""); for (var ii = 0; ii < _list[i].subs.length ; ii++) { _list[i].subs[ii].class = _list[i].subs[ii].selector.split(".").join(""); } ls.push(_list[i]); } } else{ var _list = listTag; for (var i = 0; i < _list.length ; i++) { var sel = getFirstSel(_list[i].selector); if(sel == _base){ _list[i].class = _list[i].selector.split(_base + ".").join(""); for (var ii = 0; ii < _list[i].subs.length ; ii++) { _list[i].subs[ii].class = _list[i].subs[ii].selector.split(_base + ".").join(""); } ls.push(_list[i]); } } } return ls; } /* ---------- ---------- ---------- */ //セレクタの先頭のノードを返す function getFirstSel(_s){ if(_s.charAt(0) == "."){ var s = _s.split("."); return "." + s[1]; } else{ var s = _s.split("."); return s[0]; } } /* equal(_f(".clearfix"),".clearfix"); equal(_f(".w100p"),".w100p"); equal(_f(".fs36"),".fs36"); equal(_f(".cms-layout.default"),".cms-layout"); equal(_f(".cms-layout.designA"),".cms-layout"); equal(_f(".cms-layout.designB"),".cms-layout"); equal(_f(".cms-markdown.default"),".cms-markdown"); equal(_f("h1.default"),"h1"); equal(_f(".cms-layout.free"),".cms-layout"); equal(_f(".cms-layout-table.free"),".cms-layout-table"); */ /* ---------- ---------- ---------- */ var updateCallback = null; function registUpdateCallback(_cb){ updateCallback = _cb; } /* ---------- ---------- ---------- */ function reload(_s){ if(url.indexOf(_s)!= -1){ load(function(){ if(updateCallback){ updateCallback(); } }); } } return { load:load, hasData:hasData, getList:getList, reload:reload, registUpdateCallback:registUpdateCallback } })(); <file_sep>/src/js/cms_stage_page/CMS_PageList_PageDB.js var CMS_PageList_PageDB = (function(){ var list = []; function _trace(){ return list; } function add_(_page){ var a = [] for (var i = 0; i < list.length ; i++) { if(list[i].isRemoved == false){ a.push(list[i]) } } list = a; list.push(_page); } /* ---------- ---------- ---------- */ function getPage(_id,_dir){ for (var i = 0; i < list.length ; i++) { if(list[i].param.id == _id){ if(list[i].param.dir == _dir){ return list[i]; } } } return null; } /* ---------- ---------- ---------- */ var tID; function updateState(){ if(tID) clearTimeout(tID); tID = setTimeout(function(){ updateState_delay() },200); } function updateState_delay(){ for (var i = 0; i < list.length ; i++) { list[i].updateState(); } } /* ---------- ---------- ---------- */ var tID2; function updateEditState(){ if(tID2) clearTimeout(tID2); tID2 = setTimeout(function(){ updateState_delay() },200); } function updateEditState_delay(){ for (var i = 0; i < list.length ; i++) { list[i].updateEditState(); } } return { _trace: _trace, add_: add_, getPage: getPage, updateState: updateState, updateEditState: updateEditState } })();<file_sep>/src/js/cms_stage_page/CMS_PagesView.js var CMS_PagesView = (function(){ var view; function init(){ view = $('#CMS_PagesView'); } /* ---------- ---------- ---------- */ function _getID (_id,_dir){ return CMS_PageID.getID_s(_id,_dir) } function _has (){ return CMS_PageDB.hasCurrent(); } function _getCurrent (){ return CMS_PageDB.getCurrentPage(); } function getCurrent (){ return _getCurrent(); } function _has_ps (_id,_dir){ for (var i = 0; i < _ps.length ; i++) { var id1 = _getID(_id,_dir); var id2 = _getID(_ps[i].id,_ps[i].dir); if(id1 == id2)return true; } return false; } function _getPageByID(_id,_dir){ for (var i = 0; i < _ps.length ; i++) { var id1 = _getID(_id,_dir); var id2 = _getID(_ps[i].id,_ps[i].dir); if(id1 == id2) return _ps[i]; } return false; } /* ---------- ---------- ---------- */ function historyBack (){ if(_has()) _getCurrent().historyBack(); } function save (){ if(_has()) _getCurrent().saveData(); } function publish (){ if(_has()) _getCurrent().publishData(); } function openURL (){ if(_has()) _getCurrent().openURL(); } function editMeta (){ if(_has()) _getCurrent().editMeta(); } function refresh (){ openPage(); } /* ---------- ---------- ---------- */ var _ps = []; var _current; function removePage (_id,_dir){ var tar = -1; for (var i = 0; i < _ps.length ; i++) { if(_ps[i].id == _id) { if(_ps[i].dir == _dir) { _ps[i].stageOut(); _ps[i].remove(); _ps[i] = null; _ps.splice(i,1); } } } } function openPage (_param){ if(_param == undefined) { if(_current == undefined)return; _param = _current; } //ページ作成 if(_has_ps(_param.id,_param.dir) == false){ _ps.push(new CMS_PageClass(view, _param)); } _current = _param; //前のページは非表示にして、現在のページを表示 // if(_has()) _getCurrent().stageOut(); for (var i = 0; i < _ps.length ; i++) { var id1 = _getID(_param.id,_param.dir) var id2 = _getID(_ps[i].id,_ps[i].dir) if(id1 == id2) { _ps[i].stageIn(); } else{ _ps[i].stageOut(); } } } /* ---------- ---------- ---------- */ //外からIDとDIRを指定して保存、公開 function savePageByID(_id,_dir){ var tar = _getPageByID(_id,_dir) if(tar)tar.saveData() } function publishPageByID(_id,_dir){ var tar = _getPageByID(_id,_dir); if(tar)tar.publishData(); } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } function stageIn(_pageModel,_extra){ if(! isOpen){ isOpen = true; view.show(); openPage(_pageModel,_extra); } } function stageOut(){ if(isOpen){ isOpen = false; view.hide(); } } return { init: init, removePage: removePage, stageIn: stageIn, stageOut: stageOut, historyBack: historyBack, save: save, publish: publish, openURL: openURL, editMeta: editMeta, refresh: refresh, savePageByID : savePageByID, publishPageByID : publishPageByID, getCurrent : getCurrent } })(); <file_sep>/src/js/cms_stage_page/CMS_PagesView_ZoomManager.js var CMS_PagesView_ZoomManager = (function(){ var view; var v = {}; function setView(_view){ view = _view; setBtn(); zoom(Storage.Memo.getZoomVal()); } function setBtn(_view){ view.find("._btn_zoom").click(function(){ var s = parseInt(prompt("ズーム値を指定してください(10〜100%)",currentZoom*100)); zoom(s/100); }); v._btn_zoomIn = view.find('._btn_zoomIn'); v._btn_zoomOut = view.find('._btn_zoomOut'); v._btn_zoomIn.click(function(){ zoomIn()}); v._btn_zoomOut.click(function(){ zoomOut()}); } var currentZoom = 1 var zooms = [ 0.25, 0.33, 0.5, 0.75, 1 ] function zoomIn(){ var s = 1 for (var i = 0; i < zooms.length ; i++) { if(currentZoom < zooms[i]){ s = zooms[i]; break; } } zoom(s); } function zoomOut(){ var s = zooms[0] for (var i = 0; i < zooms.length ; i++) { if(currentZoom > zooms[i]){ s = zooms[i]; } } zoom(s); } function zoom(_s){ if(!_s)return; if(isNaN(_s))return; if(_s > 1) _s = 1; if(_s < zooms[0]) _s = zooms[0]; currentZoom = _s; // _setZoom( $('#CMS_PagesView > ._cms_page > ._page_inner > ._page_inner_zoom') , currentZoom,true) ; Storage.Memo.setZoomVal(_s); updateViewState(); } function _setZoom(_tar,_s,_isW){ _tar.css("-webkit-transform" , "scale(" + _s + ")" ); _tar.css("transform" , "scale(" + _s + ")" ); if(_isW)_tar.css("width" ,100* (1/_s)+ "%" ); if(_isW)_tar.css("height" ,100* (1/_s)+ "%" ); } function updateViewState(){ var btns = $("#CMS_PagesView ._page_zooms"); btns.find("._btn_zoom").text( currentZoom * 100 +"%"); btns.find("._btn_zoomIn").removeClass("_btn_disable"); btns.find("._btn_zoomOut").removeClass("_btn_disable"); if(currentZoom == 1){ btns.find("._btn_zoomIn").addClass("_btn_disable"); } if(currentZoom == zooms[0]){ btns.find("._btn_zoomOut").addClass("_btn_disable"); } } return { setView: setView, zoomIn: zoomIn, zoomOut: zoomOut, zoom: zoom } })(); var CMS_PresetView_ZoomManager = (function(){ var view; var v = {}; function setView(_view){ view = _view; setBtn(); zoom(currentZoom); } function setBtn(_view){ view.find("._btn_zoom").click(function(){ var s = parseInt(prompt("ズーム値を指定してください(10〜100%)",currentZoom*100)); zoom(s/100); }); v._btn_zoomIn = view.find('._btn_zoomIn'); v._btn_zoomOut = view.find('._btn_zoomOut'); v._btn_zoomIn.click(function(){ zoomIn()}); v._btn_zoomOut.click(function(){ zoomOut()}); } var currentZoom = 1 var zooms = [ 0.25, 0.33, 0.5, 0.75, 1 ] function zoomIn(){ var s = 1 for (var i = 0; i < zooms.length ; i++) { if(currentZoom < zooms[i]){ s = zooms[i]; break; } } zoom(s); } function zoomOut(){ var s = zooms[0] for (var i = 0; i < zooms.length ; i++) { if(currentZoom > zooms[i]){ s = zooms[i]; } } zoom(s); } function zoom(_s){ if(!_s)return; if(isNaN(_s))return; if(_s > 1) _s = 1; if(_s < zooms[0]) _s = zooms[0]; currentZoom = _s; // _setZoom( $('#PresetStage_PagesView > ._cms_page > ._page_inner > ._page_inner_zoom') , currentZoom,true) ; // Storage.Memo.setZoomVal(_s); updateViewState(); } function _setZoom(_tar,_s,_isW){ _tar.css("-webkit-transform" , "scale(" + _s + ")" ); _tar.css("transform" , "scale(" + _s + ")" ); if(_isW)_tar.css("width" ,100* (1/_s)+ "%" ); if(_isW)_tar.css("height" ,100* (1/_s)+ "%" ); } function updateViewState(){ var btns = $("#PresetStage_PagesView ._page_zooms"); btns.find("._btn_zoom").text( currentZoom * 100 +"%"); btns.find("._btn_zoomIn").removeClass("_btn_disable"); btns.find("._btn_zoomOut").removeClass("_btn_disable"); if(currentZoom == 1){ btns.find("._btn_zoomIn").addClass("_btn_disable"); } if(currentZoom == zooms[0]){ btns.find("._btn_zoomOut").addClass("_btn_disable"); } } return { setView: setView, zoomIn: zoomIn, zoomOut: zoomOut, zoom: zoom } })();<file_sep>/js_cms/_cms/directory.php <?php /** * JS_CMS -- realtime website development web application * http://js-cms.jp/ * Copyright 2015 <NAME> - <EMAIL> * licensed under the MIT licenses. */ //usleep(100*1000);//test define('CMS', true); require_once("./setting/setting.php"); require_once("./storage.funcs.php"); require_once("./storage.login.php"); /* ! ---------- pre ---------- ---------- ---------- ---------- */ header("Content-Type: application/json; charset=utf-8"); /* ! ---------- input ---------- ---------- ---------- ---------- */ $action = getVAL('action',"",""); if($action == "") status_error("invalid action name"); if(! is_action($action)) status_error("invalid action name"); $limitDeep = getVAL('limitDeep',1,"number"); $dir_name = getVAL('dir_name',"","path"); $is_detail = getVAL('is_detail',false,"booelan"); $showDir = getVAL('showDir',false,"booelan"); $extentions = getVAL('extentions',"",""); $exs; if($extentions != "") $exs = explode("_",$extentions); // "png_gif_jpeg_jpg" /* ! ---------- main ---------- ---------- ---------- ---------- */ function getExtraInfo($path){ $s = ""; $s .= '"w":"'.isWritableDir($path).'",'; $s .= '"fileCount":"'.getFileCount($path).'",'; $s .= '"dirCount":"'.getDirCount($path).'",'; // $s .= '"filesize":"'.filesize($path).'",'; $s .= '"filemtime":"'.date ("Y/m/d H:i:s", filemtime($path)).'",'; return $s; } function getFileCount($path){ global $exs; $dir = opendir($path); $count = 0; while($filename = readdir($dir)){ if (is_file($path.$filename) == true){ if($exs != null){ if(matchExtention($filename,$exs)){ $count++; } } else{ $count++; } } } closedir($dir); return($count); } function getDirCount($path){ $dir = opendir($path); $count = 0; while($filename = readdir($dir)){ if($filename == '.' || $filename == '..') continue; if (is_dir($path.$filename) == true){ $count++; } } closedir($dir); return($count); } function getDirectory($dir_path,$dir_name,$deep){ global $limitDeep; global $is_detail; $s = ""; $list = array(); $dir = opendir($dir_path); $isFirst = true; $s .= '"path":"'.$dir_path.'",'; $s .= '"name":"'.$dir_name.'",'; if($is_detail){ $s .= getExtraInfo($dir_path) ; } $s .= '"nodes":['; while($filename = readdir($dir)){ if($filename == '.' || $filename == '..') continue; if(substr($filename ,0 ,1) == ".") continue; $path = $dir_path.$filename; if(is_dir($path)){ if($deep < $limitDeep){ if($isFirst == false) $s .= ','; $s .= '{'; $s .= getDirectory($path."/",$filename,$deep+1); $s .= '}'; } $isFirst = false; } } closedir($dir); $s .= ']'; // if($s == '[,]' ) $s = ""; return $s; } function getFileList($dir_path){ global $exs; $dir = opendir($dir_path); $files = array(); $isFirst = true; while( $file_name = readdir( $dir ) ){ if (substr($file_name, 0,1) !=".") { if(! is_dir($dir_path.$file_name)){ if($exs != null){ if(matchExtention($file_name,$exs)){ array_push($files,$file_name); } } else{ array_push($files,$file_name); } } } } $s = ""; for ($i = 0 ; $i < count($files); $i++) { if($isFirst == false) $s .= ','; $filePath = $dir_path.$files[$i]; $s .= '{'; $s .= '"path":"'.$filePath.'",'; $s .= '"name":"'.$files[$i].'",'; $s .= '"filesize":"'.filesize($filePath).'",'; $s .= '"filemtime":"'.date ("Y/m/d H:i:s", filemtime($filePath)).'"'; $s .= '}'; $isFirst = false; } closedir($dir); return $s; } if($action == "getDirList"){ $json = ""; $json .='{'; $json .= getDirectory($dir_name,basename($dir_name),0); $json .='}'; echo($json); } if($action == "getFileList"){ $json = ""; $json .='{'; $json .='"files":['; $json .= getFileList($dir_name); $json .=']'; if($showDir){ $is_detail = true; $json .=',"nodes":{'; $json .= getDirectory($dir_name,basename($dir_name),0); $json .='}'; } $json .='}'; echo($json); } <file_sep>/src/js/cms_view_inspect/InspectView.FormU_Heading.js InspectView.FormU_Heading = (function(){ var view var v = {} var currentVal = "" function setNode(_view,_val){ view = _view; currentVal = _val; v.select = $(createSelectText(listHeading,_val)); view.find("._selectArea").append(v.select); view.find("._btn_heading").click(function(){ var tar = view.find("input._in_data_H_Type"); var s = $(this).data("id"); tar.val(s).keyup(); var s2 = $(this).text(); view.find("._selectBox ._name span").html(s2) updateView(s); }); } /* ! ---------- ---------- ---------- ---------- ---------- */ function updateView(_s){ currentVal = _s; var views = view.find("._btn_heading"); views.removeClass("_active"); views.each(function (index, dom) { var id = $(this).data("id"); if(currentVal == id) $(this).addClass("_active"); }); } /* ! ---------- ---------- ---------- ---------- ---------- */ var listHeading = [ ["h1" ,"<span>タイトル<H1></span>","1"], ["h2" ,"<span>大見出し<H2></span>","0"], ["h3" ,"<span>中見出し<H3></span>","0"], ["h4" ,"<span>小見出し<H4></span>","0"], ["h5" ,"<span style='font-size:10px;margin-top:10px'>小見出し2<H5></span>","0"], ["h6" ,"<span style='font-size:10px;'>小見出し3<H6></span>","0"] ]; function createSelectText (_vars,_current){ if(!_current)return ""; var a = _current.split(" "); var tag = '<div class="_selectBox">' tag += '<div class="_name"><span>{NAME}</span> <i class="fa fa-sort " style="color:yellow"></i></div>' tag += '<div class="_list">' for (var i = 0; i < _vars.length ; i++) { var seld = ""; for (var ii = 0; ii < a.length ; ii++) { if(_vars[i][0] == a[ii]) { seld = "_active" } } tag += '<div class="_btn_heading _btn_' + _vars[i][0] + " "+ seld +'" data-id="'+_vars[i][0]+'" >'+_vars[i][1]+'</div>'; } tag += "</div>"; tag += "</div>"; var seld = ""; for (var i = 0; i < _vars.length ; i++) { if(_vars[i][0] == _current) { seld = _vars[i][1]; } } tag = tag.split("{NAME}").join(seld); return tag; } return { setNode:setNode } })(); <file_sep>/src/js/cms_main/CMS_LoginView.js var CMS_LoginView = (function(){ var view; var v = {}; var useLogin = true; function init(){ stageInit(); } /* ---------- ---------- ---------- */ function createlayout(){ getLoginState(function(_s){ if(_s == "0")showLoginView(); if(_s == "1")logined(); if(_s == "2"){ useLogin = false; logined(); } }); } function setBtn(){ } function getLoginState(_callback) { var url = CMS_Path.PHP_LOGIN; $.ajax({ scriptCharset : 'utf-8', type : 'GET', url : url+"?action=state", dataType : 'json', success : function(data) { _callback(data.status); }, error : function(data) { CMS_ErrorView.stageIn("NET",url,null,data); } }); } function logined(){ callback(); setInterval(function(){ updateLoginState(); },1000*60*5); } /* ---------- ---------- ---------- */ function showLoginView(){ var tag = ""; tag += '<div id="CMS_LoginView">'; tag += ' <div class="_title">'+SITE_NAME+'</div>'; tag += ' <div class="_read">Powered by JS CMS version '+CMS_INFO.version +' <i class=" fa fa-info-circle"></i> '+CMS_INFO.loginAbout+'</div>'; tag += ' <table>'; tag += ' <tr><th>ID</th><td><input type="text" class="_in_login_u" /></td></tr>'; tag += ' <tr><th>PASS</th><td><input type="password" class="_in_login_p" /></td></tr>'; tag += ' <tr><th></th><td>' tag += ' <div class="_cms_btn_alpha _btn_memori_ac"><i class="fa fa-check-square "></i> ID PASSを保存する</div>' tag += ' <div class="_cms_btn_alpha _btn_memori"><i class="fa fa-square-o "></i> ID PASSを保存する</div>' tag += ' </td></tr>'; tag += ' <tr><td></td><td><div class="_cms_btn_alpha _btn_login">LOGIN</div></td></tr>'; tag += ' <tr><td></td><td><div class="_t_message"></div></td></tr>'; tag += ' </table>'; tag += '</div>'; $("body").html(tag); view = $('#CMS_LoginView'); view.show(); v.btn_login = view.find('._btn_login'); v.in_login_u = view.find('._in_login_u'); v.in_login_p = view.find('._in_login_p'); v.t_message = view.find('._t_message'); v.btn_login.click(function(){ var id = v.in_login_u.val(); var ps = v.in_login_p.val(); login(id,ps); }); setMemoriInit() } /* ---------- ---------- ---------- */ var isSaveLoginInfo = "1" function setMemoriInit() { if(localStorage["isSaveLoginInfo"]) isSaveLoginInfo = localStorage["isSaveLoginInfo"]; v.btn_memori_ac = view.find('._btn_memori_ac'); v.btn_memori = view.find('._btn_memori'); v.btn_memori_ac.click(function(){ setMemori("0")}); v.btn_memori.click(function(){ setMemori("1")}); setMemori(isSaveLoginInfo); if(isSaveLoginInfo != "0"){ var ids = ["",""]; if(localStorage["saveLoginInfo"]) ids =JSON.parse(localStorage["saveLoginInfo"]); v.in_login_u.val(ids[0]); v.in_login_p.val(ids[1]); } } function setMemori(_b) { v.btn_memori.hide() v.btn_memori_ac.hide() if(_b == "0"){ v.btn_memori.show() } else{ v.btn_memori_ac.show() } localStorage["isSaveLoginInfo"] = _b; } function setMemoriInfo(_id,_ps) { var a = ["",""] if(isSaveLoginInfo) a = JSON.stringify([_id,_ps]); localStorage["saveLoginInfo"] = a; } /* ---------- ---------- ---------- */ function login(_u,_p) { setMemoriInfo(_u,_p); var url = CMS_Path.PHP_LOGIN; $.ajax({ scriptCharset : 'utf-8', type : 'POST', url : url + "?action=login", data : {u:_u,p:_p}, dataType : 'json', success : function(data) {login_comp(data) }, error : function(data) { CMS_ErrorView.stageIn("NET",url,null,data); } }) } function login_comp(_json){ if(_json.status == 1){ stageOut(); callback(); } else{ v.t_message.html("ID、もしくはPASSが正しくありません"); } } /* ---------- ---------- ---------- */ function updateLoginState() { $.ajax({ scriptCharset : 'utf-8', type : 'GET', url : "login.php?action=state", dataType : 'json', success : function(data) { // } }); } /* ---------- ---------- ---------- */ function getLogout() { return useLogin } function logout() { $.ajax({ scriptCharset : 'utf-8', type : 'GET', url : CMS_Path.PHP_LOGIN + "?action=logout", dataType : 'json', success : function(data) { location.reload(); } }) } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit(){ //view.hide(); } var callback = true; function stageIn(_callback){ if(! isOpen){ isOpen = true; //view.show(); callback = _callback if(isFirst){ createlayout(); setBtn(); } isFirst = false; } } function stageOut(){ if(isOpen){ isOpen = false; //view.hide(); } } return { init: init, stageIn: stageIn, stageOut: stageOut, getLogout: getLogout, logout: logout } })(); <file_sep>/src/js/cms_model/PageElement.tag.note.js PageElement.tag.note = (function(){ var _ = new PageModel.Tag_(); /* ---------- ---------- ---------- */ _.pageInfo = new PageModel.Object_Info({ id : "tag.note", name : "制作用ノート", name2 : "", inputs : [] }); /* ---------- ---------- ---------- */ _.getInitData = function(){ var o = {}; o.type = _.pageInfo.id; o.data = "このテキストは制作用のノートです。HTMLには出力されません。"; o.attr ={} return o; } /* ---------- ---------- ---------- */ _.getPreview = function(_o){ var data = _o.data; var attr = _o.attrs; var tag = "" if(data == ""){ tag += '<span class="_no-input-data">制作用ノートを入力...</span>' } else{ tag += '<div class="_element_note"><i class="fa fa-lg fa-comment-o"></i> <b>制作用ノート:</b>' + CMS_TagU.t_2_tag(data) + '</div>'; } return tag; } /* ---------- ---------- ---------- */ _.getHTML = function(_o,_tab){ return ""; } /* ---------- ---------- ---------- */ return _; })();<file_sep>/src/js/cms_view_modals/DirTreeViewTest.js var DirTreeViewTest = (function(){ var view; var v = {}; function init(){ view = $('#DirTreeViewTest'); stageInit(); } /* ---------- ---------- ---------- */ function createlayout(){ v = ModalViewCreater.createBaseView(DirTreeViewTest,view); var tag = "" tag = '<div class="_title">ディレクトリ選択</div>' v.header.html(tag); tag = "" tag += '<div class="_replaceDir _dirTreeView"></div><br><br><br>' tag += '*********************************' tag += '<div class="_replaceDir1 _dirTreeView"></div><br><br><br>' tag += '*********************************' tag += '<div class="_replaceDir2 _dirTreeView"></div><br><br><br>' tag += '*********************************' tag += '<div class="_replaceDir3 _dirTreeView"></div>' v.body.html(tag); v.replaceDir = view.find('._replaceDir'); v.replaceDir1 = view.find('._replaceDir1'); v.replaceDir2 = view.find('._replaceDir2'); v.replaceDir3 = view.find('._replaceDir3'); tag = "" tag += '<div class="_cms_btn _btn_close">閉じる</div> '; v.footer.html(tag) v.btn_close = view.find('._btn_close'); // createCheck(); // setBtn(); var tree = new DirTreeViewNode( v.replaceDir,null,0, { initDeep :1, def :{ path: "", name: ""}, showCMSDir :true, showWriteDir :false, isClickNGDir :true, currentSelect :null, extentions :"", callback:function(s,_view){ if(isLog) console.log(s); } } ); window.openDIR = function(_s){ // openDIR("../test_blog_rename/cgi/lib/"); tree.setCurrent(_s) } var tree = new DirTreeViewNode( v.replaceDir1,null,0, { initDeep :1, def :{ path: "", name: ""}, showCMSDir :true, showWriteDir :false, isClickNGDir :true, currentSelect :null, hideRootNode :true, extentions :"", hideDirs :["../_cms/","../_backup/","../html/","../__"], callback:function(s){ if(isLog) console.log(s); } } ); /* ---------- ---------- ---------- */ var tree2 = new DirTreeViewNode( v.replaceDir2,null,0, { initDeep :1, def :{ path: "../html/", name: "html"}, showCMSDir :true, showWriteDir :true, isClickNGDir :true, currentSelect :null, extentions :"", callback:function(s){ if(isLog) console.log(s); } } ); /* ---------- ---------- ---------- */ var tree3 = new DirTreeViewNode( v.replaceDir3,null,0, { initDeep :1, def :{ path: "../uploads/", name: "uploads"}, showCMSDir :true, showWriteDir :true, isClickNGDir :true, currentSelect :null, extentions :"", callback:function(s){ if(isLog) console.log(s); } } ); tree3.setCurrent({dir:"../uploads/sub_3/",id:""}); setBtn(); } function setBtn(){ v.btn_close.click(function(){ stageOut(); }); } /* ---------- ---------- ---------- */ //表示・非表示処理 var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } function stageIn(){ if(! isOpen){ isOpen = true; view.show(); if(isFirst){createlayout()} isFirst = false; } } function stageOut(){ if(isOpen){ isOpen = false; view.hide(); } } return { init:init, stageIn:stageIn, stageOut:stageOut } })(); // var tID; // if(tID) clearTimeout(tID); // tID = setTimeout(function(){ // DirTreeViewTest.init(); // DirTreeViewTest.stageIn(); // },1000); <file_sep>/src/js/cms_util/CMS_SaveDateU.js var CMS_SaveDateU = (function(){ function getDate(){ return DateUtil.getFormattedDate(new Date(),"YYYY/MM/DD hh:mm:ss"); } function getRelatedDate(_s,_current){ if(!_s) return "--"; if(_s == "-") return "--"; var d = new Date(_s); var c = new Date(); if(_current != undefined)c = _current; var sec = (c.getTime()- d.getTime()) / (1000); var min = sec/60; var hour = min/60; var day = hour/24; var ss = ""; if(sec < 20){ ss = '<span class="_time-sec10">' + Math.floor(sec) +"秒前" + '</span>'; } else if(sec < 60){ ss = '<span class="_time-sec">' +Math.floor(sec) +"秒前" + '</span>' } else if(min < 60){ ss = '<span class="_time-min">' +Math.floor(min) +"分前" + '</span>'; } else if(hour < 24){ ss = '<span class="_time-hour">' +Math.floor(hour) +"時間前" + '</span>'; } else if(hour < 24*7){ ss = '<span class="_time-day7">' +Math.floor(day) +"日前" + '</span>'; } else if(hour < 24*30){ ss = '<span class="_time-day30">' +Math.floor(day) +"日前" + '</span>'; } else{ ss = '<span class="_time-day">' +Math.floor(day) +"日前" + '</span>'; } return ss; } return { getDate:getDate, getRelatedDate:getRelatedDate } })(); <file_sep>/src/js/cms_view_floats/FreeLayoutInfoView.js var FreeLayoutInfoView = (function(){ var view; var v = {}; function init(){ view = $('#FreeLayoutInfoView'); setBtn(); } /* ---------- ---------- ---------- */ function createlayout(){ v.inner = $('<div class="_inner"></div>'); view.append(v.inner) var tag = "" tag += '<div class="_item _item_edit" data-action="dClick">'+TIP2("#+Enter")+'<span class="_block_btn">'+Dic.I.Edit+'</span> ブロックを編集</div>'; tag += '<div class="_items">'; tag += ' <div class="_item-title">ブロックのコピペ</div>'; tag += ' <div class="_item-body">'; tag += ' <div class="_item" data-action="copyCurrent">'+TIP2("#+C")+'<i class="fa fa-copy"></i> コピー</div>'; tag += ' <div class="_item" data-action="cutCurrent">'+TIP2("#+X")+'<i class="fa fa-cut "></i> カット</div>'; tag += ' <div class="_item" data-action="pastCurrent">'+TIP2("#+V")+'<i class="fa fa-clipboard "></i> ペースト</div>'; tag += ' <div class="_item" data-action="pastCurrent2">'+TIP2("#+Shift+V")+'<i class="fa fa-clipboard "></i> 上書きペースト</div>'; tag += ' </div>'; tag += '</div>'; tag += '<div class="_item" data-action="duplicateCurrent">'+TIP2("#+D")+'<i class="fa fa-copy"></i> ブロックを複製</div>'; tag += '<div class="_items">'; tag += ' <div class="_item-title">ブロックの移動</div>'; tag += ' <div class="_item-body">'; tag += ' <div class="_item" data-action="moveTopCurrent"><i class="fa fa-angle-double-up "></i> 一番上へ</div>'; tag += ' <div class="_item" data-action="moveUpCurrent">'+TIP2("#+↑")+'<i class="fa fa-angle-up "></i> ひとつ上へ</div>'; tag += ' <div class="_item" data-action="moveDownCurrent">'+TIP2("#+↓")+'<i class="fa fa-angle-down "></i> ひとつ下へ</div>'; tag += ' <div class="_item" data-action="moveBottomCurrent"><i class="fa fa-angle-double-down "></i> 一番下へ</div>'; tag += ' </div>'; tag += '</div>'; tag += '<div class="_item " data-action="editJSON">{<i class="fa fa-ellipsis-h "></i>} 直接編集-JSON</div>'; tag += '<div class="_item " data-action="addToMyBlock"><i class="fa fa-plus-circle "></i> Myブロック登録</div>'; tag += '<div class="_item" data-action="deleteCurrent">'+TIP2("#+DELL")+'<i class="fa fa-times-circle " style="color:red"></i> ブロックを削除</div>'; tag += '<div class="_note">●操作ヒント<br>' tag += '<b>編集</b>:Ctrl-Enter or ダブルクリック<br>' tag += '<b>選択変更</b>:[↑][↓]<br>' tag += '<b>移動</b>:ドラッグ<br>'; tag += '</div>'; v.inner.html(tag); v.item_edit = view.find("._item_edit"); v.item = view.find("._item"); v.item.click(function(){ if($(this).hasClass("_disable"))return; var ac = $(this).data("action"); tar.click(); if(window.sc[ac]) window.sc[ac](); stageOut() }) view.hover( function(){ }, function(){ stageOut()} ) } function setBtn(){ } /* ---------- ---------- ---------- */ var tar function update(_view,_type){ tar = $(_view); var y = 0; if (CMS_StatusH < CMS_Status.mouseY + view.height() ) { y = CMS_StatusH - view.height() - 20 + "px"; } else{ y = CMS_Status.mouseY-10 + "px" } if(CMS_Status.mouseY + view.height() +10); view.css({ left: CMS_Status.mouseX-10 + "px", top: y }); var cs = tar.attr("class"); if(cs.indexOf("_freeLayoutTable") != -1 || cs.indexOf("_freeLayoutDiv") != -1){ v.item_edit.addClass("_disable"); } else { v.item_edit.removeClass("_disable"); } } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } function stageIn(_view,_type){ view.show(); if(isFirst){ createlayout(); } isFirst = false; update(_view,_type) } function stageOut(){ view.hide(); tar = null; } return { init:init, stageIn:stageIn, stageOut:stageOut } })(); <file_sep>/src/js/cms_view_modals/ImageDetailView.js var ImageDetailView = (function(){ var view; var v = {}; var baseDir = "../"; //var targetDir = "images/oneday/"; var targetDir = ""//"images/"; function init(){ view = $('#ImageDetailView'); v.replaceArea = view.find('.body .replaceArea'); var tag = '<div class="replacePath"></div>' tag += '<div class="clearfix">' tag += ' <div class="replaceDetail"></div>' tag += ' <input id="upload_image" type="file" name="image" enctype="multipart/form-data">' tag += "</div>"; v.replaceArea.html(tag); v.replaceDetail = view.find('.replaceDetail'); stageInit(); setBtn(); } /* ---------- ---------- ---------- */ function setBtn(){ view.find('._bg ,._btn_close').click(function(){ stageOut() }); $('#upload_image').change(function() { $(this).upload( CMS_Path.PHPH_UPLOAD_FILEPATH, _uploadFile_comp, 'json' ); }); } function _uploadFile_comp(){ alert(1) } function setVal(_val){ var a_img = new Image(); var p = _val.split("../").join("") a_img.src = CMS_Path.SITE.URL + p; a_img.onload = function(){ renderTag($(this).attr("src")) }; } function renderTag(_val){ var tag = ""; tag += '<p>'+_val+'</p>' tag += '<img src="'+_val+'">' v.replaceDetail.html(tag); setTimeout(function(){ var tag = "<div>" tag += "幅 : " + v.replaceDetail.find("img").width() + " , " tag += "高さ : " + v.replaceDetail.find("img").height() + "" v.replaceDetail.append(tag) } , 100); } function clickImage(_s){ callback(_s); stageOut(); } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; var callback = true; var currentPath = ""; function stageInit(){ view.hide(); } function stageIn(_val,_callback){ if(! isOpen){ isOpen = true; currentPath = _val; setVal(_val) callback = _callback; view.show(); } } function stageOut(){ if(isOpen){ isOpen = false; view.hide(); } } return { init:init, stageIn:stageIn, stageOut:stageOut } })();//modal underconst<file_sep>/src/js/cms_view_floats/SimpleToolTip.js var SimpleToolTip = (function(){ var view; var v = {}; function init(){ view = $('#SimpleToolTip'); stageInit(); createlayout(); setBtn(); } /* ---------- ---------- ---------- */ function createlayout(){ } function setBtn(){ } /* ---------- ---------- ---------- */ function update(_xy,_html){ view.css("left",_xy.x) view.css("top",_xy.y) view.html(_html) } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } function stageIn(_xy,_html){ // if(! isOpen){ isOpen = true; view.show(); if(isFirst){} isFirst = false; update(_xy,_html); // } } function stageOut(){ // if(isOpen){ isOpen = false; view.hide(); view.html("") // } } return { init:init, stageIn:stageIn, stageOut:stageOut } })();<file_sep>/src/js/cms_main/CMS_E.js var CMS_E = {} CMS_E.DIR_ERROR = "dir error"; CMS_E.PARSE_ERROR = '<div style="color:red;background:#ff0;">パースエラー</div>'; CMS_E.NOT_FOUND = "file or directory not found"; CMS_E.getText = function(_s){ if(_s == this.DIR_ERROR) return "ディレクトリがありません"; if(_s == this.NOT_FOUND) return "ディレクトリかファイルがありません"; return _s; } <file_sep>/src/js/copyright.js /** * JS_CMS -- realtime website development web application * http://js-cms.jp/ * Copyright 2018 <NAME> - <EMAIL> * licensed under the MIT licenses. */ <file_sep>/src/js/cms_view_editable/EditableView.FreeLayout.js /** * フリーレイアウトビュー * コンポジットクラスになっており、 * FreeLayoutか、FreeLayoutColsしか、使用しない * * オブジェクト要素をクリックで、SubPageViewを開く */ EditableView.FreeLayout = (function() { /* ---------- ---------- ---------- */ var c = function() { this.init(); } var p = c.prototype; /* ---------- ---------- ---------- */ p.isDragable = false; p.currentEditDetailNo = 0; p.init = function() { this.v = {}; this.isDragable = false; this.currentEditDetailNo = 0; } /* ---------- ---------- ---------- */ //#registParent p.registParent = function(_parent,_parentView,_pageParam,_deep){ this.parent = _parent; this.parentView = _parentView; this.pageParam = _pageParam; this.deep = (_deep == null) ? 0:_deep; } /* ---------- ---------- ---------- */ p.getData = function (){ return this.gridData.getRecords(); } p.getDataAt = function (_n){ return this.gridData.getRecordAt(_n); } p.addData = function (_type,_param){ var o = PageElement_Util.getInitData(_type,_param); this.gridData.addRecord(o); this.update(); this.parent.updateSubData(); } p.addDataAt = function (data,_n){ this.gridData.addRecordAt(data,_n); } p.changeData = function (data,no){ this.gridData.overrideRecordAt(data,no); this.parent.updateSubData(); } // p.historyData p.removeData = function (no){ this.gridData.removeRecordAt(no); this.update(); this.parent.updateSubData(); InspectView.stageOut(); this.select(no); } p.duplicateData = function (no){ this.gridData.duplicateAt(no); this.update(); this.parent.updateSubData(); this.select(no+1); } /* ---------- ---------- ---------- */ //#要素の移動 p.canMove = function (targetNo,_move){ return (this.gridData.isValidArge(targetNo,_move)); } p.moveData = function (targetNo,_move){ this.gridData.moveRecord(targetNo,_move); var t0 = this.v.replaceView.find('> *').eq(targetNo*2); var t1 = this.v.replaceView.find('> *').eq(targetNo*2+1); var t2 = this.v.replaceView.find('> *').eq(_move*2+1); t2.after(t1) t0.after(t2) var n1 = t1.attr("data-no"); var n2 = t2.attr("data-no"); t1.attr("data-no",n2) t2.attr("data-no",n1) this.parent.updateSubData(); } //20150527 最初と最後に移動を追加 p.moveDataToFirst = function (targetNo){ var _move = this.gridData.moveRecordToFirst(targetNo); this.update(); this.select(_move); this.parent.updateSubData(); return _move; } p.moveDataLast = function (targetNo){ var _move = this.gridData.moveRecordToLast(targetNo); this.update(); this.select(_move); this.parent.updateSubData(); return _move; } p.initData = function (_data,_no){ this.no = _no; this.type = _data.type; this.attr = _data.attr; this.extra = _data.extra; this.gridData = new EditableView.GridClass(); this.gridData.initRecords(_data.data); this.setInitView(); this.update(); } p.setInitView = function (){ var self = this; if(this.deep > 0 && this.parent.type == "layout.div") this.isDragable = true; if(this.deep > 0 && this.parent.type == "replace.div") this.isDragable = true; // var className = ""; var rootStyle = "" // var title = ""; if(this.deep == 0){ //ルートDIV時 this.parent.setFreeLayout(this) className = "_freeLayoutRoot"; //編集幅を指定 rootStyle += CMS_SizeManager.getContentsWidth(this.pageParam.type); AddElementsManager.setData(this,this.getData().length-1) //コンテクストメニュー var ts = '._freeLayout,._freeLayoutDiv,._freeLayoutTable,._freeLayoutCols' this.parentView.on('contextmenu',ts,function(){ if(window.isPressCommandKey)return; FreeLayoutInfoView.stageIn(this); $(this).click() return false; }) } else{ if(this.parent.type != "layout.cols"){ className = "_freeLayoutDiv _freeLayoutToggle" } else{ className = "_freeLayoutCols"; } }; //入力ID名やブロック出力のタグを取得 var blockInfo = (function(_deep,_attr,_class){ if(_deep == 0) return ""; if(_class.indexOf("_freeLayoutDiv") != -1) return CMS_BlockAttrU.getMarkTag(_attr,true) return "" })(this.deep,this.attr,className); var _style = (function(_ex,_attr,_root){ var _bg = CMS_ImgBlockU.getBgStyle(_ex); var _input = CMS_BlockAttrU.get_style(_attr) ; return _bg + " " + _input + " " + _root; })(this.extra, this.attr, rootStyle); var _class = CMS_BlockAttrU.get_class(this.attr); var _aliasId = CMS_BlockAttrU.get_id(this.attr); _aliasId = (_aliasId) ? "_alias_" + _aliasId :""; if(this.parent.type != "layout.cols"){ var tag = ""; tag += '<div class=" '+className+" " +_aliasId+'" data-no="'+this.no+'">'; tag += '<div class="cms-layout _replaceArea ' + _class + '" style="' + _style + '"></div>'; tag += blockInfo; // tag += (!this.isDragable) ? "": ; if (this.isDragable) { tag += '<span class="_btn_delete"></span>' if(this.deep == 1){ if(this.attr.narrow){ tag += '<span class="_block_toggle _block_toggle_close"></span>'; } else{ tag += '<span class="_block_toggle"></span>'; } } } tag += '</div>'; this.view = $(tag); this.parentView.append(this.view); this.v.replaceView = this.view.find('> ._replaceArea'); this.view.find(' > ._btn_delete').click(function(){ $(this).parent().click(); InspectView.doCommand("delete"); }); this.view.find(' > ._block_toggle').click(function(){ $(this).parent().click(); $(this).toggleClass("_block_toggle_close"); InspectView.doCommand("toggle"); }); //コンテナブロック ボタン this.view.on('click','._block_info ._btn',function(){ $(this).parent().parent().parent().click(); InspectView.doCommand($(this).data("command"),$(this).data("extra")); }); //Myタグ定義 表示切り替え // this.view.on('click','._block_info ._replace_id',function(){ // $(this).parent().parent().parent().parent().toggleClass("_cms_replace_open"); // }); } else{ this.view = this.parent.v.replaceView.eq(this.no); this.view.attr("style", _style); this.view.attr("class", this.view.attr("class") + " " + _class); this.v.replaceView = this.parent.v.replaceView.eq(this.no); } } /* ---------- ---------- ---------- */ //#update p.update = function (){ var self = this; var list = this.gridData.getRecords(); this.v.replaceView.html(""); //createViews for (var i = 0; i < list.length ; i++) { if(list[i] !== null){ this.v.replaceView.append(DragController.getDropTag(i)); var targetReplaceV = this.v.replaceView if(this.v.replaceView.length >1){ targetReplaceV = this.v.replaceView.eq(i); } var type = list[i].type; if (type == "layout.div" || type == "replace.div" ) { var node = new EditableView.FreeLayout(); node.registParent(this,targetReplaceV,this.pageParam,this.deep +1); node.initData(list[i],i); node.view.click(function(event){ event.stopPropagation(); InspectView.setPageData(this.pageParam); InspectView.setData("layout.div",$(this) , self ,null, $(this).find("> div").eq(0)); }); } else if(type == "layout.cols"){ var node = new EditableView.FreeLayoutCols(); node.registParent(this,targetReplaceV,this.pageParam,this.deep +1); node.initData(list[i],i); node.view.click(function(event){ event.stopPropagation(); InspectView.setPageData(this.pageParam); InspectView.setData("col", $(this), self, $(this), $(this).find("> div").eq(0)); }); } else { var _free = PageElement_Util.getPreview(list[i]); _free = HTMLServiceU.getReplacedHTML(_free,this.pageParam,type,false); var tag = ""; tag += '<div class="_freeLayout '+'" data-no="'+i+'">'; tag += _free; tag += CMS_BlockAttrU.getCommandTag(type); tag += CMS_BlockAttrU.getMarkTag(list[i].attr,true); tag += ' <span class="_btn_delete"></span>' tag += '</div>'; try{ this.v.replaceView.append(tag); }catch( e ){ this.v.replaceView.append(CMS_E.PARSE_ERROR); } } } } this.v.replaceView.append(DragController.getDropTag(list.length)); //クリック this.v.freeLayout = this.v.replaceView.find('> ._freeLayout'); this.v.freeLayout.bind("click",function(event){ var this_ = $(this); InspectView.setPageData(self.pageParam); InspectView.setData("object",this_ , self ,this_ ,this_.find("> * ").eq(0)); return false; }); this.v.freeLayout.bind("dblclick",function(event){ var this_ = $(this); InspectView.setPageData(self.pageParam); InspectView.setData_DoubleClick("object",this_ , self ,this_ ,this_.find("> * ").eq(0)); return false; }); //削除 this.v.freeLayout.find('._btn_delete').bind("mouseup",function(){ $(this).parent().click(); InspectView.doCommand("delete"); }); this.v.freeLayout.on('click','._block_command ._btn',function(){ $(this).parent().parent().click(); InspectView.doCommand($(this).data("command")); }); this.v.freeLayout.on('click','._block_info ._btn',function(){ $(this).parent().parent().parent().click(); InspectView.doCommand($(this).data("command"),$(this).data("extra")); }); /* ---------- ---------- ---------- */ //ドラッグ if(this.isDragable){ DragController.setDrag(this.parent,this.view,DragController.FREE_DROP); } DragController.setDrag(this,this.v.replaceView.find("> ._freeLayout"),DragController.FREE_DROP); DragController.setDrop(this,this.v.replaceView.find("> ._dropArea"),DragController.FREE_DROP); // this.updateSubData(); } p.updateSubData = function(){ this.parent.updateSubData(); } /* ---------- ---------- ---------- */ //#グリッドエディタ表示管理 //フリーレイアウトで、表組をクリックして編集画面を開くなど p.showInlineGridEditor = function(no,_subPageType){ currentEditDetailNo = no; var record = this.gridData.getRecordAt(no); this.detailNo = no; this.detailView = null; this.detailView = new EditableView.SubPageView(); this.detailView.setObjectType(_subPageType); this.detailView.registParent(this); this.detailView.createView(); this.detailView.initData(record.data); this.detailView.stageIn(); } p.hideInlineGridEditor = function(_updated){ if(! _updated) return; var _array = this.detailView.getData(); var record = this.gridData.getRecordAt(currentEditDetailNo); record.data = _array; this.gridData.overrideRecordAt(record,this.detailNo); this.update(); this.parent.updateSubData(); this.select(this.detailNo); } /* ---------- ---------- ---------- */ // p.selectNodeNext = function(_n){ this.select(_n); } p.select = function(_n){ try{ var tar = this.v.replaceView.find('> *').eq(_n*2+1); tar.trigger("click"); currentTop = tar.offset().top; }catch( e ){ currentTop = 0; } } return c; })(); <file_sep>/src/js/cms_stage_asset/CMS_Asset_FilePreviewView.js var CMS_Asset_FilePreviewView = (function(){ var view; var v = {}; /* ---------- ---------- ---------- */ //初期化 function init(){ view = $('#CMS_Asset_FilePreviewView'); createlayout(); } function createlayout(){ var tag = "" tag += '<div class="_header">' tag += ' <div class="_header_inner">' tag += ' <div class="_title"></div>' tag += ' </div>' tag += '</div>' tag += '<div class="_body _asset-scroll">' tag += '</div>'; view.html(tag); v.header = view.find("._header"); v.title = view.find("._header ._title"); v.body = view.find("._body"); } function openPage(_param){ var _t = CMS_Path.ASSET.getAbsPath_deco_file(_param.id , _param.dir); v.title.html('<div class="_fs12 _filePath_wh _cms_btn_alpha">' + _t +'</div>'); var path = _param.dir + _param.id; var tag = ""; var b = false; var ex = CMS_AssetFileU.getExtention(_param.id); if(CMS_AssetFileU.isExtention(ex,"img")){ b = true; tag += '<div class="_body_core"><img src="{URL}" class="_cms_bg_trans"></div>'; } if(CMS_AssetFileU.isExtention(ex,"mov")){ b = true; tag += '<div class="_body_core"><video controls src="{URL}"></div>'; } if(CMS_AssetFileU.isExtention(ex,"pdf")){ b = true; tag += '<iframe class="_preview" src ="{URL}" ></iframe>'; } if(b){ tag = tag.split("{URL}").join(path); } else{ tag += '<div class="_body_core"><div class="_anno">このファイルは、プレビューできません</div></div>'; } v.body.html(tag); } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } function stageIn(_param){ // if(! isOpen){ isOpen = true; view.show(); openPage(_param); // } } function stageOut(){ // if(isOpen){ isOpen = false; view.hide(); // } } return { init: init, stageIn: stageIn, stageOut: stageOut, } })();<file_sep>/src/js/cms_model/PageModel.Object_Grid.js PageModel.Object_Grid = (function() { /* ---------- ---------- ---------- */ var c = function(o,addPub) { this.init(o,addPub); } var p = c.prototype; /* ---------- ---------- ---------- */ p.addPub p.init = function (o,_addPub){ this.param = o; this.addPub = (_addPub == undefined) ? true : _addPub; this.setParam(); } p.setParam = function (){ this.isNarrow = (this.param.isNarrow !== undefined) ? this.param.isNarrow : false; this.gridType = this.param.gridType; this.gridInfo = this.param.gridInfo; this.multiGridRepeat = this.param.multiGridRepeat; this.textData = this.param.textData; this.hideGridEdit = (this.param.hideGridEdit !== undefined) ? this.param.hideGridEdit : false; if(this.param.gridData){ if(this.addPub){ var pub = new PageModel.OG_Cell({ id: "publicData", name: "公開", type: CELL_TYPE.CHECK, style: "", view: "", def: "1" }); this.param.gridData.cells.unshift(pub); var edit = new PageModel.OG_Cell({ id: "_state", name: "編集フラグ", type: CELL_TYPE.STATE, style: "", view: "", def: "" }); this.param.gridData.cells.push(edit); } } this.gridData = this.param.gridData; } p.getInitData = function (_o,_n){ if(_n == undefined) _n = 1; var o = { texts:{}, grid:[] } if(this.textData){ for (var i = 0; i < this.textData.cells.length ; i++) { var tar = this.textData.cells[i]; o.texts[tar.id] = tar.def; } } if(this.param.gridData){ for (var n = 0; n < _n ; n++) { o.grid[n] = {} for (var i = 0; i < this.param.gridData.cells.length ; i++) { var tar = this.param.gridData.cells[i]; o.grid[n][tar.id] = tar.def; } } } _o[this.gridInfo.id] = o; } p.getTestTag = function() { function _getTag(_list){ var tag = ""; tag += ' <table>'; tag += ' <tr>'; tag += ' <td>'; tag += _list.info.getTestTag(); tag += ' </td>'; tag += ' <td>'; tag += ' <table class="_ut_grid">'; tag += ' <tr>'; tag += ' <th>id</th>'; tag += ' <th>name</th>'; tag += ' <th>type</th>'; tag += ' <th>view</th>'; tag += ' <th>def</th>'; tag += ' <th>note</th>'; tag += ' <th>list</th>'; tag += ' <th>style</th>'; //tag += ' <th>class_</th>'; tag += ' <th>vals</th>'; tag += ' </tr>'; var cells = _list.cells; for (var i = 0; i < cells.length ; i++) { tag += cells[i].getTestTag() } tag += ' </table>'; tag += ' </td>'; tag += ' </tr>'; tag += ' </table>'; return tag } var gridTag = ""; gridTag += '<div class="_ut_gridText_text">' if(this.textData != undefined){ gridTag += _getTag(this.textData) } gridTag += '</div>'; gridTag += '<div class="_ut_gridText_grid">' if(this.gridData != undefined){ gridTag += _getTag(this.gridData) } gridTag += '</div>'; var tag = ""; tag += '<div class="_ut_grids">' tag += ' <table>'; tag += ' <tr>'; tag += ' <td>'+this.gridInfo.getTestTag()+'</td>'; tag += ' <td>'+gridTag+'</td>'; tag += ' </tr>'; tag += ' </table>'; tag += '</div>'; return tag; } return c; })();<file_sep>/src/js/cms_model/PageModel.OG_SubInfo.js PageModel.OG_SubInfo = (function() { /* ---------- ---------- ---------- */ var c = function(o) { this.init(o); } var p = c.prototype; /* ---------- ---------- ---------- */ p.param; p.name; p.note; p.sub; p.image; p.init = function (o) { this.param = o; this.name; this.note; this.sub; this.image;//BaseGridのサイドに表示される this.image2;// this.setParam(); } p.setParam = function (){ this.name = defaultVal(this.param.name, ""); this.note = defaultVal(this.param.note, ""); this.sub = defaultVal(this.param.sub, ""); this.image = defaultVal(this.param.image, ""); this.freeHTML = defaultVal(this.param.freeHTML, ""); } p.getHeadTag = function (){ var tag = "" tag += '<div class="_head ">' if(this.name != "")tag += '<div class="_h3">'+this.name +'</div>' if(this.note != "")tag += '<div class="_read">'+this.note +'</div>' if(this.freeHTML != "")tag += this.freeHTML; tag += '</div>' return tag; } p.getFootTag = function (){ var tag = "" tag += '<div class="_foot">' if(this.sub != ""){ tag += '<div class="_read">'+this.sub +'</div>' } tag += '</div>' return tag; } p.getTestTag = function (){ var tag = "" tag += '<table class="_ut_info _ut_w300">'; tag += ' <tr><th>name</th><td>' + this.name + '</td></tr>'; tag += ' <tr><th>note</th><td>' + this.note + '</td></tr>'; tag += ' <tr><th>sub</th><td>' + this.sub + '</td></tr>'; tag += ' <tr><th>image</th><td>' + this.image + '</td></tr>'; tag += '</table>'; return tag; } //BaseGridのサイドに表示される p.getGuideImageTag = function (){ var tag = ""; // if(this.image) tag += '<img src="' + this.image +'" style="">' if(this.image) tag += this.image return tag; } return c; })();<file_sep>/src/js/cms_view_floats/Float_Preview.4.js var Float_PreviewFull = (function(){ var view; var v = {}; function init(){ view = $('#Float_PreviewFull'); stageInit(); createlayout(); setBtn(); } /* ---------- ---------- ---------- */ function createlayout(){ var tag = ""; tag += '<div class="_arrow"></div>'; tag += '<div class="_zoomArea"></div>'; tag += '<div class="_inner"></div>'; tag += '<div class="_cms_btn_alpha _btn_preview_close"><i class="fa fa-caret-up "></i> プレビューを閉じる</div>'; view.html(tag) v.inner = view.find('._inner'); v.arrow = view.find('._arrow'); v.zoomArea = view.find('._zoomArea'); Float_PreviewFullZoom.init(view,v.zoomArea); } function setBtn(){ view.hover(function(){ if(tID) clearTimeout(tID) } , function(){ stageOut(); }) v.btn_preview_close = view.find('._btn_preview_close'); v.btn_preview_close.click(function(){ Float_Preview.switchPreview(false); }); } /* ---------- ---------- ---------- */ function update(_type,_xy,_param){ updatePos(_xy); if(prevPage) prevPage.stageOut(); var tar = hasPage(_type,_param); if(tar == null){ tar = new Float_PreviewFrame(_type,v.inner,_param); pages.push(tar); } tar.stageIn(); prevPage = tar; current = prevPage; if(_type == Dic.ListType.DIR)v.btn_preview_close.hide(); if(_type == Dic.ListType.PAGE)v.btn_preview_close.show(); } var current; function getCurrent(){ return current; } var prevPage; var pages = []; function hasPage(_type,_param){ var u = CMS_Path.PAGE.getRelPath(_param.id,_param.dir) for (var i = 0; i < pages.length ; i++) { if(_type == Dic.ListType.PAGE){ if(pages[i].type == _type){ if(pages[i].url == u){ return pages[i]; } } } if(_type == Dic.ListType.DIR){ if(pages[i].type == _type){ if(pages[i].id == _param.id){ return pages[i]; } } } } return null; } /* ---------- ---------- ---------- */ var prevY = -1; var currentY = -1; function updatePos(_xy){ v.arrow.css("top", (_xy.y-35) + "px"); /* var tarY = _xy.y var saH = CMS_StatusH - view.height() ; if(saH < tarY) tarY = saH; if(tarY < 100) tarY = 100; if(prevY == -1){ currentY = tarY - 50 view.css("top",currentY+ "px"); } var saY = tarY - currentY; v.arrow.css("top", _xy.y + "px"); prevY = tarY */ } /* ---------- ---------- ---------- */ function updateSitemapDate(){ for (var i = 0; i < pages.length ; i++) { pages[i].resetDate(); } } /* ---------- ---------- ---------- */ function getPages(){ return pages; } /* ---------- ---------- ---------- */ var isOpen = false; var isFirst = true; function stageInit(){ view.hide(); } function stageIn(_type,_xy,_param){ // if(! isOpen){ isOpen = true; if(isFirst){} if(tID) clearTimeout(tID) tID = setTimeout(function(){ view.show(); isFirst = false; update(_type,_xy,_param) },50); // } } var tID; function stageOut(){ if(tID) clearTimeout(tID) tID = setTimeout(function(){ view.hide(); prevY = -1; },500); } function stageOut_core(){ if(tID) clearTimeout(tID) view.hide(); prevY = -1 } return { init: init, getPages: getPages, getCurrent: getCurrent, stageIn: stageIn, stageOut: stageOut, stageOut_core: stageOut_core, updateSitemapDate: updateSitemapDate } })(); var FloatPreviewState = { currentWs:["1000"], currentZoom:0.33 } var Float_PreviewFullZoom = (function(){ var parentView; var view; var v = {}; /* ---------- ---------- ---------- */ //初期化 function init(_parentView,_view){ parentView = _parentView; view = _view; createlayout(); setBtn(); initStage(); } /* ---------- ---------- ---------- */ //レイアウト作成・イベントアサイン function createlayout(){ var tag = "" tag += ' <div class="_btnSet">幅 :'; tag += ' <span class="_btn_ws _cms_btn_alpha">1000px</span>'; tag += ' </div>'; tag += ' <div class="_btnSet">拡大 :'; tag += ' <span class="_cms_btn_alpha _btn_zoomOut"><i class="fa fa-lg fa-minus-circle "></i> '; tag += ' </span>'; tag += ' <span class="_cms_btn_alpha _btn_zoom">33%</span>'; tag += ' <span class="_cms_btn_alpha _btn_zoomIn"><i class="fa fa-lg fa-plus-circle "></i> '; tag += ' </span>'; tag += ' </div>'; view.html(tag); } function setBtn(){ v.btn_ws = view.find('._btn_ws'); v.btn_ws.click(function(){ setW(prompt("プレビュー幅を指定してください(px)。カンマで区切ると複数のプレビューを作成できます。",currentWs.join(","))); }); v._btn_zoom = view.find('._btn_zoom'); v._btn_zoom.click(function(){ zoomInput() }); v._btn_zoomOut = view.find('._btn_zoomOut'); v._btn_zoomIn = view.find('._btn_zoomIn'); v._btn_zoomOut.click(function(){ zoomOut() }); v._btn_zoomIn.click(function(){ zoomIn() }); } /* ---------- ---------- ---------- */ var currentWs function updateState(){ Storage.Memo.setListPreviewState([ currentZoom , currentWs.join(",") ]); var pages = Float_PreviewFull.getPages(); var current = Float_PreviewFull.getCurrent(); updateStateView(); for (var i = 0; i < pages.length ; i++) { pages[i].reset(); } if(current) current.updateWS_State(); } function updateStateView(){ FloatPreviewState.currentWs = currentWs; FloatPreviewState.currentZoom = currentZoom; v._btn_zoom.html(currentZoom+"%"); v.btn_ws.html(currentWs.join(",")+"px"); var ww = (function(_w,_z){ var w = 0; for (var i = 0; i < _w.length ; i++) { w += Number(_w[i]); } var ss = (w * (_z/100)) + 30; if(ss < 250)ss = 250; return ss; })(currentWs, currentZoom); parentView.width(ww); updateZoomState(); } function initStage(){ var state = Storage.Memo.getListPreviewState(); currentZoom = parseInt(state[0]); if(currentZoom < minZoom)currentZoom = minZoom; if(currentZoom > maxZoom)currentZoom = maxZoom; currentWs = state[1].split(","); updateStateView(); } function setW(_s){ if(!_s) return; var a = _s.split(",") for (var i = 0; i < a.length ; i++) { if(isNaN(a[i]))return; } currentWs = _s.split(","); for (var i = 0; i < currentWs.length ; i++) { var s = currentWs[i] if(s < 320) s = 320; if(s > 2000)s = 2000; currentWs[i] = s } updateState(); } /* ---------- ---------- ---------- */ var currentZoom = 50; var zooms = [10,20, 25, 33, 50 ]; function zoomInput(){ zoom(parseInt(prompt("ズーム値を指定してください(10〜50%)",currentZoom))); } var minZoom = 10; var maxZoom = 50; function zoomIn(){ var s = maxZoom; for (var i = 0; i < zooms.length ; i++) { if(currentZoom < zooms[i]){ s = zooms[i]; break; } } zoom(s); } function zoomOut(){ var s = zooms[0]; for (var i = 0; i < zooms.length ; i++) { if(currentZoom > zooms[i]){ s = zooms[i]; } } zoom(s); } function zoom(_s){ if(!_s)return; if(isNaN(_s))return; if(currentZoom == _s)return; if(_s >= maxZoom) { _s = maxZoom; } if(_s <= zooms[0]) { _s = zooms[0]; } currentZoom = _s; updateState(); } function updateZoomState(){ v._btn_zoomIn.removeClass("_btn_disable"); v._btn_zoomOut.removeClass("_btn_disable"); if(currentZoom == maxZoom) { v._btn_zoomIn.addClass("_btn_disable"); } if(currentZoom == zooms[0]) { v._btn_zoomOut.addClass("_btn_disable"); } } return { init:init } })();
06a332d403fbe63f93ffe5eafc3faefdfad67613
[ "JavaScript", "Markdown", "PHP" ]
214
JavaScript
ediezindell/js-cms
10b2eb4a1942e12c33714d3bdc4ff978c14485a8
79edc3c023a8f2d6d531951ab0ebdb51677a5f3f
refs/heads/master
<repo_name>Jonathan0832/Netbeans<file_sep>/Home.java import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JOptionPane; import javax.swing.Timer; import javax.swing.UIManager; import javax.swing.plaf.ColorUIResource; import proyecto.Ventana; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author Vic */ public class Home extends javax.swing.JFrame { Timer t; int x = 0; ActionListener Al; String[] random = new String[]{"Corriendo la aplicación", "Cargando Modulos", "Configurando Metodos", "Estableciendo Parametros", "Habilitando Archivos"}; /** * Creates new form Home */ public Home() { initComponents(); ColorUIResource colorResource = new ColorUIResource(Color.green.darker().darker()); UIManager.put("nimbusOrange",colorResource); Al = (ActionEvent ae) -> { int Min = 1; int Max = 10; int s = Min + (int) (Math.random() * ((Max - Min) + 1)); x = x + s; Barra.setValue(x); int ran = 0 + (int) (Math.random() * ((3 - 0) + 1)); Etiqueta.setText(random[ran]); if (Barra.getValue() == 100) { this.dispose(); t.stop(); /*Aquí va el siguiente form*/ Ventana menu = new Ventana(); menu.setVisible(true); //JOptionPane.showMessageDialog(null,"Aquí el siguiente form!"); } }; t = new Timer(300, Al); t.start(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { Etiqueta = new javax.swing.JLabel(); Barra = new javax.swing.JProgressBar(); jLabel2 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("INICIO"); setAlwaysOnTop(true); setMinimumSize(new java.awt.Dimension(498, 270)); setUndecorated(true); setResizable(false); setSize(new java.awt.Dimension(500, 300)); setType(java.awt.Window.Type.UTILITY); getContentPane().setLayout(null); Etiqueta.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N Etiqueta.setForeground(new java.awt.Color(255, 255, 255)); Etiqueta.setText("------------------------"); getContentPane().add(Etiqueta); Etiqueta.setBounds(20, 230, 230, 20); Barra.setBackground(new java.awt.Color(255, 255, 255)); Barra.setForeground(new java.awt.Color(255, 255, 255)); Barra.setBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED, new java.awt.Color(255, 255, 255), new java.awt.Color(255, 255, 255))); Barra.setBorderPainted(false); getContentPane().add(Barra); Barra.setBounds(20, 250, 460, 10); jLabel2.setFont(new java.awt.Font("Verdana", 1, 48)); // NOI18N jLabel2.setForeground(new java.awt.Color(255, 255, 255)); jLabel2.setText("3JVC"); getContentPane().add(jLabel2); jLabel2.setBounds(20, 100, 140, 60); jLabel4.setFont(new java.awt.Font("Verdana", 0, 18)); // NOI18N jLabel4.setForeground(new java.awt.Color(255, 255, 255)); jLabel4.setText("& ENCRYPTING"); getContentPane().add(jLabel4); jLabel4.setBounds(20, 170, 140, 23); jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Logoas.png"))); // NOI18N getContentPane().add(jLabel3); jLabel3.setBounds(270, 10, 224, 210); jLabel5.setFont(new java.awt.Font("Verdana", 0, 18)); // NOI18N jLabel5.setForeground(new java.awt.Color(255, 255, 255)); jLabel5.setText("COMPRESSING"); getContentPane().add(jLabel5); jLabel5.setBounds(20, 150, 140, 23); jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/fondo-a.jpg"))); // NOI18N jLabel1.setMaximumSize(new java.awt.Dimension(500, 300)); jLabel1.setMinimumSize(new java.awt.Dimension(498, 168)); jLabel1.setPreferredSize(new java.awt.Dimension(500, 300)); getContentPane().add(jLabel1); jLabel1.setBounds(0, 0, 500, 270); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Home.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Home().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JProgressBar Barra; private javax.swing.JLabel Etiqueta; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; // End of variables declaration//GEN-END:variables } <file_sep>/LZWCompresion.java package proyecto; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author Vic */ import java.io.*; import java.util.*; public class LZWCompresion { // Definir un HashMap y otras variables public HashMap<String, Integer> dictionary = new HashMap<>(); public int dictSize = 256; public String str = ""; public byte inputByte; public byte[] buffer = new byte[3]; public boolean onleft = true; public void compress(String uncompressed) throws IOException { // Este es el limite de tamaño del diccionario, se construye el diccionario for (int i = 0; i < 256; i++) { dictionary.put(Character.toString((char) i), i); } String[] archivo; // Leer el archivo no comprimido y escribir archivo comiprimido RandomAccessFile read = new RandomAccessFile(uncompressed, "r"); //Aquí puse la extensión con la que se va guardar el archivo comprimido ".lzw" archivo = uncompressed.split("\\."); RandomAccessFile out = new RandomAccessFile(archivo[0] + ".lzw", "rw"); try { // Lee el primer caracter del archivo ingresado en el string inputByte = read.readByte(); int i = new Byte(inputByte).intValue(); if (i < 0) { i += 256; } char ch = (char) i; str = "" + ch; // Lee caracter x caracter while (true) { inputByte = read.readByte(); i = new Byte(inputByte).intValue(); if (i < 0) { i += 256; } System.out.print(i + ", "); ch = (char) i; // Si str + ch está en el diccionario... // asignar str a str + ch if (dictionary.containsKey(str + ch)) { str = str + ch; } else { String s12 = to12bit(dictionary.get(str)); // Almacena los 12 bits en un arreglo y luego lo escribe en un archivo de salida if (onleft) { buffer[0] = (byte) Integer.parseInt(s12.substring(0, 8), 2); buffer[1] = (byte) Integer.parseInt(s12.substring(8, 12) + "0000", 2); } else { buffer[1] += (byte) Integer.parseInt(s12.substring(0, 4), 2); buffer[2] = (byte) Integer.parseInt(s12.substring(4, 12), 2); for (int b = 0; b < buffer.length; b++) {out.writeByte(buffer[b]); buffer[b] = 0; } } onleft = !onleft; // Agrega str + ch al diccionario if (dictSize < 4096) { dictionary.put(str + ch, dictSize++); } // asigna str a ch str = "" + ch; } } } catch (IOException e) { String str12bit = to12bit(dictionary.get(str)); if (onleft) { buffer[0] = (byte) Integer.parseInt(str12bit.substring(0, 8), 2); buffer[1] = (byte) Integer.parseInt(str12bit.substring(8, 12) + "0000", 2); out.writeByte(buffer[0]); out.writeByte(buffer[1]); } else { buffer[1] += (byte) Integer.parseInt(str12bit.substring(0, 4), 2); buffer[2] = (byte) Integer.parseInt(str12bit.substring(4, 12), 2); for (int b = 0; b < buffer.length; b++) { out.writeByte(buffer[b]); buffer[b] = 0; } } read.close(); out.close(); } } /** * Convierte 8 bit a 12 bits */ public String to12bit(int i) { String str = Integer.toBinaryString(i); while (str.length() < 12) { str = "0" + str; } return str; } //Ya el main public static void main(String[] args) throws IOException { try { LZWCompresion lzw = new LZWCompresion(); //Instancia de la clase Scanner input = new Scanner(System.in); System.out.println("Ingrese el nombre de su (nombredearchivo.txt) archivo..."); String str = input.nextLine(); //Para ingresar el nombre del objeto que tenemos almacenado File file = new File(str); Scanner fileScanner = new Scanner(file); String line = ""; while (fileScanner.hasNext()) { line = fileScanner.nextLine(); System.out.println("Los contenidos de su archivo estan siendo comprimidos: \n" + line); } lzw.compress(str); System.out.println("\n¡La compresion ha sido exitosa!"); System.out.println("El nombre de su nuevo archivo es: " + str.concat(".txt.vic")); } catch (FileNotFoundException e) { System.out.println("¡Archivo no encontrado!"); } } }<file_sep>/Inicio.java import java.awt.Color; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ImageIcon; import javax.swing.JOptionPane; import javax.swing.Timer; import javax.swing.UIManager; import javax.swing.plaf.ColorUIResource; import proyecto.Ventana; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author Vic */ public class Inicio extends javax.swing.JFrame { Timer t; int x = 0; ActionListener Al; String[] random = new String[]{"Corriendo la aplicación", "Un poco más para iniciar", "¡Ya casi estamos ahí!", "¡Espéranos un poco más!"}; /** * Creates new form Inicio */ public Inicio() { initComponents(); ImageIcon jvc = new ImageIcon(getClass().getResource("/imagenes/Logo.png")); ImageIcon icono = new ImageIcon(jvc.getImage().getScaledInstance(Background.getWidth(),Background.getHeight(),Image.SCALE_DEFAULT)); ColorUIResource colorResource = new ColorUIResource(Color.green.darker().darker()); UIManager.put("nimbusOrange",colorResource); Background.setIcon(icono); Al = (ActionEvent ae) -> { int Min = 1; int Max = 25; int s = Min + (int) (Math.random() * ((Max - Min) + 1)); x = x + s; Barra.setValue(x); int ran = 0 + (int) (Math.random() * ((3 - 0) + 1)); Etiqueta.setText("Cargando... " + random[ran]); if (Barra.getValue() == 100) { this.dispose(); t.stop(); /*Aquí va el siguiente form*/ Ventana menu = new Ventana(); menu.setVisible(true); JOptionPane.showMessageDialog(null,"Aquí el siguiente form!"); } }; t = new Timer(1050, Al); t.start(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { Barra = new javax.swing.JProgressBar(); Etiqueta = new javax.swing.JLabel(); Titulo = new javax.swing.JLabel(); Background = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("INICIO"); setAlwaysOnTop(true); setMaximumSize(null); setMinimumSize(null); setUndecorated(true); setPreferredSize(new java.awt.Dimension(519, 264)); setType(java.awt.Window.Type.UTILITY); getContentPane().setLayout(null); Barra.setBackground(new java.awt.Color(255, 255, 255)); Barra.setForeground(new java.awt.Color(255, 255, 255)); getContentPane().add(Barra); Barra.setBounds(10, 230, 500, 10); Etiqueta.setForeground(new java.awt.Color(255, 255, 255)); getContentPane().add(Etiqueta); Etiqueta.setBounds(150, 240, 250, 20); Titulo.setFont(new java.awt.Font("Bernard MT Condensed", 1, 18)); // NOI18N Titulo.setForeground(new java.awt.Color(255, 255, 255)); Titulo.setText("3JVC Compressor"); getContentPane().add(Titulo); Titulo.setBounds(190, 10, 170, 22); getContentPane().add(Background); Background.setBounds(-10, 0, 530, 270); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Inicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Inicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Inicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Inicio.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Inicio().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel Background; private javax.swing.JProgressBar Barra; private javax.swing.JLabel Etiqueta; private javax.swing.JLabel Titulo; // End of variables declaration//GEN-END:variables }
aca542a12a0ce936ccc8455e56ea2deeeb900dc0
[ "Java" ]
3
Java
Jonathan0832/Netbeans
c56379d631db005fcb851572237ae82ed8cfe122
a0ad730485d93cc74c2a81901b7984668dd7ffe4
refs/heads/master
<repo_name>gaming32/Screen-Log<file_sep>/screenlog.ini [tracking] log_level=thread poll_time=75 [logging] filename=screenlog %(startdate)s - %(enddate)s.log new_log_time=24 when_new=timeloop_hours [email] do_email=yes smtp_server=smtp.gmail.com smtp_port=25 username= password= from= to= subject=Your Screen Log is in! (from "%(startdate)s" to "%(enddate)s") body=You latest Screen Log is in! You can find the log as an attachment. (It is named "%(filename)s")<file_sep>/screenlog.py import sys import win32gui, win32process, _thread, queue, time import configparser import smtplib import email.message, email.utils def getwindowinfo() -> (int, str, int, int): "Returns (hwnd, text, threadId, processId)" hwnd = win32gui.GetForegroundWindow() text = win32gui.GetWindowText(hwnd) threadid, procid = win32process.GetWindowThreadProcessId(hwnd) return hwnd, text, threadid, procid def input_thread(log_queue:queue.Queue, command_queue:queue.Queue, stdout_mutex:_thread.LockType): global exited_threads while not exited_threads2: line = sys.stdin.readline().strip() command_queue.put(line) if line == 'exit': exited_threads += 1 break def log_thread(log_queue:queue.Queue, log_queue2:queue.Queue, config:configparser.ConfigParser, log:dict, log2:dict, wait_time:int): global exited_threads file = open(log['filename'], 'a', buffering=1, encoding='utf-8') while not exited_threads2: while not log_queue.empty(): m = log_queue.get() try: print(m, file=file) except UnicodeEncodeError: print(repr(m), file=file) log_queue2.put(m) if time.time() >= log['endtime']: file.close() log2.clear() log2['starttime'] = time.time() log2['endtime'] = log2['starttime'] + parse_length( config.getfloat('logging', 'new_log_time', fallback=0), config.get('logging', 'when_new', fallback='never')) log2.update({'startdate': time.ctime(log2['starttime']), 'enddate': time.ctime(log2['endtime'])}) log2['filename'] = config.get('logging', 'filename', fallback='screenlog.log') % log2 log2['filename'] = log2['filename'].replace(':', '_').replace('/', '_').replace('\\', '_') file = open(log2['filename'], 'a', buffering=1, encoding='utf-8') file.close() exited_threads += 1 def doprint(mutex:_thread.LockType, *vals, sep=' '): mutex.acquire() print('\r' + vals[0], *vals[1:], end='\n> ', sep=sep) mutex.release() exited_threads = None exited_threads2 = None def parse_length(new_log_time, when_new): if when_new == 'never': return 0 elif when_new == 'timeloop_minutes': return new_log_time * 60 elif when_new == 'timeloop_hours': return new_log_time * 60 * 60 elif when_new == 'timeloop_days': return new_log_time * 60 * 60 * 24 else: return new_log_time def log_message(queue:queue.Queue, message): queue.put('%s -- %s' % (time.ctime(), message)) def detect_thread(log_queue:queue.Queue, config:configparser.ConfigParser, wait_time:int): global exited_threads option = config.get('tracking', 'log_level', fallback='window') prevvalue = None while not exited_threads2: time.sleep(wait_time) window = getwindowinfo() if option == 'window': value = window[0] elif option == 'title': value = window[1] elif option == 'thread': value = window[2] elif option == 'process': value = window[3] else: value = None if value != prevvalue: label = window[1].strip() if label: prevvalue = value log_message(log_queue, label) def run(config:configparser.ConfigParser, configfile:str=None): global exited_threads, exited_threads2 exited_threads = 0 exited_threads2 = 0 wait_time = config.getint('tracking', 'poll_time', fallback=100)/1000. log_queue = queue.Queue() log_queue2 = queue.Queue() command_queue = queue.Queue() stdout_mutex = _thread.allocate_lock() _thread.start_new_thread(input_thread, (log_queue, command_queue, stdout_mutex)) log = { 'starttime': time.time(), } log['endtime'] = log['starttime'] + parse_length( config.getfloat('logging', 'new_log_time', fallback=0), config.get('logging', 'when_new', fallback='never')) log.update({'startdate': time.ctime(log['starttime']), 'enddate': time.ctime(log['endtime'])}) log['filename'] = config.get('logging', 'filename', fallback='screenlog.log') % log log['filename'] = log['filename'].replace(':', '_').replace('/', '_').replace('\\', '_') log2 = {} _thread.start_new_thread(log_thread, (log_queue, log_queue2, config, log, log2, wait_time)) try: _thread.start_new_thread(detect_thread, (log_queue, config, wait_time)) log_message(log_queue, 'Screen Log started...') while not exited_threads: time.sleep(wait_time) while not command_queue.empty(): command = command_queue.get() if command == 'exit': pass elif command.startswith('log'): arg = command.split(' ', 1)[1] log_message(log_queue, arg) elif command == 'reloadconf': if configfile is None: doprint(stdout_mutex, 'Sorry, the config file was not provided') else: config.clear() config.read(configfile) doprint(stdout_mutex, 'Successfully reloaded config...') # elif command == 'exit_no_email': # config['email']['do_email'] = 'no' # break elif command == 'forcemail': send_email(config, log) else: doprint(stdout_mutex, 'Invalid command "%s"' % command) while not log_queue2.empty(): doprint(stdout_mutex, log_queue2.get()) if log2 != {}: send_email(config, log) log.update(log2) log2.clear() log_message(log_queue, 'Screen Log exited...') exited_threads += 1 time.sleep(wait_time) exited_threads2 = exited_threads log['endtime'] = time.time() log['enddate'] = time.ctime() send_email(config, log) except: log_message(log_queue, 'Screen Log exited...') exited_threads += 1 time.sleep(wait_time) exited_threads2 = exited_threads # log['endtime'] = time.time() # log['enddate'] = time.ctime() # send_email(config, log) raise def send_email(config:configparser.ConfigParser, log:dict): if not config.getboolean('email', 'do_email', fallback=False): return message = email.message.EmailMessage() message['From'] = config.get('email', 'from') message['To'] = config.get('email', 'to') if config.has_option('email', 'cc'): message['Cc'] = config.get('email', 'cc') if config.has_option('email', 'bcc'): message['Bcc'] = config.get('email', 'bcc') message['Date'] = email.utils.formatdate(localtime=True) message['Subject'] = config.get('email', 'subject') % log textmessage = email.message.Message() textmessage.set_payload(config.get('email', 'body') % log) message.make_mixed() message.attach(textmessage) message.add_attachment(open(log['filename'], 'rb').read(), filename=log['filename'], maintype='text', subtype='plain') smtp = smtplib.SMTP(config.get('email', 'smtp_server'), config.getint('email', 'smtp_port', fallback=25)) smtp.ehlo() smtp.starttls() smtp.login(config.get('email', 'username'), config.get('email', 'password')) smtp.send_message(message) smtp.quit() def main(): p = configparser.ConfigParser(interpolation=None) fname = p.read((len(sys.argv) > 1 and sys.argv[1]) or 'screenlog.ini') run(p, fname) if __name__ == '__main__': # from configparser import ConfigParser # p = ConfigParser(interpolation=None) # p.read('screenlog.ini') # send_email(p, {'startdate':0, 'enddate':10000, 'filename': 'screenlog today - tomorrow.log'}) main()<file_sep>/README.md # Config options Config File | Command Line | Description ----------- | ------------ | ----------- `tracking:log_level=value` | `--log-level=value` | Can be `process`, `thread`, `window`, or `title`; indicates when to log a change `email:do_email=value` | `--do-email=value` | `email:smpt_server=value` | `--smtp-server=value` |
4d9eff751c9eec8090e6652264133b540f160e79
[ "Markdown", "Python", "INI" ]
3
INI
gaming32/Screen-Log
7101d96f6c00ebaa67f0a99ea47b8bef4756bf70
bd3a8992d49f2652cc93dbc125e5df009d573130
refs/heads/master
<file_sep>import discord from discord.ext import commands import asyncio import os bot = commands.Bot(command_prefix=os.environ['PREFIX']) # Getting Environ Vars os.environ['VAR_NAME'] @bot.event async def on_ready(): print(bot.user.name) #A SIMPLE TEST COMMAND @bot.command(pass_context=True) async def hi(ctx): await bot.say("Hello there"+" "+ctx.message.author.name) bot.run(os.environ['TOKEN'])
dcb00aa089d07df0659a33a24e398e167a8eb4a0
[ "Python" ]
1
Python
RedstonedLife/DPY-Test
5a43f51cb827a147fbe27eb4b170c35bfa72da5b
a44a15e876ef3b0559bfc4aba473c7c484db44e3
refs/heads/main
<file_sep>import Joi from "joi" import { NextFunction, Request, Response } from "express" import catchAsync from "../utils/catchAsync" export class ProductValidator { keys = { required: "required", optional: "optional" } productSchema = Joi.object({ org_id: Joi.string().required(), owner_id: Joi.string().required(), name: Joi.string().required(), barcode: Joi.string().required(), }) updateSchema = Joi.object({ name: Joi.string().required(), description: Joi.string().required() }) create = catchAsync(async (req: Request, res: Response, next: NextFunction) => { const { error } = this.productSchema.validate(req.body) if (error) return next(error) next() }) update = catchAsync(async (req: Request, res: Response, next: NextFunction) => { const { error } = this.updateSchema.validate(req.body) if (error) return next(error) next() }) } <file_sep>import { ProductStorage } from "./mongo/Product" interface IStorage { Product: ProductStorage } export let storage: IStorage = { Product: new ProductStorage() }
d4f0498b54c8b839077d1080ac3968c39416e6e1
[ "TypeScript" ]
2
TypeScript
an-ikhtiyour/product
8db5a12189ef222c6abd5513d648e1af7ed61f07
a7215b9ae82ba3801dbac45d9c0cb53e56ccdf01
refs/heads/master
<repo_name>varuns23/ntupleProducer<file_sep>/interface/TCGenParticle.h #ifndef _TGENPARTICLE_H #define _TGENPARTICLE_H #include "TCPhysObject.h" class TCGenParticle : public TCPhysObject { private: TCGenParticle* _mother; int _PDGID; unsigned _status; bool _isParton; public: TCGenParticle(); virtual ~TCGenParticle(); TCGenParticle* Mother(); //TCGenParticle* PrimaryAncestor(); int GetPDGId(); unsigned GetStatus(); bool IsParton(); void SetMother(TCGenParticle* m); void SetPDGId(int pdg_id); void SetStatus(unsigned s); void SetIsParton(bool a); ClassDef(TCGenParticle, 1); }; #endif <file_sep>/src/TCMuon.cc #include "../interface/TCMuon.h" #include "TCMuonLinkDef.h" TCMuon::TCMuon() { } TCMuon::~TCMuon() { } // "get" methods ------------------------------------- float TCMuon::PtError() const { return _ptError; } bool TCMuon::IsGLB() const { return _isGLB; } bool TCMuon::IsTRK() const { return _isTRK; } bool TCMuon::IsPF() const { return _isPF; } bool TCMuon::IsSoft() const { return _isSoft; } bool TCMuon::IsTight() const { return _isTight; } bool TCMuon::IsGood() const { return _isGood; } bool TCMuon::IsGoodLoose() const { return _isGoodLoose; } int TCMuon::NumberOfMatchedStations() const { return _numberOfMatchedStations; } int TCMuon::TrackLayersWithMeasurement() const { return _trackLayersWithMeasurement; } int TCMuon::PixelLayersWithMeasurement() const { return _pixelLayersWithMeasurement; } int TCMuon::NumberOfValidPixelHits() const { return _numberOfValidPixelHits; } int TCMuon::NumberOfValidTrackerHits() const { return _numberOfValidTrackerHits; } int TCMuon::NumberOfValidMuonHits() const { return _numberOfValidMuonHits; } int TCMuon::NumberOfLostPixelHits() const { return _numberOfLostPixelHits; } int TCMuon::NumberOfLostTrackerHits() const { return _numberOfLostTrackerHits; } float TCMuon::NormalizedChi2() const { return _normalizedChi2; } float TCMuon::NormalizedChi2_tracker() const { return _normalizedChi2_tracker; } int TCMuon::NumberOfMatches() const { return _numberOfMatches; } float TCMuon::CaloComp() const { return _caloComp; } float TCMuon::SegComp() const { return _segComp; } float TCMuon::PfIsoPU() const { return _pfIsoPU; } float TCMuon::PfIsoCharged() const { return _pfIsoChargedHad; } float TCMuon::PfIsoChargedHad() const { return _pfIsoChargedHad; } float TCMuon::PfIsoChargedPart() const { return _pfIsoChargedPart; } float TCMuon::PfIsoNeutral() const { return _pfIsoNeutral; } float TCMuon::PfIsoPhoton() const { return _pfIsoPhoton; } // "set" methods --------------------------------------------- void TCMuon::SetNumberOfMatchedStations(int n){ _numberOfMatchedStations = n; } void TCMuon::SetTrackLayersWithMeasurement(int n) { _trackLayersWithMeasurement = n; } void TCMuon::SetPixelLayersWithMeasurement(int n) { _pixelLayersWithMeasurement = n; } void TCMuon::SetPtError(float er){ _ptError = er; } void TCMuon::SetIsGLB(bool t){ _isGLB = t; } void TCMuon::SetIsTRK(bool t){ _isTRK = t; } void TCMuon::SetIsPF(bool t){ _isPF = t; } void TCMuon::SetIsSoft(bool t){ _isSoft = t; } void TCMuon::SetIsTight(bool t){ _isTight = t; } void TCMuon::SetIsGood(bool g){ _isGood = g; } void TCMuon::SetIsGoodLoose(bool g){ _isGoodLoose = g; } void TCMuon::SetNumberOfValidMuonHits(int n) { _numberOfValidMuonHits = n; } void TCMuon::SetNumberOfValidPixelHits(int n) { _numberOfValidPixelHits = n; } void TCMuon::SetNumberOfValidTrackerHits(int n) { _numberOfValidTrackerHits = n; } void TCMuon::SetNumberOfLostPixelHits(int n) { _numberOfLostPixelHits = n; } void TCMuon::SetNumberOfLostTrackerHits(int n) { _numberOfLostTrackerHits = n; } void TCMuon::SetNormalizedChi2(float n) { _normalizedChi2 = n; } void TCMuon::SetNormalizedChi2_tracker(float n) { _normalizedChi2_tracker = n; } void TCMuon::SetNumberOfMatches(int n) { _numberOfMatches = n; } void TCMuon::SetCaloComp(float c){ _caloComp = c; } void TCMuon::SetSegComp(float s){ _segComp = s; } void TCMuon::SetPfIsoPU(float f) { _pfIsoPU = f; } void TCMuon::SetPfIsoChargedHad(float f) { _pfIsoChargedHad = f; } void TCMuon::SetPfIsoChargedPart(float f) { _pfIsoChargedPart = f; } void TCMuon::SetPfIsoNeutral(float f) { _pfIsoNeutral = f; } void TCMuon::SetPfIsoPhoton(float f) { _pfIsoPhoton = f; }
0058b135d575407b576cf6fd4cefaed494f4eb78
[ "C++" ]
2
C++
varuns23/ntupleProducer
335d8135ec2773fb9262b4cdc3d4b2e7a12af056
2afd9bbba8967d9b323484b5ebb7447d6077dbd0
refs/heads/master
<file_sep>var pageHeight = window.innerHeight; function scrollDown() { var vheight = $(window).height(); $('html, body').animate({ scrollTop: (Math.floor($(window).scrollTop() / vheight)+1) * vheight }, 500); }; function scrollUp() { $('html, body').animate({ scrollTop: 0 }, 500); }; <file_sep>let mediaPreviewTitle = "Featured Articles"; let mediaPreviewContent = ` <li> Aug. 15, 2018, finished and submitted a new paper on FRB energetics and detectability from high redshifts <a target="_blank" class="text-link" href="https://arxiv.org/abs/1808.05277">(Here)</a>. </li> <br> <li> Aug. 15, 2018, a paper with <NAME> accepted for publication in ApJL <a target="_blank" class="text-link" href="https://arxiv.org/abs/1808.05170">(Here)</a>. This paper suggests that the ultimate synchrotron "line of death" is at Fnu ~ nu^{2/3} rather than nu^{1/3}. However, in order to achieve this harder spectrum, one needs to have significant anisotropy in the emission region. </li> <br> <li> Jul. 24-27, 2018, attended <a target="_blank" class="text-link" href="http://2018gw.csp.escience.cn/dct/page/1">Workshop on Gravitational Waves</a> in Beijing and gave an invited talk. </li> <br> `; let mediaDetailTitle = "News"; let mediaDetailContent = ` </li> <br> <li> Jul. 9, 2018, New graduate student <NAME> arrived to start his PhD journey. Welcome Jiawei! </li> <br> <li> Jul. 1-5, 2018, attended <a class="text-link" target="_blank" href="http://www.icra.it/mg/mg15/">the Fifteenth Marcel Grossman Meeting (MG15)</a> in Rome and delivered 1 plenary talk, 1 invited talk, and 2 contributed talks. </li> <br> <li> Jun. 25-29, 2018, attended a Psi2 scientific program of the Paris-Saclay University entitled <a class="text-link" target="_blank" href="http://gamma-sn-psi2.lmpa.eu/teaser.html">"Gamma-Ray Bursts and Supernovae: From Central Engines to the Observer"</a> and gave an invited opening talk. </li> <br> <li> Jun. 19, 2018, paper led by visiting student <NAME> <a class="text-link" target="_blank" href="https://arxiv.org/abs/1804.06597">(Here)</a> accepted for publication in ApJL. This paper suggests that the optical transient AT2017gfo associated with GW170817 is better interpreted as being partially powered by a long-lived neutron star at the central engine. </li> <br> <li> May 23-25, 2018, attended <a class="text-link" target="_blank" href="http://astro.xmu.edu.cn/gwastro2018/">2nd Gravitational Wave Astrophysics Workshop</a> in Xiamen, gave an invited talk and workshop summary. </li> <br> <li> May 15-18, 2018, attended <a class="text-link" target="_blank" href="https://indico.in2p3.fr/event/16310/">the 3rd SVOM workshop</a> at Les Houches and gave an invited talk. </li> <br> <li> Apr. 19, 2018, h-index hit 80 according to ADS. </li> <br> <li> Apr. 6, 2018, UNLV student <NAME> successfully defended his Ph.D. dissertation. Congratulations, Jared! </li> <br> <li> Apr. 2, 2018, Wang et al. accepted to ApJ. <a class="text-link" target="_blank" href="https://arxiv.org/abs/1804.02113">(Here)</a>. This paper reports a reinvestigation of GRB jet breaks. </li> <br> <li> Mar. 23, 2018, Huang et al. accepted to ApJ. <a class="text-link" target="_blank" href="https://arxiv.org/abs/1804.02104">(Here)</a>. This paper reports the possible external shock origin of one GRB (GRB 120729A). </li> <br> <li> Feb. 6, 2018, FRB 121102 - cosmic comb paper accepted for publication in ApJL. </li> <br> <li> Jan. 31, 2018, short visit to Arizona State University, delivered a Cosmology Seminar entitled "Fast radio bursts and their possible origins". </li> <br> <li> Jan. 23, 2018, The paper entitled "Are there multiple populations of Fast Radio Bursts?" accepted for publication in ApJL <a class="text-link" target="_blank" href="https://arxiv.org/abs/1703.09232">(Here)</a>. This paper was started by <NAME> and finished by Ye Li. We show that the only repeating FRB 121102 is abnormously active. Other FRBs either repeat much less frequenctly or do not repeat at all. </li> <br> <li> Jan. 22, 2018, formally starting a new job as Associate Dean for Research, College of Sciences, UNLV. </li> <br> <li> Jan. 19, 2018, The paper entitled "Relativistic Astronomy" finally accepted for publication in ApJ <a class="text-link" target="_blank" href="https://arxiv.org/abs/1708.03002">(Here)</a>. In this paper, we (together with <NAME> at Georgia tech) proposed that the <a class="text-link" target="_blank" href="https://breakthroughinitiatives.org/initiative/3">"Breakthrough Starshot"</a> project may be developed into an astronomy observatory to study the universe. </li> <br> <li> Jan. 11, 2018, a paper published in Nature reporting the discovery of strong and variable rotation measure of the bursts detected from the repeating FRB 121102 <a class="text-link" target="_blank" href="http://www.nature.com/articles/nature25149">(Here)</a>. All the data seem to be interpretable within the framework of my "Cosmic Comb" model <a class="text-link" target="_blank" href="http://adsabs.harvard.edu/abs/2017ApJ...836L..32Z">(Here)</a>. A paper was written in four days, which was submitted for publication on Jan. 15. <a class="text-link" target="_blank" href="https://arxiv.org/abs/1801.05436">(Here)</a>. </li> <br> <li> Jan. 4, 2018, the paper on the short GRB 170817A associated with the first NS-NS merger gravitational wave event GW170817 (led by <NAME> and contributed by 8 former UNLV associates as well as other coauthors) formally accepted for publication in Nature Communications <a class="text-link" target="_blank" href="https://arxiv.org/abs/1710.05851">(Here)</a>. </li> <br> <li> Jan. 1, 2018, our paper on GRB 160625B formally published in Nature Astronomy <a class="text-link" target="_blank" href="https://www.nature.com/articles/s41550-017-0309-8">(Here)</a>. In this paper. we found a clear jet composition transition within a same burst, from a fireball in the first sub-pulse to a Poynting-flux-dominated jet in the second sub-pulse. First author is <NAME>. </li> <br> <li> Feb. 28, 2017, Aspen FRB meeting reported in <a class="text-link" target="_blank" href="http://www.nature.com/news/astronomers-grapple-with-new-era-of-fast-radio-bursts-1.21557">Nature</a> and <a class="text-link" target="_blank" href="https://www.scientificamerican.com/article/fast-radio-bursts-are-astronomy-rsquo-s-next-big-thing/">Scientific American</a>. </li> <br> <li> Feb. 26, 2017, paper on "Cosmological evolution of primordial black holes" led by <NAME> accepted for publication in Journal of High Energy Astrophysics (<a class="text-link" target="_blank" href="https://arxiv.org/abs/1702.08069">here</a>). </li> <br> <li> Feb. 12-17, 2017, Co-organized the 2017 Winter Conference on Fast Radio Bursts at Aspen Center for Physics (<a class="text-link" target="_blank" href="http://aspen17.phys.wvu.edu/">here</a>). </li> <br> <li> Jan. 15, 2017, Proposed the "Cosmic Comb" model of fast radio bursts (FRBs) (<a class="text-link" target="_blank" href="https://arxiv.org/abs/1701.04094">here</a>). </li> <br> <br> <li> Mar. 17, 2016, Deng et al. ("Collision-induced magnetic reconnection and a unified interpretation of polarization properties of GRBs and blazars") accepted for publication in ApJL (<a class="text-link" target="_blank" href="http://adsabs.harvard.edu/abs/2016arXiv160203879D">here</a>). </li> <br> <li> Mar. 10, 2016, Liu et al. ("A method to constrain mass and spin of GRB black hole within the NDAF model") accepted for publication in ApJ (<a class="text-link" target="_blank" href="http://adsabs.harvard.edu/abs/2015arXiv151102800L">here</a>). </li> <br> <li> Mar. 6, 2016, Chu et al. ("Capturing the electromagnetic counterparts of binary neutron star mergers through low latency gravitational wave triggers") accepted for publication in MNRAS (<a class="text-link" target="_blank" href="http://adsabs.harvard.edu/abs/2015arXiv150906876C">here</a>). </li> <br> <li> Mar. 4, 2016, Zhang (Bin-Bin), Zhang & Castro-Tirado ("Central engine memory of Gamma-Ray Bursts and Soft Gamma-Ray Repeaters") accepted for publication in ApJL (<a class="text-link" target="_blank" href="http://adsabs.harvard.edu/abs/2016arXiv160301381Z">here</a>). </li> <br> <li> Mar. 2, 2016, Quanta Magazine reports recent Fermi GBM signal following GW 150914 as well as theoretical challenges and possible models - including <a class="text-link" target="_blank" href="http://adsabs.harvard.edu/abs/2016arXiv160204542Z">this model</a>. (see <a class="text-link" target="_blank" href="https://www.quantamagazine.org/20160302-black-hole-flash/">this link</a>, also <a class="text-link" target="_blank" href="http://www.wired.com/2016/03/two-black-holes-collide-puzzling-flash/">this link</a>). </li> <br> <li> <b>Feb. 25, 2016, a short paper (in ApJL style) to discuss the implications of afterglow and progenitor of FRB 150418 finished and posted to arXiv.</b> (<a class="text-link" target="_blank" href="http://adsabs.harvard.edu/abs/2016arXiv160208086Z">here</a>). </li> <br> <li> <b>Feb. 23, 2016, a discovery (Keane et al.) of a radio afterglow of a fast radio burst (FRB 150418) published in Nature.</b> </li> <br> <li> Feb. 16, 2016, Yang, Zhang & Dai accepted for publication in ApJL (synchrotron heating by an FRB in a self-absorbed nebula) (<a class="text-link" target="_blank" href="http://adsabs.harvard.edu/abs/2016arXiv160205013Y">here</a>). </li> <br> <li> <b>Feb. 15, 2016, a toy model of interpreting LIGO-GBM associations within the framework of double black hole mergers (with slight charge) posted to arXiv.</b> (<a class="text-link" target="_blank" href="http://adsabs.harvard.edu/abs/2016arXiv160204542Z">here</a>). </li> <br> <li> <b>Feb. 14, 2016, Fermi GBM team announced in arXiv the discovery of a putative short GRB candidate following GW 150914.</b> </li> <br> <li> <b>Feb. 11, 2016, Advanced LIGO team announced the discovery of gravitational waves!</b> Many GW 150914 papers flooded in on arXiv. </li> <br> <li> Feb. 3, 2016, <NAME> & Lü accepted for publication in Physical Review D (using short GRB data to constrain neutron star equation of state and the birth properties of the supra-massive neutron stars) (<a class="text-link" target="_blank" href="http://adsabs.harvard.edu/abs/2016PhRvD..93d4065G">here</a>). </li> <br> <li> Jan. 21, 2016, Dr. <NAME> (Xiamen University) begins her three-month visit. </li> <br> <li> Jan. 22, 2016, a Fermi proposal submitted. </li> <br> <li> Jan. 20-22, 2016, Dr. <NAME> (Caltech) visits group, discusses a collaboration, and gives a talk. </li> <br> <li> Jan. 19, 2016, new semester starts, first lecture. </li> <br> <li> Jan. 17, 2016, a complete draft of Chapter 8 (Afterglow physics) of the book "The Physics of Gamma-Ray Bursts" finished. </li> <br> <li> Jun. 2, 2015, long paper led by <NAME> on testing the external forward shock models with broad-band data accepted for publication in ApJS. (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1503.03193">here</a>). </li> <br> <li> Jun. 1, 2015, Uhm & Zhang paper on curvature effect accepted for publication in ApJ. (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1411.0118">here</a>). </li> <br> <li> Jun. 1-3, 2015, Prof. <NAME> visited the group. </li> <br> <li> May 25-27, 2015, Prof. <NAME> visited the group and gave a talk. </li> <br> <li> May 14-Jun. 4, 2015, Dr. <NAME> visited the group and gave a talk. </li> <br> <li> May 12-15, 2015, UT Austin student <NAME> visited the group and gave a talk. </li> <br> <li> May 14, 2015, <NAME> successfully defended his PhD dissertation entitled "Study the mechanism of the prompt emission of Gamma-Ray Bursts". </li> <br> <li> May. 13, 2015, Guiriec et al. (three-spectral-component fit to Fermi GRB data) accepted for publication in ApJ (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1501.07595">here</a>). </li> <br> <li> May 4, 2015, traveled to NRAO, Soccorro to have a working lunch with <NAME>, <NAME>, and <NAME> to discuss FRB observations. </li> <br> <li> May 3-6, 2015, traveled to Los Alamos to attend a workshop entitled "Plasma Energization: Exchanges between Fluid and Kinetic Scales". Delivered on May 6 on "The composition of GRB jets and the ICMART model". </li> <br> <li>Apr. 22, 2015, a new paper led by <NAME> on event rate densities and luminosity functions of extra-galactic high-energy transients submitted for publication. </li> <br> <li> Apr. 20, 2015, Dr. <NAME> formally joined the group as a postdoctoral research associate. </li> <br> <li> Apr. 11-18, 2015, traveled to China to attend ISSI-Beijing workshop on "GRBs as cosmological tools". Delivered a talk on "GRB populations" on Monday Apr. 13. </li> <br> <li> Apr. 18, 2015, attended a POLAR science meeting on Friday Apr. 17, delivered a talk entitled "GRB prompt emission, ICMART model, and polarization". </li> <br> <li> Apr. 9, 2015, <NAME> successfully defended his PhD dissertation entitled "Constraining the progenitor and central engine of gamma-ray bursts with observational data". </li> <br> <li> Mar. 23, 2015, Heard from NASA that a three-year proposal to the Astrophysics Theory Program (ATP) was selected for funding. </li> <br> <li> Mar. 23, 2015, <NAME> et al. (numerical simulations of collision induced magnetic dissipation in Poynting flux dominated jets) accepted for publication in ApJ (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1501.07595">here</a>). </li> <br> <li> Mar. 23, 2015, <NAME> et al. paper on short GRB central engine / NS equation-of-state accepted for publication in ApJ. (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1501.02589">here</a>). </li> <br> <li> Mar. 1, 2015, a collaboration paper led by <NAME> on a GRB afterglow study accepted for publication in ApJ (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1503.00976">here</a>). </li> <br> <li> Feb. 27, 2015, <NAME> visited UNLV and gave a public talk at the Russell Frank Lecture Series. </li> <br> <li> Feb. 25, 2015, the Niino, Nagamine & Zhang paper on metallicity of GRB hosts accepted for publication in MNRAS (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1408.7059">here</a>). </li> <br> <li> Feb. 9, 2015, a collaboration paper led by formal postdoc <NAME> accepted for publication in MNRAS (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1312.1648">here</a>). </li> <br> <li> Jan. 29-30, 2015, Prof. <NAME> and Mr. <NAME> visited UNLV and our group. Mr. Wei gave a morning talk on "Constraining cosmological models with different cosmic rulers". Prof. Melia gave an afternoon colloquium on "The zero active mass condition in FRW cosmologies". </li> <br> <li> Jan. 28, 2015, The numerical simulation work led by <NAME> finally submitted for publication. It verified several hypotheses of the ICMART model, and revealed some new interesting features (including a correlation between initial and final sigma values in an ICMART event. (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1501.07595">here</a>) </li> <br> <li> Jan. 15, 2015, UNLV College of Sciences news on APS fellow (<a class="text-link" target="_blank" href="http://www.unlv.edu/news-story/astrophysicist-bing-zhang-elected-aps-fellow">here</a>) </li> <br> <li> Jan. 14, 2015, the paper Gao & Zhang, "Photosphere emission from a hybrid relativistic outflow with arbitrary dimensionless entropy and magnetization in GRBs", accepted for publication in ApJ. (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1409.3584">here</a>) </li> <br> <li> Jan. 12, 2015, new paper led by <NAME> submitted for publication. It uses the Swift data to study the putative magnetar central engine of short GRBs, and constrain NS equation of state. (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1501.02589">here</a>) </li> <br> <br> <li> Dec. 9-12, 2014, Dr. <NAME> visited our group, and delivered a talk on high-energy neutrinos </li> <br> <li> Dec. 4, 2014, received notification, elected as a Fellow of American Physical Society, with citation: "For his significant scientific contributions to the understanding of the physical mechanisms of high-energy astrophysical sources, especially the prompt emission and afterglows of cosmological gamma-ray bursts." See link <a class="text-link" target="_blank" href="http://www.aps.org/programs/honors/fellowships/archive-all.cfm?initial=&year=2014&unit_id=DAP&institution=">here</a>. </li> <br> <li> Nov. 25, 2014, a new paper led by <NAME> (an undergraduate student in Peking University), entitled "Oscillation Driven Magnetospheric Activity In Pulsars" accepted for publication in ApJ (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1411.5942">here</a>) </li> <br> <li> Nov. 6-7, 2014, Dr. <NAME> visited our group and gave a Physics Forum talk. </li> <br> <li> Oct. 22-24, 2014, former group member, Dr. <NAME> from UAU, visited our group and gave a Physics Forum talk. </li> <br> <li> Sep. 11, 2014, a new paper with He Gao submitted to ApJ. We developed a theory of photosphere emission of a hybrid relativistic jet with arbitrary dimensionless entropy and magnetization, and a method to diagnose central engine properties using Fermi data. (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1409.3584">here</a>) </li> <br> <li> Sep. 4, 2014, a long review paper with <NAME> accepted for publication in Physics Reports (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1409.????">here</a>) </li> <br> <li> Aug. 29, 2014, a new paper led by <NAME> and <NAME> about metallicity of GRB amd SN host galaxies submitted for publication. (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1408.7059">here</a>) </li> <br> <li> Jul. 31, 2014, the Yi, Gao & Zhang paper accepted for publication in ApJL. (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1407.0348">here</a>) </li> <br> <li> Jul. 27, 2014, a new paper led by <NAME>, entitled "Magnetic Field Generation in Core-Sheath Jets via the Kinetic Kelvin-Helmholtz Instability" accepted for publication in ApJ (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1405.5247">here</a>) </li> <br> <li> Jul. 23, 2014, a new paper led by <NAME>, entitled "Distributions of Gamma-Ray Bursts and Blazars in the Lp-Ep Plane and Possible Implications for their Radiation Physics" accepted for publication in ApJ (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1407.6159">here</a>) </li> <br> <li> Jul. 21-25, 2014, attended INT Program INT-14-2a, "Binary Neutron Star Coalescence as a Fundamental Physics Laboratory" (Week 4 on "Merger astrophysics") (<a class="text-link" target="_blank" href="http://www.int.washington.edu/PROGRAMS/14-2a/">website</a>), Institute for Nuclear Theory (INT), University of Washington </li> <br> <li> Jul. 18, 2014, short visit to SLAC, attending morning coffee. </li> <br> <li> Jul. 14, 2014, visit Caltech, gave a special talk entitled "Fast Radio Bursts: Mysterious Transients and Implications". </li> <br> <li> Jul. 6, 2014, back to Las Vegas. </li> <br> <li> Jul. 1, 2014, a new paper ("Multi-wavelength afterglows of fast radio bursts") led by <NAME> (co-authored by <NAME> and me) submitted to ApJL for publication (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1407.0348">here</a>). It gave a detailed calculation on faint multi-wavelength afterglows of FRBs, and discuss observational strategies. </li> <br> <li> Jun. 28 - Jul. 3, 2014, visited Guangxi University and gave two lectures on GRBs and FRBs. </li> <br> <li> Jun. 25, 2014, colloquium at National Astronomical Observatory of China (NAOC), title: "Fast Radio Bursts: Mysterious Transients and Implications". </li> <br> <li> Jun. 23-24, 2014, organized/attended a workshop on GRB cosmology at KIAA, gave a talk entitled "GRBs in the cosmological content" (Jun. 23, 2014). </li> <br> <li> Jun. 16, 2014, Yuan & Zhang paper accepted for publication in JHEAp (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1404.2318">here</a>). </li> <br> <li> Jun. 15-19, 2014, attended "Gamma-ray bursts in the multi-messenger era" meeting (<a class="text-link" target="_blank" href="https://indico.in2p3.fr/conferenceDisplay.py?confId=9603">website</a>), gave an invited talk entitled "Radiation Processes in GRBs" (Jun. 17, 2014). </li> <br> <li> Jun. 9-14, 2014, attended "The Unquiet Universe" meeting (<a class="text-link" target="_blank" href="http://www.oa-roma.inaf.it/meetings/cefalu/2014/">website</a>), gave an invited talk entitled "Gamma-ray bursts prompt emission and afterglow: observations vs. theory" (Jun. 9, 2014). </li> <br> <li> May 28-31, 2014, attended SPCS2014 (Shanghai Particle Physics and Cosmology Symposium) (<a class="text-link" target="_blank" href="http://www.physics.sjtu.edu.cn/spcs2014/">website</a>), gave an invited talk entitled "High energy neutrinos from gamma-ray bursts" (May 31, 2014). </li> <br> <li> May 24-27, 2014, visited Huazhong University of Science Technology (HUST), gave a colloquium entitled "On the nature of fasr radio bursts". </li> <br> <li> May 23, 2014, a new paper led by <NAME>, entitled "Internal Energy Dissipation of Gamma-Ray Bursts Observed with Swift: Precursors, Prompt Gamma-rays, Extended emission and Late X-ray Flares" accepted for publication in ApJ (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1405.5949">here</a>) </li> <br> <li> May 22-23, 2014, visited Purple Mountain Observatory and Nanjing University, gave a colloquium at PMO entitled "Fermi GeV gamma-ray excess in the Galactic center". </li> <br> <li> May 21, 2014, gave two lectures at Summer School of SPCS2014 (Shanghai Particle Physics and Cosmology Symposium) on GRBs. </li> <br> <li> May 6-7, 2014, attended "Exploring the Dynamic Universe Forum. ISSI-Beijing, China, and delivered an invited talk entitled "Electromagnetic counterparts of gravitational wave events" (May 6, 2014). </li> <br> <li> Apr. 30, 2014, a new paper led by <NAME> and <NAME> accepted for publication in ApJ (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1405.0180">here</a>). In this paper, we interpret the two-frequency QPOs and radio emission rebrightening within a unified two-component jet model. </li> <br> <li> Apr. 9, 2014, a new paper "Millisecond pulsar interpretation of the Galactic center gamma-ray excess", was submitted for publication in Journal of High Energy Astrophysics (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1404.2318">here</a>). In this paper, we suggest that millisecond pulsars are adequate to interpret the gamma-ray excess in the Galactic center without the need of introducing dark matter annihilation. </li> <br> <li> Apr. 1, 2014, the paper led by <NAME> "How long does a burst burst", accepted for publication in ApJ (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1310.2540">here</a>). In this paper, we suggest that current data do not allow us to draw the conclusion that the so-called "ultra-long GRBs" form a distinct population with a new type of progenitor. </li> <br> <li> Mar. 28, 2014, He Gao defended his PhD thesis entitled "Physics of Gamma-ray bursts and multi-messenger signals from double neutron star mergers". He will move to Pennsylvania State University to take a postdoc position in August. </li> <br> <li> Mar. 21 (Mar. 22 in China), 2014, attended a discussion meeting on POLAR mission (in IHEP, Beijing) over Skype. Delivered an invited talk entitled "Gamma-ray burst polarization & POLAR connection". </li> <br> <li> Mar. 20, 2014, one day visit to University of Utah. Delivered a colloquium entitled "On the nature of fast radio bursts". </li> <br> <li> Mar. 19, 2014, A paper led by <NAME>, entitled "Fermi Large Area Telescope detection of supernova remnant RCW 86", accepted for publication in ApJL (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1403.4915">here</a>). </li> <br> <li> Feb. 26, 2014, Uhm & Zhang, "Fast cooling synchrotron radiation in a decaying magnetic field and gamma-ray burst emission mechanism", accepted for publication in Nature Physics (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1303.2704">here</a>). In this paper, we overcome the standard fast-cooling problem of GRB prompt emission, and suggest that the famous phenomenological "Band" function of GRB prompt emission with a mysterious low-energy photon index around -1 could be simply due to synchrotron emission in a varying magnetic field. This model requires a relatively large emission radius, as is expected in the "ICMART model" (<a class="text-link" target="_blank" href="zy11.pdf">here</a>) of GRB prompt emission. </li> <br> <li> Feb. 19, 2014, Deng & Zhang, "Low energy spectral index and Ep evolution of quasi-thermal photosphere emission of gamma-ray bursts", accepted for publication in ApJ (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1402.5364">here</a>). </li> <br> <li> Feb. 19, 2014, Lü & Zhang, "A test of the millisecond magnetar central engine model of GRBs with Swift data", accepted for publication in ApJ (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1401.1562">here</a>). </li> <br> <li> Feb. 9, 2014, first-author review paper with <NAME> (<a class="text-link" target="_blank" href="http://adsabs.harvard.edu/abs/2004IJMPA..19.2385Z">here</a>) hits 500 citation mark. For a full citation statistics, see <a class="text-link" target="_blank" href="http://www.physics.unlv.edu/~bzhang/citation.html">here</a>. </li> <br> <li> Jan. 31, 2014, <NAME>, Melikidze, Gil & Xu, "Radio efficiency of pulsars", accepted for publication in ApJ (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1402.0228">here</a>). </li> <br> <li> Jan. 28, 2014, Deng & Zhang, "Cosmological implications of Fast Radio Burst / Gamma-Ray Burst Associations" accepted for publication in ApJL (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1401.0059">here</a>). </li> <br> <li> Jan. 27, 2014, a new paper on GRB blastwave encountering a bump or void, led by <NAME>, submitted for publication (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1401.6758">here</a>). </li> <br> <li> Jan. 27, 2014, a new paper entitled "Magnetic Field Amplification and Saturation in Turbulence Behind a Relativistic Shock", led by <NAME>, accepted for publication in MNRAS (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1401.7080">here</a>). </li> <br> <li> Jan. 12, 2014, returned to UNLV. </li> <br> <li> Jan. 10, 2014, delivered a lunch talk at KIAA and Department of Astronomy, Peking University, China. Title: "On the nature of fast radio bursts". </li> <br> <li> Jan. 6, 2014, a new paper on a statistical analysis of GRB millisecond magnetar central engine, led by <NAME>,, submitted for publication in ApJ (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1401.1562">here</a>). </li> <br> <li> Jan. 4, 2014, attended a workshop on "GRBs and related physics frontier" in Nanjing, China. Delivered an invited talk on "On the nature of fast radio bursts". </li> <br> <br> <br> <li> Dec. 30, 2013, a new paper on using FRB/GRB association to study cosmology, led by <NAME>, submitted for publication in ApJL (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1401.0059">here</a>). </li> <br> <li> Dec. 28, 2013, a paper on GRB light curves in the ICMART model led by <NAME> accepted for publication in ApJ (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1312.7701">here</a>). </li> <br> <li> Dec. 11-12, 2013, traveled to KIAA, Beijing for a collaborative visit. </li> <br> <li> Dec. 10, 2013, finished AST 713 (Astrophysics I) teaching. </li> <br> <li> Nov. 26, 2013, the FRB/GRB connection paper accepted for publication in ApJ Letters (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1310.4893">here</a>). </li> <br> <li> Nov. 23, 2013, a paper on interpreting afterglow and "kilonova" of GRB 130603B within the framework of a supra-massive magnetar central engine, led by <NAME>, accepted for publication in ApJ Letters (<a class="text-link" target="_blank" href="fan13.pdf">here</a>). </li> <br> <li> Nov. 21-22, 2013, visited University of Oklahoma, and delivered a colloquium talk entitled "Physics of gamma-ray bursts and prospects in the multi-messenger era". </li> <br> <li> Nov. 12, 2013, a paper on the origin of smooth cooling break in GRB afterglows, led by <NAME>, accepted for publication in ApJ (<a class="text-link" target="_blank" href="uz13.pdf">here</a>). </li> <br> <li> Nov. 11-15, 2013, attended "Supernova and Gamma-Ray Bursts 2013", Kyoto, Japan. Delivered an invited talk entitled "GRB prompt emission models" (Nov. 11, 2013). </li> <br> <li> Oct. 31, 2013, Mr. <NAME> joined our group as a visiting student (from Nanjing University), supported by Chinese Scholarship Program. </li> <br> <li> Oct. 30, 2013, heard from NASA ADAP program that our proposal entitled "Understanding GRB physics with multi-wavelength data" (13-ADAP13-0134) has been selected for funding (3 years). </li> <br> <li> Oct. 28-29, 2013, attended Swift Science Planning Meeting, State College, Pennsylvania. Delivered a talk entitled "A possible FRB/GRB connection" (Oct. 28, 2013). </li> <br> <li> Oct. 22, 2013, Dr. <NAME> joined our group as a postdoc fellow, supported by Chinese Scholarship Program. </li> <br> <li> Oct. 17, 2013, a new single-author paper "A possible FRB/GRB connection: towards a multi-wavelength campaign to unveil the nature of fast radio bursts" submitted for publication (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1310.4893">here</a>). </li> <br> <li> Oct. 9, 2013, 1st first-author paper (<a class="text-link" target="_blank" href="http://adsabs.harvard.edu/abs/2006ApJ...642..354Z">here</a>) hits 500 citation mark. For a full citation statistics, see <a class="text-link" target="_blank" href="http://www.physics.unlv.edu/~bzhang/citation.html">here</a>. </li> <br> <li> Oct. 9, 2013, a new paper "How long does a burst burst?", led by <NAME> at CSPAR, UAH, submitted for publication (<a class="text-link" target="_blank" href="http://arxiv.org/abs/1310.2540">here</a>). </li> <br> <li> Oct. 6, 2013, long review for New Astronomy Reviews, led by <NAME>, accepted for publication (<a class="text-link" target="_blank" href="gao13d.pdf">here</a>). This is a very detailed review of the analytical synchrotron external shock models of GRBs. Many useful formulae are collected. </li> <br> <li> Sep. 26, 2013, 14th first-author paper (<a class="text-link" target="_blank" href="http://adsabs.harvard.edu/abs/2007ApJ...655L..25Z">here</a>) hits 100 citation mark. For a full citation statistics, see <a class="text-link" target="_blank" href="http://www.physics.unlv.edu/~bzhang/citation.html">here</a>. </li> <br> <li> Sep. 23-26, 2013, Dr. <NAME> (Los Alamos National Laboratory) visited our group. Collaboration discussions. </li> <br> <li> Sep. 19, 2013, a paper on magnetar-powered "mergernova", led by <NAME>, accepted for publication in ApJ Letters (<a class="text-link" target="_blank" href="yzg13.pdf">here</a>). </li> <br> <li> Sep. 15-20, 2013, attended "Explosive Transients: Lighthouses of the Universe" in Santorini, Greece (<a class="text-link" target="_blank" href="http://fermi.gsfc.nasa.gov/science/mtgs/explosive_transients/">web site</a>). Delivered a talk "Theories of GRB prompt emission: the case of a strongly magnetized outflow" (Sep. 19, 2013). </li> <br> <li> Aug. 6, 2013, back to UNLV after one-year sabbatical leave. </li> <br> `; <file_sep># bzhang-website <NAME>'s website <file_sep> let renderPublicationDetails = () => { $("#details").html( ` <div class='arrow-container detail-arrow-up' onClick="scrollUp(); setTimeout(function(){ $('#details').hide() }, 500);"> <div class='arrow'> <i class="fas fa-chevron-up fa-2x"></i> </div> </div> <h1 class="heading detailed-heading">` + publicationDetailTitle + `</h1> <div class="pub-list"> <p class="grey-text">` + publicationDetailContent + ` </p> </div class="pub-list"> `) }; let renderMediaDetails = () => { $("#details").html(` <div class='arrow-container detail-arrow-up' onClick="scrollUp(); setTimeout(function(){ $('#details').hide() }, 500);"> <div class='arrow'> <i class="fas fa-chevron-up fa-2x"></i> </div> </div> <h1 class="heading detailed-heading">`+ mediaDetailTitle + `</h1> <ul class="grey-text">` + mediaDetailContent + ` </ul> `) } let renderAbout = () => { $("#main").hide().html(` <h1 class="heading">` + aboutPreviewTitle + `</h1> <p class="grey-text"> ` + aboutPreviewContent + ` </p> `).fadeIn(1000) } let renderMedia = () => { $("#main").hide().html(` <h1 class="heading">Media</h1> <br> <h4> ` + mediaPreviewTitle + ` </h4><br> <ul class="grey-text"> ` + mediaPreviewContent + ` </ul> <p class="grey-text"> More Articles Below: <div class='arrow-container' onClick="$('#details').show(); renderMediaDetails(); scrollDown()"> <div class='arrow'> <i class="fas fa-chevron-down fa-2x"></i> </div> </div> </p> `).fadeIn(1000); } let renderTeaching = () => { $("#main").hide().html(` <h1 class="heading">` + teachingPreviewTitle + `</h1> <p class="grey-text"> ` + teachingPreviewContent + ` </p> `).fadeIn(1000); } let renderResearch = () => { $("#main").hide().html(` <h1 class="heading">` + researchPreviewTitle + `</h1> <p class="grey-text"> ` + researchPreviewContent + ` <div class='arrow-container' onClick="$('#details').show(); renderGWEM(); scrollDown()"> <div class='arrow'> <i class="fas fa-chevron-down fa-2x"></i> </div> </div> </p> `).fadeIn(1000); } let renderHome = () => { $("#main").hide().html(` <h1 class="heading">` + homePreviewTitle + `</h1> <p class="grey-text"> ` + homePreviewContent + ` </p> <div class="contact-block"> <div class="contact-tex">Contact Me:</div><a href="mailto:<EMAIL>" class="link-v1"><EMAIL></a> </div> `).fadeIn(1000); } let renderPub = () => { $("#main").hide().html(` <h1 class="heading">`+ publicationPreviewTitle + `</h1> <div class="grey-text pub-content"> ` + publicationPreviewContent + ` </div> <div class="grey-text"> <br> My full list of publications can be found below: </div> <br><br> <div class='arrow-container' onClick="$('#details').show(); renderPublicationDetails(); scrollDown()"> <div class='arrow'> <i class="fas fa-chevron-down fa-2x"></i> </div> </div> `).fadeIn(1000); } let renderGWEM = () => { $("#details").html(` <div class='arrow-container detail-arrow-up' onClick="scrollUp(); setTimeout(function(){ $('#details').hide() }, 500);"> <div class='arrow'> <i class="fas fa-chevron-up fa-2x"></i> </div> </div> ` + gwemContent + ` <div class="detail-button-container"> <div class="detail-button selected"> Gravitational Waves and Their Electromagnetic Counterparts </div> <div class="detail-button" onClick="renderFRB()"> Fast Radio Bursts </div> <div class="detail-button" onClick="renderGRB()"> Gamma Ray Bursts </div> </div> `) } let renderFRB = () => { $("#details").html(` <div class='arrow-container detail-arrow-up' onClick="scrollUp(); setTimeout(function(){ $('#details').hide() }, 500);"> <div class='arrow'> <i class="fas fa-chevron-up fa-2x"></i> </div> </div> <h1 class="heading detailed-heading">Fast Radio Bursts</h1> <p class="grey-text"> `+ frbContent + ` </p> <div class="detail-button-container"> <div class="detail-button" onClick="renderGWEM()"> Gravitational Waves and Their Electromagnetic Counterparts </div> <div class="detail-button selected"> Fast Radio Bursts </div> <div class="detail-button" onClick="renderGRB()"> Gamma Ray Bursts </div> </div> `) } let renderGRB = () => { $("#details").html(` <div class='arrow-container detail-arrow-up' onClick="scrollUp(); setTimeout(function(){ $('#details').hide() }, 500);"> <div class='arrow'> <i class="fas fa-chevron-up fa-2x"></i> </div> </div> <h1 class="heading detailed-heading">Gamma Ray Bursts</h1> <p class="grey-text"> ` + grbContent + ` </p> <div class="detail-button-container"> <div class="detail-button" onClick="renderGWEM()"> Gravitational Waves and Their Electromagnetic Counterparts </div> <div class="detail-button" onClick="renderFRB()"> Fast Radio Bursts </div> <div class="detail-button selected" onClick="renderGRB()"> Gamma Ray Bursts </div> </div> `) } window.onload = () => { document.getElementById("about-but").addEventListener('click', () => { event.preventDefault(); scrollUp(); setTimeout(function(){ $('#details').hide() }, 500); history.pushState(null,null, '#about'); renderAbout(); }); document.getElementById("research-but").addEventListener('click', () => { event.preventDefault(); scrollUp(); setTimeout(function(){ $('#details').hide() }, 500); history.pushState(null,null, '#research'); renderResearch(); }); document.getElementById("teaching-but").addEventListener('click', () => { event.preventDefault(); scrollUp(); setTimeout(function(){ $('#details').hide() }, 500); history.pushState(null,null, '#teaching'); renderTeaching(); }); document.getElementById("pub-but").addEventListener('click', () => { event.preventDefault(); scrollUp(); setTimeout(function(){ $('#details').hide() }, 500); history.pushState(null,null, '#publications'); renderPub(); }); document.getElementById("media-but").addEventListener('click', () => { event.preventDefault(); scrollUp(); setTimeout(function(){ $('#details').hide() }, 500); history.pushState(null,null, '#media'); renderMedia(); }); document.getElementById("pfp").addEventListener('click', () => { scrollUp(); setTimeout(function(){ $('#details').hide() }, 500); history.pushState(null,null, '#'); renderHome(); }); $("#details").hide(); } switch(location.hash.substr(1)) { case "about": console.log("about"); renderAbout(); break; case "research": renderResearch(); break; case "teaching": renderTeaching(); break; case "publications": renderPub(); break; case "media": renderMedia(); break; default: renderHome(); } <file_sep>let teachingPreviewTitle = "Teaching"; let teachingPreviewContent = ` AST103: (General Astronomy: Solar System) (fall 2004, spring 2005, spring 2010, spring 2015) <br> AST104: (General Astronomy: Stars and Galaxies) (fall 2005, spring 2006, spring 2007, fall 2007, spring 2008, spring 2009, fall 2015)<br> AST713: (Astrophysics I) (spring 2006, fall 2008, fall 2013)<br> AST725: (High Energy Astrophysics) (fall 2006, fall 2009, spring 2014)<br> AST735: (Gamma-Ray Bursts) (spring 2012. fall 2014)<br> `; <file_sep>let homePreviewTitle = "<NAME>"; let homePreviewContent = ` Professor of Astrophysics at <a target="_blank" href="http://unlv.edu" class="text-link">University of Nevada, Las Vegas</a><br> Member of the <a target="_blank" href="http://www.physics.unlv.edu/" class="text-link">Department of Physics and Astronomy</a><br> Fellow of the American Physical Society <br><br> Check out this <a target="_blank" href="https://www.unlv.edu/news-story/astrophysicist-bing-zhang-elected-aps-fellow" class="text-link">Interview</a> to get to know me! `;
c87c75ef9010ce76599a08d72ad120a93a920002
[ "JavaScript", "Markdown" ]
6
JavaScript
a-lchen/bzhang-website
48cf60ff53c332923637da4e117a2d5633896ca2
69704a12281e6c2b7c2f45319e43b4ca7bbfe52d
refs/heads/master
<file_sep>package com.eventoapp.models; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Evento implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) // Anotação para geração de ID automático no banco private long codigo; public long getCodigo() { return codigo; } public void setCodigo(long codigo) { this.codigo = codigo; } private String nome; private String cidadeDestino; private String km; private String dataSaida; private String dataChegada; private String horaSaida; private String previsaoChegada; public String getKm() { return km; } public void setKm(String km) { this.km = km; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getCidadeDestino() { return cidadeDestino; } public void setCidadeDestino(String cidadeDestino) { this.cidadeDestino = cidadeDestino; } public String getDataSaida() { return dataSaida; } public void setDataSaida(String dataSaida) { this.dataSaida = dataSaida; } public String getDataChegada() { return dataChegada; } public void setDataChegada(String dataChegada) { this.dataChegada = dataChegada; } public String getHoraSaida() { return horaSaida; } public void setHoraSaida(String horaSaida) { this.horaSaida = horaSaida; } public String getPrevisaoChegada() { return previsaoChegada; } public void setPrevisaoChegada(String previsaoChegada) { this.previsaoChegada = previsaoChegada; } }
363596838a397f498334e7231c45c70918f9984f
[ "Java" ]
1
Java
calebeso/projetoWebDocs
dc443719c8c82ec4e21734b6f3cd8a83fb9bd916
f9a7b0b5cf5bc99649041cec2a5a241167ec9122
refs/heads/master
<file_sep>package group.tamasha.rockaar; import android.content.Context; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.TextView; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.StringRequest; import com.google.gson.JsonArray; import com.squareup.picasso.Picasso; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; import group.tamasha.rockaar.util.IabHelper; import group.tamasha.rockaar.util.IabResult; import group.tamasha.rockaar.util.Inventory; import group.tamasha.rockaar.util.Purchase; import libs.mjn.prettydialog.PrettyDialog; import libs.mjn.prettydialog.PrettyDialogCallback; import me.tankery.lib.circularseekbar.CircularSeekBar; import static group.tamasha.rockaar.Utilities.getCurrentShamsidate; public class DashboardFragment extends Fragment { SharedPreferences Token, Username; String token, username; CircularSeekBar seekBarb, seekBarr, seekBarg; String doneWorksString = "0", worksCountString, allAmountString = "0", gottenAmountString = "0", nameOfLastProject, currentTimeFa, url_raiseOffer = "https://raakar.ir/simpleRaiseOffer"; String base64EncodedPublicKey = "<KEY>; Integer doneWorks = 0, worksCount = 0, allAmount = 0, gottenAmount = 0; TextView numberred, numbergreen, numberblue, timelinetime, timelinetitle; SeekBar timeline; static final String TAG = "______________________"; String membership; PrettyDialog pDialog; ImageView Medal; TextView MedalText; static final String SKU_BRONZE = "sku_bronze"; static final String SKU_SILVER = "sku_silver"; static final String SKU_GOLD = "sku_gold"; // IabHelper mHelper; int currentYear, currentMonth, currentDay, startDay, startMonth, startYear, endDay, endMonth, endYear, deadlineDay, myoffernumber, finaloffernumber; public DashboardFragment() { // Required empty public constructor } Button AccountButton; String URLgetInfo = "https://raakar.ir/info"; @Override public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_dashboard, container, false); popupForCheckInternet(); AccountButton=(Button) view.findViewById(R.id.medalbutton); seekBarb = (CircularSeekBar)view.findViewById(R.id.seekbarblue); seekBarr = (CircularSeekBar)view.findViewById(R.id.seekbarred); seekBarg = (CircularSeekBar)view.findViewById(R.id.seekbargreen); numberred = (TextView)view.findViewById(R.id.numberred); numbergreen = (TextView)view.findViewById(R.id.numbergreen); numberblue = (TextView)view.findViewById(R.id.numberblue); timelinetitle = (TextView)view.findViewById(R.id.timelinetitle); timeline = (SeekBar)view.findViewById(R.id.timeline); timelinetime = (TextView)view.findViewById(R.id.timelinetime); timeline.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return true; } }); Token = getActivity().getSharedPreferences("token", Context.MODE_PRIVATE); token = Token.getString("token", null); Username = getActivity().getSharedPreferences("user", Context.MODE_PRIVATE); username = Username.getString("user", null); Medal = (ImageView)view.findViewById(R.id.medalimg); MedalText = (TextView)view.findViewById(R.id.medaltype); final JsonObjectRequest njsonRequest = new JsonObjectRequest (Request.Method.GET, "https://raakar.ir/info", null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d("Response:", response.toString()); try { JSONObject myinfo = response.getJSONObject("info"); membership = myinfo.getString("membership"); if (membership.equals("0")) { Medal.setImageResource(R.drawable.nomedal); MedalText.setText("برای خرید لمس کنید"); MedalText.setTextSize(10); } else if (membership.equals("1")) { Medal.setImageResource(R.drawable.bronzemedal); MedalText.setText("برنزی"); MedalText.setTextSize(12); } else if (membership.equals("2")) { Medal.setImageResource(R.drawable.silvermedal); MedalText.setText("نقره ای"); MedalText.setTextSize(12); } else if (membership.equals("3")) { Medal.setImageResource(R.drawable.goldmedal); MedalText.setText("طلایی"); MedalText.setTextSize(12); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }){@Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); //headers.put("Content-Type", "application/json"); headers.put("token", token); return headers; }}; Singleton.getInstance(getActivity()).addToRequestqueue(njsonRequest); if (membership == "0") { Medal.setImageResource(R.drawable.nomedal); MedalText.setText("برای خرید لمس کنید"); MedalText.setTextSize(10); } else if (membership == "1") { Medal.setImageResource(R.drawable.bronzemedal); MedalText.setText("برنزی"); MedalText.setTextSize(12); } else if (membership == "2") { Medal.setImageResource(R.drawable.silvermedal); MedalText.setText("نقره ای"); MedalText.setTextSize(12); } else if (membership == "3") { Medal.setImageResource(R.drawable.goldmedal); MedalText.setText("طلایی"); MedalText.setTextSize(12); } final JsonArrayRequest mjsonRequest = new JsonArrayRequest (Request.Method.GET, "https://raakar.ir/getMyOffers", null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { Log.d("Response:", response.toString()); try { for (int i = 0; i < response.length(); i++){ JSONObject getMyOffers = response.getJSONObject(i); JSONArray offersArray = getMyOffers.getJSONArray("offersArray"); endDay = 0; startDay = 0; deadlineDay = 0; for (int j = 0; j < offersArray.length(); j++){ JSONObject offerArrayItems = offersArray.getJSONObject(j); if (username.equals(offerArrayItems.getString("creatorUsername"))){ if (offerArrayItems.getBoolean("status") == true){ nameOfLastProject = getMyOffers.getString("name"); timelinetitle.setText(nameOfLastProject); currentTimeFa = getCurrentShamsidate(); String[] separated = currentTimeFa.split("/"); currentYear = Integer.parseInt(separated[0]); currentMonth = Integer.parseInt(separated[1]); currentDay = Integer.parseInt(separated[2]); startDay = offerArrayItems.getInt("acceptionDate"); startMonth = offerArrayItems.getInt("acceptionMonth"); startYear = offerArrayItems.getInt("acceptionYear"); endDay = startDay + offerArrayItems.getInt("deadline"); endMonth = startMonth; endYear = startYear; if ( startMonth == 1 || startMonth == 2 || startMonth == 3 || startMonth == 4 || startMonth == 5 || startMonth == 6 ){ if (endDay > 31){ endDay = endDay - 31; endMonth++; } }else { if (endMonth != 12){ if (endDay > 30){ endDay = endDay - 30; endMonth++; } }else { if (endDay > 29){ endDay = endDay - 29; endMonth = 1; endYear++; } } } if (endYear - currentYear > 0 ){ deadlineDay += (endYear - currentYear) * 365; } if (endMonth - currentMonth > 0){ if (endMonth == 1 || endMonth == 2 || endMonth == 3 || endMonth == 4 || endMonth == 5 || endMonth ==6){ deadlineDay += (endMonth - currentMonth) * 31; }else { deadlineDay += (endMonth - currentMonth) * 30; } } if (endDay - currentDay > 0){ deadlineDay += endDay - currentDay; } timeline.setProgress(0); timeline.setProgress((100*deadlineDay)/offerArrayItems.getInt("deadline")); timelinetime.setText("مدت زمان باقی مانده به روز " + String.valueOf(deadlineDay)); } } } } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }){ @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("token", token); return headers; }}; Singleton.getInstance(getActivity()).addToRequestqueue(mjsonRequest); final JsonObjectRequest jsonRequest = new JsonObjectRequest (Request.Method.GET, URLgetInfo, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d("Response:", response.toString()); try { JSONObject info = response.getJSONObject("info"); doneWorksString = info.getString("doneworks"); Log.d("doneWorksString", doneWorksString); worksCountString = info.getString("workscount"); Log.d("worksCountString", worksCountString); seekBarb.setProgress(0); myoffernumber = info.getInt("myoffernumber"); finaloffernumber = info.getInt("finaloffernumber"); seekBarb.setProgress((100 * myoffernumber) / finaloffernumber); numberblue.setText(String.valueOf(myoffernumber)); JSONObject credit = info.getJSONObject("credit"); int total = credit.getInt("total"); int current = credit.getInt("current"); int allAmount = total + current; int total100 = total/1000; if (worksCountString.equals("0")){ seekBarr.setProgress(0); int seekredValue = ((doneWorks.parseInt(doneWorksString) * 100) / 1); seekBarr.setProgress(seekredValue); numberred.setText(doneWorksString); }else { seekBarr.setProgress(0); int seekredValue = ((doneWorks.parseInt(doneWorksString) * 100) / allAmount); seekBarr.setProgress(seekredValue); numberred.setText(doneWorksString); } if (allAmount == 0){ seekBarg.setProgress(0); int seekgreenValue = ((total * 100) / 1); seekBarg.setProgress(seekgreenValue); numbergreen.setText(String.valueOf(total100)); }else { int seekgreenValue = ((total * 100) / allAmount); seekBarg.setProgress(seekgreenValue); numbergreen.setText(String.valueOf(total100)); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d("Response:", "_______________________________error"); } }){@Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); //headers.put("Content-Type", "application/json"); headers.put("token", token); return headers; }}; Singleton.getInstance(getActivity()).addToRequestqueue(jsonRequest); AccountButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AccountFragment account = new AccountFragment(); getActivity().getSupportFragmentManager().beginTransaction() .replace(R.id.mycontainer, account,"findThisFragment") .addToBackStack(null) .commit(); }}); return view; } public void popupForCheckInternet() { ConnectivityManager connectivityManager = (ConnectivityManager) getContext().getSystemService(getActivity().CONNECTIVITY_SERVICE); NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); NetworkInfo mobileInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if ((wifiInfo != null && wifiInfo.isConnected()) || (mobileInfo != null && mobileInfo.isConnected())){ }else{ pDialog = new PrettyDialog(getActivity()); pDialog.setCancelable(false); pDialog .setTitle("خطا!") .setMessage("لطفا اتصال به اینترنت را برقرار نمایید") .setIcon( R.drawable.pdlg_icon_close, // icon resource R.color.pdlg_color_red, null) .addButton( "تلاش مجدد", R.color.pdlg_color_white, R.color.pdlg_color_red, new PrettyDialogCallback() { @Override public void onClick() { popupForCheckInternet(); pDialog.dismiss(); } } ) .show(); } } } <file_sep>package group.tamasha.rockaar; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.constraint.ConstraintLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.text.Layout; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import com.wang.avi.AVLoadingIndicatorView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Stack; import libs.mjn.prettydialog.PrettyDialog; import libs.mjn.prettydialog.PrettyDialogCallback; public class MessagesFragment extends Fragment { public MessagesFragment() { // Required empty public constructor } String url = "https://raakar.ir/getMyMessages", token, username, nextUsername, lastText; SharedPreferences Token; ListView lv; MyCustomAdapter myadapter; TextView MessagesNullText; ArrayList<MessagesItems> listnewsData = new ArrayList<MessagesItems>(); ArrayList<MessagesItems> result = new ArrayList<MessagesItems>(); AVLoadingIndicatorView av; ConstraintLayout constraint; String nextSenderusername, nextRecieverusername, nextText; boolean nextstatus; Stack<String> message; PrettyDialog pDialog; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_messages, container, false); popupForCheckInternet(); lv = (ListView)view.findViewById(R.id.messages_listView); av = (AVLoadingIndicatorView)view.findViewById(R.id.messages_av); constraint = (ConstraintLayout)view.findViewById(R.id.messages_constraint); message = new Stack<>(); MessagesNullText = (TextView)view.findViewById(R.id.messages_nulltext); Token = getActivity().getSharedPreferences("token", Context.MODE_PRIVATE); token = Token.getString("token", null); av.setVisibility(View.VISIBLE); constraint.setAlpha(0.5f); startAnim(); listnewsData.clear(); final JsonArrayRequest jsonRequest = new JsonArrayRequest (Request.Method.GET, url, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { Log.d("Response:", response.toString()); MessagesNullText.setVisibility(View.GONE); try { for (int i = 0 ; i < response.length() ; i++){ JSONObject ListOfmessages = response.getJSONObject(i); String senderusername = ListOfmessages.getString("senderusername"); String recieverusername = ListOfmessages.getString("recieverusername"); String text = ListOfmessages.getString("text"); boolean status = ListOfmessages.getBoolean("status"); lastText = text; int notEqual = 0; for (int t = 0; t < i ; t++){ JSONObject checkingListOfmessages = response.getJSONObject(t); String checkingSenderusername = checkingListOfmessages.getString("senderusername"); String checkingRecieverusername = checkingListOfmessages.getString("recieverusername"); String checkingText = checkingListOfmessages.getString("text"); boolean checkingStatus = checkingListOfmessages.getBoolean("status"); if (t == i){ for (int j = i + 1; j < response.length(); j++){ JSONObject nextListOfmessages = response.getJSONObject(j); String nextSenderusername = nextListOfmessages.getString("senderusername"); String nextRecieverusername = nextListOfmessages.getString("recieverusername"); String nextText = nextListOfmessages.getString("text"); boolean nextStatus = nextListOfmessages.getBoolean("status"); if (status && nextStatus && recieverusername.equals(nextRecieverusername)){ lastText = nextText; }else if (status && !nextStatus && recieverusername.equals(nextSenderusername)){ lastText = nextText; }else if (!status && nextStatus && senderusername.equals(nextRecieverusername)){ lastText = nextText; }else if (!status && !nextStatus && senderusername.equals(nextSenderusername)){ lastText = nextText; } } if (status){ username = recieverusername; }else { username = senderusername; } listnewsData.add(new MessagesItems(0, username, "تیترها", lastText, "", "2")); } if (status && checkingStatus && !recieverusername.equals(checkingRecieverusername)){ notEqual++; }else if (status && !checkingStatus && !recieverusername.equals(checkingSenderusername)){ notEqual++; }else if (!status && checkingStatus && !senderusername.equals(checkingRecieverusername)){ notEqual++; }else if (!status && !checkingStatus && !senderusername.equals(checkingSenderusername)){ notEqual++; } } if (notEqual == i){ for (int j = i + 1; j < response.length(); j++){ JSONObject nextListOfmessages = response.getJSONObject(j); String nextSenderusername = nextListOfmessages.getString("senderusername"); String nextRecieverusername = nextListOfmessages.getString("recieverusername"); String nextText = nextListOfmessages.getString("text"); boolean nextStatus = nextListOfmessages.getBoolean("status"); if (status && nextStatus && recieverusername.equals(nextRecieverusername)){ lastText = nextText; }else if (status && !nextStatus && recieverusername.equals(nextSenderusername)){ lastText = nextText; }else if (!status && nextStatus && senderusername.equals(nextRecieverusername)){ lastText = nextText; }else if (!status && !nextStatus && senderusername.equals(nextSenderusername)){ lastText = nextText; } } if (status){ username = recieverusername; }else { username = senderusername; } listnewsData.add(new MessagesItems(0, username, "تیترها", lastText, "", "2")); } } } catch (JSONException e1) { e1.printStackTrace(); } myadapter = new MyCustomAdapter(listnewsData); lv.setAdapter(myadapter); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ChatFragment chat = new ChatFragment(); FragmentManager manager = getActivity().getSupportFragmentManager(); manager.beginTransaction().replace(R.id.mycontainer, chat).addToBackStack("chat").commit(); TextView messages_name = (TextView)view.findViewById(R.id.messages_name); SharedPreferences positionOfChat = getActivity().getSharedPreferences("positionOfChat", Context.MODE_PRIVATE); SharedPreferences.Editor positionEditor = positionOfChat.edit(); positionEditor.putInt("position", position); positionEditor.commit(); Bundle senderName = new Bundle(); senderName.putString("senderName", messages_name.getText().toString()); chat.setArguments(senderName); } }); stopAnim(); constraint.setAlpha(1f); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { stopAnim(); constraint.setAlpha(1f); MessagesNullText.setText("مشکل در اتصال به اینترنت!"); MessagesNullText.setVisibility(View.VISIBLE); } }){@Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); //headers.put("Content-Type", "application/json"); headers.put("token", token); return headers; }}; Singleton.getInstance(getActivity()).addToRequestqueue(jsonRequest); return view; } private class MyCustomAdapter extends BaseAdapter { public ArrayList<MessagesItems> listnewsDataAdpater ; public MyCustomAdapter(ArrayList<MessagesItems> listnewsDataAdpater) { this.listnewsDataAdpater = listnewsDataAdpater; } @Override public int getCount() { return listnewsDataAdpater.size(); } @Override public String getItem(int position) { return null; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater mInflater = getActivity().getLayoutInflater(); View myView = mInflater.inflate(R.layout.title_of_messages, null); final MessagesItems s = listnewsDataAdpater.get(position); TextView name = (TextView)myView.findViewById(R.id.messages_name); name.setText(s.name); TextView text = (TextView)myView.findViewById(R.id.messages_text); text.setText(s.text); TextView date = (TextView)myView.findViewById(R.id.messages_date); date.setText(s.date); TextView num = (TextView)myView.findViewById(R.id.messages_num); num.setText(s.num); return myView; } } public void startAnim(){ av.smoothToShow(); } public void stopAnim(){ av.smoothToHide(); } public void popupForCheckInternet() { ConnectivityManager connectivityManager = (ConnectivityManager) getContext().getSystemService(getActivity().CONNECTIVITY_SERVICE); NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); NetworkInfo mobileInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if ((wifiInfo != null && wifiInfo.isConnected()) || (mobileInfo != null && mobileInfo.isConnected())){ }else{ // new AwesomeNoticeDialog(getActivity()) // .setTitle("خطا!") // .setMessage("لطفا اتصال به اینترنت را برقرار نمایید") // .setColoredCircle(R.color.dialogErrorBackgroundColor) // .setDialogIconAndColor(R.drawable.ic_dialog_info, R.color.white) // .setCancelable(false) // .setButtonText("تلاش مجدد") // .setButtonBackgroundColor(R.color.dialogErrorBackgroundColor) // .setButtonText("تلاش مجدد") // .setNoticeButtonClick(new Closure() { // @Override // public void exec() { // popupForCheckInternet(); // } // }) // .show(); pDialog = new PrettyDialog(getActivity()); pDialog.setCancelable(false); pDialog .setTitle("خطا!") .setMessage("لطفا اتصال به اینترنت را برقرار نمایید") .setIcon( R.drawable.pdlg_icon_close, // icon resource R.color.pdlg_color_red, null) .addButton( "تلاش مجدد", R.color.pdlg_color_white, R.color.pdlg_color_red, new PrettyDialogCallback() { @Override public void onClick() { popupForCheckInternet(); pDialog.dismiss(); } } ) .show(); } } } <file_sep>package group.tamasha.rockaar; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import libs.mjn.prettydialog.PrettyDialog; import libs.mjn.prettydialog.PrettyDialogCallback; public class InviteFragment extends Fragment { public InviteFragment() { // Required empty public constructor } PrettyDialog pDialog1; PrettyDialog pDialog2; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_invite, container, false); popupForCheckInternet(); Button invite_button = (Button)view.findViewById(R.id.invite_button); invite_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, "برای دانلود اپلیکیشن راکار و بهره مندی از سرویس فریلنسینگ، اپلیکیشن را از طریق لینک زیر دانلود و نصب نمایید:\n" + "https://raakar.ir/#download"); sendIntent.setType("text/plain"); startActivity(sendIntent); } }); return view; } public void popupForCheckInternet() { ConnectivityManager connectivityManager = (ConnectivityManager) getContext().getSystemService(getActivity().CONNECTIVITY_SERVICE); NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); NetworkInfo mobileInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if ((wifiInfo != null && wifiInfo.isConnected()) || (mobileInfo != null && mobileInfo.isConnected())){ }else{ pDialog2 = new PrettyDialog(getActivity()); pDialog2.setCancelable(false); pDialog2 .setTitle("خطا!") .setMessage("لطفا اتصال به اینترنت را برقرار نمایید") .setIcon( R.drawable.pdlg_icon_close, // icon resource R.color.pdlg_color_red, null) .addButton( "تلاش مجدد", R.color.pdlg_color_white, R.color.pdlg_color_red, new PrettyDialogCallback() { @Override public void onClick() { popupForCheckInternet(); pDialog2.dismiss(); } } ) .show(); } } } <file_sep>package group.tamasha.rockaar; import android.Manifest; import android.app.Activity; import android.content.ClipData; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.ParcelFileDescriptor; import android.provider.MediaStore; import android.support.annotation.RequiresApi; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.MimeTypeMap; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.nononsenseapps.filepicker.FilePickerActivity; import com.nononsenseapps.filepicker.Utils; import java.io.File; import java.io.FileDescriptor; import java.io.IOException; import java.net.URISyntaxException; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; import java.util.Locale; import libs.mjn.prettydialog.PrettyDialog; import libs.mjn.prettydialog.PrettyDialogCallback; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class AddFragment extends Fragment { String token, userProfileImagePath; Button add; PrettyDialog pDialog1; PrettyDialog pDialog2; PrettyDialog pDialog3; PrettyDialog pDialog4, pDialog5; EditText name, amount, deadline, description; Spinner category; ImageView add_attachback, imageToUpload, upload; SharedPreferences Token; private static int RESULT_LOAD_IMAGE = 1; TextView add_attachtitle; private static final int REQUEST_EXTERNAL_STORAGE = 1; private static String[] PERMISSIONS_STORAGE = { android.Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE }; public AddFragment() { // Required empty public constructor } @Override public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_add, container, false); popupForCheckInternet(); add =(Button)view.findViewById(R.id.add_button); name = (EditText)view.findViewById(R.id.add_titletext); amount = (EditText)view.findViewById(R.id.add_pricenumber); description = (EditText)view.findViewById(R.id.add_infotext); category = (Spinner)view.findViewById(R.id.add_spinnercategory); deadline = (EditText)view.findViewById(R.id.add_timenumber); imageToUpload = (ImageView)view.findViewById(R.id.add_imageToUpload); add_attachtitle = (TextView)view.findViewById(R.id.add_attachtitle); upload = (ImageView)view.findViewById(R.id.add_upload); imageToUpload.setVisibility(View.GONE); add_attachback = (ImageView)view.findViewById(R.id.add_attachback); upload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.i("sss", "onClick"); int permission = ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.WRITE_EXTERNAL_STORAGE); if (permission != PackageManager.PERMISSION_GRANTED) { Log.i("sss", "!PERMISSION_GRANTED"); requestPermissions( PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE ); return; } else { Log.i("sss", "PERMISSION_GRANTED"); openImagePicker(); } } }); Token = getActivity().getSharedPreferences("token", Context.MODE_PRIVATE); token = Token.getString("token", null); add.setOnClickListener(new View.OnClickListener() { @RequiresApi(api = Build.VERSION_CODES.KITKAT) @Override public void onClick(View v) { if (name.getText().toString().equals("") || description.getText().toString().equals("") || deadline.getText().toString().equals("")) { popupForErrorEmptyField(); } else { Client client = ServiceGenerator.createService(Client.class); File file = null; RequestBody requestFile = null; MultipartBody.Part body = null; if (userProfileImagePath != null) { try { file = new File(userProfileImagePath); Uri uri = Uri.fromFile(file); if (file.exists()) { Log.i("finaltest", "found"); requestFile = RequestBody.create(MediaType.parse(getMimeType(uri)), file); body = MultipartBody.Part.createFormData("projectFile", file.getName(), requestFile); } else { Log.i("finaltest", "not found"); pDialog5 = new PrettyDialog(getActivity()); pDialog5 .setTitle("خطا!") .setMessage("حجم فایل مورد نظر زیاد می باشد") .setIcon( R.drawable.pdlg_icon_close, // icon resource R.color.pdlg_color_red, null) .addButton( "باشه", R.color.pdlg_color_white, R.color.pdlg_color_red, new PrettyDialogCallback() { @Override public void onClick() { pDialog5.dismiss(); } } ) .show(); } } catch (Exception e) { } } long Amount; String T = amount.getText().toString(); String Text = T.replaceAll("[^0-9]+",""); RequestBody nameRequestBody = RequestBody.create(MediaType.parse("text/plain"), name.getText().toString().trim()); if (amount.getText().toString().equals("")){ Amount = 0; } else { Amount = Long.parseLong(Text); } RequestBody descriptionRequestBody = RequestBody.create(MediaType.parse("text/plain"), description.getText().toString().trim()); RequestBody categoryRequestBody = RequestBody.create(MediaType.parse("text/plain"), category.getSelectedItem().toString()); RequestBody deadlineRequestBody = RequestBody.create(MediaType.parse("text/plain"), deadline.getText().toString().trim()); Call<AddProjectResponse> call = client.addProject( token, body, Amount, nameRequestBody, descriptionRequestBody, categoryRequestBody, deadlineRequestBody); call.enqueue(new Callback<AddProjectResponse>() { @Override public void onResponse(Call<AddProjectResponse> call, Response<AddProjectResponse> response) { Log.e("xcxc", "code:" + response.code()); if (response.isSuccessful()) { Log.e("xcxc", "success:"); popupForSuccessAddingProject(); } else { Toast.makeText(getContext(), "مشکلی در ثبت پروژه به وجود آمد!", Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call<AddProjectResponse> call, Throwable t) { Log.e("test123", t.getMessage()); popupForErrorToAddProject(); } }); } } }); amount.addTextChangedListener(onTextChangedListener()); return view; } public void openImagePicker() { Log.i("sss", "call"); // Intent i = new Intent( // Intent.ACTION_PICK, // android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); // startActivityForResult(i, RESULT_LOAD_IMAGE); Intent i = new Intent(getActivity(), FilePickerActivity.class); // This works if you defined the intent filter // Intent i = new Intent(Intent.ACTION_GET_CONTENT); // Set these depending on your use case. These are the defaults. i.putExtra(FilePickerActivity.EXTRA_ALLOW_MULTIPLE, false); i.putExtra(FilePickerActivity.EXTRA_ALLOW_CREATE_DIR, false); i.putExtra(FilePickerActivity.EXTRA_MODE, FilePickerActivity.MODE_FILE); // Configure initial directory by specifying a String. // You could specify a String like "/storage/emulated/0/", but that can // dangerous. Always use Android's API calls to get paths to the SD-card or // internal memory. i.putExtra(FilePickerActivity.EXTRA_START_PATH, Environment.getExternalStorageDirectory().getPath()); startActivityForResult(i, RESULT_LOAD_IMAGE); } private Bitmap getBitmapFromUri(Uri uri) throws IOException { ParcelFileDescriptor parcelFileDescriptor = getContext().getContentResolver().openFileDescriptor(uri, "r"); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor); parcelFileDescriptor.close(); return image; } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RESULT_LOAD_IMAGE && resultCode == -1 && null != data) { add_attachtitle.setText("فایل با موفقیت ضمیمه شد!"); Uri selectedImageUri = data.getData(); if ("content".equalsIgnoreCase(selectedImageUri.getScheme())) { String[] projection = { "_data" }; Cursor cursor = null; try { cursor = getContext().getContentResolver().query(selectedImageUri, projection, null, null, null); int column_index = cursor.getColumnIndexOrThrow("_data"); if (cursor.moveToFirst()) { userProfileImagePath = cursor.getString(column_index); } } catch (Exception e) { // Eat it } } else if ("file".equalsIgnoreCase(selectedImageUri.getScheme())) { userProfileImagePath = selectedImageUri.getPath(); } Log.d("file path", userProfileImagePath); Log.d("uri", selectedImageUri.toString()); Bitmap bmp = null; try { bmp = getBitmapFromUri(selectedImageUri); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // if (requestCode == RESULT_LOAD_IMAGE && resultCode == Activity.RESULT_OK) { // if (data.getBooleanExtra(FilePickerActivity.EXTRA_ALLOW_MULTIPLE, false)) { // // For JellyBean and above // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { // ClipData clip = data.getClipData(); // // if (clip != null) { // for (int i = 0; i < clip.getItemCount(); i++) { // Uri uri = clip.getItemAt(i).getUri(); // // Do something with the URI // } // } // // For Ice Cream Sandwich // } else { // ArrayList<String> paths = data.getStringArrayListExtra // (FilePickerActivity.EXTRA_PATHS); // // if (paths != null) { // for (String path: paths) { // Uri uri = Uri.parse(path); // // Do something with the URI // } // } // } // // } else { // Uri uri = data.getData(); // // Do something with the URI // // add_attachtitle.setText("فایل با موفقیت ضمیمه شد!"); // // Uri selectedImageUri = data.getData(); // // String[] filePathColumn = {MediaStore.Images.Media.DATA}; // // // Cursor cursor = getContext().getContentResolver().query(selectedImageUri, // filePathColumn, null, null, null); // cursor.moveToFirst(); // // int columnIndex = cursor.getColumnIndex(filePathColumn[0]); // userProfileImagePath = cursor.getString(columnIndex); // cursor.close(); // // Bitmap bmp = null; // try { // bmp = getBitmapFromUri(selectedImageUri); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { switch (requestCode) { case REQUEST_EXTERNAL_STORAGE: if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission Granted openImagePicker(); } else { // Permission Denied } break; default: super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } public void popupForErrorEmptyField(){ pDialog2 = new PrettyDialog(getActivity()); pDialog2.setCancelable(false); pDialog2 .setTitle("خطا!") .setMessage("فیلدهای عنوان، مدت زمان انجام و توضیحات نباید خالی باشد") .setIcon( R.drawable.pdlg_icon_close, // icon resource R.color.pdlg_color_red, null) .addButton( "باشه", R.color.pdlg_color_white, R.color.pdlg_color_red, new PrettyDialogCallback() { @Override public void onClick() { pDialog2.dismiss(); } } ) .show(); } public void popupForErrorToAddProject(){ pDialog1 = new PrettyDialog(getActivity()); pDialog1.setCancelable(false); pDialog1 .setTitle("خطا!") .setMessage("مشکلی در ثبت پروژه پیش آمده است") .setIcon( R.drawable.pdlg_icon_close, // icon resource R.color.pdlg_color_red, null) .addButton( "باشه", R.color.pdlg_color_white, R.color.pdlg_color_red, new PrettyDialogCallback() { @Override public void onClick() { pDialog1.dismiss(); } } ) .show(); } public void popupForSuccessAddingProject(){ // new AwesomeSuccessDialog(getContext()) // .setTitle("ثبت با موفقیت انجام شد!") // .setMessage("پروژه شما در حال بررسی توسط ادمین می باشد") // .setPositiveButtonText(getString(R.string.dialog_ok_button)) // .setPositiveButtonClick(new Closure() { // @Override // public void exec() { // ProjectsFragment projectsFragment = new ProjectsFragment(); // FragmentManager manager = getActivity().getSupportFragmentManager(); // manager.beginTransaction().replace(R.id.mycontainer, projectsFragment).commit(); // } // }) // .show(); pDialog3 = new PrettyDialog(getActivity()); pDialog3.setCancelable(false); pDialog3 .setTitle("ثبت با موفقیت انجام شد!") .setMessage("پروژه شما در حال بررسی توسط ادمین می باشد") .setIcon( R.drawable.pdlg_icon_success, // icon resource R.color.pdlg_color_green, null) .addButton( "باشه", R.color.pdlg_color_white, R.color.pdlg_color_green, new PrettyDialogCallback() { @Override public void onClick() { pDialog3.dismiss(); ProjectsFragment projectsFragment = new ProjectsFragment(); FragmentManager manager = getActivity().getSupportFragmentManager(); manager.beginTransaction().replace(R.id.mycontainer, projectsFragment).commit(); } } ) .show(); } public String getMimeType(Uri uri) { String mimeType = ""; if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) { ContentResolver cr = getActivity().getContentResolver(); mimeType = cr.getType(uri); } else { String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri .toString()); mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension( fileExtension.toLowerCase()); } return mimeType; } public void popupForCheckInternet() { ConnectivityManager connectivityManager = (ConnectivityManager) getContext().getSystemService(getActivity().CONNECTIVITY_SERVICE); NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); NetworkInfo mobileInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if ((wifiInfo != null && wifiInfo.isConnected()) || (mobileInfo != null && mobileInfo.isConnected())){ }else{ pDialog4 = new PrettyDialog(getActivity()); pDialog4.setCancelable(false); pDialog4 .setTitle("خطا!") .setMessage("لطفا اتصال به اینترنت را برقرار نمایید") .setIcon( R.drawable.pdlg_icon_close, // icon resource R.color.pdlg_color_red, null) .addButton( "تلاش مجدد", R.color.pdlg_color_white, R.color.pdlg_color_red, new PrettyDialogCallback() { @Override public void onClick() { popupForCheckInternet(); pDialog4.dismiss(); } } ) .show(); } } private TextWatcher onTextChangedListener() { return new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { amount.removeTextChangedListener(this); try { String originalString = s.toString(); Long longval; if (originalString.contains(",")) { originalString = originalString.replaceAll(",", ""); } longval = Long.parseLong(originalString); DecimalFormat formatter = (DecimalFormat) NumberFormat.getInstance(Locale.US); formatter.applyPattern("#,###,###,###"); String formattedString = formatter.format(longval); //setting text after format to EditText amount.setText(formattedString); amount.setSelection(amount.getText().length()); } catch (NumberFormatException nfe) { nfe.printStackTrace(); } amount.addTextChangedListener(this); } }; } } <file_sep>package group.tamasha.rockaar; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.StringRequest; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import libs.mjn.prettydialog.PrettyDialog; import libs.mjn.prettydialog.PrettyDialogCallback; public class MyBidsFragment extends Fragment { ListView mybids_listview; ArrayList<MyBidsAdapterItems> mlistnewsData = new ArrayList<MyBidsAdapterItems>(); String url = "https://raakar.ir/getMyProjects", token, projectIndex, url_accept = "https://raakar.ir/acceptOffer", offerIndex; SharedPreferences Token, usernameOfOffer; Bundle bundle; int position; TextView mybids_title, mybids_details, mybids_nulltext; ArrayList<String> usernames = new ArrayList<String>(); SharedPreferences.Editor usernameEditor; String paymentURL = "https://raakar.ir", trimmed, amountString; PrettyDialog pDialog1; PrettyDialog pDialog2; public MyBidsFragment() { // Required empty public constructor } // Store instance variables based on arguments passed @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } // Inflate the view for the fragment based on layout XML @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_mybids, container, false); popupForCheckInternet(); bundle = getArguments(); position = bundle.getInt("position"); mybids_title = (TextView)view.findViewById(R.id.mybids_title); mybids_details = (TextView)view.findViewById(R.id.mybids_details); mybids_nulltext = (TextView)view.findViewById(R.id.mybids_nulltext); mybids_title.setText(bundle.getString("name")); mybids_listview = (ListView)view.findViewById(R.id.mybids_listview); Token = getActivity().getSharedPreferences("token", Context.MODE_PRIVATE); token = Token.getString("token", null); usernameOfOffer = getActivity().getSharedPreferences("username", Context.MODE_PRIVATE); usernameEditor = usernameOfOffer.edit(); final JsonObjectRequest jsonRequest = new JsonObjectRequest (Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d("Response:", response.toString()); mlistnewsData.clear(); try { mybids_nulltext.setVisibility(View.GONE); JSONArray myProjects = response.getJSONArray("yourProjects"); JSONObject offerInfo = myProjects.getJSONObject(position); projectIndex = offerInfo.getString("projectIndex"); amountString = offerInfo.getString("amount"); String Text = amountString.replaceAll("[^0-9]+",""); long Number = Long.parseLong(Text); DecimalFormat formatter = new DecimalFormat("#,###,###,###,###"); String yourFormattedString = formatter.format(Number); if (yourFormattedString.equals("0")){ mybids_details.setText("توافقی"); }else { mybids_details.setText(yourFormattedString + " تومان " + " ( " + offerInfo.getString("deadline") + " روز ) " ); } JSONArray offerArray = offerInfo.getJSONArray("offersArray"); if (offerArray.length() == 0){ mybids_nulltext.setVisibility(View.VISIBLE); }else { for (int j = 0; j < offerArray.length(); j++){ JSONObject infoOfOffer = offerArray.getJSONObject(j); String TXT = infoOfOffer.getString("amount"); String MyText = TXT.replaceAll("[^0-9]+",""); long MyNumber = Long.parseLong(MyText); DecimalFormat myformatter = new DecimalFormat("#,###,###,###,###"); String myFormattedString = myformatter.format(MyNumber); // int day = infoOfOffer.getInt(""); if (infoOfOffer.getBoolean("status") == false){ mlistnewsData.add(new MyBidsAdapterItems(1, 1, infoOfOffer.getString("creatorName"), infoOfOffer.getString("description"), infoOfOffer.getString("creationDate"), myFormattedString, "-1000000", infoOfOffer.getString("deadline"), "+10")); usernames.add(infoOfOffer.getString("creatorUsername")); } } MyBidsFragment.MyBidsAdapter madapter; madapter = new MyBidsAdapter(mlistnewsData); mybids_listview.setAdapter(madapter); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }){@Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); //headers.put("Content-Type", "application/json"); headers.put("token", token); return headers; }}; Singleton.getInstance(getActivity()).addToRequestqueue(jsonRequest); mybids_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { PublicProfileFragment PublicProfileFragment = new PublicProfileFragment(); FragmentManager manager = getActivity().getSupportFragmentManager(); manager.beginTransaction().replace(R.id.mycontainer, PublicProfileFragment).addToBackStack("Back").commit(); String username = usernames.get(position); usernameEditor.putString("userName", username).commit(); } }); return view; } private class MyBidsAdapter extends BaseAdapter { public ArrayList<MyBidsAdapterItems> mlistnewsDataAdpater ; public MyBidsAdapter(ArrayList<MyBidsAdapterItems> mlistnewsDataAdpater) { this.mlistnewsDataAdpater=mlistnewsDataAdpater; } @Override public int getCount() { return mlistnewsDataAdpater.size(); } @Override public String getItem(int position) { return null; } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { LayoutInflater mInflater = getActivity().getLayoutInflater(); View myView = mInflater.inflate(R.layout.mybids_item, null); final MyBidsAdapterItems m = mlistnewsDataAdpater.get(position); TextView name = (TextView)myView.findViewById(R.id.mybids_name); name.setText(m.mname); TextView describtion = (TextView)myView.findViewById(R.id.mybids_describtion); describtion.setText(m.mdescribtion); TextView date = (TextView)myView.findViewById(R.id.mybids_date); date.setText(m.mdate); TextView bidprice = (TextView)myView.findViewById(R.id.mybids_bidprice); bidprice.setText(m.mbidprice); TextView bidtime = (TextView)myView.findViewById(R.id.mybids_bidtime); bidtime.setText(m.mbidtime); ImageView mybids_accept_button = (ImageView)myView.findViewById(R.id.mybids_accept_button); mybids_accept_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { offerIndex = String.valueOf(mybids_listview.getPositionForView(v)); popupForAccept(); } }); return myView; } } public void popupForAccept(){ // new AwesomeInfoDialog(getActivity()) // .setTitle("توجه!") // .setMessage("برای پذیرش پیشنهاد شما باید 20% مبلغ پیشنهادی را پرداخت نمایید!") // .setColoredCircle(R.color.RakaarColor) // .setDialogIconAndColor(R.drawable.ic_dialog_info, R.color.white) // .setCancelable(true) // .setPositiveButtonText("باشه") // .setPositiveButtonbackgroundColor(R.color.RakaarColor) // .setPositiveButtonTextColor(R.color.white) // .setPositiveButtonClick(new Closure() { // @Override // public void exec() { // StringRequest postRequest = new StringRequest(Request.Method.POST, url_accept, // new Response.Listener<String>() // { // @Override // public void onResponse(String response) { // // response // Log.d("Response", response); // trimmed = response.substring(1, response.length()-1); // paymentURL += trimmed; // Log.d("payment", paymentURL); // Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(paymentURL)); // startActivity(intent); // paymentURL = "https://raakar.ir"; // trimmed = ""; // } // }, // new Response.ErrorListener() { // @Override // public void onErrorResponse(VolleyError error) { // // error // Log.d("Error.Response", "Error"); // // } // } // ) { // @Override // protected Map<String, String> getParams() // { // Map<String, String> params = new HashMap<String, String>(); // params.put("projectIndex", projectIndex); // params.put("offerIndex", offerIndex); // params.put("description", "پیش پرداخت انجام پروژه برای راکار"); // params.put("email", "<EMAIL>"); // params.put("phonenumber", "09016081024"); // // return params; // } // // @Override // public Map<String, String> getHeaders() throws AuthFailureError // { // HashMap<String, String> headers = new HashMap<String, String>(); // //headers.put("Content-Type", "application/json"); // headers.put("token", token); // return headers; // } // }; // Singleton.getInstance(getActivity()).addToRequestqueue(postRequest); // } // }) // .setNegativeButtonText("نه") // .setNegativeButtonbackgroundColor(R.color.RakaarColor) // .setNegativeButtonTextColor(R.color.white) // .setNegativeButtonClick(new Closure() { // @Override // public void exec() { // //click // } // }) // .show(); pDialog1 = new PrettyDialog(getActivity()); pDialog1 .setTitle("توجه!") .setMessage("برای پذیرش پیشنهاد شما باید 10% مبلغ پیشنهادی را پرداخت نمایید!") .setIcon( R.drawable.pdlg_icon_info, // icon resource R.color.RakaarColor, null) .addButton( "باشه", R.color.pdlg_color_white, R.color.RakaarColor, new PrettyDialogCallback() { @Override public void onClick() { pDialog1.dismiss(); StringRequest postRequest = new StringRequest(Request.Method.POST, url_accept, new Response.Listener<String>() { @Override public void onResponse(String response) { // response Log.d("Response", response); trimmed = response.substring(1, response.length()-1); paymentURL += trimmed; Log.d("payment", paymentURL); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(paymentURL)); startActivity(intent); paymentURL = "https://raakar.ir"; trimmed = ""; } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // error Log.d("Error.Response", "Error"); } } ) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); params.put("projectIndex", projectIndex); params.put("offerIndex", offerIndex); params.put("description", "پیش پرداخت انجام پروژه برای راکار"); params.put("email", "<EMAIL>"); params.put("phonenumber", "09016081024"); return params; } @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); //headers.put("Content-Type", "application/json"); headers.put("token", token); return headers; } }; Singleton.getInstance(getActivity()).addToRequestqueue(postRequest); } } ) .addButton( "نه", R.color.pdlg_color_white, R.color.RakaarColor, new PrettyDialogCallback() { @Override public void onClick() { pDialog1.dismiss(); } } ) .show(); } public void popupForCheckInternet() { ConnectivityManager connectivityManager = (ConnectivityManager) getContext().getSystemService(getActivity().CONNECTIVITY_SERVICE); NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); NetworkInfo mobileInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if ((wifiInfo != null && wifiInfo.isConnected()) || (mobileInfo != null && mobileInfo.isConnected())){ }else{ pDialog2 = new PrettyDialog(getActivity()); pDialog2.setCancelable(false); pDialog2 .setTitle("خطا!") .setMessage("لطفا اتصال به اینترنت را برقرار نمایید") .setIcon( R.drawable.pdlg_icon_close, // icon resource R.color.pdlg_color_red, null) .addButton( "تلاش مجدد", R.color.pdlg_color_white, R.color.pdlg_color_red, new PrettyDialogCallback() { @Override public void onClick() { popupForCheckInternet(); pDialog2.dismiss(); } } ) .show(); } } } <file_sep>package group.tamasha.rockaar; import com.google.gson.annotations.SerializedName; public class AddProjectResponse { @SerializedName("success") private boolean success; public boolean isSuccess() { return success; } public String err; public String getError(){ return err; } } <file_sep>package group.tamasha.rockaar; public class MessagesItems { public int green; public String name; public String title; public String text; public String date; public String num; MessagesItems(int green, String name, String title, String text, String date, String num) { this.green = green; this.name = name; this.title = title; this.text = text; this.date = date; this.num = num; } } <file_sep>package group.tamasha.rockaar; public class AdapterItems { public int more; public String name; public String details; public String cost; AdapterItems(int more, String name, String details, String cost) { this.more = more; this.name = name; this.details = details; this.cost = cost; } } <file_sep>package group.tamasha.rockaar; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import java.util.HashMap; import java.util.Map; import libs.mjn.prettydialog.PrettyDialog; import libs.mjn.prettydialog.PrettyDialogCallback; import uk.co.chrisjenx.calligraphy.CalligraphyConfig; import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper; public class RatingActivity extends AppCompatActivity { PrettyDialog pDialog1; PrettyDialog pDialog2; PrettyDialog pDialog3; ImageView Star1, Star2, Star3, Star4, Star5, Line1, Line2, Line3, Line4, Line5; TextView Text1, Text2, Text3, Text4, Text5; Button RatingButton; int Rate = 0; SharedPreferences LaunchCounter, Token; SharedPreferences.Editor LaunchCounterEditor; int Counter; String url = "https://raakar.ir/rate", token; String projectOwnerUserName, projectIndex, projectOwerName; TextView rating_name, rating_expertise; public void setupFont() { CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() .setDefaultFontPath("fonts/IRANSansMobile.TTF") .setFontAttrId(R.attr.fontPath) .build() ); } @Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase)); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setupFont(); setContentView(R.layout.activity_rating); popupForCheckInternet(); // final Bundle bundle = getArguments(); final SharedPreferences category,creatorName,projectOwnerUsername,projectIndex; category = getSharedPreferences("category", Context.MODE_PRIVATE); creatorName = getSharedPreferences("creatorName", Context.MODE_PRIVATE); projectOwnerUsername = getSharedPreferences("creatorUsername", Context.MODE_PRIVATE); projectIndex = getSharedPreferences("projectIndex", Context.MODE_PRIVATE); Log.e("creatorUsername", projectOwnerUsername.getString("creatorUsername", "")); Log.e("projectIndex", projectIndex.getString("projectIndex", "")); rating_name = (TextView)findViewById(R.id.rating_name); rating_expertise = (TextView)findViewById(R.id.rating_expertise); rating_name.setText(creatorName.getString("creatorName", "")); rating_expertise.setText(category.getString("category", "")); Token = getSharedPreferences("token", Context.MODE_PRIVATE); token = Token.getString("token", null); Star1 = (ImageView)findViewById(R.id.rating_star1); Star2 = (ImageView)findViewById(R.id.rating_star2); Star3 = (ImageView)findViewById(R.id.rating_star3); Star4 = (ImageView)findViewById(R.id.rating_star4); Star5 = (ImageView)findViewById(R.id.rating_star5); Line1 = (ImageView)findViewById(R.id.rating_line1); Line2 = (ImageView)findViewById(R.id.rating_line2); Line3 = (ImageView)findViewById(R.id.rating_line3); Line4 = (ImageView)findViewById(R.id.rating_line4); Line5 = (ImageView)findViewById(R.id.rating_line5); Text1 = (TextView)findViewById(R.id.rating_text1); Text2 = (TextView)findViewById(R.id.rating_text2); Text3 = (TextView)findViewById(R.id.rating_text3); Text4 = (TextView)findViewById(R.id.rating_text4); Text5 = (TextView)findViewById(R.id.rating_text5); RatingButton = (Button)findViewById(R.id.rating_button); Star1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Star1.setBackgroundResource(R.drawable.stary); Star2.setBackgroundResource(R.drawable.starg); Star3.setBackgroundResource(R.drawable.starg); Star4.setBackgroundResource(R.drawable.starg); Star5.setBackgroundResource(R.drawable.starg); Line1.setBackgroundResource(R.drawable.ratingline_yu); Line2.setBackgroundResource(R.drawable.ratingline_gd); Line3.setBackgroundResource(R.drawable.ratingline_gu); Line4.setBackgroundResource(R.drawable.ratingline_gd); Line5.setBackgroundResource(R.drawable.ratingline_gu); Text1.setTextColor(Color.parseColor("#e5bc17")); Text2.setTextColor(Color.parseColor("#999999")); Text3.setTextColor(Color.parseColor("#999999")); Text4.setTextColor(Color.parseColor("#999999")); Text5.setTextColor(Color.parseColor("#999999")); Rate = 1; Log.e("Rate", String.valueOf(Rate)); } }); Star2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Star1.setBackgroundResource(R.drawable.stary); Star2.setBackgroundResource(R.drawable.stary); Star3.setBackgroundResource(R.drawable.starg); Star4.setBackgroundResource(R.drawable.starg); Star5.setBackgroundResource(R.drawable.starg); Line1.setBackgroundResource(R.drawable.ratingline_yu); Line2.setBackgroundResource(R.drawable.ratingline_yd); Line3.setBackgroundResource(R.drawable.ratingline_gu); Line4.setBackgroundResource(R.drawable.ratingline_gd); Line5.setBackgroundResource(R.drawable.ratingline_gu); Text1.setTextColor(Color.parseColor("#e5bc17")); Text2.setTextColor(Color.parseColor("#e5bc17")); Text3.setTextColor(Color.parseColor("#999999")); Text4.setTextColor(Color.parseColor("#999999")); Text5.setTextColor(Color.parseColor("#999999")); Rate = 2; Log.e("Rate", String.valueOf(Rate)); } }); Star3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Star1.setBackgroundResource(R.drawable.stary); Star2.setBackgroundResource(R.drawable.stary); Star3.setBackgroundResource(R.drawable.stary); Star4.setBackgroundResource(R.drawable.starg); Star5.setBackgroundResource(R.drawable.starg); Line1.setBackgroundResource(R.drawable.ratingline_yu); Line2.setBackgroundResource(R.drawable.ratingline_yd); Line3.setBackgroundResource(R.drawable.ratingline_yu); Line4.setBackgroundResource(R.drawable.ratingline_gd); Line5.setBackgroundResource(R.drawable.ratingline_gu); Text1.setTextColor(Color.parseColor("#e5bc17")); Text2.setTextColor(Color.parseColor("#e5bc17")); Text3.setTextColor(Color.parseColor("#e5bc17")); Text4.setTextColor(Color.parseColor("#999999")); Text5.setTextColor(Color.parseColor("#999999")); Rate = 3; Log.e("Rate", String.valueOf(Rate)); } }); Star4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Star1.setBackgroundResource(R.drawable.stary); Star2.setBackgroundResource(R.drawable.stary); Star3.setBackgroundResource(R.drawable.stary); Star4.setBackgroundResource(R.drawable.stary); Star5.setBackgroundResource(R.drawable.starg); Line1.setBackgroundResource(R.drawable.ratingline_yu); Line2.setBackgroundResource(R.drawable.ratingline_yd); Line3.setBackgroundResource(R.drawable.ratingline_yu); Line4.setBackgroundResource(R.drawable.ratingline_yd); Line5.setBackgroundResource(R.drawable.ratingline_gu); Text1.setTextColor(Color.parseColor("#e5bc17")); Text2.setTextColor(Color.parseColor("#e5bc17")); Text3.setTextColor(Color.parseColor("#e5bc17")); Text4.setTextColor(Color.parseColor("#e5bc17")); Text5.setTextColor(Color.parseColor("#999999")); Rate = 4; Log.e("Rate", String.valueOf(Rate)); } }); Star5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Star1.setBackgroundResource(R.drawable.stary); Star2.setBackgroundResource(R.drawable.stary); Star3.setBackgroundResource(R.drawable.stary); Star4.setBackgroundResource(R.drawable.stary); Star5.setBackgroundResource(R.drawable.stary); Line1.setBackgroundResource(R.drawable.ratingline_yu); Line2.setBackgroundResource(R.drawable.ratingline_yd); Line3.setBackgroundResource(R.drawable.ratingline_yu); Line4.setBackgroundResource(R.drawable.ratingline_yd); Line5.setBackgroundResource(R.drawable.ratingline_yu); Text1.setTextColor(Color.parseColor("#e5bc17")); Text2.setTextColor(Color.parseColor("#e5bc17")); Text3.setTextColor(Color.parseColor("#e5bc17")); Text4.setTextColor(Color.parseColor("#e5bc17")); Text5.setTextColor(Color.parseColor("#e5bc17")); Rate = 5; Log.e("Rate", String.valueOf(Rate)); } }); LaunchCounter = getApplicationContext().getSharedPreferences("launch", Context.MODE_PRIVATE); LaunchCounterEditor = LaunchCounter.edit(); Counter = LaunchCounter.getInt("launch",0); RatingButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (Rate == 0) { popupForEmptyRating(); } else { if (Counter == 0) { Intent intent = new Intent(RatingActivity.this, DashboardActivity.class); startActivity(intent); Counter = 0; } else if (Counter > 0) { // RequestBody pointRequestBody = RequestBody.create(MediaType.parse("text/plain"), String.valueOf(Rate).trim()); // RequestBody offererRequestBody = RequestBody.create(MediaType.parse("text/plain"), projectOwnerUsername.getString("creatorUsername", "").trim()); // RequestBody projectIndexRequestBody = RequestBody.create(MediaType.parse("text/plain"), projectIndex.getString("projectIndex", "").trim()); // // Client client = ServiceGenerator.createService(Client.class); // // Call<AddProjectResponse> call = client.rate( // token, // pointRequestBody, // offererRequestBody, // projectIndexRequestBody // ); // // call.enqueue(new Callback<AddProjectResponse>() { // @Override // public void onResponse(Call<AddProjectResponse> call, retrofit2.Response<AddProjectResponse> response) { // Log.e("response code", String.valueOf(response.code())); // if (response.isSuccessful()){ // popupForSuccessfullRating(); // } // } // // @Override // public void onFailure(Call<AddProjectResponse> call, Throwable t) { // Log.e("error", t.getMessage()); // } // }); StringRequest postRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { // response Log.e("Response", response); popupForSuccessfullRating(); Counter = 0; LaunchCounter.edit().putInt("launch", Counter).apply(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // error Log.e("Error.Response", error.toString()); } } ) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); params.put("point", Rate + ""); params.put("offerer", projectOwnerUsername.getString("creatorUsername", "")); params.put("projectIndex", projectIndex.getString("projectIndex", "")); return params; } @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("token", token); return headers; } }; rate(postRequest); } } }}); } public void popupForCheckInternet() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); NetworkInfo mobileInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if ((wifiInfo != null && wifiInfo.isConnected()) || (mobileInfo != null && mobileInfo.isConnected())){ }else{ pDialog1 = new PrettyDialog(this); pDialog1.setCancelable(false); pDialog1 .setTitle("خطا!") .setMessage("لطفا اتصال به اینترنت را برقرار نمایید") .setIcon( R.drawable.pdlg_icon_close, // icon resource R.color.pdlg_color_red, null) .addButton( "تلاش مجدد", R.color.pdlg_color_white, R.color.pdlg_color_red, new PrettyDialogCallback() { @Override public void onClick() { popupForCheckInternet(); pDialog1.dismiss(); } } ) .show(); } } public void popupForSuccessfullRating(){ pDialog2 = new PrettyDialog(this); pDialog2.setCancelable(false); pDialog2 .setTitle("تبریک!") .setMessage("ثبت امتیاز با موفقیت انجام شد") .setIcon( R.drawable.pdlg_icon_success, // icon resource R.color.pdlg_color_green, null) .addButton( "باشه", R.color.pdlg_color_white, R.color.pdlg_color_green, new PrettyDialogCallback() { @Override public void onClick() { pDialog2.dismiss(); Intent intent = new Intent(RatingActivity.this, DashboardActivity.class); startActivity(intent); } } ) .show(); } public void popupForEmptyRating(){ pDialog3 = new PrettyDialog(this); pDialog3.setCancelable(false); pDialog3 .setTitle("خطا!") .setMessage("لطفا امتیاز مورد نظر را ثبت نمایید") .setIcon( R.drawable.pdlg_icon_close, // icon resource R.color.pdlg_color_red, null) .addButton( "باشه", R.color.pdlg_color_white, R.color.pdlg_color_red, new PrettyDialogCallback() { @Override public void onClick() { pDialog3.dismiss(); } } ) .show(); } public void rate(StringRequest postRequest){ Singleton.getInstance(this).addToRequestqueue(postRequest); } } <file_sep>package group.tamasha.rockaar; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.Typeface; import android.os.Handler; import android.support.constraint.ConstraintLayout; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.animation.TranslateAnimation; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import com.aigestudio.wheelpicker.WheelPicker; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.wang.avi.AVLoadingIndicatorView; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import libs.mjn.prettydialog.PrettyDialog; import libs.mjn.prettydialog.PrettyDialogCallback; import uk.co.chrisjenx.calligraphy.CalligraphyConfig; import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper; public class RegisterActivity extends AppCompatActivity { TranslateAnimation slideup,slidedown; LinearLayout wheellinear, buttonlinear; TextView Expertise_Text, expertise; Button Expertise_Button, Register_Button; WheelPicker Expertise; ArrayList Expertises; String Expertise_String, token, MailValid, MobileValid; RequestQueue queue; String url = "https://raakar.ir/register", url_login = "https://raakar.ir/login"; EditText Username , Password , Email , Mellicode , Phonenumber , Name; SharedPreferences UserName, PassWord, Token, ExpertisePref; AVLoadingIndicatorView av; ConstraintLayout constraint; int MailV, MobileV; PrettyDialog pDialog1; PrettyDialog pDialog2; PrettyDialog pDialog3; PrettyDialog pDialog4; PrettyDialog pDialog5; PrettyDialog pDialog6; PrettyDialog pDialog7; public void setupFont() { CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() .setDefaultFontPath("fonts/IRANSansMobile.TTF") .setFontAttrId(R.attr.fontPath) .build() ); } @Override protected void attachBaseContext(Context newBase) { super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase)); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setupFont(); setContentView(R.layout.activity_register); Username = (EditText)findViewById(R.id.editun); Password = (EditText)findViewById(R.id.editpw); Email = (EditText)findViewById(R.id.editem); Name = (EditText)findViewById(R.id.editfn); Mellicode = (EditText)findViewById(R.id.editmc); Phonenumber = (EditText)findViewById(R.id.editpn); Expertise_Text = (TextView)findViewById(R.id.editex); buttonlinear = (LinearLayout)findViewById(R.id.wheelbutton); wheellinear = (LinearLayout)findViewById(R.id.wheelpicker); Register_Button = (Button)findViewById(R.id.regbutton); Expertise_Button = (Button)findViewById(R.id.regexbutton); Expertise = (WheelPicker)findViewById(R.id.main_wheel_center); av = (AVLoadingIndicatorView)findViewById(R.id.avi); expertise = (TextView)findViewById(R.id.editex); constraint = (ConstraintLayout)findViewById(R.id.constraint); expertise.requestFocus(); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(expertise, InputMethodManager.SHOW_IMPLICIT); Expertise_Text.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showSoftKeyboard(v); } }); slideup = new TranslateAnimation(0,0,400,0); slidedown = new TranslateAnimation(0,0,0,800); slideup.setDuration(400); slideup.setFillAfter(true); slidedown.setDuration(600); slidedown.setFillAfter(true); Expertises = new ArrayList<>(); Expertises.add("--- کارفرما ---"); Expertises.add("برنامه نویسی"); Expertises.add("طراحی"); Expertises.add("ترجمه و محتوا"); Expertises.add("تحقیقات"); Expertises.add("تجارت و حسابداری"); for (int i=0; i<6; i++) { Expertises.add(i+1); } Expertise_Text.setOnClickListener(new View.OnClickListener(){ public void onClick(View view) { // rootView.startAnimation(slideup2); buttonlinear.setVisibility(View.VISIBLE); wheellinear.setVisibility(View.VISIBLE); Register_Button.setVisibility(View.GONE); Register_Button.setAlpha(0); buttonlinear.startAnimation(slideup); wheellinear.startAnimation(slideup); Expertises = new ArrayList<>(); Expertises.add("--- کارفرما ---"); Expertises.add("برنامه نویسی"); Expertises.add("طراحی"); Expertises.add("ترجمه و محتوا"); Expertises.add("تحقیقات"); Expertises.add("تجارت و حسابداری"); if (Expertise.getCurrentItemPosition() == 0 ) { Expertise_String = "--- کارفرما ---"; }else if (Expertise.getCurrentItemPosition() == 1) { Expertise_String = "برنامه نویسی"; }else if (Expertise.getCurrentItemPosition() == 2) { Expertise_String = "طراحی"; }else if (Expertise.getCurrentItemPosition() == 3) { Expertise_String = "ترجمه و محتوا"; }else if (Expertise.getCurrentItemPosition() == 4) { Expertise_String = "تحقیقات"; }else if (Expertise.getCurrentItemPosition() == 5) { Expertise_String = "تجارت و حسابداری"; } Typeface IRANSansFaNum = Typeface.createFromAsset(getAssets(), "fonts/IRANSansMobile.TTF"); Expertise.setData(Expertises); Expertise.setTypeface(IRANSansFaNum); } }); Expertise_Button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Register_Button.setVisibility(View.VISIBLE); buttonlinear.startAnimation(slidedown); wheellinear.startAnimation(slidedown); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { buttonlinear.setVisibility(View.GONE); wheellinear.setVisibility(View.GONE);} } , 550); final Handler handler1 = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { Register_Button.setAlpha(0.5F); Register_Button.setAlpha(1F);} } , 300); Expertises.add("--- کارفرما ---"); Expertises.add("برنامه نویسی"); Expertises.add("طراحی"); Expertises.add("ترجمه و محتوا"); Expertises.add("تحقیقات"); Expertises.add("تجارت و حسابداری"); if (Expertise.getCurrentItemPosition() == 0 ) { Expertise_String = "--- کارفرما ---"; }else if (Expertise.getCurrentItemPosition() == 1) { Expertise_String = "برنامه نویسی"; }else if (Expertise.getCurrentItemPosition() == 2) { Expertise_String = "طراحی"; }else if (Expertise.getCurrentItemPosition() == 3) { Expertise_String = "ترجمه و محتوا"; }else if (Expertise.getCurrentItemPosition() == 4) { Expertise_String = "تحقیقات"; }else if (Expertise.getCurrentItemPosition() == 5) { Expertise_String = "تجارت و حسابداری"; } Typeface IRANSansFaNum = Typeface.createFromAsset(getAssets(), "fonts/IRANSansMobile.TTF"); Expertise.setData(Expertises); Expertise.setTypeface(IRANSansFaNum); Expertise_Text.setText( Expertise_String ); Expertise_Text.setTextColor(Color.parseColor("#222222")); } }); queue = Volley.newRequestQueue(this); Register_Button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { av.setVisibility(View.VISIBLE); constraint.setAlpha(0.5f); startAnim(); if (Username.getText().toString().equals("") || Password.getText().toString().equals("") || Email.getText().toString().equals("") || Name.getText().toString().equals("") || Mellicode.getText().toString().equals("") || Phonenumber.getText().toString().equals("")){ stopAnim(); constraint.setAlpha(1f); popupForErrorEmptyField(); }else { MailValid = Email.getText().toString(); MobileValid = Phonenumber.getText().toString(); if (isValidMail(MailValid)) { MailV = 1; } else { MailV = 0; } if (isValidMobile(MobileValid)) { MobileV = 1; } else { MobileV = 0; } if (MailV == 0 && MobileV == 0) { stopAnim(); constraint.setAlpha(1f); popupForNotValidBoth(); } if (MailV == 0 && MobileV == 1) { stopAnim(); constraint.setAlpha(1f); popupForNotValidMail(); } if (MailV == 1 && MobileV == 0) { stopAnim(); constraint.setAlpha(1f); popupForNotValidMobile(); } if (MailV == 1 && MobileV == 1) { popUpForAcceptRegister(); } } } }); } @Override public boolean onTouchEvent(MotionEvent event) { InputMethodManager imm = (InputMethodManager)getSystemService(Context. INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); return true; } public void popupForSuccessfullRegister(){ // new AwesomeSuccessDialog(this) // .setTitle("تبریک!") // .setMessage("ثبت نام شما با موفقیت انجام شد") // .setPositiveButtonText(getString(R.string.dialog_ok_button)) // .setPositiveButtonClick(new Closure() { // @Override // public void exec() { // Intent intent = new Intent(RegisterActivity.this, DashboardActivity.class); // startActivity(intent); // StringRequest postRequest = new StringRequest(Request.Method.POST, url_login, // new Response.Listener<String>() // { // @Override // public void onResponse(String response) { // // response // Log.d("Response", response); // UserName = getSharedPreferences("user", MODE_PRIVATE); // SharedPreferences.Editor userEditor = UserName.edit(); // userEditor.putString("user", Username.getText().toString()); // userEditor.commit(); // // PassWord = getSharedPreferences("pass", MODE_PRIVATE); // SharedPreferences.Editor passEditor = PassWord.edit(); // passEditor.putString("pass", Password.getText().toString()); // passEditor.commit(); // // try { // JSONObject jsonObject = new JSONObject(response); // if (jsonObject.getString("success").equals("true")) { // // token = jsonObject.getString("token"); // Log.d("Token : ", token); // // Token = getSharedPreferences( "token" , MODE_PRIVATE ); // SharedPreferences.Editor editor = Token.edit(); // editor.putString("token", token); // editor.apply(); // } // } // catch (JSONException e) { // } // } // }, // new Response.ErrorListener() // { // @Override // public void onErrorResponse(VolleyError error) { // // error // Log.d("Error.Response", "Error"); // } // } // ) { // @Override // protected Map<String, String> getParams() // { // Map<String, String> params = new HashMap<String, String>(); // params.put("username", Username.getText().toString()); // params.put("password", <PASSWORD>.getText().toString()); // // return params; // } // }; // register(postRequest); // } // }) // .show(); pDialog1 = new PrettyDialog(this); pDialog1.setCancelable(false); pDialog1 .setTitle("تبریک!") .setMessage("ثبت نام شما با موفقیت انجام شد") .setIcon( R.drawable.pdlg_icon_success, // icon resource R.color.pdlg_color_green, null) .addButton( "باشه", R.color.pdlg_color_white, R.color.pdlg_color_green, new PrettyDialogCallback() { @Override public void onClick() { pDialog1.dismiss(); Intent intent = new Intent(RegisterActivity.this, DashboardActivity.class); startActivity(intent); StringRequest postRequest = new StringRequest(Request.Method.POST, url_login, new Response.Listener<String>() { @Override public void onResponse(String response) { // response Log.d("Response", response); UserName = getSharedPreferences("user", MODE_PRIVATE); SharedPreferences.Editor userEditor = UserName.edit(); userEditor.putString("user", Username.getText().toString()); userEditor.commit(); PassWord = getSharedPreferences("pass", MODE_PRIVATE); SharedPreferences.Editor passEditor = PassWord.edit(); passEditor.putString("pass", Password.getText().toString()); passEditor.commit(); try { JSONObject jsonObject = new JSONObject(response); if (jsonObject.getString("success").equals("true")) { token = jsonObject.getString("token"); Log.d("Token : ", token); Token = getSharedPreferences( "token" , MODE_PRIVATE ); SharedPreferences.Editor editor = Token.edit(); editor.putString("token", token); editor.apply(); } } catch (JSONException e) { } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // error Log.d("Error.Response", "Error"); } } ) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); params.put("username", Username.getText().toString()); params.put("password", <PASSWORD>.getText().toString()); return params; } }; register(postRequest); } } ) .show(); } public void popupForUsernameExist(){ // new AwesomeWarningDialog(this) // .setTitle("خطا!") // .setMessage("نام کاربری که وارد کرده اید قبلا استفاده شده است") // .setColoredCircle(R.color.dialogErrorBackgroundColor) // .setDialogIconAndColor(R.drawable.ic_dialog_info ,R.color.white) // .setButtonBackgroundColor(R.color.dialogErrorBackgroundColor) // .setButtonText(getString(R.string.dialog_ok_button)) // .setButtonTextColor(R.color.white) // .setWarningButtonClick(new Closure() { // @Override // public void exec() { // // click // } // }) // .show(); pDialog2 = new PrettyDialog(this); pDialog2.setCancelable(false); pDialog2 .setTitle("خطا!") .setMessage("نام کاربری که وارد کرده اید قبلا استفاده شده است") .setIcon( R.drawable.pdlg_icon_info, // icon resource R.color.pdlg_color_red, null) .addButton( "باشه", R.color.pdlg_color_white, R.color.pdlg_color_red, new PrettyDialogCallback() { @Override public void onClick() { pDialog2.dismiss(); } } ) .show(); } public void popupForErrorEmptyField(){ // new AwesomeNoticeDialog(this) // .setTitle("خطا!") // .setMessage("لطفا همه فیلد ها را پر کنید") // .setColoredCircle(R.color.dialogErrorBackgroundColor) // .setDialogIconAndColor(R.drawable.ic_dialog_info, R.color.white) // .setCancelable(true) // .setButtonText(getString(R.string.dialog_ok_button)) // .setButtonBackgroundColor(R.color.dialogErrorBackgroundColor) // .setButtonText(getString(R.string.dialog_ok_button)) // .setNoticeButtonClick(new Closure() { // @Override // public void exec() { // // click // } // }) // .show(); pDialog3 = new PrettyDialog(this); pDialog3.setCancelable(false); pDialog3 .setTitle("خطا!") .setMessage("لطفا همه فیلد ها را پر کنید") .setIcon( R.drawable.pdlg_icon_info, // icon resource R.color.pdlg_color_red, null) .addButton( "باشه", R.color.pdlg_color_white, R.color.pdlg_color_red, new PrettyDialogCallback() { @Override public void onClick() { pDialog3.dismiss(); } } ) .show(); } public void register(StringRequest postRequest){ Singleton.getInstance(this).addToRequestqueue(postRequest); } public void startAnim(){ av.smoothToShow(); // or avi.smoothToShow(); } public void stopAnim(){ av.smoothToHide(); // or avi.smoothToHide(); } public void showSoftKeyboard(View view) { if (view.requestFocus()) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT); } } private boolean isValidMail(String email) { boolean check; Pattern p; Matcher m; String EMAIL_STRING = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; p = Pattern.compile(EMAIL_STRING); m = p.matcher(email); check = m.matches(); return check; } private boolean isValidMobile(String phone) { boolean check; if(!Pattern.matches("[a-zA-Z]+", phone)) { if(phone.length() < 6 || phone.length() > 13) { // if(phone.length() != 10) { check = false; } else { check = true; } } else { check=false; } return check; } public void popupForNotValidMail(){ // new AwesomeNoticeDialog(this) // .setTitle("خطا!") // .setMessage("ایمیل وارد شده معتبر نیست") // .setColoredCircle(R.color.dialogErrorBackgroundColor) // .setDialogIconAndColor(R.drawable.ic_dialog_info, R.color.white) // .setCancelable(true) // .setButtonText(getString(R.string.dialog_ok_button)) // .setButtonBackgroundColor(R.color.dialogErrorBackgroundColor) // .setButtonText(getString(R.string.dialog_ok_button)) // .setNoticeButtonClick(new Closure() { // @Override // public void exec() { // // click // } // }) // .show(); pDialog4 = new PrettyDialog(this); pDialog4.setCancelable(false); pDialog4 .setTitle("خطا!") .setMessage("ایمیل وارد شده معتبر نیست") .setIcon( R.drawable.pdlg_icon_info, // icon resource R.color.pdlg_color_red, null) .addButton( "باشه", R.color.pdlg_color_white, R.color.pdlg_color_red, new PrettyDialogCallback() { @Override public void onClick() { pDialog4.dismiss(); } } ) .show(); } public void popupForNotValidMobile(){ // new AwesomeNoticeDialog(this) // .setTitle("خطا!") // .setMessage("شماره همراه وارد شده معتبر نیست") // .setColoredCircle(R.color.dialogErrorBackgroundColor) // .setDialogIconAndColor(R.drawable.ic_dialog_info, R.color.white) // .setCancelable(true) // .setButtonText(getString(R.string.dialog_ok_button)) // .setButtonBackgroundColor(R.color.dialogErrorBackgroundColor) // .setButtonText(getString(R.string.dialog_ok_button)) // .setNoticeButtonClick(new Closure() { // @Override // public void exec() { // // click // } // }) // .show(); pDialog5 = new PrettyDialog(this); pDialog5.setCancelable(false); pDialog5 .setTitle("خطا!") .setMessage("شماره همراه وارد شده معتبر نیست") .setIcon( R.drawable.pdlg_icon_info, // icon resource R.color.pdlg_color_red, null) .addButton( "باشه", R.color.pdlg_color_white, R.color.pdlg_color_red, new PrettyDialogCallback() { @Override public void onClick() { pDialog5.dismiss(); } } ) .show(); } public void popupForNotValidBoth(){ // new AwesomeNoticeDialog(this) // .setTitle("خطا!") // .setMessage("ایمیل و شماره همراه وارد شده معتبر نیست") // .setColoredCircle(R.color.dialogErrorBackgroundColor) // .setDialogIconAndColor(R.drawable.ic_dialog_info, R.color.white) // .setCancelable(true) // .setButtonText(getString(R.string.dialog_ok_button)) // .setButtonBackgroundColor(R.color.dialogErrorBackgroundColor) // .setButtonText(getString(R.string.dialog_ok_button)) // .setNoticeButtonClick(new Closure() { // @Override // public void exec() { // // click // } // }) // .show(); pDialog6 = new PrettyDialog(this); pDialog6.setCancelable(false); pDialog6 .setTitle("خطا!") .setMessage("ایمیل و شماره همراه وارد شده معتبر نیست") .setIcon( R.drawable.pdlg_icon_info, // icon resource R.color.pdlg_color_red, null) .addButton( "باشه", R.color.pdlg_color_white, R.color.pdlg_color_red, new PrettyDialogCallback() { @Override public void onClick() { pDialog6.dismiss(); } } ) .show(); } public void popUpForAcceptRegister(){ pDialog7 = new PrettyDialog(this); pDialog7.setCancelable(false); pDialog7 .setTitle("توجه!") .setMessage("راکار متعهد میشود که فضای امنی برای کاربران خود فراهم کند و در صورت نا امن شدن پلتفرم و یا احتمال خطر آن مسوولیت آن را بر عهده بگیرد. \n" + " راکار این حق را دارد که پروژه ای را لغو و یا حذف کند. همچنین حق تایید پروژه ها نیز بر عهده برنامه راکار است.\n" + "کارفرما متعهد میشود که با اشتراک گذاری پروژه 10% از مبلغ کل قرار داد را به عنوان پیش پرداخت در نظر بگیرد و در صورت لغو آن تمام پول پیش پرداخت به او باز گردد.") .setIcon( R.drawable.pdlg_icon_info, // icon resource R.color.RakaarColor, null) .addButton( "شرایط را می پذیرم", R.color.pdlg_color_white, R.color.RakaarColor, new PrettyDialogCallback() { @Override public void onClick() { pDialog7.dismiss(); StringRequest postRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { // response Log.d("Response", response); popupForSuccessfullRegister(); stopAnim(); constraint.setAlpha(1f); UserName = getSharedPreferences("user", MODE_PRIVATE); SharedPreferences.Editor userEditor = UserName.edit(); userEditor.putString("user", Username.getText().toString()); userEditor.commit(); PassWord = getSharedPreferences("pass", MODE_PRIVATE); SharedPreferences.Editor passEditor = PassWord.edit(); passEditor.putString("pass", Password.getText().toString()); passEditor.commit(); try { JSONObject jsonObject = new JSONObject(response); if (jsonObject.getString("success").equals("true")) { token = jsonObject.getString("token"); Log.d("Token : ", token); Token = getSharedPreferences( "token" , MODE_PRIVATE ); SharedPreferences.Editor editor = Token.edit(); editor.putString("token", token); editor.apply(); } } catch (JSONException e) { } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // error Log.d("Error.Response", "Error"); stopAnim(); constraint.setAlpha(1f); switch(error.networkResponse.statusCode){ case 303: popupForUsernameExist(); break; } } } ) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); params.put("username", Username.getText().toString()); params.put("password", Password.getText().toString()); params.put("email", Email.getText().toString()); params.put("name", Name.getText().toString()); params.put("mellicode", Mellicode.getText().toString()); params.put("phonenumber", Phonenumber.getText().toString()); params.put("expertise", expertise.getText().toString()); //<NAME> :-P params.put("workscount", "0"); return params; } }; register(postRequest); } } ) .addButton( "نه", R.color.pdlg_color_white, R.color.RakaarColor, new PrettyDialogCallback() { @Override public void onClick() { pDialog7.dismiss(); stopAnim(); constraint.setAlpha(1f); } } ) .show(); } } <file_sep>package group.tamasha.rockaar; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.text.InputType; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.Toast; import com.android.vending.billing.IInAppBillingService; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import java.util.HashMap; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import group.tamasha.rockaar.util.IabHelper; import group.tamasha.rockaar.util.IabResult; import group.tamasha.rockaar.util.Inventory; import group.tamasha.rockaar.util.Purchase; import libs.mjn.prettydialog.PrettyDialog; import libs.mjn.prettydialog.PrettyDialogCallback; public class AccountFragment extends Fragment { public AccountFragment() { // Required empty public constructor } // Debug tag, for logging static final String TAG = "______________________"; // SKUs for our products: the premium upgrade (non-consumable) static final String SKU_BRONZE = "sku_bronze"; static final String SKU_SILVER = "sku_silver"; static final String SKU_GOLD = "sku_gold"; // Does the user have the premium upgrade? boolean mIsPremium1 = true; // (arbitrary) request code for the purchase flow static final int RC_REQUEST = 3; IabHelper mHelper; Button Gold, Silver, Bronze; SharedPreferences Token; String url_raiseOffer = "https://raakar.ir/simpleRaiseOffer", token; PrettyDialog pDialog; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_account, container, false); popupForCheckInternet(); Gold = (Button)view.findViewById(R.id.goldbutton); Silver = (Button)view.findViewById(R.id.silverbutton); Bronze = (Button)view.findViewById(R.id.bronzebutton); Token = getActivity().getSharedPreferences("token", Context.MODE_PRIVATE); token = Token.getString("token", null); String base64EncodedPublicKey = "<KEY>; mHelper = new IabHelper(getContext(), base64EncodedPublicKey); Log.e(TAG, "Starting setup."); mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { public void onIabSetupFinished(IabResult result) { Log.e(TAG, "Setup finished."); if (!result.isSuccess()) { // Oh noes, there was a problem. Log.e(TAG, "Problem setting up In-app Billing: " + result); } // Hooray, IAB is fully set up! mHelper.queryInventoryAsync(mGotInventoryListener); } }); Gold.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mHelper != null) mHelper.flagEndAsync(); mHelper.launchPurchaseFlow(getActivity(), SKU_GOLD, RC_REQUEST, mPurchaseFinishedListener, "payload-string"); }}); Silver.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mHelper != null) mHelper.flagEndAsync(); mHelper.launchPurchaseFlow(getActivity(), SKU_SILVER, RC_REQUEST, mPurchaseFinishedListener, "payload-string"); }}); Bronze.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mHelper != null) mHelper.flagEndAsync(); mHelper.launchPurchaseFlow(getActivity(), SKU_BRONZE, RC_REQUEST, mPurchaseFinishedListener, "payload-string"); }}); return view; } public void popupForCheckInternet() { ConnectivityManager connectivityManager = (ConnectivityManager) getContext().getSystemService(getActivity().CONNECTIVITY_SERVICE); NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); NetworkInfo mobileInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if ((wifiInfo != null && wifiInfo.isConnected()) || (mobileInfo != null && mobileInfo.isConnected())){ }else{ pDialog = new PrettyDialog(getActivity()); pDialog.setCancelable(false); pDialog .setTitle("خطا!") .setMessage("لطفا اتصال به اینترنت را برقرار نمایید") .setIcon( R.drawable.pdlg_icon_close, // icon resource R.color.pdlg_color_red, null) .addButton( "تلاش مجدد", R.color.pdlg_color_white, R.color.pdlg_color_red, new PrettyDialogCallback() { @Override public void onClick() { popupForCheckInternet(); pDialog.dismiss(); } } ) .show(); } } IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() { public void onIabPurchaseFinished(IabResult result, Purchase purchase) { Log.e("purche", "_________________________now here in purche"); if (result.isFailure()) { Log.e("result", "___________________Error purchasing: " + result); return; } else if (purchase.getSku().equals(SKU_GOLD)) { mHelper.queryInventoryAsync(mGotInventoryListener); } else if (purchase.getSku().equals(SKU_SILVER)){ mHelper.queryInventoryAsync(mGotInventoryListener); } else if (purchase.getSku().equals(SKU_BRONZE)){ mHelper.queryInventoryAsync(mGotInventoryListener); } } }; IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() { public void onQueryInventoryFinished(IabResult result, Inventory inventory) { Log.e(TAG, "Query inventory finished."); if (result.isFailure()) { Log.e(TAG, "Failed to query inventory: " + result); return; } else { Log.e(TAG, "Query inventory was successful."); // does the user have the premium upgrade? if (inventory.hasPurchase(SKU_GOLD)){ // mHelper.launchPurchaseFlow(getActivity(), SKU_FREE, RC_REQUEST, mPurchaseFinishedListener, "payload-string"); mHelper.consumeAsync(inventory.getPurchase(SKU_GOLD), mConsumeFinishedListener); } else if (inventory.hasPurchase(SKU_SILVER)){ mHelper.consumeAsync(inventory.getPurchase(SKU_SILVER), mConsumeFinishedListener); } else if (inventory.hasPurchase(SKU_BRONZE)){ mHelper.consumeAsync(inventory.getPurchase(SKU_BRONZE), mConsumeFinishedListener); } // update UI accordingly Log.e(TAG, "User is " + (mIsPremium1 ? "PREMIUM" : "NOT PREMIUM")); } Log.e(TAG, "Initial inventory query finished; enabling main UI."); } }; // @Override // public void onActivityResult(int requestCode, int resultCode, Intent data) { // super.onActivityResult(requestCode, resultCode, data); // // Log.d(TAG, "onActivityResult(" + requestCode + "," + resultCode + "," + data); // // // Pass on the activity result to the helper for handling // if (!mHelper.handleActivityResult(requestCode, resultCode, data)) { // super.onActivityResult(requestCode, resultCode, data); // } else { // Log.d(TAG, "onActivityResult handled by IABUtil."); // } // } IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() { public void onConsumeFinished(Purchase purchase, IabResult result) { // provision the in-app purchase to the user // (for example, credit 50 gold coins to player's character) Log.e(TAG, "request for consuming & checking result "); if (result.isSuccess()) { if (purchase.getSku().equals(SKU_BRONZE)){ StringRequest postRequest = new StringRequest(Request.Method.POST, url_raiseOffer, new Response.Listener<String>() { @Override public void onResponse(String response) { // response Log.e("Response", response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // error Log.e("Error.Response", "Error"); } } ) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); params.put("membership", "1"); return params; } @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/x-www-form-urlencoded"); headers.put("token", token); return headers; } }; Singleton.getInstance(getActivity()).addToRequestqueue(postRequest); } else if (purchase.getSku().equals(SKU_SILVER)){ StringRequest postRequest = new StringRequest(Request.Method.POST, url_raiseOffer, new Response.Listener<String>() { @Override public void onResponse(String response) { // response Log.e("Response", response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // error Log.e("Error.Response", "Error"); } } ) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); params.put("membership", "2"); return params; } @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/x-www-form-urlencoded"); headers.put("token", token); return headers; } }; Singleton.getInstance(getActivity()).addToRequestqueue(postRequest); } else if (purchase.getSku().equals(SKU_GOLD)){ StringRequest postRequest = new StringRequest(Request.Method.POST, url_raiseOffer, new Response.Listener<String>() { @Override public void onResponse(String response) { // response Log.e("Response", response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // error Log.e("Error.Response", "Error"); } } ) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); params.put("membership", "3"); return params; } @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/x-www-form-urlencoded"); headers.put("token", token); return headers; } }; Singleton.getInstance(getActivity()).addToRequestqueue(postRequest); } } else { Log.e("error in consume", result.getMessage() + " result string:" + result.toString()); } } }; @Override public void onDestroy() { super.onDestroy(); if (mHelper != null) mHelper.dispose(); mHelper = null; } } <file_sep>package group.tamasha.rockaar; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; import libs.mjn.prettydialog.PrettyDialog; import libs.mjn.prettydialog.PrettyDialogCallback; public class AddShabaFragment extends Fragment { SharedPreferences Cardnumber, Token; Button addshaba_acceptcard_button; EditText addshaba_cardnumber_edittext; String token; CreditCardFormatTextWatcher tv; PrettyDialog pDialog1; PrettyDialog pDialog2; PrettyDialog pDialog3, pDialog4; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_add_shaba, container, false); addshaba_cardnumber_edittext = (EditText)view.findViewById(R.id.addshaba_cardnumber_edittext); addshaba_acceptcard_button = (Button)view.findViewById(R.id.addshaba_acceptcard_button); Token = getActivity().getSharedPreferences("token", Context.MODE_PRIVATE); token = Token.getString("token", null); tv = new CreditCardFormatTextWatcher(addshaba_cardnumber_edittext); addshaba_cardnumber_edittext.addTextChangedListener(tv); addshaba_acceptcard_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (addshaba_cardnumber_edittext.length() == 0){ popupForEmptyEditText(); }else { if (addshaba_cardnumber_edittext.length() != 16){ popupForLengthOfEditText(); }else { StringRequest postRequest = new StringRequest(Request.Method.POST, "https://raakar.ir/addCardNumber", new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d("Response", response); Cardnumber = getActivity().getSharedPreferences("cardnumber", Context.MODE_PRIVATE); SharedPreferences.Editor CardnumberEditor = Cardnumber.edit(); CardnumberEditor.putString("cardnumber", addshaba_cardnumber_edittext.getText().toString()); CardnumberEditor.commit(); popupForSuccessAddCardNumber(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d("Error.Response", "Error"); } } ) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); params.put("cardNumber", addshaba_cardnumber_edittext.getText().toString()); return params; } public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); //headers.put("Content-Type", "application/json"); headers.put("token", token); return headers; } }; Singleton.getInstance(getActivity()).addToRequestqueue(postRequest); } } } }); return view; } public void popupForLengthOfEditText(){ pDialog1 = new PrettyDialog(getActivity()); pDialog1.setCancelable(false); pDialog1 .setTitle("توجه!") .setMessage("شماره کارت باید 16 رقمی باشد") .setIcon( R.drawable.pdlg_icon_close, // icon resource R.color.pdlg_color_red, null) .addButton( "باشه", R.color.pdlg_color_white, R.color.pdlg_color_red, new PrettyDialogCallback() { @Override public void onClick() { pDialog1.dismiss(); } } ) .show(); } public void popupForSuccessAddCardNumber(){ pDialog2 = new PrettyDialog(getActivity()); pDialog2.setCancelable(false); pDialog2 .setTitle("تبریک!") .setMessage("شماره کارت شما با موفقیت ثبت شد") .setIcon( R.drawable.pdlg_icon_success, // icon resource R.color.pdlg_color_green, null) .addButton( "باشه", R.color.pdlg_color_white, R.color.pdlg_color_green, new PrettyDialogCallback() { @Override public void onClick() { pDialog2.dismiss(); CreditFragment creditFragment = new CreditFragment(); FragmentManager manager = getActivity().getSupportFragmentManager(); manager.beginTransaction().replace(R.id.mycontainer, creditFragment).commit(); } } ) .show(); } public void popupForCheckInternet() { ConnectivityManager connectivityManager = (ConnectivityManager) getContext().getSystemService(getActivity().CONNECTIVITY_SERVICE); NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); NetworkInfo mobileInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if ((wifiInfo != null && wifiInfo.isConnected()) || (mobileInfo != null && mobileInfo.isConnected())){ }else{ pDialog4 = new PrettyDialog(getActivity()); pDialog4.setCancelable(false); pDialog4 .setTitle("خطا!") .setMessage("لطفا اتصال به اینترنت را برقرار نمایید") .setIcon( R.drawable.pdlg_icon_close, // icon resource R.color.pdlg_color_red, null) .addButton( "تلاش مجدد", R.color.pdlg_color_white, R.color.pdlg_color_red, new PrettyDialogCallback() { @Override public void onClick() { popupForCheckInternet(); pDialog4.dismiss(); } } ) .show(); } } public void popupForEmptyEditText(){ pDialog3 = new PrettyDialog(getActivity()); pDialog3.setCancelable(false); pDialog3 .setTitle("توجه!") .setMessage("شماره کارت را وارد کنید") .setIcon( R.drawable.pdlg_icon_close, // icon resource R.color.pdlg_color_red, null) .addButton( "باشه", R.color.pdlg_color_white, R.color.pdlg_color_red, new PrettyDialogCallback() { @Override public void onClick() { pDialog3.dismiss(); } } ) .show(); } } <file_sep>package group.tamasha.rockaar; public class MyWorksAdapterItems { public String delete; public String mname; public String mdetails; public String amount_of_bids; public String date; MyWorksAdapterItems(String delete, String name, String details, String amount_of_bids, String date) { this.delete = delete; this.mname = name; this.mdetails = details; this.amount_of_bids = amount_of_bids; this.date = date; } } <file_sep>package group.tamasha.rockaar; public class MyBidsAdapterItems { public int mconfirm; public int mdecline; public String mname; public String mdescribtion; public String mdate; public String mbidprice; public String mdifprice; public String mbidtime; public String mdiftime; MyBidsAdapterItems(int mconfirm, int mdecline, String mname, String mdescribtion, String mdate, String mbidprice, String mdifprice, String mbidtime, String mdiftime) { this.mconfirm = mconfirm; this.mdecline = mdecline; this.mname = mname; this.mdescribtion = mdescribtion; this.mdate = mdate; this.mbidprice = mbidprice; this.mdifprice = mdifprice; this.mbidtime = mbidtime; this.mdiftime = mdiftime; } } <file_sep>package group.tamasha.rockaar; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Typeface; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.JsonObjectRequest; import com.wang.avi.AVLoadingIndicatorView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import co.ceryle.radiorealbutton.RadioRealButton; import co.ceryle.radiorealbutton.RadioRealButtonGroup; import libs.mjn.prettydialog.PrettyDialog; import libs.mjn.prettydialog.PrettyDialogCallback; public class ProjectsFragment extends Fragment { PrettyDialog pDialog; PrettyDialog pDialog2; RadioRealButton myworks_btn, sentbids_btn, existprojects_btn; RadioRealButtonGroup group; ListView project_listView; SharedPreferences Token, UserName, TabPosition; SharedPreferences.Editor TabPositionEditor; TextView project_nulltext; ArrayList<MyWorksAdapterItems> mlistnewsData = new ArrayList<MyWorksAdapterItems>(); ArrayList<ProjectsAdapterItems> plistnewsData = new ArrayList<ProjectsAdapterItems>(); ArrayList<SentBidsAdapterItems> alistnewsData = new ArrayList<SentBidsAdapterItems>(); ArrayList<String> status = new ArrayList<String>(); ArrayList<String> acception = new ArrayList<String>(); int green = 1, red = 0; AVLoadingIndicatorView Projects_av; String URLgetallprojects = "https://raakar.ir/getAllProjects", URLgetmyprojects = "https://raakar.ir/getMyProjects", token; String URLgetmyoffers = "https://raakar.ir/getMyOffers", username; int TabP; public ProjectsFragment() { // Required empty public constructor } @Override public View onCreateView(final LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_projects, container, false); popupForCheckInternet(); Token = getActivity().getSharedPreferences("token", Context.MODE_PRIVATE); token = Token.getString("token", null); myworks_btn = (RadioRealButton)view.findViewById(R.id.project_myworks_btn); sentbids_btn = (RadioRealButton)view.findViewById(R.id.project_sentbids_btn); existprojects_btn = (RadioRealButton)view.findViewById(R.id.project_existprojects_btn); group = (RadioRealButtonGroup)view.findViewById(R.id.project_segment); project_listView = (ListView)view.findViewById(R.id.project_listView); Projects_av = (AVLoadingIndicatorView)view.findViewById(R.id.projects_av); project_nulltext = (TextView)view.findViewById(R.id.project_nulltext); TabPosition = getActivity().getSharedPreferences("tabposition", Context.MODE_PRIVATE); TabPositionEditor = TabPosition.edit(); TabP = TabPosition.getInt("tabposition", 2); group.setPosition(TabP); if (TabP == 2){ group.setPosition(TabP); ProjectsAdapter exsitProjectAdapter; startAnim(); final JsonArrayRequest jsonRequest = new JsonArrayRequest (Request.Method.GET, URLgetallprojects, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { Log.d("Response:", response.toString()); try { plistnewsData.clear(); if(response.length() == 0){ stopAnim(); project_listView.setVisibility(View.GONE); project_nulltext.setText("هیچ پروژه ای برای نمایش وجود ندارد!"); project_nulltext.setVisibility(View.VISIBLE); }else { project_listView.setVisibility(View.VISIBLE); project_nulltext.setVisibility(View.GONE); for (int i=0; i<response.length(); i++) { JSONObject Projects = response.getJSONObject(i); String T = Projects.getString("amount"); String Text = T.replaceAll("[^0-9]+",""); long Number = Long.parseLong(Text); DecimalFormat formatter = new DecimalFormat("#,###,###,###,###"); String yourFormattedString = formatter.format(Number); JSONArray offerArrayLength = Projects.getJSONArray("offersArray"); if (T.equals("0")){ plistnewsData.add(new ProjectsAdapterItems( Projects.getString("name") , Projects.getString("category") + "، " + Projects.getString("description") , "توافقی" , Projects.getString("deadline") + " روز" , Projects.getString("creationDate") , "تعداد پیشنهادات: " + String.valueOf(offerArrayLength.length()))); }else { plistnewsData.add(new ProjectsAdapterItems( Projects.getString("name") , Projects.getString("category") + "، " + Projects.getString("description") , yourFormattedString + " تومان" , Projects.getString("deadline") + " روز" , Projects.getString("creationDate") , String.valueOf("تعداد پیشنهادات: " + offerArrayLength.length()))); } } stopAnim(); ProjectsAdapter exsitProjectAdapter; exsitProjectAdapter = new ProjectsAdapter(plistnewsData); project_listView.setAdapter(exsitProjectAdapter); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { project_listView.setVisibility(View.GONE); project_nulltext.setText("هیچ پروژه ای برای نمایش وجود ندارد!"); project_nulltext.setVisibility(View.VISIBLE); stopAnim(); } }){ @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("token", token); return headers; }}; Singleton.getInstance(getActivity()).addToRequestqueue(jsonRequest); TabPositionEditor.putInt("tabposition", 2).apply(); exsitProjectAdapter = new ProjectsAdapter(plistnewsData); project_listView.setAdapter(exsitProjectAdapter); } if (TabP == 1) { group.setPosition(TabP); alistnewsData.clear(); startAnim(); final JsonArrayRequest offerjsonRequest = new JsonArrayRequest (Request.Method.GET, URLgetmyoffers, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { Log.d("Response:", response.toString()); try { UserName = getActivity().getSharedPreferences("user", Context.MODE_PRIVATE); username = UserName.getString("user", null); if(response.length() == 0){ stopAnim(); project_listView.setVisibility(View.GONE); project_nulltext.setText("شما پیشنهادی ارسال نکرده اید!"); project_nulltext.setVisibility(View.VISIBLE); }else { project_listView.setVisibility(View.VISIBLE); project_nulltext.setVisibility(View.GONE); for (int j = 0; j < response.length() ; j++){ JSONObject offers = response.getJSONObject(j); acception.add(offers.getString("status")); JSONArray myOffer = offers.getJSONArray("offersArray"); for (int i = 0; i < myOffer.length(); i++){ JSONObject infoOffer = myOffer.getJSONObject(i); String T = infoOffer.getString("amount"); String Text = T.replaceAll("[^0-9]+",""); long Number = Long.parseLong(Text); DecimalFormat formatter = new DecimalFormat("#,###,###,###,###"); String yourFormattedString = formatter.format(Number); if (username.equals(infoOffer.getString("creatorUsername"))){ if (infoOffer.getBoolean("status") == false){ alistnewsData.add(new SentBidsAdapterItems(red, "ویرایش", "حذف", offers.getString("name"), yourFormattedString + " تومان" + " ( " + offers.getString("deadline") + " روز" + " ) ", "وضعیت: تایید نشده", "")); }else if (infoOffer.getBoolean("status") == true){ alistnewsData.add(new SentBidsAdapterItems(green, "ویرایش", "حذف", offers.getString("name"), yourFormattedString + " تومان" + " ( " + offers.getString("deadline") + " روز" + " ) ", "وضعیت: تایید شده", infoOffer.getString("acceptionYear") + "/" + infoOffer.getString("acceptionMonth") + "/" + infoOffer.getString("acceptionDate"))); } } } } stopAnim(); SentBidsAdapter sadapter; sadapter = new SentBidsAdapter(alistnewsData); project_listView.setAdapter(sadapter); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { project_listView.setVisibility(View.GONE); project_nulltext.setText("هیچ پروژه ای برای نمایش وجود ندارد!"); project_nulltext.setVisibility(View.VISIBLE); stopAnim(); } }){ @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("token", token); return headers; } }; Singleton.getInstance(getActivity()).addToRequestqueue(offerjsonRequest); TabPositionEditor.putInt("tabposition", 1).apply(); } if (TabP == 0) { group.setPosition(TabP); startAnim(); final JsonObjectRequest mjsonRequest = new JsonObjectRequest (Request.Method.GET, URLgetmyprojects, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d("Response:", response.toString()); try { plistnewsData.clear(); alistnewsData.clear(); mlistnewsData.clear(); status.clear(); if(response.toString().equals("your project array is empty")){ stopAnim(); project_listView.setVisibility(View.GONE); project_nulltext.setText("شما پروژه ای ثبت نکرده اید!"); project_nulltext.setVisibility(View.VISIBLE); }else { stopAnim(); project_listView.setVisibility(View.VISIBLE); project_nulltext.setVisibility(View.GONE); JSONArray MyWorks = response.getJSONArray("yourProjects"); for (int i=0; i < MyWorks.length(); i++) { JSONObject Index = MyWorks.getJSONObject(i); JSONArray indexLenght = Index.getJSONArray("offersArray"); if (Index.getString("status").equals("0")){ stopAnim(); project_listView.setVisibility(View.GONE); project_nulltext.setText("شما پروژه ای ثبت نکرده اید!"); project_nulltext.setVisibility(View.VISIBLE); }else { stopAnim(); project_listView.setVisibility(View.VISIBLE); project_nulltext.setVisibility(View.GONE); status.add(Index.getString("status")); mlistnewsData.add(new MyWorksAdapterItems("حذف" , Index.getString("name") , Index.getString("description") , "تعداد پیشنهادات: " + String.valueOf(indexLenght.length()) , Index.getString("creationDate"))); } } stopAnim(); MyWorksAdapter myWorksAdapter; myWorksAdapter = new MyWorksAdapter(mlistnewsData); project_listView.setAdapter(myWorksAdapter); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { project_listView.setVisibility(View.GONE); project_nulltext.setText("شما پروژه ای ثبت نکرده اید!"); project_nulltext.setVisibility(View.VISIBLE); stopAnim(); } }){ @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("token", token); return headers; }}; Singleton.getInstance(getActivity()).addToRequestqueue(mjsonRequest); TabPosition = getActivity().getSharedPreferences("tabposition", Context.MODE_PRIVATE); TabPositionEditor = TabPosition.edit(); TabPositionEditor.putInt("tabposition", 0).apply(); } Typeface IRANSansFaNum = Typeface.createFromAsset(getActivity().getAssets(), "fonts/IRANSansMobile.TTF"); myworks_btn.setTypeface(IRANSansFaNum); sentbids_btn.setTypeface(IRANSansFaNum); existprojects_btn.setTypeface(IRANSansFaNum); group.setOnClickedButtonListener(new RadioRealButtonGroup.OnClickedButtonListener() { @Override public void onClickedButton(RadioRealButton button, int position) { switch (position){ case 0: startAnim(); final JsonObjectRequest mjsonRequest = new JsonObjectRequest (Request.Method.GET, URLgetmyprojects, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d("Response:", response.toString()); try { plistnewsData.clear(); alistnewsData.clear(); mlistnewsData.clear(); status.clear(); if(response.toString().equals("your project array is empty")){ stopAnim(); project_listView.setVisibility(View.GONE); project_nulltext.setText("شما پروژه ای ثبت نکرده اید!"); project_nulltext.setVisibility(View.VISIBLE); }else { stopAnim(); project_listView.setVisibility(View.VISIBLE); project_nulltext.setVisibility(View.GONE); JSONArray MyWorks = response.getJSONArray("yourProjects"); for (int i=0; i < MyWorks.length(); i++) { JSONObject Index = MyWorks.getJSONObject(i); JSONArray indexLenght = Index.getJSONArray("offersArray"); if (Index.getString("status").equals("0")){ stopAnim(); project_listView.setVisibility(View.GONE); project_nulltext.setText("شما پروژه ای ثبت نکرده اید!"); project_nulltext.setVisibility(View.VISIBLE); }else { stopAnim(); project_listView.setVisibility(View.VISIBLE); project_nulltext.setVisibility(View.GONE); status.add(Index.getString("status")); mlistnewsData.add(new MyWorksAdapterItems("حذف" , Index.getString("name") , Index.getString("description") , "تعداد پیشنهادات: " + String.valueOf(indexLenght.length()) , Index.getString("creationDate"))); } } stopAnim(); MyWorksAdapter myWorksAdapter; myWorksAdapter = new MyWorksAdapter(mlistnewsData); project_listView.setAdapter(myWorksAdapter); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { project_listView.setVisibility(View.GONE); project_nulltext.setText("شما پروژه ای ثبت نکرده اید!"); project_nulltext.setVisibility(View.VISIBLE); stopAnim(); } }){ @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("token", token); return headers; }}; Singleton.getInstance(getActivity()).addToRequestqueue(mjsonRequest); TabPosition = getActivity().getSharedPreferences("tabposition", Context.MODE_PRIVATE); TabPositionEditor = TabPosition.edit(); TabPositionEditor.putInt("tabposition", 0).apply(); break; case 1: alistnewsData.clear(); startAnim(); final JsonArrayRequest offerjsonRequest = new JsonArrayRequest (Request.Method.GET, URLgetmyoffers, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { Log.d("Response:", response.toString()); try { UserName = getActivity().getSharedPreferences("user", Context.MODE_PRIVATE); username = UserName.getString("user", null); if(response.length() == 0){ stopAnim(); project_listView.setVisibility(View.GONE); project_nulltext.setText("شما پیشنهادی ارسال نکرده اید!"); project_nulltext.setVisibility(View.VISIBLE); }else { project_listView.setVisibility(View.VISIBLE); project_nulltext.setVisibility(View.GONE); for (int j = 0; j < response.length() ; j++){ JSONObject offers = response.getJSONObject(j); acception.add(offers.getString("status")); JSONArray myOffer = offers.getJSONArray("offersArray"); for (int i = 0; i < myOffer.length(); i++){ JSONObject infoOffer = myOffer.getJSONObject(i); String T = infoOffer.getString("amount"); String Text = T.replaceAll("[^0-9]+",""); long Number = Long.parseLong(Text); DecimalFormat formatter = new DecimalFormat("#,###,###,###,###"); String yourFormattedString = formatter.format(Number); if (username.equals(infoOffer.getString("creatorUsername"))){ if (infoOffer.getBoolean("status") == false){ alistnewsData.add(new SentBidsAdapterItems(red, "ویرایش", "حذف", offers.getString("name"), yourFormattedString + " تومان" + " ( " + offers.getString("deadline") + " روز" + " ) ", "وضعیت: تایید نشده", "")); }else if (infoOffer.getBoolean("status") == true){ alistnewsData.add(new SentBidsAdapterItems(green, "ویرایش", "حذف", offers.getString("name"), yourFormattedString + " تومان" + " ( " + offers.getString("deadline") + " روز" + " ) ", "وضعیت: تایید شده", infoOffer.getString("acceptionYear") + "/" + infoOffer.getString("acceptionMonth") + "/" + infoOffer.getString("acceptionDate"))); } } } } stopAnim(); SentBidsAdapter sadapter; sadapter = new SentBidsAdapter(alistnewsData); project_listView.setAdapter(sadapter); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { project_listView.setVisibility(View.GONE); project_nulltext.setText("شما پیشنهادی ارسال نکرده اید!"); project_nulltext.setVisibility(View.VISIBLE); stopAnim(); } }){ @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("token", token); return headers; }}; Singleton.getInstance(getActivity()).addToRequestqueue(offerjsonRequest); TabPosition = getActivity().getSharedPreferences("tabposition", Context.MODE_PRIVATE); TabPositionEditor = TabPosition.edit(); TabPositionEditor.putInt("tabposition", 1).apply(); break; case 2: ProjectsAdapter exsitProjectAdapter; startAnim(); final JsonArrayRequest jsonRequest = new JsonArrayRequest (Request.Method.GET, URLgetallprojects, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { Log.d("Response:", response.toString()); try { plistnewsData.clear(); if(response.length() == 0){ stopAnim(); project_listView.setVisibility(View.GONE); project_nulltext.setText("هیچ پروژه ای برای نمایش وجود ندارد!"); project_nulltext.setVisibility(View.VISIBLE); }else { project_listView.setVisibility(View.VISIBLE); project_nulltext.setVisibility(View.GONE); for (int i=0; i<response.length(); i++) { JSONObject Projects = response.getJSONObject(i); String T = Projects.getString("amount"); String Text = T.replaceAll("[^0-9]+",""); long Number = Long.parseLong(Text); DecimalFormat formatter = new DecimalFormat("#,###,###,###,###"); String yourFormattedString = formatter.format(Number); JSONArray offerArrayLength = Projects.getJSONArray("offersArray"); if (T.equals("0")){ plistnewsData.add(new ProjectsAdapterItems( Projects.getString("name") , Projects.getString("category") + "، " + Projects.getString("description") , "توافقی" , Projects.getString("deadline") + " روز" , Projects.getString("creationDate") , "تعداد پیشنهادات: " + String.valueOf(offerArrayLength.length()))); }else { plistnewsData.add(new ProjectsAdapterItems( Projects.getString("name") , Projects.getString("category") + "، " + Projects.getString("description") , yourFormattedString + " تومان" , Projects.getString("deadline") + " روز" , Projects.getString("creationDate") , String.valueOf("تعداد پیشنهادات: " + offerArrayLength.length()))); } } stopAnim(); ProjectsAdapter exsitProjectAdapter; exsitProjectAdapter = new ProjectsAdapter(plistnewsData); project_listView.setAdapter(exsitProjectAdapter); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { project_listView.setVisibility(View.GONE); project_nulltext.setText("هیچ پروژه ای برای نمایش وجود ندارد!"); project_nulltext.setVisibility(View.VISIBLE); stopAnim(); } }){ @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("token", token); return headers; }}; Singleton.getInstance(getActivity()).addToRequestqueue(jsonRequest); TabPositionEditor.putInt("tabposition", 2).apply(); exsitProjectAdapter = new ProjectsAdapter(plistnewsData); project_listView.setAdapter(exsitProjectAdapter); break; } } }); Log.d("position:", "____________________________________________________" + group.getPosition()); project_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, final int position, long id) { if (group.getPosition() == 0){ if (status.get(position).equals("1")){ MyBidsFragment MyBidsFragment = new MyBidsFragment(); FragmentManager manager = getActivity().getSupportFragmentManager(); manager.beginTransaction().replace(R.id.mycontainer, MyBidsFragment).addToBackStack("Back").commit(); TextView name = (TextView)view.findViewById(R.id.myworks_name); Bundle bundle = new Bundle(); bundle.putInt("position", position); bundle.putString("name", name.getText().toString()); MyBidsFragment.setArguments(bundle); } if (status.get(position).equals("2") || status.get(position).equals("4") || status.get(position).equals("3") || status.get(position).equals("5")){ final JsonObjectRequest pjsonRequest = new JsonObjectRequest (Request.Method.GET, URLgetmyprojects, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d("Response:", response.toString()); try { String projectDate; JSONArray yourProjects = response.getJSONArray("yourProjects"); JSONObject myProject = yourProjects.getJSONObject(position); int status = myProject.getInt("status"); SharedPreferences statusSHP = getActivity().getSharedPreferences("statusMyWork", Context.MODE_PRIVATE); SharedPreferences.Editor statusSHPE = statusSHP.edit(); statusSHPE.putInt("statusMyWork", status); statusSHPE.apply(); Bundle myWorkBundle = new Bundle(); myWorkBundle.putString("name", myProject.getString("name")); myWorkBundle.putString("projectIndex", myProject.getString("projectIndex")); myWorkBundle.putString("category", myProject.getString("category")); JSONArray offer = myProject.getJSONArray("offersArray"); for (int i = 0; i < offer.length(); i++){ JSONObject acceptOffer = offer.getJSONObject(i); if (acceptOffer.getBoolean("status") == true){ myWorkBundle.putString("amount", acceptOffer.getString("amount")); myWorkBundle.putInt("deadline", acceptOffer.getInt("deadline")); myWorkBundle.putString("description", acceptOffer.getString("description")); myWorkBundle.putInt("acceptionYear", acceptOffer.getInt("acceptionYear")); myWorkBundle.putInt("acceptionMonth", acceptOffer.getInt("acceptionMonth")); myWorkBundle.putInt("acceptionDate", acceptOffer.getInt("acceptionDate")); myWorkBundle.putString("offerIndex", String.valueOf(i)); myWorkBundle.putString("creatorName", acceptOffer.getString("creatorName")); myWorkBundle.putString("creatorUsername", acceptOffer.getString("creatorUsername")); projectDate = acceptOffer.getInt("acceptionYear") + "/" + acceptOffer.getInt("acceptionMonth") + "/" + acceptOffer.getInt("acceptionDate"); myWorkBundle.putString("projectDate" , projectDate); MyWorkInfoFragment myWorkInfoFragment = new MyWorkInfoFragment(); FragmentManager manager = getActivity().getSupportFragmentManager(); manager.beginTransaction().replace(R.id.mycontainer, myWorkInfoFragment).addToBackStack("Back").commit(); myWorkInfoFragment.setArguments(myWorkBundle); } } final String finallink = myProject.getString("finalLink"); SharedPreferences finalfile = getActivity().getSharedPreferences("finalLink", Context.MODE_PRIVATE); SharedPreferences.Editor finalFileE = finalfile.edit(); finalFileE.putString("finalLink", finallink); finalFileE.apply(); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }){ @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("token", token); return headers; }}; Singleton.getInstance(getActivity()).addToRequestqueue(pjsonRequest); } }else if (group.getPosition() == 2){ final ProjectsItemsFragment ProjectsItemsFragment = new ProjectsItemsFragment(); final JsonArrayRequest pjsonRequest = new JsonArrayRequest (Request.Method.GET, URLgetallprojects, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { Log.d("Response:", response.toString()); try { JSONObject infoProject = response.getJSONObject(position); String name = infoProject.getString("name"); String amount = infoProject.getString("amount"); String deadline = infoProject.getString("deadline"); String offerNumber = infoProject.getString("offersnumber"); String description = infoProject.getString("description"); String category = infoProject.getString("category"); String projectOwnerName = infoProject.getString("projectOwnerName"); String projectIndex = infoProject.getString("projectIndex"); String projectOwnerUsername = infoProject.getString("projectOwnerUsername"); Bundle bundle = new Bundle(); bundle.putInt("position", position); bundle.putString("name", name); bundle.putString("amount", amount); bundle.putString("deadline", deadline); bundle.putString("offerNumber", offerNumber); bundle.putString("description", description); bundle.putString("category", category); bundle.putString("projectOwnerName", projectOwnerName); bundle.putString("projectIndex", projectIndex); bundle.putString("projectOwnerUsername", projectOwnerUsername); ProjectsItemsFragment.setArguments(bundle); JSONObject projectFile = infoProject.getJSONObject("projectFile"); String filePath = ""; String urlString = ""; filePath = projectFile.getString("path"); urlString = "https://raakar.ir"; filePath = filePath.substring(6, filePath.length()); urlString += filePath; SharedPreferences filePathSHP = getActivity().getSharedPreferences("filePath", Context.MODE_PRIVATE); SharedPreferences.Editor fileSHPE = filePathSHP.edit(); fileSHPE.putString("filePath", urlString); fileSHPE.apply(); } catch (JSONException e) { e.printStackTrace(); } FragmentManager manager = getActivity().getSupportFragmentManager(); manager.beginTransaction().replace(R.id.mycontainer, ProjectsItemsFragment).addToBackStack("Back").commit(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }){ @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("token", token); return headers; }}; Singleton.getInstance(getActivity()).addToRequestqueue(pjsonRequest); }else if (group.getPosition() == 1){ if (acception.get(position).equals("2")){ final JsonArrayRequest offerjsonRequest = new JsonArrayRequest (Request.Method.GET, URLgetmyoffers, null, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { Log.d("Response:", response.toString()); try { Bundle myOfferBundle = new Bundle(); JSONObject projectSelected = response.getJSONObject(position); myOfferBundle.putString("name", projectSelected.getString("name")); myOfferBundle.putString("category", projectSelected.getString("category")); myOfferBundle.putString("projectOwnerName", projectSelected.getString("projectOwnerName")); myOfferBundle.putString("description", projectSelected.getString("description")); myOfferBundle.putString("projectIndex", projectSelected.getString("projectIndex")); myOfferBundle.putString("projectOwnerUsername", projectSelected.getString("projectOwnerUsername")); SharedPreferences projectIndex = getActivity().getSharedPreferences("projectIndex", Context.MODE_PRIVATE); SharedPreferences.Editor projectIndexEditor = projectIndex.edit(); projectIndexEditor.putString("projectIndex", projectSelected.getString("projectIndex")); projectIndexEditor.apply(); SharedPreferences projectOwnerName = getActivity().getSharedPreferences("projectOwnerUsername", Context.MODE_PRIVATE); SharedPreferences.Editor projectOwnerNameEditor = projectOwnerName.edit(); projectOwnerNameEditor.putString("projectOwnerUsername", projectSelected.getString("projectOwnerUsername")); projectOwnerNameEditor.apply(); JSONArray offersArray = projectSelected.getJSONArray("offersArray"); for (int i = 0; i < offersArray.length(); i++){ JSONObject myOffer = offersArray.getJSONObject(i); if (myOffer.getString("creatorUsername").equals(username)){ if (myOffer.getBoolean("status") == true){ myOfferBundle.putInt("deadline", myOffer.getInt("deadline")); myOfferBundle.putInt("acceptionYear", myOffer.getInt("acceptionYear")); myOfferBundle.putInt("acceptionMonth", myOffer.getInt("acceptionMonth")); myOfferBundle.putInt("acceptionDate", myOffer.getInt("acceptionDate")); myOfferBundle.putString("amount", myOffer.getString("amount")); DeadlineFragment deadlineFragment = new DeadlineFragment(); final FragmentManager manager = getActivity().getSupportFragmentManager(); manager.beginTransaction().replace(R.id.mycontainer, deadlineFragment) .addToBackStack("Back").commit(); deadlineFragment.setArguments(myOfferBundle); } } } JSONObject projectFile = projectSelected.getJSONObject("projectFile"); String filePath = ""; String url_download = ""; filePath = projectFile.getString("path"); filePath = filePath.substring(6, filePath.length()); url_download = "https://raakar.ir"; url_download += filePath; SharedPreferences DownloadFileForDeadline = getActivity().getSharedPreferences("filePathDeadline", Context.MODE_PRIVATE); SharedPreferences.Editor editor = DownloadFileForDeadline.edit(); editor.putString("filePathDeadline", url_download); editor.apply(); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }){ @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("token", token); return headers; } }; Singleton.getInstance(getActivity()).addToRequestqueue(offerjsonRequest); }else if (acception.get(position).equals("3")){ pDialog2 = new PrettyDialog(getActivity()); pDialog2 .setTitle("") .setMessage("شما فایل نهایی را ارسال کرده اید!") .setIcon( R.drawable.pdlg_icon_info, // icon resource R.color.RakaarColor, null) .addButton( "باشه", R.color.pdlg_color_white, R.color.RakaarColor, new PrettyDialogCallback() { @Override public void onClick() { pDialog2.dismiss(); } } ) .show(); } } } }); Button plus = (Button)view.findViewById(R.id.projects_plus_button); plus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AddFragment Add = new AddFragment(); FragmentManager manager = getActivity().getSupportFragmentManager(); manager.beginTransaction().replace(R.id.mycontainer, Add).addToBackStack("Back").commit(); } }); return view; } private class MyWorksAdapter extends BaseAdapter { public ArrayList<MyWorksAdapterItems> mlistnewsDataAdpater ; public MyWorksAdapter(ArrayList<MyWorksAdapterItems> mlistnewsDataAdpater) { this.mlistnewsDataAdpater=mlistnewsDataAdpater; } @Override public int getCount() { return mlistnewsDataAdpater.size(); } @Override public String getItem(int position) { return null; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater mInflater = getActivity().getLayoutInflater(); View myView = mInflater.inflate(R.layout.title_of_secondlistview, null); final MyWorksAdapterItems m = mlistnewsDataAdpater.get(position); TextView name = (TextView)myView.findViewById(R.id.myworks_name); name.setText(m.mname); TextView details = (TextView)myView.findViewById(R.id.myworks_details); details.setText(m.mdetails); TextView amount_of_bids = (TextView)myView.findViewById(R.id.myworks_amount_of_bids); amount_of_bids.setText(m.amount_of_bids); TextView date = (TextView)myView.findViewById(R.id.myworks_date); date.setText(m.date); return myView; } } private class ProjectsAdapter extends BaseAdapter { public ArrayList<ProjectsAdapterItems> plistnewsDataAdpater ; public ProjectsAdapter(ArrayList<ProjectsAdapterItems> plistnewsDataAdpater) { this.plistnewsDataAdpater=plistnewsDataAdpater; } @Override public int getCount() { return plistnewsDataAdpater.size(); } @Override public String getItem(int position) { return null; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater mInflater = getActivity().getLayoutInflater(); View myView = mInflater.inflate(R.layout.title_of_firstlistview, null); final ProjectsAdapterItems p = plistnewsDataAdpater.get(position); TextView name = (TextView)myView.findViewById(R.id.projects_name); name.setText(p.pname); TextView details = (TextView)myView.findViewById(R.id.projects_details); details.setText(p.pdetails); TextView cost = (TextView)myView.findViewById(R.id.projects_cost); cost.setText(p.pcost); TextView day = (TextView)myView.findViewById(R.id.projects_day); day.setText(p.day); TextView date = (TextView)myView.findViewById(R.id.projects_date); date.setText(p.date); TextView bids = (TextView)myView.findViewById(R.id.project_propsal); bids.setText(p.bids); return myView; } } private class SentBidsAdapter extends BaseAdapter { public ArrayList<SentBidsAdapterItems> plistnewsDataAdpater ; public SentBidsAdapter(ArrayList<SentBidsAdapterItems> plistnewsDataAdpater) { this.plistnewsDataAdpater=plistnewsDataAdpater; } @Override public int getCount() { return plistnewsDataAdpater.size(); } @Override public String getItem(int position) { return null; } @Override public long getItemId(int position) { return position; } @Override public int getViewTypeCount() { return 3; } @Override public int getItemViewType(int position) { SentBidsAdapterItems color = plistnewsDataAdpater.get(position); if (color.color == 0){ return 0; }else if (color.color == 1){ return 1; }else if (color.color == 2){ return 2; }else return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater mInflater = getActivity().getLayoutInflater(); final SentBidsAdapterItems p = plistnewsDataAdpater.get(position); if (getItemViewType(position) == 0){ View myView = mInflater.inflate(R.layout.sentbids_red, null); TextView name = (TextView)myView.findViewById(R.id.sentbids_red_name); name.setText(p.name); TextView details = (TextView)myView.findViewById(R.id.sentbids_red_details); details.setText(p.details); TextView date = (TextView)myView.findViewById(R.id.sentbids_red_date); date.setText(p.date); TextView status = (TextView)myView.findViewById(R.id.sentbids_red_status); status.setText(p.status); return myView; }else { View myView = mInflater.inflate(R.layout.sentbids_green, null); TextView name = (TextView)myView.findViewById(R.id.sentbids_green_name); name.setText(p.name); TextView details = (TextView)myView.findViewById(R.id.sentbids_green_details); details.setText(p.details); TextView date = (TextView)myView.findViewById(R.id.sentbids_green_date); date.setText(p.date); TextView status = (TextView)myView.findViewById(R.id.sentbids_green_status); status.setText(p.status); return myView; } } } public void startAnim(){ Projects_av.smoothToShow(); // or avi.smoothToShow(); } public void stopAnim(){ Projects_av.smoothToHide(); // or avi.smoothToHide(); } public void popupForCheckInternet() { ConnectivityManager connectivityManager = (ConnectivityManager) getContext().getSystemService(getActivity().CONNECTIVITY_SERVICE); NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); NetworkInfo mobileInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if ((wifiInfo != null && wifiInfo.isConnected()) || (mobileInfo != null && mobileInfo.isConnected())) { } else { pDialog = new PrettyDialog(getActivity()); pDialog.setCancelable(false); pDialog .setTitle("خطا!") .setMessage("لطفا اتصال به اینترنت را برقرار نمایید") .setIcon( R.drawable.pdlg_icon_close, // icon resource R.color.pdlg_color_red, null) .addButton( "تلاش مجدد", R.color.pdlg_color_white, R.color.pdlg_color_red, new PrettyDialogCallback() { @Override public void onClick() { popupForCheckInternet(); pDialog.dismiss(); } } ) .show(); } } } <file_sep>package group.tamasha.rockaar; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.ParcelFileDescriptor; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.MimeTypeMap; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.nononsenseapps.filepicker.FilePickerActivity; import java.io.File; import java.io.FileDescriptor; import java.io.IOException; import java.text.DecimalFormat; import libs.mjn.prettydialog.PrettyDialog; import libs.mjn.prettydialog.PrettyDialogCallback; import me.tankery.lib.circularseekbar.CircularSeekBar; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.Request; import okhttp3.RequestBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import static group.tamasha.rockaar.Utilities.getCurrentShamsidate; import static java.lang.String.valueOf; public class DeadlineFragment extends Fragment { PrettyDialog pDialog1; PrettyDialog pDialog2; PrettyDialog pDialog3; TextView deadline_title, deadline_undertitle, deadline_price, deadline_start, deadline_time, deadline_end, deadline_infotext, deadline_seeknumber, deadline_filetitle; int getDeadlineDay; int endDay, endMonth, endYear, startDay, startMonth, startYear, currentYear, currentMonth, currentDay, deadlineDay, seekbarValue; CircularSeekBar deadline_seekbar; String currentTimeFa, userProfileImagePath, token; ImageView deadline_fileback, deadline_upload_finalFile, deadline_dowload; Button deadline_button; SharedPreferences Token, projectOwnerUserName, projectIndex, DLfile, statusSHP; int status; EditText add_linktext; String download_file; Call<AddProjectResponse> call; private static int RESULT_LOAD_IMAGE = 1; private static final int REQUEST_EXTERNAL_STORAGE = 1; private static String[] PERMISSIONS_STORAGE = { android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE }; public DeadlineFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_deadline, container, false); popupForCheckInternet(); statusSHP = getActivity().getSharedPreferences("statusMyWork", Context.MODE_PRIVATE); status = statusSHP.getInt("statusMyWork", 0); deadline_title = (TextView)view.findViewById(R.id.deadline_title); deadline_undertitle = (TextView)view.findViewById(R.id.deadline_undertitle); deadline_price = (TextView)view.findViewById(R.id.deadline_price); deadline_start = (TextView)view.findViewById(R.id.deadline_start); deadline_time = (TextView)view.findViewById(R.id.deadline_time); deadline_end = (TextView)view.findViewById(R.id.deadline_end); deadline_infotext = (TextView)view.findViewById(R.id.deadline_infotext); deadline_seeknumber = (TextView)view.findViewById(R.id.deadline_seeknumber); deadline_filetitle = (TextView)view.findViewById(R.id.deadline_filetitle); deadline_upload_finalFile = (ImageView)view.findViewById(R.id.deadline_upload); add_linktext = (EditText)view.findViewById(R.id.add_linktext); deadline_dowload = (ImageView)view.findViewById(R.id.deadline_dowload); deadline_seekbar = (CircularSeekBar)view.findViewById(R.id.deadline_seekbar); deadline_fileback =(ImageView)view.findViewById(R.id.deadline_fileback); deadline_button = (Button)view.findViewById(R.id.deadline_button); DLfile = getActivity().getSharedPreferences("filePathDeadline", Context.MODE_PRIVATE); download_file = DLfile.getString("filePathDeadline", ""); deadline_dowload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(download_file)); startActivity(intent); } }); Token = getActivity().getSharedPreferences("token", Context.MODE_PRIVATE); token = Token.getString("token", null); Log.e("token", token); currentTimeFa = getCurrentShamsidate(); String[] separated = currentTimeFa.split("/"); currentYear = Integer.parseInt(separated[0]); currentMonth = Integer.parseInt(separated[1]); currentDay = Integer.parseInt(separated[2]); final Bundle bundle = getArguments(); String T = bundle.getString("amount"); String Text = T.replaceAll("[^0-9]+",""); long Number = Long.parseLong(Text); DecimalFormat formatter = new DecimalFormat("#,###,###,###,###"); String yourFormattedString = formatter.format(Number); deadline_title.setText(bundle.getString("name")); deadline_undertitle.setText(bundle.getString("projectOwnerName") + " / " + bundle.getString("category")); deadline_price.setText(yourFormattedString + " تومان"); startDay = bundle.getInt("acceptionDate"); startMonth = bundle.getInt("acceptionMonth"); startYear = bundle.getInt("acceptionYear"); deadline_start.setText(startYear + "/" + startMonth + "/" + startDay); deadline_time.setText(bundle.getInt("deadline") + " روز"); deadline_infotext.setText(bundle.getString("description")); endDay = startDay + bundle.getInt("deadline"); endMonth = startMonth; endYear = startYear; if ( bundle.getInt("acceptionMonth") == 1 || bundle.getInt("acceptionMonth") == 2 || bundle.getInt("acceptionMonth") == 3 || bundle.getInt("acceptionMonth") == 4 || bundle.getInt("acceptionMonth") == 5 || bundle.getInt("acceptionMonth") == 6 ){ for (;endDay>31;){ if (endDay > 31){ endDay = endDay - 31; endMonth++; } } }else if (bundle.getInt("acceptionMonth") == 7 || bundle.getInt("acceptionMonth") == 8 || bundle.getInt("acceptionMonth") == 9 || bundle.getInt("acceptionMonth") == 10 || bundle.getInt("acceptionMonth") == 11){ for (;endDay>30;){ if (endMonth != 12){ if (endDay > 30){ endDay = endDay - 30; endMonth++; } } } } else { for(;endDay>29;){ if (endDay > 30){ endDay = endDay - 30; endMonth = 1; endYear++; } } } deadline_end.setText(endYear + "/" + endMonth + "/" + endDay); int difDay, difYear, difMonth; difDay = endDay - startDay; difMonth = endMonth - startMonth; difYear = endYear - startYear; deadlineDay = 0; if (difMonth > 0){ deadlineDay += difDay; deadlineDay += difYear*365; if (1 <= startMonth && startMonth <= 6){ if (1 <= endMonth && endMonth <= 6){ deadlineDay += difMonth*31; }else if (7 <= endMonth && endMonth <=11){ deadlineDay += (7 - startMonth)*31 + (endMonth - 7)*30; }else if (endMonth == 12){ deadlineDay += (7 - startMonth)*31 + (endMonth - 7)*30; } }else if (7 <= startMonth && startMonth <=11){ if (1 <= endMonth && endMonth <= 6){ deadlineDay += (endMonth - 1)*31 + (13 - startMonth)*30 - 1 - 365; }else if (7 <= endMonth && endMonth <=11){ deadlineDay += difMonth*30; }else if (endMonth == 12){ deadlineDay += difMonth*30; } }else if (startMonth == 12){ if (1 <= endMonth && endMonth <= 6){ deadlineDay += (endMonth - 1)*31 + (13 - startMonth)*30 - 1 - 365; }else if (7 <= endMonth && endMonth <=11){ deadlineDay += difMonth*30; }else if (endMonth == 12){ deadlineDay += 0; } } }else if (difMonth < 0){ deadlineDay += difDay; deadlineDay += difYear*365; if (1 <= startMonth && startMonth <= 6){ if (1 <= endMonth && endMonth <= 6){ deadlineDay += 179 + ((7 - startMonth) + (endMonth - 1))*31 - 365; }else if (7 <= endMonth && endMonth <=11){ }else if (endMonth == 12){ } }else if (7 <= startMonth && startMonth <=11){ if (1 <= endMonth && endMonth <= 6){ deadlineDay += (13 - startMonth)*30 - 1 + (endMonth - 1)*31 - 365; }else if (7 <= endMonth && endMonth <=11){ deadlineDay += 215 + ((12 - startMonth) + (endMonth - 7))*30 - 365; }else if (endMonth == 12){ } }else if (startMonth == 12){ if (1 <= endMonth && endMonth <= 6){ deadlineDay += (13 - startMonth)*30 - 1 + (endMonth - 1)*31 - 365; }else if (7 <= endMonth && endMonth <=11){ deadlineDay += 186 + (endMonth - 6)*30 - 1 - 365; }else if (endMonth == 12){ } } }else if (difMonth == 0){ deadlineDay += difDay; deadlineDay += difYear; } SharedPreferences getDeadline = getActivity().getSharedPreferences("deadline", Context.MODE_PRIVATE); getDeadlineDay = getDeadline.getInt("deadlineDay", deadlineDay); deadline_seeknumber.setText(valueOf(getDeadlineDay)); final Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { SharedPreferences deadlineSHR = getActivity().getSharedPreferences("deadline", Context.MODE_PRIVATE); SharedPreferences.Editor deadlineEditor = deadlineSHR.edit(); deadline_seeknumber.setText(valueOf(getDeadlineDay)); getDeadlineDay--; deadlineEditor.putInt("deadlineDay", getDeadlineDay).apply(); } }, 86400000); seekbarValue = (100 * deadlineDay)/bundle.getInt("deadline"); deadline_seekbar.setProgress(seekbarValue); projectOwnerUserName = getActivity().getSharedPreferences("projectOwnerUsername", Context.MODE_PRIVATE); projectIndex = getActivity().getSharedPreferences("projectIndex", Context.MODE_PRIVATE); Log.e("projetIndex", "_____________________________" + projectIndex.getString("projectIndex", "")); String proIndex = projectIndex.getString("projectIndex", ""); Log.e("projectOwnerUsername","_____________________________" + projectOwnerUserName.getString("projectOwnerUsername", "null")); String proUsername = projectOwnerUserName.getString("projectOwnerUsername", "null"); Log.e("token", "" + token); deadline_upload_finalFile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.i("sss", "onClick"); int permission = ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.WRITE_EXTERNAL_STORAGE); if (permission != PackageManager.PERMISSION_GRANTED) { Log.i("sss", "!PERMISSION_GRANTED"); requestPermissions( PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE ); return; } else { Log.i("sss", "PERMISSION_GRANTED"); chooseFile(); } } }); deadline_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Client client = ServiceGenerator.createService(Client.class); File file = null; RequestBody requestFile = null; MultipartBody.Part body = null; if (userProfileImagePath != null) { try { file = new File(userProfileImagePath); Uri uri = Uri.fromFile(file); if (file.exists()) { Log.i("finaltest", "found"); requestFile = RequestBody.create(MediaType.parse(getMimeType(uri)), file); body = MultipartBody.Part.createFormData("finalFile", file.getName(), requestFile); } else { Log.i("finaltest", "not found"); } } catch (Exception e) { } } RequestBody proIndexRequestBody = RequestBody.create(MediaType.parse("text/plain"), projectIndex.getString("projectIndex", "").trim()); RequestBody proUsernameRequestBody = RequestBody.create(MediaType.parse("text/plain"), projectOwnerUserName.getString("projectOwnerUsername", "").trim()); RequestBody finalLinkRequestBody = RequestBody.create(MediaType.parse("text/plain"), add_linktext.getText().toString().trim()); if (add_linktext.getText().toString().equals("")){ call = client.sendFinalProject( token, proUsernameRequestBody, proIndexRequestBody, finalLinkRequestBody, body); }else { call = client.sendFinalProject( token, proUsernameRequestBody, proIndexRequestBody, finalLinkRequestBody, body); } call.enqueue(new Callback<AddProjectResponse>() { @Override public void onResponse(Call<AddProjectResponse> call, Response<AddProjectResponse> response) { Log.e("xcxc", "code:" + response.code()); Log.e("eeeeee", response.body() + ""); if (response.isSuccessful()) { Log.e("xcxc", "success:"); popupForSuccessAddingFinalFile(); } else { popupForErrorAddingFinalFile(); } } @Override public void onFailure(Call<AddProjectResponse> call, Throwable t) { Log.e("test123", t.getMessage()); } }); } }); return view; } public void chooseFile(){ Intent i = new Intent(getActivity(), FilePickerActivity.class); // This works if you defined the intent filter // Intent i = new Intent(Intent.ACTION_GET_CONTENT); // Set these depending on your use case. These are the defaults. i.putExtra(FilePickerActivity.EXTRA_ALLOW_MULTIPLE, false); i.putExtra(FilePickerActivity.EXTRA_ALLOW_CREATE_DIR, false); i.putExtra(FilePickerActivity.EXTRA_MODE, FilePickerActivity.MODE_FILE); // Configure initial directory by specifying a String. // You could specify a String like "/storage/emulated/0/", but that can // dangerous. Always use Android's API calls to get paths to the SD-card or // internal memory. i.putExtra(FilePickerActivity.EXTRA_START_PATH, Environment.getExternalStorageDirectory().getPath()); startActivityForResult(i, RESULT_LOAD_IMAGE); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); super.onActivityResult(requestCode, resultCode, data); if (requestCode == RESULT_LOAD_IMAGE && resultCode == -1 && null != data) { deadline_filetitle.setText("فایل با موفقیت ضمیمه شد!"); Uri selectedImageUri = data.getData(); if ("content".equalsIgnoreCase(selectedImageUri.getScheme())) { String[] projection = { "_data" }; Cursor cursor = null; try { cursor = getContext().getContentResolver().query(selectedImageUri, projection, null, null, null); int column_index = cursor.getColumnIndexOrThrow("_data"); if (cursor.moveToFirst()) { userProfileImagePath = cursor.getString(column_index); } } catch (Exception e) { // Eat it } } else if ("file".equalsIgnoreCase(selectedImageUri.getScheme())) { userProfileImagePath = selectedImageUri.getPath(); } Log.e("file path", userProfileImagePath); Log.e("uri", selectedImageUri.toString()); Bitmap bmp = null; try { bmp = getBitmapFromUri(selectedImageUri); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } private Bitmap getBitmapFromUri(Uri uri) throws IOException { ParcelFileDescriptor parcelFileDescriptor = getContext().getContentResolver().openFileDescriptor(uri, "r"); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor); parcelFileDescriptor.close(); return image; } public String getMimeType(Uri uri) { String mimeType = ""; if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) { ContentResolver cr = getActivity().getContentResolver(); mimeType = cr.getType(uri); } else { String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri .toString()); mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension( fileExtension.toLowerCase()); } return mimeType; } public void popupForSuccessAddingFinalFile(){ pDialog1 = new PrettyDialog(getActivity()); pDialog1.setCancelable(false); pDialog1 .setTitle("تبریک!") .setMessage("فایل نهایی شما با موفقیت ارسال شد") .setIcon( R.drawable.pdlg_icon_success, // icon resource R.color.pdlg_color_green, null) .addButton( "باشه", R.color.pdlg_color_white, R.color.pdlg_color_green, new PrettyDialogCallback() { @Override public void onClick() { pDialog1.dismiss(); ProjectsFragment projectsFragment = new ProjectsFragment(); FragmentManager manager = getActivity().getSupportFragmentManager(); manager.beginTransaction().replace(R.id.mycontainer, projectsFragment).commit(); } } ) .show(); } public void popupForCheckInternet() { ConnectivityManager connectivityManager = (ConnectivityManager) getContext().getSystemService(getActivity().CONNECTIVITY_SERVICE); NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); NetworkInfo mobileInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if ((wifiInfo != null && wifiInfo.isConnected()) || (mobileInfo != null && mobileInfo.isConnected())){ }else{ pDialog2 = new PrettyDialog(getActivity()); pDialog2.setCancelable(false); pDialog2 .setTitle("خطا!") .setMessage("لطفا اتصال به اینترنت را برقرار نمایید") .setIcon( R.drawable.pdlg_icon_close, // icon resource R.color.pdlg_color_red, null) .addButton( "تلاش مجدد", R.color.pdlg_color_white, R.color.pdlg_color_red, new PrettyDialogCallback() { @Override public void onClick() { popupForCheckInternet(); pDialog2.dismiss(); } } ) .show(); } } public void popupForErrorAddingFinalFile(){ pDialog3 = new PrettyDialog(getActivity()); pDialog3.setCancelable(false); pDialog3 .setTitle("خطا!") .setMessage("مشکلی در ارسال فایل بوجود آمده است") .setIcon( R.drawable.pdlg_icon_close, // icon resource R.color.pdlg_color_red, null) .addButton( "تلاش مجدد", R.color.pdlg_color_white, R.color.pdlg_color_red, new PrettyDialogCallback() { @Override public void onClick() { pDialog3.dismiss(); } } ) .show(); } }
f298df12487935f0651cc88625dbfa98a127c79c
[ "Java" ]
16
Java
hosein2rd/raakar
ef5621e14c16ca9ce4f6ee60ded7a6df5d20f302
97a84b157e351b527ab7fa266de7f1675a2f8532
refs/heads/master
<repo_name>MashaSamoylova/secure-modbus-rtu<file_sep>/README.md # secure-modbus-rtu Реализация защищенного соединения протокола Modbus RTU ## Сборка hardware части ``` cd hardware make CONF=Release clean make CONF=Release ``` ## Загрузка на плату ``` sudo mstn-m100-client -d <full-path-to-directory>/hardware/dist/Release/GNU-Linux/hardware.bin ``` ## Тестовое соединение ``` cd software/master ./master.py ``` ## Сбор трафика со стороны злоумышленика ``` cd software/spy ./spy.py <serial port> ./parse.py ``` <file_sep>/software/master/master.py #!/usr/bin/env python3 import fcntl import struct import time from serial import Serial, PARITY_NONE from umodbus.client.serial import rtu def get_serial_port(): """ Return serial.Serial instance, ready to use for RS485.""" port = Serial(port="/dev/ttyUSB0", baudrate=9600, parity=PARITY_NONE, stopbits=1, bytesize=8, timeout=1) return port raw_message = "sensitive_data_sensitive_data_" array_message = [] for i in range(0, len(raw_message), 2): array_message.append((ord(raw_message[i]) << 8) | ord(raw_message[i+1])) for e in array_message: print(hex(e)) serial_port = get_serial_port() message = rtu.write_multiple_registers(slave_id=1, starting_address=1, values=array_message) print(message) response = rtu.send_message(message, serial_port) print("response", response) time.sleep(1) message = rtu.read_holding_registers(slave_id=1, starting_address=1, quantity=30) response = rtu.send_message(message, serial_port) print("response", response) restored_message = "" for i in response: restored_message += chr(i & ((1 << 8) - 1)) restored_message += chr(i >> 8) print("restored message: ", restored_message) serial_port.close() <file_sep>/hardware/src/Serial.h /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: Serial.h * Author: maria * * Created on May 14, 2019, 11:38 PM */ #ifndef SERIAL_H #define SERIAL_H #include <inttypes.h> #include <stdio.h> // for size_t #include <string.h> // for size_t #include "mstn_uart.h" #include "mstn_clk.h" class HardwareSerial { public: inline HardwareSerial(_UART_InterfaceNum inum) { iNum = inum; }; inline void init(_UART_InterfaceNum inum) { iNum = inum; }; void begin(unsigned long baud) {UART_Begin(iNum, baud); } void end() {UART_End(this->iNum); }; int available(void) {return UART_Available(iNum);}; int peek(void) { return UART_Peek(iNum); }; int read(void) { return UART_Read(iNum); }; void flush(void) { UART_Flush(iNum); }; size_t write(uint8_t c) {UART_Write(iNum, (char)c); return (size_t)1; }; size_t write(uint8_t* buffer, unsigned char size); inline size_t write(unsigned long n) { return write((uint8_t)n); } inline size_t write(long n) { return write((uint8_t)n); } inline size_t write(unsigned int n) { return write((uint8_t)n); } inline size_t write(int n) { return write((uint8_t)n); } void print(const char *str); void println(const char *str); void print(const char c); private: _UART_InterfaceNum iNum; }; extern HardwareSerial Serial1; extern HardwareSerial Serial2; extern HardwareSerial Serial3; extern HardwareSerial Serial4; #endif /* SERIAL_H */ <file_sep>/hardware/src/aes_config.h /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: aes_config.h * Author: maria * * Created on March 23, 2019, 10:23 PM */ /* code was modified by <NAME> <<EMAIL>> * 16/12/14 */ #ifndef __AES_CONFIG_H__ #define __AES_CONFIG_H__ #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <unistd.h> #include <stdint.h> #include <string.h> #if defined(__ARDUINO_X86__) || defined(__arm__) || (defined (__linux) || defined (linux)) #undef PROGMEM #define PROGMEM __attribute__(( section(".progmem.data") )) #define pgm_read_byte(p) (*(p)) typedef unsigned char byte; #define printf_P printf #ifndef PSTR #define PSTR(x) (x) #endif #elif defined ( ESP8266 ) #include <pgmspace.h> #ifndef PSTR #define PSTR(x) (x) #endif #else #if (defined(__AVR__)) #include <avr/pgmspace.h> #else #include <pgmspace.h> #endif #endif #define N_ROW 4 #define N_COL 4 #define N_BLOCK (N_ROW * N_COL) #define N_MAX_ROUNDS 14 #define KEY_SCHEDULE_BYTES ((N_MAX_ROUNDS + 1) * N_BLOCK) #define SUCCESS (0) #define FAILURE (-1) #endif <file_sep>/software/spy/parse.py #!/usr/bin/env python3 import struct from umodbus.client.serial.redundancy_check import get_crc, validate_crc, CRCError def get_frame(adu): frame = adu[:2] i = 2 while 1: try: validate_crc(frame) break except (CRCError, struct.error) as e: frame += adu[i:i+1] i += 1 return frame def parse(): with open("dump.txt", "rb") as f: dump = f.read() frames = [] while len(dump) > 0: new_frame = get_frame(dump) dump = dump[len(new_frame):] frames.append(new_frame) for f in frames: print("----------------------") print(f) print("[slave id] ", f[0]) print("[function code] ", f[1]) print("[data] ", f[2: -2]) print("[crc] ", f[-2:]) if __name__=="__main__": parse() <file_sep>/hardware/nbproject/Makefile-Release.mk # # Generated Makefile - do not edit! # # Edit the Makefile in the project folder instead (../Makefile). Each target # has a -pre and a -post target defined where you can add customized code. # # This makefile implements configuration specific macros and targets. # Environment MKDIR=mkdir CP=cp GREP=grep NM=nm CCADMIN=CCadmin RANLIB=ranlib CC=arm-none-eabi-gcc CCC=arm-none-eabi-g++ CXX=arm-none-eabi-g++ FC=gfortran AS=arm-none-eabi-as # Macros CND_PLATFORM=GNU-Linux CND_DLIB_EXT=so CND_CONF=Release CND_DISTDIR=dist CND_BUILDDIR=build # Include project Makefile include Makefile # Object Directory OBJECTDIR=${CND_BUILDDIR}/${CND_CONF}/${CND_PLATFORM} # Object Files OBJECTFILES= \ ${OBJECTDIR}/Startup/startup_mstn_MDR32F9Qx.o \ ${OBJECTDIR}/src/AES.o \ ${OBJECTDIR}/src/Serial.o \ ${OBJECTDIR}/src/main.o # C Compiler Flags CFLAGS=-mcpu=cortex-m3 -mthumb -MD -Wall -O2 -fdata-sections -ffunction-sections # CC Compiler Flags CCFLAGS=-mcpu=cortex-m3 -mthumb -MD -Wall -O2 -fdata-sections -ffunction-sections -fno-exceptions CXXFLAGS=-mcpu=cortex-m3 -mthumb -MD -Wall -O2 -fdata-sections -ffunction-sections -fno-exceptions # Fortran Compiler Flags FFLAGS= # Assembler Flags ASFLAGS= # Link Libraries and Options LDLIBSOPTIONS=-L/opt/Intec/MSTN/M100/Lib/arm-none-eabi/ # Build Targets .build-conf: ${BUILD_SUBPROJECTS} "${MAKE}" -f nbproject/Makefile-${CND_CONF}.mk ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/hardware ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/hardware: ${OBJECTFILES} ${MKDIR} -p ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM} ${LINK.cc} -o ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/hardware ${OBJECTFILES} ${LDLIBSOPTIONS} -u _printf_float -mcpu=cortex-m3 -mthumb -lstdc++ -nostartfiles -lm -N -Ttext=0x08003000 -Tdata=0x20000000 --specs=nano.specs -Wl,--start-group -lgcc -lc -lm -lMSTN-M100 -Wl,--end-group -Wl,-gc-sections -ffreestanding -T/opt/Intec/MSTN/M100/Lib/arm-none-eabi/MSTN_M100_User.ld -Wl,--start-group -lgcc -lc -lm -lMSTN-M100 -Wl,--end-group ${OBJECTDIR}/Startup/startup_mstn_MDR32F9Qx.o: Startup/startup_mstn_MDR32F9Qx.S ${MKDIR} -p ${OBJECTDIR}/Startup ${RM} "[email protected]" $(COMPILE.c) -O2 -DF_CPU=80000000 -DMSTN=100 -DUSE_MDR1986VE9x -D__MODE_USER -D__NO_SYSTEM_INIT -D__STARTUP_CLEAR_BSS -D_start=mstn_main -I./Startup -I./src -I/opt/Intec/MSTN/M100/Inc/MSTN -I/opt/Intec/MSTN/M100/Inc/SPL_MDR -I/opt/Intec/MSTN/M100/Inc/Cpp -I/opt/Intec/MSTN/M100/Inc/Core -I/opt/Intec/MSTN/M100/Inc/Device -I./ -MMD -MP -MF "[email protected]" -o ${OBJECTDIR}/Startup/startup_mstn_MDR32F9Qx.o Startup/startup_mstn_MDR32F9Qx.S ${OBJECTDIR}/src/AES.o: src/AES.cpp ${MKDIR} -p ${OBJECTDIR}/src ${RM} "[email protected]" $(COMPILE.cc) -O2 -DF_CPU=80000000 -DMSTN=100 -DUSE_MDR1986VE9x -D__MODE_USER -D__NO_SYSTEM_INIT -D__STARTUP_CLEAR_BSS -D_start=mstn_main -I./Startup -I./src -I/opt/Intec/MSTN/M100/Inc/MSTN -I/opt/Intec/MSTN/M100/Inc/SPL_MDR -I/opt/Intec/MSTN/M100/Inc/Cpp -I/opt/Intec/MSTN/M100/Inc/Core -I/opt/Intec/MSTN/M100/Inc/Device -I./ -MMD -MP -MF "[email protected]" -o ${OBJECTDIR}/src/AES.o src/AES.cpp ${OBJECTDIR}/src/Serial.o: src/Serial.cpp ${MKDIR} -p ${OBJECTDIR}/src ${RM} "[email protected]" $(COMPILE.cc) -O2 -DF_CPU=80000000 -DMSTN=100 -DUSE_MDR1986VE9x -D__MODE_USER -D__NO_SYSTEM_INIT -D__STARTUP_CLEAR_BSS -D_start=mstn_main -I./Startup -I./src -I/opt/Intec/MSTN/M100/Inc/MSTN -I/opt/Intec/MSTN/M100/Inc/SPL_MDR -I/opt/Intec/MSTN/M100/Inc/Cpp -I/opt/Intec/MSTN/M100/Inc/Core -I/opt/Intec/MSTN/M100/Inc/Device -I./ -MMD -MP -MF "[email protected]" -o ${OBJECTDIR}/src/Serial.o src/Serial.cpp ${OBJECTDIR}/src/main.o: src/main.cpp ${MKDIR} -p ${OBJECTDIR}/src ${RM} "[email protected]" $(COMPILE.cc) -O2 -DF_CPU=80000000 -DMSTN=100 -DUSE_MDR1986VE9x -D__MODE_USER -D__NO_SYSTEM_INIT -D__STARTUP_CLEAR_BSS -D_start=mstn_main -I./Startup -I./src -I/opt/Intec/MSTN/M100/Inc/MSTN -I/opt/Intec/MSTN/M100/Inc/SPL_MDR -I/opt/Intec/MSTN/M100/Inc/Cpp -I/opt/Intec/MSTN/M100/Inc/Core -I/opt/Intec/MSTN/M100/Inc/Device -I./ -MMD -MP -MF "[email protected]" -o ${OBJECTDIR}/src/main.o src/main.cpp # Subprojects .build-subprojects: # Clean Targets .clean-conf: ${CLEAN_SUBPROJECTS} ${RM} -r ${CND_BUILDDIR}/${CND_CONF} # Subprojects .clean-subprojects: # Enable dependency checking .dep.inc: .depcheck-impl include .dep.inc <file_sep>/software/spy/umodbus/client/serial/rtu.py """ .. note:: This section is based on `MODBUS over Serial Line Specification and Implementation Guide V1.02`_. The ADU for Modbus RTU messages differs from Modbus TCP/IP messages. Messages send over RTU don't have a MBAP header, instead they have an Address field. This field contains the slave id. A CRC is appended to the message. Below all parts of a Modbus RTU message are listed together with their byte size: +---------------+-----------------+ | **Component** | **Size** (bytes)| +---------------+-----------------+ | Address field | 1 | +---------------+-----------------+ | PDU | N | +---------------+-----------------+ | CRC | 2 | +---------------+-----------------+ The CRC is calculated from the Address field and the PDU. Below you see an hexidecimal presentation of request over RTU with Modbus function code 1. It requests data of slave with 1, starting at coil 100, for the length of 3 coils: .. Note: the backslash in the bytes below are escaped using an extra back slash. Without escaping the bytes aren't printed correctly in the HTML output of this docs. To work with the bytes in Python you need to remove the escape sequences. `b'\\x01\\x00d` -> `b\x01\x00d` .. code-block:: python >>> # Read coils, starting from coil 100 for the length of 3 coils. >>> adu = b'\\x01\\x01\\x00d\\x00\\x03=\\xd4' The lenght of this ADU is 8 bytes:: >>> len(adu) 8 """ import struct from umodbus.client.serial.redundancy_check import get_crc, validate_crc from umodbus.functions import (create_function_from_response_pdu, expected_response_pdu_size_from_request_pdu, pdu_to_function_code_or_raise_error, ReadCoils, ReadDiscreteInputs, ReadHoldingRegisters, ReadInputRegisters, WriteSingleCoil, WriteSingleRegister, WriteMultipleCoils, WriteMultipleRegisters) from umodbus.utils import recv_exactly def _create_request_adu(slave_id, req_pdu): """ Return request ADU for Modbus RTU. :param slave_id: Slave id. :param req_pdu: Byte array with PDU. :return: Byte array with ADU. """ first_part_adu = struct.pack('>B', slave_id) + req_pdu return first_part_adu + get_crc(first_part_adu) def read_coils(slave_id, starting_address, quantity): """ Return ADU for Modbus function code 01: Read Coils. :param slave_id: Number of slave. :return: Byte array with ADU. """ function = ReadCoils() function.starting_address = starting_address function.quantity = quantity return _create_request_adu(slave_id, function.request_pdu) def read_discrete_inputs(slave_id, starting_address, quantity): """ Return ADU for Modbus function code 02: Read Discrete Inputs. :param slave_id: Number of slave. :return: Byte array with ADU. """ function = ReadDiscreteInputs() function.starting_address = starting_address function.quantity = quantity return _create_request_adu(slave_id, function.request_pdu) def read_holding_registers(slave_id, starting_address, quantity): """ Return ADU for Modbus function code 03: Read Holding Registers. :param slave_id: Number of slave. :return: Byte array with ADU. """ function = ReadHoldingRegisters() function.starting_address = starting_address function.quantity = quantity return _create_request_adu(slave_id, function.request_pdu) def read_input_registers(slave_id, starting_address, quantity): """ Return ADU for Modbus function code 04: Read Input Registers. :param slave_id: Number of slave. :return: Byte array with ADU. """ function = ReadInputRegisters() function.starting_address = starting_address function.quantity = quantity return _create_request_adu(slave_id, function.request_pdu) def write_single_coil(slave_id, address, value): """ Return ADU for Modbus function code 05: Write Single Coil. :param slave_id: Number of slave. :return: Byte array with ADU. """ function = WriteSingleCoil() function.address = address function.value = value return _create_request_adu(slave_id, function.request_pdu) def write_single_register(slave_id, address, value): """ Return ADU for Modbus function code 06: Write Single Register. :param slave_id: Number of slave. :return: Byte array with ADU. """ function = WriteSingleRegister() function.address = address function.value = value return _create_request_adu(slave_id, function.request_pdu) def write_multiple_coils(slave_id, starting_address, values): """ Return ADU for Modbus function code 15: Write Multiple Coils. :param slave_id: Number of slave. :return: Byte array with ADU. """ function = WriteMultipleCoils() function.starting_address = starting_address function.values = values return _create_request_adu(slave_id, function.request_pdu) def write_multiple_registers(slave_id, starting_address, values): """ Return ADU for Modbus function code 16: Write Multiple Registers. :param slave_id: Number of slave. :return: Byte array with ADU. """ function = WriteMultipleRegisters() function.starting_address = starting_address function.values = values return _create_request_adu(slave_id, function.request_pdu) def parse_response_adu(resp_adu, req_adu=None): """ Parse response ADU and return response data. Some functions require request ADU to fully understand request ADU. :param resp_adu: Resonse ADU. :param req_adu: Request ADU, default None. :return: Response data. """ resp_pdu = resp_adu[1:-2] validate_crc(resp_adu) req_pdu = None if req_adu is not None: req_pdu = req_adu[1:-2] function = create_function_from_response_pdu(resp_pdu, req_pdu) return function.data def raise_for_exception_adu(resp_adu): """ Check a response ADU for error :param resp_adu: Response ADU. :raises ModbusError: When a response contains an error code. """ resp_pdu = resp_adu[1:-2] pdu_to_function_code_or_raise_error(resp_pdu) def send_message(adu, serial_port): """ Send ADU over serial to to server and return parsed response. :param adu: Request ADU. :param sock: Serial port instance. :return: Parsed response from server. """ serial_port.write(adu) serial_port.flush() # Check exception ADU (which is shorter than all other responses) first. exception_adu_size = 5 response_error_adu = recv_exactly(serial_port.read, exception_adu_size) raise_for_exception_adu(response_error_adu) expected_response_size = \ expected_response_pdu_size_from_request_pdu(adu[1:-2]) + 3 response_remainder = recv_exactly( serial_port.read, expected_response_size - exception_adu_size) return parse_response_adu(response_error_adu + response_remainder, adu) <file_sep>/hardware/src/main.cpp #include "main.h" #include <stdlib.h> #include <stdio.h> #include "mstn_usb.h" #include "mstn_gpio.h" #include "mstn_clk.h" #include "Serial.h" #include "ModBusRtu.h" int main(int argc, char *argv[]) { while (USB_GetStatus() != PERMITTED); int8_t state = 0; uint16_t au16data[250]; Modbus slave(1, 1, 2); slave.begin( 9600 ); printf("slave begin\n"); while (1) { state = slave.poll(au16data, 250); if (state > 4) { printf("recieve packet %d \n", state); } } } <file_sep>/hardware/src/main.h #ifndef MAIN_H #define MAIN_H /** * Внимание! * В состав стандартной библиотеки MSTN-M100 входят некоторые модули стандартной * библиотеки MDR32F9Qx, распространяемой компанией Миландр (https://github.com/eldarkg/emdr1986x-std-per-lib). * Использована версия библиотек, актуальная на 04.10.2016. * Библиотека собрана с константой препроцессора "USE_MDR1986VE9x". * Уровень оптимизации -O2. * Список задействованных модулей библиотеки MDR32F9Qx: * MDR32F9Qx_adc * MDR32F9Qx_bkp * MDR32F9Qx_comp * MDR32F9Qx_dac * MDR32F9Qx_eeprom * MDR32F9Qx_i2c * MDR32F9Qx_port * MDR32F9Qx_power * MDR32F9Qx_rst_clk * MDR32F9Qx_ssp * MDR32F9Qx_timer * MDR32F9Qx_uart * MDR32F9Qx_usb * * Для конфигурации Таймера 1 предлагается использовать функции, определенные в модуле MDR32F9Qx_timer * (заг. файл C:\Intec\MSTN\M100\Inc\SPL_MDR\MDR32F9Qx_timer.h). * * Приоритеты прерываний, используемые в библиотеке MSTNLib (0 - наивысший приоритет, 7 - наименьший): * SysTick_IRQ - приоритет 0 * USB_IRQ - приоритет 1 * UART_IRQ - приоритет 3 * TIMER2_IRQ, TIMER3_IRQ - приоритет 3 (пользовательское прерывание, устанавливаемое функцией TMR2CH4_AttachInterrupt() модуля mstn_pwm * и внешние прерывания, устанавливаемые функцией EINT_AttachExtInt() модуля mstn_external_interrupt) * * Категорически не рекомендуется изм енять приоритеты прерываний USB_IRQ и SysTick_IRQ и устанавливать * приоритеты других прерываний выше или равными приоритету прерывания USB_IRQ. * В противном случае корректная работа ПО, собранного на основе библиотеки MSTNLib, не гарантируется. */ #include "mstn_types.h" extern const _MainArgs MAIN_ARGS_STATE = MAIN_ARGS_DISABLE; extern const _StatesJp1 JP1_STATE = JP1_ADC; #endif /* MAIN_H */ <file_sep>/software/master/umodbus/functions.py """ .. note:: This section is based on `MODBUS Application Protocol Specification V1.1b3`_ The Protocol Data Unit (PDU) is the request or response message and is indepedent of the underlying communication layer. This module only implements requests PDU's. A request PDU contains two parts: a function code and request data. A response PDU contains the function code from the request and response data. The general structure is listed in table below: +---------------+-----------------+ | **Field** | **Size** (bytes)| +---------------+-----------------+ | Function code | 1 | +---------------+-----------------+ | data | N | +---------------+-----------------+ Below you see the request PDU with function code 1, requesting status of 3 coils, starting from coil 100. .. Note: the backslash in the bytes below are escaped using an extra back slash. Without escaping the bytes aren't printed correctly in the HTML output of this docs. To work with the bytes in Python you need to remove the escape sequences. `b'\\x01\\x00d` -> `b\x01\x00d` .. code-block:: python >>> req_pdu = b'\\x01\x00d\\x00\\x03' >>> function_code = req_pdu[:1] >>> function_code b'\\x01' >>> starting_address = req_pdu[1:3] >>> starting_address b'\\x00d' >>> quantity = req_pdu[3:] >>> quantity b'\\x00\\x03' A response PDU could look like this:: >>> resp_pdu = b'\\x01\\x01\\x06' >>> function_code = resp_pdu[:1] >>> function_code b'\\x01' >>> byte_count = resp[1:2] >>> byte_count b'\\x01' >>> coil_status = resp[2:] 'b\\x06' """ from __future__ import division import struct import inspect import math try: from functools import reduce except ImportError: pass from umodbus import conf, log from umodbus.exceptions import (error_code_to_exception_map, IllegalDataValueError, IllegalFunctionError, IllegalDataAddressError) from umodbus.utils import memoize, get_function_code_from_request_pdu # Function related to data access. READ_COILS = 1 READ_DISCRETE_INPUTS = 2 READ_HOLDING_REGISTERS = 3 READ_INPUT_REGISTERS = 4 WRITE_SINGLE_COIL = 5 WRITE_SINGLE_REGISTER = 6 WRITE_MULTIPLE_COILS = 15 WRITE_MULTIPLE_REGISTERS = 16 READ_FILE_RECORD = 20 WRITE_FILE_RECORD = 21 READ_WRITE_MULTIPLE_REGISTERS = 23 READ_FIFO_QUEUE = 24 # Diagnostic functions, only available when using serial line. READ_EXCEPTION_STATUS = 7 DIAGNOSTICS = 8 GET_COMM_EVENT_COUNTER = 11 GET_COM_EVENT_LOG = 12 REPORT_SERVER_ID = 17 def pdu_to_function_code_or_raise_error(resp_pdu): """ Parse response PDU and return of :class:`ModbusFunction` or raise error. :param resp_pdu: PDU of response. :return: Subclass of :class:`ModbusFunction` matching the response. :raises ModbusError: When response contains error code. """ function_code = struct.unpack('>B', resp_pdu[0:1])[0] if function_code not in function_code_to_function_map.keys(): error_code = struct.unpack('>B', resp_pdu[1:2])[0] raise error_code_to_exception_map[error_code] return function_code def create_function_from_response_pdu(resp_pdu, req_pdu=None): """ Parse response PDU and return instance of :class:`ModbusFunction` or raise error. :param resp_pdu: PDU of response. :param req_pdu: Request PDU, some functions require more info than in response PDU in order to create instance. Default is None. :return: Number or list with response data. """ function_code = pdu_to_function_code_or_raise_error(resp_pdu) function = function_code_to_function_map[function_code] if req_pdu is not None and \ 'req_pdu' in inspect.getargspec(function.create_from_response_pdu).args: # NOQA return function.create_from_response_pdu(resp_pdu, req_pdu) return function.create_from_response_pdu(resp_pdu) @memoize def create_function_from_request_pdu(pdu): """ Return function instance, based on request PDU. :param pdu: Array of bytes. :return: Instance of a function. """ function_code = get_function_code_from_request_pdu(pdu) try: function_class = function_code_to_function_map[function_code] except KeyError: raise IllegalFunctionError(function_code) return function_class.create_from_request_pdu(pdu) def expected_response_pdu_size_from_request_pdu(pdu): """ Return number of bytes expected for response PDU, based on request PDU. :param pdu: Array of bytes. :return: number of bytes. """ return create_function_from_request_pdu(pdu).expected_response_pdu_size class ModbusFunction(object): function_code = None class ReadCoils(ModbusFunction): """ Implement Modbus function code 01. "This function code is used to read from 1 to 2000 contiguous status of coils in a remote device. The Request PDU specifies the starting address, i.e. the address of the first coil specified, and the number of coils. In the PDU Coils are addressed starting at zero. Therefore coils numbered 1-16 are addressed as 0-15. The coils in the response message are packed as one coil per bit of the data field. Status is indicated as 1= ON and 0= OFF. The LSB of the first data byte contains the output addressed in the query. The other coils follow toward the high order end of this byte, and from low order to high order in subsequent bytes. If the returned output quantity is not a multiple of eight, the remaining bits in the final data byte will be padded with zeros (toward the high order end of the byte). The Byte Count field specifies the quantity of complete bytes of data." -- MODBUS Application Protocol Specification V1.1b3, chapter 6.1 The request PDU with function code 01 must be 5 bytes: ================ =============== Field Length (bytes) ================ =============== Function code 1 Starting address 2 Quantity 2 ================ =============== The PDU can unpacked to this: .. Note: the backslash in the bytes below are escaped using an extra back slash. Without escaping the bytes aren't printed correctly in the HTML output of this docs. To work with the bytes in Python you need to remove the escape sequences. `b'\\x01\\x00d` -> `b\x01\x00d` .. code-block:: python >>> struct.unpack('>BHH', b'\\x01\\x00d\\x00\\x03') (1, 100, 3) The reponse PDU varies in length, depending on the request. Each 8 coils require 1 byte. The amount of bytes needed represent status of the coils to can be calculated with: bytes = ceil(quantity / 8). This response contains ceil(3 / 8) = 1 byte to describe the status of the coils. The structure of a compleet response PDU looks like this: ================ =============== Field Length (bytes) ================ =============== Function code 1 Byte count 1 Coil status n ================ =============== Assume the status of 102 is 0, 101 is 1 and 100 is also 1. This is binary 011 which is decimal 3. The PDU can packed like this:: >>> struct.pack('>BBB', function_code, byte_count, 3) b'\\x01\\x01\\x03' """ function_code = READ_COILS max_quantity = 2000 format_character = 'B' data = None starting_address = None _quantity = None @property def quantity(self): return self._quantity @quantity.setter def quantity(self, value): """ Set number of coils to read. Quantity must be between 1 and 2000. :param value: Quantity. :raises: IllegalDataValueError. """ if not (1 <= value <= 2000): raise IllegalDataValueError('Quantify field of request must be a ' 'value between 0 and ' '{0}.'.format(2000)) self._quantity = value @property def request_pdu(self): """ Build request PDU to read coils. :return: Byte array of 5 bytes with PDU. """ if None in [self.starting_address, self.quantity]: # TODO Raise proper exception. raise Exception return struct.pack('>BHH', self.function_code, self.starting_address, self.quantity) @staticmethod def create_from_request_pdu(pdu): """ Create instance from request PDU. :param pdu: A request PDU. :return: Instance of this class. """ _, starting_address, quantity = struct.unpack('>BHH', pdu) instance = ReadCoils() instance.starting_address = starting_address instance.quantity = quantity return instance @property def expected_response_pdu_size(self): """ Return number of bytes expected for response PDU. :return: number of bytes. """ return 2 + int(math.ceil(self.quantity / 8)) def create_response_pdu(self, data): """ Create response pdu. :param data: A list with 0's and/or 1's. :return: Byte array of at least 3 bytes. """ log.debug('Create single bit response pdu {0}.'.format(data)) bytes_ = [data[i:i + 8] for i in range(0, len(data), 8)] # Reduce each all bits per byte to a number. Byte # [0, 0, 0, 0, 0, 1, 1, 1] is intepreted as binary en is decimal 3. for index, byte in enumerate(bytes_): bytes_[index] = \ reduce(lambda a, b: (a << 1) + b, list(reversed(byte))) log.debug('Reduced single bit data to {0}.'.format(bytes_)) # The first 2 B's of the format encode the function code (1 byte) and # the length (1 byte) of the following byte series. Followed by # a B # for every byte in the series of bytes. 3 lead to the format '>BBB' # and 257 lead to the format '>BBBB'. fmt = '>BB' + self.format_character * len(bytes_) return struct.pack(fmt, self.function_code, len(bytes_), *bytes_) @staticmethod def create_from_response_pdu(resp_pdu, req_pdu): """ Create instance from response PDU. Response PDU is required together with the quantity of coils read. :param resp_pdu: Byte array with request PDU. :param quantity: Number of coils read. :return: Instance of :class:`ReadCoils`. """ read_coils = ReadCoils() read_coils.quantity = struct.unpack('>H', req_pdu[-2:])[0] byte_count = struct.unpack('>B', resp_pdu[1:2])[0] fmt = '>' + ('B' * byte_count) bytes_ = struct.unpack(fmt, resp_pdu[2:]) data = list() for i, value in enumerate(bytes_): padding = 8 if (read_coils.quantity - (8 * i)) // 8 > 0 \ else read_coils.quantity % 8 fmt = '{{0:0{padding}b}}'.format(padding=padding) # Create binary representation of integer, convert it to a list # and reverse the list. data = data + [int(i) for i in fmt.format(value)][::-1] read_coils.data = data return read_coils def execute(self, slave_id, route_map): """ Execute the Modbus function registered for a route. :param slave_id: Slave id. :param eindpoint: Instance of modbus.route.Map. :return: Result of call to endpoint. """ try: values = [] for address in range(self.starting_address, self.starting_address + self.quantity): endpoint = route_map.match(slave_id, self.function_code, address) values.append(endpoint(slave_id=slave_id, address=address, function_code=self.function_code)) return values # route_map.match() returns None if no match is found. Calling None # results in TypeError. except TypeError: raise IllegalDataAddressError() class ReadDiscreteInputs(ModbusFunction): """ Implement Modbus function code 02. "This function code is used to read from 1 to 2000 contiguous status of discrete inputs in a remote device. The Request PDU specifies the starting address, i.e. the address of the first input specified, and the number of inputs. In the PDU Discrete Inputs are addressed starting at zero. Therefore Discrete inputs numbered 1-16 are addressed as 0-15. The discrete inputs in the response message are packed as one input per bit of the data field. Status is indicated as 1= ON; 0= OFF. The LSB of the first data byte contains the input addressed in the query. The other inputs follow toward the high order end of this byte, and from low order to high order in subsequent bytes. If the returned input quantity is not a multiple of eight, the remaining bits in the final d ata byte will be padded with zeros (toward the high order end of the byte). The Byte Count field specifies the quantity of complete bytes of data." -- MODBUS Application Protocol Specification V1.1b3, chapter 6.2 The request PDU with function code 02 must be 5 bytes: ================ =============== Field Length (bytes) ================ =============== Function code 1 Starting address 2 Quantity 2 ================ =============== The PDU can unpacked to this: .. Note: the backslash in the bytes below are escaped using an extra back slash. Without escaping the bytes aren't printed correctly in the HTML output of this docs. To work with the bytes in Python you need to remove the escape sequences. `b'\\x01\\x00d` -> `b\x01\x00d` .. code-block:: python >>> struct.unpack('>BHH', b'\\x02\\x00d\\x00\\x03') (2, 100, 3) The reponse PDU varies in length, depending on the request. 8 inputs require 1 byte. The amount of bytes needed represent status of the inputs to can be calculated with: bytes = ceil(quantity / 8). This response contains ceil(3 / 8) = 1 byte to describe the status of the inputs. The structure of a compleet response PDU looks like this: ================ =============== Field Length (bytes) ================ =============== Function code 1 Byte count 1 Coil status n ================ =============== Assume the status of 102 is 0, 101 is 1 and 100 is also 1. This is binary 011 which is decimal 3. The PDU can packed like this:: >>> struct.pack('>BBB', function_code, byte_count, 3) b'\\x02\\x01\\x03' """ function_code = READ_DISCRETE_INPUTS max_quantity = 2000 format_character = 'B' data = None starting_address = None _quantity = None @property def quantity(self): return self._quantity @quantity.setter def quantity(self, value): """ Set number of inputs to read. Quantity must be between 1 and 2000. :param value: Quantity. :raises: IllegalDataValueError. """ if not (1 <= value <= 2000): raise IllegalDataValueError('Quantify field of request must be a ' 'value between 0 and ' '{0}.'.format(2000)) self._quantity = value @property def request_pdu(self): """ Build request PDU to read discrete inputs. :return: Byte array of 5 bytes with PDU. """ if None in [self.starting_address, self.quantity]: # TODO Raise proper exception. raise Exception return struct.pack('>BHH', self.function_code, self.starting_address, self.quantity) @staticmethod def create_from_request_pdu(pdu): """ Create instance from request PDU. :param pdu: A request PDU. :return: Instance of this class. """ _, starting_address, quantity = struct.unpack('>BHH', pdu) instance = ReadDiscreteInputs() instance.starting_address = starting_address instance.quantity = quantity return instance @property def expected_response_pdu_size(self): """ Return number of bytes expected for response PDU. :return: number of bytes. """ return 2 + int(math.ceil(self.quantity / 8)) def create_response_pdu(self, data): """ Create response pdu. :param data: A list with 0's and/or 1's. :return: Byte array of at least 3 bytes. """ log.debug('Create single bit response pdu {0}.'.format(data)) bytes_ = [data[i:i + 8] for i in range(0, len(data), 8)] # Reduce each all bits per byte to a number. Byte # [0, 0, 0, 0, 0, 1, 1, 1] is intepreted as binary en is decimal 3. for index, byte in enumerate(bytes_): bytes_[index] = \ reduce(lambda a, b: (a << 1) + b, list(reversed(byte))) log.debug('Reduced single bit data to {0}.'.format(bytes_)) # The first 2 B's of the format encode the function code (1 byte) and # the length (1 byte) of the following byte series. Followed by # a B # for every byte in the series of bytes. 3 lead to the format '>BBB' # and 257 lead to the format '>BBBB'. fmt = '>BB' + self.format_character * len(bytes_) return struct.pack(fmt, self.function_code, len(bytes_), *bytes_) @staticmethod def create_from_response_pdu(resp_pdu, req_pdu): """ Create instance from response PDU. Response PDU is required together with the quantity of inputs read. :param resp_pdu: Byte array with request PDU. :param quantity: Number of inputs read. :return: Instance of :class:`ReadDiscreteInputs`. """ read_discrete_inputs = ReadDiscreteInputs() read_discrete_inputs.quantity = struct.unpack('>H', req_pdu[-2:])[0] byte_count = struct.unpack('>B', resp_pdu[1:2])[0] fmt = '>' + ('B' * byte_count) bytes_ = struct.unpack(fmt, resp_pdu[2:]) data = list() for i, value in enumerate(bytes_): padding = 8 if (read_discrete_inputs.quantity - (8 * i)) // 8 > 0 \ else read_discrete_inputs.quantity % 8 fmt = '{{0:0{padding}b}}'.format(padding=padding) # Create binary representation of integer, convert it to a list # and reverse the list. data = data + [int(i) for i in fmt.format(value)][::-1] read_discrete_inputs.data = data return read_discrete_inputs def execute(self, slave_id, route_map): """ Execute the Modbus function registered for a route. :param slave_id: Slave id. :param eindpoint: Instance of modbus.route.Map. :return: Result of call to endpoint. """ try: values = [] for address in range(self.starting_address, self.starting_address + self.quantity): endpoint = route_map.match(slave_id, self.function_code, address) values.append(endpoint(slave_id=slave_id, address=address, function_code=self.function_code)) return values # route_map.match() returns None if no match is found. Calling None # results in TypeError. except TypeError: raise IllegalDataAddressError() class ReadHoldingRegisters(ModbusFunction): """ Implement Modbus function code 03. "This function code is used to read the contents of a contiguous block of holding registers in a remote device. The Request PDU specifies the starting register address and the number of registers. In the PDU Registers are addressed starting at zero. Therefore registers numbered 1-16 are addressed as 0-15. The register data in the response message are packed as two bytes per register, with the binary contents right justified within each byte. For each register, the first byte contains the high order bits and the second contains the low order bits." -- MODBUS Application Protocol Specification V1.1b3, chapter 6.3 The request PDU with function code 03 must be 5 bytes: ================ =============== Field Length (bytes) ================ =============== Function code 1 Starting address 2 Quantity 2 ================ =============== The PDU can unpacked to this: .. Note: the backslash in the bytes below are escaped using an extra back slash. Without escaping the bytes aren't printed correctly in the HTML output of this docs. To work with the bytes in Python you need to remove the escape sequences. `b'\\x01\\x00d` -> `b\x01\x00d` .. code-block:: python >>> struct.unpack('>BHH', b'\\x03\\x00d\\x00\\x03') (3, 100, 3) The reponse PDU varies in length, depending on the request. By default, holding registers are 16 bit (2 bytes) values. So values of 3 holding registers is expressed in 2 * 3 = 6 bytes. ================ =============== Field Length (bytes) ================ =============== Function code 1 Byte count 1 Register values Quantity * 2 ================ =============== Assume the value of 100 is 8, 101 is 0 and 102 is also 15. The PDU can packed like this:: >>> data = [8, 0, 15] >>> struct.pack('>BBHHH', function_code, len(data) * 2, *data) b'\\x03\\x06\\x00\\x08\\x00\\x00\\x00\\x0f' """ function_code = READ_HOLDING_REGISTERS max_quantity = 0x007D data = None starting_address = None _quantity = None @property def quantity(self): return self._quantity @quantity.setter def quantity(self, value): """ Set number of registers to read. Quantity must be between 1 and 0x00FD. :param value: Quantity. :raises: IllegalDataValueError. """ if not (1 <= value <= 0x00FD): raise IllegalDataValueError('Quantify field of request must be a ' 'value between 0 and ' '{0}.'.format(0x00FD)) self._quantity = value @property def request_pdu(self): """ Build request PDU to read coils. :return: Byte array of 5 bytes with PDU. """ if None in [self.starting_address, self.quantity]: # TODO Raise proper exception. raise Exception return struct.pack('>BHH', self.function_code, self.starting_address, self.quantity) @staticmethod def create_from_request_pdu(pdu): """ Create instance from request PDU. :param pdu: A request PDU. :return: Instance of this class. """ starting_address = struct.unpack('>H', pdu[1:3])[0] quantity = struct.unpack('>H', pdu[3:5])[0] instance = ReadHoldingRegisters() instance.starting_address = starting_address instance.quantity = quantity return instance @property def expected_response_pdu_size(self): """ Return number of bytes expected for response PDU. :return: number of bytes. """ expected_quantity = 2 + self.quantity * 2 if expected_quantity % 16: return expected_quantity + (16 - expected_quantity%16) return expected_quantity def create_response_pdu(self, data): """ Create response pdu. :param data: A list with values. :return: Byte array of at least 4 bytes. """ log.debug('Create multi bit response pdu {0}.'.format(data)) fmt = '>BB' + conf.TYPE_CHAR * len(data) return struct.pack(fmt, self.function_code, len(data) * 2, *data) @staticmethod def create_from_response_pdu(resp_pdu, req_pdu): """ Create instance from response PDU. Response PDU is required together with the number of registers read. :param resp_pdu: Byte array with request PDU. :param quantity: Number of coils read. :return: Instance of :class:`ReadCoils`. """ read_holding_registers = ReadHoldingRegisters() read_holding_registers.quantity = struct.unpack('>H', req_pdu[3:5])[0] read_holding_registers.byte_count = \ struct.unpack('>B', resp_pdu[1:2])[0] read_holding_registers.data = [] for i in range(0, read_holding_registers.quantity, 2): read_holding_registers.data.append(struct.unpack("<H", resp_pdu[2+i: 2+i + 2])[0]) #fmt = '>' + (conf.TYPE_CHAR * read_holding_registers.quantity) #read_holding_registers.data = list(struct.unpack(fmt, resp_pdu[2:])) return read_holding_registers def execute(self, slave_id, route_map): """ Execute the Modbus function registered for a route. :param slave_id: Slave id. :param eindpoint: Instance of modbus.route.Map. :return: Result of call to endpoint. """ try: values = [] for address in range(self.starting_address, self.starting_address + self.quantity): endpoint = route_map.match(slave_id, self.function_code, address) values.append(endpoint(slave_id=slave_id, address=address, function_code=self.function_code)) return values # route_map.match() returns None if no match is found. Calling None # results in TypeError. except TypeError: raise IllegalDataAddressError() class ReadInputRegisters(ModbusFunction): """ Implement Modbus function code 04. "This function code is used to read from 1 to 125 contiguous input registers in a remote device. The Request PDU specifies the starting register address and the number of registers. In the PDU Registers are addressed starting at zero. Therefore input registers numbered 1-16 are addressed as 0-15. The register data in the response message are packed as two bytes per register, with the binary contents right justified within each byte. For each register, the first byte contains the high order bits and the second contains the low order bits." -- MODBUS Application Protocol Specification V1.1b3, chapter 6.4 The request PDU with function code 04 must be 5 bytes: ================ =============== Field Length (bytes) ================ =============== Function code 1 Starting address 2 Quantity 2 ================ =============== The PDU can unpacked to this: .. Note: the backslash in the bytes below are escaped using an extra back slash. Without escaping the bytes aren't printed correctly in the HTML output of this docs. To work with the bytes in Python you need to remove the escape sequences. `b'\\x01\\x00d` -> `b\x01\x00d` .. code-block:: python >>> struct.unpack('>BHH', b'\\x04\\x00d\\x00\\x03') (4, 100, 3) The reponse PDU varies in length, depending on the request. By default, holding registers are 16 bit (2 bytes) values. So values of 3 holding registers is expressed in 2 * 3 = 6 bytes. ================ =============== Field Length (bytes) ================ =============== Function code 1 Byte count 1 Register values Quantity * 2 ================ =============== Assume the value of 100 is 8, 101 is 0 and 102 is also 15. The PDU can packed like this:: >>> data = [8, 0, 15] >>> struct.pack('>BBHHH', function_code, len(data) * 2, *data) b'\\x04\\x06\\x00\\x08\\x00\\x00\\x00\\x0f' """ function_code = READ_INPUT_REGISTERS max_quantity = 0x007D data = None starting_address = None _quantity = None @property def quantity(self): return self._quantity @quantity.setter def quantity(self, value): """ Set number of registers to read. Quantity must be between 1 and 0x00FD. :param value: Quantity. :raises: IllegalDataValueError. """ if not (1 <= value <= 0x007D): raise IllegalDataValueError('Quantify field of request must be a ' 'value between 0 and ' '{0}.'.format(0x007D)) self._quantity = value @property def request_pdu(self): """ Build request PDU to read coils. :return: Byte array of 5 bytes with PDU. """ if None in [self.starting_address, self.quantity]: # TODO Raise proper exception. raise Exception return struct.pack('>BHH', self.function_code, self.starting_address, self.quantity) @staticmethod def create_from_request_pdu(pdu): """ Create instance from request PDU. :param pdu: A request PDU. :return: Instance of this class. """ _, starting_address, quantity = struct.unpack('>BHH', pdu) instance = ReadInputRegisters() instance.starting_address = starting_address instance.quantity = quantity return instance @property def expected_response_pdu_size(self): """ Return number of bytes expected for response PDU. :return: number of bytes. """ return 2 + self.quantity * 2 def create_response_pdu(self, data): """ Create response pdu. :param data: A list with values. :return: Byte array of at least 4 bytes. """ log.debug('Create multi bit response pdu {0}.'.format(data)) fmt = '>BB' + conf.TYPE_CHAR * len(data) return struct.pack(fmt, self.function_code, len(data) * 2, *data) @staticmethod def create_from_response_pdu(resp_pdu, req_pdu): """ Create instance from response PDU. Response PDU is required together with the number of registers read. :param resp_pdu: Byte array with request PDU. :param quantity: Number of coils read. :return: Instance of :class:`ReadCoils`. """ read_input_registers = ReadInputRegisters() read_input_registers.quantity = struct.unpack('>H', req_pdu[-2:])[0] fmt = '>' + (conf.TYPE_CHAR * read_input_registers.quantity) read_input_registers.data = list(struct.unpack(fmt, resp_pdu[2:])) return read_input_registers def execute(self, slave_id, route_map): """ Execute the Modbus function registered for a route. :param slave_id: Slave id. :param eindpoint: Instance of modbus.route.Map. :return: Result of call to endpoint. """ try: values = [] for address in range(self.starting_address, self.starting_address + self.quantity): endpoint = route_map.match(slave_id, self.function_code, address) values.append(endpoint(slave_id=slave_id, address=address, function_code=self.function_code)) return values # route_map.match() returns None if no match is found. Calling None # results in TypeError. except TypeError: raise IllegalDataAddressError() class WriteSingleCoil(ModbusFunction): """ Implement Modbus function code 05. "This function code is used to write a single output to either ON or OFF in a remote device. The requested ON/OFF state is specified by a constant in the request data field. A value of FF 00 hex requests the output to be ON. A value of 00 00 requests it to be OFF. All other values are illegal and will not affect the output. The Request PDU specifies the address of the coil to be forced. Coils are addressed starting at zero. Therefore coil numbered 1 is addressed as 0. The requested ON/OFF state is specified by a constant in the Coil Value field. A value of 0XFF00 requests the coil to be ON. A value of 0X0000 requests the coil to be off. All other values are illegal and will not affect the coil. The normal response is an echo of the request, returned after the coil state has been written." -- MODBUS Application Protocol Specification V1.1b3, chapter 6.5 The request PDU with function code 05 must be 5 bytes: ================ =============== Field Length (bytes) ================ =============== Function code 1 Address 2 Value 2 ================ =============== The PDU can unpacked to this: .. Note: the backslash in the bytes below are escaped using an extra back slash. Without escaping the bytes aren't printed correctly in the HTML output of this docs. To work with the bytes in Python you need to remove the escape sequences. `b'\\x01\\x00d` -> `b\x01\x00d` .. code-block:: python >>> struct.unpack('>BHH', b'\\x05\\x00d\\xFF\\x00') (5, 100, 65280) The reponse PDU is a copy of the request PDU. ================ =============== Field Length (bytes) ================ =============== Function code 1 Address 2 Value 2 ================ =============== """ function_code = WRITE_SINGLE_COIL format_character = 'B' address = None data = None _value = None @property def value(self): if self._value == 0xFF00: return 1 return self._value @value.setter def value(self, value): if value not in [0, 1, 0xFF00]: raise IllegalDataValueError value = 0xFF00 if value == 1 else value self._value = value @property def request_pdu(self): """ Build request PDU to write single coil. :return: Byte array of 5 bytes with PDU. """ if None in [self.address, self.value]: # TODO Raise proper exception. raise Exception return struct.pack('>BHH', self.function_code, self.address, self._value) @staticmethod def create_from_request_pdu(pdu): """ Create instance from request PDU. :param pdu: A response PDU. """ _, address, value = struct.unpack('>BHH', pdu) value = 1 if value == 0xFF00 else value instance = WriteSingleCoil() instance.address = address instance.value = value return instance @property def expected_response_pdu_size(self): """ Return number of bytes expected for response PDU. :return: number of bytes. """ return 5 def create_response_pdu(self): """ Create response pdu. :param data: A list with values. :return: Byte array of at least 4 bytes. """ fmt = '>BHH' return struct.pack(fmt, self.function_code, self.address, self._value) @staticmethod def create_from_response_pdu(resp_pdu): """ Create instance from response PDU. :param resp_pdu: Byte array with request PDU. :return: Instance of :class:`WriteSingleCoil`. """ write_single_coil = WriteSingleCoil() address, value = struct.unpack('>HH', resp_pdu[1:5]) value = 1 if value == 0xFF00 else value write_single_coil.address = address write_single_coil.data = value return write_single_coil def execute(self, slave_id, route_map): """ Execute the Modbus function registered for a route. :param slave_id: Slave id. :param eindpoint: Instance of modbus.route.Map. """ endpoint = route_map.match(slave_id, self.function_code, self.address) try: endpoint(slave_id=slave_id, address=self.address, value=self.value, function_code=self.function_code) # route_map.match() returns None if no match is found. Calling None # results in TypeError. except TypeError: raise IllegalDataAddressError() class WriteSingleRegister(ModbusFunction): """ Implement Modbus function code 06. "This function code is used to write a single holding register in a remote device. The Request PDU specifies the address of the register to be written. Registers are addressed starting at zero. Therefore register numbered 1 is addressed as 0. The normal response is an echo of the request, returned after the register contents have been written." -- MODBUS Application Protocol Specification V1.1b3, chapter 6.6 The request PDU with function code 06 must be 5 bytes: ================ =============== Field Length (bytes) ================ =============== Function code 1 Address 2 Value 2 ================ =============== The PDU can unpacked to this: .. Note: the backslash in the bytes below are escaped using an extra back slash. Without escaping the bytes aren't printed correctly in the HTML output of this docs. To work with the bytes in Python you need to remove the escape sequences. `b'\\x01\\x00d` -> `b\x01\x00d` .. code-block:: python >>> struct.unpack('>BHH', b'\\x06\\x00d\\x00\\x03') (6, 100, 3) The reponse PDU is a copy of the request PDU. ================ =============== Field Length (bytes) ================ =============== Function code 1 Address 2 Value 2 ================ =============== """ function_code = WRITE_SINGLE_REGISTER address = None data = None _value = None @property def value(self): return self._value @value.setter def value(self, value): """ Value to be written on register. :param value: An integer. :raises: IllegalDataValueError when value isn't in range. """ try: struct.pack('>' + conf.TYPE_CHAR, value) except struct.error: raise IllegalDataValueError self._value = value @property def request_pdu(self): """ Build request PDU to write single register. :return: Byte array of 5 bytes with PDU. """ if None in [self.address, self.value]: # TODO Raise proper exception. raise Exception return struct.pack('>BH' + conf.TYPE_CHAR, self.function_code, self.address, self.value) @staticmethod def create_from_request_pdu(pdu): """ Create instance from request PDU. :param pdu: A response PDU. """ _, address, value = \ struct.unpack('>BH' + conf.MULTI_BIT_VALUE_FORMAT_CHARACTER, pdu) instance = WriteSingleRegister() instance.address = address instance.value = value return instance @property def expected_response_pdu_size(self): """ Return number of bytes expected for response PDU. :return: number of bytes. """ return 5 def create_response_pdu(self): fmt = '>BH' + conf.TYPE_CHAR return struct.pack(fmt, self.function_code, self.address, self.value) @staticmethod def create_from_response_pdu(resp_pdu): """ Create instance from response PDU. :param resp_pdu: Byte array with request PDU. :return: Instance of :class:`WriteSingleRegister`. """ write_single_register = WriteSingleRegister() address, value = struct.unpack('>H' + conf.TYPE_CHAR, resp_pdu[1:5]) write_single_register.address = address write_single_register.data = value return write_single_register def execute(self, slave_id, route_map): """ Execute the Modbus function registered for a route. :param slave_id: Slave id. :param eindpoint: Instance of modbus.route.Map. """ endpoint = route_map.match(slave_id, self.function_code, self.address) try: endpoint(slave_id=slave_id, address=self.address, value=self.value, function_code=self.function_code) # route_map.match() returns None if no match is found. Calling None # results in TypeError. except TypeError: raise IllegalDataAddressError() class WriteMultipleCoils(ModbusFunction): """ Implement Modbus function 15 (0x0F) Write Multiple Coils. "This function code is used to force each coil in a sequence of coils to either ON or OFF in a remote device. The Request PDU specifies the coil references to be forced. Coils are addressed starting at zero. Therefore coil numbered 1 is addressed as 0. The requested ON/OFF states are specified by contents of the request data field. A logical '1' in a bit position of the field requests the corresponding output to be ON. A logical '0' requests it to be OFF. The normal response returns the function code, starting address, and quantity of coils forced." -- MODBUS Application Protocol Specification V1.1b3, chapter 6.11 The request PDU with function code 15 must be at least 7 bytes: ================ =============== Field Length (bytes) ================ =============== Function code 1 Starting Address 2 Byte count 1 Quantity 2 Value n ================ =============== The PDU can unpacked to this: .. Note: the backslash in the bytes below are escaped using an extra back slash. Without escaping the bytes aren't printed correctly in the HTML output of this docs. To work with the bytes in Python you need to remove the escape sequences. `b'\\x01\\x00d` -> `b\x01\x00d` .. code-block:: python >>> struct.unpack('>BHHBB', b'\\x0f\\x00d\\x00\\x03\\x01\\x05') (16, 100, 3, 1, 5) The reponse PDU is 5 bytes and contains following structure: ================ =============== Field Length (bytes) ================ =============== Function code 1 Starting address 2 Quantity 2 ================ =============== """ function_code = WRITE_MULTIPLE_COILS starting_address = None _values = None _data = None @property def values(self): return self._values @values.setter def values(self, values): if not (1 <= len(values) <= 0x7B0): raise IllegalDataValueError for value in values: if value not in [0, 1]: raise IllegalDataValueError self._values = values @property def request_pdu(self): if None in [self.starting_address, self._values]: raise IllegalDataValueError bytes_ = [self.values[i:i + 8] for i in range(0, len(self.values), 8)] # Reduce each all bits per byte to a number. Byte # [0, 0, 0, 0, 0, 1, 1, 1] is intepreted as binary en is decimal 3. for index, byte in enumerate(bytes_): bytes_[index] = \ reduce(lambda a, b: (a << 1) + b, list(reversed(byte))) fmt = '>BHHB' + 'B' * len(bytes_) return struct.pack(fmt, self.function_code, self.starting_address, len(self.values), (len(self.values) // 8) + 1, *bytes_) @staticmethod def create_from_request_pdu(pdu): """ Create instance from request PDU. This method requires some clarification regarding the unpacking of the status that are being passed to the callbacks. A coil status can be 0 or 1. The request PDU contains at least 1 byte, representing the status for 1 to 8 coils. Assume a request with starting address 100, quantity set to 3 and the value byte is 6. 0b110 is the binary reprensention of decimal 6. The Least Significant Bit (LSB) is status of coil with starting address. So status of coil 100 is 0, status of coil 101 is 1 and status of coil 102 is 1 too. coil address 102 101 100 1 1 0 Again, assume starting address 100 and byte value is 6. But now quantity is 4. So the value byte is addressing 4 coils. The binary representation of 6 is now 0b0110. LSB again is 0, meaning status of coil 100 is 0. Status of 101 and 102 is 1, like in the previous example. Status of coil 104 is 0. coil address 104 102 101 100 0 1 1 0 In short: the binary representation of the byte value is in reverse mapped to the coil addresses. In table below you can see some more examples. # quantity value binary representation | 102 101 100 == ======== ===== ===================== | === === === 01 1 0 0b0 - - 0 02 1 1 0b1 - - 1 03 2 0 0b00 - 0 0 04 2 1 0b01 - 0 1 05 2 2 0b10 - 1 0 06 2 3 0b11 - 1 1 07 3 0 0b000 0 0 0 08 3 1 0b001 0 0 1 09 3 2 0b010 0 1 0 10 3 3 0b011 0 1 1 11 3 4 0b100 1 0 0 12 3 5 0b101 1 0 1 13 3 6 0b110 1 1 0 14 3 7 0b111 1 1 1 :param pdu: A request PDU. """ _, starting_address, quantity, byte_count = \ struct.unpack('>BHHB', pdu[:6]) fmt = '>' + (conf.SINGLE_BIT_VALUE_FORMAT_CHARACTER * byte_count) values = struct.unpack(fmt, pdu[6:]) res = list() for i, value in enumerate(values): padding = 8 if (quantity - (8 * i)) // 8 > 0 else quantity % 8 fmt = '{{0:0{padding}b}}'.format(padding=padding) # Create binary representation of integer, convert it to a list # and reverse the list. res = res + [int(i) for i in fmt.format(value)][::-1] instance = WriteMultipleCoils() instance.starting_address = starting_address instance.quantity = quantity instance.values = res return instance @property def expected_response_pdu_size(self): """ Return number of bytes expected for response PDU. :return: number of bytes. """ return 5 def create_response_pdu(self): """ Create response pdu. :param data: A list with values. :return: Byte array 5 bytes. """ return struct.pack('>BHH', self.function_code, self.starting_address, len(self.values)) @staticmethod def create_from_response_pdu(resp_pdu): write_multiple_coils = WriteMultipleCoils() starting_address, data = struct.unpack('>HH', resp_pdu[1:5]) write_multiple_coils.starting_address = starting_address write_multiple_coils.data = data return write_multiple_coils def execute(self, slave_id, route_map): """ Execute the Modbus function registered for a route. :param slave_id: Slave id. :param eindpoint: Instance of modbus.route.Map. """ for index, value in enumerate(self.values): address = self.starting_address + index endpoint = route_map.match(slave_id, self.function_code, address) try: endpoint(slave_id=slave_id, address=address, value=value, function_code=self.function_code) # route_map.match() returns None if no match is found. Calling None # results in TypeError. except TypeError: raise IllegalDataAddressError() class WriteMultipleRegisters(ModbusFunction): """ Implement Modbus function 16 (0x10) Write Multiple Registers. "This function code is used to write a block of contiguous registers (1 to 123 registers) in a remote device. The requested written values are specified in the request data field. Data is packed as two bytes per register. The normal response returns the function code, starting address, and quantity of registers written." -- MODBUS Application Protocol Specification V1.1b3, chapter 6.12 The request PDU with function code 16 must be at least 8 bytes: ================ =============== Field Length (bytes) ================ =============== Function code 1 Starting Address 2 Quantity 2 Byte count 1 Value Quantity * 2 ================ =============== The PDU can unpacked to this: .. Note: the backslash in the bytes below are escaped using an extra back slash. Without escaping the bytes aren't printed correctly in the HTML output of this docs. To work with the bytes in Python you need to remove the escape sequences. `b'\\x01\\x00d` -> `b\x01\x00d` .. code-block:: python >>> struct.unpack('>BHHBH', b'\\x10\\x00d\\x00\\x01\\x02\\x00\\x05') (16, 100, 1, 2, 5) The reponse PDU is 5 bytes and contains following structure: ================ =============== Field Length (bytes) ================ =============== Function code 1 Starting address 2 Quantity 2 ================ =============== """ function_code = WRITE_MULTIPLE_REGISTERS starting_address = None _values = None _data = None @property def values(self): return self._values @values.setter def values(self, values): if not (1 <= len(values) <= 0x7B0): raise IllegalDataValueError for value in values: try: struct.pack(">" + conf.MULTI_BIT_VALUE_FORMAT_CHARACTER, value) except struct.error: raise IllegalDataValueError self._values = values self._values = values @property def request_pdu(self): fmt = '>BHHB' + (conf.TYPE_CHAR * len(self.values)) return struct.pack(fmt, self.function_code, self.starting_address, len(self.values), len(self.values) * 2, *self.values) @staticmethod def create_from_request_pdu(pdu): """ Create instance from request PDU. :param pdu: A request PDU. :return: Instance of this class. """ _, starting_address, quantity, byte_count = struct.unpack('>BHHB', pdu[:6]) # Values are 16 bit, so each value takes up 2 bytes. fmt = '>' + (conf.MULTI_BIT_VALUE_FORMAT_CHARACTER * int((byte_count / 2))) #values = list(struct.unpack(fmt, pdu[6:])) instance = WriteMultipleRegisters() instance.starting_address = starting_address #instance.values = values return instance @property def expected_response_pdu_size(self): """ Return number of bytes expected for response PDU. :return: number of bytes. """ return 16 def create_response_pdu(self): """ Create response pdu. :param data: A list with values. :return: Byte array 5 bytes. """ return struct.pack('>BHH', self.function_code, self.starting_address, len(self.values)) @staticmethod def create_from_response_pdu(resp_pdu): write_multiple_registers = WriteMultipleRegisters() starting_address, data = struct.unpack('>HH', resp_pdu[1:5]) write_multiple_registers.starting_address = starting_address write_multiple_registers.data = data return write_multiple_registers def execute(self, slave_id, route_map): """ Execute the Modbus function registered for a route. :param slave_id: Slave id. :param eindpoint: Instance of modbus.route.Map. """ for index, value in enumerate(self.values): address = self.starting_address + index endpoint = route_map.match(slave_id, self.function_code, address) try: endpoint(slave_id=slave_id, address=address, value=value, function_code=self.function_code) # route_map.match() returns None if no match is found. Calling None # results in TypeError. except TypeError: raise IllegalDataAddressError() function_code_to_function_map = { READ_COILS: ReadCoils, READ_DISCRETE_INPUTS: ReadDiscreteInputs, READ_HOLDING_REGISTERS: ReadHoldingRegisters, READ_INPUT_REGISTERS: ReadInputRegisters, WRITE_SINGLE_COIL: WriteSingleCoil, WRITE_SINGLE_REGISTER: WriteSingleRegister, WRITE_MULTIPLE_COILS: WriteMultipleCoils, WRITE_MULTIPLE_REGISTERS: WriteMultipleRegisters, } <file_sep>/software/master/umodbus/server/serial/rtu.py from __future__ import division import struct from binascii import hexlify from umodbus import log from umodbus.server.serial import AbstractSerialServer from umodbus.client.serial.redundancy_check import get_crc, validate_crc def get_char_size(baudrate): """ Get the size of 1 character in seconds. From the implementation guide: "The implementation of RTU reception driver may imply the management of a lot of interruptions due to the t 1.5 and t 3.5 timers. With high communication baud rates, this leads to a heavy CPU load. Consequently these two timers must be strictly respected when the baud rate is equal or lower than 19200 Bps. For baud rates greater than 19200 Bps, fixed values for the 2 timers should be used: it is recommended to use a value of 750us for the inter-character time-out (t 1.5) and a value of 1.750ms for inter-frame delay (t 3.5)." """ if baudrate <= 19200: # One frame is 11 bits. return 11 / baudrate # 750 us / 1.5 = 500 us or 0.0005 s. return 0.0005 class RTUServer(AbstractSerialServer): @property def serial_port(self): return self._serial_port @serial_port.setter def serial_port(self, serial_port): """ Set timeouts on serial port based on baudrate to detect frames. """ char_size = get_char_size(serial_port.baudrate) # See docstring of get_char_size() for meaning of constants below. serial_port.inter_byte_timeout = 1.5 * char_size serial_port.timeout = 3.5 * char_size self._serial_port = serial_port def serve_once(self): """ Listen and handle 1 request. """ # 256 is the maximum size of a Modbus RTU frame. request_adu = self.serial_port.read(256) print("request_adu", request_adu) print('<-- {0}'.format(hexlify(request_adu))) if len(request_adu) == 0: raise ValueError response_adu = self.process(request_adu) #self.respond(response_adu) def process(self, request_adu): """ Process request ADU and return response. :param request_adu: A bytearray containing the ADU request. :return: A bytearray containing the response of the ADU request. """ validate_crc(request_adu) return super(RTUServer, self).process(request_adu) def create_response_adu(self, meta_data, response_pdu): """ Build response ADU from meta data and response PDU and return it. :param meta_data: A dict with meta data. :param request_pdu: A bytearray containing request PDU. :return: A bytearray containing request ADU. """ first_part_adu = struct.pack('>B', meta_data['unit_id']) + response_pdu return first_part_adu + get_crc(first_part_adu) <file_sep>/hardware/src/Serial.cpp /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: Serial.cpp * Author: maria * * Created on May 14, 2019, 11:38 PM */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include "Serial.h" void HardwareSerial::println(const char *str) { UART_PrintStr(iNum, str); UART_PrintStr(iNum, "\n"); } void HardwareSerial::print(const char c) { UART_Write(iNum, c); } void HardwareSerial::print(const char *str) { UART_PrintStr(iNum, str); } size_t HardwareSerial::write(uint8_t* buffer, unsigned char size) { //UART_WriteBuff(iNum, (char*)buffer, size); unsigned char i; char c; for(i = 0; i < size; i++) { c = (char)buffer[i]; printf("send %c\n", c); UART_Write(iNum, c); ProgramDelay(100); } return size; }; HardwareSerial Serial1(SERIAL1); HardwareSerial Serial2(SERIAL2); HardwareSerial Serial3(SERIAL3); HardwareSerial Serial4(SERIAL4); <file_sep>/hardware/nbproject/Makefile-variables.mk # # Generated - do not edit! # # NOCDDL # CND_BASEDIR=`pwd` CND_BUILDDIR=build CND_DISTDIR=dist # Debug configuration CND_PLATFORM_Debug=arm-none-eabi-Linux CND_ARTIFACT_DIR_Debug=dist/Debug/arm-none-eabi-Linux CND_ARTIFACT_NAME_Debug=mstn_template CND_ARTIFACT_PATH_Debug=dist/Debug/arm-none-eabi-Linux/mstn_template CND_PACKAGE_DIR_Debug=dist/Debug/arm-none-eabi-Linux/package CND_PACKAGE_NAME_Debug=mstntemplate.tar CND_PACKAGE_PATH_Debug=dist/Debug/arm-none-eabi-Linux/package/mstntemplate.tar # Release configuration CND_PLATFORM_Release=GNU-Linux CND_ARTIFACT_DIR_Release=dist/Release/GNU-Linux CND_ARTIFACT_NAME_Release=hardware CND_ARTIFACT_PATH_Release=dist/Release/GNU-Linux/hardware CND_PACKAGE_DIR_Release=dist/Release/GNU-Linux/package CND_PACKAGE_NAME_Release=hardware.tar CND_PACKAGE_PATH_Release=dist/Release/GNU-Linux/package/hardware.tar # # include compiler specific variables # # dmake command ROOT:sh = test -f nbproject/private/Makefile-variables.mk || \ (mkdir -p nbproject/private && touch nbproject/private/Makefile-variables.mk) # # gmake command .PHONY: $(shell test -f nbproject/private/Makefile-variables.mk || (mkdir -p nbproject/private && touch nbproject/private/Makefile-variables.mk)) # include nbproject/private/Makefile-variables.mk <file_sep>/software/spy/spy.py #!/usr/bin/env python3 import sys import time import serial def read(port): ser = serial.Serial(port,9600,timeout=0.1) while 1: read_data = ser.read(256) print(read_data) if len(read_data) != 0: with open("dump.txt", "ab") as f: f.write(read_data) if __name__=="__main__": read(sys.argv[1]) <file_sep>/software/master/umodbus/client/serial/redundancy_check.py """ CRC is calculated over slave id + PDU. Most code is taken from: https://github.com/pyhys/minimalmodbus/blob/e99f4d74c83258c6039073082955ac9bed3f2155/minimalmodbus.py # NOQA """ import struct def generate_look_up_table(): """ Generate look up table. :return: List """ poly = 0xA001 table = [] for index in range(256): data = index << 1 crc = 0 for _ in range(8, 0, -1): data >>= 1 if (data ^ crc) & 0x0001: crc = (crc >> 1) ^ poly else: crc >>= 1 table.append(crc) return table look_up_table = generate_look_up_table() def get_crc(msg): """ Return CRC of 2 byte for message. >>> assert get_crc(b'\x02\x07') == struct.unpack('<H', b'\x41\x12') :param msg: A byte array. :return: Byte array of 2 bytes. """ register = 0xFFFF for byte_ in msg: try: val = struct.unpack('<B', byte_)[0] # Iterating over a bit-like objects in Python 3 gets you ints. # Because fuck logic. except TypeError: val = byte_ register = \ (register >> 8) ^ look_up_table[(register ^ val) & 0xFF] # CRC is little-endian! return struct.pack('<H', register) def add_crc(msg): """ Append CRC to message. :param msg: A byte array. :return: Byte array. """ return msg + get_crc(msg) def validate_crc(msg): """ Validate CRC of message. :param msg: Byte array with message with CRC. :raise: CRCError. """ print("validate crc") if not struct.unpack('<H', get_crc(msg[:-2])) ==\ struct.unpack('<H', msg[-2:]): print("not ok") raise CRCError('CRC validation failed.') print("ok") class CRCError(Exception): """ Valid error to raise when CRC isn't correct. """ pass <file_sep>/software/master/umodbus/server/serial/__init__.py import struct from binascii import hexlify from types import MethodType from serial import SerialTimeoutException from umodbus import log from umodbus.route import Map from umodbus.server import route from umodbus.functions import create_function_from_request_pdu from umodbus.exceptions import ModbusError, ServerDeviceFailureError from umodbus.utils import (get_function_code_from_request_pdu, pack_exception_pdu) from umodbus.client.serial.redundancy_check import CRCError def get_server(server_class, serial_port): """ Return instance of :param:`server_class` with :param:`request_handler` bound to it. This method also binds a :func:`route` method to the server instance. >>> server = get_server(TcpServer, ('localhost', 502), RequestHandler) >>> server.serve_forever() :param server_class: (sub)Class of :class:`socketserver.BaseServer`. :param request_handler_class: (sub)Class of :class:`umodbus.server.RequestHandler`. :return: Instance of :param:`server_class`. """ print("get_server") s = server_class() s.serial_port = serial_port s.route_map = Map() s.route = MethodType(route, s) return s class AbstractSerialServer(object): _shutdown_request = False def get_meta_data(self, request_adu): """" Extract MBAP header from request adu and return it. The dict has 4 keys: transaction_id, protocol_id, length and unit_id. :param request_adu: A bytearray containing request ADU. :return: Dict with meta data of request. """ return { 'unit_id': struct.unpack('>B', request_adu[:1])[0], } def get_request_pdu(self, request_adu): """ Extract PDU from request ADU and return it. :param request_adu: A bytearray containing request ADU. :return: An bytearray container request PDU. """ return request_adu[1:-2] def serve_once(self): """ Listen and handle 1 request. """ raise NotImplementedError def serve_forever(self, poll_interval=1.2): """ Wait for incomming requests. """ print("serve_forever") self.serial_port.timeout = poll_interval while not self._shutdown_request: try: self.serve_once() except (CRCError, struct.error) as e: print('Can\'t handle request: {0}'.format(e)) except (SerialTimeoutException, ValueError): pass def process(self, request_adu): """ Process request ADU and return response. :param request_adu: A bytearray containing the ADU request. :return: A bytearray containing the response of the ADU request. """ print("abstract process") meta_data = self.get_meta_data(request_adu) request_pdu = self.get_request_pdu(request_adu) response_pdu = self.execute_route(meta_data, request_pdu) response_adu = self.create_response_adu(meta_data, response_pdu) return response_adu def execute_route(self, meta_data, request_pdu): """ Execute configured route based on requests meta data and request PDU. :param meta_data: A dict with meta data. It must at least contain key 'unit_id'. :param request_pdu: A bytearray containing request PDU. :return: A bytearry containing reponse PDU. """ try: function = create_function_from_request_pdu(request_pdu) results =\ function.execute(meta_data['unit_id'], self.route_map) try: # ReadFunction's use results of callbacks to build response # PDU... return function.create_response_pdu(results) except TypeError: # ...other functions don't. return function.create_response_pdu() except ModbusError as e: function_code = get_function_code_from_request_pdu(request_pdu) return pack_exception_pdu(function_code, e.error_code) except Exception as e: log.exception('Could not handle request: {0}.'.format(e)) function_code = get_function_code_from_request_pdu(request_pdu) return pack_exception_pdu(function_code, ServerDeviceFailureError.error_code) def respond(self, response_adu): """ Send response ADU back to client. :param response_adu: A bytearray containing the response of an ADU. """ log.debug('--> {0}'.format(hexlify(response_adu))) self.serial_port.write(response_adu) def shutdown(self): self._shutdown_request = True
55b7d1c9406249de8040c1c6226361d611ab0a19
[ "Markdown", "Makefile", "Python", "C", "C++" ]
16
Markdown
MashaSamoylova/secure-modbus-rtu
de8a1acab88b0fefe901a72221a8c32af4dd9547
d8cd184f325880ba6c1b84c607b77806fdd9b197
refs/heads/master
<repo_name>chenkang123456/java<file_sep>/java代码/src/java代码/mulu.java package java代码; import java.util.Scanner; public class mulu { public static void main(String[] args){ Scanner in=new Scanner(System.in); int a = 0; //是否注册校验 String answer; do{ System.out.println("*****欢迎进入24分游戏系统*****"); System.out.println("\t1.登录\n\t2.玩游戏\n\t3.排行榜"); System.out.println("请选择菜单:"); int num = in.nextInt(); if(a == 0 && num != 1){ System.out.println("您未登录,请先登录"); num = 1; }else if(a != 2 && num == 3){ System.out.println("请先登录!"); num = 2; } switch(num){ case 1: System.out.println("[24分游戏系统>登录]"); a = 1; //已登录; break; case 2: System.out.println("[24分游戏系统>玩游戏]"); a = 2; //已登录; break; case 3: System.out.println("[24分游戏系统>排行榜]"); break; default: System.out.println("您的输入有错误"); break; } System.out.println("继续吗(y/n):"); answer=in.next(); System.out.println(" "); }while("y".equals(answer)); System.out.println("系统退出,谢谢使用!"); } } <file_sep>/mybatis_12_2_4/src/com/yq/mapper/OrderMapper.java package com.yq.mapper; import com.yq.pojo.OrderPojo; public interface OrderMapper { //查询一个订单,同时查出下单用户 OrderPojo selectById(Integer id); //查询一个订单,同时查出明细集合 OrderPojo selectById2(Integer id); } <file_sep>/java代码/src/java代码/login.java package java代码; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPasswordField; import javax.swing.JTextField; public class login { public static void main(String[] args) { final String userName = "abc"; final String password = "123"; JFrame jFrame = new JFrame("登陆界面"); Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize(); jFrame.setBounds(((int)dimension.getWidth() - 200) / 2, ((int)dimension.getHeight() - 300) / 2, 200, 150); jFrame.setResizable(false); jFrame.setLayout(null); jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label1 = new JLabel("姓名"); label1.setBounds(10, 10, 100, 30); jFrame.add(label1); JLabel label2 = new JLabel("密码"); label2.setBounds(10, 40, 100, 30); jFrame.add(label2); final JTextField text1 = new JTextField(); text1.setBounds(50, 15, 130, 20); jFrame.add(text1); final JPasswordField text2 = new JPasswordField(); text2.setBounds(50, 45, 130, 20); jFrame.add(text2); JButton button = new JButton("Login"); button.setBounds(10, 75, 170, 40); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if(userName.equals(text1.getText()) && password.equals(text2.getText())) { JOptionPane.showMessageDialog(null, "登录成功", "提示", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(null, "登录失败", "提示", JOptionPane.ERROR_MESSAGE); text1.setText(""); text2.setText(""); } } }); jFrame.add(button); jFrame.setVisible(true); } } <file_sep>/Game/src/UserDao.java //import Game.domain.User; public interface UserDao { //这个接口保证两个功能 //注册 public abstract void regist(User user); //登录 public abstract boolean isLogin(String userName,String passWord); //排行榜 } <file_sep>/mybatis_12_3_1/src/com/yq/pojo/OrderPojo.java package com.yq.pojo; import java.sql.Timestamp; import java.util.List; public class OrderPojo { private Integer id; private Integer user_id; private String number; private Timestamp createTime; private String note; private UserPojo user;//当前订单的下单人对象 private List<OrderDetailPojo> Details;//订单对应的名细集合 public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getUser_id() { return user_id; } public void setUser_id(Integer user_id) { this.user_id = user_id; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public Timestamp getCreateTime() { return createTime; } public void setCreateTime(Timestamp createTime) { this.createTime = createTime; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public UserPojo getUser() { return user; } public void setUser(UserPojo user) { this.user = user; } public List<OrderDetailPojo> getDetails() { return Details; } public void setDetails(List<OrderDetailPojo> details) { Details = details; } @Override public String toString() { return "OrderPojo [id=" + id + ", user_id=" + user_id + ", number=" + number + ", createTime=" + createTime + ", note=" + note + "]"; } } <file_sep>/Day_11_23/src/Test1.java class one{ public one(){ System.out.println("Hello Constructor"); } public one(String s){ this(); System.out.println(s); } } public class Test1 { public static void main(String[] args) { // TODO Auto-generated method stub new one(args[0]); } } /** class Test1{ public int i; public char a; public static int x=8;//static的成员变量 public Test1(int i,char a){//构造方法 this.i=i; this.a=a; } } public class Test{ public static void main(String[] args) { Test1 test1 = new Test1(1,'a');//创建多个实例 Test1 test2 = new Test1(2,'b'); System.out.println("test1-"+test1.i+test1.a+test1.x); System.out.println("test2-"+test2.i+test2.a+test2.x); } }*/ /** class Person{ public int age; public String name; public static String country; } public class Test1{ public static void main (String[] args) { Person per = new Person(); per.name = "龟田"; per.age = 1; Person.country = "日本"; Person per1 = new Person(); per1.name = "张三"; per1.age = 999; Person.country = "中国"; System.out.println(per.country); System.out.println(per1.country); } } */<file_sep>/src/test06.java public class test06 { public static void main(String[] args){ int i=1, sum = 0; while(sum<8888){ sum = sum +i; i++; } System.out.println(" "+(i-1)); } } <file_sep>/24tfgame/src/AutoGame.java import java.io.BufferedOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Calendar; import java.util.Date; import java.util.Random; import java.util.Scanner; import java.util.Timer; import java.util.TimerTask; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class AutoGame { static boolean flag = true;//该变量标识是否超时 static int life = 3;//初始化生命值 static int score=0;//初始化分数 /** *开始游戏的方法,该方法通过当前生命值判断是否结束 */ public void start() throws IOException { Calendar date = Calendar.getInstance();//实例化Calendar对象 while(life>0) {//当生命值大于0才会进行 flag=true;//初始化分数标记 date.setTime(new Date()); date.add(Calendar.SECOND, 20);//设置限定时间 Timer timer = new Timer(); //当达到限定时间将会执行run()方法,即把全局变量flag变为false timer.schedule(new RemindTask(), date.getTime()); int answer = answer(); switch(answer) { case -1: System.out.println("表达式错误!! 当前生命值为"+life+" 分数为:"+score); break; case -2: System.out.println("输入超时!! 当前生命值为"+life+" 分数为:"+score); break; case -3: System.out.println("结果错误!! 当前生命值为"+life+" 分数为:"+score); break; case 1: System.out.println("正确,得到1分奖励!! 当前生命值为"+life+" 分数为:"+score); break; } System.out.println("----------"); } System.out.println("游戏结束……分数为: "+score);//循环结束也就是生命值为0,打印游戏结束 saveScore(score);//将玩家当前分数存入文件 return; } /** * * Title: getData</p> * Description:给定任意的数据 * @return */ private float[] getData() { float[] data = new float[4]; Random r = new Random();//随机生成四个数据存入数组中 data[0] = r.nextInt(12) + 1; data[1] = r.nextInt(12) + 1; data[2] = r.nextInt(12) + 1; data[3] = r.nextInt(12) + 1; System.out.print("四个数字为:"); for (float f : data) switch ((int) f) { case 1: System.out.print("A" + " "); break; case 11: System.out.print("J" + " "); break; case 12: System.out.print("O" + " "); break; case 13: System.out.print("K" + " "); break; default: System.out.print((int) f + " "); break; } System.out.println("请开始作答,时间20秒"); return data; } /** * * Title: answer</p> * Description:根据用户输入返回false或true * 1.输入不含给定值,返回FALSE * 2.输入超时,返回false * 3.输入表达式的值不为24,返回false * 否则,返回true * @return -1代表输入的表达式与系统给出的数字不吻合 * @return -2代表用户计算结果超时 * @return -3代表结果错误 * @return 1代表用户计算正确 */ public int answer() { Scanner sc = new Scanner(System.in); float[] data = getData();//获取给定的数据 //获取script引擎,调用eval()方法来判断表达式是否正确 ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("nashorn"); String exper = sc.next(); try { String res = String.valueOf(scriptEngine.eval(exper)); for (int i = 0; i < data.length; i++) if (!exper.contains(data[i] + "")) {//输入的表达式不含给定的值 life--; return -1; } if(!flag) {//判断超时 life--; return -2; } if (res.equals("24")) {//回答正確并且没有超时 score++;//分数加一 return 1; } life--; } catch (ScriptException e) { System.out.println("表达式输入不合法"); } return -3; } /** * Title: saveScore</p> * Description: 该方法表示将玩家当前分数存入TopList.txt文件 * @param score 需要存入的分数 * @throws IOException */ public static void saveScore(int score) throws IOException { FileOutputStream fos = new FileOutputStream("e:/TopList.txt"); BufferedOutputStream bos = new BufferedOutputStream(fos); bos.write((score+"").getBytes());//把分数写入文件 bos.close(); } public static void main(String[] args) throws IOException { saveScore(1); } } /** * * Title: RemindTask * Description:该TimerTask并且重写run()可以实现在指定的定时时间执行run方法的内容 * @author jianglei */ class RemindTask extends TimerTask { @Override public void run() { AutoGame.flag = false;//当超时会把全局变量flag变为false } } <file_sep>/Demo/src/MyServer.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.*; import java.util.HashMap; /*24分游戏 * 服务器端,在9999端口上监听 * 可以通过控制台,输入给客户端的信息 */ public class MyServer { /* * * @param args */ public static void main(String[] args) { InputStream is = null; OutputStream os = null; int sum = 0; int score=0; ServerSocket serverSocket = null; Socket socket = null; try { serverSocket = new ServerSocket(6005); System.out.println("服务器启动请选择菜单!"); System.out.println("\t1.玩游戏\n\t2.排行榜"); socket = serverSocket.accept(); // 从客户端读取数据,需要先转换为字符流 is = socket.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String str = str = br.readLine(); System.out.println("我是服务器,客户端输入的消息为:" + str); socket.shutdownInput(); // 对客户端输入的账号密码信息进行处理 String[] str2 = str.split("&"); HashMap<String, String> hm = new HashMap<>(); for (String str1 : str2) { String[] str3 = str1.split(":"); hm.put(str3[0], str3[1]); } String reply = "选择失败"; if ("1".equals(hm.get("change")) && "1".equals(hm.get("pwchange"))) { reply = "游戏开始!"; System.out.println("开始游戏"); int a=(int)(Math.random()*9+1); int b=(int)(Math.random()*9+1); int c=(int)(Math.random()*9+1); int d=(int)(Math.random()*9+1); System.out.println("n1\tn2\tn3\tn4"); System.out.println(a+"\t"+b+"\t"+c+"\t"+d); System.out.println("请输入:"); socket = serverSocket.accept(); is = socket.getInputStream(); } // 向客户端发送消息 os = socket.getOutputStream(); os.write(reply.getBytes()); socket.shutdownOutput(); } catch (IOException e) { e.printStackTrace(); }finally { try { if (is != null) is.close(); if (os != null) os.close(); socket.close(); serverSocket.close(); }catch (IOException e) { e.printStackTrace(); } } } }<file_sep>/java代码/src/java代码/main.java package java代码; import java.util.Scanner; public class main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in=new Scanner(System.in ); System.out.println("游戏开始"); int score=0; for(int i=0;i<10;i++){ int sum=0; int a=(int)(Math.random()*(8)+1); int b=(int)(Math.random()*(8)+1); int c=(int)(Math.random()*(8)+1); int d=(int)(Math.random()*(8)+1); String []fu=new String[3]; System.out.println("n1\tn2\tn3\tn4"); System.out.println(a+"\t"+b+"\t"+c+"\t"+d); Scanner sc=new Scanner(System.in); for(int j=0;j<fu.length;j++){ fu[j]=sc.next(); } System.out.println(" "+fu[0]+" "+fu[1]+" "+fu[2]); switch(fu[0]){ case "+": sum = a+b; break; case "-": if(a>b){ sum = a-b; break; } case "*": sum = a*b; break; case "/": sum = a/b; break; default: System.out.println("输入错误,符号不存在!"); break; } switch(fu[1]){ case "+": sum += c; break; case "-": if(sum>c){ sum -= c; break; } case "*": sum *= c; break; case "/": sum /= c; break; default: System.out.println("输入错误,符号不存在!"); break; } switch(fu[2]){ case "+": sum += d; break; case "-": if(sum>d){ sum -= d; break; } case "*": sum *= d; break; case "/": sum /= d; break; default: System.out.println("输入错误,符号不存在!"); break; } System.out.println(sum); if(sum==24){ System.out.println("恭喜你回答正确!!!"); score=score+1; System.out.println("得分为" +score); }else{ System.out.println("很抱歉你回答错了"); } } } } <file_sep>/Day_11_23/src/Test.java class Test1{ public int a; public int b; } public class Test { public static void main(String[] args) { // TODO Auto-generated method stub Test1 test1 = new Test1(); System.out.println(test1.a + " " + test1.b); } } <file_sep>/src/Main.java class test03 { public static void main(String[] args) { int i; double e=0, j=1; for(i=1; i<=10; i++){ j *= (1.0/i); e += j; } System.out.println("e ="+e); } } <file_sep>/src/test07.java import java.util.Scanner; public class test07 { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.println("请输入一个1~100之间的整数!"); int j = (int) (Math.random() * 100 + 1); while (true) { int i = scan.nextInt(); if (i > j) { System.out.println("您猜的数大了"); System.out.println("请继续输入!"); } else if (i < j) { System.out.println("您猜的数小了"); System.out.println("请继续输入!"); } else{ System.out.println("恭喜您猜对了"); System.out.println("这个数是:"+i); break; } } } } <file_sep>/Game/src/Test.java import java.util.Scanner; //import Game.dao.impl.UserDaoImpl; //import Game.edu.domain.User; //import Game.edu.game.GuessNumber; public class Test { public static void main(String[] args) { while(true){ //首先给出提示 System.out.println("欢迎进入注册登录界面:"); System.out.println("1.注册"); System.out.println("2.登录"); System.out.println("3.退出"); //创建一个用户操作类 UserDaoImpl udi = new UserDaoImpl(); //创建键盘录入对象,并获取键盘录入数据 Scanner sc = new Scanner(System.in); String choice = sc.nextLine(); //利用switch循环来判断 switch (choice) { case "1": System.out.println("欢迎来到注册界面!"); System.out.println("请输入用户名:"); String userName = sc.nextLine(); System.out.println("请输入密码:"); String passWord = sc.nextLine(); //把用户名和密码封装成一个用户类对象 User user = new User(userName,passWord); //通过用户操作类对象调用注册方法 udi.regist(user); System.out.println("注册成功!"); break; case "2": System.out.println("欢迎来到登录界面!"); System.out.println("请输入用户名:"); String inputUserName = sc.nextLine(); System.out.println("请输入密码:"); String inputPassWord = sc.nextLine(); //通过用户操作类对象调用登录方法 boolean flag = udi.isLogin(inputUserName,inputPassWord); if (flag) { System.out.println("登录成功,玩游戏吧!"); GuessNumber.playGame(); }else{ System.out.println("登录失败!"); } break; case "3": default: //对于3或者其他数字的选择,都直接退出系统 System.exit(0); break; } } } }<file_sep>/24Game/src/Service.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.Arrays; import java.util.HashMap; import java.util.Map.Entry; public class Service { public static void main(String[] args) { InputStream is = null; OutputStream os = null; ServerSocket serverSocket = null; Socket socket = null; try { serverSocket = new ServerSocket(6013); System.out.println("服务器已经启动!"); socket = serverSocket.accept(); // 从客户端读取数据,需要先转换为字符流 is = socket.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String str = str = br.readLine(); System.out.println("我是服务器,客户端输入的消息为:" + str); socket.shutdownInput(); // 对客户端输入的账号密码信息进行处理 String[] str2 = str.split("&"); HashMap<String, String> hm = new HashMap<>(); for (String str1 : str2) { String[] str3 = str1.split(":"); hm.put(str3[0], str3[1]); } String reply = "登录失败"; if ("chenkang".equals(hm.get("name")) && "<PASSWORD>".equals(hm.get("password"))) { reply = "登录成功,开始游戏!"; } // 向客户端发送消息 os = socket.getOutputStream(); os.write(reply.getBytes()); socket.shutdownOutput(); } catch (IOException e) { e.printStackTrace(); }finally { try { if (is != null) is.close(); if (os != null) os.close(); socket.close(); serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
93590dba7b73d08bdeec440a59d8b26629ce557f
[ "Java" ]
15
Java
chenkang123456/java
c62db48be7395122038535d02f7255595ece985b
dd9aa1f288ff2483d3e656f067589d5d64ae64c3
refs/heads/master
<file_sep>package br.com.tap.negocio; import java.util.List; public class Cliente extends Pessoa { private int idCli; private String email; private List<Telefone> telefones; private Endereco endereco; public Cliente() { } public Cliente(String cpf, String nome, String email, List<Telefone> telefones, Endereco endereco) { super(cpf, nome); setEmail(email); setTelefones(telefones); setEndereco(endereco); } public Cliente(String cpf, String nome, String email) { super(cpf, nome); setEmail(email); } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getIdCli() { return idCli; } public void setIdCli(int idCli) { this.idCli = idCli; } public List<Telefone> getTelefones() { return telefones; } public void setTelefones(List<Telefone> telefones) { this.telefones = telefones; } public Endereco getEndereco() { return endereco; } public void setEndereco(Endereco endereco) { this.endereco = endereco; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("idCli:" + getIdCli() + "\n"); sb.append("email: " + getEmail() + "\n"); sb.append("Nome: "+getNome()); return sb.toString(); } } <file_sep>package br.com.tap.dados; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import br.com.tap.negocio.Aluguel; public class RepositorioAluguel implements IRepositorioAluguel { private Connection conexao; public RepositorioAluguel() throws Exception { this.conexao = SingletonConexaoDB.getInstance().conectar(); } @Override public void inserirAluguel(Aluguel novoAluguel) throws Exception { if (novoAluguel != null) { PreparedStatement pstm = null; ResultSet rs = null; try { String sql = "INSERT INTO Aluguel(id_cli_fk, id_fun_fk, valor_total_alug, data_saida_alug, data_entrega_alug)" + "VALUES(?,?,?,?,?)"; pstm = this.conexao.prepareStatement(sql, java.sql.Statement.RETURN_GENERATED_KEYS); pstm.setInt(1,novoAluguel.getIdCliente()); pstm.setInt(2, novoAluguel.getIdFuncionario()); pstm.setDouble(3, novoAluguel.getValorTotal()); pstm.setString(4, novoAluguel.getDataSaida()); pstm.setString(5, novoAluguel.getDataEntrega()); pstm.executeUpdate(); rs = pstm.getGeneratedKeys(); if(rs.next()){ int idAlug = rs.getInt(1); novoAluguel.setIdAluguel(idAlug); } } finally { SingletonConexaoDB.getInstance().desconectar(conexao, pstm, rs); } } } @Override public void atualizarAluguel(Aluguel aluguel) throws Exception { // TODO Auto-generated method stub } public static void main(String[] args) { try { RepositorioAluguel repo = new RepositorioAluguel(); Aluguel aluguel = new Aluguel(); aluguel.setIdCliente(30); aluguel.setIdFuncionario(4); aluguel.setDataSaida("20/12/2014"); aluguel.setDataEntrega("27/12/2014"); aluguel.setValorTotal(1050.50); repo.inserirAluguel(aluguel); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>package br.com.tap.controle; import br.com.tap.dados.IRepositorioFuncionario; import br.com.tap.dados.RepositorioFuncionario; import br.com.tap.dados.SingletonConexaoDB; import br.com.tap.negocio.Funcionario; import br.com.tap.util.UtilGUI; public class CCadastroFuncionario { private IRepositorioFuncionario repositorioFun; public CCadastroFuncionario() throws Exception { this.repositorioFun = new RepositorioFuncionario(); } /* inserir um funcionario */ public boolean inserirFuncionario(Funcionario funcionario) { boolean result = false; try { this.repositorioFun.inserirFuncionario(funcionario); result = true; } catch (Exception e) { UtilGUI.erroMenssage("Cadastro-Funcionário", "Erro ao cadastrar funcionário"); } finally { try { SingletonConexaoDB.getInstance().desconectar(); } catch (Exception e) { e.printStackTrace(); } } return result; } public boolean removerFuncionario(String cpf) { boolean result = false; try { if (cpf != null) { repositorioFun.removerFuncionario(cpf); result = true; } } catch (Exception e) { UtilGUI.erroMenssage("Remover Funcionario", "Erro ao tentar remover funcionario!!!"); } finally { try { SingletonConexaoDB.getInstance().desconectar(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } return result; } public boolean atualizarFuncionario(Funcionario funcionario)throws Exception{ boolean result = false; try{ try{ }finally{ } }catch(Throwable e){ e.printStackTrace(); throw new Exception(e); } return result; } } <file_sep>package br.com.tap.dados; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.List; import br.com.tap.negocio.Roupa; import br.com.tap.negocio.Telefone; /*Criado a classe "Roupa", Projeto TAP P2 2014.2 Prof Allan Criada as classes: - Roupa, - RepositorioRoupa A Interface - IRepositorioRoupa //Adicionar campo, "codigoRoupa" na tabela do banco * DELETAR ISSO DEPOIS */ public class RepositorioRoupa implements IRepositorioRoupa { private Connection conexao = null; public RepositorioRoupa() throws Exception { this.conexao = SingletonConexaoDB.getInstance().conectar(); } @Override public void inserirRoupa(Roupa novaRoupa) throws Exception { if (novaRoupa != null) { PreparedStatement pstm = null; ResultSet rs = null; try { String sql; sql = "INSERT INTO Roupa() VALUES(?,?,?)"; pstm = this.conexao.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); pstm.setLong(1, novaRoupa.getCodigoRoupa()); pstm.setString(2, novaRoupa.getDescricao()); pstm.setDouble(3, novaRoupa.getValor()); pstm.executeUpdate(); rs = pstm.getGeneratedKeys(); if (rs.next()) { int idRoupa = rs.getInt(1); novaRoupa.setIdRoupa(idRoupa); } } finally { if (pstm != null) { pstm.close(); } if (rs != null) { rs.close(); } } } }// fim do método inserir @Override public void atualizarRoupa(Roupa Roupa) throws Exception { // TODO Auto-generated method stub } @Override public void removerRoupa(long codRoupa) throws Exception { PreparedStatement pstm = null; try { String sql; sql = "DELETE FROM Roupa WHERE codigo_roupa = ?"; pstm = this.conexao.prepareStatement(sql); pstm.setLong(1, codRoupa); pstm.executeUpdate(); } finally { if (pstm != null) { pstm.close(); } } } @Override public List<Roupa> listarRoupaPorNome(long codigoRoupa) { // TODO Auto-generated method stub return null; } } <file_sep>package br.com.tap.visao; import java.awt.BorderLayout; import java.awt.Container; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.border.EmptyBorder; public class TelaCadastroCliente extends JFrame { private PainelCadastroCliente painelCliente; private JTabbedPane tabbepane; public TelaCadastroCliente() throws Exception { setDefaultCloseOperation(DISPOSE_ON_CLOSE); setSize(610, 450); setLocationRelativeTo(null); setResizable(false); Container container = getContentPane(); container.setLayout(new BorderLayout()); painelCliente = new PainelCadastroCliente(); tabbepane = new JTabbedPane(); tabbepane.addTab("Cadastro", painelCliente); container.add(tabbepane, BorderLayout.CENTER); } public static void main(String[] args) { TelaCadastroCliente t; try { t = new TelaCadastroCliente(); t.setVisible(true); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>package br.com.tap.dados; import java.util.List; import br.com.tap.negocio.Telefone; public interface IRepositorioTelefone { public void inserirTel(Telefone telefone) throws Exception; public void atualizarTel(Telefone Telefone) throws Exception; public void removerTel(Integer id) throws Exception; public List<Telefone> listarPorCliente(Integer idCliente) throws Exception; public Telefone buscarPorId(Integer id) throws Exception; public List<Telefone> buscaPorNumero(String numero) throws Exception; } <file_sep>package br.com.tap.controle; import br.com.tap.dados.IRepositorioRoupa; import br.com.tap.dados.RepositorioRoupa; import br.com.tap.dados.SingletonConexaoDB; import br.com.tap.negocio.Roupa; import br.com.tap.util.UtilGUI; public class CCadastroRoupa { private IRepositorioRoupa repositorioRoupa; public CCadastroRoupa() throws Exception { this.repositorioRoupa = new RepositorioRoupa(); } public boolean inserirRoupa(Roupa novaRoupa) { boolean result = false; try { this.repositorioRoupa.inserirRoupa(novaRoupa); result = true; } catch (Exception e) { UtilGUI.erroMenssage("Cadastro-Roupa", "Erro ao cadastrar roupa!!!"); } finally { try { SingletonConexaoDB.getInstance().desconectar(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } return result; } public boolean removerRoupa(long codRoupa) { boolean result = false; try { repositorioRoupa.removerRoupa(codRoupa); result = true; } catch (Exception e) { UtilGUI.erroMenssage("REMOVER ROUPA", "ERRO AO TENTAR REMOVER ROUPA"); } finally { try { SingletonConexaoDB.getInstance().desconectar(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } return result; } } <file_sep>package br.com.tap.dados; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import br.com.tap.negocio.Telefone; public class RepositorioTelefone implements IRepositorioTelefone { private Connection conexao = null; public RepositorioTelefone() throws Exception { this.conexao = SingletonConexaoDB.getInstance().conectar(); } @Override public void inserirTel(Telefone telefone) throws Exception { if (telefone != null) { PreparedStatement pstm = null; ResultSet rs = null; try { try { String sql = "INSERT INTO Telefone(id_fk_cli,tel_numero,tel_operadora) VALUES(?,?,?)"; pstm = this.conexao.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); pstm.setInt(1, telefone.getCliente().getIdCli()); pstm.setString(2, telefone.getNumero()); pstm.setString(3, telefone.getOperadora()); pstm.executeUpdate(); rs = pstm.getGeneratedKeys(); if (rs.next()) { int id = rs.getInt(1); telefone.setIdTelefone(id); System.out.println(telefone.getIdTelefone()); } } finally { if (pstm != null) { pstm.close(); } } } catch (SQLException e) { e.printStackTrace(); throw new Exception(e); } } }// fim do método inserir @Override public void atualizarTel(Telefone telefone) throws Exception { String sql = "UPDATE Telefone SET tel_numeto=?, tel_operadora=? WHERE id_tel=?"; PreparedStatement pstm = null; if (telefone != null) { try { try { pstm = this.conexao.prepareStatement(sql); pstm.setString(1, telefone.getNumero()); pstm.setString(2, telefone.getOperadora()); pstm.setInt(3, telefone.getIdTelefone()); pstm.executeUpdate(); } finally { if (pstm != null && !pstm.isClosed()) { pstm.close(); } } } catch (SQLException e) { e.printStackTrace(); throw new Exception(e); } } } @Override public void removerTel(Integer id) throws Exception { if (id != null) { String sql = "DELETE FROM Telefone WHERE id_fk_cli=?"; PreparedStatement pstm = null; try { try { pstm = this.conexao.prepareStatement(sql); pstm.setInt(1, id); pstm.executeUpdate(); } finally { if (pstm != null && !pstm.isClosed()) { pstm.close(); } } } catch (SQLException e) { e.printStackTrace(); throw new Exception(e); } } } @Override public List<Telefone> buscaPorNumero(String numero) throws Exception { List<Telefone> telefones = new ArrayList<Telefone>(); PreparedStatement pstm = null; ResultSet rs = null; Telefone telefone = null; if (numero != null) { String sql = "SELECT * FROM Telefone WHERE tel_numero=?"; pstm = this.conexao.prepareStatement(sql); pstm.setString(1, numero); rs = pstm.executeQuery(); while (rs.next()) { telefone = new Telefone(); telefone.setIdTelefone(rs.getInt(1)); telefone.setNumero(rs.getString(2)); telefone.setOperadora(rs.getString(3)); telefones.add(telefone); } try { try { } finally { if (pstm != null && !pstm.isClosed()) { pstm.close(); } } } catch (Exception e) { e.printStackTrace(); throw new Exception(e); } } return telefones; } @Override public List<Telefone> listarPorCliente(Integer idCliente) throws Exception { List<Telefone> telefones = new ArrayList<Telefone>(); if (idCliente != null) { String sql = "SELECT * FROM Telefone WHERE id_fk_cli=?"; PreparedStatement pstm = null; ResultSet rs = null; try { try { pstm = this.conexao.prepareStatement(sql); pstm.setInt(1, idCliente); rs = pstm.executeQuery(); while (rs.next()) { Telefone telefone = new Telefone(); telefone.setIdTelefone(rs.getInt(2)); telefone.setNumero(rs.getString(3)); telefone.setOperadora(rs.getString(4)); telefones.add(telefone); } } finally { if (pstm != null && !pstm.isClosed()) { pstm.close(); } } } catch (SQLException e) { e.printStackTrace(); throw new Exception(e); } } return telefones; } @Override public Telefone buscarPorId(Integer id) throws Exception { String sql = "SELECT * FROM Telefone WHERE id_tel=?"; PreparedStatement pstm = null; Telefone telefone = null; ResultSet rs = null; try { try { pstm = this.conexao.prepareStatement(sql); pstm.setInt(1, id); rs = pstm.executeQuery(); if (rs.next()) { telefone = new Telefone(); telefone.setIdTelefone(id); telefone.setNumero(rs.getString(2)); telefone.setOperadora(rs.getString(3)); } } finally { if (pstm != null && !pstm.isClosed()) { pstm.close(); } } } catch (Exception e) { e.printStackTrace(); throw new Exception(e); } return telefone; } } <file_sep>package br.com.tap.dados; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.List; import br.com.tap.negocio.Cliente; public class RepositorioCliente implements IRepositorioCliente { private Connection conexao; public RepositorioCliente() throws Exception { this.conexao = SingletonConexaoDB.getInstance().conectar(); } @Override public void inserirCliente(Cliente novoCliente) throws Exception { if (novoCliente != null) { PreparedStatement pstm = null; ResultSet rs = null; try { try { String sql = "INSERT INTO Cliente(cli_nome,cli_cpf,cli_email) VALUES(?,?,?)"; pstm = this.conexao.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); pstm.setString(1, novoCliente.getNome()); pstm.setString(2, novoCliente.getCpf()); pstm.setString(3, novoCliente.getEmail()); pstm.executeUpdate(); rs = pstm.getGeneratedKeys(); if (rs.next()) { int idCli = rs.getInt(1); novoCliente.setIdCli(idCli); } } finally { if (pstm != null && !pstm.isClosed()) { pstm.close(); } } } catch (SQLException e) { e.printStackTrace(); throw new Exception(e); } } } @Override public void removerClientePorId(Integer id) throws Exception { if (id != null) { PreparedStatement pstm = null; try { String sql = "DELETE FROM Cliente WHERE id_cli=?"; pstm = this.conexao.prepareStatement(sql); pstm.setInt(1, id); pstm.executeUpdate(); try { } finally { if (pstm != null && !pstm.isClosed()) { pstm.close(); } } } catch (Exception e) { e.printStackTrace(); throw new Exception(e); } } } @Override public void alualizarCliente(Cliente cliente) throws Exception { if (cliente != null) { PreparedStatement pstm = null; try { try { String sql = "UPDATE Cliente SET cli_nome=?,cli_cpf=?,cli_email=? WHERE id_cli=?"; pstm = this.conexao.prepareStatement(sql); pstm.setString(1, cliente.getNome()); pstm.setString(2, cliente.getCpf()); pstm.setString(3, cliente.getEmail()); pstm.executeUpdate(); } finally { if (pstm != null && !pstm.isClosed()) { pstm.close(); } } } catch (Exception e) { e.printStackTrace(); throw new Exception(e); } } } @Override public Cliente buscarPorId(Integer id) throws Exception { Cliente cliente = null; if (id != null) { PreparedStatement pstm = null; ResultSet rs = null; try { try { String sql = "SELECT * FROM Cliente WHERE id_cli=?"; pstm = this.conexao.prepareStatement(sql); pstm.setInt(1, id); rs = pstm.executeQuery(); if (rs.next()) { cliente = new Cliente(); cliente.setIdCli(id); cliente.setNome(rs.getString(2)); cliente.setCpf(rs.getString(3)); cliente.setEmail(rs.getString(4)); } } finally { if (pstm != null && !pstm.isClosed()) { pstm.close(); } } } catch (Exception e) { e.printStackTrace(); throw new Exception(e); } } return cliente; } @Override public Cliente buscarPorCpf(String cpf) throws Exception { Cliente cliente = null; if (cpf != null) { PreparedStatement pstm = null; ResultSet rs = null; try { try { String sql = "SELECT * FROM Cliente WHERE cli_cpf=?"; pstm = this.conexao.prepareStatement(sql); pstm.setString(1, cpf); rs = pstm.executeQuery(); if (rs.next()) { cliente = new Cliente(); cliente.setCpf(cpf); cliente.setNome(rs.getString(2)); cliente.setEmail(rs.getString(3)); } } finally { if (pstm != null) { pstm.close(); } if (rs != null) { rs.close(); } } } catch (Exception e) { e.printStackTrace(); throw new Exception(e); } } return cliente; } @Override public List<Cliente> listarPorNome(String nome) throws Exception { if (nome != null) { PreparedStatement pstm = null; try { try { } finally { if (pstm != null && !pstm.isClosed()) { pstm.close(); } } } catch (Exception e) { e.printStackTrace(); throw new Exception(e); } } return null; } @Override public List<Cliente> listar() throws Exception { PreparedStatement pstm = null; try { try { } finally { if (pstm != null && !pstm.isClosed()) { pstm.close(); } } } catch (Exception e) { e.printStackTrace(); throw new Exception(e); } return null; } public static void main(String[] args) { try { RepositorioCliente r = new RepositorioCliente(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } <file_sep>package br.com.tap.visao; import javax.swing.JPanel; import java.awt.BorderLayout; import javax.swing.border.TitledBorder; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.UIManager; import javax.swing.JButton; import br.com.tap.comunicacao.Fachada; import br.com.tap.comunicacao.IFachada; import br.com.tap.negocio.Cliente; import br.com.tap.negocio.Endereco; import br.com.tap.negocio.Telefone; import br.com.tap.util.UtilGUI; public class PainelCadastroCliente extends JPanel { private final JPanel panel = new JPanel(); private JTextField textNome; private JTextField textCpf; private JTextField textEmail; private JTextField textFone; private JTextField textCel; private JTextField textOperadoraCel; private JTextField textOperadoraFone; private JTextField textCep; private JTextField textCidade; private JTextField textBairro; private JTextField textNumero; private JTextField textComplemento; private JTextField textEstado; private JButton btnSalvar; private JButton btnNovo; private JButton btnSair; private IFachada fachada; public PainelCadastroCliente() throws Exception { this.fachada = new Fachada(); setLayout(new BorderLayout(0, 0)); panel.setBorder(new TitledBorder(null, "Cadastro-Cliente", TitledBorder.LEADING, TitledBorder.TOP, null, Color.BLUE)); add(panel, BorderLayout.CENTER); panel.setLayout(null); JLabel lblNome = new JLabel("Nome:"); lblNome.setBounds(20, 40, 46, 14); panel.add(lblNome); textNome = new JTextField(); textNome.setBounds(66, 37, 293, 20); panel.add(textNome); textNome.setColumns(10); JLabel lblCpf = new JLabel("CPF:"); lblCpf.setBounds(369, 40, 46, 14); panel.add(lblCpf); textCpf = new JTextField(); textCpf.setBounds(396, 37, 194, 20); panel.add(textCpf); textCpf.setColumns(10); JLabel lblEmail = new JLabel("E-mail:"); lblEmail.setBounds(20, 78, 46, 14); panel.add(lblEmail); textEmail = new JTextField(); textEmail.setBounds(66, 75, 189, 20); panel.add(textEmail); textEmail.setColumns(10); JLabel lblFone = new JLabel("Fone:"); lblFone.setBounds(20, 117, 46, 14); panel.add(lblFone); textFone = new JTextField(); textFone.setBounds(66, 114, 118, 20); panel.add(textFone); textFone.setColumns(10); JLabel lblNewLabel = new JLabel("Cel:"); lblNewLabel.setBounds(20, 155, 46, 14); panel.add(lblNewLabel); textCel = new JTextField(); textCel.setColumns(10); textCel.setBounds(66, 152, 118, 20); panel.add(textCel); textOperadoraCel = new JTextField(); textOperadoraCel.setColumns(10); textOperadoraCel.setBounds(285, 152, 118, 20); panel.add(textOperadoraCel); JLabel lblOperadoraCel = new JLabel("Operadora Cel:"); lblOperadoraCel.setBounds(194, 155, 106, 14); panel.add(lblOperadoraCel); JLabel lblOperadoraFone = new JLabel("Operadora Fone:"); lblOperadoraFone.setBounds(194, 117, 106, 14); panel.add(lblOperadoraFone); textOperadoraFone = new JTextField(); textOperadoraFone.setColumns(10); textOperadoraFone.setBounds(297, 114, 118, 20); panel.add(textOperadoraFone); JLabel lblCep = new JLabel("CEP:"); lblCep.setBounds(20, 192, 46, 14); panel.add(lblCep); textCep = new JTextField(); textCep.setColumns(10); textCep.setBounds(66, 189, 118, 20); panel.add(textCep); JLabel lblCidade = new JLabel("Cidade:"); lblCidade.setBounds(194, 192, 74, 14); panel.add(lblCidade); textCidade = new JTextField(); textCidade.setColumns(10); textCidade.setBounds(247, 189, 118, 20); panel.add(textCidade); JLabel lblBairro = new JLabel("Bairro:"); lblBairro.setBounds(377, 192, 57, 14); panel.add(lblBairro); textBairro = new JTextField(); textBairro.setColumns(10); textBairro.setBounds(428, 189, 162, 20); panel.add(textBairro); JLabel lblNmero = new JLabel("N\u00FAmero: "); lblNmero.setBounds(20, 230, 79, 14); panel.add(lblNmero); textNumero = new JTextField(); textNumero.setColumns(10); textNumero.setBounds(76, 227, 75, 20); panel.add(textNumero); JLabel lblComplemento = new JLabel("Complemento:"); lblComplemento.setBounds(177, 230, 106, 14); panel.add(lblComplemento); textComplemento = new JTextField(); textComplemento.setColumns(10); textComplemento.setBounds(268, 227, 135, 20); panel.add(textComplemento); JLabel lblNewLabel_1 = new JLabel("Estado:"); lblNewLabel_1.setBounds(415, 230, 57, 14); panel.add(lblNewLabel_1); textEstado = new JTextField(); textEstado.setColumns(10); textEstado.setBounds(472, 227, 118, 20); panel.add(textEstado); JPanel panel_1 = new JPanel(); panel_1.setBorder(new TitledBorder(UIManager .getBorder("TitledBorder.border"), "Opera\u00E7\u00F5es", TitledBorder.LEADING, TitledBorder.TOP, null, Color.BLUE)); panel_1.setBounds(20, 259, 570, 130); panel.add(panel_1); panel_1.setLayout(null); btnSalvar = new JButton("Salvar"); btnSalvar.setBounds(75, 53, 89, 23); btnSalvar.addActionListener(new TrataEventos()); panel_1.add(btnSalvar); btnNovo = new JButton("Novo"); btnNovo.setBounds(239, 53, 89, 23); panel_1.add(btnNovo); btnSair = new JButton("Sair"); btnSair.setBounds(403, 53, 89, 23); panel_1.add(btnSair); } private class TrataEventos implements ActionListener { @Override public void actionPerformed(ActionEvent e) { try { if (e.getSource() == btnSalvar) { String nome = textNome.getText(); String cpf = textCpf.getText(); String email = textEmail.getText(); String fone = textFone.getText(); String cel = textCel.getText(); String operadoraFone = textOperadoraFone.getText(); String operadoraCel = textOperadoraCel.getText(); String cep = textCep.getText(); String cidade = textCidade.getText(); String bairro = textBairro.getText(); int numero = Integer.parseInt(textNumero.getText()); String complemento = textComplemento.getText(); String estado = textEstado.getText(); List<Telefone> telefones = new ArrayList<Telefone>(); Cliente cliente = new Cliente(cpf, nome, email); Endereco end = new Endereco(cep, bairro, numero, cidade, estado, complemento, cliente); Telefone telCel = new Telefone(cliente, cel, operadoraCel); Telefone telFone = new Telefone(cliente, fone, operadoraFone); telefones.add(telCel); telefones.add(telFone); cliente.setEndereco(end); cliente.setTelefones(telefones); if (fachada.inserirCliente(cliente)) { UtilGUI.sucessoMensagem("Cadastro-Cliente", "Cliente " + cliente.getNome() + "\ncadastrado com sucesso!!!"); } } } catch (Exception ex) { ex.printStackTrace(); } } } }
7fb191ba2b547cf9bbd62b5dd1a05e5ffd184b06
[ "Java" ]
10
Java
DiSantos/SisAluguel
c1eddbde34582b535c1d39fcd33a94b3821ad190
90fad8dc53a4d535bb97672af8beca0044ee052b
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using RabbitMQ.Client; using RabbitMQ.Client.Events; using System.IO; using System.Xml.Serialization; namespace WorkerSweetDreams { class Program { public static List<WorkerUser> listOfUsers=new List<WorkerUser>(); public static readonly string pathToUsers = "WorkerUsers.xml"; public static WorkerUser currentUser; static void Main(string[] args) { listOfUsers = GetUsers(); var factory = new ConnectionFactory() { HostName = "localhost" }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { channel.QueueDeclare(queue: "q1", durable: false, exclusive: false, autoDelete: false, arguments: null); channel.BasicQos(0, 1, false); var consumer = new EventingBasicConsumer(channel); channel.BasicConsume(queue: "q1", autoAck: false, consumer: consumer); Console.WriteLine(" [x] Awaiting requests"); consumer.Received += (model, ea) => { string response = null; var body = ea.Body; var props = ea.BasicProperties; var replyProps = channel.CreateBasicProperties(); replyProps.CorrelationId = props.CorrelationId; try { var message = Encoding.UTF8.GetString(body); string[] userData = message.Split(' '); Console.WriteLine($" Recived request from User Id {userData[0]}"); for(int i = 0; i < listOfUsers.Count;i++) { if (listOfUsers[i].UserID == Int32.Parse(userData[0])) { response = "You ve alredy sent request. Wait!!!"; goto somePoint; } } AddUser(userData); if (listOfUsers.Count >= 3) { response = MatchPair(currentUser).ToString(); } else { response = "Our base of people is too small"; } somePoint: ; } catch (Exception e) { Console.WriteLine(" [.] " + e.Message); response = "something has gone wrong "; } finally { var responseBytes = Encoding.UTF8.GetBytes(response); channel.BasicPublish(exchange: "", routingKey: props.ReplyTo, basicProperties: replyProps, body: responseBytes); channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false); } }; Console.WriteLine(" Press [enter] to exit."); Console.ReadLine(); } } public static bool CreateUser(WorkerUser addUser) { List<WorkerUser> Users = GetUsers(); Users.Add(addUser); XmlSerializer formatter = new XmlSerializer(typeof(List<WorkerUser>)); try { using (FileStream fs = new FileStream(pathToUsers, FileMode.OpenOrCreate)) { formatter.Serialize(fs, Users); } return true; } catch (Exception) { return false; } } public static List<WorkerUser> GetUsers() { List<WorkerUser> Users = new List<WorkerUser>(); XmlSerializer formatter = new XmlSerializer(typeof(List<WorkerUser>)); FileInfo fi = new FileInfo(pathToUsers); if (fi.Exists) { using (FileStream fs = new FileStream(pathToUsers, FileMode.OpenOrCreate)) { Users = (List<WorkerUser>)formatter.Deserialize(fs); } } return Users == null ? new List<WorkerUser>() : Users; } public static void AddUser(string[] user) { WorkerUser newUser = new WorkerUser(); newUser.UserID=Int32.Parse(user[0]); newUser.PersonalKey = new Guid(user[1]); newUser.Gender= (user[2] == "Male") ? gender.Male : gender.Female; newUser.LookingFor = (user[3] == "Male") ? gender.Male : gender.Female; listOfUsers.Add(newUser); CreateUser(newUser); currentUser = newUser; } public static int MatchPair(WorkerUser user) { int id = 0; foreach (var u in listOfUsers) { if (user.UserID != u.UserID && user.LookingFor == u.Gender) { id = u.UserID; listOfUsers.Remove(user); listOfUsers.Remove(u); break; } } File.Delete(pathToUsers); XmlSerializer formatter = new XmlSerializer(typeof(List<WorkerUser>)); try { using (FileStream fs = new FileStream(pathToUsers, FileMode.OpenOrCreate)) { formatter.Serialize(fs, listOfUsers); } } catch (Exception) { } return id; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WorkerSweetDreams { public enum gender { Male, Female }; public class WorkerUser { public int UserID { get; set; } public Guid PersonalKey { get; set; } public gender Gender { get; set; } public gender LookingFor { get; set; } } }
a2ddeeca254653c4d97edb6337be9207dbd798dd
[ "C#" ]
2
C#
danofff/WorkerSweetDreams
b4cf1bf40d33d0b4dd6946246a61da91d5c5d564
86692a4306a61b1eb4c50508450ad24a9d94fc55
refs/heads/master
<repo_name>rodolfocampos/curso-python<file_sep>/README.md # curso-python Testando Python <file_sep>/adivinhacao.py import random def jogar(): imprime_boas_vindas() iniciar_jogo() def imprime_boas_vindas(): print("*********************************\n") print("Bem vindo ao jogo de adivinhacão!\n") print("*********************************\n") def selecionar_dificuldade(): print("Qual o nível de dificuldade?") print("(1) Fácil (2) Médio (3) Difícil") nivel = int(input("Defina o nível: ")) if nivel == 1: tentativas = 10 elif nivel == 2: tentativas = 6 elif nivel == 3: tentativas = 3 else: selecionar_dificuldade() return tentativas def iniciar_jogo(): numero_secreto = int(random.randint(1, 50)) pontos = 1000 total_de_tentativas = selecionar_dificuldade() for rodada in range(1, total_de_tentativas + 1): print("Tentativa {} de {}\n".format(rodada, total_de_tentativas)) chute = int(input("Digite o um numero entre 1 e 50: ")) print("\n*********************************\n") print("Você digitou {}\n".format(chute)) if chute < 1 or chute > 50: continue acertou = chute == numero_secreto maior = chute > numero_secreto menor = chute < numero_secreto if acertou: print("Você acertou e fez {} pontos!\n".format(pontos)) break else: if maior: print("Você errou! O seu chute foi maior que o número secreto.\n") elif menor: print("Você errou! O seu chute foi menor que o número secreto.\n") pontos_perdidos = round(abs(numero_secreto - chute)) pontos = pontos - pontos_perdidos if rodada == total_de_tentativas: print("O número secreto era {}. Você fez {} pontos".format(numero_secreto, pontos)) print("Fim do jogo") if __name__ == "__main__": jogar() <file_sep>/forca.py import random def jogar(): imprime_msg_boas_vindas() palavras = busca_palavras_no_arquivo() palavra_secreta = get_palavra_secreta(palavras) inicia_loop_jogo(palavra_secreta) def imprime_msg_boas_vindas(): print("*********************************\n") print("Bem vindo ao jogo da forca!\n") print("*********************************\n") def busca_palavras_no_arquivo(): with open("palavras.txt") as arquivo: palavras = [] for linha in arquivo: linha = linha.strip() palavras.append(linha) arquivo.close() return palavras def get_palavra_secreta(palavras): sorteio = int(random.randint(1, len(palavras))) palavra_secreta = palavras[sorteio].upper() return palavra_secreta def inicia_loop_jogo(palavra_secreta): letras_acertadas = ["_" for letra in palavra_secreta] enforcou = False acertou = False erros = 0 print("A palavra secreta contem: {}\n".format(letras_acertadas)) while not acertou and not enforcou: chute = input("Qual letra? ") chute = chute.strip().upper() if chute in palavra_secreta: index = 0 for letra in palavra_secreta: if chute == letra: letras_acertadas[index] = letra print("\nEncontrei as letras na posição {}\n".format(letras_acertadas)) index += 1 acertou = "_" not in letras_acertadas else: erros += 1 print("\nOps, você errou! Faltam {} tentativas.".format(6 - erros)) enforcou = (erros == 7) desenha_forca(erros) print("\nFim do jogo\n") if acertou: imprime_mensagem_vencedor() else: imprime_mensagem_perdedor(palavra_secreta) def imprime_mensagem_perdedor(palavra_secreta): print("Puxa, você foi enforcado!") print("A palavra era {}".format(palavra_secreta)) print(" _______________ ") print(" / \ ") print(" / \ ") print("// \/\ ") print("\| XXXX XXXX | / ") print(" | XXXX XXXX |/ ") print(" | XXX XXX | ") print(" | | ") print(" \__ XXX __/ ") print(" |\ XXX /| ") print(" | | | | ") print(" | I I I I I I I | ") print(" | I I I I I I | ") print(" \_ _/ ") print(" \_ _/ ") print(" \_______/ ") def imprime_mensagem_vencedor(): print("Parabéns, você ganhou!") print(" ___________ ") print(" '._==_==_=_.' ") print(" .-\\: /-. ") print(" | (|:. |) | ") print(" '-|:. |-' ") print(" \\::. / ") print(" '::. .' ") print(" ) ( ") print(" _.' '._ ") print(" '-------' ") def desenha_forca(erros): print(" _______ ") print(" |/ | ") if erros == 1: print(" | (_) ") print(" | ") print(" | ") print(" | ") if erros == 2: print(" | (_) ") print(" | \ ") print(" | ") print(" | ") if erros == 3: print(" | (_) ") print(" | \| ") print(" | ") print(" | ") if erros == 4: print(" | (_) ") print(" | \|/ ") print(" | ") print(" | ") if erros == 5: print(" | (_) ") print(" | \|/ ") print(" | | ") print(" | ") if erros == 6: print(" | (_) ") print(" | \|/ ") print(" | | ") print(" | / ") if erros == 7: print(" | (_) ") print(" | \|/ ") print(" | | ") print(" | / \ ") print(" | ") print("_|___ ") print() if __name__ == "__main__": jogar()
081113b3437b339037f7b88c750472f38e782a05
[ "Markdown", "Python" ]
3
Markdown
rodolfocampos/curso-python
4df206244360e25ad08ac3cc1efae71919021075
50072858418152628360fbbcc538bf43ec40c82d
refs/heads/master
<repo_name>MMurlyka/lp-earnings-on-the-land<file_sep>/js/main.js $(window).load(function() { if(!isMobile.any) { new WOW().init(); } }); $(window).ready(function() { /* Timer Start */ if($.cookie('timer')) { $timer = new Date(+$.cookie('timer')); if($timer < new Date()) { $.cookie('timer', null); } } if(!$.cookie('timer') || $.cookie('timer') == "null") { $date = new Date(); $timer = new Date($date.setMinutes($date.getMinutes() + 30)); $.cookie('timer', $timer.getTime()); } $('#clock').countdown($timer, function(event) { $(this).html(event.strftime('<span class="circle"><span class="nn">%M</span></span> : <span class="circle"><span class="nn">%S</span></span>')); }); /* Timer End*/ /* Slick slider Start*/ $(".slick").slick({ slidesToShow: 1, arrows: true, dots: true, autoplay: true, responsive: [ { breakpoint: 768, settings: { dots: false, arrows: false, adaptiveHeight: true, autoplay: false } }] }); /* Slick slider End*/ /* Form star */ $("form").submit(function() { var $email = $(this).find(".in-email"), reg = /.+@.+\..+/i; if(!~$email.val().search(reg)) { $email.addClass("invalid"); return false; } $(this).attr("method", "GET"); yaCounter36798385.reachGoal('form'); $email.removeClass("invalid"); }); /* Form end */ /* Popup start */ $(".link-mgf").magnificPopup(); /* Popup end */ });
bfea234d94ce591ee662b6992841f9863de88cf8
[ "JavaScript" ]
1
JavaScript
MMurlyka/lp-earnings-on-the-land
783b40a5280aee26831a22e5ffd7fda5a57ec5eb
5ed81f0c0eed542eaf2c2f04e03e4e2e334415bb
refs/heads/master
<file_sep># vue-vuex vuex <file_sep>import Vue from "vue"; import Vuex from "vuex"; import Axios from "axios"; Vue.use(Vuex); export const store = new Vuex.Store({ state: { name: "arda", post_title: "Default title", post_content: "Default content" }, mutations: { // Commit state updatePostTitle(state, post_title) { console.log("updatePostTitle triggered"); state.post_title = post_title; }, updatePostContent(state, post_content) { console.log("updatePostContent triggered"); state.post_content = post_content; }, // Commit state using Object-Style Commit SET_CONTENT: (state, payload) => { state.post_content = payload.body; state.post_title = payload.title; } }, getters: { POST_TITLE: state => { return state.post_title; }, POST_CONTENT: state => { return state.post_content; } }, actions: { // load content from server LOAD_CONTENT: async (context, payload) => { let { data } = await Axios.get( "https://jsonplaceholder.typicode.com/posts/1" ); console.log(data); context.commit("SET_CONTENT", data); } } });
d285eb466465be671473a6d6e39f380a2febb2cc
[ "Markdown", "JavaScript" ]
2
Markdown
alexanderarda/vue-vuex
9aae612313317f7f53a42e2c179a07d7339e3f9e
13017100fa9af286053193696a1a1df55c068a75
refs/heads/master
<repo_name>daniel-madera/paa-android-ares<file_sep>/app/src/main/java/cz/tul/nti/paa/ares/exception/DownloadFileException.java package cz.tul.nti.paa.ares.exception; /** * Created by daniel on 1/11/15. */ public class DownloadFileException extends RuntimeException { public DownloadFileException() { super(); } public DownloadFileException(String s) { super(s); } public DownloadFileException(String s, Throwable throwable) { super(s, throwable); } public DownloadFileException(Throwable throwable) { super(throwable); } } <file_sep>/app/src/main/java/cz/tul/nti/paa/ares/data/objects/Company.java package cz.tul.nti.paa.ares.data.objects; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.security.acl.Owner; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Collection; import java.util.List; import cz.tul.nti.paa.ares.data.adapters.XmlParser; public class Company { private static final String ns = null; private int ico; private String name; private Address address; private double deposit; private List<String> subjects; private CompanyType companyType; private List<Person> owners; public Company(int ico, String name, String street, String city, int zip, CompanyType companyType, long deposit) { this.ico = ico; this.name = name; this.companyType = companyType; this.deposit = deposit; owners = new ArrayList<Person>(); subjects = new ArrayList<String>(); } public Company() { owners = new ArrayList<Person>(); subjects = new ArrayList<String>(); } public Company(int ico) { owners = new ArrayList<Person>(); subjects = new ArrayList<String>(); } public void setIco(int ico) { this.ico = ico; } public int getIco() { return ico; } public String getName() { return name; } public List<String> getSubjects() { return subjects; } public CompanyType getCompanyType() { return companyType; } public List<Person> getOwners() { return owners; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public void setName(String name) { this.name = name; } public double getDeposit() { return deposit; } public String getReadableDeposit() { DecimalFormat decimalFormat = new DecimalFormat(" 000.00"); return decimalFormat.format(deposit); } public void setDeposit(double deposit) { this.deposit = deposit; } public void addSubject(String subject) { subjects.add(subject); } public void setCompanyType(CompanyType companyType) { this.companyType = companyType; } public void addOwner(Person p) { owners.add(p); } } <file_sep>/README.md paa-android-ares ================ ARES <file_sep>/app/src/main/java/cz/tul/nti/paa/ares/data/objects/CompanySimple.java package cz.tul.nti.paa.ares.data.objects; public class CompanySimple { private String ico; private String name; private String address; private String person; public CompanySimple() {} public CompanySimple(String ico, String name, String address, String person) { this.ico = ico; this.name = name; this.address = address; this.person = person; } public String getIco() { return ico; } public void setIco(String ico) { this.ico = ico; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPerson() { return person; } public void setPerson(String person) { this.person = person; } } <file_sep>/app/src/main/java/cz/tul/nti/paa/ares/exception/NoDataFoundException.java package cz.tul.nti.paa.ares.exception; /** * Created by daniel on 1/13/15. */ public class NoDataFoundException extends RuntimeException { public NoDataFoundException() { super(); } public NoDataFoundException(String s) { super(s); } public NoDataFoundException(String s, Throwable throwable) { super(s, throwable); } public NoDataFoundException(Throwable throwable) { super(throwable); } }<file_sep>/app/src/main/java/cz/tul/nti/paa/ares/data/adapters/AresXmlCompanyParser.java package cz.tul.nti.paa.ares.data.adapters; import android.content.res.Resources; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import cz.tul.nti.paa.ares.data.objects.Address; import cz.tul.nti.paa.ares.data.objects.Company; import cz.tul.nti.paa.ares.data.objects.CompanySimple; import cz.tul.nti.paa.ares.exception.NoDataFoundException; public class AresXmlCompanyParser extends XmlParser { public AresXmlCompanyParser(InputStream in, String encoding) throws XmlPullParserException { super(in, encoding); } public List<CompanySimple> parse() throws IOException, XmlPullParserException { List<CompanySimple> companies = new ArrayList<CompanySimple>(); moveToTag("are:Odpoved"); int count = Integer.parseInt(readTag("are:Pocet_zaznamu")); if(count == 0) { throw new NoDataFoundException(); } CompanySimple company; for(int i = 0; i < count; i++) { company = new CompanySimple(); readSimpleCompany(company); companies.add(company); } return companies; } public void readSimpleCompany(CompanySimple company) throws XmlPullParserException, IOException { moveToTag("are:Zaznam"); company.setName(readTag("are:Obchodni_firma")); company.setIco(readTag("are:ICO")); company.setAddress(readTag("dtt:Nazev_obce") + ", " + readTag("dtt:PSC")); moveToEndTag("are:Zaznam"); } } <file_sep>/app/src/main/java/cz/tul/nti/paa/ares/data/objects/CompanyType.java package cz.tul.nti.paa.ares.data.objects; import android.content.res.Resources; /** * Created by daniel on 1/5/15. */ public enum CompanyType { AS(121, "Akciová společnost"), SRO(112, "Společnost s ručeným omezeným"), COOPERATIVES(205, "Druzstvo"); private int id; private String name; private CompanyType(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public String getName() { return name; } public static CompanyType valueOf(int id) { CompanyType[] types = CompanyType.values(); for(CompanyType type : types) { if(type.getId() == id) { return type; } } throw new RuntimeException("Company Type not found."); } } <file_sep>/app/src/main/java/cz/tul/nti/paa/ares/exception/DataParsingException.java package cz.tul.nti.paa.ares.exception; public class DataParsingException extends RuntimeException { public DataParsingException() { super(); } public DataParsingException(String s) { super(s); } public DataParsingException(String s, Throwable throwable) { super(s, throwable); } public DataParsingException(Throwable throwable) { super(throwable); } } <file_sep>/app/src/main/java/cz/tul/nti/paa/ares/data/adapters/AresDataAdapter.java package cz.tul.nti.paa.ares.data.adapters; import android.net.Uri; import android.os.Environment; import android.util.Log; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import java.util.List; import cz.tul.nti.paa.ares.data.objects.Address; import cz.tul.nti.paa.ares.data.objects.Company; import cz.tul.nti.paa.ares.data.objects.CompanySimple; import cz.tul.nti.paa.ares.exception.DataParsingException; import cz.tul.nti.paa.ares.exception.DownloadFileException; import cz.tul.nti.paa.ares.exception.NoDataFoundException; public class AresDataAdapter { protected final String dataDirectory = "/ares"; public AresDataAdapter() { } public Company getDataByIco(String ico) { try { Uri uri = AresUrlCreator.getIcoUrl(ico, null); Log.i("Requested URL", uri.toString()); downloadFile(uri, "ico-data"); File f = getFile("ico-data"); AresXmlIcoParser aresXmlIcoParser = new AresXmlIcoParser(new FileInputStream(f), null); return aresXmlIcoParser.parse(); } catch(NoDataFoundException | DownloadFileException e) { throw e; } catch(Exception e) { throw new DataParsingException(e.getMessage()); } } public List<CompanySimple> getDataByCompanyName(String companyName, String city) { try { HashMap<String, String> parameters = new HashMap<>(); parameters.put("max_pocet", "50"); if(!city.isEmpty()) { parameters.put("nazev_obce", city); } Uri uri = AresUrlCreator.getCompanyUrl(companyName, parameters); Log.i("Requested URL", uri.toString()); downloadFile(uri, "companies-data"); File f = getFile("companies-data"); AresXmlCompanyParser aresXmlCompanyParser = new AresXmlCompanyParser( new FileInputStream(f), null); return aresXmlCompanyParser.parse(); } catch(NoDataFoundException | DownloadFileException e) { throw e; } catch(Exception e) { throw new DataParsingException(e.getMessage()); } } public List<CompanySimple> getDataByPersonName(String companyName, String street, String city, String zip) { try { HashMap<String, String> parameters = new HashMap<>(); parameters.put("maxpoc", "500"); if(!city.isEmpty()) { parameters.put("obec", city); } if(!zip.isEmpty()) { parameters.put("psc", zip); } if(!street.isEmpty()) { parameters.put("adresa", street); } Uri uri = AresUrlCreator.getPersonUrl(companyName, parameters); Log.i("Requested URL", uri.toString()); downloadFile(uri, "persons-data"); File f = getFile("persons-data"); AresXmlPersonParser aresXmlPersonParser = new AresXmlPersonParser( new FileInputStream(f), null); return aresXmlPersonParser.parse(); } catch(NoDataFoundException | DownloadFileException e) { throw e; } catch(Exception e) { throw new DataParsingException(e.getMessage()); } } protected File getDir() { File root = Environment.getExternalStorageDirectory(); File dir = new File (root.getAbsolutePath() + dataDirectory); if(!dir.exists()) { dir.mkdirs(); } return dir; } protected File getFile(String fileName) { return new File(getDir(), fileName); } public void downloadFile(Uri uri, String fileName) throws DownloadFileException { int count; try { URL url = new URL(uri.toString()); URLConnection connection = url.openConnection(); connection.connect(); InputStream input = new BufferedInputStream(url.openStream(), 8192); File outputFile = getFile(fileName); OutputStream output = new FileOutputStream(outputFile); byte data[] = new byte[1024]; while ((count = input.read(data)) != -1) { output.write(data, 0, count); } output.flush(); output.close(); input.close(); } catch (Exception e) { throw new DownloadFileException(e.getMessage()); } } }
ce82cf040a533633204c56b98a475eb6cd34132e
[ "Markdown", "Java" ]
9
Java
daniel-madera/paa-android-ares
56ed1388f6103c582df1ba6159c6a474d0c0991a
811c4dee5b87869b54d078756f45170b64f6a2e7
refs/heads/master
<repo_name>aminems/PerfStat<file_sep>/parallel.cpp #include "PerfStat.h" #include<cmath> #include<iostream> #include<omp.h> template<typename T> // typedef float T; inline T polyHorner(T y) { return T(0x2.p0) + y * (T(0x2.p0) + y * (T(0x1.p0) + y * (T(0x5.55523p-4) + y * (T(0x1.5554dcp-4) + y * (T(0x4.48f41p-8) + y * T(0xb.6ad4p-12)))))) ; } int main() { bool ret=true; std::cout << "number of threads " << omp_get_num_threads() << " " << omp_get_max_threads() << std::endl; { PerfStat perf; // will vectorize 256 only with avx2 (because of the int) float s =0; for (int k=0; k!=100; ++k) { perf.start(); #pragma omp parallel reduction (+ : s) { float c = 1.f/1000000.f; float v=0; for (int i=1; i<10000001; ++i) s+= polyHorner((++v)*c); } // end omp parallel perf.stop(); } ret &= s!=0; //std::cout << " " << s << std::endl; std::cout << "|Parallel all "; perf.print(std::cout,true); } { PerfStat perf; // will vectorize 256 only with avx2 (because of the int) float s =0; for (int k=0; k!=100; ++k) { perf.start(); #pragma omp parallel reduction (+ : s) { float c = 1.f/1000000.f; float v=0; int N = 10000000; int NT = N/omp_get_num_threads(); // ok I know there is nothing left v += NT* omp_get_thread_num(); for (int i=0; i<NT; ++i) s+= polyHorner((++v)*c); } // end omp parallel perf.stop(); } ret &= s!=0; //std::cout << " " << s << std::endl; std::cout << "|Parallel for "; perf.print(std::cout,true); } return ret ? 0 : 1; } <file_sep>/UnitTest.cpp #include "PerfStat.h" /* self consistency test * (aka Unit test) * does not validate the counter content inself; */ #include<iostream> #define test_verify(expr) \ if (!(expr)) { std::cout << #expr << " failed" << std::endl;} int main(int argc, char **) { int ret = 0; double resolution = 0.01; auto ok = [=](double x, double y) { return std::abs((x-y)/y)<resolution;}; PerfStat ps; std::cout << "we are " << (PerfStat::isINTEL() ? "on" : "not on") << " an INTEL Machine. Model "; printf("%x",PerfStat::modelNumber()); std::cout<< std::endl; std::cout << "|test "; ps.header(std::cout); std::cout << "|test "; ps.header(std::cout,true); bool debug = argc>1; test_verify(0==ps.calls()); test_verify(0==ps.callsTot()); test_verify(0==ps.read()); ps.calib(); test_verify(0==ps.calls()); test_verify(0==ps.callsTot()); test_verify(0==ps.cyclesRaw()); test_verify(0==ps.instructionsRaw()); test_verify(0==ps.taskTimeRaw()); test_verify(0==ps.realTimeRaw()); ps.start();ps.stop(); ps.start();ps.stop(); test_verify(2==ps.calls()); test_verify(2==ps.callsTot()); test_verify(0==ps.read()); ps.calib(); if(debug) ps.print(std::cout,true,true); { PerfStat perf; double s =0; for (int k=0; k!=100; ++k) { perf.start(); for (int i=1; i!=1000001; ++i) s+= std::log(i+1); perf.stop(); } ret &= (s!=0); test_verify(100==perf.calls()); test_verify(100==perf.callsTot()); perf.read(); perf.calib(); test_verify(ok(perf.cyclesRaw(),perf.cyclesTot())); test_verify(ok(perf.cyclesRaw()/double(perf.calls()),perf.cycles())); // test_verify(perf.verify(0.01)); std::cout <<"|default "; perf.summary(std::cout); //std::cout << std::endl; std::cout <<"|default "; perf.summary(std::cout,true); //std::cout << std::endl; if(debug) perf.print(std::cout,true,true); PerfStat perf1(true); s =0; for (int k=0; k!=100; ++k) { perf1.start(); for (int i=1; i!=1000001; ++i) s+= std::log(i+1); perf1.stop(); } ret &= (s!=0); test_verify(100==perf1.calls()); test_verify(100*PerfStat::ngroups()==perf1.callsTot()); perf1.read(); perf1.calib(); // test_verify(perf.verify(0.01)); std::cout <<"|multi "; perf1.summary(std::cout,true); //std::cout << std::endl; if(debug) perf1.print(std::cout,true,true); } { PerfStat perf1; PerfStat perf2; double s1 =0; double s2 =0; for (int k=0; k!=100; ++k) { perf1.start(); for (int i=1; i!=1000001; ++i) s1+= std::log(i+1); perf1.stop(); perf2.start(); for (int i=1; i!=1000001; ++i) s2+= std::log2(i+1); perf2.stop(); } ret &= (s1!=0);ret &= (s2!=0); test_verify(100==perf1.calls()); test_verify(100==perf1.callsTot()); test_verify(100==perf2.calls()); test_verify(100==perf2.callsTot()); perf1.read(); perf1.calib(); perf2.read(); perf2.calib(); // test_verify(perf.verify(0.01)); std::cout <<"|one ";perf1.summary(std::cout,true); //std::cout << std::endl; std::cout <<"|two ";perf2.summary(std::cout,true);// std::cout << std::endl; } { PerfStat perf1; PerfStat perf2; double s1 =0; double s2 =0; for (int k=0; k!=100; ++k) { perf1.start(0); for (int i=1; i!=1000001; ++i) s1+= std::log(i+1); perf1.stop(); perf2.start(1); for (int i=1; i!=1000001; ++i) s2+= std::log2(i+1); perf2.stop(); } ret &= (s1!=0);ret &= (s2!=0); test_verify(100==perf1.calls()); test_verify(100==perf1.callsTot()); test_verify(100==perf2.calls()); test_verify(100==perf2.callsTot()); perf1.read(); perf1.calib(); perf2.read(); perf2.calib(); // test_verify(perf.verify(0.01)); std::cout <<"|0 ";perf1.summary(std::cout,true); //std::cout << std::endl; std::cout <<"|1 ";perf2.summary(std::cout,true);// std::cout << std::endl; if(debug) perf1.print(std::cout,true,true); if(debug) perf2.print(std::cout,true,true); } { PerfStat perf1; double s1 =0; for (int k=0; k!=100; ++k) { perf1.start(0); for (int i=1; i!=1000001; ++i) s1+= std::log(i+1); perf1.stop(); perf1.start(k&1); for (int i=1; i!=1000001; ++i) s1+= std::log2(i+1); perf1.stop(); } test_verify(100*PerfStat::ngroups()==perf1.calls()); test_verify(100*PerfStat::ngroups()==perf1.callsTot()); ret &= (s1!=0); perf1.read(); perf1.calib(); // test_verify(perf.verify(0.01)); std::cout <<"|0/1 ";perf1.summary(std::cout,true);// std::cout << std::endl; if(debug) perf1.print(std::cout,true,true); } { PerfStat perf1; double s1 =0; double s2 =0; for (int k=0; k!=100; ++k) { perf1.start(); for (int i=1; i!=1000001; ++i) s1+= std::log(i+1); perf1.stop(); } perf1.read(); perf1.calib(); std::cout <<"| ";perf1.summary(std::cout); //std::cout << std::endl; perf1.reset(); for (int k=0; k!=100; ++k) { perf1.start(); for (int i=1; i!=1000001; ++i) s2+= std::log2(i+1); perf1.stop(); } test_verify(100==perf1.calls()); test_verify(100==perf1.callsTot()); ret &= (s1!=0);ret &= (s2!=0); perf1.read(); perf1.calib(); // test_verify(perf.verify(0.01)); std::cout <<"|reset ";perf1.summary(std::cout,true);// std::cout << std::endl; } { // sharing PerfStat perf; PerfStat perf1(perf.fd()); PerfStat perf2(perf.fd()); double s1 =0; double s2 =0; for (int k=0; k!=100; ++k) { perf1.startDelta(); for (int i=1; i!=1000001; ++i) s1+= std::log(i+1); perf1.stopDelta(); perf2.startDelta(); for (int i=1; i!=1000001; ++i) s2+= std::log2(i+1); perf2.stopDelta(); perf.start();perf.stop(); } ret &= (s1!=0);ret &= (s2!=0); test_verify(100==perf.calls()); test_verify(100==perf.callsTot()); test_verify(100==perf1.calls()); test_verify(100==perf1.callsTot()); test_verify(100==perf2.calls()); test_verify(100==perf2.callsTot()); // perf1.calib(); // perf2.calib(); // test_verify(perf.verify(0.01)); perf.read(); perf.calib(); std::cout <<"|total "; perf.summary(std::cout,true); //std::cout << std::endl; std::cout <<"|one sh ";perf1.summary(std::cout,true); //std::cout << std::endl; std::cout <<"|two sh ";perf2.summary(std::cout,true); //std::cout << std::endl; if(debug) perf.print(std::cout,true,true); } { // sharing multiplex PerfStat perf(true); PerfStat perf1(perf.fd()); PerfStat perf2(perf.fd()); double s1 =0; double s2 =0; for (int k=0; k!=100; ++k) { perf1.startDelta(); for (int i=1; i!=1000001; ++i) s1+= std::log(i+1); perf1.stopDelta(); perf2.startDelta(); for (int i=1; i!=1000001; ++i) s2+= std::log2(i+1); perf2.stopDelta(); perf.start();perf.stop(); } ret &= (s1!=0);ret &= (s2!=0); test_verify(100==perf.calls()); test_verify(100*PerfStat::ngroups()==perf.callsTot()); test_verify(100==perf1.calls()); test_verify(100*PerfStat::ngroups()==perf1.callsTot()); test_verify(100==perf2.calls()); test_verify(100*PerfStat::ngroups()==perf2.callsTot()); // perf1.calib(); // perf2.calib(); // test_verify(perf.verify(0.01)); perf.read(); perf.calib(); std::cout <<"|totmp "; perf.summary(std::cout,true); //std::cout << std::endl; std::cout <<"|one mp ";perf1.summary(std::cout,true); //std::cout << std::endl; std::cout <<"|two mp ";perf2.summary(std::cout,true); //std::cout << std::endl; if(debug) perf.print(std::cout,true,true); } // ps.print(std::cout); // ps.print(std::cout,true); return ret; } <file_sep>/TopDown.h #ifndef TopDown_H #define TopDonw_H #include "PerfStatBase.h" // Performance Monitoring Events for 3rd Generation Intel Core Processors Code Name IvyTown-IVT V7 8/16/2013 1:32:19 PM class TopDown final : public PerfStatBase<4> { public: static constexpr unsigned int CODE_ARITH__FPU_DIV_ACTIVE = 0x530114; static constexpr unsigned int CODE_BACLEARS__ANY = 0x531FE6; static constexpr unsigned int CODE_BR_INST_RETIRED__NEAR_TAKEN = 0x5320C4; static constexpr unsigned int CODE_BR_MISP_RETIRED__ALL_BRANCHES = 0x5300C5; static constexpr unsigned int CODE_CPU_CLK_UNHALTED__REF_TSC = 0x530300; static constexpr unsigned int CODE_CPU_CLK_UNHALTED__THREAD = 0x530200; static constexpr unsigned int CODE_CYCLE_ACTIVITY__CYCLES_NO_EXECUTE = 0x45304A3; static constexpr unsigned int CODE_CYCLE_ACTIVITY__STALLS_L1D_PENDING = 0xC530CA3; static constexpr unsigned int CODE_CYCLE_ACTIVITY__STALLS_L2_PENDING = 0x55305A3; static constexpr unsigned int CODE_CYCLE_ACTIVITY__STALLS_LDM_PENDING = 0x65306A3; static constexpr unsigned int CODE_DSB2MITE_SWITCHES__PENALTY_CYCLES = 0x5302AB; static constexpr unsigned int CODE_FP_COMP_OPS_EXE__SSE_PACKED_DOUBLE = 0x531010; static constexpr unsigned int CODE_FP_COMP_OPS_EXE__SSE_PACKED_SINGLE = 0x534010; static constexpr unsigned int CODE_FP_COMP_OPS_EXE__SSE_SCALAR_DOUBLE = 0x538010; static constexpr unsigned int CODE_FP_COMP_OPS_EXE__SSE_SCALAR_SINGLE = 0x532010; static constexpr unsigned int CODE_FP_COMP_OPS_EXE__X87 = 0x530110; static constexpr unsigned int CODE_ICACHE__IFETCH_STALL = 0x530480; static constexpr unsigned int CODE_IDQ__ALL_DSB_CYCLES_4_UOPS = 0x4531879; static constexpr unsigned int CODE_IDQ__ALL_DSB_CYCLES_ANY_UOPS = 0x1531879; static constexpr unsigned int CODE_IDQ__ALL_MITE_CYCLES_4_UOPS = 0x4532479; static constexpr unsigned int CODE_IDQ__ALL_MITE_CYCLES_ANY_UOPS = 0x1532479; static constexpr unsigned int CODE_IDQ__MS_SWITCHES = 0x1573079; static constexpr unsigned int CODE_IDQ__MS_UOPS = 0x533079; static constexpr unsigned int CODE_IDQ_UOPS_NOT_DELIVERED__CORE = 0x53019C; static constexpr unsigned int CODE_IDQ_UOPS_NOT_DELIVERED__CYCLES_0_UOPS_DELIV__CORE = 0x453019C; static constexpr unsigned int CODE_ILD_STALL__LCP = 0x530187; static constexpr unsigned int CODE_INST_RETIRED__ANY = 0x5300C0;// 0x530100; static constexpr unsigned int CODE_INT_MISC__RECOVERY_CYCLES = 0x153030D; static constexpr unsigned int CODE_ITLB_MISSES__WALK_DURATION = 0x530485; static constexpr unsigned int CODE_L1D_PEND_MISS__PENDING = 0x530148; static constexpr unsigned int CODE_L1D_PEND_MISS__PENDING_CYCLES = 0x1530148; static constexpr unsigned int CODE_LSD__CYCLES_4_UOPS = 0x45301A8; static constexpr unsigned int CODE_LSD__CYCLES_ACTIVE = 0x15301A8; static constexpr unsigned int CODE_LSD__UOPS = 0x5301A8; static constexpr unsigned int CODE_MACHINE_CLEARS__COUNT = 0x15701C3; static constexpr unsigned int CODE_MEM_LOAD_UOPS_RETIRED__L1_MISS = 0x5308D1; static constexpr unsigned int CODE_MEM_LOAD_UOPS_RETIRED__LLC_HIT = 0x5304D1; static constexpr unsigned int CODE_MEM_LOAD_UOPS_RETIRED__LLC_MISS = 0x5320D1; static constexpr unsigned int CODE_RESOURCE_STALLS__SB = 0x5308A2; static constexpr unsigned int CODE_RS_EVENTS__EMPTY_CYCLES = 0x53015E; static constexpr unsigned int CODE_RS_EVENTS__EMPTY_END = 0x1D7015E; static constexpr unsigned int CODE_UOPS_EXECUTED__CYCLES_GE_1_UOP_EXEC = 0x15301B1; static constexpr unsigned int CODE_UOPS_EXECUTED__CYCLES_GE_2_UOPS_EXEC = 0x25301B1; static constexpr unsigned int CODE_UOPS_EXECUTED__THREAD = 0x5301B1; static constexpr unsigned int CODE_UOPS_ISSUED__ANY = 0x53010E; static constexpr unsigned int CODE_UOPS_RETIRED__RETIRE_SLOTS = 0x5302C2; static constexpr int PipelineWidth = 4; static constexpr int MEM_L3_WEIGHT = 7; Type types[NGROUPS][METRIC_COUNT] = { { PERF_TYPE_HARDWARE, // PERF_COUNT_HW_CPU_CYCLES PERF_TYPE_SOFTWARE, // PERF_COUNT_SW_CPU_CLOCK PERF_TYPE_SOFTWARE, // PERF_COUNT_SW_TASK_CLOCK PERF_TYPE_RAW, PERF_TYPE_RAW, PERF_TYPE_RAW, PERF_TYPE_RAW }, { PERF_TYPE_HARDWARE, // PERF_COUNT_HW_CPU_CYCLES PERF_TYPE_SOFTWARE, // PERF_COUNT_SW_CPU_CLOCK PERF_TYPE_SOFTWARE, // PERF_COUNT_SW_TASK_CLOCK PERF_TYPE_RAW, PERF_TYPE_RAW, PERF_TYPE_RAW, PERF_TYPE_RAW }, { PERF_TYPE_HARDWARE, // PERF_COUNT_HW_CPU_CYCLES PERF_TYPE_SOFTWARE, // PERF_COUNT_SW_CPU_CLOCK PERF_TYPE_SOFTWARE, // PERF_COUNT_SW_TASK_CLOCK PERF_TYPE_RAW, PERF_TYPE_RAW, PERF_TYPE_RAW, PERF_TYPE_RAW }, { PERF_TYPE_HARDWARE, // PERF_COUNT_HW_CPU_CYCLES PERF_TYPE_SOFTWARE, // PERF_COUNT_SW_CPU_CLOCK PERF_TYPE_SOFTWARE, // PERF_COUNT_SW_TASK_CLOCK PERF_TYPE_RAW, PERF_TYPE_RAW, PERF_TYPE_RAW, PERF_TYPE_RAW } }; Conf confs[NGROUPS][METRIC_COUNT]= { { PERF_COUNT_HW_CPU_CYCLES, PERF_COUNT_SW_CPU_CLOCK, PERF_COUNT_SW_TASK_CLOCK, CODE_INST_RETIRED__ANY, CODE_IDQ_UOPS_NOT_DELIVERED__CORE, CODE_CYCLE_ACTIVITY__STALLS_LDM_PENDING, CODE_RESOURCE_STALLS__SB }, { PERF_COUNT_HW_CPU_CYCLES, PERF_COUNT_SW_CPU_CLOCK, PERF_COUNT_SW_TASK_CLOCK, CODE_UOPS_ISSUED__ANY, CODE_UOPS_RETIRED__RETIRE_SLOTS, CODE_INT_MISC__RECOVERY_CYCLES, CODE_ARITH__FPU_DIV_ACTIVE }, { PERF_COUNT_HW_CPU_CYCLES, PERF_COUNT_SW_CPU_CLOCK, PERF_COUNT_SW_TASK_CLOCK, CODE_UOPS_EXECUTED__CYCLES_GE_1_UOP_EXEC, CODE_UOPS_EXECUTED__CYCLES_GE_2_UOPS_EXEC, CODE_RS_EVENTS__EMPTY_CYCLES, CODE_CYCLE_ACTIVITY__CYCLES_NO_EXECUTE }, { PERF_COUNT_HW_CPU_CYCLES, PERF_COUNT_SW_CPU_CLOCK, PERF_COUNT_SW_TASK_CLOCK, CODE_MEM_LOAD_UOPS_RETIRED__LLC_HIT, CODE_MEM_LOAD_UOPS_RETIRED__LLC_MISS, CODE_CYCLE_ACTIVITY__STALLS_L2_PENDING, CODE_ICACHE__IFETCH_STALL // CODE_IDQ_UOPS_NOT_DELIVERED__CYCLES_0_UOPS_DELIV__CORE } }; TopDown(bool imultiplex=false) : PerfStatBase<4>(imultiplex){init();} TopDown(PerfStatBase::FD f) : PerfStatBase<4>(f){} void get(Conf * c, Type * t) const { memcpy(c,&confs[0][0], NGROUPS*METRIC_COUNT*sizeof(Conf)); memcpy(t,&types[0][0], NGROUPS*METRIC_COUNT*sizeof(Type)); }; double CYCLES(int n) const { return double(results[n][METRIC_OFFSET+0]);} double SLOTS(int n) const { return PipelineWidth*CYCLES(n);} long long INST_RETIRED__ANY() const { return results[0][METRIC_OFFSET+3];} // backward compatible interface.... long long instructionsRaw() const { return INST_RETIRED__ANY();} double instructionsTot() const { return double(INST_RETIRED__ANY())*(CYCLES(0)+CYCLES(1)+CYCLES(2)+CYCLES(3))/CYCLES(0);} double instructions() const { return (0==calls()) ? 0 : instructionsTot()/double(calls()); } // instructions per cycle double ipc() const { return double(INST_RETIRED__ANY())/CYCLES(0);} // raw long long IDQ_UOPS_NOT_DELIVERED__CORE() const { return results[0][METRIC_OFFSET+4];} long long CYCLE_ACTIVITY__STALLS_LDM_PENDING() const { return results[0][METRIC_OFFSET+5];} long long RESOURCE_STALLS__SB() const { return results[0][METRIC_OFFSET+6];} long long UOPS_ISSUED__ANY() const { return results[1][METRIC_OFFSET+3];} long long UOPS_RETIRED__RETIRE_SLOTS() const { return results[1][METRIC_OFFSET+4];} long long INT_MISC__RECOVERY_CYCLES() const { return results[1][METRIC_OFFSET+5];} long long ARITH__FPU_DIV_ACTIVE() const { return results[1][METRIC_OFFSET+6];} long long UOPS_EXECUTED__CYCLES_GE_1_UOP_EXEC() const { return results[2][METRIC_OFFSET+3];} long long UOPS_EXECUTED__CYCLES_GE_2_UOPS_EXEC() const { return results[2][METRIC_OFFSET+4];} long long RS_EVENTS__EMPTY_CYCLES() const { return results[2][METRIC_OFFSET+5];} long long CYCLE_ACTIVITY__CYCLES_NO_EXECUTE() const { return results[2][METRIC_OFFSET+6];} long long MEM_LOAD_UOPS_RETIRED__LLC_HIT() const { return results[3][METRIC_OFFSET+3];} long long MEM_LOAD_UOPS_RETIRED__LLC_MISS() const { return results[3][METRIC_OFFSET+4];} long long CYCLE_ACTIVITY__STALLS_L2_PENDING() const { return results[3][METRIC_OFFSET+5];} long long IDQ_UOPS_NOT_DELIVERED__CYCLES_0_UOPS_DELIV__CORE() const { return results[3][METRIC_OFFSET+6];} long long ICACHE__IFETCH_STALL() const { return results[3][METRIC_OFFSET+6];} // level 1 double frontendBound() const { return IDQ_UOPS_NOT_DELIVERED__CORE() / SLOTS(0);} double backendBound() const { return 1. - ( frontendBound() + badSpeculation() + retiring() ); } double badSpeculation() const { return ( UOPS_ISSUED__ANY() - UOPS_RETIRED__RETIRE_SLOTS() + PipelineWidth * INT_MISC__RECOVERY_CYCLES() ) / SLOTS(1); } double retiring() const { return UOPS_RETIRED__RETIRE_SLOTS() / SLOTS(1); } // level2 double frontLatency() const { return IDQ_UOPS_NOT_DELIVERED__CYCLES_0_UOPS_DELIV__CORE()/CYCLES(3); } double iCache() const { return ICACHE__IFETCH_STALL()/CYCLES(3); } double backendBoundAtEXE_stalls() const { return CYCLE_ACTIVITY__CYCLES_NO_EXECUTE() + UOPS_EXECUTED__CYCLES_GE_1_UOP_EXEC() - UOPS_EXECUTED__CYCLES_GE_2_UOPS_EXEC() - RS_EVENTS__EMPTY_CYCLES(); } double backendBoundAtEXE() const { return backendBoundAtEXE_stalls()/CYCLES(2);} double memBoundFraction() const { return double( CYCLE_ACTIVITY__STALLS_LDM_PENDING() + RESOURCE_STALLS__SB() ) / double( backendBoundAtEXE_stalls()*(CYCLES(0)/CYCLES(2)) + RESOURCE_STALLS__SB() ); } double memBound() const { return memBoundFraction()*backendBoundAtEXE(); } double coreBound() const { return backendBoundAtEXE() - memBound(); } // level3 double memL3HitFraction() const { return double( MEM_LOAD_UOPS_RETIRED__LLC_HIT()) / double ( MEM_LOAD_UOPS_RETIRED__LLC_HIT() + MEM_L3_WEIGHT * MEM_LOAD_UOPS_RETIRED__LLC_MISS()); } double memL3Bound() const { return memL3HitFraction() * CYCLE_ACTIVITY__STALLS_L2_PENDING() / CYCLES(3);} double dramBound() const { return (1.-memL3HitFraction()) * CYCLE_ACTIVITY__STALLS_L2_PENDING() / CYCLES(3);} double divideBound() const { return ARITH__FPU_DIV_ACTIVE()/CYCLES(1); } void header(std::ostream & out, bool details=false) const { const char * sepF = "| *"; const char * sep = "*| *"; const char * sepL = "*|"; out << sepF << "real time" << sep << "task time" << sep << "cycles" << sep << "ipc" << sep << "frontend" << sep << "backend" << sep << "bad spec" << sep << "retiring" // << sep << "front lat" << sep << "icache" << sep << "exe" << sep << "mem" << sep << "core" << sep << "l3/cy" << sep << "dram/cy" << sep << "div/cy" << sep << "ncalls" ; if (details) { out << sep << "clock" << sep << "turbo" << sep << "multiplex"; } out << sepL << std::endl; } void summary(std::ostream & out, bool details=false, double mult=1.e-6, double percent=100.) const { const char * sep = "| "; out << sep << mult*realTime() << sep << mult*taskTime() << sep << mult*cycles() << sep << ipc() << sep << percent*frontendBound() << sep << percent*backendBound() << sep << percent*badSpeculation() << sep << percent*retiring() // << sep << percent*frontLatency() << sep << percent*iCache() << sep << percent*backendBoundAtEXE() << sep << percent*memBound() << sep << percent*coreBound() << sep << percent*memL3Bound() << sep << percent*dramBound() << sep << percent*divideBound() << sep << calls() ; if (details) { out << sep << clock() << sep << turbo() << sep; for (int k=0; k!=NGROUPS; k++) { out << ncalls[k] <<'/'<<percent/corr(k) <<",";} } out << sep << std::endl; } }; #endif <file_sep>/README.md PerfStat ======== C++ class to instrument code using Linux Perf <file_sep>/VinPerf.h #ifndef VinPerf_H #define VinPerf_H #include "PerfStatBase.h" // VI preferred... class VinPerf final : public PerfStatBase<4>{ private: Type types[NGROUPS][METRIC_COUNT] = { { PERF_TYPE_HARDWARE, PERF_TYPE_SOFTWARE, PERF_TYPE_SOFTWARE, PERF_TYPE_HARDWARE, // PERF_TYPE_HARDWARE, PERF_TYPE_HARDWARE, PERF_TYPE_HARDWARE, PERF_TYPE_RAW // PERF_TYPE_RAW }, { PERF_TYPE_HARDWARE, PERF_TYPE_SOFTWARE, PERF_TYPE_SOFTWARE, PERF_TYPE_HARDWARE, PERF_TYPE_RAW, // PERF_TYPE_RAW, PERF_TYPE_HARDWARE, PERF_TYPE_HARDWARE }, { PERF_TYPE_HARDWARE, PERF_TYPE_SOFTWARE, PERF_TYPE_SOFTWARE, PERF_TYPE_HARDWARE, PERF_TYPE_RAW, PERF_TYPE_RAW, PERF_TYPE_RAW }, { PERF_TYPE_HARDWARE, PERF_TYPE_SOFTWARE, PERF_TYPE_SOFTWARE, PERF_TYPE_HARDWARE, PERF_TYPE_RAW, PERF_TYPE_RAW, PERF_TYPE_RAW } }; Conf confs[NGROUPS][METRIC_COUNT]= { { PERF_COUNT_HW_CPU_CYCLES, PERF_COUNT_SW_CPU_CLOCK, PERF_COUNT_SW_TASK_CLOCK, PERF_COUNT_HW_INSTRUCTIONS, // 0xc488, // All indirect branches that are not calls nor returns. // 0xc888, // All indirect return branches // 0xd088, // All non-indirect calls executed. // PERF_COUNT_HW_BUS_CYCLES, PERF_COUNT_HW_BRANCH_INSTRUCTIONS, PERF_COUNT_HW_BRANCH_MISSES, 0xc488 // All indirect branches that are not calls nor returns. }, { PERF_COUNT_HW_CPU_CYCLES, PERF_COUNT_SW_CPU_CLOCK, PERF_COUNT_SW_TASK_CLOCK, PERF_COUNT_HW_INSTRUCTIONS, 0x0114, // ARITH.DIV_BUSY PERF_COUNT_HW_CACHE_REFERENCES, PERF_COUNT_HW_CACHE_MISSES }, { PERF_COUNT_HW_CPU_CYCLES, PERF_COUNT_SW_CPU_CLOCK, PERF_COUNT_SW_TASK_CLOCK, PERF_COUNT_HW_INSTRUCTIONS, 0x180010e, // stall issued (front-end stalls) 0x180ffa1, // 0-ports (back-end stalls) 0x18063a1, // 0-exec-ports (back-end stalls) // 0x1a2, // res stall // 0x0408, // DTLB walk // 0x0485, // ITLB walk // 0x02C2 // RETIRE_SLOTS }, { PERF_COUNT_HW_CPU_CYCLES, PERF_COUNT_SW_CPU_CLOCK, PERF_COUNT_SW_TASK_CLOCK, PERF_COUNT_HW_INSTRUCTIONS, 0x0280, // ICACHE.MISSES 0x0151, // L1D.REPLACEMENT 0x1a2 // res stall // 0x6000860 // off core outstanding > 6 } }; public: VinPerf (bool imultiplex=false) : PerfStatBase<4>(imultiplex){init();} VinPerf(PerfStatBase::FD f) : PerfStatBase<4>(f){} void get(Conf * c, Type * t) const { memcpy(c,&confs[0][0], NGROUPS*METRIC_COUNT*sizeof(Conf)); memcpy(t,&types[0][0], NGROUPS*METRIC_COUNT*sizeof(Type)); }; long long instructionsRaw() const { return sum(METRIC_OFFSET+3);} double instructionsTot() const { return corrsum(METRIC_OFFSET+3);} double instructions() const { return (0==calls()) ? 0 : instructionsTot()/double(calls()); } // instructions per cycle double ipc() const { return double(instructionsRaw())/double(cyclesRaw());} // fraction of branch instactions double brfrac() const { return double(results[0][METRIC_OFFSET+4])/double(results[0][METRIC_OFFSET+3]);} // missed branches per cycle double mbpc() const { return double(results[0][METRIC_OFFSET+5])/double(results[0][METRIC_OFFSET+0]);} double dtlbpc() const { return double(results[2][METRIC_OFFSET+4])/double(results[2][METRIC_OFFSET+0]);} double itlbpc() const { return double(results[2][METRIC_OFFSET+5])/double(results[2][METRIC_OFFSET+0]);} double stallFpc() const { return double(results[2][METRIC_OFFSET+4])/double(results[2][METRIC_OFFSET+0]);} double stallBpc() const { return double(results[2][METRIC_OFFSET+5])/double(results[2][METRIC_OFFSET+0]);} double stallEpc() const { return double(results[2][METRIC_OFFSET+6])/double(results[2][METRIC_OFFSET+0]);} // double rslotpc() const { return double(results[2][METRIC_OFFSET+6])/double(results[2][METRIC_OFFSET+0]);} // cache references per cycle double crpc() const { return double(results[1][METRIC_OFFSET+5])/double(results[1][METRIC_OFFSET+0]);} // main memory references (cache misses) per cycle double mrpc() const { return double(results[1][METRIC_OFFSET+6])/double(results[1][METRIC_OFFSET+0]);} // div-busy per cycle double divpc() const { return double(results[1][METRIC_OFFSET+4])/double(results[1][METRIC_OFFSET+0]);} // L1 instruction-cache misses (per cycles) double il1mpc() const { return double(results[3][METRIC_OFFSET+4])/double(results[0][METRIC_OFFSET+0]);} // L1 data-cache misses (per cycles) double dl1mpc() const { return double(results[3][METRIC_OFFSET+5])/double(results[0][METRIC_OFFSET+0]);} // offcore full double offpc() const { return double(results[3][METRIC_OFFSET+6])/double(results[0][METRIC_OFFSET+0]);} // indirect calls (per cycles) double icallpc() const { return double(results[0][METRIC_OFFSET+6])/double(results[0][METRIC_OFFSET+0]);} // fraction of bus cycles // double buspc() const { return double(results0[METRIC_OFFSET+4])/double(results0[METRIC_OFFSET+0]);} void header(std::ostream & out, bool details=false) const { const char * sepF = "| *"; const char * sep = "*| *"; const char * sepL = "*|"; out << sepF << "real time" << sep << "task time" << sep << "cycles" << sep << "ipc" << sep << "br/ins" << sep << "missed-br/cy" << sep << "cache-ref/cy" << sep << "mem-ref/cy" << sep << "missed-L1I/cy" << sep << "missed-L1D/cy" << sep << "offcore/cy" << sep << (isINTEL() ? "div/cy" : "bus/cy") << sep << "ind-call/cy" // << sep << "dtlb-walk/cy" // << sep << "itlb-walk/cy" << sep << "front-stall/cy" << sep << "back-stall/cy" << sep << "exec-stall/cy" // << sep << "rslot/cy" // << sep << "bus/cy" << sep << "ncalls" ; if (details) { out << sep << "clock" << sep << "turbo" << sep << "multiplex"; } out << sepL << std::endl; } void summary(std::ostream & out, bool details=false, double mult=1.e-6, double percent=100.) const { const char * sep = "| "; out << sep << mult*realTime() << sep << mult*taskTime() << sep << mult*cycles() << sep << ipc() << sep << percent*brfrac() << sep << percent*mbpc() << sep << percent*crpc() << sep << percent*mrpc() << sep << percent*il1mpc() << sep << percent*dl1mpc() << sep << percent*offpc() << sep << percent*divpc() << sep << percent*icallpc() // << sep << percent*1000.*1000.*dtlbpc() // << sep << percent*1000.*1000.*itlbpc() << sep << percent*stallFpc() << sep << percent*stallBpc() << sep << percent*stallEpc() // << sep << rslotpc() // buspc() << sep << calls() ; if (details) { out << sep << clock() << sep << turbo() << sep; for (int k=0; k!=NGROUPS; k++) { out << ncalls[k] <<'/'<<percent/corr(k) <<",";} } out << sep << std::endl; } }; #endif <file_sep>/featureTest.cpp #include "PerfStat.h" #include<cmath> #include<iostream> template<typename T> // typedef float T; inline T polyHorner(T y) { return T(0x2.p0) + y * (T(0x2.p0) + y * (T(0x1.p0) + y * (T(0x5.55523p-4) + y * (T(0x1.5554dcp-4) + y * (T(0x4.48f41p-8) + y * T(0xb.6ad4p-12)))))) ; } template<typename T> inline T polyEstrin(T y) { T p56 = T(0x4.48f41p-8) + y * T(0xb.6ad4p-12); T p34 = T(0x5.55523p-4) + y * T(0x1.5554dcp-4); T y2 = y*y; T p12 = T(0x2.p0) + y; // By chance we save one operation here! Funny. T p36 = p34 + y2*p56; T p16 = p12 + y2*p36; T p = T(0x2.p0) + y*p16; return p; } int main0() { std::cout << "T(i)" << std::endl; bool ret=true; { PerfStat perf; std::cout << "we are " << (PerfStat::isINTEL() ? "on" : "not on") << " an INTEL Machine" << std::endl; perf.header(std::cout,true); double s =0; for (int k=0; k!=100; ++k) { perf.start(); for (int i=1; i!=1000001; ++i) s+= std::log(i+1); perf.stop(); } ret &= s!=0; //std::cout << " " << s << std::endl; std::cout << "|log "; perf.print(std::cout); } { PerfStat perf; double s =0; for (int k=0; k!=100; ++k) { perf.start(); for (int i=1; i!=1000001; ++i) s+= std::log2(i+1); perf.stop(); } ret &= s!=0; //std::cout << " " << s << std::endl; std::cout << "|log2 "; perf.print(std::cout); } { PerfStat perf; // will vectorize 256 only with avx2 (because of the int) float s =0; for (int k=0; k!=100; ++k) { perf.start(); float c = 1.f/1000000.f; for (int i=1; i<10000001; ++i) s+= polyHorner((float(i)+1.f)*c); perf.stop(); } ret &= s!=0; //std::cout << " " << s << std::endl; std::cout << "|Horner f "; perf.print(std::cout,true); } { PerfStat perf; // will vectorize 256 only with avx2 (because of the int) float s =0; for (int k=0; k!=100; ++k) { perf.start(); float c = 1.f/1000000.f; for (int i=1; i<10000001; ++i) s+= polyEstrin((float(i)+1.f)*c); perf.stop(); } ret &= s!=0; //std::cout << " " << s << std::endl; std::cout << "|Estrin f "; perf.print(std::cout,true); } { PerfStat perf; // double precision and int. it wil vectorize in mix 128 for int and 256 for double double s =0; for (int k=0; k!=100; ++k) { perf.start(); double c = 1./1000000.; for (int i=1; i<10000001; ++i) s+= polyHorner((i+1)*c); perf.stop(); } ret &= s!=0; //std::cout << " " << s << std::endl; std::cout << "|Horner d "; perf.print(std::cout,true); } { PerfStat perf; // double precision and int. it wil vectorize in mix 128 for int and 256 for double double s =0; for (int k=0; k!=100; ++k) { perf.start(); double c = 1./1000000.; for (int i=1; i<10000001; ++i) s+= polyEstrin((i+1)*c); perf.stop(); } ret &= s!=0; //std::cout << " " << s << std::endl; std::cout << "|Estrin d "; perf.print(std::cout,true); } { PerfStat perf; // double precision and int. it wil vectorize in mix 128 for int and 256 for double double s =0; for (int k=0; k!=100; ++k) { perf.start(); double c = 1./1000000.; for (int i=1; i<10000001; ++i) s+= polyEstrin((i+1.)*c); perf.stop(); } ret &= s!=0; //std::cout << " " << s << std::endl; std::cout << "|Estrin dd "; perf.print(std::cout,true); } { PerfStat perf; // will vectorize 256 only with avx2 (because of the int) float s =0; for (int k=0; k!=100; ++k) { perf.start(); for (int i=1; i<10000001; ++i) s+= 1.f/(float(i)+1.f); perf.stop(); } ret &= s!=0; //std::cout << " " << s << std::endl; std::cout << "|inv f "; perf.print(std::cout,true); } { PerfStat perf; // double precision and int. it wil vectorize in mix 128 for int and 256 for double double s =0; for (int k=0; k!=100; ++k) { perf.start(); for (int i=1; i<10000001; ++i) s+= 1./(i+1.); perf.stop(); } ret &= s!=0; //std::cout << " " << s << std::endl; std::cout << "|inv d "; perf.print(std::cout,true); } { PerfStat perf; // double precision and int. it wil vectorize in mix 128 for int and 256 for double double s =0; for (int k=0; k!=100; ++k) { perf.start(); for (int i=1; i<10000001; ++i) s+= std::sqrt(i+1.); perf.stop(); } ret &= s!=0; //std::cout << " " << s << std::endl; std::cout << "|sqrt d "; perf.print(std::cout,true); } return ret ? 0 : -1; } int main1() { std::cout << "++v" << std::endl; bool ret=true; { PerfStat perf; std::cout << "we are " << (PerfStat::isINTEL() ? "on" : "not on") << " an INTEL Machine" << std::endl; perf.header(std::cout,true); double s =0; for (int k=0; k!=100; ++k) { perf.start(); double v=0; for (int i=1; i!=1000001; ++i) s+= std::log((++v)); perf.stop(); } ret &= s!=0; //std::cout << " " << s << std::endl; std::cout << "|log "; perf.print(std::cout); } { PerfStat perf; double s =0; for (int k=0; k!=100; ++k) { perf.start(); double v=0; for (int i=1; i!=1000001; ++i) s+= std::log2((++v)); perf.stop(); } ret &= s!=0; //std::cout << " " << s << std::endl; std::cout << "|log2 "; perf.print(std::cout); } { PerfStat perf; // will vectorize 256 only with avx2 (because of the int) float s =0; for (int k=0; k!=100; ++k) { perf.start(); float c = 1.f/1000000.f; float v=0; for (int i=1; i<10000001; ++i) s+= polyHorner((++v)*c); perf.stop(); } ret &= s!=0; //std::cout << " " << s << std::endl; std::cout << "|Horner f "; perf.print(std::cout,true); } { PerfStat perf; // will vectorize 256 only with avx2 (because of the int) float s =0; for (int k=0; k!=100; ++k) { perf.start(); float c = 1.f/1000000.f; float v=0; for (int i=1; i<10000001; ++i) s+= polyEstrin((++v)*c); perf.stop(); } ret &= s!=0; //std::cout << " " << s << std::endl; std::cout << "|Estrin f "; perf.print(std::cout,true); } { PerfStat perf; // double precision and int. it wil vectorize in mix 128 for int and 256 for double double s =0; for (int k=0; k!=100; ++k) { perf.start(); double c = 1./1000000.; double v=0; for (int i=1; i<10000001; ++i) s+= polyHorner((++v)*c); perf.stop(); } ret &= s!=0; //std::cout << " " << s << std::endl; std::cout << "|Horner d "; perf.print(std::cout,true); } { PerfStat perf; // double precision and int. it wil vectorize in mix 128 for int and 256 for double double s =0; for (int k=0; k!=100; ++k) { perf.start(); double c = 1./1000000.; double v=0; for (int i=1; i<10000001; ++i) s+= polyEstrin((++v)*c); perf.stop(); } ret &= s!=0; //std::cout << " " << s << std::endl; std::cout << "|Estrin d "; perf.print(std::cout,true); } { PerfStat perf; // will vectorize 256 only with avx2 (because of the int) float s =0; for (int k=0; k!=100; ++k) { perf.start(); float v=0; for (int i=1; i<10000001; ++i) s+= 1.f/(++v); perf.stop(); } ret &= s!=0; //std::cout << " " << s << std::endl; std::cout << "|inv f "; perf.print(std::cout,true); } { PerfStat perf; // double precision and int. it wil vectorize in mix 128 for int and 256 for double double s =0; for (int k=0; k!=100; ++k) { perf.start(); double v=0; for (int i=1; i<10000001; ++i) s+= 1./(++v); perf.stop(); } ret &= s!=0; //std::cout << " " << s << std::endl; std::cout << "|inv d "; perf.print(std::cout,true); } { PerfStat perf; // double precision and int. it wil vectorize in mix 128 for int and 256 for double double s =0; for (int k=0; k!=100; ++k) { perf.start(); double v=0; for (int i=1; i<10000001; ++i) s+= std::sqrt(++v); perf.stop(); } ret &= s!=0; //std::cout << " " << s << std::endl; std::cout << "|sqrt d "; perf.print(std::cout,true); } return ret ? 0 : -1; } #include <random> int main2() { std::cout << "a[i]=f(r[i])" << std::endl; constexpr int NN = 1024*4; alignas(128) float rf[NN]; alignas(128) double rd[NN]; alignas(128) float of[NN]; alignas(128) double od[NN]; std::mt19937 eng; std::uniform_real_distribution<float> rgen(0.5,1.5); for (int i=0;i!=NN;++i) od[i]=of[i]=rd[i]=rf[i]=rgen(eng); bool ret=true; { PerfStat perf; std::cout << "we are " << (PerfStat::isINTEL() ? "on" : "not on") << " an INTEL Machine" << std::endl; perf.header(std::cout,true); double s =0; for (int k=0; k!=10000; ++k) { perf.start(); for (int i=0; i!=NN; ++i) od[i]+= std::log(rd[i]); perf.stop(); } for (int i=0; i!=NN; ++i) s+=od[i]; ret &= s!=0; //std::cout << " " << s << std::endl; std::cout << "|log "; perf.print(std::cout); } { PerfStat perf; double s =0; for (int k=0; k!=10000; ++k) { perf.start(); for (int i=0; i!=NN; ++i) od[i]+= std::log2(rd[i]); perf.stop(); } for (int i=0; i!=NN; ++i) s+=od[i]; ret &= s!=0; //std::cout << " " << s << std::endl; std::cout << "|log2 "; perf.print(std::cout); } { PerfStat perf; // will vectorize 256 only with avx2 (because of the int) float s =0; for (int k=0; k!=10000; ++k) { perf.start(); for (int i=0; i!=NN; ++i) of[i]+= polyHorner(rf[i]); perf.stop(); } for (int i=0; i!=NN; ++i) s+=of[i]; ret &= s!=0; //std::cout << " " << s << std::endl; std::cout << "|Horner f "; perf.print(std::cout,true); } { PerfStat perf; // float s =0; for (int k=0; k!=10000; ++k) { perf.start(); for (int i=0; i!=NN; ++i) of[i]+= polyEstrin(rf[i]); perf.stop(); } for (int i=0; i!=NN; ++i) s+=of[i]; ret &= s!=0; //std::cout << " " << s << std::endl; std::cout << "|Estrin f "; perf.print(std::cout,true); } { PerfStat perf; // double s =0; for (int k=0; k!=10000; ++k) { perf.start(); for (int i=0; i!=NN; ++i) od[i]+= polyHorner(rd[i]); perf.stop(); } for (int i=0; i!=NN; ++i) s+=od[i]; ret &= s!=0; //std::cout << " " << s << std::endl; std::cout << "|Horner d "; perf.print(std::cout,true); } { PerfStat perf; // double s =0; for (int k=0; k!=10000; ++k) { perf.start(); for (int i=0; i!=NN; ++i) od[i]+= polyEstrin(rd[i]); perf.stop(); } for (int i=0; i!=NN; ++i) s+=od[i]; ret &= s!=0; //std::cout << " " << s << std::endl; std::cout << "|Estrin d "; perf.print(std::cout,true); } { PerfStat perf; // float s =0; for (int k=0; k!=10000; ++k) { perf.start(); for (int i=0; i!=NN; ++i) of[i]+= 1.f/rf[i]; perf.stop(); } for (int i=0; i!=NN; ++i) s+=of[i]; ret &= s!=0; //std::cout << " " << s << std::endl; std::cout << "|inv f "; perf.print(std::cout,true); } { PerfStat perf; // double s =0; for (int k=0; k!=10000; ++k) { perf.start(); for (int i=0; i!=NN; ++i) od[i]+= 1./rd[i]; perf.stop(); } for (int i=0; i!=NN; ++i) s+=od[i]; ret &= s!=0; //std::cout << " " << s << std::endl; std::cout << "|inv d "; perf.print(std::cout,true); } { PerfStat perf; // double s =0; for (int k=0; k!=10000; ++k) { perf.start(); for (int i=0; i!=NN; ++i) od[i]+= std::sqrt(rd[i]); perf.stop(); } for (int i=0; i!=NN; ++i) s+=od[i]; ret &= s!=0; //std::cout << " " << s << std::endl; std::cout << "|sqrt d "; perf.print(std::cout,true); } return ret ? 0 : -1; } int main() { return main0() + main1() + main2(); } <file_sep>/PerfStatBase.h #ifndef PERFSTATBASE_H #define PERFSTATBASE_H #include <linux/perf_event.h> #include <iostream> #include <cstring> #include <cstdlib> #include <cstdio> #include <cerrno> #include <unistd.h> #include <sys/ioctl.h> #include <asm/unistd.h> #include <x86intrin.h> #include<cmath> #ifdef __MACH__ #include <mach/clock.h> #include <mach/mach.h> #endif template<int NG> class PerfStatBase { protected: using Type = unsigned int; using Conf = unsigned long long; static constexpr int METRIC_COUNT=7; static constexpr int METRIC_OFFSET=3; static constexpr int NGROUPS=NG; int fds[NGROUPS]={-1,}; int cfds=-1; // current one int cgroup=NGROUPS-1; unsigned long long ncalls[NGROUPS]={0,}; unsigned long long totcalls=0; long long times[2]; // 0 seems needed +1 is rdtsc +2 is gettime long long results[NGROUPS][METRIC_OFFSET+METRIC_COUNT+2]; long long bias[NGROUPS][METRIC_OFFSET+METRIC_COUNT+2]; long long bias1[METRIC_OFFSET+METRIC_COUNT+2]; bool active=false; bool multiplex=false; public: template<typename T> static T sum(T const * t) { T s=0; for (int i=0; i!=NGROUPS; i++) s+=t[i]; return s;} static constexpr int ngroups() { return NGROUPS;} unsigned long long calls() const { return totcalls;} unsigned long long callsTot() const { return sum(ncalls);} double nomClock() const { return double(times[0])/double(times[1]); } double clock() const { return double(cyclesRaw())/double(taskTimeRaw()); } double turbo() const { return cyclesTot()/double(nomCyclesRaw());} // double corr(int i) const { return ( (0==ncalls[i]) | (0==results[i][2]) ) ? 0 : double(ncalls[i])*double(results[i][1])/(double(results[i][2])*double(callsTot()));} double corr(int i) const { return ( (0==ncalls[i]) | (0==results[i][2]) ) ? 0 : double(results[i][1])/(double(results[i][2])*(multiplex ? double(NGROUPS) : 1. ));} long long sum(int k) const { long long s=0; for (int i=0; i!=NGROUPS; i++) s+=results[i][k]; return s;} long long cyclesRaw() const { return sum(METRIC_OFFSET+0);} long long taskTimeRaw() const { return sum(METRIC_OFFSET+2);} long long realTimeRaw() const { return results[0][METRIC_OFFSET+METRIC_COUNT+1];} long long nomCyclesRaw() const { return results[0][METRIC_OFFSET+METRIC_COUNT+0];} double corrsum(int k) const { double s=0; for (int i=0; i!=NGROUPS; i++) s+=corr(i)*results[i][k]; return s;} double cyclesTot() const { return corrsum(METRIC_OFFSET+0);} double taskTimeTot() const { return corrsum(METRIC_OFFSET+2);} double cycles() const { return (0==calls()) ? 0 : cyclesTot()/double(calls()); } double taskTime() const { return (0==calls()) ? 0 : taskTimeTot()/double(calls()); } double realTime() const { return (0==calls()) ? 0 : double(results[0][METRIC_OFFSET+METRIC_COUNT+1])/double(calls()); } PerfStatBase(bool imultiplex=false) : multiplex(imultiplex){} // share file descriptors... struct FD { int const * fds; bool mplex;}; FD fd() const { FD f; f.fds=fds; f.mplex=multiplex; return f;} PerfStatBase(FD f) : multiplex(f.mplex) { totcalls=0; times[0]=times[1]=0; for (int k=0; k!=NGROUPS; k++) { for (int i=0; i!=METRIC_COUNT+METRIC_OFFSET+2; ++i) results[k][i]=bias[k][i]=0; ncalls[k]=0; fds[k] = f.fds[k]; } } virtual void get(Conf * c, Type * t) const=0; void init() { Conf confs[NGROUPS][METRIC_COUNT]; Type types[NGROUPS][METRIC_COUNT]; get(&confs[0][0],&types[0][0]); // pid_t id = getpid(); pid_t id = 0; int cpuid=-1; int flags=0; struct perf_event_attr pe; memset(&pe, 0, sizeof(struct perf_event_attr)); pe.type = types[0][0]; pe.size = sizeof(struct perf_event_attr); pe.config = confs[0][0]; pe.disabled = 1; pe.inherit=0; pe.exclude_kernel = 1; pe.exclude_hv = 1; pe.read_format = PERF_FORMAT_GROUP|PERF_FORMAT_TOTAL_TIME_ENABLED|PERF_FORMAT_TOTAL_TIME_RUNNING; pe.mmap = 0; for (int k=0; k!=NGROUPS; k++) { pe.type = types[k][0]; pe.config = confs[k][0]; fds[k] = syscall(__NR_perf_event_open, &pe, id, cpuid, -1, flags); } pe.disabled = 0; /* // a small hack if (!isINTEL()) { confs[1][4] = PERF_COUNT_HW_BUS_CYCLES; types[1][4] = PERF_TYPE_HARDWARE; } */ // non exe uops // confs[2][6] = isHaswell() ? 0x18063a1 : 0x18083a1; for (int k=0; k!=NGROUPS; k++) { for (int i=1; i!=METRIC_COUNT; ++i) { pe.config = confs[k][i]; pe.type = types[k][i]; int f = syscall(__NR_perf_event_open, &pe, id, cpuid, fds[k], flags); if (f==-1) std::cout << "error 1:" << i << " " << errno << " " << strerror(errno) << std::endl; } ioctl(fds[k], PERF_EVENT_IOC_RESET, 0); } totcalls=0; times[0]=times[1]=0; for (int k=0; k!=NGROUPS; k++) { for(int i=0; i!=METRIC_COUNT+METRIC_OFFSET+2; ++i) results[k][i]=bias[k][i]=0; ncalls[k]=0; } cgroup=NGROUPS-1; warmup(); } virtual ~PerfStatBase(){ // don't! messes up the whole thing // ::close(fds0); // ::close(fds1); } void reset() { totcalls=0; for (int k=0; k!=NGROUPS; k++){ ncalls[k]=0; for(int i=0; i!=METRIC_COUNT+METRIC_OFFSET+2; ++i) bias[0][i]+=results[0][i]; } cgroup=NGROUPS-1; // ::close(fds0); //::close(fds1); //init(); } void start() { if(active) return; if (multiplex) return startAll(); if((++cgroup)==NGROUPS) cgroup=0; start(cgroup); } void start(int k) { if(active) return; active=true; ++totcalls; ++ncalls[k]; cfds = fds[k]; times[1] -= seconds(); ioctl(cfds, PERF_EVENT_IOC_ENABLE, 0); times[0] -= rdtsc(); } void startAll() { if(active) return; active=true; ++totcalls; for (int k=0; k!=NGROUPS; k++) { ++ncalls[k]; ioctl(fds[k], PERF_EVENT_IOC_ENABLE, 0); } times[0] -= rdtsc(); } void stop() { if (multiplex) return stopAll(); times[0] += rdtsc(); ioctl(cfds, PERF_EVENT_IOC_DISABLE, 0); times[1] += seconds(); active=false; cfds=-1; } void stopAll() { times[0] += rdtsc(); for (int k=0; k!=NGROUPS; k++) ioctl(fds[k], PERF_EVENT_IOC_DISABLE, 0); times[1] += seconds(); active=false; cfds=-1; } int read() { long int ret=0; for (int k=0; k!=NGROUPS; k++) ret = std::min(ret,::read(fds[k], results[k], (METRIC_OFFSET+METRIC_COUNT)*sizeof(long long))); results[0][METRIC_OFFSET+METRIC_COUNT]=times[0];results[0][METRIC_OFFSET+METRIC_COUNT+1]=times[1]; return ret; } bool verify(double res) { read();calib(); auto ok = [=](double x, double y) { return std::abs((x-y)/y)<res;}; bool ret=true; for (int k=0; k!=NGROUPS; k++) if (ncalls[k]>0) ret &= ok(results[k][1],results[k][METRIC_OFFSET+METRIC_COUNT+1]); ret &= ok(sum(2),results[0][METRIC_OFFSET+3]); return ret; } void warmup() { if(active) return; int nloop = multiplex ? 10 : 10*NGROUPS; for (int i=0; i!=nloop; ++i) {start();stop();} read(); totcalls-=nloop; for (int k=0; k!=NGROUPS; k++) { ncalls[k]-=10; for (int i=1; i!=METRIC_COUNT+METRIC_OFFSET+2; ++i) bias[k][i] +=results[k][i]; } } void calib() { if(active) return; int nloop = multiplex ? 10 : 10*NGROUPS; for (int i=0; i!=nloop; ++i) {start();stop();} totcalls-=nloop; for (int k=0; k!=NGROUPS; k++) ncalls[k]-=10; long long results_c[NGROUPS][METRIC_COUNT+METRIC_OFFSET+2]; long int err=0; for (int k=0; k!=NGROUPS; k++) err = std::min(err,::read(fds[k], results_c[k], (METRIC_OFFSET+METRIC_COUNT)*sizeof(long long))); results_c[0][METRIC_OFFSET+METRIC_COUNT]=times[0];results_c[0][METRIC_OFFSET+METRIC_COUNT+1]=times[1]; if (err==-1) return; for (int k=0; k!=NGROUPS; k++) { for (int i=1; i!=METRIC_OFFSET+METRIC_COUNT+2; ++i) { results_c[k][i]-=results[k][i]; results[k][i] -= ncalls[k]*results_c[k][i]/10 + bias[k][i]; // update bias for next read... bias[k][i] +=results_c[k][i]; } } } void startDelta() { if(active) return; long long results_c[METRIC_COUNT+METRIC_OFFSET]; long int err=0; for (int k=0; k!=NGROUPS; k++) { err = std::min(err,::read(fds[k], results_c, (METRIC_OFFSET+METRIC_COUNT)*sizeof(long long))); for (int i=0; i!=METRIC_OFFSET+METRIC_COUNT; ++i) results[k][i] -= results_c[i]; } if (err==-1) return; start(); } void stopDelta() { if(!active) return; stop(); long long results_c[METRIC_COUNT+METRIC_OFFSET]; long int err=0; for (int k=0; k!=NGROUPS; k++) { err = std::min(err,::read(fds[k], results_c, (METRIC_OFFSET+METRIC_COUNT)*sizeof(long long))); for (int i=0; i!=METRIC_OFFSET+METRIC_COUNT; ++i) results[k][i] += results_c[i]; } results[0][METRIC_OFFSET+METRIC_COUNT]=times[0];results[0][METRIC_OFFSET+METRIC_COUNT+1]=times[1]; if (err==-1) return; } virtual void header(std::ostream & out, bool details=false) const =0; virtual void summary(std::ostream & out, bool details=false, double mult=1.e-6, double percent=100.) const =0; void print(std::ostream & out, bool docalib=true, bool debug=false) { if (-1==read()) out << "error in reading" << std::endl; if (docalib) calib(); summary(out,true); if (!debug) return; out << double(results[0][METRIC_OFFSET+METRIC_COUNT])/double(results[0][METRIC_OFFSET+METRIC_COUNT+1]) << " "<< double(results[0][METRIC_OFFSET+0])/double(results[0][METRIC_OFFSET+3]) << " "<< double(cyclesRaw())/double(results[0][METRIC_OFFSET+METRIC_COUNT]) << " "<< double(taskTimeRaw())/double(results[0][METRIC_OFFSET+METRIC_COUNT+1]) << std::endl; for (int k=0; k!=NGROUPS; k++) { out << ncalls[k] << " "; for (int i=0; i!=METRIC_COUNT+METRIC_OFFSET+2; ++i) out << results[k][i] << " "; out << "; " << double(results[k][METRIC_OFFSET+0])/double(results[k][METRIC_OFFSET+2]) << " " << double(results[k][METRIC_OFFSET+3])/double(results[k][METRIC_OFFSET+0]) << " " << double(results[k][2])/double(results[k][1]); out << std::endl; } out << std::endl; } static long long seconds() { struct timespec ts; #ifdef __MACH__ // OS X does not have clock_gettime, use clock_get_time clock_serv_t cclock; mach_timespec_t mts; host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); clock_get_time(cclock, &mts); mach_port_deallocate(mach_task_self(), cclock); ts.tv_sec = mts.tv_sec; ts.tv_nsec = mts.tv_nsec; #else clock_gettime(CLOCK_REALTIME, &ts); #endif return (long long)(ts.tv_sec)*1000000000LL + ts.tv_nsec; } static volatile unsigned long long rdtsc() { unsigned int taux=0; return __rdtscp(&taux); } static bool isHaswell() { return modelNumber()==0x3c; } static unsigned int modelNumber() { unsigned int eax; cpuid(1, &eax, nullptr, nullptr, nullptr); // return eax; return ( (eax&0xf0) >> 4) + ( (eax&0xf0000) >> 12); } static bool isINTEL() { char v[13] = { 0, }; unsigned int cpuid_level=0; cpuid(0, &cpuid_level, (unsigned int *)&v[0], ( unsigned int *)&v[8], ( unsigned int *)&v[4]); return 0==::strcmp(v,"GenuineIntel"); } static void cpuid(unsigned int op, unsigned int *eax, unsigned int *ebx, unsigned int *ecx, unsigned int *edx) { unsigned int a = eax ? *eax : 0; unsigned int b = ebx ? *ebx : 0; unsigned int c = ecx ? *ecx : 0; unsigned int d = edx ? *edx : 0; #if defined __i386__ __asm__ __volatile__ ("xchgl %%ebx,%0\n\t" "cpuid \n\t" "xchgl %%ebx,%0\n\t" : "+r" (b), "=a" (a), "=c" (c), "=d" (d) : "1" (op), "2" (c)); #else __asm__ __volatile__ ("cpuid" : "=a" (a), "=b" (b), "=c" (c), "=d" (d) : "0" (op), "2" (c)); #endif if (eax) *eax = a; if (ebx) *ebx = b; if (ecx) *ecx = c; if (edx) *edx = d; } }; #endif <file_sep>/libCall.cc struct A { A(){} A(int ii) : i(ii){} virtual ~A(){} int val() const; virtual int ival() const=0; virtual int jval() const=0; virtual int kval() const=0; int i; }; struct B : public A { B(){} B(int ii) : A(ii){} virtual int ival() const override; virtual int jval() const final { return i;} virtual int kval() const final { return i;} }; struct C : public A { C(){} C(int ii) : A(ii){} virtual int ival() const override; virtual int jval() const final { return i;} virtual int kval() const override { return i;} }; struct E : public A { E(){} E(int ii) : A(ii){} virtual int ival() const override; virtual int jval() const final; virtual int kval() const override { return i;} }; int A::val() const { return i;} int B::ival() const { return i;} int C::ival() const { return i;} int E::ival() const { return i;} int E::jval() const { return i;} void modify(A**){} void modify(C**){} void modify(C*){} #include<iostream> void hello() { std::cout << "from library" << std::endl;} namespace { struct Q{ Q() { std::cout << "library loaded" << std::endl; } }; } <file_sep>/L3Mem.cpp #include <random> #include <iostream> #include "PerfStat.h" #include<malloc.h> int main(int argc, char**) { std::mt19937 eng; std::uniform_real_distribution<float> rgen(0.,1.); constexpr int NN = 1024*1024; // alignas(128) float r[NN]; float * r = (float*)__builtin_assume_aligned(::memalign(32,NN*sizeof(float)),32); std::cout << sizeof(r) << " " << alignof(r) << std::endl; PerfStat c12, c2, c11, c22; c12.header(std::cout,true); std::cout << std::endl; c11.startAll(); for (int i=0;i!=NN;++i) r[i]=rgen(eng); c11.stopAll(); std::cout << "|rgen " << std::endl; c11.print(std::cout); c12.startAll(); for (int i=0;i!=NN;++i) r[i]=rgen(eng); c12.stopAll(); std::cout << "|rgen " << std::endl; c12.print(std::cout); std::cout << std::endl; std::cout << std::endl; constexpr int KK=10000; bool err=false; float s[KK+3]; for (int ok=0; ok!=KK+3; ++ok) { s[ok]=0; c2.start(); for (int i=0;i!=NN;++i) s[ok]+=r[i]; c2.stop(); if (ok>0 && s[ok] != s[ok-1]) err=true; if ( (ok%1000)==2) { std::cout << "|sum " << ok << " "; c2.print(std::cout); } } if (err) std::cout << "a mess " << std::endl; std::cout << "end \n" << std::endl; c2.print(std::cout); ::free(r); return 0; } <file_sep>/Makefile CXX = c++ ${ADDOPT} -std=gnu++11 -Wall -Wno-format -Wstrict-overflow -Wunsafe-loop-optimizations -ftree-vectorizer-verbose=1 -ftree-loop-if-convert-stores -lrt -fPIC -fvisibility-inlines-hidden -fopenmp .PHONY : run all clean L3Mem UnitTest featureTest callTest libCall parallel all : UnitTest L3Mem featureTest callTest libCall callTest_O3_wl parallel L3Mem : L3Mem_O2 L3Mem_O2_avx L3Mem_O2_avx2 L3Mem_O3 L3Mem_O3_avx L3Mem_O3_avx2 L3Mem_fast L3Mem_fast_avx L3Mem_fast_avx2 UnitTest : UnitTest_O3 featureTest : featureTest_O2 featureTest_O2_avx featureTest_O2_avx2 featureTest_O3 featureTest_O3_avx featureTest_O3_avx2 featureTest_fast featureTest_fast_avx featureTest_fast_avx2 callTest : callTest_O2 callTest_O2_avx callTest_O2_avx2 callTest_O3 callTest_O3_avx callTest_O3_avx2 callTest_fast callTest_fast_avx callTest_fast_avx2 libCall : libCall_O3.so libCall_O3_avx.so libCall_O3_avx2.so parallel : parallel_O2 parallel_O2_avx parallel_O2_avx2 parallel_O3 parallel_O3_avx parallel_O3_avx2 parallel_fast parallel_fast_avx parallel_fast_avx2 %_O2 : %.cpp $(CXX) $(INCDIR) $< -o $@ -O2 -march=corei7 %_O2_avx : %.cpp $(CXX) $(INCDIR) $< -o $@ -O2 -march=corei7-avx %_O2_avx2 : %.cpp $(CXX) $(INCDIR) $< -o $@ -O2 -march=core-avx2 %_O3 : %.cpp $(CXX) $(INCDIR) $< -o $@ -O3 -march=corei7 %_O3_avx : %.cpp $(CXX) $(INCDIR) $< -o $@ -O3 -march=corei7-avx %_O3_avx2 : %.cpp $(CXX) $(INCDIR) $< -o $@ -O3 -march=core-avx2 %_fast : %.cpp $(CXX) $(INCDIR) $< -o $@ -Ofast -march=corei7 %_fast_avx : %.cpp $(CXX) $(INCDIR) $< -o $@ -Ofast -march=corei7-avx %_fast_avx2 : %.cpp $(CXX) $(INCDIR) $< -o $@ -Ofast -march=core-avx2 %_O3.so : %.cc $(CXX) $(INCDIR) $< -o $@ -O3 -march=corei7 -shared %_O3_avx.so : %.cc $(CXX) $(INCDIR) $< -o $@ -O3 -march=corei7-avx -shared %_O3_avx2.so : %.cc $(CXX) $(INCDIR) $< -o $@ -O3 -march=core-avx2 -shared callTest_O3_wl : callTest.cpp libCall_O3.so $(CXX) $(INCDIR) $< -o $@ -O3 -march=corei7 -L./ -lCall_O3 -Wl,-rpath ./ -DWITHLIB run : all for exe in *_*; do echo "\nrunning " $${exe}; ./$${exe}; done; clean: rm *_O2 *_O3 *_fast *_avx *_avx2 *.so callTest_O3_wl <file_sep>/PerfStat.h #include "VinPerf.h" #include "TopDown.h" // using PerfStat=VinPerf; using PerfStat=TopDown; <file_sep>/callTest.cpp #include <random> #include <iostream> #include "PerfStat.h" #include<malloc.h> #include<sstream> struct A { A(){} A(int ii) : i(ii){} virtual ~A(){} int val() const; virtual int ival() const=0; virtual int jval() const=0; virtual int kval() const=0; int i; }; struct B : public A { B(){} B(int ii) : A(ii){} virtual int ival() const override; virtual int jval() const final { return i;} virtual int kval() const final { return i;} }; struct C : public A { C(){} C(int ii) : A(ii){} virtual int ival() const override; virtual int jval() const final { return i;} virtual int kval() const override { return i;} }; struct E : public A { E(){} E(int ii) : A(ii){} virtual int ival() const override; virtual int jval() const final; virtual int kval() const override { return i;} }; #ifndef WITHLIB int A::val() const { return i;} int B::ival() const { return i;} int C::ival() const { return i;} int E::ival() const { return i;} int E::jval() const { return i;} void modify(A**){} void modify(C**){} void modify(C*){} void hello() { std::cout << "from main" << std::endl;} #else void modify(A**); void modify(C**); void modify(C*); void hello(); #endif int main(int argc, char** argv) { hello(); bool nostring = argc>1; bool q1 = argc>2; bool q2 = argc>4; char * ww = argv[3]; PerfStat c11, c12, c13; PerfStat c21, c22, c23; PerfStat c31, c32, c33; PerfStat c41, c42, c43; PerfStat c51, c52, c53; PerfStat if1; PerfStat mn, md, ss1, ss2; constexpr int NN =1024*4; A * a[NN]; A * b[NN]; C * c[NN]; C d[NN]; E e[NN]; PerfStat m1; m1.startAll(); for (int i=0; i!=NN; i++) { b[i] = new B(i); c[i] = new C(i); d[i] = C(i); } m1.stopAll(); std::cout <<"|new "; m1.print(std::cout); m1.startAll(); for (int i=0; i!=NN; i+=2) { a[i]= new B(i); a[i+1]= new C(i); } m1.stopAll(); std::cout <<"|new "; m1.print(std::cout); if (q1) { b[int(ww[3])] = a[int(ww[4])]; } constexpr int KK=100000; bool err=false; int s[100]; for (int ok=0; ok!=KK; ++ok) { auto k = ok%100; s[k]=0; if (!nostring) { md.start(); for (int i=0; i!=NN; i+=2) { delete a[i]; delete a[i+1]; } md.stop(); mn.start(); for (int i=0; i!=NN; i+=2) { a[i]= new B(i); a[i+1]= new C(i); } mn.stop(); ss1.start(); std::string st1,st2; bool sb=true; for (int i=0; i!=NN; i+=2) { char q = 50 - ok%10 + i%20; st1 += q; st2 += q; sb &= st1==st2; } if (sb) s[k]+=st1.size(); ss1.stop(); ss2.start(); std::stringstream sss; for (int i=0; i!=NN; i+=2) { sss << i; } if (sss.str()==st1) s[k]+=st1.size(); ss2.stop(); } modify(a);modify(b); modify(c);modify(d); if (q2) { b[int(ww[ok%32])] = a[int(ww[ok%64])]; a[int(ww[ok%32])] = c[int(ww[ok%64])]; d[int(ww[ok%32])] = *c[int(ww[ok%64])]; } c11.start(); for (int i=0;i!=NN;++i) s[k] += a[i]->val(); c11.stop(); c12.start(); for (int i=0;i!=NN;++i) s[k] += a[i]->ival(); c12.stop(); c13.start(); for (int i=0;i!=NN;++i) s[k] += a[i]->jval(); c13.stop(); c21.start(); for (int i=0;i!=NN;++i) s[k] += b[i]->val(); c21.stop(); c22.start(); for (int i=0;i!=NN;++i) s[k] += b[i]->ival(); c22.stop(); c23.start(); for (int i=0;i!=NN;++i) s[k] += b[i]->jval(); c23.stop(); c31.start(); for (int i=0;i!=NN;++i) s[k] += c[i]->val(); c31.stop(); c32.start(); for (int i=0;i!=NN;++i) s[k] += c[i]->ival(); c32.stop(); c33.start(); for (int i=0;i!=NN;++i) s[k] += c[i]->jval(); c33.stop(); c41.start(); for (int i=0;i!=NN;++i) s[k] += d[i].val(); c41.stop(); c42.start(); for (int i=0;i!=NN;++i) s[k] += d[i].ival(); c42.stop(); c43.start(); for (int i=0;i!=NN;++i) s[k] += d[i].jval(); c43.stop(); c51.start(); for (int i=0;i!=NN;++i) s[k] += e[i].kval(); c51.stop(); c52.start(); for (int i=0;i!=NN;++i) s[k] += e[i].ival(); c52.stop(); c53.start(); for (int i=0;i!=NN;++i) s[k] += e[i].jval(); c53.stop(); if1.start(); for (int i=0;i!=NN;++i) { if (0==(a[i]->ival()&1)) b[i]->i = c[i]->ival(); else b[i]->i = d[i].jval(); if (b[i]->jval()&1) s[k] += d[c[i]->kval()].jval(); } if1.stop(); modify(a);modify(b); modify(c);modify(d); if (k>0 && s[k] != s[k-1]) err=true; } PerfStat perf; if (err) std::cout << "a mess " << std::endl; std::cout << "|kernel "; perf.header(std::cout,true); std::cout << "|new "; mn.print(std::cout); std::cout << "|delete "; md.print(std::cout); std::cout << "|string "; ss1.print(std::cout); std::cout << "|stream "; ss2.print(std::cout); std::cout << "|a val "; c11.print(std::cout); std::cout << "|a ival "; c12.print(std::cout); std::cout << "|a jval "; c13.print(std::cout); std::cout << "|b val "; c21.print(std::cout); std::cout << "|b ival "; c22.print(std::cout); std::cout << "|b jval "; c23.print(std::cout); std::cout << "|c val "; c31.print(std::cout); std::cout << "|c ival "; c32.print(std::cout); std::cout << "|c jval "; c33.print(std::cout); std::cout << "|d val "; c41.print(std::cout); std::cout << "|d ival "; c42.print(std::cout); std::cout << "|d jval "; c43.print(std::cout); std::cout << "|e kval "; c51.print(std::cout); std::cout << "|e ival "; c52.print(std::cout); std::cout << "|e jval "; c53.print(std::cout); std::cout << "|if "; if1.print(std::cout); return err ? -1 : 0; }
e2e0a57dbadea8d44e2230822c9d9acf1ce430b4
[ "Markdown", "C", "Makefile", "C++" ]
12
C++
aminems/PerfStat
2b9bd101e240949af8eaf2393a5a69acb22c00da
b8f480405a1383a5a8c6b78bd97383f4d2d289a8
refs/heads/master
<repo_name>bestarti99/ajax-wprowadzenie<file_sep>/js/main.js 'use strict' // Definicja funkcji ajax function ajax(ajaxOptions) { // Opcje połączenia i jego typu, ||-inicjacja var options = { type: ajaxOptions.type || 'POST', url: ajaxOptions.url || '', onError: ajaxOptions.onError || function () {}, onSuccess: ajaxOptions.onSuccess || function () {}, dataType: ajaxOptions.dataType || 'text', } //funkcja sprawdająca statusy function httpSuccess(httpRequest) { try { return (httpRequest.status >= 200 && httpRequest.status < 300 || httpRequest.status == 304 || // Dotyczy przeglądarek Safari navigator.userAgent.indexOf('Safari') >= 0 && typeof httpRequest.status == 'undefind'); } catch (e) { return false; } } // Utworzenie obiektu XMLHttpRequest var httpReq = new XMLHttpRequest(); // Otwarcie połączenia metoda-adres-asynchronicznie? httpReq.open(options.type, options.url, true); // Iterowanie za każdym razem , kiedy zmienia się ready state - od 0 do 4 httpReq.onreadystatechange = function () { // Sprawdź status połącznia - funkcja httpSuccess if (this.readyState == 4) { if (httpSuccess(this)) { // jęsli dane w formacie XML, to zwróć obiekt responseXML, w przeciwnym wypadku responseText (JOSN to tekst) var returnData = (options.dataType == 'xml') ? this.responseXML : this.responseText; options.onSuccess(returnData); httpReq = null; } else { options.onError(console.log('Błąd')); } } } httpReq.send(); } ajax({ type: 'GET', url: 'http://echo.jsontest.com/userId/108/userName/Akademia108/userURL/akademia108', onError: function (msg) { console.log(msg); }, onSuccess: function (response) { var jsonObj = JSON.parse(response); console.log(jsonObj.userId); console.log(jsonObj.userName); console.log(jsonObj.userURL); var userId = jsonObj.userId; $('#testowy').text(userId); document.getElementById('testowy').innerHTML = userId; // nadpisuje całe body i wstawia w nim element bez znaczników //document.write(jsonObj.userId); } });
2c22194c28349f4896bf6e5712f3eb5d1883e5c7
[ "JavaScript" ]
1
JavaScript
bestarti99/ajax-wprowadzenie
c47611b82052d6d9477caf162ff2f592fdca52c6
9b142641ebb44678620a3020cba14b4fd6a1c12e
refs/heads/master
<file_sep># dse-fit Set of tools for customing Datastax Enterprise Stack (Cassandra and Solr) <h4>Usage:</h4> 1. First, you must have to downlaod Datastax Enterprise instalation package https://portal.datastax.com/downloads.php?dsedownload=tar/enterprise/dse.tar.gz 2. Then add following packages into local Maven repository, run: <i>mvn install:install-file -Dfile=[path to datastax]/dse-6.7.2/resources/solr/lib/solr-uber-with-auth_2.1-6.0.1.2.2381.jar -DgroupId=org.apache.solr -DartifactId=solr-core -Dversion=6.0.1.2.2381 -Dpackaging=jar</i> <i>mvn install:install-file -Dfile=[path to datastax]/dse-6.7.2/lib/dse-search-6.7.2.jar -DgroupId=com.datastax -DartifactId=dse-search -Dversion=6.7.2 -Dpackaging=jar</i> 3. Run <i>maven build</i> 4. Copy jar file into [datastax server instalation directory]/dse/resources/solr/lib 5. Put this line into your <i>solrconfig.xml</i> file (inside <i>\<config></i> section): \<fieldInputTransformer name="dse" class="com.artwork.mori.dse.search.AbstractLowerCaseFieldInputTransformer"></fieldInputTransformer> # FIT Copy Transformers - <b>LowerCaseFieldInputTransformer</b> - Insert lowercase value into [name]_ci document field # Related DSE issues: <h5>Lowercase filter factory doesn't work when docvalues=true</h3> - https://stackoverflow.com/questions/39697408/lowercase-filter-factory-doesnt-work-when-docvalues-true<file_sep>package com.artwork.mori.dse.search; public class SortTableLowerCaseFieldInputTransformerTest { public static void main(String[] args) { } } <file_sep>CREATE KEYSPACE sort WITH replication = {'class': 'NetworkTopologyStrategy', 'dc1': '1'} AND durable_writes = true; CREATE TABLE sort.sort_table ( owner text, id text, name text, shortname text, PRIMARY KEY (owner, id) ); COPY sort.sort_table FROM 'sort_data.csv'; select * from sort.sort_table where solr_query = '{"q": "*:*", "sort": "shortname_ci asc"}';
fe949a3d2fd36005495d88f5b70c588dc364c097
[ "Markdown", "Java", "SQL" ]
3
Markdown
mntmori/dse-fit
070101e21ebb2166f274f6c9a81a5e69f62b6be0
efce62232b4ad8224500702eedb43d98d960d946
refs/heads/master
<repo_name>daaasheng/dash<file_sep>/README.md <p align="center"> <img width="200" height="200" src="./logo.png" alt="my-logo"> <p align="center"><EMAIL></p> </p> author: <EMAIL> description: demo of web [css](https://daaasheng.github.io/dash/css) [vue实现](https://daaasheng.github.io/dash/vue "https://daaasheng.github.io/dash/vue") ### 可视化 #### canvas [投掷骰子](https://daaasheng.github.io/dash/game/craps/craps.html) [d3实现](https://daaasheng.github.io/dash/d3) [echarts实现](https://daaasheng.github.io/dash/echarts) <file_sep>/base/bs/list.html <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>列表--简介</title> <link rel="stylesheet" href="./bootstrap.v3.css"> </head> <body> <ul> <li>无序列表信息1</li> <li>无序列表信息2</li> <li>无序列表信息3</li> </ul> <ol> <li>有序列表信息1</li> <li>有序列表信息2</li> <li>有序列表信息3</li> </ol> <dl> <dt>定义列表标题</dt> <dd>定义列表信息1</dd> <dd>定义列表信息2</dd> </dl> <ol class="list-unstyled"> <li>列表--去点列表</li> <li>不带项目编号</li> <p>.list-unstyled { padding-left: 0; list-style: none; }</p> </ol> <ul class="list-inline"> <li>列表--内联列表:把垂直列表换成水平列表,而且去掉项目符号(编号),保持水平显示。</li> <li>Blog</li> <li>CSS3</li> <li>jQuery</li> <li>PHP</li> <p>.list-inline { padding-left: 0; margin-left: -5px; list-style: none; } .list-inline > li { display: inline-block; padding-right: 5px; padding-left: 5px; }</p> </ul> <dl class="dl-horizontal"> <dt>水平定义列表</dt> <dd>一个致力于推广国内前端行业的技术博客。它以探索为己任,不断活跃在行业技术最前沿,努力提供高质量前端技术博文</dd> <dt>慕课网</dt> <dd>一个专业的,真心实意在做培训的网站</dd> <dt>我来测试一个标题,我来测试一个标题</dt> <dd>我在写一个水平定义列表的效果,我在写一个水平定义列表的效果</dd> <p>@media (min-width: 768px) { .dl-horizontal dt { float: left; width: 160px; overflow: hidden; clear: left; text-align: right; text-overflow: ellipsis; white-space: nowrap; } .dl-horizontal dd { margin-left: 180px; } }</p> </dl> </body> </html><file_sep>/algorithm/quickSort.js function quickSort(arr, start, end){ if( start >= end){ return arr; } var key = arr[0]; var arrL = []; var arrR = []; for(var i = start+1; i <= end; i++){ arr[i] <= key ? arrL.push(arr[i]) : arrR.push(arr[i]); } arrL.push(key); return quickSort(arrL, 0, arrL.length-1).concat(quickSort(arrR, 0, arrR.length - 1)); } var array = [61, 17, 29, 22, 34, 60, 72, 21, 50, 1, 62]; console.info(quickSort(array, 0, array.length - 1));<file_sep>/py/101cases/test37.py # py2 # select sort # time o(n ^ 2) def insertSort(alist): for i,alist_i in enumerate(alist): index = i while index > 0 and alist_i < alist[index-1]: alist[index] = alist[index-1] index -= 1 alist[index] = alist_i return alist def bubbleSort(alist): for i in range(len(alist)): for j in range(1, len(alist) - i): if alist[j-1] > alist[j]: alist[j-1], alist[j] = alist[j], alist[j-1] return alist class MergeSort: def sort(self,alist): if len(alist) <= 1: return alist else: mid = len(alist) / 2 left = self.sort(alist[:mid]) right = self.sort(alist[mid:]) return self.mergeList(left, right) def mergeList(self, left, right): tmpList = [] i = 0 j = 0 while i < len(left) and j < len(right): if left[i] < right[j]: tmpList.append(left[i]) i += 1 else: tmpList.append(right[j]) j += 1 tmpList += left[i:] tmpList += right[j:] return tmpList def bucketSort(alist): buckets = [0] * (max() - min() + 1) return alist def selectSort(alist): for i in range(len(alist)): min_index = i for j in range(i+1, len(alist)): if alist[j] < alist[min_index]: min_index = j alist[i], alist[min_index] = alist[min_index], alist[i] return alist # for j in range(len(alist)): unsorted_list = [29, 25, 3, 49, 9, 37, 21, 43] print unsorted_list # print insertSort(unsorted_list) # print bubbleSort(unsorted_list) print MergeSort().sort(unsorted_list) # print selectSort(unsorted_list) <file_sep>/py/101cases/test12.py # time 0.277 from math import sqrt def isPrime(num): max = int(sqrt(num+1))+1 flag = True if num > 3: for i in range(2, max): if(num % i == 0): flag = False break return flag res = [] for i in range(101, 200): if(isPrime(i)): res.append(i) print res print len(res)<file_sep>/algorithm/1000/1000.md 来源:hihocoder 限制语言: C、C++、Java、C#、Python2 #1000 : A + B 时间限制:1000ms 单点时限:1000ms 内存限制:256MB 描述 求两个整数A+B的和 输入 输入包含多组数据。 每组数据包含两个整数A(1 ≤ A ≤ 100)和B(1 ≤ B ≤ 100)。 输出 对于每组数据输出A+B的和。 样例输入 1 2 3 4 样例输出 3 7<file_sep>/py/101cases/test64.py from Tkinter import * canvas = Canvas(width = 400, height = 600, bg = 'white') canvas.create_rectangle(10, 10, 10, 10) canvas.pack() mainloop()<file_sep>/game/soduku/src/README.md code from imooc rules: box: 3 * 3 3* box --src |--js |--less --www |--css |--js 1. $ npm init 2. $ npm install webpack --save-dev gulp gulp-util gulp-less webpack-stream babel-core babel-loader babel-preset-es2015 3. create gulpfile.js webpack、less、default 4. $ npm insatll -g gulp 5. $ gulp 实现: 1. 生成完整数独 2. 删除一些数字 3. 每次三次,行、列、宫 4. 最后一个结束,表示通关 交互: mobile: 360*640 pc: 1. 9 * 9 pc: 1.再来一次 code: es2016、object <file_sep>/nodejs/crypto/aes.js const crypto = require('crypto'); const cryptoUtils = new Object(); cryptoUtils.encrypt = function(data, key) { const cipher = crypto.createCipher('aes192', key); var crypted = cipher.update(data, 'utf8', 'hex'); crypted += cipher.final('hex'); return crypted.toUpperCase(); } cryptoUtils.decrypt = function(encrypted, key){ const decipher = crypto.createDecipher('aes192', key); var decrypted = decipher.update(encrypted, 'hex', 'utf8'); decrypted += decipher.final('utf8'); return decrypted; } var data = "Hello, China!"; key = '123456', encrypted = cryptoUtils.encrypt(data, key), decrypted = cryptoUtils.decrypt(encrypted, key); console.log('Plain text: ' + data); console.log('Encrypted text: ' + encrypted); console.log('Decrypted text: ' + decrypted);<file_sep>/py/101cases/test88.py while True: i = int(raw_input('input a number range[0,50]:\n')) print type(i) if i>-1 and i<51: print i * '*' <file_sep>/js/page.js function pageView(len = 0, current = 1) { let res = [1]; if ( len <= 7){ res = Array.from({ length: len}, (v, i) => i + 1); } else { res = [1, 2, 3, 4, 5, '...', len]; // res = [1, '...', 4,5,6,'...', len]; } return res; } console.log(pageView(20));<file_sep>/py/101cases/test62.py str = 'sdfghjk' sub = 'df' print str.find(sub)<file_sep>/py/101cases/test29.py n = raw_input('input:\n') if len(n) < 6: strLen = len(n) numList = [] for i in n: numList.append(i) print('%d length\n' % (strLen)) print numList[::-1] else: print "input error"<file_sep>/py/101cases/test9.py import time a = {'a': 1, 'b': 2} for key,value in dict.items(a): print key,value time.sleep(3) # s<file_sep>/algorithm/bubbleSort.js var array = [61, 17, 29, 22, 34, 60, 72, 21, 50, 1, 62]; function bubbleSort(arr){ var len = array.length; for(var i = 0; i < len; i++){ for(var j = 0; j < len - i; j ++){ if(arr[j] > arr[j+1]){ var temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } } bubbleSort(array); console.info(array);<file_sep>/py/101cases/testcard.py # len len = 11 indexArr = [] arr = [len] for i in range(1, len): indexArr.append(len-i) if i > 0: tmp = arr.pop() arr.insert(0, tmp) arr.insert(0, len-i) print indexArr print arr<file_sep>/tdd/tddjs.js 'use strict' function isUserAdmin(id, users) { const user = users.find(u => u.id === id); return user.isAdmin; } const testUsers = [ { id: 1, isAdmin: true }, { id: 2, isAdmin: false } ]; const isAdmin = isUserAdmin(1, testUsers); // TODO: assert isAdmin is true console.log(isAdmin);<file_sep>/nodejs/crypto/md5.js const crypto = require('crypto'); var encryptUtils = new Object(); /** * MD5加密 * @param data * @returns {*} */ encryptUtils.md5 = function(data) { const md5 = crypto.createHash('md5').update(data); return md5.digest('hex').toUpperCase(); } console.log(encryptUtils.md5('33422'));<file_sep>/py/101cases/test50.py import random print random.uniform(20, 30) <file_sep>/py/101cases/test7.py a = [1,2,3] b = a[:] b[1] = 4 print a print b<file_sep>/py/101cases/test10.py import time print time.time() time.sleep(2) print time.localtime(time.time()) time.sleep(2) print time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))<file_sep>/py/101cases/test23.py from sys import stdout len = 4 for i in range(4): stdout.write((len-i) * ' ' + (2 * i - 1) * '*' + '\n') for i in range(4): stdout.write(i * ' ' + (2 * (len-i) - 1) * '*' + '\n') print<file_sep>/nodejs/crypto/sha1.js const crypto = require('crypto'); var encryptUtils = new Object(); /** * MD5加密 * @param data * @returns {*} */ encryptUtils.sha1 = function(data) { const sha1 = crypto.createHash('sha1').update(data); return sha1.digest('hex').toUpperCase(); } console.log(encryptUtils.sha1('33422'));<file_sep>/echarts/README.md ## echarts4.0实例[svg方式渲染] [折线](https://daaasheng.github.io/dash/echarts/v4/line-simple.html) [折线-轴线-固定间隔](https://daaasheng.github.io/dash/echarts/v4/line-axis.html) [面积图](https://daaasheng.github.io/dash/echarts/v4/area-simple.html) [折面积图线-轴线-固定间隔](https://daaasheng.github.io/dash/echarts/v4/area-axis.html) 堆积面积图, 暂不推荐 [柱状图(直方图) bar](https://daaasheng.github.io/dash/echarts/v4/bar-axis.html) [并列柱状图(直方图) bar](https://daaasheng.github.io/dash/echarts/v4/bar-multi.html) 堆积柱状图 [(并列)条形图(水平直方图) barH-底部图例](https://daaasheng.github.io/dash/echarts/v4/barH-multi.html) 堆积条形图 [基础饼图](https://daaasheng.github.io/dash/echarts/v4/pie.html) [环形图](https://daaasheng.github.io/dash/echarts/v4/dount.html) [环形图-图例-动画](https://daaasheng.github.io/dash/echarts/v4/dount-label-legend.html) <file_sep>/py/101cases/test27.py # py2 print '123456'[::-1] print type('123456'[::-1])<file_sep>/py/101cases/test70.py i = raw_input('input string:\n') print len(i)<file_sep>/algorithm/README.md ### hiho题库练习 [1000AplusB]()<file_sep>/py/101cases/test20.py ## halve high = 100.0 count = 10 sum = high high /= 2 for i in range(count-1): print(str(high)+','), sum += 2 * high high /= 2 print print sum <file_sep>/py/101cases/test21.py ## reserved day = 9 count = 1 for i in range(day): count = 2 * (count + 1) print str(count)+',', print print count <file_sep>/nodejs/main.js 'use strict' var hello = require('./hello'); var bye = require('./bye'); hello.greet('Charloo'); bye('Jane');<file_sep>/py/101cases/test30.py # py2 def idPlalindrome(str): flag = True for i in range(len(str)/2): if str[i] != str[len(str) - i]: flag = False break return flag print idPlalindrome('12321')<file_sep>/vue/README.md ### 基础用法 [事件监听](eventListen.html) [表单](formBind.html) ### vue-render [https://daaasheng.github.io/dash/vue/render.html](https://daaasheng.github.io/dash/vue/render.html "https://daaasheng.github.io/dash/vue/render.html") ### todo list [https://daaasheng.github.io/dash/vue/todoList.html](https://daaasheng.github.io/dash/vue/todoList.html) <file_sep>/py/101cases/test84.py print ','.join(['344', 'xixix', 'okkk'])<file_sep>/py/101cases/test33.py s = '-' print s.join(['1', '2', '3']) print s.join(('1', '2', '3')) print s.join({'a': 1, 'b': 2,'c':3 })<file_sep>/py/101cases/test25.py # py2 def accuMultiply(count): res = 1 if count > 1: for i in range(2, count+1): res *= i return res s = 0 for i in range(20): s += accuMultiply(i+1) print '1! + 2! + 3! + ... + 20! = %d' % s<file_sep>/nodejs/bye.js 'use strict' function bye(name) { console.log('bye,'+name+'!'); } module.exports = bye;<file_sep>/py/101cases/test13.py res = [] for index in range(101, 1000): i = int(index / 100) j = int(index % 100 / 10) k = int(index % 100 % 10) if (i ** 3 + j ** 3 + k ** 3) == index: res.append(index) print res print len(res)<file_sep>/py/101cases/test34.py def funChild(): print 'child' def funPar(): for i in range(3): funChild() funPar()<file_sep>/py/101cases/test78.py person = {'li': 12, 'eee': 4, 'zhang': 89, 'liu': 56} m = person.keys()[0] for key in person.keys(): if person[key] > person[m]: m = key print m<file_sep>/py/101cases/test47.py def ex(a, b): a,b = b,a return (a,b) x = 1 y = 2 print 'x=%d, y=%d'%(x,y) print 'x=%d, y=%d'%ex(x,y)<file_sep>/py/101cases/test16.py import datetime print datetime.date.today() print(datetime.date.today().strftime('%d,%m,%Y')) print(datetime.date(1992,6,27).strftime('%d,%m,%Y')) print((datetime.date(1992,6,27)+datetime.timedelta(days=1)).strftime('%d,%m,%Y')) myDate = datetime.date(1992,6,27) newDate = myDate.replace(year=myDate.year+1) print(newDate.strftime('%d,%m,%Y'))<file_sep>/py/101cases/test36.py # prime [1, 100] # time 0.247 max = 100 composite = [] for i in range(2, max+1): for j in range(2, max+1): if i * j <= max: composite.append(i * j) res = set(range(1, max)) - set(composite) print res<file_sep>/nodejs/fs/readcss.js /** * 读取css文件, 过滤出class */ const fs = require('fs'); fs.readFile('./style.css', 'utf-8', (err, data) => { console.log(data.length); const regx = /icon-bms-[a-z]*/g; const iconArr = data.match(regx); if( iconArr.length > 2) { iconArr.splice(0, 2); } console.log(iconArr); }); // 3334 // [ 'icon-bms-dbleft', // 'icon-bms-dbright', // 'icon-bms-dbup', // 'icon-bms-dbdown', // 'icon-bms-close',<file_sep>/py/101cases/test31.py weekList = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'] letter_st = raw_input('input first letter:\n')[0] if letter_st != 's': for i in weekList[0:4]: if letter_st == i[0]: print i break elif letter_st == 's': letter_ed = raw_input('input second letter:\n')[0] for i in weekList[5:7]: if letter_ed == i[1]: print i break <file_sep>/py/101cases/test17.py str = raw_input('input string:\n') letters = 0 space = 0 digit = 0 other = 0 for i in str: if i.isalpha(): letters += 1 elif i.isspace(): space += 1 elif i.isdigit(): digit += 1 else: other += 1 print 'char=%d,\nspace=%d,\ndigit=%d,\nothers=%d'%(letters, space, digit, other)<file_sep>/py/101cases/test8.py len = 9 for i in range(1,len +1): print for j in range(1, i+1): print '%dX%d=%d '%(j,i,i*j),<file_sep>/backup/homework_zhaochen/readme.md #单元测试报告 #####目录 1. 单元描述 2. 单元控制流图 3. 单元关键代码 4. 测试数据及结果 **完整作业见homework.html** 输入: 2016-06-02 20:00~22:00 7 2016-06-03 09:00~12:00 14 2016-06-04 14:00~17:00 22 2016-06-05 19:00~22:00 3 2016-06-06 12:00~15:00 15 2016-06-07 15:00~17:00 12 2016-06-08 10:00~13:00 19 2016-06-09 16:00~18:00 16 2016-06-10 20:00~22:00 5 2016-06-11 13:00~15:00 11 输出: [Summary] 2016-06-02 20:00~22:00 +210 -240 -30 2016-06-03 09:00~12:00 +420 -180 +240 2016-06-04 14:00~17:00 +660 -600 +60 2016-06-05 19:00~22:00 +0 -0 0 2016-06-06 12:00~15:00 +450 -300 +150 2016-06-07 15:00~17:00 +360 -200 +160 2016-06-08 10:00~13:00 +570 -330 +240 2016-06-09 16:00~18:00 +480 -300 +180 2016-06-10 20:00~22:00 +150 -120 +30 2016-06-11 13:00~15:00 +330 -200 +130 Total Income: 3630 Total Payment: 2470 Profit: 1160 end ##单元分布 ###设计背景: 小明打算成立羽毛球俱乐部,不定期组织羽毛球活动。参加活动的人向小明支付费用,小明向羽毛球馆预定球场并支付费用。帮助小明结算收入。 ###设计分析: 设计网页,使用javascript实现计算。设计单元如下: 1. 网页布局,获取输入内容并输出。 2. 依据年、月、日计算星期数 3. 依据星期数、场地的租用时间段计算一个场地一日的开销 4. 依据人数计算需要租用的场地数 5. 合计收入和支出的输出以及最后的盈利 ##单元1 ###1.1单元描述 网页使用html来实现,主要为了获取输入内容并按照原格式输出 ###1.2单元结构 分为标题、输入提示、输入框textarea、输出四部分 ###1.3单元控制流图及主要代码 .html文件见test1.html <!DOCTYPE html> <html> <head> <title>homework-zc</title> <meta charset="utf-8"> <style type="text/css"> body{font-family: theta /*Arial,Lucida,Verdana,"宋体","微软雅黑",Helvetica,sans-serif*/;} </style> </head> <body> <h1>羽毛球俱乐部收支费用</h1> <p>输入格式为{活动时间yyyy-MM-dd HH:mm~HH:mm} {人数}</p> <p>例如:2016-06-02 20:00~22:00 7</p> <textarea id="input" rows="8" cols="40" placeholder="请在此输入!" wrap="hard"></textarea> <input type="button" name="button" value="提 交" id="btn"> <p id="summary"></p> <script type="text/javascript"> var input=document.getElementById("input"), btn=document.getElementById("btn"), summary=document.getElementById("summary"); var strs= new Array(); //定义一数组来储存每一行 var i; var str="[Summary]<br><br>";//用于输出的文本字符串 //提交按钮事件 btn.onclick=function(){ generateSummary(input); } //生成总计 function generateSummary(input){ strs=input.value.split("\n"); //字符分割,一行分割为三个数组 for (i=0;i<strs.length ;i++ ) { str=str.concat(strs[i]); str=str.concat("<br> ");//分割后的字符输出 } str=str.concat("<br>end"); summary.innerHTML=str; } </script> </body> </html> ###1.4测试数据及结果 单行输入: 2016-06-03 09:00~12:00 14 输出: [Summary] 2016-06-03 09:00~12:00 14 end 多行输入: 2016-06-02 20:00~22:00 7 2016-06-03 09:00~12:00 14 2016-06-04 14:00~17:00 22 2016-06-05 19:00~22:00 3 2016-06-06 12:00~15:00 15 2016-06-07 15:00~17:00 12 2016-06-08 10:00~13:00 19 2016-06-09 16:00~18:00 16 输出: [Summary] 2016-06-02 20:00~22:00 7 2016-06-03 09:00~12:00 14 2016-06-04 14:00~17:00 22 2016-06-05 19:00~22:00 3 2016-06-06 12:00~15:00 15 2016-06-07 15:00~17:00 12 2016-06-08 10:00~13:00 19 2016-06-09 16:00~18:00 16 end 单行、多行都以原格式输出,因此测试成功! ##单元2 ###2.1单元描述 使用substr()获取需要的字符段,使用parseInt()转成数值,创建计算星期数的函数countWeekday()。 计算星期数使用Zeller公式 ###2.2单元结构 函数的参数1:cent 世纪-1 函数的参数2:yy 年份后两位 函数的参数3:mm 月份 函数的参数4:day 日期 返回:weekday 星期数0-6 ###2.3单元控制流图及主要代码 .html文件见test2.html 在for中添加 cent=parseInt(strs[i].substr(0,2));//世纪 cent=parseInt(strs[i].substr(0,2));//世纪 yy=parseInt(strs[i].substr(2,4));//年份后两位 mm=parseInt(strs[i].substr(5,2));//月 day=parseInt(strs[i].substr(8,2));//日 countWeekday(cent,yy,mm,day);//计算星期几 weekday 在`<script>`标签中添加函数 //计算星期 function countWeekday(cent,yy,mm,day){ //蔡勒(Zeller)公式 //蔡勒(Zeller)公式:w=y+[y/4]+[c/4]-2c+[26(m+1)/10]+d-1 //w:星期;c:世纪-1;y:年(两位数);m:月(m大于等于3,小于等于14,即在蔡勒公式中,某年的1、2月要看作上一年的13、14月来计算,比如2003年1月1日要看作2002年的13月1日来计算);d:日;[ ]代表取整,即只要整数部分。(C是世纪数减一,y是年份后两位,M是月份,d是日数。1月和2月要按上一年的13月和 14月来算,这时C和y均按上一年取值。) if(mm==1) mm=13; else if(mm==2) mm=14; weekday=yy+Math.floor(yy/4)+Math.floor(cent/4)-2*cent+Math.floor(26*(mm+1)/10)+day-1; weekday=Math.floor(weekday%7); } 更改输出 str=str.concat(strs[i]+"星期:"+weekday); ###2.4测试数据及结果 多行输入: 2015-03-01 09:00~12:00 14 2015-12-04 14:00~17:00 22 2016-06-05 19:00~22:00 3 2016-06-06 12:00~15:00 15 2016-06-07 15:00~17:00 12 2017-06-08 10:00~13:00 19 2016-10-17 10:00~13:00 19 输出: [Summary] 2015-03-01 09:00~12:00 14星期:0 2015-12-04 14:00~17:00 22星期:5 2016-06-05 19:00~22:00 3 星期:0 2016-06-06 12:00~15:00 15星期:1 2016-06-07 15:00~17:00 12星期:2 2017-06-08 10:00~13:00 19星期:4 2016-10-17 10:00~13:00 19星期:1 end 输入不同日期,对照万年历逐个检查输出正确,因此测试成功! ##单元3 ###3.1单元描述 计算所租用的一个场地一日的花费 ###3.2单元结构 函数的参数1:weekday 星期数0-6 函数的参数2:start 开始时间 函数的参数2:end 结束时间 返回:dayprice 一个场地一日的开销 ###3.3单元控制流图及主要代码 .html文件见test3.html 注意:由于`dayprice`采用的是累加的方式来计价,因此获取每行数据后应对`dayprice=0;`初始化 function chargeStandard(weekday,start,end){ if(weekday>=1&&weekday<=5){ //周一到周五 while(start!=end){ if(start>=9&&start<12){ dayprice=dayprice+30; start=start+1;} else if(start>=12&&start<18){ dayprice=dayprice+50; start=start+1;} else if(start>=18&&start<20){ dayprice=dayprice+80; start=start+1;} else if(start>=20&&start<22){ dayprice=dayprice+60; start=start+1;} } } else{ //周六及周日 while(start!=end){ if(start>=9 && start<12){ dayprice=dayprice+40; start=start+1;} else if(start>=12&&start<18){ dayprice=dayprice+50; start=start+1;} else if(start>=18&&start<22){ dayprice=dayprice+60; start=start+1;} } } } ###3.4测试数据及结果 选择周一到周日的不同以及交叉的时间段进行测试。 输入: 2016-06-02 20:00~22:00 7 2016-06-03 09:00~12:00 14 2016-06-04 14:00~17:00 22 2016-06-05 19:00~22:00 3 2016-06-06 12:00~15:00 15 2016-06-07 15:00~17:00 12 2016-06-08 10:00~13:00 19 2016-06-09 16:00~18:00 16 2016-06-10 20:00~22:00 5 2016-06-11 13:00~15:00 11 输出: [Summary] 2016-06-02 20:00~22:00 7 星期数:4 dayprice:120 2016-06-03 09:00~12:00 14 星期数:5 dayprice:90 2016-06-04 14:00~17:00 22 星期数:6 dayprice:150 2016-06-05 19:00~22:00 3 星期数:0 dayprice:180 2016-06-06 12:00~15:00 15 星期数:1 dayprice:150 2016-06-07 15:00~17:00 12 星期数:2 dayprice:100 2016-06-08 10:00~13:00 19 星期数:3 dayprice:110 2016-06-09 16:00~18:00 16 星期数:4 dayprice:100 2016-06-10 20:00~22:00 5 星期数:5 dayprice:120 2016-06-11 13:00~15:00 11 星期数:6 dayprice:100 end 对照时间段、星期数,逐个检查dayprice的输出正确,因此测试成功! ##单元4 ###4.1单元描述 计算需要租用的场地数 ###4.2单元结构 函数的参数1:member 报名人数 返回:games 需要租用的场地数 ###4.3单元控制流图及主要代码 .html文件见test4.html //计算场数 function countGames(member){ t=Math.floor(member/6),x=Math.floor(member%6); if(t==0&&x<4) games=0; else if(t==0&&x>=4) games=1; else if(t==1) games=2; else if((t==2||t==3)&&x<4) games=t; else if((t==2||t==3)&&x>=4) games=t+1; else games=t; } ###4.4测试数据及结果 测试的数据应涉及订场策略的六种情况。 输入: 2016-06-02 20:00~22:00 7 2016-06-03 09:00~12:00 14 2016-06-04 14:00~17:00 22 2016-06-05 19:00~22:00 3 2016-06-06 12:00~15:00 15 2016-06-07 15:00~17:00 12 2016-06-08 10:00~13:00 19 2016-06-09 16:00~18:00 16 2016-06-10 20:00~22:00 5 2016-06-11 13:00~15:00 11 输出: [Summary] 2016-06-02 20:00~22:00 7 场数:2 2016-06-03 09:00~12:00 14 场数:2 2016-06-04 14:00~17:00 22 场数:4 2016-06-05 19:00~22:00 3 场数:0 2016-06-06 12:00~15:00 15 场数:2 2016-06-07 15:00~17:00 12 场数:2 2016-06-08 10:00~13:00 19 场数:3 2016-06-09 16:00~18:00 16 场数:3 2016-06-10 20:00~22:00 5 场数:1 2016-06-11 13:00~15:00 11 场数:2 end 对照场订场策略,逐行检查场数输出正确,因此测试成功! ##单元5 ###5.1单元描述 计算每次活动的收入、支出、盈利。 ###5.2单元结构 收入:`30*member` 支出:`dayprice*games` 盈利:`(30*member-dayprice*games)` ###5.3单元控制流图及主要代码 .html文件见test5.html 总收入、总支出、总盈利 income+=30*member;//收入 payment+=dayprice*games;//支出:所需场地的费用=场地*场地日单价 profit=income-payment;//盈余 ###5.4测试数据及结果 输入: 2016-06-02 20:00~22:00 7 2016-06-03 09:00~12:00 14 2016-06-04 14:00~17:00 22 2016-06-05 19:00~22:00 3 2016-06-06 12:00~15:00 15 2016-06-07 15:00~17:00 12 2016-06-08 10:00~13:00 19 2016-06-09 16:00~18:00 16 2016-06-10 20:00~22:00 5 2016-06-11 13:00~15:00 11 输出: [Summary] 2016-06-02 20:00~22:00 7 星期数:4 dayprice:120 场数:2 每日收入:+210 每日支出:-240 每日收益-30 2016-06-03 09:00~12:00 14 星期数:5 dayprice:90 场数:2 每日收入:+420 每日支出:-180 每日收益 +240 2016-06-04 14:00~17:00 22 星期数:6 dayprice:150 场数:4 每日收入:+660 每日支出:-600 每日收益 +60 2016-06-05 19:00~22:00 3 星期数:0 dayprice:180 场数:0 每日收入:+0 每日支出:-0 每日收益0 2016-06-06 12:00~15:00 15 星期数:1 dayprice:150 场数:2 每日收入:+450 每日支出:-300 每日收益 +150 2016-06-07 15:00~17:00 12 星期数:2 dayprice:100 场数:2 每日收入:+360 每日支出:-200 每日收益 +160 2016-06-08 10:00~13:00 19 星期数:3 dayprice:110 场数:3 每日收入:+570 每日支出:-330 每日收益 +240 2016-06-09 16:00~18:00 16 星期数:4 dayprice:100 场数:3 每日收入:+480 每日支出:-300 每日收益 +180 2016-06-10 20:00~22:00 5 星期数:5 dayprice:120 场数:1 每日收入:+150 每日支出:-120 每日收益 +30 2016-06-11 13:00~15:00 11 星期数:6 dayprice:100 场数:2 每日收入:+330 每日支出:-200 每日收益 +130 Total Income: 3630 Total Payment: 2470 Profit: 1160 end 对照范例,逐行检查输出正确,因此测试成功!<file_sep>/js/datetime.js /** * 字符串转时间戳 * @param {*} str */ export const str2ts = str => Date.parse(new Date(str)) / 1000; /** * 时间戳转字符串 * @param {*} ts 时间戳 * @param {*} formatType 类型 * @param {*} checkRange 校验区域 * 支持H24进制,h12进制 * 支持M、d、h、m、s两位时首位补零 */ export const ts2str = (ts = Date.parse(new Date()) / 1000, formatType = 'yyyy-MM-dd HH:mm:ss') => { let res = formatType; const dt = new Date(ts * 1000); const t = { 'y+': dt.getFullYear(), 'M+': dt.getMonth() + 1, 'd+': dt.getDate(), 'H+': dt.getHours(), 'h+': dt.getHours() > 12 ? dt.getHours() - 12 : dt.getHours(), 'm+': dt.getMinutes(), 's+': dt.getSeconds(), 'S+': 0, }; function padStr(source, padLen) { return padLen < 2 ? source : String(source).padStart(2, '0'); } function fixStr(source, fixLen) { const tmpNum = Number(`0.${source}`); return String(Number(tmpNum.toFixed(fixLen))).substring(2); }; for (const k of Object.keys(t)) { if (new RegExp(`(${k})`).test(res)) { const len = RegExp.$1.length; if (k === 'y+') { res = res.replace(RegExp.$1, String(t[k]).substr(4 - len)); } else if (k === 'S+') { const decimals = String(ts).split('.')[1]; res = res.replace(RegExp.$1, fixStr(decimals, 3 * len)); } else { res = res.replace(RegExp.$1, padStr(t[k], len)); } } } return res; }; // 2018/9/1 9:9:9 // console.log(ts2str(1535764149)); // 2018-09-01 09:09:09 // console.log(ts2str(1535764149, 'yyyy-MM-dd hh:mm:ss')); //2018-09-01 09:09:09 // console.log(ts2str(1535764149.870763, 'yyyy-MM-dd hh:mm:ss.SS')); // 2018-09-01 09:09:09.870763 // console.log(ts2str(1535764149.870763, 'yyyy-MM-dd hh:mm:ss.S')); // 2018-09-01 09:09:09.871 // console.log(ts2str(1535764149, 'yyyy-MM-dd hh:mm')); // 2018-09-01 09:09 // console.log(ts2str(1535764149, 'yyyy-M-d h:m:s')); // 2018-9-1 9:9:9 // console.log(ts2str(1535764149, 'yyyy年MM月dd日hh时mm分ss秒')); // 2018年09月01日09时09分09秒 <file_sep>/py/101cases/test22.py teamA = ['a', 'b', 'c'] teamB = ['x', 'y', 'z'] # for i in teamA: # for j in teamB: # if not ((i == 'a' and j == 'x') or (i == 'c' and (j == 'x' or j == 'z'))): # print i,j count = len(teamA) for i in range(count): print i<file_sep>/py/101cases/test4.py # year = int(raw_input('year:\n')) # month = int(raw_input('month:\n')) # day = int(raw_input('day:\n')) year = 2018 month = 2 day = 3 # 31[1,3,5,7,8,10,12] daysList = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] count = day for i in range(month-1): count += daysList[i] if month > 2 and ((year % 400 == 0) or (year % 4 == 0 and year%100 != 0)): count += 1 print count <file_sep>/py/101cases/test2.py # raw_input i = int(raw_input('input:')) threshold = [100,60,40,20,10,0] rate = [0.01,0.015,0.03,0.05,0.075,0.1] r = 0 for index in range(1,6): if i > threshold[index]: tmp = (i-threshold[index])*rate[index] r += tmp i = threshold[index] print r # print type(i) # print r<file_sep>/py/101cases/test74.py # sort and extend a = [1,2] b = [4,6] b.extend(a) print b b.sort() print b<file_sep>/game/soduku/src/js/index.js const Generator = require('./core/generator'); const Toolkit = require('./core/toolkit'); Generator.generate(); // console.log(matrix); // const a = makeMatrix(); // a[3][3] = 2; // const a = Array.from({length: 9}, (v,i)=> i); // console.log(a); // console.log(Toolkit.matrix.shuffle(a));<file_sep>/py/101cases/test32.py tmpList = ['one', 'two', 'three'] tmpStr = '12345' print tmpList[::-1] print tmpStr[::-1] print list(reversed(tmpList)) print list(reversed(tmpStr))<file_sep>/py/101cases/test53.py a = 234 print a^3<file_sep>/py/101cases/test24.py # py2 # fib def fib(count): a = 1.0 b = 1.0 res = 1.0 if count > 2: for i in range(2, count): res = a + b a,b = b,res # print res return res # fib(5) sum = 0 for index in range(20): sum += fib(index+3)/fib(index+2) print fib(index+3),fib(index+2) print sum<file_sep>/py/101cases/test18.py a = int(raw_input('a:')) n = int(raw_input('n:')) res = 0 for i in range(1, n+1): # use i * str, then turn int res += int(i * str(a)) print int(i * str(a)) print res<file_sep>/py/101cases/test26.py # py2 def accuMultiplyRecu(count): res = 1 if count > 1: res = count * accuMultiplyRecu(count - 1) return res print accuMultiplyRecu(5)<file_sep>/backup/zhaochen-2018-7-homework/task.md 假设我们现在有一个 3 x 3 的井字棋游戏,我们用一个二维数组代表棋盘,’x’ 代表玩家 X 下的棋子,’o’ 代表玩家 O 下的棋子,’e’ 代表该格没有棋子。例如: 一个空白的棋盘以下面的二维数组表示 [ [‘e’, ‘e’, ‘e’], [‘e’, ‘e’, ‘e’], [‘e’, ‘e’, ‘e’] ] 如果玩家 X 在第一行第一列下了一步棋,玩家 O 在第二行第二列下了一步棋,则表示如下: [ [‘x’, ‘e’, ‘e’], [‘e’, ‘o’, ‘e’], [‘e’, ‘e’, ‘e’] ] 现在需要一个 function,接受一个已有任意棋子的棋盘(和上面二维数组一样的格式),和玩家的标志(’x’ 或 ‘o'),返回该玩家下一步有几种可能的获胜方式(获胜方式以数组表示,[0, 0] 代表在第一行第一列下一步棋即可获胜,[2, 2] 代表在第三行第三列下一步棋即可获胜)。例如: someFunction( ‘x’, [ [‘o’, ‘e’, ‘e’], [‘o’, ‘x’, ‘o’], [‘x’, ‘x’, ‘e’] ] ) // return [ [2, 2], [0, 1], [0, 2] ] someFunction( ‘x’, [ [‘x’, ‘o’, ‘o’], [‘x’, ‘x’, ‘e’], [‘e’, ‘o’, ‘e’] ] ) // return [ [2, 2], [1, 2], [2, 0] ] someFunction( ‘x’, [ [‘x’, ‘x’, ‘o’], [‘e’, ‘e’, ‘e’], [‘e’, ‘e’, ‘e’] ] ) // return [ ] someFunction( ‘o’, [ [‘o’, ‘o’, ‘o’], [‘e’, ‘e’, ‘e’], [‘e’, ‘e’, ‘e’] ] ) // return [ ] 除了实现功能以外,我们还有一些加分项: 代码可读性高 代码量少 性能高 有可运行的单元测试 使用 ES6 语法实现 使用 functional programming 实现<file_sep>/py/101cases/test86.py a = raw_input('input:\n') b = '7hh' print a+b<file_sep>/py/101cases/test77.py s = ['334', '45', '455'] for i in range(len(s)): print s[i]<file_sep>/py/101cases/test15.py def getGrade(num): res = 'error' if num >= 0 and num <= 100: sourceLi = [90, 60, 0] gradeLi = ['A', 'B', 'C'] for i in range(len(sourceLi)): if num >= sourceLi[i]: res = gradeLi[i] break return res print getGrade(99)<file_sep>/backup/zhaochen-2018-7-homework/index.js // const tictactoe = { matrix: [ [0, 0, 0], [0, 0, 0], [0, 0, 0] ], format(str) { let num = 0; if (str === 'x') { num = 1; } else if (str === 'o') { num = -1; } return num; }, initMatrix(str, tmpMatrix) { that = this; const newMatrix = tmpMatrix.map(function(d) { const newArr = d.map(function(sub) { return sub = that.format(sub); // console.log(this); }); return newArr; }); // console.log(that.format(str), newMatrix); return this.getNextStep(that.format(str), newMatrix); }, creat() {}, isEqual(role, num1, num2, num3) { return (num1+num2+num3) === 3 * role; }, isWin(role, tmpMatrix) { let flag = false; // 三行三列两条对角线 tmpMatrix.forEach((d, i) => { if (this.isEqual(role, ...d)) { flag = true; } }); if (!flag) { tmpMatrix.forEach((d, i) => { if (this.isEqual(role, tmpMatrix[0][i], tmpMatrix[1][i], tmpMatrix[2][i])) { flag = true; } }); } if (!flag) { flag = this.isEqual(role, tmpMatrix[0][0], tmpMatrix[1][1], tmpMatrix[2][2]) || this.isEqual(role, tmpMatrix[2][0], tmpMatrix[1][1], tmpMatrix[0][2]); } return flag; }, isEnd(tmpMatrix) { let flag = true; tmpMatrix.forEach(d => { if (d.indexOf(0) > -1) { flag = false; } }); return flag; }, getNextStep(role, tmpMatrix) { const nextArr = []; if (this.isEnd(tmpMatrix)) { console.log('game is over, try again!'); } else if (this.isWin(role, tmpMatrix) && !this.isWin(-role, tmpMatrix)) { console.log(`you are win!`); } else { tmpMatrix.forEach((d,i) => { d.forEach((sub,j) => { if (tmpMatrix[i][j] === 0) { const newMatrix = Array.from({length: 3}, (v, i) => tmpMatrix[i].concat()); newMatrix[i][j] = role; if (this.isWin(role, newMatrix)) { nextArr.push([i,j]); } } }); }); } return nextArr; }, } // console.log(tictactoe.getNextStep(1, [ // [1, -1, 1], // [-1, 0, -1], // [1, 0, 1] // ])); const testData1 = function() { console.log('test1'); console.log(tictactoe.initMatrix( 'x', [ ['o', 'e', 'e'], ['o', 'x', 'o'], ['x', 'x', 'e'] ] )); }; testData1(); //[ [ 0, 1 ], [ 0, 2 ], [ 2, 2 ] ] const testData2 = function() { console.log('test2'); console.log(tictactoe.initMatrix( 'x', [ ['x', 'o', 'o'], ['x', 'x', 'e'], ['e', 'o', 'e'] ] )); }; testData2(); //[ [ 1, 2 ], [ 2, 0 ], [ 2, 2 ] ] const testData3 = function() { console.log('test3'); console.log(tictactoe.initMatrix( 'x', [ ['x', 'x', 'o'], ['e', 'e', 'e'], ['e', 'e', 'e'] ] )); }; testData3(); // [] const testData4 = function() { console.log('test4'); console.log(tictactoe.initMatrix( 'o', [ ['o', 'o', 'o'], ['e', 'e', 'e'], ['e', 'e', 'e'] ] )); }; testData4(); // [] // const testFunc = function(str, matric) { // console.log(tictactoe.initMatrix(str, matric)); // }; // testFunc('o', [ ['o', 'o', 'o'], // ['e', 'e', 'e'], // ['e', 'e', 'e'] ]);<file_sep>/d3/README.md ## d3绘制demo(以v4为主) [扇形](https://daaasheng.github.io/dash/d3/v4/pie-v4.html) [立体扇形](https://daaasheng.github.io/dash/d3/v4/pie-3d-v4.html) [环形](https://daaasheng.github.io/dash/d3/v4/dount-v4.html) [柱状](https://daaasheng.github.io/dash/d3/v4/simple-bar-v4.html) [横向柱状](https://daaasheng.github.io/dash/d3/v4/bar-v4.html) 折线 面积图 散点 地图 ### 特殊图形 仪表 [油表](https://daaasheng.github.io/dash/d3/v4/gauge-oil.html) [油表参考1](http://bl.ocks.org/metormote/6392996) [油表参考2](http://bl.ocks.org/NPashaP/59c2c7483fb61070486835d15c807941) 进度 ### 基础组件 时间轴 [直角坐标轴](https://daaasheng.github.io/dash/d3/v4/axis-rect.html) 网格 [环形坐标轴](https://daaasheng.github.io/dash/d3/v4/axis-circle.html) 提示 标题 放缩 图例 ### 参考 [动画](http://bl.ocks.org/brattonc/b1abb535227b2f722b51) [path-w3](https://www.w3.org/TR/SVG/paths.html)<file_sep>/py/101cases/test5.py li = [] for i in range(3): li.append(int(raw_input('input int:\n'))) li.sort() print li<file_sep>/base/README.md [阴影](https://daaasheng.github.io/dash/css/box-shadow.html) [斜线](line.html) ### bootstrap [主题](theme.html) [标题和副标题](title.html) [列表](list.html) [代码引用](code.html) [滚动和回到顶部--未实现](scroll.html) [表格](table.html)<file_sep>/form/freezeHeader/tableFreezeHeader.js /** * * @param elem table * @param params 参数OBJECT * { * height : 200 , //若无父滚动DIV则按此高度添加 * freezeTop : 200, //固定表头所在位置 * scroller : window, //父滚动元素 * dynamicDiv : jsDomElement //不定表头TopDiv * } * @returns {boolean} */ var tableFreezeHeader = function(elem,params){ if(!elem || elem.tagName.toLowerCase() != "table")return false; if(params){ if(params.height == undefined && params.top == undefined && params.dynamicDiv == undefined) return false; if(params.height !== undefined && params.height >= elem.clientHeight) return false; } else{ // if (elem.parentNode.tagName.toLowerCase() == "div" && elem.clientHeight <= elem.parentNode.clientHeight)return false; } var TABLE_ID = document.querySelectorAll('.freezeHeader').length + 1; var obj = { id: elem.id || ('tbl-' + TABLE_ID), table: elem, header: elem.querySelector('thead'), scroller: window, divScroll: null, container: null, isFreezeTop: params && ( params.top !== undefined || params.dynamicDiv !== undefined) }; if (params && params.height !== undefined) { obj.divScroll = document.createElement("div"); obj.divScroll.id = "hdScroll" + obj.id ; obj.divScroll.style.height = params.height + 'px'; obj.divScroll.style.overflowY = 'auto'; } if(params){ if(params.height !== undefined) { if (!document.querySelector('#hdScroll' + obj.id)) { obj.table.parentNode.insertBefore(obj.divScroll,obj.table).appendChild(obj.table); obj.scroller = document.querySelector('#hdScroll' + obj.id); } }else if(obj.isFreezeTop){ obj.scroller = params.scroller || window; } }else{ if (obj.table.parentNode.tagName.toLowerCase() == "div") { obj.scroller = obj.table.parentNode; } } if (!document.querySelector('#hd' + obj.id)) { var hd = document.createElement('div'); hd.id = "hd" + obj.id; obj.table.parentNode.insertBefore(hd,obj.table); }else{ document.querySelector('#hd' + obj.id).parentNode.removeChild(document.querySelector('#hd' + obj.id)); } obj.container = document.querySelector('#hd' + obj.id); obj.container.style.position = 'fixed'; obj.container.style.overflow = 'hidden'; obj.container.style.top = obj.scroller == window ? 0 : obj.scroller.getBoundingClientRect().top + "px"; obj.container.style.width = (obj.isFreezeTop ? obj.table.parentNode.clientWidth : obj.scroller.clientWidth) + 'px'; cloneHeaderRow(obj); if(obj.isFreezeTop){ var lastTr = obj.table.querySelector('tbody tr:last-child'); var scrollDivTop = obj.scroller == window ? 0 : obj.scroller.getBoundingClientRect().top; } var headerHeight = obj.header.getBoundingClientRect().height; var evenWidth = obj.scroller.clientWidth; containerScroll(); obj.scroller.addEventListener('scroll', containerScroll); window.addEventListener('resize',headerResize); /** * 滚动 */ function containerScroll() { if(!obj.container.clientWidth){ obj.scroller.removeEventListener('scroll',containerScroll); }else{ if(obj.isFreezeTop) { var freezeTop = params.dynamicDiv.clientHeight || params.top; var lastTop = lastTr.getBoundingClientRect().top; var headerTop = obj.header.getBoundingClientRect().top; if(headerTop - scrollDivTop < freezeTop && lastTop - scrollDivTop - headerHeight > freezeTop){ showFreeze(obj); obj.container.style.top = (scrollDivTop + freezeTop) + "px"; }else{ hideFreeze(obj); } }else{ if (obj.scroller.scrollTop > headerHeight) { showFreeze(obj); } else { hideFreeze(obj); } } obj.container.querySelector('table').style.marginLeft = (-obj.scroller.scrollLeft) + 'px'; } } /** * 自适应 */ function headerResize() { if(!obj.container.clientWidth){ window.removeEventListener('resize',headerResize); }else{ var nowWidth = obj.scroller.clientWidth; // if(evenWidth != nowWidth){ obj.container.style.width = nowWidth + 'px'; obj.container.querySelector('table').style.width = obj.table.clientWidth + 'px'; var arr = Array.prototype.slice.call(obj.container.querySelectorAll('th')); arr.forEach(function (th,index) { var cellWidth = document.defaultView.getComputedStyle(obj.table.querySelectorAll('th')[index]).width; th.style.width = cellWidth; }); // } } } /** * 创建固定表头 * @param obj */ function cloneHeaderRow(obj) { obj.container.innerHTML = ""; obj.container.className = "freezeHeader" ; var freezeTable = document.createElement("table"); var freezeHeader = document.createElement("thead"); var attributes = obj.table.attributes; for(var i=0;i < attributes.length;i++){ if (attributes[i].name != "id") { freezeTable.setAttribute(attributes[i].name, attributes[i].value); } } freezeTable.style.width = obj.table.clientWidth + 'px'; freezeTable.style.margin = "0px"; freezeHeader.innerHTML = obj.header.innerHTML; obj.container.appendChild(freezeTable); obj.container.querySelector('table').appendChild(freezeHeader); obj.container.querySelector('thead').id = ''; obj.container.querySelector('tr').id = ''; var arr = Array.prototype.slice.call(obj.container.querySelectorAll('th')); arr.forEach(function (th,index) { th.id = ''; th.style.width = document.defaultView.getComputedStyle(obj.table.querySelectorAll('th')[index]).width; }); hideFreeze(obj); } /** * 隐藏固定表头 */ function hideFreeze(obj) { obj.container.style.visibility = "hidden"; obj.container.style.height = "0px"; } /** * 显示固定表头 */ function showFreeze(obj) { obj.container.style.visibility = "visible"; obj.container.style.height = obj.header.clientHeight + 'px'; } }; <file_sep>/nodejs/crypto/hmac.js const crypto = require('crypto'); const cryptoUtils = new Object(); cryptoUtils.hmac = function(data) { const hmac = crypto.createHmac('sha256', 'secret-key'); hmac.update(data); return hmac.digest('hex').toUpperCase(); } console.log(cryptoUtils.hmac('22222'));<file_sep>/py/101cases/test35.py class bcolors: HEADER = '\033[95m' ENDC = '\033[0m' print bcolors.HEADER + 'header' + bcolors.ENDC<file_sep>/nodejs/fs/readfilesync.js 'use strict' try { var data = fs.readFileSync('test.txt', 'utf-8'); console.log(data); } catch (err) { // 出错了 }<file_sep>/algorithm/1000/1000.py while True: try: (x, y) = (int(x) for x in raw_input().split()) print x + y except EOFError: break<file_sep>/backup/zhaochen-2018-7-homework/README.md ### 需求澄清: 井字游戏是简化的五子棋游戏, 两方参与, 在空置位置放置棋子, 最先达到三棋子连成一条线者获胜。 依据当前棋局, 给出参与者一步棋获胜的解法。 考虑实际场景, 需要前提: 1. 当前游戏未结束。 不是平局、不是获胜方、不是失败方。 ### 算法: 1. 简化输入 2. 判断是否有下一步输入的条件--空余位置、仍未胜输 3. 遍历剩余位置 4. 判断某位置为下一步若获胜, 给出为位置坐标--当前行、当前列、对角线上的点对角线,满足其中一个连续相同的符号 ### 说明 由于时间有限, 仅给出函数接口。tictactoe.initMatrix(str, matric); 每个小模块已做自测。 释放注释 node 运行 index.js 参考实例测试结构见png<file_sep>/py/101cases/test3.py # math # import math for i in range(1,85): if 168 % i == 0: j = 168 / i if i > j and (i+j)%2 == 0 and (i-j)%2 == 0: n = (i-j) /2 print(n * n -100) <file_sep>/py/101cases/test55.py a = 234 print ~a<file_sep>/py/101cases/test6.py def fib(max): li = [1] len = max if len > 1: li.append(1) len -= 1 for i in range(1, len): li.append(li[i-1] + li[i]) return li print fib(9) <file_sep>/py/101cases/test60.py print len('12345') print '12345'.__len__()
54e14e0f0140058aa7c422aaaecccd60d117b515
[ "Markdown", "Python", "JavaScript", "HTML" ]
76
Markdown
daaasheng/dash
7cad23c7207a6ee62c994a7206cf6dd5ba0a2a5b
6bc3696e17217d03713205e739d82d990ddb96fa
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { public delegate void Mydelegate(); static void Main(string[] args) { var d1 = new Mydelegate(F1); Mydelegate d2 = F1; Mydelegate d3 = null; d3 = d1 + d2; Function(d1); Function(d2); Function(d3); } static void F1() { Console.WriteLine("F1"); Console.ReadLine(); } static void Function(Mydelegate d) { if (d == null) { throw new ArgumentNullException(nameof(d)); } d(); } } }
ae9164c30ed7b76072b7c73c0bedcf408d964561
[ "C#" ]
1
C#
ssaqo/digitain-coding-bootcamp
42348d14f49a7db21fc0070ae86337f29ef796d6
3a3eb3bbc360f5fb1f11fff4431662ec7da3984c
refs/heads/main
<file_sep># Stock Tracker - A simple stock tracking app ## Running the application Open this project's directory in a command line Run Project: `npm run serve` Run Unit Tests: `npm run test:unit` Build Project: `npm run build` ## Framework Stock Tracker was built using Vue.js (initialized with the Vue CLI) ## API Info This project uses the IEX Cloud API to grab stock prices. Find more information here: https://iexcloud.io/ <file_sep>const state = { symbols: localStorage.getItem('symbols') ? JSON.parse(localStorage.getItem('symbols')) : ["TLSA", "AAPL", "GOOG"], symbolData: [], symbolNameError: "", symbolServerError: "", loadingStatus: false }; export const getters = { allSymbolData: state => state.symbolData, getSymbolNameError: state => state.symbolNameError, getSymbolServerError: state => state.symbolServerError, getLoadingStatus: state => state.loadingStatus }; export const actions = { async getSymbolData({commit}) { commit('setLoadingStatus', true); let symbolData = []; if (state.symbols.length > 0) { await fetch(`https://cloud.iexapis.com/v1/stock/market/batch?types=quote&symbols=${state.symbols.join()}&range=5y%20&token=<PASSWORD>`, {headers: {'Content-Type': 'application/json'}}) .then(response => response.json()) .then(data => { Object.keys(data).forEach(function(key) { symbolData.push({symbol: data[key].quote.symbol, latestPrice: data[key].quote.latestPrice, change: data[key].quote.change}) }); commit('setSymbolData', symbolData); commit('setSymbolServerError', ""); commit('setLoadingStatus', false); }) .catch(() => { commit('setSymbolServerError', "Couldn't contact server"); commit('setLoadingStatus', false); }); } else { commit('setSymbolData', symbolData); commit('setLoadingStatus', false); } }, async addSymbol({commit}, newSymbol) { commit('setLoadingStatus', true); let symbolUpperCase = newSymbol.toUpperCase(); await fetch(`https://cloud.iexapis.com/stable/stock/${symbolUpperCase}/quote?token=<PASSWORD>`, {headers: {'Content-Type': 'application/json'}}) .then(response => response.json()) .then(data => { if (data.symbol === symbolUpperCase) { let symbolData = {symbol: data.symbol, latestPrice: data.latestPrice, change: data.change}; commit('addSymbol', symbolUpperCase); commit('addSymbolData', symbolData); commit('setSymbolNameError', ""); } commit('setLoadingStatus', false); }) .catch(() => { commit('setSymbolNameError', "Couldn't find symbol"); commit('setLoadingStatus', false); }); }, async deleteSymbol({commit}, symbolName) { commit('removeSymbol', symbolName); }, async removeAllSymbols({commit}) { commit('removeAllSymbols'); commit('setSymbolData', []) } }; export const mutations = { setSymbolData: (state, symbolData) => (state.symbolData = symbolData), addSymbol: (state, newSymbol) => { state.symbols.push(newSymbol); localStorage.setItem('symbols', JSON.stringify(state.symbols)); }, addSymbolData: (state,symbolData) => (state.symbolData.push(symbolData)), removeSymbol: (state,symbolName) => { state.symbols = state.symbols.filter(symbol => symbol !== symbolName); state.symbolData = state.symbolData.filter(data => data.symbol !== symbolName); localStorage.setItem('symbols', JSON.stringify(state.symbols)); }, removeAllSymbols: (state) => { state.symbols = []; state.symbolData = []; localStorage.removeItem('symbols'); }, setSymbolNameError: (state, newError) => (state.symbolNameError = newError), setSymbolServerError: (state, newError) => (state.symbolServerError = newError), setLoadingStatus: (state, newStatus) => (state.loadingStatus = newStatus) }; export default {state, getters, actions, mutations} <file_sep>import SymbolOptions from '@/components/SymbolOptions.vue'; import Vuex from 'vuex'; import store from '@/store'; import {createLocalVue, shallowMount} from '@vue/test-utils'; const localVue = createLocalVue(); localVue.use(Vuex); global.fetch = jest.fn(() => Promise.resolve([{symbol:'TLSA', latestPrice: 1023.92, change: -20.58}])); describe("SymbolOptions", () => { let wrapper = null; beforeEach(() => { wrapper = shallowMount(SymbolOptions, { localVue, store }); }); afterEach(() => { wrapper.destroy() }) it('Submit button fires addSymbol and submitSymbol event with valid input. Symbol input is then cleared', async () => { const submitSymbol = jest.spyOn(wrapper.vm, 'submitSymbol'); const addSymbol = jest.spyOn(wrapper.vm, 'addSymbol'); await wrapper.setData({symbol: 'GNUS'}); await wrapper.findAll('#symbolOptions-addSymbol button').at(0).trigger('click'); expect(submitSymbol).toHaveBeenCalled(); expect(addSymbol).toHaveBeenCalled(); expect(wrapper.findAll('input').at(0).text()).toMatch(''); }); it('Submit button fires submitSymbol event and then throws error to user on incorrect input', async () => { const submitSymbol = jest.spyOn(wrapper.vm, 'submitSymbol'); const addSymbol = jest.spyOn(wrapper.vm, 'addSymbol'); await wrapper.setData({symbol: ''}); await wrapper.findAll('#symbolOptions-addSymbol button').at(0).trigger('click'); expect(submitSymbol).toHaveBeenCalled(); expect(addSymbol).not.toHaveBeenCalled(); expect(wrapper.findAll('input').at(0).classes()).toContain('input-error'); }); it('Refresh button fires getSymbolData event', async () => { const getSymbolData = jest.spyOn(wrapper.vm, 'getSymbolData'); await wrapper.find('#symbolOptions-refreshBtn').trigger('click'); expect(getSymbolData).toHaveBeenCalled(); }); }); <file_sep>import NavBar from '@/components/NavBar.vue'; import {shallowMount} from '@vue/test-utils'; describe("NavBar", () => { let wrapper = null; beforeEach(() => { wrapper = shallowMount(NavBar, { stubs: ['router-link'] }); }); afterEach(() => { wrapper.destroy() }) it('Default Render', () => { expect(wrapper.findAll('router-link-stub').at(0).text()).toMatch('Tracker'); expect(wrapper.findAll('router-link-stub').at(0).attributes().to).toMatch('/'); expect(wrapper.findAll('router-link-stub').at(1).text()).toMatch('Settings'); expect(wrapper.findAll('router-link-stub').at(1).attributes().to).toMatch('/settings'); }); }); <file_sep>import {getters} from '@/store/symbols.js'; describe("Symbol Store Getters", () => { let state = { symbols: ["TLSA"], symbolData: [{symbol:'TLSA', latestPrice: 1023.92, change: -20.58}], symbolNameError: "A name error", symbolServerError: "A server error", loadingStatus: false }; it('Get All Symbol Data', async () => { const symbolData = [{symbol:'TLSA', latestPrice: 1023.92, change: -20.58}]; const retrievedData = await getters.allSymbolData(state); expect(retrievedData[0].symbol).toBe(symbolData[0].symbol); expect(retrievedData[0].latestPrice).toBe(symbolData[0].latestPrice); expect(retrievedData[0].change).toBe(symbolData[0].change); }); it('Get Symbol Name Error', () => { const nameError = "A name error"; expect(getters.getSymbolNameError(state,nameError)).toBe(nameError); }); it('Get Symbol Server Error', () => { const serverError = "A server error"; expect(getters.getSymbolServerError(state,serverError)).toBe(serverError); }); it('Get Loading Status', () => { const expectedStatus = false; expect(getters.getLoadingStatus(state,expectedStatus)).toBe(expectedStatus); }); }); <file_sep>import SymbolObject from '@/components/SymbolObject.vue'; import Vuex from 'vuex'; import store from '@/store'; import {createLocalVue, shallowMount} from '@vue/test-utils'; const localVue = createLocalVue(); localVue.use(Vuex); describe("SymbolObject", () => { let wrapper = null; beforeEach(() => { wrapper = shallowMount(SymbolObject, { localVue, store, propsData: { symbol: 'GNUS', price: 1.79, change: -0.02, } }); }); afterEach(() => { wrapper.destroy() }) it('Renders with valid props', () => { expect(wrapper.findAll('p').at(0).text()).toMatch('GNUS'); expect(wrapper.findAll('strong').at(0).text()).toMatch('$1.79'); expect(wrapper.findAll('span').at(0).text()).toMatch('(-0.02)'); }); it('Object is missing props', async () => { await wrapper.setProps({symbol: null, price: null, change: null}); expect(wrapper.findAll('p').at(0).text()).toMatch('?'); expect(wrapper.findAll('strong').at(0).text()).toMatch('Unavaliable'); expect(wrapper.findAll('span').at(0).text()).toMatch('(Unavaliable)'); }); it('Object has positive class on positive change', async () => { await wrapper.setProps({change: 0.02}); expect(wrapper.findAll('.symbolObject').at(0).classes()).toContain('symbolObject-positive'); }); it('Object has negative class on negative change', () => { expect(wrapper.findAll('.symbolObject').at(0).classes()).toContain('symbolObject-negative'); }); it('Delete button fires both submitDeleteSymbol and Vuex deleteSymbol actions', async () => { const submitDeleteSymbol = jest.spyOn(wrapper.vm, 'submitDeleteSymbol'); const vuexDeleteSymbol = jest.spyOn(wrapper.vm, 'deleteSymbol'); await wrapper.findAll('img').at(0).trigger('click'); expect(submitDeleteSymbol).toHaveBeenCalled(); expect(vuexDeleteSymbol).toHaveBeenCalled(); }); }); <file_sep>import Footer from '@/components/Footer.vue'; import {shallowMount} from '@vue/test-utils'; describe("Footer", () => { let wrapper = null; beforeEach(() => { wrapper = shallowMount(Footer); }); afterEach(() => { wrapper.destroy() }) it('Default Render', () => { expect(wrapper.findAll('span').at(0).text()).toMatch('Stocks are pulled from the IEX Cloud API'); }); }); <file_sep>import {mutations} from '@/store/symbols.js'; const fakelocalStorage = { getItem: jest.fn(), removeItem: jest.fn(), setItem: jest.fn() }; global.localStorage = fakelocalStorage; describe("Symbol Store Mutations", () => { let state = { symbols: ["TLSA", "AAPL", "GOOG"], symbolData: [ {symbol:'TLSA', latestPrice: 1023.92, change: -20.58}, {symbol:'AAPL', latestPrice: 321.22, change: -0.34}, {symbol:'GOOG', latestPrice: 10.94, change: 0.022} ], symbolNameError: "", symbolServerError: "", loadingStatus: false }; it('Remove All Symbols', () => { mutations.removeAllSymbols(state); expect(state.symbols.length).toBe(0); expect(state.symbolData.length).toBe(0); expect(localStorage.getItem('symbols')).toBe(null); }); it('Set Symbol Data', () => { let symbolData = [{symbol:'GNUS', latestPrice: 1.92, change: 0.02}]; mutations.setSymbolData(state,symbolData); expect(state.symbolData).toBe(symbolData); }); it('Add Symbol', () => { let newSymbol = "GNUS"; mutations.addSymbol(state,newSymbol); expect(state.symbols.includes(newSymbol)).toBe(true); expect(JSON.parse(localStorage.getItem('symbols')).includes(newSymbol)).toBe(true); }); it('Add Symbol Data', () => { let symbolData = [{symbol:'GNUS', latestPrice: 1.92, change: 0.02}]; mutations.addSymbol(state,symbolData); expect(state.symbolData[0].symbol).toBe(symbolData[0].symbol); expect(state.symbolData[0].latestPrice).toBe(symbolData[0].latestPrice); expect(state.symbolData[0].change).toBe(symbolData[0].change); }); it('Remove Symbol', () => { let removedSymbol = "GNUS"; mutations.removeSymbol(state,removedSymbol); expect(state.symbols.includes(removedSymbol)).toBe(false); expect(state.symbolData.length).toBe(0); expect(JSON.parse(localStorage.getItem('symbols')).includes('GNUS')).toBe(false); }); it('Set Symbol Name Error', () => { mutations.setSymbolNameError(state,"test"); expect(state.symbolNameError).toBe("test"); }); it('Set Symbol Server Error', () => { mutations.setSymbolServerError(state,"test"); expect(state.symbolServerError).toBe("test"); }); it('Change loading status to true', () => { mutations.setLoadingStatus(state,true); expect(state.loadingStatus).toBe(true); }); }); <file_sep>import SymbolContainer from '@/components/SymbolContainer.vue'; import Vuex from 'vuex'; import store from '@/store'; import {createLocalVue, shallowMount} from '@vue/test-utils'; const localVue = createLocalVue(); localVue.use(Vuex); global.fetch = jest.fn(() => Promise.resolve([{symbol:'TLSA', latestPrice: 1023.92, change: -20.58}])); describe("SymbolContainer", () => { let wrapper = null; beforeEach(() => { wrapper = shallowMount(SymbolContainer, { localVue, store }); }); afterEach(() => { wrapper.destroy() }) it('getSymbolData is called upon init', () => { const getSymbolData = jest.spyOn(wrapper.vm, 'getSymbolData'); SymbolContainer.created.call(wrapper.vm); expect(getSymbolData).toHaveBeenCalled(); }); }); <file_sep>import {actions, mutations} from '@/store/symbols.js'; import fetchMock from "jest-fetch-mock"; fetchMock.enableMocks(); describe("Symbol Store Actions", () => { let state = { symbols: ["TLSA", "AAPL", "GOOG"], symbolData: [ {symbol:'TLSA', latestPrice: 1023.92, change: -20.58}, {symbol:'AAPL', latestPrice: 321.22, change: -0.34}, {symbol:'GOOG', latestPrice: 10.94, change: 0.022} ], symbolNameError: "", symbolServerError: "", loadingStatus: false }; it('Get all symbol data with successful fetch', () => { const symbolRequestData = {'TLSA': {'quote' : {symbol:'TLSA', latestPrice: 1023.92, change: -20.58}}}; const symbolData = [{symbol: 'TLSA', latestPrice: 1023.92, change: -20.58}]; const commitObj = { commit: jest.fn() } const commitSpy = jest.spyOn(commitObj, 'commit'); fetch.mockResponseOnce(JSON.stringify(symbolRequestData)); actions.getSymbolData(commitObj) .then(() => { expect(commitSpy.mock.calls).toEqual([ ['setLoadingStatus', true], ['setSymbolData', symbolData], ['setSymbolServerError', ''], ['setLoadingStatus', false], ]); }) }); it('Get all symbol data with unsuccessful fetch', () => { const commitObj = { commit: jest.fn() } const commitSpy = jest.spyOn(commitObj, 'commit'); fetch.mockRejectOnce(new Error('Could not grab quotes')); actions.getSymbolData(commitObj) .then(() => { expect(commitSpy.mock.calls).toEqual([ ['setLoadingStatus', true], ['setSymbolServerError', "Couldn't contact server"], ['setLoadingStatus', false], ]); }) }); it('Add Symbol with successful fetch', () => { const symbolToAdd = "TLSA"; const symbolData = {symbol:'TLSA', latestPrice: 1023.92, change: -20.58}; const commitObj = { commit: jest.fn() } const commitSpy = jest.spyOn(commitObj, 'commit'); fetch.mockResponseOnce(JSON.stringify(symbolData)); actions.addSymbol(commitObj, symbolToAdd) .then(() => { expect(commitSpy.mock.calls).toEqual([ ['setLoadingStatus', true], ['addSymbol', symbolToAdd], ['addSymbolData', symbolData], ['setSymbolNameError', ''], ['setLoadingStatus', false], ]); }) }); it('Add Symbol with unsuccessful fetch', () => { const symbolToAdd = "TLSA"; const symbolData = {symbol:'TLSA', latestPrice: 1023.92, change: -20.58}; const commitObj = { commit: jest.fn() } const commitSpy = jest.spyOn(commitObj, 'commit'); fetch.mockRejectOnce(new Error('Could not grab symbol')); actions.addSymbol(commitObj, symbolToAdd) .then(() => { expect(commitSpy.mock.calls).toEqual([ ['setLoadingStatus', true], ['setSymbolNameError', "Couldn't find symbol"], ['setLoadingStatus', false], ]); }) }); it('Delete Symbol', () => { const symbolToDelete = "TLSA"; const commitObj = { commit: jest.fn() } const commitSpy = jest.spyOn(commitObj, 'commit'); actions.deleteSymbol(commitObj, symbolToDelete) .then(() => { expect(commitSpy).toHaveBeenCalledWith('removeSymbol', symbolToDelete); }) }); it('Remove All Symbols', () => { const commitObj = { commit: jest.fn() } const commitSpy = jest.spyOn(commitObj, 'commit'); actions.removeAllSymbols(commitObj) .then(() => { expect(commitSpy.mock.calls).toEqual([ ['removeAllSymbols'], ['setSymbolData', []] ]); }) }); }); <file_sep>import RemoveSymbolsBtn from '@/components/RemoveSymbolsBtn.vue'; import Vuex from 'vuex'; import store from '@/store'; import {createLocalVue, shallowMount} from '@vue/test-utils'; const localVue = createLocalVue(); localVue.use(Vuex); describe("RemoveSymbolsBtn", () => { let wrapper = null; beforeEach(() => { wrapper = shallowMount(RemoveSymbolsBtn, { localVue, store }); }); afterEach(() => { wrapper.destroy() }) it('Remove button fires removeAllSymbols event', async () => { const removeAllSymbols = jest.spyOn(wrapper.vm, 'removeAllSymbols'); await wrapper.find('#settings-removeSymbolsBtn').trigger('click'); expect(removeAllSymbols).toHaveBeenCalled(); }); });
22ebd0525153206a687ce000b52c31d2412f20fc
[ "Markdown", "JavaScript" ]
11
Markdown
BCrausen/stock_tracker
1bfa19a5ad1f442eabcd35e106f5edca76b5005a
0f9daed39b307ed4c54010622601d4cc50320a03
refs/heads/master
<repo_name>MiguelFreire/rl-generalization<file_sep>/requirements.txt argparse==1.4.0 gym==0.15.3 numpy==1.17.3 nvidia-ml-py3==7.352.0 opencv-python==4.1.1.26 pandas==0.24.2 procgen==0.9.4 -e git+https://github.com/astooke/rlpyt.git@668290d1ca94e9d193388a599d4f719bc3a23fba#egg=rlpyt tensorboard==1.13.1 torch==1.5.0+cu101 torchsummary==1.5.1 torchvision==0.6.0+cu101 wandb==0.8.33 <file_sep>/evaluation/run_eval_dataaug.py import wandb import os import sys from evaluation import evaluate_generalization if __name__ == "__main__": models_to_evaluate = [ {"model_name":"CoinRunNature-ColorJitter", "num_levels": 500, "model_path": "../saved_models/CoinRunNature-ColorJitter.pt" , "data_aug": "jitter"}, {"model_name":"CoinRunNature-Cutout", "num_levels": 500, "model_path": "../saved_models/CoinRunNature-Cutout.pt", "data_aug": "cutout"}, ] evaluate_generalization(models_to_evaluate, "CoinRun-Evaluation-DataAug") sys.exit(0) <file_sep>/agents/impala.py from rlpyt.agents.pg.categorical import CategoricalPgAgent from models.impala import ImpalaModel from rlpyt.agents.pg.atari import AtariMixin #Agent that uses CNNNature with 2 heads to parametrize policy and value functions class ImpalaAgent(AtariMixin, CategoricalPgAgent): def __init__(self, **kwargs): super().__init__(ModelCls=ImpalaModel, **kwargs)<file_sep>/experiments/base.py from experiments.experiment import Experiment class BaseExperimentNature(Experiment): def __init__(self, name="CoinRunNatureLevels-default", num_levels=500, batchNorm=False, dropout=0.0, l2_penalty=0, entropy_bonus = 0.01, augment_obs=None, attention=None, num_steps=25_000_000, hidden_sizes=[512], max_pooling=False, arch="original", env="coinrun", gpu=0): self.num_levels = num_levels self.batchNorm = batchNorm self.dropout = dropout self.name = name self.l2_penalty = l2_penalty self.entropy_bonus = entropy_bonus self.augment_obs = augment_obs self.attention = attention self.num_steps = num_steps self.max_pooling = max_pooling self.hidden_sizes = hidden_sizes self.arch = arch self.env = env self.gpu = gpu def getConfig(self): return { "name": self.name, "discount": 0.999, "lambda": 0.95, "timesteps_per_rollout": 256, "epochs_per_rollout": 3, "minibatches_per_epoch": 8, "entropy_bonus": self.entropy_bonus, "ppo_clip": 0.2, "learning_rate": 5e-4, "workers": 8, "envs_per_worker": 64, "total_timesteps": self.num_steps, "l2_penalty": self.l2_penalty, "dropout": self.dropout, "batchNorm": self.batchNorm, "num_levels": self.num_levels, "model": "nature", "augment_obs": self.augment_obs, "attention": self.attention, "maxpool": self.max_pooling, "hidden_sizes": self.hidden_sizes, "arch": self.arch, "env": self.env, "gpu": self.gpu, } <file_sep>/README.md # rl-generalization- Master Thesis code on optimization of RL algorithms and Deep Learning Models with focus on generalization <file_sep>/experiments/ppo.py from rlpyt.algos.pg.ppo import PPO default = { "discount": 0.999, "lambda": 0.95, "timesteps_per_rollout": 256, "epochs_per_rollout": 3, "minibatches_per_epoch": 8, "entropy_bonus": 0.01, "ppo_clip": 0.2, "learning_rate": 5e-4, "workers": 4, "envs_per_worker": 64, "total_timesteps": 25_000_000, } def makePPOExperiment(config): return PPO(discount=config["discount"], entropy_loss_coeff=config["entropy_bonus"], gae_lambda=config["lambda"], minibatches=config["minibatches_per_epoch"], epochs=config["epochs_per_rollout"], ratio_clip=config["ppo_clip"], learning_rate=config["learning_rate"], normalize_advantage=True) <file_sep>/models/impala.py import torch from torch.nn import functional as F from rlpyt.models.utils import conv2d_output_shape from rlpyt.utils.tensor import infer_leading_dims, restore_leading_dims class ResidualBlock(torch.nn.Module): def __init__(self, in_channels, channels, layers=2, kernel_size=3, stride=1, padding=1, useConv1x1=False): super().__init__() non_linearlity = torch.nn.ReLU() if layers == 2: conv1 = torch.nn.Conv2d(in_channels=in_channels, out_channels=channels, kernel_size=kernel_size, stride=stride, padding=padding) conv2 = torch.nn.Conv2d(in_channels=channels, out_channels=channels, kernel_size=kernel_size, stride=stride, padding=padding) self.block = torch.nn.Sequential(*[non_linearlity, conv1, non_linearlity, conv2]) else: conv = torch.nn.Conv2d(in_channels=in_channels, out_channels=channels, kernel_size=kernel_size, stride=stride, padding=padding) self.block = torch.nn.Sequential(*[non_linearlity, conv]) self.conv1x1 = torch.nn.Conv2d(in_channels, out_channels=channels, kernel_size=1, stride=1) if useConv1x1 else None def forward(self, x): residual = x if self.conv1x1: residual = self.conv1x1(x) y = self.block(x) return y + residual def conv_out_size(self, h, w, c=None): """Helper function ot return the output size for a given input shape, without actually performing a forward pass through the model.""" for child in self.block.children(): try: h, w = conv2d_output_shape(h, w, child.kernel_size, child.stride, child.padding) except AttributeError: pass # Not a conv or maxpool layer. try: c = child.out_channels except AttributeError: pass # Not a conv layer. return h, w, c class ImpalaBlock(torch.nn.Module): def __init__(self, in_channels, channels): super().__init__() conv1 = torch.nn.Conv2d(in_channels=in_channels, out_channels=channels, kernel_size=3, stride=1, padding=1) maxpool = torch.nn.MaxPool2d(kernel_size=3, stride=2, padding=1) resBlock1 = ResidualBlock(in_channels=channels, channels=channels) resBlock2 = ResidualBlock(in_channels=channels, channels=channels) self.block = torch.nn.Sequential(*[conv1, maxpool, resBlock1, resBlock2]) def forward(self, x): return self.block(x) def conv_out_size(self, h, w, c=None): """Helper function ot return the output size for a given input shape, without actually performing a forward pass through the model.""" for child in self.block.children(): if isinstance(child, torch.nn.Conv2d): h, w = conv2d_output_shape(h, w, child.kernel_size, child.stride, child.padding) c = child.out_channels elif isinstance(child, torch.nn.MaxPool2d): h, w = conv2d_output_shape(h, w, child.kernel_size, child.stride, child.padding) elif isinstance(child, ResidualBlock): h, w, c = child.conv_out_size(h,w,c) return h, w, c class ImpalaCNN(torch.nn.Module): def __init__(self, in_channels, out_channels): super().__init__() impala_blocks = ([ImpalaBlock(c_in,c_out) for (c_in, c_out) in zip(in_channels, out_channels)]) self.blocks = torch.nn.Sequential(*impala_blocks) def forward(self,x): return self.blocks(x) def conv_out_size(self, h, w, c=None): for child in self.blocks.children(): h, w, c = child.conv_out_size(h, w, c) return h * w * c class ImpalaHead(torch.nn.Module): def __init__( self, image_shape, in_channels, out_channels, hidden_size ): super().__init__() c, h, w = image_shape self.conv = ImpalaCNN(in_channels, out_channels) conv_output_size = self.conv.conv_out_size(h,w,c) self.head = torch.nn.Linear(conv_output_size, hidden_size) self.output_size = hidden_size def forward(self,x): y = torch.nn.functional.relu(self.conv(x)) y = self.head(y.view(x.shape[0], -1)) return torch.nn.functional.relu(y) class ImpalaModel(torch.nn.Module): def __init__( self, image_shape, output_size, in_channels, out_channels, hidden_size ): super().__init__() c, h, w = image_shape self.conv = ImpalaHead(image_shape, in_channels, out_channels, hidden_size) self.pi = torch.nn.Linear(self.conv.output_size, output_size) #value function head self.value = torch.nn.Linear(self.conv.output_size, 1) def forward(self, image, prev_action=None, prev_reward=None): #input normalization, cast to float then grayscale it img = image.type(torch.float) img = img.mul_(1. / 255) lead_dim, T, B, img_shape = infer_leading_dims(img, 3) fc_out = self.conv(img.view(T * B, *img_shape)) pi = torch.nn.functional.softmax(self.pi(fc_out), dim=-1) v = self.value(fc_out).squeeze(-1) # Restore leading dimensions: [T,B], [B], or [], as input. #T -> transition #B -> batch_size? pi, v = restore_leading_dims((pi, v), lead_dim, T, B) return pi, v<file_sep>/experiments/experiment.py import torch #from rlpyt.samplers.parallel.cpu.sampler import CpuSampler from rlpyt.utils.launching.affinity import affinity_from_code from rlpyt.samplers.parallel.gpu.sampler import GpuSampler from rlpyt.runners.minibatch_rl import MinibatchRl from rlpyt.utils.logging.context import logger_context from agents.nature import OriginalNatureAgent, AttentionNatureAgent, SelfAttentionNatureAgent, NatureRecurrentAgent from rlpyt.samplers.parallel.gpu.collectors import GpuResetCollector from agents.impala import ImpalaAgent from rlpyt.algos.pg.ppo import PPO from gym import Wrapper from environments.procgen import ProcgenWrapper import gym import wandb def make_env(*args, **kwargs): num_levels = kwargs['num_levels'] difficulty="easy" paint_vel_info=True seed=42069 if "env" in kwargs: env_name = "procgen:procgen-"+kwargs['env']+"-v0" else: env_name = "procgen:procgen-coinrun-v0" start_level = kwargs["start_level"] if "start_level" in kwargs else 0 env = gym.make(env_name, num_levels=num_levels, start_level=start_level, distribution_mode=difficulty, paint_vel_info=paint_vel_info) return ProcgenWrapper(env) class Experiment: def getConfig(self): return { "name": "CoinRunNature500-default", "discount": 0.999, "lambda": 0.95, "timesteps_per_rollout": 256, "epochs_per_rollout": 3, "minibatches_per_epoch": 8, "entropy_bonus": 0.01, "ppo_clip": 0.2, "learning_rate": 5e-4, "workers": 8, "envs_per_worker": 64, "total_timesteps": 30_000_000, "dropout": 0.0, "batchNorm": False, "num_levels": 500, "model": "nature", "augment_obs": "", "attention": None, "maxpool": False, "hidden_sizes": 512, "arch": "original", "env": "coinrun", } def run(self, run_ID=0): config = self.getConfig() sampler = GpuSampler( EnvCls=make_env, env_kwargs={"num_levels": config["num_levels"], "env": config['env']}, CollectorCls=GpuResetCollector, batch_T=256, batch_B=config["envs_per_worker"], max_decorrelation_steps=1000) optim_args = dict(weight_decay=config["l2_penalty"]) if "l2_penalty" in config else None algo = PPO( value_loss_coeff=0.5, clip_grad_norm=0.5, discount=config["discount"], entropy_loss_coeff=config["entropy_bonus"], gae_lambda=config["lambda"], minibatches=config["minibatches_per_epoch"], epochs=config["epochs_per_rollout"], ratio_clip=config["ppo_clip"], learning_rate=config["learning_rate"], normalize_advantage=True, optim_kwargs=optim_args) if config["arch"] == 'impala': agent = ImpalaAgent(model_kwargs={"in_channels": [3,16,32], "out_channels": [16,32,32], "hidden_size": 256}) elif config["arch"] == 'lstm': agent = NatureRecurrentAgent(model_kwargs={"hidden_sizes": [512], "lstm_size": 256}) else: agent = OriginalNatureAgent(model_kwargs={"batchNorm": config["batchNorm"], "dropout": config["dropout"], "augment_obs": config["augment_obs"], "use_maxpool": config["maxpool"], "hidden_sizes": config["hidden_sizes"], "arch": config["arch"]}) affinity = dict(cuda_idx=config['gpu']) runner = MinibatchRl( algo=algo, agent=agent, sampler=sampler, n_steps=config["total_timesteps"], log_interval_steps=500, affinity=affinity) log_dir="./logs" name=config["name"] with logger_context(log_dir, run_ID, name, config, use_summary_writer=True, override_prefix=False): runner.train() torch.save(agent.state_dict(), "./" + name + ".pt") wandb.save("./" + name + ".pt") <file_sep>/run_eval.py import wandb import os import sys from evaluation.evaluate import evaluate_generalization from argparse import ArgumentParser if __name__ == "__main__": parser = ArgumentParser() parser.add_argument('--name', type=str, default="Default Name") parser.add_argument('--path', type=str) parser.add_argument('--num_levels', type=int, default=200) parser.add_argument('--batchNorm', type=bool, default=False) parser.add_argument('--dropout', type=float, default=0.0) parser.add_argument('--augment_obs', type=str, default=None) parser.add_argument('--hidden_sizes', nargs='+', type=int, default=[512]) parser.add_argument('--max_pooling', type=bool, default=False) parser.add_argument('--arch', type=str, default="original") parser.add_argument('--env', type=str, default="coinrun") args = parser.parse_args() model_to_evaluate = vars(args) evaluate_generalization(model_to_evaluate) sys.exit(0) <file_sep>/evaluation/evaluate.py import torch import os import wandb from agents.nature import OriginalNatureAgent, NatureRecurrentAgent from agents.impala import ImpalaAgent from experiments.experiment import make_env from rlpyt.utils.prog_bar import ProgBarCounter import pandas import numpy as np import multiprocessing as mp def calculateWinRate(levels_outcome): wins = 0 for level in levels_outcome: if level: wins += 1 return wins / len(levels_outcome) * 100 def evaluate_in_training(agent, num_levels=500, seed=42069, env_name='procgen'): print("Evaluating in training") env = make_env(num_levels=1, start_level=0, seed=seed, env=env_name) levels = [False for i in range(num_levels)] for j in range(num_levels): #Init level reset variables env = make_env(num_levels=1, start_level=j, seed=seed, env=env_name) done = False obs, _, _, info = env.step(-1) obs = torch.from_numpy(obs).unsqueeze(0) prev_action = torch.tensor(0.0, dtype=torch.float) #None prev_reward = torch.tensor(0.0, dtype=torch.float) #None while True: if done: if info.prev_level_complete: levels[j] = True break step = agent.step(obs, prev_action, prev_reward) obs, rewards, done, info = env.step(step.action) obs = torch.from_numpy(obs).unsqueeze(0) prev_action = step.action.clone() prev_reward = torch.tensor([rewards], dtype=torch.float) return calculateWinRate(levels) def evaluate_in_testing(agent, num_levels=5000, start_level=400000, seed=42069, env_name='procgen'): print("Evaluating in testing") env = make_env(num_levels=1, start_level=start_level, seed=seed, env=env_name) levels = [False for i in range(num_levels)] for j in range(num_levels): env = make_env(num_levels=1, start_level=start_level+j, seed=seed, env=env_name) done = False obs, _, _, info = env.step(-1) obs = torch.from_numpy(obs).unsqueeze(0) prev_action = torch.tensor(0.0, dtype=torch.float) #None prev_reward = torch.tensor(0.0, dtype=torch.float) #None while True: if done: if info.prev_level_complete: levels[j] = True break step = agent.step(obs, prev_action, prev_reward) obs, rewards, done, info = env.step(step.action) # Next stat obs = torch.from_numpy(obs).unsqueeze(0) prev_action = step.action.clone() prev_reward = torch.tensor([rewards], dtype=torch.float) return calculateWinRate(levels) def evaluate(i, agent, num_levels=200, start_level=0, env_name="procgen", q=None): if start_level == 0: #evaluate training result = (i, evaluate_in_training(agent, num_levels, env_name=env_name)) if q is not None: q.put(result) return result else: result = (i, evaluate_in_testing(agent, start_level=start_level, num_levels=num_levels, env_name=env_name)) if q is not None: q.put(result) return result def evaluate_generalization(m): data = [] wandb.init(name=m['name']) print("Evaluation " + m['name'] + "\n") saved_params = torch.load(os.getcwd() + m['path']) batchNorm = m['batchNorm'] if "batchNorm" in m else False dropout = m['dropout'] if "dropout" in m else 0.0 data_aug= m['augment_obs'] if "augment_obs" in m else None hidden_sizes = m['hidden_sizes'] if "hidden_sizes" in m else [512] max_pooling = m['max_pooling'] if "max_pooling" in m else False arch = m['arch'] if "arch" in m else "original" env = m['env'] if "env" in m else "coinrun" impala = arch == 'impala' model_kwargs = { "batchNorm": batchNorm, "dropout": dropout, "augment_obs": data_aug, "hidden_sizes": hidden_sizes, "use_maxpool": max_pooling, "arch": arch, } impala_kwargs = { "in_channels": [3, 16, 32], "out_channels": [16, 32, 32], "hidden_size": 512, } lstm_kwargs = { "hidden_sizes": [512], "lstm_size": 256, } if impala: agent = ImpalaAgent(initial_model_state_dict=saved_params, model_kwargs=impala_kwargs) else: if arch === 'lstm': agent = NatureRecurrentAgent(initial_model_state_dict=saved_params, model_kwargs=model_kwargs) else: agent = OriginalNatureAgent(initial_model_state_dict=saved_params, model_kwargs=model_kwargs) num_levels = m['num_levels'] dummy_env = make_env(num_levels=1, start_level=0, env=env) agent.initialize(dummy_env.spaces, share_memory=True) agent.eval_mode(0) mp.set_start_method('spawn', force=True) q = mp.Queue() params = [ (0, agent, num_levels, 0, env, q), (1, agent, 500, 40000, env, q), (2, agent, 500, 50000, env, q), (3, agent, 500, 60000, env, q) ] processes = [] results = [] for param in params: p = mp.Process(target=evaluate, args=param) p.start() processes.append(p) for p in processes: p.join() for i in params: results.append(q.get()) results.sort(key=lambda x: x[0]) train_winrate = results[0][1] test_winrate = np.array([results[1][1], results[2][1], results[3][1]]) std = np.std(test_winrate) avg = np.average(test_winrate) wandb.log({ "Train": train_winrate, "Test 1": test_winrate[0], "Test 2": test_winrate[1], "Test 3": test_winrate[2], "Test Std": std, "Test Avg": avg, }) return <file_sep>/evaluation/run_eval_arch.py import wandb import os import sys from evaluation import evaluate_generalization if __name__ == "__main__": models_to_evaluate = [ {"model_name":"CoinRunImpala-16", "num_levels": 500, "model_path": "../saved_models/CoinRunImpala-16.pt"}, {"model_name":"CoinRunImpala-16-32", "num_levels": 500, "model_path": "../saved_models/CoinRunImpala-16-32.pt"}, {"model_name":"CoinRunImpala-16-32-32", "num_levels": 500, "model_path": "../saved_models/CoinRunImpala-16-32-32.pt"}, ] evaluate_generalization(models_to_evaluate, "CoinRun-Evaluation-Architecture", impala=True) sys.exit(0) <file_sep>/evaluation/run_eval_batchnorm.py import wandb import os import sys from evaluation import evaluate_generalization if __name__ == "__main__": models_to_evaluate = [ {"model_name":"CoinRunNature-BatchNorm", "num_levels": 500, "model_path": "../saved_models/CoinRunNature-BatchNorm.pt", "batchNorm": True}, ] evaluate_generalization(models_to_evaluate, "CoinRun-Evaluation-BatchNorm") sys.exit(0) <file_sep>/evaluation/run_eval_l2.py import wandb import os import sys from evaluation import evaluate_generalization if __name__ == "__main__": models_to_evaluate = [ {"model_name":"CoinRunNature-l2-0.1", "num_levels": 500, "model_path": "../saved_models/CoinRunNature-L2-0.1.pt"}, {"model_name":"CoinRunNature-l2-0.25", "num_levels": 500, "model_path": "../saved_models/CoinRunNature-L2-0.25.pt"}, {"model_name":"CoinRunNature-l2-0.5", "num_levels": 500, "model_path": "../saved_models/CoinRunNature-L2-0.5.pt"}, {"model_name":"CoinRunNature-l2-1.0", "num_levels": 500, "model_path": "../saved_models/CoinRunNature-L2-1.0.pt"}, {"model_name":"CoinRunNature-l2-2.5", "num_levels": 500, "model_path": "../saved_models/CoinRunNature-L2-2.5.pt"}, ] evaluate_generalization(models_to_evaluate, "CoinRun-Evaluation-L2") sys.exit(0) <file_sep>/experiments/impala.py import torch from rlpyt.samplers.parallel.cpu.sampler import CpuSampler from rlpyt.runners.minibatch_rl import MinibatchRl from rlpyt.utils.logging.context import logger_context from agents.impala import ImpalaAgent from rlpyt.algos.pg.ppo import PPO from gym import Wrapper from environments.procgen import ProcgenWrapper import gym import wandb def make_env(*args, **kwargs): num_levels = kwargs['num_levels'] difficulty="easy" paint_vel_info=True seed=42069 env = gym.make("procgen:procgen-coinrun-v0", num_levels=num_levels, distribution_mode=difficulty, rand_seed=seed, paint_vel_info=paint_vel_info) return ProcgenWrapper(env) class ExperimentImpala: def __init__(self, name="CoinRunImpala-Default", num_levels=500, learning_rate=5e-4, in_channels=[3,16,32], out_channels=[16,32,32]): self.name = name self.learning_rate = learning_rate self.in_channels = in_channels self.out_channels = out_channels self.num_levels = num_levels def getConfig(self): return { "name": self.name, "discount": 0.999, "lambda": 0.95, "timesteps_per_rollout": 256, "epochs_per_rollout": 3, "minibatches_per_epoch": 8, "entropy_bonus": 0.01, "ppo_clip": 0.2, "learning_rate": self.learning_rate, "workers": 8, "envs_per_worker": 64, "total_timesteps": 25_000_000, "dropout": 0.0, "batchNorm": False, "num_levels": self.num_levels, "model": "impala", "out_channels": self.out_channels, "in_channels": self.in_channels, "hidden_size": 512, } def run(self): config = self.getConfig() sampler = CpuSampler( EnvCls=make_env, env_kwargs={"num_levels": config["num_levels"]}, batch_T=256, batch_B=8, max_decorrelation_steps=0) optim_args = dict(weight_decay=config["l2_penalty"]) if "l2_penalty" in config else None algo = PPO(discount=config["discount"], entropy_loss_coeff=config["entropy_bonus"], gae_lambda=config["lambda"], minibatches=config["minibatches_per_epoch"], epochs=config["epochs_per_rollout"], ratio_clip=config["ppo_clip"], learning_rate=config["learning_rate"], normalize_advantage=True, optim_kwargs=optim_args) agent = ImpalaAgent(model_kwargs={"in_channels": config["in_channels"], "out_channels": config["out_channels"], "hidden_size": config["hidden_size"]}) affinity = dict(cuda_idx=0, workers_cpus=list(range(config["workers"]))) runner = MinibatchRl( algo=algo, agent=agent, sampler=sampler, n_steps=25e6, log_interval_steps=500, affinity=affinity, seed=42069) log_dir="./logs" name=config["name"] run_ID=name with logger_context(log_dir, run_ID, name, config, use_summary_writer=True): runner.train() torch.save(agent.state_dict(), "./" + name + ".pt") wandb.save("./" + name + ".pt") <file_sep>/models/nature_attention.py import torch from rlpyt.models.utils import conv2d_output_shape from models.attention import SelfAttention, ProjectorBlock, LinearAttentionBlock from rlpyt.utils.tensor import infer_leading_dims, restore_leading_dims from environments.procgen import make_env import numpy as np class NatureSelfAttention(torch.nn.Module): def __init__(self, image_shape, output_size): super().__init__() c, h, w = image_shape self.conv1 = torch.nn.Conv2d(in_channels=c, out_channels=32, kernel_size=8, stride=4, padding=0) self.conv2 = torch.nn.Conv2d(in_channels=32, out_channels=64, kernel_size=4, stride=3, padding=0) self.conv3 = torch.nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1) self.attention = SelfAttention(32) convs = [self.conv1, self.attention, self.conv2, self.conv3] conv_output_size = self.conv_out_size(convs, h, w) self.fc = torch.nn.Linear(conv_output_size, 512) self.pi = torch.nn.Linear(512, output_size) #value function head self.value = torch.nn.Linear(512, 1) #reset weights just like nature paper self.init_weights() @torch.no_grad() def init_weights(self): #orthogonal initialization with gain of sqrt(2) def weights_initializer(m): if isinstance(m, torch.nn.Conv2d): torch.nn.init.orthogonal_(m.weight, np.sqrt(2)) self.apply(weights_initializer) def conv_out_size(self, convs, h, w, c=None): """Helper function ot return the output size for a given input shape, without actually performing a forward pass through the model.""" for child in convs: try: h, w = conv2d_output_shape(h, w, child.kernel_size, child.stride, child.padding) except AttributeError: pass # Not a conv or maxpool layer. try: c = child.out_channels except AttributeError: pass # Not a conv layer. return h * w * c def forward(self, image, prev_action=None, prev_reward=None): img = image.type(torch.float) img = img.mul_(1. / 255) lead_dim, T, B, img_shape = infer_leading_dims(img, 3) img = img.view(T * B, *img_shape) relu = torch.nn.functional.relu y = relu(self.conv1(img)) y = self.attention(y) y = relu(self.conv2(y)) y = relu(self.conv3(y)) fc_out = self.fc(y.view(T * B, -1)) pi = torch.nn.functional.softmax(self.pi(fc_out), dim=-1) v = self.value(fc_out).squeeze(-1) # Restore leading dimensions: [T,B], [B], or [], as input. #T -> transition #B -> batch_size? pi, v = restore_leading_dims((pi, v), lead_dim, T, B) return pi, v class NatureAttention(torch.nn.Module): def __init__(self, image_shape, output_size): super().__init__() c, h, w = image_shape self.conv1 = torch.nn.Conv2d(in_channels=c, out_channels=32, kernel_size=8, stride=4, padding=0) self.conv2 = torch.nn.Conv2d(in_channels=32, out_channels=64, kernel_size=4, stride=3, padding=0) self.conv3 = torch.nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1) self.projector = ProjectorBlock(32, 512) self.projector2 = ProjectorBlock(64, 512) self.attn1 = LinearAttentionBlock(in_features=512, normalize_attn=True) self.attn2 = LinearAttentionBlock(in_features=512, normalize_attn=True) convs = [self.conv1, self.conv2, self.conv3] conv_output_size = self.conv_out_size(convs, h, w) #self.fc = torch.nn.Linear(conv_output_size, 512) self.fc = torch.nn.Conv2d(in_channels=64, out_channels=512, kernel_size=4, padding=0, bias=True) self.pi = torch.nn.Linear(512*2, output_size) #value function head self.value = torch.nn.Linear(512*2, 1) #reset weights just like nature paper self.init_weights() @torch.no_grad() def init_weights(self): #orthogonal initialization with gain of sqrt(2) def weights_initializer(m): if isinstance(m, torch.nn.Conv2d): torch.nn.init.orthogonal_(m.weight, np.sqrt(2)) self.apply(weights_initializer) def conv_out_size(self, convs, h, w, c=None): """Helper function ot return the output size for a given input shape, without actually performing a forward pass through the model.""" for child in convs: try: h, w = conv2d_output_shape(h, w, child.kernel_size, child.stride, child.padding) except AttributeError: pass # Not a conv or maxpool layer. try: c = child.out_channels except AttributeError: pass # Not a conv layer. return h * w * c def forward(self, image, prev_action=None, prev_reward=None): img = image.type(torch.float) img = img.mul_(1. / 255) lead_dim, T, B, img_shape = infer_leading_dims(img, 3) img = img.view(T * B, *img_shape) relu = torch.nn.functional.relu l1 = relu(self.conv1(img)) l2 = relu(self.conv2(l1)) y = relu(self.conv3(l2)) #fc_out = self.fc(y.view(T * B, -1)) fc_out = self.fc(y) l1 = self.projector(l1) l2 = self.projector2(l2) c1, g1 = self.attn1(l1, fc_out) c2, g2 = self.attn2(l2, fc_out) g = torch.cat((g1,g2), dim=1) # batch_sizexC # classification layer pi = torch.nn.functional.softmax(self.pi(g), dim=-1) v = self.value(g).squeeze(-1) # Restore leading dimensions: [T,B], [B], or [], as input. #T -> transition #B -> batch_size? pi, v = restore_leading_dims((pi, v), lead_dim, T, B) return pi, v<file_sep>/experiments/attention_maps.py import torch import os from models.attention import NatureAttention, ImpalaAttention from matplotlib import pyplot as plt class AttentionMaps(): def __init__( self, path="./", obs="./", name="Default", batchNorm=False, dropout=0.0, augment_obs=None, hidden_sizes=[512], max_pooling=False, arch="original"): self.name = name self.obs = torch.load(os.getcwd() + obs, map_location=torch.device('cpu')) dummy_x = torch.rand((3,64,64)) if arch=="impala": in_channels = [3,16,32] out_channels = [16,32,32] self.model = ImpalaAttention(dummy_x.shape, 15, [], [], 512) else: self.model = NatureAttention( dummy_x.shape, 15, batchNorm=batchNorm, dropout=dropout, augment_obs=augment_obs, hidden_sizes=hidden_sizes, use_maxpool=max_pooling, arch=arch) saved_params = torch.load(os.getcwd() + path, map_location=torch.device('cpu')) self.model.load_state_dict(saved_params) def run(self): with torch.no_grad(): #img = torch.from_numpy(self.obs).unsqueeze(0) img = self.obs.type(torch.float) img = img.mul_(1. / 255) gs = self.model(img) titles = ['Low Level', 'Medium Level', 'High Level'] extent = 0, 64, 0, 64 fig, axs = plt.subplots(3, figsize=(5,12)) fig.suptitle('Attention Maps') for i, g in enumerate(gs): x = self.obs.squeeze(0).numpy().transpose((1,2,0)) axs[i].imshow(x, extent=extent) axs[i].imshow(g[0], interpolation='bilinear', extent=extent, alpha=0.7) axs[i].set_title(titles[i]) fig.savefig(self.name + '.png')<file_sep>/models/inception.py import torch from rlpyt.models.utils import conv2d_output_shape from rlpyt.utils.tensor import infer_leading_dims, restore_leading_dims class InceptionBlock(torch.nn.Module): def __init__(self, channels): super().__init__() conv0 = torch.nn.Conv2d(in_channels=channels, out_channels=channels, kernel_size=3, stride=1, padding=1) conv2 = torch.nn.Conv2d(in_channels=channels, out_channels=channels, kernel_size=3, stride=1, padding=1) non_linearlity = torch.nn.ReLU() self.block = torch.nn.Sequential(*[non_linearlity, conv1, non_linearlity, conv2]) def forward(self, x): return self.block(x) + x def conv_out_size(self, h, w, c=None): """Helper function ot return the output size for a given input shape, without actually performing a forward pass through the model.""" for child in self.block.children(): try: h, w = conv2d_output_shape(h, w, child.kernel_size, child.stride, child.padding) except AttributeError: pass # Not a conv or maxpool layer. try: c = child.out_channels except AttributeError: pass # Not a conv layer. return h, w, c<file_sep>/run.py from experiments.base import BaseExperimentNature import wandb import os import sys import math from argparse import ArgumentParser if __name__ == "__main__": parser = ArgumentParser() parser.add_argument('--name', type=str, default="Default Name") parser.add_argument('--num_levels', type=int, default=200) parser.add_argument('--batchNorm', type=bool, default=False) parser.add_argument('--dropout', type=float, default=0.0) parser.add_argument('--l2_penalty', type=float, default=0) parser.add_argument('--entropy_bonus', type=float, default=0.01) parser.add_argument('--augment_obs', type=str, default=None) parser.add_argument('--attention', type=str, default=None) parser.add_argument('--num_steps', type=int, default=25_000_000) parser.add_argument('--hidden_sizes', nargs='+', type=int, default=[512]) parser.add_argument('--max_pooling', type=bool, default=False) parser.add_argument('--arch', type=str, default="original") parser.add_argument('--env', type=str, default="coinrun") parser.add_argument('--gpu', type=int, default=0) args = parser.parse_args() experiment = BaseExperimentNature(**vars(args)) config = experiment.getConfig() run = wandb.init(name=config['name'], config=config, reinit=False, sync_tensorboard=True) experiment.run() sys.exit(0) <file_sep>/evaluation/run_eval_entropy.py import wandb import os import sys from evaluation import evaluate_generalization if __name__ == "__main__": models_to_evaluate = [ {"model_name":"CoinRunNature-entropy-0", "num_levels": 500, "model_path": "../saved_models/CoinRunNature-Entropy-0.pt"}, {"model_name":"CoinRunNature-entropy-0.02", "num_levels": 500, "model_path": "../saved_models/CoinRunNature-Entropy-0.02.pt"}, {"model_name":"CoinRunNature-entropy-0.05", "num_levels": 500, "model_path": "../saved_models/CoinRunNature-Entropy-0.05.pt"}, {"model_name":"CoinRunNature-entropy-0.07", "num_levels": 500, "model_path": "../saved_models/CoinRunNature-Entropy-0.07.pt"}, {"model_name":"CoinRunNature-entropy-0.1", "num_levels": 500, "model_path": "../saved_models/CoinRunNature-Entropy-0.1.pt"}, ] evaluate_generalization(models_to_evaluate, "CoinRun-Evaluation-Entropy") sys.exit(0) <file_sep>/run_attention_map.py from experiments.attention_maps import AttentionMaps import wandb import os import sys import math from argparse import ArgumentParser if __name__ == "__main__": parser = ArgumentParser() parser.add_argument('--name', type=str, default="default") parser.add_argument('--batchNorm', type=bool, default=False) parser.add_argument('--dropout', type=float, default=0.0) parser.add_argument('--augment_obs', type=str, default=None) parser.add_argument('--hidden_sizes', nargs='+', type=int, default=[512]) parser.add_argument('--max_pooling', type=bool, default=False) parser.add_argument('--arch', type=str, default="original") parser.add_argument('--path', type=str) parser.add_argument('--obs', type=str) args = parser.parse_args() maps = AttentionMaps(**vars(args)) maps.run() sys.exit(0) <file_sep>/models/attention.py import torch from models.nature import NatureCNNModel from models.impala import ImpalaModel class NatureAttention(NatureCNNModel): def forward(self, x): conv = self.conv.conv.conv softmax = torch.nn.Softmax2d() g0 = conv[1](conv[0](x)) g1 = conv[3](conv[2](g0)) g2 = conv[5](conv[4](g1)) return [g.pow(2).mean(1) for g in (g0, g1, g2)] class ImpalaAttention(ImpalaModel): def forward(self, x): conv = imp.conv.conv.blocks softmax = torch.nn.Softmax2d() g0 = conv[0](x) g1 = conv[1](g0) g2 = conv[2](g1) return [g.pow(2).mean(1) for g in (g0, g1, g2)] class SelfAttention(torch.nn.Module): def __init__(self, in_channels): super().__init__() self.q = torch.nn.Conv2d(in_channels=in_channels, out_channels=in_channels, kernel_size=1, stride=1) self.v = torch.nn.Conv2d(in_channels=in_channels, out_channels=in_channels, kernel_size=1, stride=1) self.k = torch.nn.Conv2d(in_channels=in_channels, out_channels=in_channels, kernel_size=1, stride=1) self.y = torch.nn.Conv2d(in_channels=in_channels, out_channels=in_channels, kernel_size=1, stride=1) self.softmax = torch.nn.Softmax2d() def forward(self, x): f1 = self.q(x) f2 = self.v(x) g1 = self.k(x) z = torch.matmul(f1, f2.transpose(2, 3)) z = self.softmax(z) z = torch.matmul(z, g1) yout = self.y(z) return yout + x class ProjectorBlock(torch.nn.Module): def __init__(self, in_features, out_features): super(ProjectorBlock, self).__init__() self.conv = torch.nn.Conv2d(in_channels=in_features, out_channels=out_features, kernel_size=1, padding=0, bias=False) def forward(self, inputs): return self.conv(inputs) class LinearAttentionBlock(torch.nn.Module): def __init__(self, in_features, normalize_attn=True): super(LinearAttentionBlock, self).__init__() self.normalize_attn = normalize_attn self.op = torch.nn.Conv2d(in_channels=in_features, out_channels=1, kernel_size=1, padding=0, bias=False) def forward(self, l, g): N, C, W, H = l.size() c = self.op(l+g) # batch_sizex1xWxH if self.normalize_attn: a = torch.nn.functional.softmax(c.view(N,1,-1), dim=2).view(N,1,W,H) else: a = torch.sigmoid(c) g = torch.mul(a.expand_as(l), l) if self.normalize_attn: g = g.view(N,C,-1).sum(dim=2) # batch_sizexC else: g = torch.nn.functional.adaptive_avg_pool2d(g, (1,1)).view(N,C) return c.view(N,1,W,H), g<file_sep>/evaluation/run_eval_levels.py import wandb import os import sys from evaluation import evaluate_generalization if __name__ == "__main__": models_to_evaluate = [ {"model_name":"CoinRunNature-Levels-100", "num_levels": 100, "model_path": "../saved_models/CoinRunNature-Levels-100.pt"}, {"model_name":"CoinRunNature-Levels-500", "num_levels": 500, "model_path": "../saved_models/CoinRunNature-Levels-500.pt"}, {"model_name":"CoinRunNature-Levels-1000", "num_levels": 1000, "model_path": "../saved_models/CoinRunNature-Levels-1000.pt"}, {"model_name":"CoinRunNature-Levels-10000", "num_levels": 10000, "model_path": "../saved_models/CoinRunNature-Levels-10000.pt"}, {"model_name":"CoinRunNature-Levels-15000", "num_levels": 15000, "model_path": "../saved_models/CoinRunNature-Levels-15000.pt"}, ] evaluate_generalization(models_to_evaluate, "CoinRun-Evaluation-Levels") sys.exit(0) <file_sep>/environments/procgen.py import gym from rlpyt.envs.gym import GymEnvWrapper from rlpyt.envs.base import EnvSpaces, EnvStep from rlpyt.spaces.gym_wrapper import GymSpaceWrapper from rlpyt.utils.collections import is_namedtuple_class from rlpyt.envs.gym import build_info_tuples, info_to_nt from gym import Wrapper from gym.wrappers.time_limit import TimeLimit from collections import namedtuple class ProcgenWrapper(GymEnvWrapper): def __init__(self, env, act_null_value=0, obs_null_value=0, force_float32=True): super().__init__(env) o, r, d, info = self.env.step(self.env.action_space.sample()) env_ = self.env time_limit = isinstance(self.env, TimeLimit) while not time_limit and hasattr(env_, "env"): env_ = env_.env time_limit = isinstance(self.env, TimeLimit) if time_limit: info["timeout"] = False # gym's TimeLimit.truncated invalid name. self._time_limit = time_limit self.action_space = GymSpaceWrapper( space=self.env.action_space, name="act", null_value=act_null_value, force_float32=force_float32, ) self.observation_space = GymSpaceWrapper( space=self.env.observation_space, name="obs", null_value=obs_null_value, force_float32=force_float32, ) w = self.observation_space.space.shape[1] h = self.observation_space.space.shape[0] c = self.observation_space.space.shape[2] self.observation_space.space.shape = (c, h, w) build_info_tuples(info) def step(self, action): """Reverts the action from rlpyt format to gym format (i.e. if composite-to- dictionary spaces), steps the gym environment, converts the observation from gym to rlpyt format (i.e. if dict-to-composite), and converts the env_info from dictionary into namedtuple.""" a = self.action_space.revert(action) o, r, d, info = self.env.step(a) obs = self.observation_space.convert(o.transpose((2, 0, 1))) if self._time_limit: if "TimeLimit.truncated" in info: info["timeout"] = info.pop("TimeLimit.truncated") else: info["timeout"] = False info = info_to_nt(info) if isinstance(r, float): r = np.dtype("float32").type(r) # Scalar float32. return EnvStep(obs, r, d, info) def reset(self): """Returns converted observation from gym env reset.""" return self.observation_space.convert(self.env.reset().transpose((2, 0, 1))) def seed(self, seed): return def make_env(*args, **kwargs): num_levels = kwargs['num_levels'] difficulty="easy" paint_vel_info=True seed=42069 if "start_level" in kwargs: env = gym.make("procgen:procgen-coinrun-v0", num_levels=num_levels, start_level=kwargs['start_level'], distribution_mode=difficulty, rand_seed=seed, paint_vel_info=paint_vel_info) else: env = gym.make("procgen:procgen-coinrun-v0", num_levels=num_levels, distribution_mode=difficulty, rand_seed=seed, paint_vel_info=paint_vel_info) return ProcgenWrapper(env)<file_sep>/agents/nature.py import torch from rlpyt.agents.pg.categorical import (CategoricalPgAgent, RecurrentCategoricalPgAgent) from models.nature import (NatureCNNModel, NatureLSTMModel) from models.nature_attention import NatureAttention, NatureSelfAttention from rlpyt.agents.pg.atari import AtariMixin from rlpyt.utils.buffer import buffer_to, buffer_func, buffer_method from rlpyt.distributions.categorical import Categorical, DistInfo from rlpyt.agents.base import (AgentStep, BaseAgent, RecurrentAgentMixin, AlternatingRecurrentAgentMixin) from rlpyt.agents.pg.base import AgentInfo, AgentInfoRnn #Agent that uses CNNNature with 2 heads to parametrize policy and value functions class OriginalNatureAgent(AtariMixin, CategoricalPgAgent): def __init__(self, **kwargs): super().__init__(ModelCls=NatureCNNModel, **kwargs) @torch.no_grad() def step(self, observation, prev_action, prev_reward): prev_action = self.distribution.to_onehot(prev_action) model_inputs = buffer_to((observation, prev_action, prev_reward), device=self.device) # if is eval mode and rand_conv do monte carlo evaluation if not self.model.training and hasattr(self.model, "augment_obs") and self.model.augment_obs == 'rand_conv': pi_vector = [] value_vector = [] for i in range(10): pi, value = self.model(*model_inputs) pi_vector.append(pi) value_vector.append(value) pi_t = torch.stack(pi_vector) value_t = torch.stack(value_vector) pi = pi_t.sum(axis=0) / pi_t.shape[1] value = value_t.sum(axis=0) / value_t.shape[1] else: pi, value = self.model(*model_inputs) dist_info = DistInfo(prob=pi) action = self.distribution.sample(dist_info) agent_info = AgentInfo(dist_info=dist_info, value=value) action, agent_info = buffer_to((action, agent_info), device="cpu") return AgentStep(action=action, agent_info=agent_info) class AttentionNatureAgent(AtariMixin, CategoricalPgAgent): def __init__(self, **kwargs): super().__init__(ModelCls=NatureAttention, **kwargs) class SelfAttentionNatureAgent(AtariMixin, CategoricalPgAgent): def __init__(self, **kwargs): super().__init__(ModelCls=NatureSelfAttention, **kwargs) class NatureRecurrentAgent(AtariMixin, RecurrentCategoricalPgAgent): def __init__(self, **kwargs): super().__init__(ModelCls=NatureLSTMModel, **kwargs)<file_sep>/models/nature.py import torch from rlpyt.utils.tensor import infer_leading_dims, restore_leading_dims from models.conv2d import Conv2dHeadModel from models.cutout import random_cutout_color from models.layer_transform import ColorJitterLayer from models.rand_network import random_convolution from rlpyt.utils.collections import namedarraytuple import torch.nn.functional as F import numpy as np import math class NatureCNNModel(torch.nn.Module): def __init__(self, image_shape, output_size, batchNorm=False, dropout=0.0, augment_obs=None, use_maxpool=False, hidden_sizes=[512], arch="original", ): super().__init__() self.augment_obs = augment_obs self.transform = None channels=[32,64,64] kernel_sizes=[8,4,3] strides=[4,3,1] paddings=[0,0,1] if arch == "depth+1": channels=[32,64,64,128] kernel_sizes=[8,4,3,2] strides=[4,3,1,1] paddings=[0,0,1,0] elif arch == "depth+2": channels=[32,64,64,128,256] kernel_sizes=[8,4,3,2,2] strides=[4,3,1,1,1] paddings=[0,0,1,0,0] elif arch == "channels/2": channels=[16,32,32] kernel_sizes=[8,4,3] strides=[4,3,1] paddings=[0,0,1] elif arch == "channels*2": channels=[64,128,128] kernel_sizes=[8,4,3] strides=[4,3,1] paddings=[0,0,1] elif arch == "a": channels=[16,32,64] kernel_sizes=[8,4,3] strides=[4,3,1] paddings=[0,0,1] elif arch == "b": channels=[16,32,64] kernel_sizes=[4,3,3] strides=[2,2,2] paddings=[0,0,1] resnet = arch=="resnet" or arch=="resnet2" self.conv = Conv2dHeadModel( image_shape=image_shape, channels=channels, kernel_sizes=kernel_sizes, strides=strides, paddings=paddings, use_maxpool=use_maxpool, hidden_sizes=hidden_sizes, batchNorm=batchNorm, dropout=dropout, useResNet=resnet, resNetLayers=2 if arch == "resnet2" else 1, ) #policy head self.pi = torch.nn.Linear(self.conv.output_size, output_size) #value function head self.value = torch.nn.Linear(self.conv.output_size, 1) #reset weights just like nature paper self.init_weights() @torch.no_grad() def init_weights(self): #orthogonal initialization with gain of sqrt(2) def weights_initializer(m): if isinstance(m, torch.nn.Conv2d): torch.nn.init.orthogonal_(m.weight, np.sqrt(2)) self.apply(weights_initializer) def forward(self, image, prev_action=None, prev_reward=None): #input normalization, cast to float then grayscale it img = image.type(torch.float) img = img.mul_(1. / 255) lead_dim, T, B, img_shape = infer_leading_dims(img, 3) img = img.view(T * B, *img_shape) if self.augment_obs != None: b, c, h, w = img.shape mask_vbox = torch.zeros(size=img.shape, dtype=torch.bool, device=img.device) mh = math.ceil(h * 0.20) #2 squares side by side mw = mh * 2 ##create velocity mask -> False where velocity box is, True rest of the screen vmask = torch.ones((b, c, mh, mw), dtype=torch.bool, device=img.device) mask_vbox[:,:,:mh,:mw] = vmask obs_without_vbox = torch.where(mask_vbox, torch.zeros_like(img), img) if self.augment_obs == 'cutout': augmented = random_cutout_color(obs_without_vbox) elif self.augment_obs == 'jitter': if self.transform is None: self.transform = ColorJitterLayer(b) augmented = self.transform(obs_without_vbox) elif self.augment_obs == 'rand_conv': augmented = random_convolution(obs_without_vbox) fixed = torch.where(mask_vbox, img, augmented) img = fixed fc_out = self.conv(img) pi = F.softmax(self.pi(fc_out), dim=-1) v = self.value(fc_out).squeeze(-1) # Restore leading dimensions: [T,B], [B], or [], as input. #T -> transition #B -> batch_size? pi, v = restore_leading_dims((pi, v), lead_dim, T, B) return pi, v RnnState = namedarraytuple("RnnState", ["h", "c"]) class NatureLSTMModel(torch.nn.Module): def __init__(self, image_shape, output_size, hidden_sizes=[512], lstm_size=256 ): super().__init__() channels=[32,64,64] kernel_sizes=[8,4,3] strides=[4,3,1] paddings=[0,0,1] self.conv = Conv2dHeadModel( image_shape=image_shape, channels=channels, kernel_sizes=kernel_sizes, strides=strides, paddings=paddings, use_maxpool=False, hidden_sizes=hidden_sizes, ) self.lstm = torch.nn.LSTM(self.conv.output_size + output_size + 1, lstm_size) self.pi = torch.nn.Linear(lstm_size, output_size) self.value = torch.nn.Linear(lstm_size, 1) def forward(self, image, prev_action=None, prev_reward=None, init_rnn_state=None): img = image.type(torch.float) img = img.mul_(1. / 255) lead_dim, T, B, img_shape = infer_leading_dims(img, 3) img = img.view(T * B, *img_shape) fc_out = self.conv(img.view(T * B, *img_shape)) lstm_input = torch.cat([ fc_out.view(T, B, -1), prev_action.view(T, B, -1), # Assumed onehot. prev_reward.view(T, B, 1), ], dim=2) init_rnn_state = None if init_rnn_state is None else tuple(init_rnn_state) lstm_out, (hn, cn) = self.lstm(lstm_input, init_rnn_state) pi = F.softmax(self.pi(lstm_out.view(T * B, -1)), dim=-1) v = self.value(lstm_out.view(T * B, -1)).squeeze(-1) # Restore leading dimensions: [T,B], [B], or [], as input. pi, v = restore_leading_dims((pi, v), lead_dim, T, B) # Model should always leave B-dimension in rnn state: [N,B,H]. next_rnn_state = RnnState(h=hn, c=cn) return pi, v, next_rnn_state <file_sep>/models/cutout.py import torch def random_cutout_color(imgs, min_cut=10, max_cut=30): n, c, h, w = imgs.shape device = "cpu" for i in range(n): box_h = torch.randint(min_cut, max_cut, (1,), device=device).item() box_w = torch.randint(min_cut, max_cut, (1,), device=device).item() color = torch.randint(0, 255, (3,), device=device) / 255. r = color[0].item() g = color[1].item() b = color[2].item() x = torch.randint(0, w - box_w - 1, (1,), device=device).item() y = torch.randint(0, h - box_h -1, (1,), device=device).item() imgs[i,0, y:y+box_h,x:x+box_w] = r imgs[i,1, y:y+box_h,x:x+box_w] = g imgs[i,2, y:y+box_h,x:x+box_w] = b return imgs <file_sep>/environments/coinrun.py from rlpyt.envs.gym import GymEnvWrapper import gym class CoinRun: def __init__(self, num_levels=500, difficulty="easy", paint_vel_info=True, seed=42069): self.env = gym.make("procgen:procgen-coinrun-v0", num_levels=num_levels, distribuition_mode=difficulty, rand_seed=seed, paint_vel_info=paint_vel_info) def make(self): return GymEnvWrapper(self.env)<file_sep>/models/rand_network.py import torch from torch import nn class RandNetwork(torch.nn.Module): def __init__(self, in_channels, out_channels, kernel_size=3): super().__init__() self.conv = torch.nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, padding=1, stride=1) #parameters are frozen self.requires_grad_(requires_grad=False) @torch.no_grad() def init_weights(self): def weights_initializer(m): if isinstance(m, torch.nn.Conv2d): torch.nn.init.xavier_normal_(m.weight) self.apply(weights_initializer) def forward(self, x): self.init_weights() return self.conv(x) def random_convolution(imgs): ''' random covolution in "network randomization" (imbs): B x (C x stack) x H x W, note: imgs should be normalized and torch tensor ''' # initialize random covolution rand_conv = torch.nn.Conv2d(3, 3, kernel_size=3, bias=False, padding=1) rand_conv.weight.requires_grad = False if imgs.is_cuda: rand_conv.cuda() for i, img in enumerate(imgs): torch.nn.init.xavier_normal_(rand_conv.weight.data, gain=0.5) imgs[i] = rand_conv(img.unsqueeze(0))[0] return imgs<file_sep>/evaluation/run_eval_dropout.py import wandb import os import sys from evaluation import evaluate_generalization if __name__ == "__main__": models_to_evaluate = [ {"model_name":"CoinRunNature-Dropout-5", "num_levels": 500, "model_path": "../saved_models/CoinRunNature-Dropout-5.pt", "dropout": 0.05}, {"model_name":"CoinRunNature-Dropout-10", "num_levels": 500, "model_path": "../saved_models/CoinRunNature-Dropout-10.pt", "dropout": 0.10}, {"model_name":"CoinRunNature-Dropout-15", "num_levels": 500, "model_path": "../saved_models/CoinRunNature-Dropout-15.pt", "dropout": 0.15}, {"model_name":"CoinRunNature-Dropout-20", "num_levels": 500, "model_path": "../saved_models/CoinRunNature-Dropout-20.pt", "dropout": 0.20}, {"model_name":"CoinRunNature-Dropout-25", "num_levels": 500, "model_path": "../saved_models/CoinRunNature-Dropout-25.pt", "dropout": 0.25}, ] evaluate_generalization(models_to_evaluate, "CoinRun-Evaluation-Dropout") sys.exit(0)
b27c08cac2ae476eaba471b0f0784bf12505d341
[ "Markdown", "Python", "Text" ]
29
Text
MiguelFreire/rl-generalization
6aeffbde88447274eecac0cc171481cf7e963a67
e0bea9182876862daba261c77e3717cb511ad9b2
refs/heads/master
<file_sep>export default function ({ app }) { app.$auth.onError((error, name, endpoint) => { //console.log(endpoint) //console.log(error) //console.log(endpoint) }) }<file_sep>APP_NAME=MyApp BASE_API_URL=http://localhost:8000
3fdcf2eb86a00da305a54ea1bbd1fbb835440f00
[ "JavaScript", "Shell" ]
2
JavaScript
harimayco/timesheet
56d2b35b6ae587b01e2c331d024f4c97a1b203ed
089cd273d4e1a2c578a534766aa683ee75e2d819
refs/heads/master
<file_sep>import os from os.path import isfile, join import re path = 'papers/' def atoi(text): return int(text) if text.isdigit() else text def human_sort_keys(text): """ alist.sort(key=natural_keys) sorts in human order http://nedbatchelder.com/blog/200712/human_sorting.html (See Toothy's implementation in the comments) """ return [ atoi(c) for c in re.split('(\d+)', text) ] papers_list = [join(path, f) for f in os.listdir(path) if isfile(join(path, f))] papers_list.sort(key=human_sort_keys) for p in papers_list: with open(p) as f: title = f.readline()[3:].strip() print("- [{0}]({1})".format(title, p)) <file_sep># Human Robot Interaction Summaries of papers from CS 7633 by Dr. <NAME>. Also has papers from robotics in general. ### Papers: 1. [HERB: A home exploring robotic butler](papers/01-01.md) 2. [The Autonomous City Explorer (_ACE_) Project - Mobile Robot Navigation in Highly Populated Urban Environments](papers/01-02.md) 3. [Classifying Human-Robot Interaction: An Updated Taxonomy](papers/01-03.md)
631bd2e458f3a0a30566f2b441af76a45707799f
[ "Markdown", "Python" ]
2
Python
varunagrawal/Human-Robot-Interaction
5c2b0523241338bda33a422b75c8bf660b8048ad
9d43e01c774ca6187885b2bd15700c594e823a71
refs/heads/main
<repo_name>Mision-Tic-Grupo4/proyectoASECOL-Vue.js-<file_sep>/frontend/src/assets/script.js // Funcion para activar y desactivar el modal del carrito let shoppingCart = document.querySelector('.shopping-cart'); document.querySelector('#cart-btn').onclick = () => { shoppingCart.classList.toggle('active'); loginForm.classList.remove('active'); navbar.classList.remove('active'); } // Funcion para activar y desactivar el modal del login let loginForm = document.querySelector('.login-form'); document.querySelector('#login-btn').onclick = () => { loginForm.classList.toggle('active'); shoppingCart.classList.remove('active'); navbar.classList.remove('active'); } // Funcion para activar y desactivar el modal del menu let navbar = document.querySelector('.navbar'); document.querySelector('#menu-btn').onclick = () => { navbar.classList.toggle('active'); shoppingCart.classList.remove('active'); loginForm.classList.remove('active'); } // limpiar cuando se de click en otra opción window.onscroll = () => { shoppingCart.classList.remove('active'); loginForm.classList.remove('active'); navbar.classList.remove('active'); }<file_sep>/backend/routes/producto.js const express = require('express'); const router = express.Router(); const ProductoController = require('../controllers/productoController'); //privados router.post('/add',ProductoController.add); router.get('/list',ProductoController.list); router.put('/update',ProductoController.update); router.put('/enabled',ProductoController.enabled); router.put('/disabled',ProductoController.disabled); router.get('/listActive',ProductoController.listActive); router.delete('/remove',ProductoController.remove); module.exports = router;<file_sep>/backend/routes/categoria.js const express = require('express'); const router = express.Router(); const CategoriaController = require('../controllers/categoriaController'); //privados router.post('/add',CategoriaController.add); router.get('/list',CategoriaController.list); router.put('/update',CategoriaController.update); router.put('/enabled',CategoriaController.enabled); router.put('/disabled',CategoriaController.disabled); router.get('/listActive',CategoriaController.listActive); // router.delete('/remove',CategoriaController.remove); module.exports = router;<file_sep>/frontend/src/router/index.js import Vue from 'vue' import VueRouter from 'vue-router' import Home from '../views/Home.vue' import decode from 'jwt-decode' Vue.use(VueRouter) const routes = [ { path: '/', name: 'Home', component: Home }, { path: '/login', name: 'Login', component: () => import(/* webpackChunkName: "login" */ '../views/Login.vue') }, { path: '/cliente', name: 'Cliente', component: () => import(/* webpackChunkName: "cliente" */ '../views/Cliente.vue'), meta: { requiresAuth: true }, children: [ { path: 'gestor', name: 'Gestor', component: () => import(/* webpackChunkName: "cliente" */ '../components/ClienteDT.vue'), meta: { Cliente : true } }, { path: 'categoria', name: 'Categoria', component: () => import(/* webpackChunkName: "cliente" */ '../components/CategoriasCd.vue'), }, { path: 'producto', name: 'Producto', component: () => import(/* webpackChunkName: "cliente" */ '../components/ProductosCd.vue'), }, ] }, { path: '/admin', name: 'Admin', component: () => import(/* webpackChunkName: "admin" */ '../views/Admin.vue'), meta: { requiresAuth: true }, children: [ { path: 'usuarios', name: 'Usuarios', component: () => import(/* webpackChunkName: "usuarios" */ '../components/UsuariosDT.vue'), meta: { Administrador : true } }, { path: 'categorias', name: 'Categorias', component: () => import(/* webpackChunkName: "categoria" */ '../components/CategoriaDT.vue'), }, { path: 'productos', name: 'Productos', component: () => import(/* webpackChunkName: "producto" */ '../components/ProductoDT.vue'), }, ] } ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) router.beforeEach((to, from, next) => { if (to.matched.some(record => record.meta.requiresAuth)) { let token = localStorage.getItem('token'); if (!token) { next({ name: 'Login', }) } else { //si requiere Administrador // let auxRol = token; let auxRol = decode(token); let rolToken = auxRol.rol; console.log('Antes de validar ' ,rolToken) if (to.matched.some(record => record.meta.Administrador)) { if (rolToken === 'Administrador') { console.log('Despues de validar ' ,rolToken) next() }else { name: 'Admin' } }else { next() } if (to.matched.some(record => record.meta.Cliente)) { if (rolToken === 'Cliente') { console.log('Despues de validar ' ,rolToken) next() }else { name: 'Cliente' } }else { next() } } } else { next() // make sure to always call next()! } }) export default router <file_sep>/backend/index.js const express = require('express'); var morgan = require('morgan'); const cors = require('cors'); const apiRouter = require('./routes/index'); const mongoose = require('mongoose'); const app = express(); app.use(morgan('dev')); app.use(cors()); app.use((req, res, next)=>{ res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, ContentType, Accept"); res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE'); res.header('Allow', 'GET, POST, OPTIONS, PUT, DELETE'); next(); }); app.use(express.json()); app.use(express.urlencoded({extended:true})); // conexion DB const urlDB = 'mongodb+srv://estefaniaurro:<EMAIL>/asecol?retryWrites=true&w=majority' mongoose.Promise = global.Promise; mongoose.connect(urlDB) .then(mongoose => console.log("DB conectada en el puerto 27017")) .catch(err=>console.log(err)) app.use('/api',apiRouter); app.set('PORT', process.env.PORT || 3000); app.listen(app.get('PORT'),() =>{ console.log(`Runing on:${app.get('PORT')}`) }) <file_sep>/backend/services/token.js var jwt = require('jsonwebtoken'); module.exports = { encode: async(user) =>{ const token = jwt.sign({ _id : user._id, nombre: user.nombre, correo: user.correo, rol: user.rol }, 'UnaFraseSecretaParaCodificarMiUsuario', { expiresIn : 86400 }); return token; } }<file_sep>/backend/controllers/usuarioController.js const models = require('../models'); const bcrypt = require('bcryptjs'); const token = require('../services/token'); //privado //publica module.exports = { add : async(req,res,next) =>{ try { let checkemail = await models.Usuario.findOne({correo:req.body.correo}) if(!checkemail){ req.body.password = await bcrypt.hash(req.body.password, 10); const reg = await models.Usuario.create(req.body) res.status(200).json(reg) }else{ res.status(401).send({ message : 'El usuario ya existe!' }) } } catch (error) { res.status(500).send({ message: 'Ocurrió un error interno' }); next(error) } }, list: async(req,res,next) =>{ try { let valorBusqueda = req.query.valor; //Lo manda por params // let valorBusqueda = req.body.valor; // const reg = await models.Usuario.find({createdAt: 0, _id:0}).sort() const reg = await models.Usuario.find({$or: [ {nombre: new RegExp(valorBusqueda, 'i')}, {correo: new RegExp(valorBusqueda, 'i')}, {rol: new RegExp(valorBusqueda, 'i')} ]}).sort({createdAt : -1}); res.status(200).json(reg); } catch (error) { res.status(500).send({ message : 'Ocurrió un error interno' }); next(error); } }, enabled: async(req,res,next) =>{ try { const reg = await models.Usuario.findByIdAndUpdate({_id: req.body._id},{estado: 1}); res.status(200).json(reg); //Hacer un solo metodo de cambio de estado // const regAux = await models.Usuario.find({_id: req.body._id}); // let estadoAux = regAux.estado === 1 ? 0 : 1 // const reg2 = await models.Usuario.updateOne({_id: req.body._id},{estado : estadoAux}) // res.status(200).json(reg2); } catch (error) { res.status(500).send({ message : 'Ocurrió un error interno' }); next(error); } }, disabled: async(req,res,next) =>{ try { const reg = await models.Usuario.findByIdAndUpdate({_id: req.body._id},{estado: 0}); res.status(200).json(reg); } catch (error) { res.status(500).send({ message : 'Ocurrió un error interno' }); next(error); } }, update: async(req,res,next) =>{ try { let auxPassword = <PASSWORD>; const regAux = await models.Usuario.findOne({correo : req.body.correo}); if(auxPassword !== regAux.<PASSWORD>){ req.body.password = await bcrypt.hash(req.body.password, 10); } const reg = await models.Usuario.updateOne({correo : req.body.correo},{ nombre : req.body.nombre, rol : req.body.rol, password: <PASSWORD> }) res.status(200).json(reg); } catch (error) { res.status(500).send({ message : 'Ocurrió un error interno' }); next(error); } }, login: async(req,res,next) =>{ try { let checkUser = await models.Usuario.findOne({ correo : req.body.correo, estado : 1 }); // console.log(checkUser) if(checkUser){ let match = await bcrypt.compare(req.body.password, checkUser.password); if(match){ let tokenReturn = await token.encode(checkUser); // console.log(tokenReturn) res.status(200).json({checkUser,tokenReturn}) // res.status(200).json({checkUser}) }else{ res.status(401).send({ message : 'Usuario no autorizado' }) } }else{ res.status(404).send({ message : 'Usuario no encontrado' }) } } catch (error) { res.status(500).send({ message : 'Ocurrió un error interno' }); next(error); } } } <file_sep>/backend/controllers/categoriaController.js const models = require('../models'); const bcrypt = require('bcryptjs'); const token = require('../services/token'); //privado //publica module.exports = { add : async(req,res,next) =>{ try { let checkNombre = await models.Categoria.findOne({nombre:req.body.nombre}) if(!checkNombre){ const reg = await models.Categoria.create(req.body) res.status(200).json(reg) }else{ res.status(401).send({ message : 'La categoria ya existe!' }) } } catch (error) { res.status(500).send({ message: 'Ocurrió un error interno' }); next(error) } }, list: async(req,res,next) =>{ try { // let valorBusqueda = req.body.valor; // const reg = await models.Categoria.find({createdAt: 0, _id:0}).sort() let valorBusqueda = req.query.valor; //Lo manda por params const reg = await models.Categoria.find({$or: [ {nombre: new RegExp(valorBusqueda, 'i')}, {descripcion: new RegExp(valorBusqueda, 'i')} ]}).sort({createdAt : -1}); res.status(200).json(reg); } catch (error) { res.status(500).send({ message : 'Ocurrió un error interno' }); next(error); } }, enabled: async(req,res,next) =>{ try { const reg = await models.Categoria.findByIdAndUpdate({_id: req.body._id},{estado: 1}); res.status(200).json(reg); } catch (error) { res.status(500).send({ message : 'Ocurrió un error interno' }); next(error); } }, disabled: async(req,res,next) =>{ try { const reg = await models.Categoria.findByIdAndUpdate({_id: req.body._id},{estado: 0}); res.status(200).json(reg); } catch (error) { res.status(500).send({ message : 'Ocurrió un error interno' }); next(error); } }, update: async(req,res,next) =>{ try { let checkNombre = await models.Categoria.findOne({nombre:req.body.nombre}) if(!checkNombre){ const reg = await models.Categoria.findByIdAndUpdate({_id : req.body._id},{ nombre : req.body.nombre, descripcion : req.body.descripcion }) res.status(200).json(reg) }else{ const reg = await models.Categoria.findByIdAndUpdate({_id : req.body._id},{ descripcion : req.body.descripcion }) res.status(200).json(reg) } } catch (error) { res.status(500).send({ message : 'Ocurrió un error interno' }); next(error); } }, listActive: async(req,res,next) =>{ try { const reg = await models.Categoria.find({estado : 1}).sort({createdAt : -1}); res.status(200).json(reg) } catch (error) { res.status(500).send({ message : 'Ocurrió un error interno' }); next(error); } }, // remove: async(req,res,next) =>{ // try { // const reg = await models.Categoria.findByIdAndDelete({_id : req.body._id}); // res.status(200).json(reg) // } catch (error) { // res.status(500).send({ // message : 'Ocurrió un error interno' // }); // next(error); // } // } }<file_sep>/README.md # proyectoASECOL(Vue Js) Material de apoyo para el desarrollo - Vue.Js y documentación: https://vuejs.org/ - Vue cli: https://cli.vuejs.org/ - Vuetify: https://vuetifyjs.com/en/ - Mongo (registro): https://www.mongodb.com/cloud/atlas/lp/try2?utm_content=controlhterms&utm_source=google&utm_campaign=gs_americas_colombia_search_core_brand_atlas_desktop&utm_term=mongo&utm_medium=cpc_paid_search&utm_ad=e&utm_ad_campaign_id=12212624317&gclid=EAIaIQobChMI78_17Img8wIVibjICh0OegtkEAAYASAAEgIjEvD_BwE - Escuela Mongo: https://university.mongodb.com/ - Video de apoyo: https://www.youtube.com/watch?v=FZBbX9f6b78&list=RDCMUCMn28O1sQGochG94HdlthbA&start_radio=1&rv=FZBbX9f6b78&t=45&ab_channel=FaztCode <file_sep>/backend/models/producto.js const mongoose = require('mongoose'); const{ Schema } = mongoose; const productoSchema = new Schema({ categoria : { type : Schema.ObjectId, ref: 'categoria' }, codigo : { type: String, required:true, maxlength:25, unique:true }, nombre : { type: String, required:true, maxlength:100, unique:true }, descripcion : { type: String, required:true, maxlength:255, }, precio : { type: Number, required:true, }, estado : { type: Number, default: 1 }, imagen : { type: String, required:true, }, }); const Producto = mongoose.model('producto',productoSchema); module.exports = Producto<file_sep>/backend/routes/index.js const express = require('express'); const router = express.Router(); const usuarioRouter = require('./usuario'); const categoriaRouter = require('./categoria'); const productoRouter = require('./producto'); router.use('/usuario',usuarioRouter); router.use('/producto',productoRouter); router.use('/categoria',categoriaRouter); module.exports = router;
20499f2b4400e8681f32a93eedc0db267e5ac681
[ "JavaScript", "Markdown" ]
11
JavaScript
Mision-Tic-Grupo4/proyectoASECOL-Vue.js-
37d5f2ab01fe63fb065fd6c1e6e2b9d9d75c4144
7b93b7f0ba840bf2e871c200dc3f8d30e3ac67d2
refs/heads/master
<file_sep> <!-- README.md is generated from README.Rmd. Please edit that file --> <!-- badges: start --> [![Lifecycle: maturing](https://img.shields.io/badge/lifecycle-maturing-blue.svg)](https://www.tidyverse.org/lifecycle/#maturing) [![CRAN status](https://www.r-pkg.org/badges/version/connectapi)](https://cran.r-project.org/package=connectapi) [![Codecov test coverage](https://codecov.io/gh/rstudio/connectapi/branch/master/graph/badge.svg)](https://codecov.io/gh/rstudio/connectapi?branch=master) [![R build status](https://github.com/rstudio/connectapi/workflows/R-CMD-check/badge.svg)](https://github.com/rstudio/connectapi/actions) <!-- badges: end --> # connectapi <img src='man/figures/logo.svg' align="right" height="139" /> This package provides an R client for the [RStudio Connect Server API](https://docs.rstudio.com/connect/api/) as well as helpful functions that utilize the client. The package is based on the `rsconnnect` [package](https://rstudio.github.io/rsconnect/), but is publicly exported to be easier to use, is extensible via an R6 class, and is separated from the `rsconnect` package for easier support and maintenance. ## Disclaimer Because many of these functions are experimental, it is advisable to be cautious about (1) upgrading the package, (2) upgrading RStudio Connect when you care about the reproducibility of workflows that use `connectapi`. As a result, we would advise: - managing package versions with [`renv`](https://rstudio.github.io/renv/) - test your dependent content before and after upgrading RStudio Connect Please pay careful attention to the lifecycle badges of the various functions and warnings present when you are using experimental features. **Also, [please share feedback\!\!](https://community.rstudio.com/c/r-admin/rstudio-connect/27) We love hearing how the RStudio Connect Server API is helpful and what additional endpoints would be useful\!\!** ## Installation To install the development version: ``` r remotes::install_github('rstudio/connectapi') ``` ## Client To create a client: ``` r library(connectapi) client <- connect( host = 'https://connect.example.com', api_key = '<SUPER SECRET API KEY>' ) ``` You can also define the following environment variables (in a `.Renviron` file, for instance): CONNECT_SERVER = https://connect.example.com CONNECT_API_KEY = my-secret-api-key These environment variable values will be used automatically if defined in your R session. ``` r library(connectapi) client <- connect() ``` ## Getting Started Once a client is defined, you can use it to interact with RStudio Connect. ### Exploring Data You can use the `get_` methods to retrieve data from the RStudio Connect server. ``` r library(connectapi) client <- connect() # get data users <- get_users(client) groups <- get_groups(client) usage_shiny <- get_usage_shiny(client) usage_static <- get_usage_static(client) some_content <- get_content(client) # get all content all_content <- get_content(client, n = Inf) ``` ### Deployment The `rsconnect` package is usually used for deploying content to Connect. However, if you want to use programmatic deployment with the RStudio Connect Server API, then these `connectapi` helpers should be useful\! ``` r library(connectapi) client <- connect() # deploying content # NOTE: a `manifest.json` should already exist from `rsconnect::writeManifest()` bundle <- bundle_dir("./path/to/directory") content <- client %>% deploy(bundle, name = "my-app-name") %>% poll_task() # set an image for content content %>% set_image_path("./my/local/image.png") content %>% set_image_url("http://url.example.com/image.png") # set image and a vanity URL content %>% set_image_path("./my/local/image.png") %>% set_vanity_url("/my-awesome-app") # edit another piece of content client %>% content_item("the-content-guid") %>% set_vanity_url("/another-awesome-app") # migrate content to another server client_prod <- connect( host = "prod.example.com", api_key = "my-secret-key" ) prod_bnd <- client %>% content_item("the-guid-to-promote") %>% download_bundle() client_prod %>% deploy(prod_bnd, title = "Now in Production") %>% set_vanity_url("/my-app") # open a browser to the content item client_prod %>% browse_dashboard() client_prod %>% browse_solo() ``` # Code of Conduct Please note that the `connectapi` project is released with a [Contributor Code of Conduct](.github/CODE_OF_CONDUCT.md). By contributing to this project, you agree to abide by its terms. <file_sep># deploy the current_bundle deploy_current <- function(content) { res <- content$get_connect()$POST(glue::glue("v1/experimental/content/{content$get_content()$guid}/deploy"), body = list(bundle_id = content$get_content()$bundle_id)) return(Task$new(connect = content$get_connect(), content = content$get_content(), task = res$task_id)) } # ACLs ---------------------------------------------------- #' ACL Add Group #' #' Add a group_guid to the content as an owner or viewer #' #' @param content The R6 Content object #' @param group_guid The group's GUID #' @param role One of "owner" or "viewer" #' #' @return The R6 content object (for piping) #' #' @keywords internal acl_add_group <- function(content, group_guid, role) { warn_experimental("acl_add") res <- content$get_connect()$POST( glue::glue("applications/{content$get_content()$guid}/groups"), body = list( app_role = role, guid = group_guid ) ) return(content) } #' ACL Add User #' #' Add a user_guid to the content as an owner or viewer #' #' @param content The R6 Content object #' @param user_guid The user's GUID #' @param role One of "owner" or "viewer" #' #' @return The R6 content object (for piping) #' #' @keywords internal acl_add_user <- function(content, user_guid, role) { warn_experimental("acl_add") res <- content$get_connect()$POST( glue::glue("applications/{content$get_content()$guid}/users"), body = list( app_role = role, guid = user_guid ) ) return(content) } #' @rdname acl_add_user acl_add_collaborator <- function(content, user_guid) { acl_add_user(content = content, user_guid = user_guid, role = "owner") } # TODO: Should this be a warning if the user is a collaborator? Will downgrade # their permissions # TODO: How should this behave if the content does not have access_type: acl? #' @rdname acl_add_user acl_add_viewer <- function(content, user_guid) { acl_add_user(content = content, user_guid = user_guid, role = "viewer") } #' @rdname acl_add_user acl_remove_user <- function(content, user_guid) { warn_experimental("acl_remove") res <- content$get_connect()$DELETE( glue::glue("applications/{content$get_content()$guid}/users/{user_guid}") ) return(content) } #' @rdname acl_add_user acl_remove_collaborator <- acl_remove_user #' @rdname acl_add_user acl_remove_viewer <- acl_remove_user #' @rdname acl_add_user acl_add_self <- function(content) { acl_add_collaborator(content, content$get_connect()$GET("me")$guid) } #' @rdname acl_add_user acl_remove_self <- function(content) { acl_remove_user(content, content$get_connect()$GET("me")$guid) } acl_user_role <- function(content, user_guid) { warn_experimental("acl_user_role") scoped_experimental_silence() acls <- get_acl_user_impl(content) if (is.null(user_guid) || is.na(user_guid)) { return(NULL) } user_entry <- purrr::flatten(purrr::keep(acls, ~ .x$guid == user_guid)) return(user_entry$app_role) } #' @rdname acl_add_group acl_remove_group <- function(content, group_guid) { warn_experimental("acl_remove") res <- content$get_connect()$DELETE( glue::glue("applications/{content$get_content()$guid}/groups/{group_guid}") ) return(content) } acl_group_role <- function(content, group_guid) { warn_experimental("acl_group_role") scoped_experimental_silence() acls <- get_acl_group_impl(content) if (is.null(group_guid) || is.na(group_guid)) { return(NULL) } group_entry <- purrr::flatten(purrr::keep(acls, ~ .x$guid == group_guid)) return(group_entry$app_role) } <file_sep>context("utils") test_that("safequery handles values correctly", { pref <- "prefixed" nullval <- NULL expect_identical(safe_query(nullval, pref), "") oneval <- "blah" expect_identical(safe_query(oneval, pref), paste0(pref, oneval)) moreval <- c("blah", "blah2") expect_identical(safe_query(moreval, pref), paste0(pref, paste(moreval, collapse = "|"))) morenull <- c(NULL, NULL) expect_identical(safe_query(morenull, pref, "|"), "") }) test_that("simplify_version works", { expect_identical(simplify_version("1.8.2-4"), "1.8.2") expect_identical(simplify_version("1.8.2.1-4"), "1.8.2") expect_identical(simplify_version("10.70.204.1-4"), "10.70.204") expect_identical(simplify_version("10.0.0.0-4"), "10.0.0") }) test_that("check_connect_version works", { # silent for patch version changes expect_silent(check_connect_version("1.8.2-4", "1.8.2.1-10")) # warnings for minor version changes expect_warning(check_connect_version("1.8.2-4", "1.8.0.5-1"), "newer") expect_warning(check_connect_version("1.8.2-4", "2.8.0.5-1"), "older") })
3ce3463b0cd4cc30f9c7cd89cb011f8784146c56
[ "Markdown", "R" ]
3
Markdown
brunaw/connectapi
2cc63bd645aae04fcb5584d5162decc18b6b4f35
cc074b6aab7d94ab2b0c87a6a46fce50895b1dd6
refs/heads/master
<repo_name>signalhub/todo-list<file_sep>/app/src/components/Todo.jsx import React, { Component, PropTypes } from 'react'; const propTypes = { todoItem: PropTypes.object }; class Todo extends Component { render() { const { todoItem } = this.props; return( <div className="b-item-todo"> {todoItem.get('isComplete') ? <strike>{todoItem.get('text')}</strike> : <span>{todoItem.get('text')}</span> } </div> ) } } Todo.PropTypes = propTypes; export default Todo; <file_sep>/app/src/actions/index.js const uid = () => Math.random().toString(10).slice(2); export const addNewTodo = (text) => { return { type: 'ADD_NEW_TODO', payload: { id: uid(), isComplete: false, text } } }; export const toggleTodo = (id) => { return { type: 'TOGGLE_TODO', payload: { id } } }; export const clearAll = () => { return { type: 'CLEAR_ALL', payload: {} } }; <file_sep>/app/src/components/TodoList.jsx import React, {Component, PropTypes} from 'react'; import Todo from './Todo'; import './styles.styl' const propTypes = { todoList: PropTypes.array, addNewTodo: PropTypes.func, toggleTodo: PropTypes.func, clearAll: PropTypes.func }; class TodoList extends Component { render() { const {todoList, addNewTodo, toggleTodo, clearAll} = this.props; const onSubmit = (event) => { const input = event.target; const text = input.value; const isEnterKey = (event.which == 13); if (isEnterKey && text.length > 0) { addNewTodo(text); input.value = ''; } }; const toggleClick = (id) => event => toggleTodo(id); return ( <div className="b-main"> <h1>TODO LIST</h1> <div className="b-todo-list"> <input type='text' className='todo-list-input' placeholder='Add todo' onKeyDown={onSubmit}/> <ul> {todoList.map(todo => ( <li key={todo.get('id')} onClick={toggleClick(todo.get('id'))}> <Todo todoItem={todo}/> </li> ))} </ul> { todoList.size ? <button className="btn-clear-list" onClick={clearAll}>Clear list</button> : '' } </div> </div> ) } } TodoList.PropTypes = propTypes; export default TodoList;
1d377a7330f45e0f8f1becf3ee8e760f969e6629
[ "JavaScript" ]
3
JavaScript
signalhub/todo-list
8b618b7fc05ea4795db5caed2ca6df5457c18c97
487ca9ab108b87e8eeed743b4197c8f069211216
refs/heads/master
<file_sep>import cv2 image = cv2.imread("/home/lichen/FALSR/dataset/B100/img_99_SRF_2_LR.jpg") image = cv2.resize(image,(800,500),cv2.INTER_CUBIC) cv2.imwrite("/home/lichen/桌面/cv.jpg",image)
0e07eb2e21ac27367bb4ef88fa7b07b6bc8e6359
[ "Python" ]
1
Python
205418367/FALSR
d68976cf7285253a9c3e398c75638d99b05a8e54
428f9f01f1560c6021b147049f7684cf020e124e
refs/heads/master
<repo_name>leadpython/Grasp<file_sep>/server/models/connection.js //sets up database connection var pg = require('knex')({ client: 'pg', connection: process.env.DATABASE_URL || 'postgres://localhost:5432/graspdb', searchPath: 'knex,public' }); module.exports = pg; <file_sep>/client/reducers/index.js // MODULES ============================= // Actions import {UPDATE_MESSAGE, ADD_MESSAGE} from 'actions/message-actions' // REDUCER ============================================= // Reducers specify how the application's state changes in response. // In Redux, all application state is stored as a single object. export default function (initialState) { // The reducer is a pure function that takes the previous state and an action, // and returns the next state. return (state = initialState, action) => { switch(action.type) { case UPDATE_MESSAGE: // Never mutate the state, but create a new copy of the state. return Object.assign({}, state, { currentMessage: action.message }); case ADD_MESSAGE: const text = state.currentMessage.trim(); if (text) { let messages = state.messages.map(message => Object.assign({}, message)); messages.push({id: messages.length + 1, text}); return { messages, currentMessage: '' }; } default: // Always return the previous state for any unknown action. return state; } } } <file_sep>/server/index.js // MODULES ===================================== // Server import path from 'path'; import express from 'express'; // Client rendering import handlebars from 'express-handlebars'; import React from 'react'; import ReactDOMServer from 'react-dom/server'; // State management using Redux import {createStore} from 'redux'; import {Provider} from 'react-redux'; import App from './generated/app'; import SignupForm from '../client/components/signup'; import LoginForm from '../client/components/login'; // Database import db from './models/connection.js'; import dbsetup from './models/dbsetup.js'; // import router from './routes.js'; import models from './models' //for parsing import bodyParser from 'body-parser'; // SERVER SETUP ================================ const app = express(); app.use(bodyParser.urlencoded()); app.use(bodyParser.json()); //parsing set up // Set view templates app.engine('handlebars', handlebars({ defaultLayout: 'main', layoutsDir: path.resolve(__dirname, 'views/layouts') })); app.set('view engine', 'handlebars'); app.set('views', path.resolve(__dirname, 'views')); // Set static assets app.use(express.static(path.resolve(__dirname, '../dist'))); app.use("/css", express.static(__dirname + '/css')); // ROUTES ===================================== // Static HTML on page load app.get('/', (request, response) => { // Initialize state on page load const initialState = { currentMessage: '', messages: [] }; // Instantiate Redux store that returns initial state const store = createStore((state=initialState) => state); const appContent = ReactDOMServer.renderToString( // Provider wraps App and provides access to store <Provider store={store}> <App> <a href="/login"><button style={{fontSize: '50px'}}>ENTER SITE</button></a> </App> </Provider> ); // JSON string representation of initialState is created and passed // as a parameter to the app template so that the state can be shared // with the client. response.render('app', { app: appContent, initialState: JSON.stringify(initialState) }); }); app.get('/signup', (request, response) => { // Initialize state on page load const initialState = { currentMessage: '', messages: [] }; // Instantiate Redux store that returns initial state const store = createStore((state=initialState) => state); const appContent = ReactDOMServer.renderToString( // Provider wraps App and provides access to store <Provider store={store}> <App> <SignupForm /> </App> </Provider> ); // JSON string representation of initialState is created and passed // as a parameter to the app template so that the state can be shared // with the client. response.render('app', { app: appContent, initialState: JSON.stringify(initialState) }); }); app.get('/login', (request, response) => { // Initialize state on page load const initialState = { currentMessage: '', messages: [] }; // Instantiate Redux store that returns initial state const store = createStore((state=initialState) => state); const appContent = ReactDOMServer.renderToString( // Provider wraps App and provides access to store <Provider store={store}> <App> <LoginForm /> </App> </Provider> ); // JSON string representation of initialState is created and passed // as a parameter to the app template so that the state can be shared // with the client. response.render('app', { app: appContent, initialState: JSON.stringify(initialState) }); }); app.post('/api/signup', (request, response) => { models.users.signup(request, function (err, result) { if(err) { response.send(err.detail).status(409); } else { response.sendStatus(201); } }) }) app.post('/api/signin', (request, response) => { models.users.signin(request, function (err, result) { if(err) { console.log(err) response.send(err.detail).status(409); } else if (result.length === 0) { response.sendStatus(409) throw new Error("Sign in failed") } else { response.send(result).status(201) //render canvas } }) }) // Database middleware // app.use("/api/user", router); export default app; <file_sep>/server/models/index.js var db = require('./connection.js'); //set up database connection //this is responsible for communicating with the database module.exports = { users: { signin: function (request, callback) { db('users'). where( 'username', request.body.username ). andWhere({ hashedpw: db.raw( "crypt('"+ request.body.password + "', hashedpw)") }) .select() .then(function (res) { callback(null, res); }) .catch(function (error){ callback(error, null); }); }, signup: function (request, callback) { db('users').insert( {username: request.body.username, firstname: request.body.firstname, secondname: request.body.secondname, email: request.body.email, hashedpw: db.raw( "crypt('"+ request.body.password + "', gen_salt('md5'))" )}) .then(function(ret){ }) .then(function (res) { callback(null, res); }) .catch(function(error) { callback(error, null); }); } } }; <file_sep>/server/routes.js var controllers = require('./controllers/index.js'); var router = require('express').Router(); for (var route in controllers) { console.log("In routes") router.route("/" + route) .post(controllers[route].post); } //on initialisation sets up all the routes, saves time from writing them out module.exports = router;<file_sep>/client/containers/app/index.js import React from 'react'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import {} from './style.less'; import SignupForm from 'components/signup'; import LoginForm from 'components/login'; import Header from 'components/header'; import MessageList from 'components/message-list'; import MessageEntryBox from 'components/message-entry-box'; import AddTodo from 'components/add-to-do'; import TodoList from 'components/todo-list'; import Footer from 'components/footer'; /* Import all of the exported action creator functions and constants in the message-actions module and make them available in a single object */ import * as messageActionCreators from 'actions/message-actions'; class App extends React.Component { render() { return ( <div> <Header /> {this.props.children} </div> ); } } // Injects values from the state in the store to the components properties. function mapStateToProps(state) { return { messages: state.messages, currentMessage: state.currentMessage }; } // Injects action creator functions into the component properties that dispatch the returned objects to the store function mapDispatchToProps(dispatch) { /* bindActionCreators turns an object whose values are action creators, into an object with the same keys, but with every action creator wrapped into a dispatch call so they may be invoked directly. */ return bindActionCreators(messageActionCreators, dispatch); } // Create a connector that injects properties and action creators to a component. const connector = connect(mapStateToProps, mapDispatchToProps); // Create a new component from App with the ability to connect to the store const ConnectedApp = connector(App); export default ConnectedApp; <file_sep>/client/index.js // MODULES ================================ // React import React from 'react'; import ReactDOM from 'react-dom'; // Redux import {createStore, combineReducers} from 'redux'; import {Provider} from 'react-redux'; // App import App from 'containers/app'; import reducers from 'reducers'; // Routing Related import { Router, Route } from 'react-router' import { createHistory } from 'history' import { syncReduxAndRouter } from 'redux-simple-router'; import { routeReducer } from 'redux-simple-router'; // import reducers from './reducers' import SignupForm from './components/signup'; import LoginForm from './components/login'; const reducer = combineReducers(Object.assign({}, reducers, { routing: routeReducer })) const history = createHistory(); // Grab the state from a global injected into server-generated HTML const initialState = window.INITIAL_STATE; // Create Redux store with initial state const store = createStore(reducers(initialState)); syncReduxAndRouter(history, store) ReactDOM.render( // Provider makes store instance available to all Components <Provider store={store}> <Router history={history}> <Route path="/" component={App}> <Route path="signup" component={SignupForm} /> <Route path="login" component={LoginForm} /> </Route> </Router> </Provider> , document.getElementById('app')); /* Store = createStore(reducers) */ <file_sep>/client/actions/message-actions.js // ACTION TYPES ================================= // Actions are payloads of information that send data from your application to your store. They are the only source of information for the store. export const UPDATE_MESSAGE = 'update-message'; export const ADD_MESSAGE = 'add-message'; // ACTION CREATORS ============================== export function updateMessage(message) { // Actions are plain objects. They must have a type property that indicates the type of action being performed. Types should typically be defined as string constants. // It is a good idea to pass as little data in each action as possible. return { type: UPDATE_MESSAGE, message }; } export function addMessage() { return { type: ADD_MESSAGE }; } <file_sep>/client/components/login/index.js import React from "react"; class LoginForm extends React.Component { loginUser(e) { e.preventDefault(); // var self = this; // var userData = { // username: document.getElementById('signupUsername').value, // password: document.getElementById('signupPassword').value, // email: document.getElementById('signupEmail').value // }; alert("Username:\n" + document.getElementById('signupUsername').value + "\n\nPassword:\n" + document.getElementById('signupPassword').value); } render() { return ( <div className="signupContainer"> <h1 id="loginTitle" >LOGIN</h1> <form onSubmit={this.createUser}> <input id="signupUsername" type="text" placeholder="Enter your username..." /> <br /><br /> <input id="signupPassword" type="password" placeholder="Enter your password..." /> <br /><br /> <input id="login" type="submit" value="LOGIN" /> </form> <br/> Do not have an account? <a href="/signup"> SIGNUP!</a> </div> ); } } export default LoginForm;
e099c3f31fa62620da240256852a4acd342ca9a1
[ "JavaScript" ]
9
JavaScript
leadpython/Grasp
a95dc80ff27e7f5bee84decc453897218f9e1278
384437d7bccb4a77a1c2ad6ffba4af423441b21b
refs/heads/master
<repo_name>Gyeongseob-Seo/2021_KNU_SW-Hackathon<file_sep>/2021SWhackathon_KNUCSE/HomeViewController.swift // // HomeViewController.swift // 2021SWhackathon_KNUCSE // // Created by 서경섭 on 2021/07/23. // //import UIKit //import SwiftSoup // //class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextViewDelegate { // // // @IBOutlet weak var TotalCorona: UILabel! // @IBOutlet weak var DaeguCorona: UILabel! // // // @IBOutlet weak var GongjiTableView: UITableView!{ // didSet { // GongjiTableView.delegate = self // GongjiTableView.dataSource = self // GongjiTableView.separatorStyle = .none // GongjiTableView.rowHeight = 70 // } // } // // var count: Int = 0 // var GongjiData: [String]! // var GongjiIndex: Int = 0 // // override func viewDidLoad() { // super.viewDidLoad() // // fetchHTMLParsingResultWill() // fetchHTMLParsingResultGongji() // // GongjiTableView.register(GongjiCellTableViewCell.self, forCellReuseIdentifier: "GongjiCell") // // // Do any additional setup after loading the view. // } // // // func fetchHTMLParsingResultWill(/*completion: @escaping() -> ()*/) { // DispatchQueue.main.async { // UIApplication.shared.isNetworkActivityIndicatorVisible = true // } // var Data = [String] () // let urlAddress = "http://covid19.daegu.go.kr/index.html" // print("함수진입") // guard let url = URL(string: urlAddress) else {return} // do { // let html = try String(contentsOf: url, encoding: .utf8) // let doc: Document = try SwiftSoup.parse(html) // print(doc) // let firstLinkTitless: Elements = try doc.select("div.sa_today").select("p.info_variation") // // for element in firstLinkTitless.array() { // print("Title : ", try element.text()) // Data.append(try element.text()) // } // //completion() // }catch let error { // print("Error: ", error) // } // // } // // // func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // return GongjiData.count // } // // func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // // let Gongjicell = GongjiTableView.dequeueReusableCell(withIdentifier: "GongjiCell", for: indexPath) as! GongjiCellTableViewCell // // Gongjicell.ContentView.text = GongjiData[indexPath.row] // Gongjicell.MoveButton.addTarget(self, action: #selector(moveToView), for: .touchUpInside) // return Gongjicell // } // // // func fetchHTMLParsingResultGongji(/*completion: @escaping() -> ()*/) { // GongjiData = [String]() // DispatchQueue.main.async { // UIApplication.shared.isNetworkActivityIndicatorVisible = true // } // // let urlAddress = "http://knu.ac.kr/wbbs/wbbs/bbs/btin/list.action?bbs_cde=34&menu_idx=224" // print("함수진입공지") // guard let url = URL(string: urlAddress) else {return} // do { // let html = try String(contentsOf: url, encoding: .utf8) // let doc: Document = try SwiftSoup.parse(html) // //print(doc) // let firstLinkTitless: Elements = try doc.select("div.board_list").select("td.subject").select("a") // // for element in firstLinkTitless.array() { // print("Title : ", try element/*.text()*/) // GongjiData.append(try element.text()) // count += 1 // } // //completion() // }catch let error { // print("Error: ", error) // } // print("\(count) 회 필요 ") // } // // @objc func moveToView(){ // guard let svc = self.storyboard?.instantiateViewController(identifier: "NoticeView") as? NoticeView else { // return // } // // svc.URL = URL(string: "https://www.naver.com") // self.present(svc, animated: true) // } // // // /* // // MARK: - Navigation // // // In a storyboard-based application, you will often want to do a little preparation before navigation // override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // // Get the new view controller using segue.destination. // // Pass the selected object to the new view controller. // } // */ // //} import UIKit import SwiftSoup class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextViewDelegate{ var count: Int = 0 var currentlyWorkingIndex: Int! var GongjiData: [String]! var GongjiLink: [String]! var GongjiIndex: Int = 0 var studnum: String! var password: String! @IBOutlet weak var Time: UILabel! let timeSelector : Selector = #selector(HomeViewController.updateTime) let interval = 1.0 @IBOutlet weak var CoronaInKorea: UILabel! @IBOutlet weak var CoronaInKoreaForeign: UILabel! @IBOutlet weak var CoronaDaegu: UILabel! @IBOutlet weak var Infected_today: UITextView! @IBOutlet weak var Infected_local: UITextView! @IBOutlet weak var Infected_abroad: UITextView! @IBOutlet weak var Cured: UITextView! @IBOutlet weak var Curing: UITextView! @IBOutlet weak var newbtn: UIButton! @IBOutlet weak var schoolbtn: UIButton! @IBOutlet weak var chatbtn: UIButton! @IBOutlet weak var GongjiTableView: UITableView!{ didSet { GongjiTableView.delegate = self GongjiTableView.dataSource = self GongjiTableView.separatorStyle = .none GongjiTableView.rowHeight = 70 } } override func viewDidLoad() { super.viewDidLoad() Timer.scheduledTimer(timeInterval: interval, target: self, selector: timeSelector, userInfo: nil, repeats: true) fetchHTMLParsingResultWill() fetchHTMLParsingResultGongji() GongjiTableView.register(GongjiCellTableViewCell.self, forCellReuseIdentifier: "GongjiCell") } @objc func updateTime(){ // count 값을 문자열로 변환하여 lblCurrentTime.text에 출력 // lblCurrentTime.text = String(count) // count = count + 1 // count 값을 1 증가 let date = NSDate() // 현재 시간을 가져옴 let formatter = DateFormatter() // DateFormatter라는 클래스의 상수 formatter를 선언 formatter.dateFormat = "yyyy-MM-dd HH:mm:ss EEE" // 상수 formatter의 dateFormat 속성을 설정 // 현재날짜(date)를 formatter의 dateFormat에서 설정한 포맷대로 string 메서드를 사용하여 문자열(String)로 변환 Time.text = "현재시간 : "+formatter.string(from: date as Date) // 문자열로 변한한 date 값을 "현재시간:"이라는 문자열에 추가하고 그 문자열을 lblCurrentTime의 text에 입력 } @IBAction func LogOut(_ sender: Any) { self.presentingViewController?.dismiss(animated: true) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ func fetchHTMLParsingResultWill(/*completion: @escaping() -> ()*/) { DispatchQueue.main.async { UIApplication.shared.isNetworkActivityIndicatorVisible = true } var Data = [String] () var Data2 = [String] () let urlAdd_whole = "http://ncov.mohw.go.kr/" let urlAddress = "http://covid19.daegu.go.kr/index.html" print("함수진입") guard let url = URL(string: urlAddress) else {return} do { let html = try String(contentsOf: url, encoding: .utf8) let doc: Document = try SwiftSoup.parse(html) //print(doc) let firstLinkTitless: Elements = try doc.select("div.sa_today").select("p.info_variation") for element in firstLinkTitless.array() { print("Title : ", try element.text()) Data.append(try element.text()) } //completion() }catch let error { print("Error: ", error) } print("___진입___") guard let url_national = URL(string: urlAdd_whole) else {return} do { let html = try String(contentsOf: url_national, encoding: .utf8) let doc: Document = try SwiftSoup.parse(html) //print(doc) let firstLinkTitless: Elements = try doc/*.select("div.wrap nj").select("div.manlive_container").select("div.container")*/.select("div.datalist").select("span.data") for elements in firstLinkTitless.array() { print("Data : ", try elements.text()) Data2.append(try elements.text()) } } catch let error { print("Error: ",error) } print("---------") CoronaInKorea.text = Data2[0] + "명" CoronaInKoreaForeign.text = Data2[1] + "명" CoronaDaegu.text = Data[0] } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return GongjiData.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let Gongjicell = GongjiTableView.dequeueReusableCell(withIdentifier: "GongjiCell", for: indexPath) as! GongjiCellTableViewCell Gongjicell.ContentView.text = GongjiData[indexPath.row] currentlyWorkingIndex = indexPath.row Gongjicell.MoveButton.addTarget(self, action: #selector(moveToView), for: .touchUpInside) return Gongjicell } func fetchHTMLParsingResultGongji(/*completion: @escaping() -> ()*/) { GongjiData = [String]() GongjiLink = [String]() DispatchQueue.main.async { UIApplication.shared.isNetworkActivityIndicatorVisible = true } let urlAddress = "http://knu.ac.kr/wbbs/wbbs/bbs/btin/list.action?bbs_cde=34&menu_idx=224" print("함수진입공지") guard let url = URL(string: urlAddress) else {return} do { let html = try String(contentsOf: url, encoding: .utf8) let doc: Document = try SwiftSoup.parse(html) //print(doc) let firstLinkTitless: Elements = try doc.select("div.board_list").select("td.subject").select("a") for element in firstLinkTitless.array() { print("Title : ", try element.text()) GongjiData.append(try element.text()) let temp : String = try element.attr("href") GongjiLink.append( "http://knu.ac.kr" + temp) print("href : ",try element.attr("href")) count += 1 } //completion() }catch let error { print("Error: ", error) } print("\(count) 회 필요 ") } @objc func moveToView(){ guard let svc = self.storyboard?.instantiateViewController(identifier: "NoticeView") as? NoticeView else { return } svc.URL = URL(string: GongjiLink[currentlyWorkingIndex]) print(GongjiLink[currentlyWorkingIndex]) GongjiIndex += 1 self.present(svc, animated: true) } } <file_sep>/2021SWhackathon_KNUCSE/SettingViewController.swift // // SettingViewController.swift // 2021SWhackathon_KNUCSE // // Created by 서경섭 on 2021/07/23. // import UIKit import Firebase class SettingViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let loginVC = self.storyboard?.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController let appDel:AppDelegate = UIApplication.shared.delegate as! AppDelegate appDel.window?.rootViewController = loginVC // Do any additional setup after loading the view. } @IBAction func moveToLogin(_ sender: Any) { let firebaseAuth = Auth.auth() do { try firebaseAuth.signOut() self.navigationController?.popToRootViewController(animated: true) print("로그아웃 성공") } catch let signOutError as NSError { print ("Error signing out: %@", signOutError) } } } <file_sep>/2021SWhackathon_KNUCSE/SingUpViewController.swift // // SingUpViewController.swift // 2021SWhackathon_KNUCSE // // Created by 서경섭 on 2021/07/23. // import UIKit import Firebase class SingUpViewController: UIViewController { @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var signUpButton: UIButton! var radius: Int = 22 override func viewDidLoad() { super.viewDidLoad() usernameTextField.layer.cornerRadius = CGFloat(radius) passwordTextField.layer.cornerRadius = CGFloat(radius) signUpButton.layer.cornerRadius = CGFloat(radius) // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { self.navigationController?.navigationBar.isHidden = true } @IBAction func didTapSignUpButton(_ sender: Any) { guard let username = usernameTextField.text else { return } guard let password = passwordTextField.text else { return } Auth.auth().createUser(withEmail: username, password: <PASSWORD>) { authResult, error in if let e = error { print(e) } else { if let mainViewController = self.storyboard?.instantiateViewController(identifier: "MainViewController") as? MainViewController { // mainViewController.modalPresentationStyle = .fullScreen // present(mainViewController, animated: true, completion: nil) self.navigationController?.pushViewController(mainViewController, animated: true) } } } } } <file_sep>/2021SWhackathon_KNUCSE/ChatViewController.swift // // ChatViewController.swift // ChattingApp // // Created by 윤경록 on 23/07/2021. // Copyright © 2021 윤경록. All rights reserved. // import UIKit import Foundation import Firebase import FirebaseFirestore struct Message { let sender: String let body: String } class ChatViewController: UIViewController,UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var MessageTableView: UITableView! let db = Firestore.firestore() @IBOutlet weak var MessageTextField: UITextField! var messages: [Message] = [] func init_data(){ var m1 = Message(sender: "Hom",body: "Hi") messages.append(m1) } override func viewDidLoad() { super.viewDidLoad() self.MessageTableView.dataSource = self self.MessageTableView.delegate = self MessageTableView.register(UINib(nibName: "MessageCell", bundle: nil), forCellReuseIdentifier: "ReusableCell") /* MessageTableView.register(UINib(nibName: "MessageCell", bundle: nil), forCellReuseIdentifier: "ReusableCell") init_data()*/ self.MessageTableView.reloadData() print("RoadSuccess") loadMessages() print("Enter Chat View") // Do any additional setup after loading the view. } @IBAction func sendMessage(_ sender: UIButton) { if let messageBody = MessageTextField.text, let messageSender = Auth.auth().currentUser?.email { db.collection("messages").addDocument(data: [ "sender": messageSender, "body": messageBody, "date": Date().timeIntervalSince1970 ]) { (error) in if let e = error { print(e.localizedDescription) } else { print("Success save data ") DispatchQueue.main.async { self.MessageTextField.text = "" } } } } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ private func loadMessages() { print("Function load Message - entered") db.collection("messages") .order(by: "date") .addSnapshotListener { (querySnapshot, error) in self.messages = [] if let e = error { print(e.localizedDescription) } else { if let snapshotDocuments = querySnapshot?.documents { snapshotDocuments.forEach { (doc) in let data = doc.data() if let sender = data["sender"] as? String, let body = data["body"] as? String { self.messages.append(Message(sender: sender, body: body)) DispatchQueue.main.async { self.MessageTableView.reloadData() self.MessageTableView.scrollToRow(at: IndexPath(row: self.messages.count-1, section: 0), at: .top, animated: false) } } } } } } print(messages) print("Function - loadmessage - success") } } extension ChatViewController { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { print("Function tableview 2nd - enter") let message = messages[indexPath.row] let messageCell = tableView.dequeueReusableCell(withIdentifier: "ReusableCell", for: indexPath) as! MessageCell if message.sender == Auth.auth().currentUser?.email { messageCell.LeftImageView.isHidden = true messageCell.RightImageView.isHidden = false messageCell.MessageLabel.backgroundColor = UIColor.init(displayP3Red: 196/255, green: 139/255, blue: 58/255, alpha: 1) messageCell.MessageLabel.textColor = UIColor.white } else { messageCell.LeftImageView.isHidden = false messageCell.RightImageView.isHidden = true messageCell.MessageLabel.backgroundColor = UIColor.init(displayP3Red: 121/255, green: 121/255, blue: 119/255, alpha: 1) messageCell.MessageLabel.textColor = UIColor.white } messageCell.MessageLabel.text = message.body print("Function tableview 2nd - end") return messageCell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return messages.count } } <file_sep>/2021SWhackathon_KNUCSE/LoginViewController.swift // // ViewController.swift // 2021SWhackathon_KNUCSE // // Created by 서경섭 on 2021/07/22. // import UIKit import Firebase class LoginViewController: UIViewController { var userModel = UserModel() // 인스턴스 생성 @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var signInButton: UIButton! @IBOutlet weak var signUpButton: UIButton! var radius: Int = 22 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. usernameTextField.layer.cornerRadius = CGFloat(radius) passwordTextField.layer.cornerRadius = CGFloat(radius) signInButton.layer.cornerRadius = CGFloat(radius) signUpButton.layer.cornerRadius = CGFloat(radius) //키보드 내리기 usernameTextField.addTarget(self, action: #selector(didEndOnExit), for: UIControl.Event.editingDidEndOnExit) passwordTextField.addTarget(self, action: #selector(didEndOnExit), for: UIControl.Event.editingDidEndOnExit) signInButton.addTarget(self, action: #selector(didEndOnExit), for: UIControl.Event.editingDidEndOnExit) } // end of viewDidLoad override func viewWillAppear(_ animated: Bool) { self.navigationController?.navigationBar.isHidden = true } @IBAction func didTapLoginButton(_ sender: UIButton) { // 옵셔널 바인딩 & 예외 처리 : Textfield가 빈문자열이 아니고, nil이 아닐 때 guard let email = usernameTextField.text, !email.isEmpty else { return } guard let password = passwordTextField.text, !password.isEmpty else { return } if userModel.isValidEmail(id: email){ if let removable = self.view.viewWithTag(100) { removable.removeFromSuperview() } } else { shakeTextField(textField: usernameTextField) let emailLabel = UILabel(frame: CGRect(x: 68, y: 350, width: 279, height: 45)) emailLabel.text = "이메일 형식을 확인해 주세요" emailLabel.textColor = UIColor.red emailLabel.tag = 100 self.view.addSubview(emailLabel) } // 이메일 형식 오류 if userModel.isValidPassword(pwd: <PASSWORD>){ if let removable = self.view.viewWithTag(101) { removable.removeFromSuperview() } } else{ shakeTextField(textField: passwordTextField) let passwordLabel = UILabel(frame: CGRect(x: 68, y: 435, width: 279, height: 45)) passwordLabel.text = "비밀번호 형식을 확인해 주세요" passwordLabel.textColor = UIColor.red passwordLabel.tag = 101 self.view.addSubview(passwordLabel) } // 비밀번호 형식 오류 if userModel.isValidEmail(id: email) && userModel.isValidPassword(pwd: <PASSWORD>) { guard let username = usernameTextField.text else { return } guard let password = passwordTextField.text else { return } Auth.auth().signIn(withEmail: username, password: <PASSWORD>) { authResult, error in if let e = error { print("로그인 실패") self.shakeTextField(textField: self.usernameTextField) self.shakeTextField(textField: self.passwordTextField) let loginFailLabel = UILabel(frame: CGRect(x: 68, y: 510, width: 279, height: 45)) loginFailLabel.text = "아이디나 비밀번호가 다릅니다." loginFailLabel.textColor = UIColor.red loginFailLabel.tag = 102 self.view.addSubview(loginFailLabel) } else { if let mainViewController = self.storyboard?.instantiateViewController(identifier: "MainViewController") as? MainViewController { // mainViewController.modalPresentationStyle = .fullScreen // present(mainViewController, animated: true, completion: nil) self.navigationController?.pushViewController(mainViewController, animated: true) } } } let loginSuccess: Bool = loginCheck(id: email, pwd: password) if loginSuccess { print("로그인 성공") if let removable = self.view.viewWithTag(102) { removable.removeFromSuperview() } //self.performSegue(withIdentifier: "MainViewController", sender: self) // if let mainViewController = self.storyboard?.instantiateViewController(identifier: "MainViewController") as? MainViewController { //// mainViewController.modalPresentationStyle = .fullScreen //// present(mainViewController, animated: true, completion: nil) // self.navigationController?.pushViewController(mainViewController, animated: true) // } } // else { // print("로그인 실패") // shakeTextField(textField: usernameTextField) // shakeTextField(textField: passwordTextField) // let loginFailLabel = UILabel(frame: CGRect(x: 68, y: 510, width: 279, height: 45)) // loginFailLabel.text = "아이디나 비밀번호가 다릅니다." // loginFailLabel.textColor = UIColor.red // loginFailLabel.tag = 102 // // self.view.addSubview(loginFailLabel) // } } } // end of didTapLoginButton final class UserModel { struct User { var email: String var password: String } var users: [User] = [ User(email: "<EMAIL>", password: "<PASSWORD>"), User(email: "<EMAIL>", password: "<PASSWORD>"), User(email: "<EMAIL>", password: "<PASSWORD>") ] // 아이디 형식 검사 func isValidEmail(id: String) -> Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}" let emailTest = NSPredicate(format: "SELF MATCHES %@", emailRegEx) return emailTest.evaluate(with: id) } // 비밀번호 형식 검사 func isValidPassword(pwd: String) -> Bool { let passwordRegEx = "^[a-zA-Z0-9]{8,}$" let passwordTest = NSPredicate(format: "SELF MATCHES %@", passwordRegEx) return passwordTest.evaluate(with: pwd) } } // end of UserModel func loginCheck(id: String, pwd: String) -> Bool { for user in userModel.users { if user.email == id && user.password == pwd { return true // 로그인 성공 } } return false } // TextField 흔들기 애니메이션 func shakeTextField(textField: UITextField) -> Void{ UIView.animate(withDuration: 0.2, animations: { textField.frame.origin.x -= 10 }, completion: { _ in UIView.animate(withDuration: 0.2, animations: { textField.frame.origin.x += 20 }, completion: { _ in UIView.animate(withDuration: 0.2, animations: { textField.frame.origin.x -= 10 }) }) }) } // 다음 누르면 입력창 넘어가기, 완료 누르면 키보드 내려가기 @objc func didEndOnExit(_ sender: UITextField) { if usernameTextField.isFirstResponder { passwordTextField.becomeFirstResponder() } } } <file_sep>/2021SWhackathon_KNUCSE/GongjiCellTableViewCell.swift // // GongjiCellTableViewCell.swift // 2021SWhackathon_KNUCSE // // Created by 서경섭 on 2021/07/23. // import UIKit import SnapKit class GongjiCellTableViewCell: UITableViewCell { var ContentView: UILabel! var MoveButton: UIButton! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } override func prepareForReuse() { super.prepareForReuse() self.accessoryType = .none } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) ContentView = UILabel() MoveButton = UIButton() self.addView() self.makeConstraints() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func addView(){ self.contentView.addSubview(ContentView) self.contentView.addSubview(MoveButton) } func makeConstraints(){ ContentView.snp.makeConstraints{ make in make.top.bottom.equalToSuperview() make.left.equalToSuperview() make.width.equalToSuperview().multipliedBy(0.7) } MoveButton.setTitle("이동하기", for: .normal) MoveButton.setTitleColor(.black, for: .normal) MoveButton.snp.makeConstraints{ make in make.top.bottom.equalToSuperview() make.left.equalTo(self.ContentView.snp.right) make.right.equalToSuperview() } } }
57cda2b2a1af3231ae2a5ea09bac50c99482d1fb
[ "Swift" ]
6
Swift
Gyeongseob-Seo/2021_KNU_SW-Hackathon
64f3d3e4ae8de7bc5b6658c6bc9f584210b91607
80982e55324919d0c6c5e98d6f2d64d4702ae3e0
refs/heads/master
<repo_name>shujaatali101/agro<file_sep>/core/app/controllers/Setup/DriverController.php <?php namespace Setup; use BaseController, Input, View, Redirect, Validator, Types,Driver; class DriverController extends BaseController { /** * Display a listing of the resource. * Request GET * @return Response */ public function index() { $driver=Driver::all(); //dd($driver); return View::make('layouts.view.setup.driver') ->with('driver',$driver); } /** * Show the form for creating a new resource. * Request GET * @return Response */ public function create() { return View::make('layouts.forms.setup.driver') ->with('id', null) ->with('cnic', null) ->with('name', null) ->with('contactnumber', null); } /** * Store a newly created resource in storage. * Request POST * @return Response */ public function store() { $validation = Driver::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/driver/create')->withErrors($validation)->withInput(); }else { $driver = new Driver; $driver->createFor = Input::get('createfor'); $driver->cnic = Input::get('cnicnumber'); $driver->name = Input::get('name'); $driver->contactnumber = Input::get('contactnumber'); if($driver->save()){ return Redirect::to('setup/driver')->with('message','Driver Added'); } else { return Redirect::to('setup/driver/create')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } /** * Display the specified resource. * Request GET * @param int $id * @return Response */ public function show($id) { } /** * Show the form for editing the specified resource. * Request GET * @param int $id * @return Response */ public function edit($id) { $driver=Driver::find($id); $name = $driver->name; $cnic = $driver->cnic; $contactnumber = $driver->contactnumber; return View::make('layouts.forms.setup.driver') ->with('editform', 'Edit Driver') ->with('id', $id) ->with('cnic', $cnic) ->with('name', $name) ->with('contactnumber', $contactnumber); } /** * Update the specified resource in storage. * Request PUT * @param int $id * @return Response */ public function update($id) { $validation = Driver::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/driver/'.$id.'/edit')->withErrors($validation)->withInput(); }else { $driver = Driver::find($id); $driver->createFor = Input::get('createfor'); $driver->cnic = Input::get('cnicnumber'); $driver->name = Input::get('name'); $driver->contactnumber = Input::get('contactnumber'); if($driver->save()){ return Redirect::to('setup/driver')->with('message','Driver Edit'); } else { return Redirect::to('setup/driver/'.$id.'/edit')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } /** * Remove the specified resource from storage. * Request Delete * @param int $id * @return Response */ public function destroy($id) { // } }<file_sep>/core/app/models/Supplier.php <?php class Supplier extends Eloquent { protected $table = 'supplier'; public $timestamps = false; public function types() { return $this->belongsTo('Types'); } }<file_sep>/core/app/models/Product.php <?php class Product extends Eloquent { protected $table = 'product'; public $timestamps = false; public static $rules = array( 'category' => 'required|integer', 'createfor' => 'required|integer', 'createforname' => 'required', 'item' => 'required' ); public static function validate($data){ return Validator::make($data, static::$rules); } public function maincategory() { return $this->belongsTo('Maincategory'); } public function system() { return $this->belongsTo('System'); } public function setup() { return $this->belongsTo('Setup'); } public function category() { return $this->belongsTo('Category'); } public function classes() { return $this->belongsTo('Classes'); } public function foume() { return $this->belongsTo('Foume'); } public function grade() { return $this->belongsTo('Grade'); } public function group() { return $this->belongsTo('Group'); } public function nature() { return $this->belongsTo('Nature'); } public function type() { return $this->belongsTo('Type'); } }<file_sep>/core/app/models/Maincategory.php <?php class Maincategory extends Eloquent { protected $table = 'maincategory'; public $timestamps = false; public static $rules = array( 'types' => 'required|integer', 'name' => 'required|min:2|max:200' ); public static function validate($data){ return Validator::make($data, static::$rules); } public function types() { return $this->belongsTo('Types', 'type'); } public function category() { return $this->hasMany('Category'); } public function classes() { return $this->hasMany('Category'); } public function foume() { return $this->hasMany('Category'); } public function group() { return $this->hasMany('Category'); } public function nature() { return $this->hasMany('Category'); } public function type() { return $this->hasMany('Category'); } public function grade() { return $this->hasMany('Category'); } public function product() { return $this->hasMany('Product'); } }<file_sep>/core/app/routes.php <?php Route::group(array('before' => 'afterlogin'), function() { Route::get('/', function() { return View::make('layouts.master.blank'); }); Route::get('/home', function() { return View::make('layouts.master.blank'); }); Route::resource('setup/expense', 'Setup\ExpenseController'); Route::resource('setup/fpa/category', 'Setup\fpa\CategoryController'); Route::resource('setup/fpa/class', 'Setup\fpa\ClassController'); Route::resource('setup/fpa/foume', 'Setup\fpa\FoumeController'); Route::resource('setup/fpa/group', 'Setup\fpa\GroupController'); Route::resource('setup/fpa/nature', 'Setup\fpa\NatureController'); Route::resource('setup/fpa/type', 'Setup\fpa\TypeController'); Route::resource('setup/fpa/grade', 'Setup\fpa\GradeController'); Route::resource('setup/fpa/maincategory', 'Setup\fpa\McategoryController'); Route::resource('setup/driver', 'Setup\DriverController'); Route::resource('setup/transport', 'Setup\TransportController'); Route::resource('setup/delivery', 'Setup\DeliveryController'); Route::controller('setup/store', 'Setup\StoreController'); Route::controller('setup/factory', 'Setup\FactoryController'); Route::controller('setup/recipe', 'Setup\RecipeController'); Route::controller('setup/vechicles', 'Setup\VechiclesController'); Route::resource('setup/expensegroup', 'Setup\ExpenseGroupController'); Route::resource('setup/salarytype', 'Setup\SalaryTypeController'); Route::resource('setup/returnreason', 'Setup\ReturnReasonController'); Route::resource('setup/product', 'Setup\ProductController'); Route::controller('ajax', 'AjaxController'); Route::resource('setup/employee', 'Setup\EmployeeController'); Route::controller('view/employee', 'View\EmployeeController'); Route::get('/logout', 'LoginController@logout'); }); Route::group(array('before' => 'beforelogin'), function() { Route::get('/', function() { return View::make('login'); }); Route::get('/login', function() { return View::make('login'); }); Route::post('/auth', 'LoginController@auth'); }); /*Event::listen('laravel.query', function($sql){ var_dump($sql); });*/<file_sep>/core/app/controllers/Setup/VechiclesController.php <?php namespace Setup; use BaseController, Input, View, Redirect, Validator, Type,Vechicles,Nature, Maincategory; class VechiclesController extends BaseController { /** * Display a listing of the resource. * Request GET * @return Response */ public function getIndex() { $vechicles=Vechicles::with('type','nature')->get(); //dd($vechicles); return View::make('layouts.view.setup.vechicles') ->with('vechicles',$vechicles); } /** * Show the form for creating a new resource. * Request GET * @return Response */ public function getCreate() { foreach (Type::where('section', '=', 6)->get() as $type) { $typelist[$type->id] = $type->name; } foreach (Nature::where('section', '=', 6)->get() as $type) { $naturelist[$type->id] = $type->name; } return View::make('layouts.forms.setup.vechicles') ->with('typelist', $typelist) ->with('type_id', null) ->with('naturelist', $naturelist) ->with('nature_id', null) ->with('id', null) ->with('name', null) ->with('contact', null) ->with('CNIC', null) ->with('address', null) ->with('carname', null) ->with('regno', null) ->with('make', null) ->with('model', null) ->with('engine_no', null) ->with('chachess_no', null) ->with('cc', null) ->with('body_type', null) ->with('colour', null) ->with('date', null) ->with('insurance', null) ->with('insurance_percentage', null) ->with('meter', null) ->with('finance_by', null) ->with('period', null) ->with('account', null) ->with('finance_percentage', null) ->with('finance_amount', null) ->with('doc', null) ->with('other', null) ->with('installment', null) ->with('clearence', null) ->with('sold_amount', null) ->with('sold_date', null); } /** * Store a newly created resource in storage. * Request POST * @return Response */ public function postIndex() { $validation = Vechicles::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/vechicles/create')->withErrors($validation)->withInput(); }else { $vechicles = new vechicles; $vechicles->type_id = Input::get('type_id'); $vechicles->nature_id = Input::get('nature_id'); $vechicles->name = Input::get('name'); $vechicles->contact = Input::get('contact'); $vechicles->CNIC = Input::get('CNIC'); $vechicles->address = Input::get('address'); $vechicles->carname = Input::get('carname'); $vechicles->regno = Input::get('regno'); $vechicles->make = Input::get('make'); $vechicles->model = Input::get('model'); $vechicles->engine_no = Input::get('engine_no'); $vechicles->chachess_no = Input::get('chachess_no'); $vechicles->cc = Input::get('cc'); $vechicles->body_type = Input::get('body_type'); $vechicles->colour = Input::get('colour'); $vechicles->date = Input::get('date'); $vechicles->insurance = Input::get('insurance'); $vechicles->insurance_percentage = Input::get('insurance_percentage'); $vechicles->meter = Input::get('meter'); $vechicles->finance_by = Input::get('finance_by'); $vechicles->period = Input::get('period'); $vechicles->account = Input::get('account'); $vechicles->finance_percentage = Input::get('finance_percentage'); $vechicles->finance_amount = Input::get('finance_amount'); $vechicles->doc = Input::get('doc'); $vechicles->other = Input::get('other'); $vechicles->installment = Input::get('installment'); $vechicles->sold_amount = Input::get('sold_amount'); $vechicles->sold_date = Input::get('sold_date'); if($vechicles->save()){ return Redirect::to('setup/vechicles')->with('message','vechicles Added'); } else { return Redirect::to('setup/vechicles/create')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } public function getEdit($id) { foreach (Type::where('section', '=', 6)->get() as $type) { $typelist[$type->id] = $type->name; } foreach (Nature::where('section', '=', 6)->get() as $type) { $naturelist[$type->id] = $type->name; } $vechicles =Vechicles ::find($id); $name = $vechicles ->name; $contact = $vechicles ->contact; $CNIC = $vechicles ->CNIC; $address = $vechicles ->address; $carname = $vechicles ->carname; $regno = $vechicles ->regno; $make = $vechicles ->make; $model = $vechicles ->model; $engine_no = $vechicles ->engine_no; $chachess_no = $vechicles ->chachess_no; $cc = $vechicles ->cc; $body_type = $vechicles ->body_type; $colour = $vechicles ->colour; $date = $vechicles ->date; $insurance = $vechicles ->insurance; $insurance_percentage = $vechicles ->insurance_percentage; $meter = $vechicles ->meter; $finance_by = $vechicles ->finance_by; $period = $vechicles ->period; $account = $vechicles ->account; $finance_percentage = $vechicles ->finance_percentage; $finance_amount = $vechicles ->finance_amount; $doc = $vechicles ->doc; $other = $vechicles ->other; $installment = $vechicles ->installment; $clearence = $vechicles ->clearence; $sold_amount = $vechicles ->sold_amount; $sold_date = $vechicles ->sold_date; $type_id = $vechicles ->type_id; $nature_id = $vechicles ->nature_id; return View::make('layouts.forms.setup.vechicles') ->with('editform', 'edit') ->with('typelist', $typelist) ->with('type_id', $type_id) ->with('naturelist', $naturelist) ->with('nature_id', $nature_id) ->with('id', $id) ->with('name', $name) ->with('contact', $contact) ->with('CNIC', $CNIC) ->with('address', $address) ->with('carname', $carname) ->with('regno', $regno) ->with('make', $make) ->with('model', $model) ->with('engine_no', $engine_no) ->with('chachess_no', $chachess_no) ->with('cc', $cc) ->with('body_type', $body_type) ->with('colour', $colour) ->with('date', $date) ->with('insurance', $insurance) ->with('insurance_percentage', $insurance_percentage) ->with('meter', $meter) ->with('finance_by', $finance_by) ->with('period', $period) ->with('account', $account) ->with('finance_percentage', $finance_percentage) ->with('finance_amount', $finance_amount) ->with('doc', $doc) ->with('other', $other) ->with('installment', $installment) ->with('clearence', $clearence) ->with('sold_amount', $sold_amount) ->with('sold_date', $sold_date); } /** * Update the specified resource in storage. * Request PUT * @param int $id * @return Response */ public function putEdit($id) { $validation = vechicles::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/vechicles/'.$id.'/edit')->withErrors($validation)->withInput(); }else { $vechicles = Vechicles::find($id); $vechicles->type_id = Input::get('type_id'); $vechicles->nature_id = Input::get('nature_id'); $vechicles->name = Input::get('name'); $vechicles->contact = Input::get('contact'); $vechicles->CNIC = Input::get('CNIC'); $vechicles->address = Input::get('address'); $vechicles->carname = Input::get('carname'); $vechicles->regno = Input::get('regno'); $vechicles->make = Input::get('make'); $vechicles->model = Input::get('model'); $vechicles->engine_no = Input::get('engine_no'); $vechicles->chachess_no = Input::get('chachess_no'); $vechicles->cc = Input::get('cc'); $vechicles->body_type = Input::get('body_type'); $vechicles->colour = Input::get('colour'); $vechicles->date = Input::get('date'); $vechicles->insurance = Input::get('insurance'); $vechicles->insurance_percentage = Input::get('insurance_percentage'); $vechicles->meter = Input::get('meter'); $vechicles->finance_by = Input::get('finance_by'); $vechicles->period = Input::get('period'); $vechicles->account = Input::get('account'); $vechicles->finance_percentage = Input::get('finance_percentage'); $vechicles->finance_amount = Input::get('finance_amount'); $vechicles->doc = Input::get('doc'); $vechicles->other = Input::get('other'); $vechicles->installment = Input::get('installment'); $vechicles->sold_amount = Input::get('sold_amount'); $vechicles->sold_date = Input::get('sold_date'); if($vechicles->save()){ return Redirect::to('setup/vechicles')->with('message','vechicles Edit'); } else { return Redirect::to('setup/vechicles/edit'.$id)->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } public function getType() { foreach (Maincategory::all() as $type) { $typelist[$type->id] = $type->name; } $url = "setup/vechicles/type"; return View::make('layouts.forms.setup.fpa.type') ->with('typelist',$typelist) ->with('type',null) ->with('form', 'Vechicles') ->with('parent', '12') ->with('url', $url) ->with('name',null) ->with('id',null); } public function postType() { $validation = Type::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/vechicles/type')->withErrors($validation)->withInput(); } else { $type = new Type; $type->maincategory_id = Input::get('maincategory'); $type->name = Input::get('name'); $type->section = 6; if($type->save()){ return Redirect::to('setup/vechicles/')->with('message','Type Added'); } else { return Redirect::to('setup/vechicles/type')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } public function getNature() { foreach (Maincategory::all() as $type) { $typelist[$type->id] = $type->name; // dd ($type); } $url = "setup/vechicles/nature"; return View::make('layouts.forms.setup.fpa.nature') ->with('typelist',$typelist) ->with('url', $url) ->with('parent', '4') ->with('form', 'Finished Product Attributes') ->with('type',null) ->with('name',null) ->with('id',null); } /** * Store a newly created resource in storage. * Request POST * @return Response */ public function postNature() { $validation = Nature::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/vechicles/nature/')->withErrors($validation)->withInput(); } else { $nature = new Nature; $nature->maincategory_id = Input::get('maincategory'); $nature->name = Input::get('name'); $nature->section = 6; if($nature->save()){ return Redirect::to('setup/vechicles/')->with('message','Nature Added'); } else { return Redirect::to('setup/vechicles/nature')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } }<file_sep>/core/app/controllers/Setup/fpa/NatureController.php <?php namespace Setup\fpa; use BaseController, Input, View, Redirect, Validator, Maincategory, Nature, Expensetype; class NatureController extends BaseController { /** * Display a listing of the resource. * Request GET * @return Response */ public function index() { $nature=Nature::with('maincategory.types')->where('section', '=', 1)->get(); return View::make('layouts.view.setup.fpa.nature') ->with('nature',$nature); } /** * Show the form for creating a new resource. * Request GET * @return Response */ public function create() { foreach (Maincategory::all() as $type) { $typelist[$type->id] = $type->name; // dd ($type); } $url = "setup/fpa/nature/"; return View::make('layouts.forms.setup.fpa.nature') ->with('typelist',$typelist) ->with('url', $url) ->with('parent', '2') ->with('form', 'Finished Product Attributes') ->with('type',null) ->with('name',null) ->with('id',null); } /** * Store a newly created resource in storage. * Request POST * @return Response */ public function store() { $validation = Nature::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/fpa/nature/create')->withErrors($validation)->withInput(); } else { $nature = new Nature; $nature->maincategory_id = Input::get('maincategory'); $nature->name = Input::get('name'); $type->section = 1; if($nature->save()){ return Redirect::to('setup/fpa/nature/')->with('message','Nature Added'); } else { return Redirect::to('setup/fpa/nature/create')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } /** * Display the specified resource. * Request GET * @param int $id * @return Response */ public function show($id) { } /** * Show the form for editing the specified resource. * Request GET * @param int $id * @return Response */ public function edit($id) { foreach (Maincategory::all() as $type) { $typelist[$type->id] = $type->name; } $alltype = Nature::find($id); //dd($alltype->name); $type = $alltype->type; $name = $alltype->name; $url = "setup/fpa/nature/".$id; return View::make('layouts.forms.setup.fpa.nature') ->with('editform', 'Edit Nature') ->with('url', $url) ->with('id', $id) ->with('parent', '2') ->with('form', 'Finished Product Attributes') ->with('typelist', $typelist) ->with('type', $type) ->with('name', $name); } /** * Update the specified resource in storage. * Request PUT * @param int $id * @return Response */ public function update($id) { $validation = Nature::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/fpa/nature/edit/'.$id)->withErrors($validation)->withInput(); } else { $nature = Nature::find($id); $nature->maincategory_id = Input::get('maincategory'); $nature->name = Input::get('name'); if($nature->save()){ return Redirect::to('setup/fpa/nature')->with('message','Nature Edit'); } else { return Redirect::to('setup/fpa/nature/edit'.$id)->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } /** * Remove the specified resource from storage. * Request Delete * @param int $id * @return Response */ public function destroy($id) { // } }<file_sep>/core/app/models/Types.php <?php class Types extends Eloquent { protected $table = 'types'; public $timestamps = false; public function maincategory() { return $this->hasMany('Maincategory'); } }<file_sep>/core/app/controllers/Setup/TransportController.php <?php namespace Setup; use BaseController, Input, View, Redirect, Validator, Types,Transport,System, Address; class TransportController extends BaseController { /** * Display a listing of the resource. * Request GET * @return Response */ public function index() { $tcompany=Transport::with('system')->get(); return View::make('layouts.view.setup.transport') ->with('tcompany',$tcompany); } /** * Show the form for creating a new resource. * Request GET * @return Response */ public function create() { foreach (System::all() as $type) { $systemlist[$type->id] = $type->name; } return View::make('layouts.forms.setup.transport') ->with('id', null) ->with('name', null) ->with('system_id', null) ->with('systemlist',$systemlist) ->with('address', null) ->with('number', null); } /** * Store a newly created resource in storage. * Request POST * @return Response */ public function store() { $validation = Transport::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/transport/create')->withErrors($validation)->withInput(); }else { $transport = new Transport; $transport->system_id = Input::get('systemtype'); $transport->companyname = Input::get('name'); $transport->number = Input::get('number'); if($transport->save()){ $address = new Address; $address->transport_id = $transport->id; $address->location = Input::get('location'); $address->street = Input::get('street'); $address->nearby = Input::get('nearby'); $address->city = Input::get('city'); $address->zip = Input::get('zip'); $address->district = Input::get('district'); $address->zone = Input::get('zone'); $address->division = Input::get('division'); $address->state = Input::get('state'); $address->country = Input::get('country'); if($address->save()){ return Redirect::to('setup/transport')->with('message','Transport Comapny Added'); } else { return Redirect::to('setup/transport/create')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } else { return Redirect::to('setup/transport/create')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } /** * Display the specified resource. * Request GET * @param int $id * @return Response */ public function show($id) { } /** * Show the form for editing the specified resource. * Request GET * @param int $id * @return Response */ public function edit($id) { foreach (System::all() as $type) { $systemlist[$type->id] = $type->name; } $transport=Transport::find($id); $name = $transport->companyname; $system_id = $transport->system_id; $number = $transport->number; $address = Address::where('transport_id', '=', $id)->first(); return View::make('layouts.forms.setup.transport') ->with('editform', 'Edit Transport COmpany') ->with('id', $id) ->with('name', $name) ->with('system_id', $system_id) ->with('number', $number) ->with('address', $address) ->with('systemlist', $systemlist); } /** * Update the specified resource in storage. * Request PUT * @param int $id * @return Response */ public function update($id) { $validation = Transport::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/transport/'.$id.'/edit')->withErrors($validation)->withInput(); }else { $transport = Transport::find($id); $transport->system_id = Input::get('systemtype'); $transport->companyname = Input::get('name'); $transport->number = Input::get('number'); $address = Address::where('transport_id' , '=' , $id)->first(); if(empty($address->transport_id)){ $address = new Address; $address->transport_id = $id; } $address->location = Input::get('location'); $address->street = Input::get('street'); $address->nearby = Input::get('nearby'); $address->city = Input::get('city'); $address->zip = Input::get('zip'); $address->district = Input::get('district'); $address->zone = Input::get('zone'); $address->division = Input::get('division'); $address->state = Input::get('state'); $address->country = Input::get('country'); if($transport->save() && $address->save()){ return Redirect::to('setup/transport')->with('message','Transport Comapny Edit'); } else { return Redirect::to('setup/transport/create')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } /** * Remove the specified resource from storage. * Request Delete * @param int $id * @return Response */ public function destroy($id) { // } }<file_sep>/core/app/models/Vechicles.php <?php class Vechicles extends Eloquent { protected $table = 'vechicles'; public $timestamps = false; public static $rules = array( 'carname' => 'required', 'name' => 'required' ); public static function validate($data){ return Validator::make($data, static::$rules); } public function type() { return $this->belongsTo('Type'); } public function nature() { return $this->belongsTo('Nature'); } }<file_sep>/core/app/controllers/Setup/StoreController.php <?php namespace Setup; use BaseController, Input, View, Redirect, Validator, Types,Type,Store, Storetype,Nature,Address,Maincategory; class StoreController extends BaseController { public function getIndex() { $store=Store::with('Type', 'Nature' , 'Basicinfo')->get(); //dd($store); return View::make('layouts.view.setup.store') ->with('store',$store); } public function getCreate() { foreach (Storetype::all() as $type) { $storelist[$type->id] = $type->name; } foreach (Type::where('section', '=', 4)->get() as $type) { $typelist[$type->id] = $type->name; } foreach (Nature::where('section', '=', 4)->get() as $type) { $naturelist[$type->id] = $type->name; } return View::make('layouts.forms.setup.store') ->with('storelist', $storelist) ->with('typelist', $typelist) ->with('naturelist', $naturelist) ->with('storeid', null) ->with('typeid', null) ->with('natureid', null) ->with('name', null) ->with('dname', null) ->with('email', null) ->with('empid', null) ->with('empname', null) ->with('address', null); } public function postIndex() { $validation = Store::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/store/create')->withErrors($validation)->withInput(); } else { $store = new Store; $store->storetype_id = Input::get('storetype'); $store->type_id = Input::get('type'); $store->nature_id = Input::get('naturetype'); $store->basicinfo_id = Input::get('empid'); $store->name = Input::get('name'); $store->dname = Input::get('displayname'); $store->email = Input::get('email'); if($store->save()){ $address = new Address; $address->store = $store->id; $address->location = Input::get('location'); $address->street = Input::get('street'); $address->nearby = Input::get('nearby'); $address->city = Input::get('city'); $address->zip = Input::get('zip'); $address->district = Input::get('district'); $address->zone = Input::get('zone'); $address->division = Input::get('division'); $address->state = Input::get('state'); $address->country = Input::get('country'); if($address->save()){ return Redirect::to('setup/store')->with('message','Store Added'); } else { return Redirect::to('setup/store/create')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } else { return Redirect::to('setup/store/create')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } public function getEdit($id) { foreach (Storetype::all() as $type) { $storelist[$type->id] = $type->name; } foreach (Type::where('section', '=', 4)->get() as $type) { $typelist[$type->id] = $type->name; } foreach (Nature::where('section', '=', 4)->get() as $type) { $naturelist[$type->id] = $type->name; } $store=Store::find($id); $address = Address::where('store_id', '=', $id)->first(); return View::make('layouts.forms.setup.store') ->with('editform', 'Edit Store') ->with('id', $id) ->with('storelist', $storelist) ->with('typelist', $typelist) ->with('naturelist', $naturelist) ->with('storeid', $store->storetype_id) ->with('typeid', $store->type_id) ->with('natureid', $store->nature_id) ->with('name', $store->name) ->with('dname', $store->dname) ->with('email', $store->email) ->with('empid', $store->basicinfo_id) ->with('empname', $store->basicinfo->firstname) ->with('address', $address); } public function putEdit($id) { $validation = Store::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/store/edit/'.$id)->withErrors($validation)->withInput(); } else { $store = Store::find($id); $store->storetype_id = Input::get('storetype'); $store->type_id = Input::get('type'); $store->nature_id = Input::get('naturetype'); $store->basicinfo_id = Input::get('empid'); $store->name = Input::get('name'); $store->dname = Input::get('displayname'); $store->email = Input::get('email'); $address = Address::where('store_id' , '=' , $id)->first(); if(empty($address->store_id)){ $address = new Address; $address->store_id = $id; } $address->location = Input::get('location'); $address->street = Input::get('street'); $address->nearby = Input::get('nearby'); $address->city = Input::get('city'); $address->zip = Input::get('zip'); $address->district = Input::get('district'); $address->zone = Input::get('zone'); $address->division = Input::get('division'); $address->state = Input::get('state'); $address->country = Input::get('country'); if($store->save() && $address->save()){ return Redirect::to('setup/store/')->with('message','Store Edit'); } else { return Redirect::to('setup/store/edit/'.$id)->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } public function getType() { foreach (Maincategory::all() as $type) { $typelist[$type->id] = $type->name; } $url = "setup/store/type"; return View::make('layouts.forms.setup.fpa.type') ->with('typelist',$typelist) ->with('type',null) ->with('form', 'Store') ->with('parent', '9') ->with('url', $url) ->with('name',null) ->with('id',null); } public function postType() { $validation = Type::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/store/type')->withErrors($validation)->withInput(); } else { $type = new Type; $type->maincategory_id = Input::get('maincategory'); $type->name = Input::get('name'); $type->section = 4; if($type->save()){ return Redirect::to('setup/store/')->with('message','Type Added'); } else { return Redirect::to('setup/store/type')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } public function getNature() { foreach (Maincategory::all() as $type) { $typelist[$type->id] = $type->name; // dd ($type); } $url = "setup/store/nature"; return View::make('layouts.forms.setup.fpa.nature') ->with('typelist',$typelist) ->with('url', $url) ->with('parent', '4') ->with('form', 'Finished Product Attributes') ->with('type',null) ->with('name',null) ->with('id',null); } /** * Store a newly created resource in storage. * Request POST * @return Response */ public function postNature() { $validation = Nature::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/store/nature/')->withErrors($validation)->withInput(); } else { $nature = new Nature; $nature->maincategory_id = Input::get('maincategory'); $nature->name = Input::get('name'); $nature->section = 4; if($nature->save()){ return Redirect::to('setup/store/')->with('message','Nature Added'); } else { return Redirect::to('setup/store/nature')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } }<file_sep>/core/app/controllers/AjaxController.php <?php class AjaxController extends BaseController { public function getFactory() { if (Input::has('type') && Input::has('term')) { $type = Input::get('type'); $term = Input::get('term'); $result = array(); $data = SETUP::where('name', 'LIKE', '%' . $term . '%') ->where('system_id','=', $type) ->take(10)->get(); foreach ($data as $value) { $result[] = array('name' =>$value->name,'id' => $value->id); } echo json_encode($result); } } public function getFpa() { if (Input::has('type')) { $type = Input::get('type'); $result = array(); $category = Category::where('maincategory_id', '=', $type)->get(); foreach ($category as $value) { $result['1'][] = array('name' =>$value->name,'id' => $value->id); } $classes = Classes::where('maincategory_id', '=', $type)->get(); foreach ($classes as $value) { $result['2'][] = array('name' =>$value->name,'id' => $value->id); } $foume = Foume::where('maincategory_id', '=', $type)->get(); foreach ($foume as $value) { $result['3'][] = array('name' =>$value->name,'id' => $value->id); } $grade = Grade::where('maincategory_id', '=', $type)->get(); foreach ($grade as $value) { $result['4'][] = array('name' =>$value->name,'id' => $value->id); } $group = Group::where('maincategory_id', '=', $type)->get(); foreach ($group as $value) { $result['5'][] = array('name' =>$value->name,'id' => $value->id); } $nature = Nature::where('maincategory_id', '=', $type)->get(); foreach ($nature as $value) { $result['6'][] = array('name' =>$value->name,'id' => $value->id); } $type = Type::where('maincategory_id', '=', $type)->get(); foreach ($type as $value) { $result['7'][] = array('name' =>$value->name,'id' => $value->id); } } echo json_encode($result); } public function getEmployee() { if(Input::has('name')){ $name = Input::get('name'); $data = Basicinfo::where('firstname', 'LIKE', '%' . $name . '%') ->orWhere('middlename', 'LIKE', '%' . $name . '%') ->orWhere('lastname', 'LIKE', '%' . $name . '%') ->take(10)->get(); foreach ($data as $value) { $fullname = $value->firstname." ".$value->middlename." ".$value->lastname; $result[] = array('name' => $fullname,'id' => $value->id); } echo json_encode($result); } } public function getDriver() { if(Input::has('name')){ $name = Input::get('name'); $data = Driver::where('name', 'LIKE', '%' . $name . '%')->take(10)->get(); } foreach ($data as $value) { $result[] = array('name' =>$value->name,'id' => $value->id); } echo json_encode($result); } public function getTransport() { if(Input::has('name')){ $name = Input::get('name'); $data = Transport::where('companyname', 'LIKE', '%' . $name . '%')->take(10)->get(); } foreach ($data as $value) { $result[] = array('name' =>$value->companyname,'id' => $value->id); } echo json_encode($result); } public function getProduct() { if(Input::has('name')){ $name = Input::get('name'); $data = Product::where('item', 'LIKE', '%' . $name . '%') ->where('active', '=', 1) ->take(10)->get(); } foreach ($data as $value) { $result[] = array('name' =>$value->item,'id' => $value->id); } echo json_encode($result); } }<file_sep>/core/app/models/Setup.php <?php class Setup extends Eloquent { protected $table = 'setup'; public $timestamps = false; public function type() { return $this->belongsTo('Type'); } public function nature() { return $this->belongsTo('Nature'); } public function system() { return $this->belongsTo('System'); } public function product() { return $this->hasMany('Product'); } }<file_sep>/core/app/controllers/Setup/ExpenseGroupController.php <?php namespace Setup; use BaseController, Input, View, Redirect, Validator, Types,ExpenseGroup; class ExpenseGroupController extends BaseController { /** * Display a listing of the resource. * Request GET * @return Response */ public function index() { $expgroup=ExpenseGroup::all(); return View::make('layouts.view.setup.expensegroup') ->with('expgroup',$expgroup); } /** * Show the form for creating a new resource. * Request GET * @return Response */ public function create() { return View::make('layouts.forms.setup.expensegroup') ->with('id', null) ->with('newexpense', null) ->with('remarks', null); } /** * Store a newly created resource in storage. * Request POST * @return Response */ public function store() { $validation = ExpenseGroup::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/expensegroup/create')->withErrors($validation)->withInput(); }else { $expensegroup = new ExpenseGroup; $expensegroup->newexpense = Input::get('newexpense'); $expensegroup->remarks = Input::get('remarks'); if($expensegroup->save()){ return Redirect::to('setup/expensegroup')->with('message','Expense Group Added'); } else { return Redirect::to('setup/expensegroup/create')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } /** * Display the specified resource. * Request GET * @param int $id * @return Response */ public function show($id) { } /** * Show the form for editing the specified resource. * Request GET * @param int $id * @return Response */ public function edit($id) { $expgroup=ExpenseGroup::find($id); $newexpense = $expgroup->newexpense; $remarks = $expgroup->remarks; return View::make('layouts.forms.setup.expensegroup') ->with('editform', 'Edit Expense Group') ->with('id', $id) ->with('newexpense', $newexpense) ->with('remarks', $remarks); } /** * Update the specified resource in storage. * Request PUT * @param int $id * @return Response */ public function update($id) { $validation = ExpenseGroup::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/expensegroup/'.$id.'/edit')->withErrors($validation)->withInput(); }else { $expensegroup = ExpenseGroup::find($id); $expensegroup->newexpense = Input::get('newexpense'); $expensegroup->remarks = Input::get('remarks'); if($expensegroup->save()){ return Redirect::to('setup/expensegroup')->with('message','Expense Group Edit'); } else { return Redirect::to('setup/expensegroup/'.$id.'/edit')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } /** * Remove the specified resource from storage. * Request Delete * @param int $id * @return Response */ public function destroy($id) { // } }<file_sep>/core/app/controllers/Setup/SalarytypeController.php <?php namespace Setup; use BaseController, Input, View, Redirect, Expensetype, Validator,Salarytype; class SalarytypeController extends BaseController { /** * Display a listing of the resource. * Request GET * @return Response */ public function index() { $salarytype = Salarytype::all(); return View::make('layouts.view.setup.salarytype') ->with('salarytype', $salarytype); } /** * Show the form for creating a new resource. * Request GET * @return Response */ public function create() { return View::make('layouts.forms.setup.salarytype') ->with('salarytype', null); } /** * Store a newly created resource in storage. * Request POST * @return Response */ public function store() { /* $validation = Expensetype::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/salarytype/create')->withErrors($validation)->withInput(); } else {*/ $salarytype = new Salarytype; $salarytype->salarytype = Input::get('salarytype'); if($salarytype->save()){ return Redirect::to('setup/salarytype')->with('message','Salary Type Added'); } else { return Redirect::to('setup/salarytype/create')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } //} } /** * Display the specified resource. * Request GET * @param int $id * @return Response */ public function show($id) { } /** * Show the form for editing the specified resource. * Request GET * @param int $id * @return Response */ public function edit($id) { $salarytype = Salarytype::find($id); return View::make('layouts.forms.setup.salarytype') ->with('editform', 'Edit salarytype') ->with('id', $salarytype->id) ->with('salarytype', $salarytype->salarytype); } /** * Update the specified resource in storage. * Request PUT * @param int $id * @return Response */ public function update($id) { /* $validation = Expensetype::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/expense/create/'.$id.'/edit')->withErrors($validation)->withInput(); } else {*/ $salarytype = Salarytype::find($id); $salarytype->salarytype = Input::get('salarytype'); if($salarytype->save()){ return Redirect::to('setup/salarytype')->with('message','Salary Type Edit'); } else { return Redirect::to('setup/salarytype/create/'.$id.'/edit')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } //} } /** * Remove the specified resource from storage. * Request Delete * @param int $id * @return Response */ public function destroy($id) { // } }<file_sep>/core/app/controllers/Setup/fpa/ClassController.php <?php namespace Setup\fpa; use BaseController, Input, View, Redirect, Validator, Maincategory, Classes, Expensetype; class ClassController extends BaseController { /** * Display a listing of the resource. * Request GET * @return Response */ public function index() { $class = Classes::with('maincategory.types')->get(); return View::make('layouts.view.setup.fpa.class') ->with('class',$class); } /** * Show the form for creating a new resource. * Request GET * @return Response */ public function create() { foreach (Maincategory::all() as $type) { $typelist[$type->id] = $type->name; // dd ($type); } return View::make('layouts.forms.setup.fpa.class') ->with('typelist',$typelist) ->with('type',null) ->with('name',null) ->with('id',null); } /** * Store a newly created resource in storage. * Request POST * @return Response */ public function store() { $validation = Classes::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/fpa/class/create')->withErrors($validation)->withInput(); } else { $class = new Classes; $class->maincategory_id = Input::get('maincategory'); $class->name = Input::get('name'); if($class->save()){ return Redirect::to('setup/fpa/class/')->with('message','Class Added'); } else { return Redirect::to('setup/fpa/class/create')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } /** * Display the specified resource. * Request GET * @param int $id * @return Response */ public function show($id) { } /** * Show the form for editing the specified resource. * Request GET * @param int $id * @return Response */ public function edit($id) { foreach (Maincategory::all() as $type) { $typelist[$type->id] = $type->name; } $alltype = Classes::find($id); //dd($alltype->name); $type = $alltype->type; $name = $alltype->name; return View::make('layouts.forms.setup.fpa.class') ->with('editform', 'Edit Class') ->with('id', $id) ->with('typelist', $typelist) ->with('type', $type) ->with('name', $name); } /** * Update the specified resource in storage. * Request PUT * @param int $id * @return Response */ public function update($id) { $validation = Classes::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/fpa/class/'.$id.'/edit')->withErrors($validation)->withInput(); } else { $class = Classes::find($id); $class->maincategory_id = Input::get('maincategory'); $class->name = Input::get('name'); if($class->save()){ return Redirect::to('setup/fpa/class')->with('message','Class Edit'); } else { return Redirect::to('setup/fpa/class/'.$id.'/edit')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } /** * Remove the specified resource from storage. * Request Delete * @param int $id * @return Response */ public function destroy($id) { // } }<file_sep>/core/app/models/Store.php <?php class Store extends Eloquent { protected $table = 'store'; public $timestamps = false; public static $rules = array( 'storetype' => 'required', 'name' => 'required|min:2|max:200' ); public static function validate($data){ return Validator::make($data, static::$rules); } public function nature() { return $this->belongsTo('Nature'); } public function storetype() { return $this->belongsTo('Storetype'); } public function type() { return $this->belongsTo('Type'); } public function basicinfo() { return $this->belongsTo('Basicinfo'); } }<file_sep>/core/app/controllers/Setup/RecipeController.php <?php namespace Setup; use BaseController, Input, View, Redirect, Validator, Types,Recipe, Maincategory, Type, Nature; class RecipeController extends BaseController { /** * Display a listing of the resource. * Request GET * @return Response */ public function getIndex() { $recipes=Recipe::all(); //dd($recipe); return View::make('layouts.view.setup.recipe') ->with('recipes',$recipes); } /** * Show the form for creating a new resource. * Request GET * @return Response */ public function getCreate() { foreach (Type::where('section', '=', 5)->get() as $type) { $typelist[$type->id] = $type->name; } foreach (Nature::where('section', '=', 5)->get() as $type) { $naturelist[$type->id] = $type->name; } return View::make('layouts.forms.setup.recipe') ->with('typelist',$typelist) ->with('naturelist',$naturelist) ->with('type', null) ->with('nature', null); } /** * Store a newly created resource in storage. * Request POST * @return Response */ public function postIndex() { $validation = Recipe::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/recipe/create')->withErrors($validation)->withInput(); }else { $recipe = new Recipe; $recipe->createFor = Input::get('createfor'); $recipe->cnic = Input::get('cnicnumber'); $recipe->name = Input::get('name'); $recipe->contactnumber = Input::get('contactnumber'); if($recipe->save()){ return Redirect::to('setup/recipe')->with('message','recipe Added'); } else { return Redirect::to('setup/recipe/create')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } public function getEdit($id) { foreach (Type::where('section', '=', 5)->get() as $type) { $typelist[$type->id] = $type->name; } foreach (Nature::where('section', '=', 5)->get() as $type) { $naturelist[$type->id] = $type->name; } $recipe=Recipe::find($id); $name = $recipe->name; $cnic = $recipe->cnic; $contactnumber = $recipe->contactnumber; return View::make('layouts.forms.setup.recipe') ->with('typelist',$typelist) ->with('naturelist',$naturelist) ->with('type',$type) ->with('nature',$nature) ->with('editform', 'Edit recipe') ->with('id', $id) ->with('cnic', $cnic) ->with('name', $name) ->with('contactnumber', $contactnumber); } /** * Update the specified resource in storage. * Request PUT * @param int $id * @return Response */ public function putEdit($id) { $validation = Recipe::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/recipe/edit'.$id)->withErrors($validation)->withInput(); }else { $recipe = Recipe::find($id); $recipe->createFor = Input::get('createfor'); $recipe->cnic = Input::get('cnicnumber'); $recipe->name = Input::get('name'); $recipe->contactnumber = Input::get('contactnumber'); if($recipe->save()){ return Redirect::to('setup/recipe')->with('message','recipe Edit'); } else { return Redirect::to('setup/recipe/edit/'.$id)->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } public function getType() { foreach (Maincategory::all() as $type) { $typelist[$type->id] = $type->name; } $url = "setup/recipe/type"; return View::make('layouts.forms.setup.fpa.type') ->with('typelist',$typelist) ->with('type',null) ->with('form', 'Store') ->with('parent', '9') ->with('url', $url) ->with('name',null) ->with('id',null); } public function postType() { $validation = Type::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/recipe/type')->withErrors($validation)->withInput(); } else { $type = new Type; $type->maincategory_id = Input::get('maincategory'); $type->name = Input::get('name'); $type->section = 5; if($type->save()){ return Redirect::to('setup/recipe/')->with('message','Type Added'); } else { return Redirect::to('setup/recipe/type')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } public function getNature() { foreach (Maincategory::all() as $type) { $typelist[$type->id] = $type->name; // dd ($type); } $url = "setup/recipe/nature"; return View::make('layouts.forms.setup.fpa.nature') ->with('typelist',$typelist) ->with('url', $url) ->with('parent', '4') ->with('form', 'Finished Product Attributes') ->with('type',null) ->with('name',null) ->with('id',null); } /** * Store a newly created resource in storage. * Request POST * @return Response */ public function postNature() { $validation = Nature::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/recipe/nature/')->withErrors($validation)->withInput(); } else { $nature = new Nature; $nature->maincategory_id = Input::get('maincategory'); $nature->name = Input::get('name'); $nature->section = 5; if($nature->save()){ return Redirect::to('setup/recipe/')->with('message','Nature Added'); } else { return Redirect::to('setup/recipe/nature')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } }<file_sep>/core/app/models/Factoryc.php <?php class Factoryc extends Eloquent { protected $table = 'factoryc'; public $timestamps = false; public function types() { return $this->belongsTo('Types'); } }<file_sep>/core/app/controllers/LoginController.php <?php class LoginController extends BaseController { /** * Setup the layout used by the controller. * * @return void */ protected function auth() { try { $credentials = array( 'email' => Input::get('username'), 'password' => Input::get('password'), ); $user = Sentry::authenticate($credentials, true); if($user){ return Redirect::to('/home'); } } catch (Cartalyst\Sentry\Users\LoginRequiredException $e) { return Redirect::to('/login')->with('message','Username is required.'); } catch (Cartalyst\Sentry\Users\PasswordRequiredException $e) { return Redirect::to('/login')->with('message','Password is required.'); } catch (Cartalyst\Sentry\Users\WrongPasswordException $e) { return Redirect::to('/login')->with('message','Wrong Username or Password.'); } catch (Cartalyst\Sentry\Users\UserNotFoundException $e) { return Redirect::to('/login')->with('message','Wrong Username or Password.'); } catch (Cartalyst\Sentry\Users\UserNotActivatedException $e) { return Redirect::to('/login')->with('message','User not Activated.'); } // The following is only required if throttle is enabled catch (Cartalyst\Sentry\Throttling\UserSuspendedException $e) { return Redirect::to('/login')->with('message','User is suspended.'); } catch (Cartalyst\Sentry\Throttling\UserBannedException $e) { return Redirect::to('/login')->with('message','User is banned.'); } } protected function logout(){ Sentry::logout(); return Redirect::to('/login')->with('signoutmsg','You have been Sign out successfully!.'); } }<file_sep>/core/app/models/Nature.php <?php class Nature extends Eloquent { protected $table = 'nature'; public $timestamps = false; public static $rules = array( 'maincategory' => 'required|integer', 'name' => 'required|min:2|max:200' ); public static function validate($data){ return Validator::make($data, static::$rules); } public function maincategory() { return $this->belongsTo('Maincategory'); } public function store() { return $this->hasMany('Store'); } public function setup() { return $this->hasMany('Setup'); } public function product() { return $this->hasMany('Product'); } public function vechicles() { return $this->hasMany('Vechicles'); } }<file_sep>/core/app/models/Basicinfo.php <?php class Basicinfo extends Eloquent { protected $table = 'basicinfo'; public $timestamps = false; public static $rules = array( 'firstname' => 'required|min:2|max:200', 'middlename' => 'min:2|max:200', 'lastname' => 'required|min:2|max:200' ); public static function validate($data){ return Validator::make($data, static::$rules); } public function store() { return $this->belongsTo('Store'); } public function address() { return $this->hasOne('Address'); } }<file_sep>/core/app/models/Storetype.php <?php class Storetype extends Eloquent { protected $table = 'storetype'; public $timestamps = false; public function store(){ return $this->hasmany('Store'); } }<file_sep>/core/app/controllers/Setup/fpa/GradeController.php <?php namespace Setup\fpa; use BaseController, Input, View, Redirect, Validator, Maincategory, Grade, Expensetype; class GradeController extends BaseController { /** * Display a listing of the resource. * Request GET * @return Response */ public function index() { $grade=Grade::with('maincategory.types')->get(); return View::make('layouts.view.setup.fpa.grade') ->with('grade',$grade); } /** * Show the form for creating a new resource. * Request GET * @return Response */ public function create() { foreach (Maincategory::all() as $type) { $typelist[$type->id] = $type->name; // dd ($type); } return View::make('layouts.forms.setup.fpa.grade') ->with('typelist',$typelist) ->with('type',null) ->with('name',null) ->with('id',null); } /** * Store a newly created resource in storage. * Request POST * @return Response */ public function store() { $validation = Grade::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/fpa/grade/create')->withErrors($validation)->withInput(); } else { $grade = new Grade; $grade->maincategory_id = Input::get('maincategory'); $grade->name = Input::get('name'); if($grade->save()){ return Redirect::to('setup/fpa/grade/')->with('message','Grade Added'); } else { return Redirect::to('setup/fpa/grade/create')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } /** * Display the specified resource. * Request GET * @param int $id * @return Response */ public function show($id) { } /** * Show the form for editing the specified resource. * Request GET * @param int $id * @return Response */ public function edit($id) { foreach (Maincategory::all() as $type) { $typelist[$type->id] = $type->name; } $alltype = Grade::find($id); //dd($alltype->name); $type = $alltype->type; $name = $alltype->name; return View::make('layouts.forms.setup.fpa.grade') ->with('editform', 'Edit Grade') ->with('id', $id) ->with('typelist', $typelist) ->with('type', $type) ->with('name', $name); } /** * Update the specified resource in storage. * Request PUT * @param int $id * @return Response */ public function update($id) { $validation = Grade::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/fpa/grade/'.$id.'/edit')->withErrors($validation)->withInput(); } else { $grade = Grade::find($id); $grade->maincategory_id = Input::get('maincategory'); $grade->name = Input::get('name'); if($grade->save()){ return Redirect::to('setup/fpa/grade')->with('message','Grade Edit'); } else { return Redirect::to('setup/fpa/grade/'.$id.'/edit')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } /** * Remove the specified resource from storage. * Request Delete * @param int $id * @return Response */ public function destroy($id) { // } }<file_sep>/core/app/models/Education.php <?php class Education extends Eloquent { protected $table = 'education'; public static $timestamps = false; }<file_sep>/core/app/controllers/View/EmployeeController.php <?php namespace View; use BaseController, Input, File, View, Basicinfo, Previousjob, Redirect, Personalinfo, Empbank, Qualification, Address, Officedetail; class EmployeeController extends BaseController { public function getShow($id) { $basicinfo = Basicinfo::find($id); if($basicinfo->pic){ $picurl = 'uploads/employee/pic/'.$basicinfo->pic; } else { $picurl = 'assets/img/profile/default.jpg'; } return View::make('layouts.view.profile.index') ->with('id', $id) ->with('picurl', $picurl) ->with('basicinfo', $basicinfo); } public function postUpload($id) { $message = null; $basicinfo = Basicinfo::find($id); if (Input::hasFile('photo')) { $file = Input::file('photo'); $destinationPath = 'uploads/employee/pic/'; $fileName = $id.date('_Y_m_d_H_i_s').'.'.$file->getClientOriginalExtension(); if(!empty($basicinfo->pic)){ File::delete('uploads/employee/pic/'.$basicinfo->pic); } $upload_success = Input::file('photo')->move($destinationPath, $fileName); if($upload_success){ $basicinfo->pic = $fileName; if($basicinfo->save()){ $message = 'File Upload'; } } } return View::make('layouts.view.profile.index') ->with('id', $id) ->with('message', $message) ->with('basicinfo', $basicinfo); } public function getDetails($id) { $basicinfo = Basicinfo::find($id); $personalinfo = Personalinfo::find($id); $bank = Empbank::find($id); $address = Address::where('basicinfo_id', '=', $id)->first(); return View::make('layouts.view.profile.personalinfo') ->with('id', $id) ->with('basicinfo', $basicinfo) ->with('personalinfo', $personalinfo) ->with('bank', $bank) ->with('address', $address); } public function postDetails($id) { $validation = Personalinfo::validate(Input::get()); if($validation->fails()){ return Redirect::to('view/employee/details/'.$id)->withErrors($validation)->withInput(); } else { $personalinfo = new Personalinfo; $personalinfo->empid = $id; $personalinfo->father = Input::get('father'); $personalinfo->cnic = Input::get('cnic'); $personalinfo->religion = Input::get('religion'); $personalinfo->careoff = Input::get('careoff'); if($personalinfo->save()){ return Redirect::to('view/employee/details/'.$id)->with('message','Personal Info Added'); } else { return Redirect::to('view/employee/details/'.$id)->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } public function putDetails($id) { $validation = Personalinfo::validate(Input::get()); if($validation->fails()){ return Redirect::to('view/employee/details/'.$id)->withErrors($validation)->withInput(); } else { $personalinfo = Personalinfo::find($id); $personalinfo->father = Input::get('father'); $personalinfo->cnic = Input::get('cnic'); $personalinfo->religion = Input::get('religion'); $personalinfo->careoff = Input::get('careoff'); if($personalinfo->save()){ return Redirect::to('view/employee/details/'.$id)->with('message','Personal Info Edit'); } else { return Redirect::to('view/employee/details/'.$id)->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } public function postBank($id) { $validation = Empbank::validate(Input::get()); if($validation->fails()){ return Redirect::to('view/employee/details/'.$id)->withErrors($validation)->withInput(); } else { $bankinfo = new Empbank; $bankinfo->empid = $id; $bankinfo->name = Input::get('name'); $bankinfo->title = Input::get('title'); $bankinfo->phone = Input::get('phone'); $bankinfo->address = Input::get('address'); $bankinfo->branch = Input::get('branch'); if($bankinfo->save()){ return Redirect::to('view/employee/details/'.$id)->with('message','Bank Info Added'); } else { return Redirect::to('view/employee/details/'.$id)->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } public function putBank($id) { $validation = Empbank::validate(Input::get()); if($validation->fails()){ return Redirect::to('view/employee/details/'.$id)->withErrors($validation)->withInput(); } else { $bankinfo = Empbank::find($id); $bankinfo->name = Input::get('name'); $bankinfo->title = Input::get('title'); $bankinfo->phone = Input::get('phone'); $bankinfo->address = Input::get('address'); $bankinfo->branch = Input::get('branch'); if($bankinfo->save()){ return Redirect::to('view/employee/details/'.$id)->with('message','Bank Info Edit'); } else { return Redirect::to('view/employee/details/'.$id)->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } public function postAddress($id) { $validation = Address::validate(Input::get()); if($validation->fails()){ return Redirect::to('view/employee/details/'.$id)->withErrors($validation)->withInput(); } else { $address = new Address; $address->basicinfo_id = $id; $address->location = Input::get('location'); $address->street = Input::get('street'); $address->nearby = Input::get('nearby'); $address->city = Input::get('city'); $address->zip = Input::get('zip'); $address->district = Input::get('district'); $address->zone = Input::get('zone'); $address->division = Input::get('division'); $address->state = Input::get('state'); $address->country = Input::get('country'); if($address->save()){ return Redirect::to('view/employee/details/'.$id)->with('message','Address Detail Added'); } else { return Redirect::to('view/employee/details/'.$id)->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } public function putAddress($id) { $validation = Address::validate(Input::get()); if($validation->fails()){ return Redirect::to('view/employee/details/'.$id)->withErrors($validation)->withInput(); } else { $address = Address::where('basicinfo_id', '=', $id)->first(); $address->location = Input::get('location'); $address->street = Input::get('street'); $address->nearby = Input::get('nearby'); $address->city = Input::get('city'); $address->zip = Input::get('zip'); $address->district = Input::get('district'); $address->zone = Input::get('zone'); $address->division = Input::get('division'); $address->state = Input::get('state'); $address->country = Input::get('country'); if($address->save()){ return Redirect::to('view/employee/details/'.$id)->with('message','Address Detail Edit'); } else { return Redirect::to('view/employee/details/'.$id)->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } public function getQualification($id) { $basicinfo = Basicinfo::find($id); $qualification = Qualification::find($id); $previousjob = Previousjob::find($id); return View::make('layouts.view.profile.qualification') ->with('id', $id) ->with('basicinfo', $basicinfo) ->with('qualification', $qualification) ->with('previousjob', $previousjob); } public function postQualification($id) { $validation = Qualification::validate(Input::get()); if($validation->fails()){ return Redirect::to('view/employee/qualification/'.$id)->withErrors($validation)->withInput(); } else { $qualification = new Qualification; $qualification->empid = $id; $qualification->degree = Input::get('degree'); $qualification->institute = Input::get('institute'); $qualification->percentage = Input::get('percentage'); if($qualification->save()){ return Redirect::to('view/employee/qualification/'.$id)->with('qmessage','Qualification Added'); } else { return Redirect::to('view/employee/qualification/'.$id)->with('qemessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } public function putQualification($id) { $validation = Qualification::validate(Input::get()); if($validation->fails()){ return Redirect::to('view/employee/qualification/'.$id)->withErrors($validation)->withInput(); } else { $qualification = Qualification::find($id); $qualification->degree = Input::get('degree'); $qualification->institute = Input::get('institute'); $qualification->percentage = Input::get('percentage'); if($qualification->save()){ return Redirect::to('view/employee/qualification/'.$id)->with('qmessage','Qualification Edit'); } else { return Redirect::to('view/employee/qualification/'.$id)->with('qemessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } public function postExperience($id) { $validation = Previousjob::validate(Input::get()); if($validation->fails()){ return Redirect::to('view/employee/qualification/'.$id)->withErrors($validation)->withInput(); } else { $previousjob = new Previousjob; $previousjob->empid = $id; $previousjob->status = Input::get('status'); $previousjob->experience = Input::get('experience'); $previousjob->company = Input::get('company'); $previousjob->designation = Input::get('designation'); $previousjob->refrence = Input::get('refrence'); $previousjob->number = Input::get('number'); $previousjob->joindate = Input::get('joindate'); $previousjob->leavedate = Input::get('leavedate'); if($previousjob->save()){ return Redirect::to('view/employee/qualification/'.$id)->with('qmessage','Previousjob Added'); } else { return Redirect::to('view/employee/qualification/'.$id)->with('qemessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } public function putExperience($id) { $validation = Previousjob::validate(Input::get()); if($validation->fails()){ return Redirect::to('view/employee/qualification/'.$id)->withErrors($validation)->withInput(); } else { $previousjob = Previousjob::find($id); $previousjob->status = Input::get('status'); $previousjob->experience = Input::get('experience'); $previousjob->company = Input::get('company'); $previousjob->designation = Input::get('designation'); $previousjob->refrence = Input::get('refrence'); $previousjob->number = Input::get('number'); $previousjob->joindate = Input::get('joindate'); $previousjob->leavedate = Input::get('leavedate'); if($previousjob->save()){ return Redirect::to('view/employee/qualification/'.$id)->with('qmessage','Previous Job Edit'); } else { return Redirect::to('view/employee/qualification/'.$id)->with('qemessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } public function getOffice($id) { $basicinfo = Basicinfo::find($id); $officedetail = Officedetail::find($id); return View::make('layouts.view.profile.office') ->with('id', $id) ->with('basicinfo', $basicinfo) ->with('office', $officedetail); } public function postOffice($id) { $validation = Officedetail::validate(Input::get()); if($validation->fails()){ return Redirect::to('view/employee/office/'.$id)->withErrors($validation)->withInput(); } else { $officedetail = new Officedetail; $officedetail->empid = $id; $officedetail->salary = Input::get('salary'); $officedetail->incentive = Input::get('incentive'); $officedetail->target = Input::get('target'); $officedetail->area = Input::get('area'); if($officedetail->save()){ return Redirect::to('view/employee/office/'.$id)->with('qmessage','Officedetail Added'); } else { return Redirect::to('view/employee/office/'.$id)->with('qemessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } public function putOffice($id) { $validation = Officedetail::validate(Input::get()); if($validation->fails()){ return Redirect::to('view/employee/office/'.$id)->withErrors($validation)->withInput(); } else { $officedetail = Officedetail::find($id); $officedetail->salary = Input::get('salary'); $officedetail->incentive = Input::get('incentive'); $officedetail->target = Input::get('target'); $officedetail->area = Input::get('area'); if($officedetail->save()){ return Redirect::to('view/employee/office/'.$id)->with('qmessage','Officedetail Edit'); } else { return Redirect::to('view/employee/office/'.$id)->with('qemessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } } <file_sep>/core/app/controllers/Setup/FactoryController.php <?php namespace Setup; use BaseController, Input, View, Redirect, Validator, Types, System, Setup, Maincategory, Type, Nature; class FactoryController extends BaseController { /** * Display a listing of the resource. * Request GET * @return Response */ public function getIndex() { $setup = Setup::with('type', 'system')->get(); return View::make('layouts.view.setup.factory') ->with('setup',$setup); } public function getCreate() { foreach (Type::where('section', '=', 3)->get() as $type) { $typelist[$type->id] = $type->name; } foreach (Nature::where('section', '=', 3)->get() as $type) { $naturelist[$type->id] = $type->name; } foreach (System::all() as $type) { $systemlist[$type->id] = $type->name; } return View::make('layouts.forms.setup.factory') ->with('systemlist',$systemlist) ->with('typelist',$typelist) ->with('naturelist',$naturelist) ->with('createfor', null) ->with('types', null) ->with('nature', null) ->with('id', null) ->with('name', null) ->with('short', null); } public function postIndex() { $data = new Setup; $data->id = Input::get('id'); $data->name = Input::get('name'); $data->short = Input::get('short'); $data->type_id = Input::get('types'); $data->system_id = Input::get('createfor'); $data->nature_id = Input::get('nature'); if($data->save()){ return Redirect::to('setup/factory/')->with('message','Added'); } else { return Redirect::to('setup/factory')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } public function getEdit($id) { foreach (Type::where('section', '=', 3)->get() as $type) { $typelist[$type->id] = $type->name; } foreach (Nature::where('section', '=', 3)->get() as $type) { $naturelist[$type->id] = $type->name; } foreach (System::all() as $type) { $systemlist[$type->id] = $type->name; } $setup = Setup::find($id); return View::make('layouts.forms.setup.factory') ->with('editform', 'Edit') ->with('systemlist',$systemlist) ->with('typelist',$typelist) ->with('naturelist',$naturelist) ->with('createfor', $setup->system_id) ->with('types', $setup->type_id) ->with('nature', $setup->nature_id) ->with('id', $setup->id) ->with('name', $setup->name) ->with('short', $setup->short); } public function putEdit($id) { $data = Setup::find($id); $data->id = Input::get('id'); $data->name = Input::get('name'); $data->short = Input::get('short'); $data->type_id = Input::get('types'); $data->system_id = Input::get('createfor'); $data->nature_id = Input::get('nature'); if($data->save()){ return Redirect::to('setup/factory/')->with('message','Edit'); } else { return Redirect::to('setup/factory/edit/'.$id)->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } public function getType() { foreach (Maincategory::all() as $type) { $typelist[$type->id] = $type->name; } $url = "setup/factory/type"; return View::make('layouts.forms.setup.fpa.type') ->with('typelist',$typelist) ->with('type',null) ->with('form', 'Store') ->with('parent', '4') ->with('url', $url) ->with('name',null) ->with('id',null); } public function postType() { $validation = Type::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/factory/type')->withErrors($validation)->withInput(); } else { $type = new Type; $type->maincategory_id = Input::get('maincategory'); $type->name = Input::get('name'); $type->section = 3; if($type->save()){ return Redirect::to('setup/factory/')->with('message','Type Added'); } else { return Redirect::to('setup/factory/type')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } public function getNature() { foreach (Maincategory::all() as $type) { $typelist[$type->id] = $type->name; // dd ($type); } $url = "setup/factory/nature"; return View::make('layouts.forms.setup.fpa.nature') ->with('typelist',$typelist) ->with('url', $url) ->with('parent', '4') ->with('form', 'Finished Product Attributes') ->with('type',null) ->with('name',null) ->with('id',null); } /** * Store a newly created resource in storage. * Request POST * @return Response */ public function postNature() { $validation = Nature::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/factory/nature/')->withErrors($validation)->withInput(); } else { $nature = new Nature; $nature->maincategory_id = Input::get('maincategory'); $nature->name = Input::get('name'); $nature->section = 3; if($nature->save()){ return Redirect::to('setup/factory/')->with('message','Nature Added'); } else { return Redirect::to('setup/factory/nature')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } }<file_sep>/core/app/controllers/Setup/DeliveryController.php <?php namespace Setup; use BaseController, Input, View, Redirect, Validator, Driver,Delivery,System,Transport ; class DeliveryController extends BaseController { /** * Display a listing of the resource. * Request GET * @return Response */ public function index() { $delivery=Delivery::with('system', 'driver', 'transport')->get(); //dd($tcompany); return View::make('layouts.view.setup.delivery') ->with('delivery',$delivery); } /** * Show the form for creating a new resource. * Request GET * @return Response */ public function create() { foreach (System::all() as $type) { $systemlist[$type->id] = $type->name; } return View::make('layouts.forms.setup.delivery') ->with('systemlist', $systemlist) ->with('systemid', null) ->with('driverid', null) ->with('drivername', null) ->with('transportid', null) ->with('transportname', null); } /** * Store a newly created resource in storage. * Request POST * @return Response */ public function store() { $validation = Delivery::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/delivery/create')->withErrors($validation)->withInput(); }else { $delivery = new Delivery; $delivery->system_id = Input::get('systemtype'); $delivery->driver_id = Input::get('driver'); $delivery->transport_id = Input::get('transport'); if($delivery->save()){ return Redirect::to('setup/delivery')->with('message','Transport Comapny Updated'); } else { return Redirect::to('setup/delivery/create')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } /** * Display the specified resource. * Request GET * @param int $id * @return Response */ public function show($id) { } /** * Show the form for editing the specified resource. * Request GET * @param int $id * @return Response */ public function edit($id) { foreach (System::all() as $type) { $systemlist[$type->id] = $type->name; } $delivery=Delivery::find($id); $systemid = $delivery->system_id; $driverid = $delivery->driver_id; $drivername = Delivery::find($id)->driver->name; $transportid = $delivery->transport_id; $transportname = Delivery::find($id)->transport->companyname; return View::make('layouts.forms.setup.delivery') ->with('editform', 'Edit Delivery Information') ->with('id', $id) ->with('systemlist', $systemlist) ->with('systemid', $systemid) ->with('driverid', $driverid) ->with('drivername', $drivername) ->with('transportid', $transportid) ->with('transportname', $transportname); } /** * Update the specified resource in storage. * Request PUT * @param int $id * @return Response */ public function update($id) { $validation = Delivery::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/delivery'.$id.'/edit')->withErrors($validation)->withInput(); }else { $delivery = Delivery::find($id); $delivery->system_id = Input::get('systemtype'); $delivery->driver_id = Input::get('driver'); $delivery->transport_id = Input::get('transport'); if($delivery->save()){ return Redirect::to('setup/delivery')->with('message','Transport Comapny Updated'); } else { return Redirect::to('setup/delivery/'.$id.'/edit')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } /** * Remove the specified resource from storage. * Request Delete * @param int $id * @return Response */ public function destroy($id) { // } }<file_sep>/core/app/models/System.php <?php class System extends Eloquent { protected $table = 'system'; public $timestamps = false; public function setup() { return $this->hasMany('Setup'); } public function transport() { return $this->hasMany('Transport'); } public function delivery() { return $this->hasMany('Delivery'); } public function product() { return $this->hasMany('Product'); } }<file_sep>/core/app/models/ExpenseGroup.php <?php class ExpenseGroup extends Eloquent { protected $table = 'expensegroup'; public $timestamps = false; public static $rules = array( 'newexpense' => 'required' ); public static function validate($data){ return Validator::make($data, static::$rules); } }<file_sep>/core/app/models/Delivery.php <?php class Delivery extends Eloquent { protected $table = 'delivery'; public $timestamps = false; public static $rules = array( 'systemtype' => 'required|min:2|max:200', 'driver' => 'required', 'transport' => 'required' ); public static function validate($data){ return Validator::make($data, static::$rules); } public function system() { return $this->belongsTo('System'); } public function driver() { return $this->belongsTo('Driver'); } public function transport() { return $this->belongsTo('Transport'); } }<file_sep>/core/app/controllers/Setup/fpa/CategoryController.php <?php namespace Setup\fpa; use BaseController, Input, View, Redirect, Validator, Maincategory, Category; class CategoryController extends BaseController { /** * Display a listing of the resource. * Request GET * @return Response */ public function index() { $category = Category::with('maincategory.types')->get(); return View::make('layouts.view.setup.fpa.category') ->with('category', $category); } /** * Show the form for creating a new resource. * Request GET * @return Response */ public function create() { foreach (Maincategory::all() as $type) { $typelist[$type->id] = $type->name; } return View::make('layouts.forms.setup.fpa.category') ->with('typelist', $typelist) ->with('type', null) ->with('name', null); } /** * Store a newly created resource in storage. * Request POST * @return Response */ public function store() { $validation = Category::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/fpa/category/create')->withErrors($validation)->withInput(); } else { $expense = new Category; $expense->maincategory_id = Input::get('maincategory'); $expense->name = Input::get('name'); if($expense->save()){ return Redirect::to('setup/fpa/category/')->with('message','Category Added'); } else { return Redirect::to('setup/fpa/category/create')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } /** * Display the specified resource. * Request GET * @param int $id * @return Response */ public function show($id) { } /** * Show the form for editing the specified resource. * Request GET * @param int $id * @return Response */ public function edit($id) { foreach (Maincategory::all() as $type) { $typelist[$type->id] = $type->name; } $alltype = Category::find($id); //dd($alltype->type); $type = $alltype->type; $name = $alltype->name; return View::make('layouts.forms.setup.fpa.category') ->with('editform', 'Edit Category') ->with('id', $id) ->with('typelist', $typelist) ->with('type', $type) ->with('name', $name); } /** * Update the specified resource in storage. * Request PUT * @param int $id * @return Response */ public function update($id) { $validation = Category::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/fpa/category/'.$id.'/edit')->withErrors($validation)->withInput(); } else { $expense = Category::find($id); $expense->maincategory_id = Input::get('maincategory'); $expense->name = Input::get('name'); if($expense->save()){ return Redirect::to('setup/fpa/category')->with('message','Category Edit'); } else { return Redirect::to('setup/fpa/category/'.$id.'/edit')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } /** * Remove the specified resource from storage. * Request Delete * @param int $id * @return Response */ public function destroy($id) { // } }<file_sep>/core/app/controllers/Setup/ReturnreasonController.php <?php namespace Setup; use BaseController, Input, View, Redirect, Expensetype, Validator,Returnreason; class ReturnreasonController extends BaseController { /** * Display a listing of the resource. * Request GET * @return Response */ public function index() { $returnreason = Returnreason::all(); return View::make('layouts.view.setup.returnreason') ->with('returnreason', $returnreason); } /** * Show the form for creating a new resource. * Request GET * @return Response */ public function create() { return View::make('layouts.forms.setup.returnreason') ->with('returnreason', null); } /** * Store a newly created resource in storage. * Request POST * @return Response */ public function store() { /* $validation = Expensetype::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/salarytype/create')->withErrors($validation)->withInput(); } else {*/ $returnreason = new Returnreason; $returnreason->returnreason = Input::get('returnreason'); if($returnreason->save()){ return Redirect::to('setup/returnreason')->with('message','Return Reason Added'); } else { return Redirect::to('setup/returnreason/create')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } //} } /** * Display the specified resource. * Request GET * @param int $id * @return Response */ public function show($id) { } /** * Show the form for editing the specified resource. * Request GET * @param int $id * @return Response */ public function edit($id) { $returnreason = Returnreason::find($id); return View::make('layouts.forms.setup.returnreason') ->with('editform', 'Edit returnreason') ->with('id', $returnreason->id) ->with('returnreason', $returnreason->returnreason); } /** * Update the specified resource in storage. * Request PUT * @param int $id * @return Response */ public function update($id) { /* $validation = Expensetype::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/expense/create/'.$id.'/edit')->withErrors($validation)->withInput(); } else {*/ $returnreason = Returnreason::find($id); $returnreason->returnreason = Input::get('returnreason'); if($returnreason->save()){ return Redirect::to('setup/returnreason')->with('message','Return Reason Edit'); } else { return Redirect::to('setup/returnreason/create/'.$id.'/edit')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } //} } /** * Remove the specified resource from storage. * Request Delete * @param int $id * @return Response */ public function destroy($id) { // } }<file_sep>/core/app/controllers/Setup/ProductController.php <?php namespace Setup; use BaseController, Input, View, Redirect, Validator, Product, Types, Maincategory, System, Category, Classes, Foume, Group, Grade, Nature, Type; class ProductController extends BaseController { /** * Display a listing of the resource. * Request GET * @return Response */ public function index() { $product = Product::with('maincategory.types')->get(); return View::make('layouts.view.setup.product') ->with('product', $product); } public function create() { foreach (Types::all() as $type) { $typelist[$type->id] = $type->name; } foreach (Maincategory::all() as $value) { $mcategorylist[$value->id] = $value->name; } foreach (System::all() as $value) { $systemlist[$value->id] = $value->name; } return View::make('layouts.forms.setup.product') ->with('typelist',$typelist) ->with('systemlist',$systemlist) ->with('mcategorylist',$mcategorylist) ->with('categorylist',array('' => null)) ->with('classlist',array('' => null)) ->with('foumelist',array('' => null)) ->with('gradelist',array('' => null)) ->with('grouplist',array('' => null)) ->with('naturelist',array('' => null)) ->with('typelist',array('' => null)) ->with('mtype', null) ->with('createfor', null) ->with('createforname', null) ->with('createforid', null) ->with('item', null) ->with('brand', null) ->with('size', null) ->with('weight', null) ->with('cqty', null) ->with('psize', null) ->with('mrp', null) ->with('category', null) ->with('class', null) ->with('foum', null) ->with('grade', null) ->with('group', null) ->with('nature', null) ->with('type', null) ->with('description', null) ->with('remarks', null) ->with('active', null) ->with('status', 'checked'); } public function store() { $validation = Product::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/product/create')->withErrors($validation)->withInput(); } else { $product = new Product; $product->maincategory_id = Input::get('maincategory'); $product->system_id = Input::get('createfor'); $product->setup_id = Input::get('createforname'); $product->item = Input::get('item'); $product->brand = Input::get('brand'); $product->size = Input::get('size'); $product->weight = Input::get('weight'); $product->cqty = Input::get('cqty'); $product->psize = Input::get('psize'); $product->mrp = Input::get('mrp'); $product->category_id = Input::get('category'); $product->class_id = Input::get('class'); $product->foum_id = Input::get('foume'); $product->grade_id = Input::get('grade'); $product->group_id = Input::get('group'); $product->nature_id = Input::get('nature'); $product->type_id = Input::get('type'); $product->description = Input::get('description'); $product->remarks = Input::get('remarks'); $product->active = Input::get('active'); if($product->save()){ return Redirect::to('setup/product')->with('message','Product Added'); } else { return Redirect::to('setup/product/create')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } public function edit($id) { $product = Product::find($id); $status = null; if($product->active == 1){ $status = "checked"; } foreach (Types::all() as $type) { $typelist[$type->id] = $type->name; } foreach (Maincategory::all() as $value) { $mcategorylist[$value->id] = $value->name; } foreach (System::all() as $value) { $systemlist[$value->id] = $value->name; } foreach (Category::where('maincategory_id', '=', $product->maincategory_id)->get() as $value) { $categorylist[$value->id] = $value->name; } foreach (Classes::where('maincategory_id', '=', $product->maincategory_id)->get() as $value) { $classlist[$value->id] = $value->name; } foreach (Foume::where('maincategory_id', '=', $product->maincategory_id)->get() as $value) { $foumelist[$value->id] = $value->name; } foreach (Grade::where('maincategory_id', '=', $product->maincategory_id)->get() as $value) { $gradelist[$value->id] = $value->name; } foreach (Group::where('maincategory_id', '=', $product->maincategory_id)->get() as $value) { $grouplist[$value->id] = $value->name; } foreach (Nature::where('maincategory_id', '=', $product->maincategory_id)->get() as $value) { $naturelist[$value->id] = $value->name; } foreach (Type::where('maincategory_id', '=', $product->maincategory_id)->get() as $value) { $typelist[$value->id] = $value->name; } return View::make('layouts.forms.setup.product') ->with('editform', 'Edit') ->with('id', $id) ->with('typelist',$typelist) ->with('systemlist',$systemlist) ->with('mcategorylist',$mcategorylist) ->with('categorylist',$categorylist) ->with('classlist',$classlist) ->with('foumelist',$foumelist) ->with('gradelist',$gradelist) ->with('grouplist',$grouplist) ->with('naturelist',$naturelist) ->with('typelist',$typelist) ->with('mtype', $product->maincategory_id) ->with('createfor', $product->system_id) ->with('createforname', $product->setup->name) ->with('createforid', $product->setup_id) ->with('item', $product->item) ->with('brand', $product->brand) ->with('size', $product->size) ->with('weight', $product->weight) ->with('cqty', $product->cqty) ->with('psize', $product->psize) ->with('mrp', $product->mrp) ->with('category', $product->category_id) ->with('class', $product->class_id) ->with('foum', $product->foum_id) ->with('grade', $product->grade_id) ->with('group', $product->group_id) ->with('nature', $product->nature_id) ->with('type', $product->type_id) ->with('description', $product->description) ->with('remarks', $product->remarks) ->with('active', $product->active) ->with('status', $status); } public function update($id) { $validation = Product::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/product/'.$id.'/edit')->withErrors($validation)->withInput(); } else { $product = Product::find($id); $product->maincategory_id = Input::get('maincategory'); $product->system_id = Input::get('createfor'); $product->setup_id = Input::get('createforname'); $product->item = Input::get('item'); $product->brand = Input::get('brand'); $product->size = Input::get('size'); $product->weight = Input::get('weight'); $product->cqty = Input::get('cqty'); $product->psize = Input::get('psize'); $product->mrp = Input::get('mrp'); $product->category_id = Input::get('category'); $product->class_id = Input::get('class'); $product->foum_id = Input::get('foume'); $product->grade_id = Input::get('grade'); $product->group_id = Input::get('group'); $product->nature_id = Input::get('nature'); $product->type_id = Input::get('type'); $product->description = Input::get('description'); $product->remarks = Input::get('remarks'); $product->active = Input::get('active'); if($product->save()){ return Redirect::to('setup/product')->with('message','Product Edit'); } else { return Redirect::to('setup/product/'.$id.'/edit')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } }<file_sep>/core/app/models/Salarytype.php <?php class Salarytype extends Eloquent { protected $table = 'salarytype'; public $timestamps = false; /*public static $rules = array( 'createfor' => 'required', 'name' => 'required' ); public static function validate($data){ return Validator::make($data, static::$rules); } public function delivery() { return $this->hasMany('Delivery'); }*/ }<file_sep>/core/app/controllers/Setup/fpa/FoumeController.php <?php namespace Setup\fpa; use BaseController, Input, View, Redirect, Validator, Maincategory, Foume, Expensetype; class FoumeController extends BaseController { /** * Display a listing of the resource. * Request GET * @return Response */ public function index() { $foume=Foume::with('maincategory.types')->get(); return View::make('layouts.view.setup.fpa.foume') ->with('foume',$foume); } /** * Show the form for creating a new resource. * Request GET * @return Response */ public function create() { foreach (Maincategory::all() as $type) { $typelist[$type->id] = $type->name; // dd ($type); } return View::make('layouts.forms.setup.fpa.foume') ->with('typelist',$typelist) ->with('type',null) ->with('name',null) ->with('id',null); } /** * Store a newly created resource in storage. * Request POST * @return Response */ public function store() { $validation = Foume::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/fpa/foume/create')->withErrors($validation)->withInput(); } else { $foum = new Foume; $foum->maincategory_id = Input::get('maincategory'); $foum->name = Input::get('name'); if($foum->save()){ return Redirect::to('setup/fpa/foume/')->with('message','Foume Added'); } else { return Redirect::to('setup/fpa/foume/create')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } /** * Display the specified resource. * Request GET * @param int $id * @return Response */ public function show($id) { } /** * Show the form for editing the specified resource. * Request GET * @param int $id * @return Response */ public function edit($id) { foreach (Maincategory::all() as $type) { $typelist[$type->id] = $type->name; } $alltype = Foume::find($id); //dd($alltype->name); $type = $alltype->type; $name = $alltype->name; return View::make('layouts.forms.setup.fpa.foume') ->with('editform', 'Edit Category') ->with('id', $id) ->with('typelist', $typelist) ->with('type', $type) ->with('name', $name); } /** * Update the specified resource in storage. * Request PUT * @param int $id * @return Response */ public function update($id) { $validation = Foume::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/fpa/foume/'.$id.'/edit')->withErrors($validation)->withInput(); } else { $foum = Foume::find($id); $foum->maincategory_id = Input::get('maincategory'); $foum->name = Input::get('name'); if($foum->save()){ return Redirect::to('setup/fpa/foume')->with('message','Foume Edit'); } else { return Redirect::to('setup/fpa/foume/'.$id.'/edit')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } /** * Remove the specified resource from storage. * Request Delete * @param int $id * @return Response */ public function destroy($id) { // } }<file_sep>/core/app/controllers/Setup/fpa/GroupController.php <?php namespace Setup\fpa; use BaseController, Input, View, Redirect, Validator, Maincategory, Group, Expensetype; class GroupController extends BaseController { /** * Display a listing of the resource. * Request GET * @return Response */ public function index() { $group=Group::with('maincategory.types')->get(); //dd($group); return View::make('layouts.view.setup.fpa.group') ->with('group',$group); } /** * Show the form for creating a new resource. * Request GET * @return Response */ public function create() { foreach (Maincategory::all() as $type) { $typelist[$type->id] = $type->name; // dd ($type); } return View::make('layouts.forms.setup.fpa.group') ->with('typelist',$typelist) ->with('type',null) ->with('name',null) ->with('id',null); } /** * Store a newly created resource in storage. * Request POST * @return Response */ public function store() { $validation = Group::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/fpa/group/create')->withErrors($validation)->withInput(); } else { $group = new Group; $group->type = Input::get('types'); $group->name = Input::get('name'); if($group->save()){ return Redirect::to('setup/fpa/group/')->with('message','Group Added'); } else { return Redirect::to('setup/fpa/group/create')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } /** * Display the specified resource. * Request GET * @param int $id * @return Response */ public function show($id) { } /** * Show the form for editing the specified resource. * Request GET * @param int $id * @return Response */ public function edit($id) { foreach (Maincategory::all() as $type) { $typelist[$type->id] = $type->name; } $alltype = Group::find($id); //dd($alltype->name); $type = $alltype->type; $name = $alltype->name; return View::make('layouts.forms.setup.fpa.group') ->with('editform', 'Edit Group') ->with('id', $id) ->with('typelist', $typelist) ->with('type', $type) ->with('name', $name); } /** * Update the specified resource in storage. * Request PUT * @param int $id * @return Response */ public function update($id) { $validation = Group::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/fpa/group/'.$id.'/edit')->withErrors($validation)->withInput(); } else { $group = Group::find($id); $group->maincategory_id = Input::get('maincategory'); $group->name = Input::get('name'); if($group->save()){ return Redirect::to('setup/fpa/group')->with('message','Group Edit'); } else { return Redirect::to('setup/fpa/group/'.$id.'/edit')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } /** * Remove the specified resource from storage. * Request Delete * @param int $id * @return Response */ public function destroy($id) { // } }<file_sep>/core/app/controllers/Setup/ExpenseController.php <?php namespace Setup; use BaseController, Input, View, Redirect, Expensetype, Validator; class ExpenseController extends BaseController { /** * Display a listing of the resource. * Request GET * @return Response */ public function index() { $expense = Expensetype::all(); return View::make('layouts.view.setup.expense') ->with('expense', $expense); } /** * Show the form for creating a new resource. * Request GET * @return Response */ public function create() { return View::make('layouts.forms.setup.expense') ->with('type', null) ->with('remarks', null); } /** * Store a newly created resource in storage. * Request POST * @return Response */ public function store() { $validation = Expensetype::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/expense/create')->withErrors($validation)->withInput(); } else { $expense = new Expensetype; $expense->type = Input::get('etype'); $expense->remarks = Input::get('remarks'); if($expense->save()){ return Redirect::to('setup/expense')->with('message','Expence Type Added'); } else { return Redirect::to('setup/expense/create')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } /** * Display the specified resource. * Request GET * @param int $id * @return Response */ public function show($id) { return View::make('layouts.forms.setup.expense') ->with('type', null) ->with('remarks', null); } /** * Show the form for editing the specified resource. * Request GET * @param int $id * @return Response */ public function edit($id) { $expense = Expensetype::find($id); return View::make('layouts.forms.setup.expense') ->with('editform', 'Edit Expense Type') ->with('id', $expense->id) ->with('type', $expense->type) ->with('remarks', $expense->remarks); } /** * Update the specified resource in storage. * Request PUT * @param int $id * @return Response */ public function update($id) { $validation = Expensetype::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/expense/create/'.$id.'/edit')->withErrors($validation)->withInput(); } else { $expense = Expensetype::find($id); $expense->type = Input::get('etype'); $expense->remarks = Input::get('remarks'); if($expense->save()){ return Redirect::to('setup/expense')->with('message','Expence Type Edit'); } else { return Redirect::to('setup/expense/create/'.$id.'/edit')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } /** * Remove the specified resource from storage. * Request Delete * @param int $id * @return Response */ public function destroy($id) { // } }<file_sep>/core/app/controllers/Setup/EmployeeController.php <?php namespace Setup; use BaseController, Input, View, Redirect, Basicinfo, Validator; class EmployeeController extends BaseController { /** * Display a listing of the resource. * Request GET * @return Response */ public function index() { $employee = Basicinfo::all(); return View::make('layouts.view.setup.employeelist') ->with('employee', $employee); } /** * Show the form for creating a new resource. * Request GET * @return Response */ public function create() { $select = array( '1' => 'Factory', '2' => 'Factory Customer', '3' => 'Factory Customer Customer'); return View::make('layouts.forms.setup.employee') ->with('select', $select); } /** * Store a newly created resource in storage. * Request POST * @return Response */ public function store() { $validation = Basicinfo::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/employee/create')->withErrors($validation)->withInput(); } else { $basicinfo = new Basicinfo; $basicinfo->firstname = Input::get('firstname'); $basicinfo->middlename = Input::get('middlename'); $basicinfo->lastname = Input::get('lastname'); if($basicinfo->save()){ return Redirect::to('view/employee/details/'.$basicinfo->id)->with('message','Employee Added'); } else { return Redirect::to('setup/employee/create')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } /** * Display the specified resource. * Request GET * @param int $id * @return Response */ public function show($id) { $basicinfo = Basicinfo::find($id)->get(); return View::make('layouts.view.profile.index') ->with('basicinfo', $basicinfo); } /** * Show the form for editing the specified resource. * Request GET * @param int $id * @return Response */ public function edit($id) { } /** * Update the specified resource in storage. * Request PUT * @param int $id * @return Response */ public function update($id) { $validation = Basicinfo::validate(Input::get()); if($validation->fails()){ return Redirect::to('view/employee/details/'.$id)->withErrors($validation)->withInput(); } else { $basicinfo = Basicinfo::find($id); $basicinfo->firstname = Input::get('firstname'); $basicinfo->middlename = Input::get('middlename'); $basicinfo->lastname = Input::get('lastname'); if($basicinfo->save()){ return Redirect::to('view/employee/details/'.$id)->with('message','Employee Basic Info Edit'); } else { return Redirect::to('view/employee/details/'.$id)->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } /** * Remove the specified resource from storage. * Request Delete * @param int $id * @return Response */ public function destroy($id) { // } }<file_sep>/core/app/controllers/Setup/fpa/McategoryController.php <?php namespace Setup\fpa; use BaseController, Input, View, Redirect, Validator, Types, Category, Maincategory; class McategoryController extends BaseController { /** * Display a listing of the resource. * Request GET * @return Response */ public function index() { $category = Maincategory::with('types')->get(); return View::make('layouts.view.setup.fpa.mcategory') ->with('category', $category); } /** * Show the form for creating a new resource. * Request GET * @return Response */ public function create() { foreach (Types::all() as $type) { $typelist[$type->id] = $type->name; } return View::make('layouts.forms.setup.fpa.mcategory') ->with('typelist', $typelist) ->with('type', null) ->with('name', null); } /** * Store a newly created resource in storage. * Request POST * @return Response */ public function store() { $validation = Maincategory::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/fpa/maincategory/create')->withErrors($validation)->withInput(); } else { $expense = new Maincategory; $expense->type = Input::get('types'); $expense->name = Input::get('name'); if($expense->save()){ return Redirect::to('setup/fpa/maincategory/')->with('message','Main Category Added'); } else { return Redirect::to('setup/fpa/maincategory/create')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } /** * Display the specified resource. * Request GET * @param int $id * @return Response */ public function show($id) { } /** * Show the form for editing the specified resource. * Request GET * @param int $id * @return Response */ public function edit($id) { foreach (Types::all() as $type) { $typelist[$type->id] = $type->name; } $alltype = Maincategory::find($id); //dd($alltype->type); $type = $alltype->type; $name = $alltype->name; return View::make('layouts.forms.setup.fpa.mcategory') ->with('editform', 'Edit Category') ->with('id', $id) ->with('typelist', $typelist) ->with('type', $type) ->with('name', $name); } /** * Update the specified resource in storage. * Request PUT * @param int $id * @return Response */ public function update($id) { $validation = Maincategory::validate(Input::get()); if($validation->fails()){ return Redirect::to('setup/fpa/maincategory/'.$id.'/edit')->withErrors($validation)->withInput(); } else { $expense = Maincategory::find($id); $expense->type = Input::get('types'); $expense->name = Input::get('name'); if($expense->save()){ return Redirect::to('setup/fpa/maincategory')->with('message','Main Category Edit'); } else { return Redirect::to('setup/fpa/maincategory/'.$id.'/edit')->with('emessage','Some Thing Went Wrong Please Try Again or contact System Administrator'); } } } /** * Remove the specified resource from storage. * Request Delete * @param int $id * @return Response */ public function destroy($id) { // } }
b2178a4a70b9e4a0865d6bc3983d9745f9e1f672
[ "PHP" ]
40
PHP
shujaatali101/agro
f33d20c33c908b649c532c9a486f00e139a0c46b
7ba3fc59bd1c4b049acb1f8ff6c709310e771cef
refs/heads/master
<file_sep>__author__ = 'chris' import json import random import time import nacl.signing import bitcoin from hashlib import sha256 from binascii import unhexlify, hexlify from collections import OrderedDict from urllib2 import Request, urlopen, URLError import re import os import nacl.encoding from twisted.internet import reactor from protos.objects import Listings from protos.countries import CountryCode from dht.utils import digest from constants import DATA_FOLDER from market.profile import Profile from keyutils.keys import KeyChain from keyutils.bip32utils import derive_childkey from log import Logger class Contract(object): """ A class for creating and interacting with OpenBazaar Ricardian contracts. """ def __init__(self, database, contract=None, hash_value=None, testnet=False): """ This class can be instantiated with either an `OrderedDict` or a hash of a contract. If a hash is used, we will load the contract from either the file system or cache. Alternatively, pass in no parameters if the intent is to create a new contract. Args: contract: an `OrderedDict` containing a filled out json contract hash: a hash160 (in raw bytes) of a contract testnet: is this contract on the testnet """ self.db = database self.keychain = KeyChain(self.db) if contract is not None: self.contract = contract elif hash_value is not None: try: file_path = self.db.HashMap().get_file(hash_value) if file_path is None: file_path = DATA_FOLDER + "cache/" + hexlify(hash_value) with open(file_path, 'r') as filename: self.contract = json.load(filename, object_pairs_hook=OrderedDict) except Exception: try: file_path = DATA_FOLDER + "purchases/in progress/" + hexlify(hash_value) + ".json" with open(file_path, 'r') as filename: self.contract = json.load(filename, object_pairs_hook=OrderedDict) except Exception: self.contract = {} else: self.contract = {} self.log = Logger(system=self) # used when purchasing this contract self.testnet = testnet self.ws = None self.blockchain = None self.amount_funded = 0 self.received_txs = [] self.timeout = None self.is_purchase = False def create(self, expiration_date, metadata_category, title, description, currency_code, price, process_time, nsfw, shipping_origin=None, shipping_regions=None, est_delivery_domestic=None, est_delivery_international=None, terms_conditions=None, returns=None, keywords=None, category=None, condition=None, sku=None, images=None, free_shipping=None, shipping_currency_code=None, shipping_domestic=None, shipping_international=None, options=None, moderators=None): """ All parameters are strings except: :param expiration_date: `string` (must be formatted UTC datetime) :param keywords: `list` :param nsfw: `boolean` :param images: a `list` of image files :param free_shipping: `boolean` :param shipping_origin: a 'string' formatted `CountryCode` :param shipping_regions: a 'list' of 'string' formatted `CountryCode`s :param options: a 'dict' containing options as keys and 'list' as option values. :param moderators: a 'list' of 'string' guids (hex encoded). """ profile = Profile(self.db).get() self.contract = OrderedDict( { "vendor_offer": { "listing": { "metadata": { "version": "0.1", "category": metadata_category.lower(), "category_sub": "fixed price" }, "id": { "guid": self.keychain.guid.encode("hex"), "pubkeys": { "guid": self.keychain.guid_signed_pubkey[64:].encode("hex"), "bitcoin": bitcoin.bip32_extract_key(self.keychain.bitcoin_master_pubkey), "encryption": self.keychain.encryption_pubkey.encode("hex") } }, "item": { "title": title, "description": description, "process_time": process_time, "price_per_unit": {}, "nsfw": nsfw } } } } ) if expiration_date.lower() == "never": self.contract["vendor_offer"]["listing"]["metadata"]["expiry"] = "never" else: self.contract["vendor_offer"]["listing"]["metadata"]["expiry"] = expiration_date + " UTC" if metadata_category == "physical good" and condition is not None: self.contract["vendor_offer"]["listing"]["item"]["condition"] = condition if currency_code.upper() == "BTC": item = self.contract["vendor_offer"]["listing"]["item"] item["price_per_unit"]["bitcoin"] = price else: item = self.contract["vendor_offer"]["listing"]["item"] item["price_per_unit"]["fiat"] = {} item["price_per_unit"]["fiat"]["price"] = price item["price_per_unit"]["fiat"]["currency_code"] = currency_code if keywords is not None: self.contract["vendor_offer"]["listing"]["item"]["keywords"] = [] self.contract["vendor_offer"]["listing"]["item"]["keywords"].extend(keywords) if category is not None: self.contract["vendor_offer"]["listing"]["item"]["category"] = category if sku is not None: self.contract["vendor_offer"]["listing"]["item"]["sku"] = sku if options is not None: self.contract["vendor_offer"]["listing"]["item"]["options"] = options if metadata_category == "physical good": self.contract["vendor_offer"]["listing"]["shipping"] = {} shipping = self.contract["vendor_offer"]["listing"]["shipping"] shipping["shipping_origin"] = shipping_origin if free_shipping is False: self.contract["vendor_offer"]["listing"]["shipping"]["free"] = False self.contract["vendor_offer"]["listing"]["shipping"]["flat_fee"] = {} if shipping_currency_code == "BTC": self.contract["vendor_offer"]["listing"]["shipping"]["flat_fee"]["bitcoin"] = {} self.contract["vendor_offer"]["listing"]["shipping"]["flat_fee"]["bitcoin"][ "domestic"] = shipping_domestic self.contract["vendor_offer"]["listing"]["shipping"]["flat_fee"]["bitcoin"][ "international"] = shipping_international else: shipping = self.contract["vendor_offer"]["listing"]["shipping"] shipping["flat_fee"]["fiat"] = {} shipping["flat_fee"]["fiat"]["price"] = {} shipping["flat_fee"]["fiat"]["price"][ "domestic"] = shipping_domestic shipping["flat_fee"]["fiat"]["price"][ "international"] = shipping_international shipping["flat_fee"]["fiat"][ "currency_code"] = shipping_currency_code else: self.contract["vendor_offer"]["listing"]["shipping"]["free"] = True self.contract["vendor_offer"]["listing"]["shipping"]["shipping_regions"] = [] for region in shipping_regions: shipping = self.contract["vendor_offer"]["listing"]["shipping"] shipping["shipping_regions"].append(region) listing = self.contract["vendor_offer"]["listing"] listing["shipping"]["est_delivery"] = {} listing["shipping"]["est_delivery"]["domestic"] = est_delivery_domestic listing["shipping"]["est_delivery"][ "international"] = est_delivery_international if profile.HasField("handle"): self.contract["vendor_offer"]["listing"]["id"]["blockchain_id"] = profile.handle if images is not None: self.contract["vendor_offer"]["listing"]["item"]["image_hashes"] = [] for image_hash in images: self.contract["vendor_offer"]["listing"]["item"]["image_hashes"].append(image_hash) if terms_conditions is not None or returns is not None: self.contract["vendor_offer"]["listing"]["policy"] = {} if terms_conditions is not None: self.contract["vendor_offer"]["listing"]["policy"]["terms_conditions"] = terms_conditions if returns is not None: self.contract["vendor_offer"]["listing"]["policy"]["returns"] = returns if moderators is not None: self.contract["vendor_offer"]["listing"]["moderators"] = [] for mod in moderators: mod_info = self.db.ModeratorStore().get_moderator(unhexlify(mod)) print mod_info if mod_info is not None: moderator = { "guid": mod, "blockchain_id": mod_info[6], "pubkeys": { "signing": { "key": mod_info[1][64:].encode("hex"), "signature": mod_info[1][:64].encode("hex") }, "encryption": { "key": mod_info[2].encode("hex"), "signature": mod_info[3].encode("hex") }, "bitcoin": { "key": mod_info[4].encode("hex"), "signature": mod_info[5].encode("hex") } } } self.contract["vendor_offer"]["listing"]["moderators"].append(moderator) listing = json.dumps(self.contract["vendor_offer"]["listing"], indent=4) self.contract["vendor_offer"]["signature"] = \ self.keychain.signing_key.sign(listing, encoder=nacl.encoding.HexEncoder)[:128] self.save() def add_purchase_info(self, quantity, ship_to=None, shipping_address=None, city=None, state=None, postal_code=None, country=None, moderator=None, options=None): """ Update the contract with the buyer's purchase information. """ profile = Profile(self.db).get() order_json = { "buyer_order": { "order": { "ref_hash": digest(json.dumps(self.contract, indent=4)).encode("hex"), "quantity": quantity, "id": { "guid": self.keychain.guid.encode("hex"), "pubkeys": { "guid": self.keychain.guid_signed_pubkey[64:].encode("hex"), "bitcoin": bitcoin.bip32_extract_key(self.keychain.bitcoin_master_pubkey), "encryption": self.keychain.encryption_pubkey.encode("hex") } }, "payment": {} } } } if profile.HasField("handle"): order_json["buyer_order"]["order"]["id"]["blockchain_id"] = profile.handle if self.contract["vendor_offer"]["listing"]["metadata"]["category"] == "physical good": order_json["buyer_order"]["order"]["shipping"] = {} order_json["buyer_order"]["order"]["shipping"]["ship_to"] = ship_to order_json["buyer_order"]["order"]["shipping"]["address"] = shipping_address order_json["buyer_order"]["order"]["shipping"]["city"] = city order_json["buyer_order"]["order"]["shipping"]["state"] = state order_json["buyer_order"]["order"]["shipping"]["postal_code"] = postal_code order_json["buyer_order"]["order"]["shipping"]["country"] = country if options is not None: order_json["buyer_order"]["order"]["options"] = options if moderator: # TODO: Handle direct payments chaincode = sha256(str(random.getrandbits(256))).digest().encode("hex") order_json["buyer_order"]["order"]["payment"]["chaincode"] = chaincode valid_mod = False for mod in self.contract["vendor_offer"]["listing"]["moderators"]: if mod["guid"] == moderator: order_json["buyer_order"]["order"]["moderator"] = moderator masterkey_m = mod["pubkeys"]["bitcoin"]["key"] valid_mod = True if not valid_mod: return False masterkey_b = bitcoin.bip32_extract_key(self.keychain.bitcoin_master_pubkey) masterkey_v = self.contract["vendor_offer"]["listing"]["id"]["pubkeys"]["bitcoin"] buyer_key = derive_childkey(masterkey_b, chaincode) vendor_key = derive_childkey(masterkey_v, chaincode) moderator_key = derive_childkey(masterkey_m, chaincode) redeem_script = '75' + bitcoin.mk_multisig_script([buyer_key, vendor_key, moderator_key], 2) order_json["buyer_order"]["order"]["payment"]["redeem_script"] = redeem_script if self.testnet: payment_address = bitcoin.p2sh_scriptaddr(redeem_script, 196) else: payment_address = bitcoin.p2sh_scriptaddr(redeem_script) order_json["buyer_order"]["order"]["payment"]["address"] = payment_address price_json = self.contract["vendor_offer"]["listing"]["item"]["price_per_unit"] if "bitcoin" in price_json: order_json["buyer_order"]["order"]["payment"]["amount"] = price_json["bitcoin"] else: currency_code = price_json["fiat"]["currency_code"] fiat_price = price_json["fiat"]["price"] try: request = Request('https://api.bitcoinaverage.com/ticker/' + currency_code.upper() + '/last') response = urlopen(request) conversion_rate = response.read() except URLError: return False order_json["buyer_order"]["order"]["payment"]["amount"] = float( "{0:.8f}".format(float(fiat_price) / float(conversion_rate))) self.contract["buyer_order"] = order_json["buyer_order"] order = json.dumps(self.contract["buyer_order"]["order"], indent=4) self.contract["buyer_order"]["signature"] = \ self.keychain.signing_key.sign(order, encoder=nacl.encoding.HexEncoder)[:128] return self.contract["buyer_order"]["order"]["payment"]["address"] def add_order_confirmation(self, payout_address, comments=None, shipper=None, tracking_number=None, est_delivery=None, url=None, password=None): """ Add the vendor's order confirmation to the contract. """ if not self.testnet and not (payout_address[:1] == "1" or payout_address[:1] == "3"): raise Exception("Bitcoin address is not a mainnet address") elif self.testnet and not \ (payout_address[:1] == "n" or payout_address[:1] == "m" or payout_address[:1] == "2"): raise Exception("Bitcoin address is not a testnet address") try: bitcoin.b58check_to_hex(payout_address) except AssertionError: raise Exception("Invalid Bitcoin address") conf_json = { "vendor_order_confirmation": { "invoice": { "ref_hash": digest(json.dumps(self.contract, indent=4)).encode("hex"), "payout_address": payout_address } } } if self.contract["vendor_offer"]["listing"]["metadata"]["category"] == "physical good": shipping = {"shipper": shipper, "tracking_number": tracking_number, "est_delivery": est_delivery} conf_json["vendor_order_confirmation"]["invoice"]["shipping"] = shipping elif self.contract["vendor_offer"]["listing"]["metadata"]["category"] == "digital good": content_source = {"url": url, "password": <PASSWORD>} conf_json["vendor_order_confirmation"]["invoice"]["content_source"] = content_source if comments: conf_json["vendor_order_confirmation"]["invoice"]["comments"] = comments confirmation = json.dumps(conf_json["vendor_order_confirmation"]["invoice"], indent=4) conf_json["vendor_order_confirmation"]["signature"] = \ self.keychain.signing_key.sign(confirmation, encoder=nacl.encoding.HexEncoder)[:128] order_id = digest(json.dumps(self.contract, indent=4)).encode("hex") self.contract["vendor_order_confirmation"] = conf_json["vendor_order_confirmation"] self.db.Sales().update_status(order_id, 2) file_path = DATA_FOLDER + "store/listings/in progress/" + order_id + ".json" with open(file_path, 'w') as outfile: outfile.write(json.dumps(self.contract, indent=4)) def accept_order_confirmation(self, ws, confirmation_json=None): """ Validate the order confirmation sent over from the seller and update our node accordingly. """ self.ws = ws try: if confirmation_json: self.contract["vendor_order_confirmation"] = json.loads(confirmation_json, object_pairs_hook=OrderedDict) contract_dict = json.loads(json.dumps(self.contract, indent=4), object_pairs_hook=OrderedDict) del contract_dict["vendor_order_confirmation"] contract_hash = digest(json.dumps(contract_dict, indent=4)).encode("hex") ref_hash = self.contract["vendor_order_confirmation"]["invoice"]["ref_hash"] if ref_hash != contract_hash: raise Exception("Order number doesn't match") if self.contract["vendor_offer"]["listing"]["metadata"]["category"] == "physical good": shipping = self.contract["vendor_order_confirmation"]["invoice"]["shipping"] if "tracking_number" not in shipping or "shipper" not in shipping: raise Exception("No shipping information") # update the order status in the db self.db.Purchases().update_status(contract_hash, 2) file_path = DATA_FOLDER + "purchases/in progress/" + contract_hash + ".json" # update the contract in the file system with open(file_path, 'w') as outfile: outfile.write(json.dumps(self.contract, indent=4)) message_json = { "order_confirmation": { "order_id": contract_hash, "title": self.contract["vendor_offer"]["listing"]["item"]["title"] } } # push the message over websockets self.ws.push(json.dumps(message_json, indent=4)) return contract_hash except Exception: return False def await_funding(self, websocket_server, libbitcoin_client, proofSig, is_purchase=True): """ Saves the contract to the file system and db as an unfunded contract. Listens on the libbitcoin server for the multisig address to be funded. Deletes the unfunded contract from the file system and db if it goes unfunded for more than 10 minutes. """ # TODO: Handle direct payments self.ws = websocket_server self.blockchain = libbitcoin_client self.is_purchase = is_purchase order_id = digest(json.dumps(self.contract, indent=4)).encode("hex") payment_address = self.contract["buyer_order"]["order"]["payment"]["address"] vendor_item = self.contract["vendor_offer"]["listing"]["item"] if "image_hashes" in vendor_item: thumbnail_hash = vendor_item["image_hashes"][0] else: thumbnail_hash = "" if "blockchain_id" in self.contract["vendor_offer"]["listing"]["id"]: vendor = self.contract["vendor_offer"]["listing"]["id"]["blockchain_id"] else: vendor = self.contract["vendor_offer"]["listing"]["id"]["guid"] if is_purchase: file_path = DATA_FOLDER + "purchases/in progress/" + order_id + ".json" self.db.Purchases().new_purchase(order_id, self.contract["vendor_offer"]["listing"]["item"]["title"], time.time(), self.contract["buyer_order"]["order"]["payment"]["amount"], payment_address, 0, thumbnail_hash, vendor, proofSig) else: file_path = DATA_FOLDER + "store/listings/in progress/" + order_id + ".json" self.db.Sales().new_sale(order_id, self.contract["vendor_offer"]["listing"]["item"]["title"], time.time(), self.contract["buyer_order"]["order"]["payment"]["amount"], payment_address, 0, thumbnail_hash, vendor) with open(file_path, 'w') as outfile: outfile.write(json.dumps(self.contract, indent=4)) self.timeout = reactor.callLater(600, self._delete_unfunded) self.blockchain.subscribe_address(payment_address, notification_cb=self.on_tx_received) def _delete_unfunded(self): """ The user failed to fund the contract in the 10 minute window. Remove it from the file system and db. """ order_id = digest(json.dumps(self.contract, indent=4)).encode("hex") if self.is_purchase: file_path = DATA_FOLDER + "purchases/in progress/" + order_id + ".json" self.db.Purchases().delete_purchase(order_id) else: file_path = DATA_FOLDER + "store/listings/in progress/" + order_id + ".json" self.db.Sales().delete_sale(order_id) if os.path.exists(file_path): os.remove(file_path) def on_tx_received(self, address_version, address_hash, height, block_hash, tx): """ Fire when the libbitcoin server tells us we received a payment to this funding address. While unlikely, a user may send multiple transactions to the funding address reach the funding level. We need to keep a running balance and increment it when a new transaction is received. If the contract is fully funded, we push a notification to the websockets. """ # decode the transaction transaction = bitcoin.deserialize(tx.encode("hex")) # get the amount (in satoshi) the user is expected to pay amount_to_pay = int(float(self.contract["buyer_order"]["order"]["payment"]["amount"]) * 100000000) if tx not in self.received_txs: # make sure we aren't parsing the same tx twice. output_script = 'a914' + digest(unhexlify( self.contract["buyer_order"]["order"]["payment"]["redeem_script"])).encode("hex") + '87' for output in transaction["outs"]: if output["script"] == output_script: self.amount_funded += output["value"] if tx not in self.received_txs: self.received_txs.append(tx) if self.amount_funded >= amount_to_pay: # if fully funded self.timeout.cancel() self.blockchain.unsubscribe_address( self.contract["buyer_order"]["order"]["payment"]["address"], self.on_tx_received) order_id = digest(json.dumps(self.contract, indent=4)).encode("hex") if self.is_purchase: message_json = { "payment_received": { "address": self.contract["buyer_order"]["order"]["payment"]["address"], "order_id": order_id } } # update the db self.db.Purchases().update_status(order_id, 1) self.log.info("Payment for order id %s successfully broadcast to network." % order_id) else: message_json = { "new_order": { "order_id": order_id, "title": self.contract["vendor_offer"]["listing"]["item"]["title"] } } self.db.Sales().update_status(order_id, 1) self.log.info("Received new order %s" % order_id) # push the message over websockets self.ws.push(json.dumps(message_json, indent=4)) def get_contract_id(self): contract = json.dumps(self.contract, indent=4) return digest(contract) def delete(self, delete_images=True): """ Deletes the contract json from the OpenBazaar directory as well as the listing metadata from the db and all the related images in the file system. """ # build the file_name from the contract file_name = str(self.contract["vendor_offer"]["listing"]["item"]["title"][:100]) file_name = re.sub(r"[^\w\s]", '', file_name) file_name = re.sub(r"\s+", '_', file_name) file_path = DATA_FOLDER + "store/listings/contracts/" + file_name + ".json" h = self.db.HashMap() # maybe delete the images from disk if "image_hashes" in self.contract["vendor_offer"]["listing"]["item"] and delete_images: for image_hash in self.contract["vendor_offer"]["listing"]["item"]["image_hashes"]: # delete from disk image_path = h.get_file(unhexlify(image_hash)) if os.path.exists(image_path): os.remove(image_path) # remove pointer to the image from the HashMap h.delete(unhexlify(image_hash)) # delete the contract from disk if os.path.exists(file_path): os.remove(file_path) # delete the listing metadata from the db contract_hash = digest(json.dumps(self.contract, indent=4)) self.db.ListingsStore().delete_listing(contract_hash) # remove the pointer to the contract from the HashMap h.delete(contract_hash) def save(self): """ Saves the json contract into the OpenBazaar/store/listings/contracts/ directory. It uses the title as the file name so it's easy on human eyes. A mapping of the hash of the contract and file path is stored in the database so we can retrieve the contract with only its hash. Additionally, the contract metadata (sent in response to the GET_LISTINGS query) is saved in the db for fast access. """ # get the contract title to use as the file name and format it file_name = str(self.contract["vendor_offer"]["listing"]["item"]["title"][:100]) file_name = re.sub(r"[^\w\s]", '', file_name) file_name = re.sub(r"\s+", '_', file_name) # save the json contract to the file system file_path = DATA_FOLDER + "store/listings/contracts/" + file_name + ".json" with open(file_path, 'w') as outfile: outfile.write(json.dumps(self.contract, indent=4)) # Create a `ListingMetadata` protobuf object using data from the full contract listings = Listings() data = listings.ListingMetadata() data.contract_hash = digest(json.dumps(self.contract, indent=4)) vendor_item = self.contract["vendor_offer"]["listing"]["item"] data.title = vendor_item["title"] if "image_hashes" in vendor_item: data.thumbnail_hash = unhexlify(vendor_item["image_hashes"][0]) if "category" in vendor_item: data.category = vendor_item["category"] if "bitcoin" not in vendor_item["price_per_unit"]: data.price = float(vendor_item["price_per_unit"]["fiat"]["price"]) data.currency_code = vendor_item["price_per_unit"]["fiat"][ "currency_code"] else: data.price = float(vendor_item["price_per_unit"]["bitcoin"]) data.currency_code = "BTC" data.nsfw = vendor_item["nsfw"] if "shipping" not in self.contract["vendor_offer"]["listing"]: data.origin = CountryCode.Value("NA") else: data.origin = CountryCode.Value( self.contract["vendor_offer"]["listing"]["shipping"]["shipping_origin"].upper()) for region in self.contract["vendor_offer"]["listing"]["shipping"]["shipping_regions"]: data.ships_to.append(CountryCode.Value(region.upper())) # save the mapping of the contract file path and contract hash in the database self.db.HashMap().insert(data.contract_hash, file_path) # save the `ListingMetadata` protobuf to the database as well self.db.ListingsStore().add_listing(data) def verify(self, sender_key): """ Validate that an order sent over by a buyer is filled out correctly. """ try: contract_dict = json.loads(json.dumps(self.contract, indent=4), object_pairs_hook=OrderedDict) del contract_dict["buyer_order"] contract_hash = digest(json.dumps(contract_dict, indent=4)) ref_hash = unhexlify(self.contract["buyer_order"]["order"]["ref_hash"]) # verify that the reference hash matches the contract and that the contract actually exists if contract_hash != ref_hash or not self.db.HashMap().get_file(ref_hash): raise Exception("Order for contract that doesn't exist") # verify the signature on the order verify_key = nacl.signing.VerifyKey(sender_key) verify_key.verify(json.dumps(self.contract["buyer_order"]["order"], indent=4), unhexlify(self.contract["buyer_order"]["signature"])) # verify buyer included the correct bitcoin amount for payment price_json = self.contract["vendor_offer"]["listing"]["item"]["price_per_unit"] if "bitcoin" in price_json: asking_price = price_json["bitcoin"] else: currency_code = price_json["fiat"]["currency_code"] fiat_price = price_json["fiat"]["price"] request = Request('https://api.bitcoinaverage.com/ticker/' + currency_code.upper() + '/last') response = urlopen(request) conversion_rate = response.read() asking_price = float("{0:.8f}".format(float(fiat_price) / float(conversion_rate))) if asking_price > self.contract["buyer_order"]["order"]["payment"]["amount"]: raise Exception("Insuffient Payment") # verify a valid moderator was selected # TODO: handle direct payments valid_mod = False for mod in self.contract["vendor_offer"]["listing"]["moderators"]: if mod["guid"] == self.contract["buyer_order"]["order"]["moderator"]: valid_mod = True if not valid_mod: raise Exception("Invalid moderator") # verify all the shipping fields exist if self.contract["vendor_offer"]["listing"]["metadata"]["category"] == "physical good": shipping = self.contract["buyer_order"]["order"]["shipping"] keys = ["ship_to", "address", "postal_code", "city", "state", "country"] for value in map(shipping.get, keys): if value is None: raise Exception("Missing shipping field") # verify buyer ID pubkeys = self.contract["buyer_order"]["order"]["id"]["pubkeys"] keys = ["guid", "bitcoin", "encryption"] for value in map(pubkeys.get, keys): if value is None: raise Exception("Missing pubkey field") # verify redeem script chaincode = self.contract["buyer_order"]["order"]["payment"]["chaincode"] for mod in self.contract["vendor_offer"]["listing"]["moderators"]: if mod["guid"] == self.contract["buyer_order"]["order"]["moderator"]: masterkey_m = mod["pubkeys"]["bitcoin"]["key"] masterkey_v = bitcoin.bip32_extract_key(self.keychain.bitcoin_master_pubkey) masterkey_b = self.contract["buyer_order"]["order"]["id"]["pubkeys"]["bitcoin"] buyer_key = derive_childkey(masterkey_b, chaincode) vendor_key = derive_childkey(masterkey_v, chaincode) moderator_key = derive_childkey(masterkey_m, chaincode) redeem_script = '75' + bitcoin.mk_multisig_script([buyer_key, vendor_key, moderator_key], 2) if redeem_script != self.contract["buyer_order"]["order"]["payment"]["redeem_script"]: raise Exception("Invalid redeem script") # verify the payment address if self.testnet: payment_address = bitcoin.p2sh_scriptaddr(redeem_script, 196) else: payment_address = bitcoin.p2sh_scriptaddr(redeem_script) if payment_address != self.contract["buyer_order"]["order"]["payment"]["address"]: raise Exception("Incorrect payment address") return True except Exception: return False <file_sep>__author__ = 'chris' import bitcoin from binascii import unhexlify def derive_childkey(public_key, chaincode): """ Given a 33 byte public key and 32 byte chaincode (both in hex) derive the first child key. """ master_pubkey = bitcoin.bip32_serialize((bitcoin.MAINNET_PUBLIC, 0, b'\x00'*4, 0, unhexlify(chaincode), unhexlify(public_key))) child_key = bitcoin.bip32_ckd(master_pubkey, 0) return bitcoin.bip32_extract_key(child_key)
59c60121821ec19831420df6380fa05440071f50
[ "Python" ]
2
Python
jsindy/OpenBazaar-Server
aed89c95176f152b8318926517c483c2090e5969
16b4e0d18e2a537e0eb84f5b67e68934ebb12ea5
refs/heads/master
<repo_name>bradseibert/battleshipHomework<file_sep>/battleship.h #pragma once //battleship parent class #include <iostream> using namespace std; class battleship { public: battleship(int); ~battleship(); int firingpower; //function overload this into the other classes// virtual void fire() = 0; //pure virtual fuction; which makes this class abstract.// protected: private: }; <file_sep>/battleship.cpp #include "battleship.h" battleship::battleship(int fp) { firingpower = fp; //cout << "battleship constructor runs" << endl; } battleship::~battleship() { //dtor } void battleship::fire() { cout << "base class fires" << endl; }<file_sep>/Jalthy.cpp #include "Jalthy.h" Jalthy::Jalthy(int fp) : battleship(fp) { //cout << "Jalthy constructor runs" << endl; } Jalthy::~Jalthy() { //dstor } void Jalthy::fire() { cout << "Jalthy fires proton gun! firing power: " << firingpower << endl; } <file_sep>/Dolthy.h #pragma once #include <iostream> #include "battleship.h" using namespace std; class Dolthy : public battleship { public: Dolthy(int); ~Dolthy(); void fire(); protected: private: }; <file_sep>/Malthy.cpp #include "Malthy.h" Malthy::Malthy(int fp) : battleship(fp) { //cout << "Malthy constructor runs" << endl; } Malthy::~Malthy() { //dstor } void Malthy::fire() { cout << "Malthy fires proton gun & laser gun! firing power: " << firingpower << endl; }<file_sep>/main.cpp #include <iostream> #include "battleship.h" #include "Dolthy.h" #include "Jalthy.h" #include "Malthy.h" using namespace std; int main() { cout << "Hello World" << endl; cout << "----------------" << endl; battleship* arrayOfShips[3]; arrayOfShips[0] = new Malthy(44); arrayOfShips[1] = new Jalthy(22); arrayOfShips[2] = new Dolthy(22); for (int i = 0; i < 3; i++) { arrayOfShips[i]->fire(); } //battleship ship(44); //error because cannot make an object from abstract class.// } <file_sep>/Dolthy.cpp #include "Dolthy.h" Dolthy::Dolthy(int fp) : battleship(fp) { //cout << "dolthy constructor runs" << endl; } Dolthy::~Dolthy() { //dstor } void Dolthy::fire() { cout << "Dolthy fires laser gun! firing power: "<< firingpower << endl; }
d37afe9f9763083b90df5c0d780d2b5047fc2953
[ "C++" ]
7
C++
bradseibert/battleshipHomework
e14e2b2f99e4db818ff61f4d621438adcfea2b8c
91f4e699b48c0dbd7c56952d7fecd8e716293f03
refs/heads/master
<file_sep># .NETCoreWithAngular11 A sample project with .NET 5 and Angular 11 - The default project generation in Visual Studio generates **.NET 5** Projects with **Angular 8**, which requires to be manually updated to **Angular 11**. - This project is updated to **Angular 11**, so it can be used as a starting point for all **.NET 5 - Angular 11** Projects. <file_sep>using System; using IdentityServer4.EntityFramework.Options; using Microsoft.AspNetCore.ApiAuthorization.IdentityServer; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.Extensions.Options; using MinimalistToDo.Models; #nullable disable namespace MinimalistToDo.Data { public partial class ApplicationDbContext : ApiAuthorizationDbContext<ApplicationUser> { public ApplicationDbContext( DbContextOptions options, IOptions<OperationalStoreOptions> operationalStoreOptions) : base(options, operationalStoreOptions) { } //public TasksDbContext(DbContextOptions<TasksDbContext> options) // : base(options) //{ //} public virtual DbSet<Attachment> Attachments { get; set; } public virtual DbSet<Collection> Collections { get; set; } public virtual DbSet<SharedMapping> SharedMappings { get; set; } public virtual DbSet<Task> Tasks { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { optionsBuilder.UseSqlServer("Data Source=lmsystemserver.database.windows.net;Initial Catalog=ToDo;Persist Security Info=True;User ID=lmsadmin;Password=<PASSWORD>"); } } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.HasAnnotation("Relational:Collation", "SQL_Latin1_General_CP1_CI_AS"); modelBuilder.Entity<Attachment>(entity => { entity.HasNoKey(); entity.Property(e => e.CreatedDate).HasColumnType("datetime"); entity.Property(e => e.IsActive) .IsRequired() .HasDefaultValueSql("((1))"); entity.Property(e => e.Path) .IsRequired() .HasMaxLength(255) .IsUnicode(false); entity.Property(e => e.UpdatedDate).HasColumnType("datetime"); }); modelBuilder.Entity<Collection>(entity => { entity.Property(e => e.Id).ValueGeneratedNever(); entity.Property(e => e.CreatedDate).HasColumnType("datetime"); entity.Property(e => e.IsActive) .IsRequired() .HasDefaultValueSql("((1))"); entity.Property(e => e.Name) .IsRequired() .HasMaxLength(50); entity.Property(e => e.UpdatedDate).HasColumnType("datetime"); entity.Property(e => e.UserId) .IsRequired() .HasMaxLength(450); entity.HasOne(d => d.User) .WithMany(p => p.Collections) .HasForeignKey(d => d.UserId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_Collections_Users"); }); modelBuilder.Entity<SharedMapping>(entity => { entity.Property(e => e.Id).ValueGeneratedNever(); entity.Property(e => e.CreatedDate).HasColumnType("datetime"); entity.Property(e => e.IsActive) .IsRequired() .HasDefaultValueSql("((1))"); entity.Property(e => e.SharedUserId) .IsRequired() .HasMaxLength(450); entity.Property(e => e.UpdatedDate).HasColumnType("datetime"); entity.HasOne(d => d.SharedCollection) .WithMany(p => p.SharedMappings) .HasForeignKey(d => d.SharedCollectionId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_SharedMappings_Collections"); entity.HasOne(d => d.SharedUser) .WithMany(p => p.SharedMappings) .HasForeignKey(d => d.SharedUserId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_SharedMappings_AspNetUsers"); }); modelBuilder.Entity<Task>(entity => { entity.Property(e => e.Id).ValueGeneratedNever(); entity.Property(e => e.CreatedDate).HasColumnType("datetime"); entity.Property(e => e.Description).HasMaxLength(4000); entity.Property(e => e.DueDate).HasColumnType("datetime"); entity.Property(e => e.IsActive) .IsRequired() .HasDefaultValueSql("((1))"); entity.Property(e => e.Priority) .HasColumnType("decimal(3, 2)") .HasDefaultValueSql("((0.00))"); entity.Property(e => e.ReminderDate).HasColumnType("datetime"); entity.Property(e => e.Title) .IsRequired() .HasMaxLength(60); entity.Property(e => e.UpdatedDate).HasColumnType("datetime"); entity.HasOne(d => d.Collection) .WithMany(p => p.Tasks) .HasForeignKey(d => d.CollectionId) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_Tasks_Collections"); }); OnModelCreatingPartial(modelBuilder); } partial void OnModelCreatingPartial(ModelBuilder modelBuilder); } } <file_sep>using System; using System.Collections.Generic; #nullable disable namespace MinimalistToDo.Models { public partial class Task { public Guid Id { get; set; } public string Title { get; set; } public string Description { get; set; } public DateTime? ReminderDate { get; set; } public DateTime? DueDate { get; set; } public byte Progress { get; set; } public decimal Priority { get; set; } public Guid CollectionId { get; set; } public short HoursWorked { get; set; } public bool IsCompleted { get; set; } public byte? AttachmentId { get; set; } public bool IsSubtask { get; set; } public Guid? ParentId { get; set; } public DateTime CreatedDate { get; set; } public DateTime? UpdatedDate { get; set; } public bool? IsActive { get; set; } public virtual Collection Collection { get; set; } } } <file_sep>using System; using System.Collections.Generic; #nullable disable namespace MinimalistToDo.Models { public partial class Collection { public Collection() { SharedMappings = new HashSet<SharedMapping>(); Tasks = new HashSet<Task>(); } public Guid Id { get; set; } public string Name { get; set; } public string UserId { get; set; } public DateTime CreatedDate { get; set; } public DateTime? UpdatedDate { get; set; } public bool? IsActive { get; set; } public virtual AspNetUser User { get; set; } public virtual ICollection<SharedMapping> SharedMappings { get; set; } public virtual ICollection<Task> Tasks { get; set; } } }
630847cb703fd435175d804e0c928b1c134cdad6
[ "Markdown", "C#" ]
4
Markdown
me-heer/.NETCoreWithAngular11
3e460bb1cc272deedc32f1e9276549dc52a6a8d2
fbf608d24ee62cba438e4b88a45eff25e69e156b
refs/heads/master
<file_sep>import numpy as np import random from optimal_port_decisions import * from indices_list import * import itertools import csv import time import pandas as pd import os def find_cik(cik_df, ticker): return list(cik_df[cik_df.iloc[:, 1] == ticker].CIK)[0] def read_txt(file): with open(file, 'r') as file_r: reader = csv.reader(file_r, delimiter="\t") return list(reader) def find_compy_report(sub_dat, comp_cik, report): '''returns adsh''' for line in sub_dat: if (line[1] == str(comp_cik)) and (line[25] == report): return line[0] def find_report_dat(num_dat, adsh, year_qrts, qtr_date): report = [] for line in num_dat: if (line[0] == adsh) and (line[4] == year_qrts.get(qtr_date)): report.append(line) return report qtrly_dat = 'C:\\Users\\Jeff\\Documents\\Trading\\Python\\Data\\Quarterly_data\\' cik_dat = qtrly_dat + 'cik_ticker.csv' tickers = set(sp_500 + sp_600) periods = ['2020q1', '2020q2', '2018q1', '2018q2', '2018q3', '2018q4', '2016q1', '2016q2', '2016q3', '2016q4'] def main(): csv.field_size_limit(100000000) cik_df = pd.read_csv(cik_dat) for period in periods: print(period) year_sub = qtrly_dat + period + '\\' + 'sub.txt' year_num = qtrly_dat + period + '\\' + 'num.txt' try: sub_d = read_txt(year_sub) num_d = read_txt(year_num) for tick in tickers: print(period, tick) try: cik = find_cik(cik_df, tick) adsh = find_compy_report(sub_d, cik, '10-Q') report = [] for line in num_d: if (line[0] == adsh): report.append(line) file = qtrly_dat + 'stock_data\\' + tick + '_qrtly.txt' with open(file, 'a') as file_a: for line in report: file_a.write('\n %s' % line) file_a.close() print('appended') except: print('cik not found') finally: if (type(year_sub) is not str) or (type(year_num) is not str): year_sub.close() year_num.close() if __name__ == '__main__': main()<file_sep>import numpy as np import pandas as pd from datetime import datetime, timedelta from random import uniform class Portfolio: def __init__(self, name): self.name = name self.purse = 0 self.pnl = 0 self.pos_val = 0 self.port_val = 0 self.holdings = {} def add_holding(self, _holding): self.holdings[_holding.name] = _holding def get_val(self, date): for x in self.holdings: self.holdings[x].curr_hold_dat(date) self.pos_val = sum([self.holdings[x].curr_val for x in self.holdings]) self.purse = sum([self.holdings[x].cash for x in self.holdings]) + \ sum([self.holdings[x].dividends for x in self.holdings]) self.port_val = self.purse + self.pos_val def get_data(self, tick, dat_loc, start): t_hold = Holding(tick, 0) t_hold.get_df(dat_loc) t_hold.get_year_before(start) self.add_holding(t_hold) def print_dat(self, date): self.get_val(date) inv = [['name', 'curr_price', 'pos', 'hold_cash', 'allocation']] for hold in self.holdings: inv.append([str(x) for x in [self.holdings[hold].name, self.holdings[hold].curr_price, self.holdings[hold].curr_pos, self.holdings[hold].cash, self.holdings[hold].allo]]) inv.append(['', 'port_purse', 'port_pos_val', 'port_val']) inv.append([str(x) for x in ['Portfolio', self.purse, self.pos_val, self.port_val]]) colwidth = max(len(word) for row in inv for word in row[:-1]) + 2 for row in inv: print("".join(word.ljust(colwidth) for word in row)) print(" ") def print_res(self, date): self.get_val(date) res = [['', 'port_purse', 'port_pos_val', 'port_val']] res.append([str(x) for x in ['Portfolio', self.purse, self.pos_val, self.port_val]]) colwidth = max(len(word) for row in res for word in row[:-1]) + 2 for row in res: print("".join(word.ljust(colwidth) for word in row)) print(" ") class Holding: def __init__(self, ticker, cash): self.name = ticker self.cash = cash self.curr_pos = 0 self.curr_price = 0 self.curr_val = 0 self.side = None self.pnl = 0 self.allo = 0 self.trades = [] self.df = None self.year_before = [] self.daily_ret = [] self.dividends = 0 self.dividend_dat = [] def get_df(self, data_loc): df = pd.read_csv(data_loc + self.name + '.csv', usecols=['date', '5. adjusted close', '7. dividend amount']) df.iloc[:, 0] = [pd.to_datetime(x).date() for x in df.iloc[:, 0]] self.df = df def trade(self, date, pos): self.curr_hold_dat(date) self.trades.append(Trade(date, pos, self.curr_price)) self.curr_pos += pos self.cash -= self.curr_price * pos def check_div(self, date): if len(self.trades) > 0: last_trade_dt = self.trades[-1].date if last_trade_dt: check_df = self.df[(self.df.iloc[:, 0] >= last_trade_dt) & (self.df.iloc[:, 0] <= date)] if any(check_df[check_df.iloc[:, 2] > 0]): check_df = check_df[check_df.iloc[:, 2] > 0] for r in check_df.iloc[:, 2]: if r > 0: self.dividends += r def print_hold_dat(self): inv = [['Stock', 'Pos', 'Curr Price', 'Val', 'Allocation']] colwidth = max(len(word) for row in inv for word in row[:-1]) + 2 inv.append([str(x) for x in [self.name, self.curr_pos, self.curr_price, self.curr_val, self.allo]]) for row in inv: print("".join(word.ljust(colwidth) for word in row)) def curr_hold_dat(self, date): self.curr_price = self.df[self.df.iloc[:, 0] == date].iloc[0, 1] self.curr_val = self.curr_pos * self.curr_price self.check_div(date) if self.curr_pos > 0: self.side = 'long' elif self.curr_pos < 0: self.side = 'short' else: self.side = 'flat' def day_close(self, date): self.curr_price = self.df[self.df.iloc[:, 0] == date].iloc[0, 1] return self.curr_price def get_year_before(self, start): year_before_df = self.df[(self.df.iloc[:, 0] <= pd.to_datetime(start).date())] self.year_before = year_before_df.iloc[252:505, 1] self.dividend_dat = sum(year_before_df.iloc[252:505, 2])/self.year_before.iloc[-252] self.daily_ret = np.log(self.year_before) - np.log(self.year_before.shift(1)) self.daily_ret.append(pd.Series(self.dividend_dat)) def holding_reset(self): self.cash = 0 self.curr_pos = 0 self.curr_price = 0 self.curr_val = 0 self.side = None self.pnl = 0 self.allo = 0 self.trades = [] self.dividends = 0 class Trade: def __init__(self, date, trade_pos, decision_price): self.date = date self.trade_pos = trade_pos self.dec_price = decision_price self.trade_val = self.trade_pos * self.dec_price def find_trade(self, date): if self.date == date: return self.trade_val, self.date def print_trade_dat(self): inv = [['Date', 'Pos', 'Decision Price', 'Val']] colwidth = max(len(word) for row in inv for word in row[:-1]) + 2 inv.append([str(x) for x in [self.date, self.trade_pos, self.dec_price, self.trade_val]]) for row in inv: print("".join(word.ljust(colwidth) for word in row)) <file_sep>import numpy as np import random import pandas as pd from port_inventory import * import itertools import cProfile, pstats, io from numba import njit, jit import gc, os import matplotlib.pyplot as plt #Slow def make_ret_mat(port, tickers): day_ret_mat = [] ann_rets = [] for tick in tickers: day_ret_mat.append(np.array(port.holdings[tick].daily_ret)[1:]*100) ann_rets.append(get_ann_ret(port.holdings[tick].daily_ret)) day_ret_mat = np.array(day_ret_mat) ann_rets = np.array(ann_rets).transpose() return day_ret_mat, ann_rets def get_ann_ret(ret_list): ret_list = [x+1 for x in ret_list] ret = np.nanprod(ret_list)-1 return ret*100 def weight_cov(weights): return [weights, np.outer(weights, weights)] def create_weights(num_in_port, iters): weights = [] l, h = [1, 2] for i in range(0, int(iters * .8)): group_1 = [random.uniform(0, 1) for x in range(0, num_in_port)] weights.append([group_1[x] / sum(group_1) for x in range(0, len(group_1))]) for i in range(int(iters * .8), int(iters * .9)): group_2 = [random.uniform(l, h) for x in [1]] + [random.uniform(0, 1) for x in range(0, num_in_port - 1)] weights.append([group_2[x] / sum(group_2) for x in range(0, len(group_2))]) for i in range(int(iters * .9), int(iters)): group_3 = [random.uniform(l, h) for x in [1, 2]] + [random.uniform(0, 1) for x in range(0, num_in_port - 2)] weights.append([group_3[x] / sum(group_3) for x in range(0, len(group_3))]) weights = np.array([np.array(l) for l in weights]) return [*map(weight_cov, weights)] def create_weights_w_allo(num_in_port, iters, given_weights): allos = [] for g in range(0, len(given_weights)): if given_weights[g] > 0: allos.append([g, given_weights[g]]) num_in_port -= len(allos) weights = [] l, h = [1, 2] for i in range(0, int(iters * .8)): group_1 = [random.uniform(0, 1) for x in range(0, num_in_port)] weights.append([group_1[x]/sum(group_1) for x in range(0, len(group_1))]) for i in range(int(iters * .8), int(iters * .9)): group_2 = [random.uniform(l, h) for x in [1]] + [random.uniform(0, 1) for x in range(0, num_in_port - 1)] weights.append([group_2[x]/sum(group_2) for x in range(0, len(group_2))]) for i in range(int(iters * .9), int(iters)): group_3 = [random.uniform(l, h) for x in [1, 2]] + [random.uniform(0, 1) for x in range(0, num_in_port - 2)] weights.append([group_3[x]/sum(group_3) for x in range(0, len(group_3))]) w_allo = [] for wts in weights: for al in allos: wts.insert(*al) w_sum = sum(wts) w_allo.append([w/w_sum for w in wts]) weights = np.array([np.array(l) for l in w_allo]) return [*map(weight_cov, weights)] def weight_cov_mat(weight_cov, cov_mat): return np.matmul(weight_cov, cov_mat) def get_slope(exp_ret, std, risk_free): return (exp_ret-risk_free)/std def find_best_slope(slope_list, iterations): slopes = [x[3] for x in slope_list] high = np.unique(slopes)[int(iterations*.999)] max_s = [x for x in range(0, len(slopes)) if slopes[x] == high] return slope_list[max_s[0]] def create_port_dict(tickers, best_weights): labels = tickers + ['exp_ret', 'std_dev'] weights = [i for i in best_weights[0]] port_data = weights + best_weights[1:] port_dict = dict(zip(labels, port_data)) return port_dict def find_optimal_ports(port, combo, weight_cov, begin_stocks, iterations, risk_free): ##create all combinations of world of tickers print(combo) select_ticks = [i for i in combo] tickers = begin_stocks + select_ticks day_ret_mat, ann_rets = make_ret_mat(port, tickers) '''from a list of beginning stocks, find those stocks with the closest to zero from abs correlation values''' cov_mat = np.cov(day_ret_mat) data_result = [] for wts in weight_cov: ##multiply weights by ret for expected return ##possibly assign randomly multiple times in order to maximize computing efficiency exp_ret = np.dot(np.array(wts[0]), ann_rets) # find port variance w_cov_mat = weight_cov_mat(wts[1], cov_mat) port_var = np.sqrt(np.sum(w_cov_mat))*np.sqrt(len(day_ret_mat)) slope = get_slope(exp_ret, port_var, risk_free) data = [wts[0], exp_ret, port_var, slope] data_result.append(data) best_wts = find_best_slope(data_result, iterations) port_dict = create_port_dict(tickers, best_wts) return port_dict <file_sep>from datetime import datetime import datetime as dt import os import pandas as pd from alpha_vantage.timeseries import TimeSeries from alpha_vantage.cryptocurrencies import CryptoCurrencies import stat from indices_list import * import sched,time, threading symbols = test_port market = 'USD' function = 'TIME_SERIES_DAILY_ADJUSTED' interval = '5min' datatype = 'csv' api_key1 = "TS943WP11EVAK281" api_key2 = "<KEY>" api_key = api_key1 data_path = 'C:\\Users\\Jeff\\Documents\\Trading\\Python\\Data\\Alpha_vantage\\port_creator_dat\\' api_url = "https://www.alphavantage.co/query" outputsize = 'full' columns = {'data', '1. open', '2. high', '3. low', '4. close', '5. adjusted close','6. volume'} '''date', '1. open', '2. high', '3. low', '4. close', '5. adjusted close', '6. volume', '7. dividend amount', '8. split coefficient''' age = 2 wait = 55 def main(): if not os.path.exists(data_path + function): os.mkdir(data_path + function) refresh = [] for symbol in symbols: if os.path.exists(data_path + function + '\\' + symbol + '.csv'): filestatsobj = os.stat(data_path + function + '\\' + symbol + '.csv') modified_time = time.ctime(filestatsobj[stat.ST_MTIME]) print('File: ', str(symbol)) print('Modified Time: ', modified_time) time_dif = datetime.now() - pd.to_datetime(modified_time) print('File Age: ', time_dif) if time_dif > dt.timedelta(hours=age): refresh.append(symbol) else: refresh.append(symbol) i = 0 missing_downloads = [] print('Downloading %s Files' % len(refresh)) while i <= len(refresh) & (len(refresh)-i > 0): for symbol in refresh: try: if function == 'TIME_SERIES_INTRADAY': if not os.path.exists(data_path + function + '\\' + interval): os.mkdir(data_path + function + '\\' + interval) file_to_save = data_path + function + '\\' + interval + '\\' + symbol + '.csv' ts = TimeSeries(key=api_key, output_format='pandas') data, meta_data = ts.get_intraday(symbol=symbol, interval=interval, outputsize=outputsize) data['date'] = data.index data.index = list(range(0,len(data.index))) data = data[['date','1. open','2. high','3. low','4. close','5. volume']] if os.path.exists(data_path + function + '\\' + interval + '\\' + symbol + '.csv'): temp_df = pd.read_csv(data_path + function + '\\' + interval + '\\' + symbol + '.csv') temp_df = temp_df[['date','1. open','2. high','3. low','4. close','5. volume']] data = data.append(temp_df) data.drop_duplicates(inplace=True) data = data.sort_index() data.to_csv(file_to_save) print('Data saved to : %s' % file_to_save) else: data.to_csv(file_to_save) print('Data saved to : %s' % file_to_save) elif function == 'TIME_SERIES_DAILY_ADJUSTED': file_to_save = data_path + function + '\\' + symbol + '.csv' ts = TimeSeries(key=api_key, output_format='pandas') data, meta_data = ts.get_daily_adjusted(symbol=symbol, outputsize=outputsize) data.to_csv(file_to_save) print('Data saved to : %s' % file_to_save) elif function == 'DIGITAL_CURRENCY_DAILY': file_to_save = data_path + function + '\\' + symbol + '.csv' cc = CryptoCurrencies(key=api_key2, output_format='pandas') data, meta_data = cc.get_digital_currency_daily(symbol = symbols, market=market) data.to_csv(file_to_save) print('Data saved to : %s' % file_to_save) else: print('Edit Code for new data') i += 1 if i == len(refresh): pass if (i % 5 == 0): print('Waiting %s seconds' % wait) print('%s Completed, %s Remain' % (i, (len(refresh)) - i)) print(str(datetime.now())) print('Approximately %s Minutes Until Complete' % str(round((len(refresh)-i)/5*wait/60,1))) time.sleep(wait) else: pass except ValueError: print(str(symbol), ' Not Found') missing_downloads.append(symbol) except KeyError: print('Keyerror, waiting %s seconds' % '10') time.sleep(10) print('Download Complete') print('Missing Symbols: ', missing_downloads) names, df_list, missing = [],[],[] for symbol in symbols: names.append(symbol) try: n = pd.read_csv(data_path + function + '\\' + symbol +'.csv') df_list.append(n) except FileNotFoundError: print(str(symbol),' is missing.') missing.append(symbol) names.sort() print(names, 'Loaded') print(missing, 'Missing') tickers = [] for x, y in zip(names, df_list): globals()[x] = y tickers.append(globals()[x]) missing_downloads = pd.DataFrame(missing_downloads) missing_downloads.to_csv(data_path + function + '\\' + 'missing.csv') if __name__ == '__main__': main()<file_sep>from port_inventory import * from indices_list import * from optimal_port_decisions import * from tools import * import pandas as pd import random import matplotlib.pyplot as plt import itertools dat_loc = 'C:\\Users\\Jeff\\Documents\\Trading\\Python\\Data\\Alpha_vantage\\port_creator_dat\\' \ 'TIME_SERIES_DAILY_ADJUSTED\\' world = random.sample(list(set(sp_600)), 400) tick_group = 'sp600' # world = list(set(sp_600)) begin_stocks_dict = tda_paper_port total_in_port = 12 start_cash = 1000000 risk_free = .018 iterations = [40000] start = pd.to_datetime("2019-09-27").date() end = pd.to_datetime("2020-09-29").date() trade_date = ['2019-12-02', '2020-01-06', '2020-02-03', '2020-03-02', '2020-04-06', '2020-05-04', '2020-06-01', '2020-07-06', '2020-08-03', '2020-09-25'] trade_dates = [pd.to_datetime(x).date() for x in trade_date] def main(): pr = start_profile() df = pd.read_csv(dat_loc + 'INTU' + '.csv') strt, nd = [pd.to_datetime(x).date() for x in [start, end]] df.iloc[:, 0] = [pd.to_datetime(x).date() for x in df.iloc[:, 0]] #remove already in port from sample group begin_stocks = [k for k, v in begin_stocks_dict.items()] tickers = [item for item in world if item not in begin_stocks] given_weights = [v for k, v in begin_stocks_dict.items()] for tick in list(tickers): if not os.path.exists(dat_loc + tick + '.csv'): tickers.remove(tick) print(tick, 'Not Found') else: print(tick, 'File Found') data_port = Portfolio('data_port') print('Loading sample stocks') for tick in list(tickers): data_port.get_data(tick, dat_loc, start) if data_port.holdings[tick].name in data_port.holdings: print(tick, 'tick data exists') if (len(data_port.holdings[tick].df.index)) <= 600 or \ (trade_dates[-1] not in list(data_port.holdings[tick].df.date)): tickers.remove(tick) print(tick, 'Removed from sample') else: tickers.remove(tick) print('Loading port stocks') for tick in begin_stocks: data_port.get_data(tick, dat_loc, start) if total_in_port - len(begin_stocks) >= 2: tick_combos = itertools.combinations(tickers, total_in_port - len(begin_stocks)) tick_combos = [i for i in tick_combos] else: tick_combos = tickers full_res_dict = {} i = 0 co = 0 weight_covs = [*map(lambda x: create_weights_w_allo(total_in_port, x, given_weights), iterations)] for combo in tick_combos: port = Portfolio('main') if type(combo) != str: combo_1 = [c for c in combo] else: combo_1 = [combo] for tick in combo_1 + begin_stocks: port.add_holding(data_port.holdings[tick]) for itr in range(0, len(iterations)): working_dict = find_optimal_ports(port, combo_1, weight_covs[itr], begin_stocks, iterations[itr], risk_free) # print(working_dict) print('Combo: %s/%s Iterations: %s' % (co, len(tick_combos), iterations[itr])) dict_list = [[tick, cash] for tick, cash in working_dict.items()] for pair in dict_list[0:total_in_port]: tick = pair[0] allo = pair[1] port.holdings[tick].holding_reset() port.holdings[tick].cash = allo * start_cash port.holdings[tick].allo = round(allo,4)*100 pos = int(port.holdings[tick].cash/port.holdings[tick].day_close(start)) port.holdings[tick].trade(start, pos) port.print_res(trade_dates[-1]) res = [port.purse, port.pos_val, port.port_val] res_dict = dict(zip(['port_purse', 'port_pos_val', 'port_val'],res)) new_dict = {**working_dict, **res_dict} full_res = [[key, val] for key,val in new_dict.items()] temp_dict = {} for pair in full_res: temp_dict.update({pair[0]: pair[1]}) full_res_dict[i] = temp_dict if co % 1000 == 0: save_res_dict(full_res_dict, world, total_in_port, tick_group) i += 1 co += 1 save_res_dict(full_res_dict, world, total_in_port, tick_group) # marg_df.to_csv('marg_iter_improv.csv') finish_profile(pr, 'main_profile.csv') if __name__ == '__main__': main()<file_sep>import cProfile, pstats, io from optimal_port_decisions import * import json import pandas as pd import numpy as np import matplotlib.pyplot as plt def start_profile(): pr = cProfile.Profile() pr.enable() return pr def finish_profile(pr, output_name): pr.disable() result = io.StringIO() pstats.Stats(pr, stream=result).print_stats() result = result.getvalue() # chop the string into a csv-like buffer result = 'ncalls' + result.split('ncalls')[-1] result = '\n'.join([','.join(line.rstrip().split(None, 5)) for line in result.split('\n')]) # save it to disk with open(str(output_name), 'w+') as f: f.write(result) f.close() def save_res_dict(full_res_dict, world, total_in_port, tick_group): with open('res_df' + '_' + str(len(world)) + '_' + tick_group + '_' + str(total_in_port) + '.json', 'w') as fp: json.dump(full_res_dict, fp) fp.close() def parse_res_dict(dat_loc, json_res, risk_free, gspc_list, plot=False): with open(dat_loc + json_res + '.json', 'r') as fp: data = json.load(fp) ret_sharp = [] df_list = [] for i in range(0, len(data)): work_dict = data[str(i)] work_dict['sharpe'] = (work_dict['exp_ret'] - risk_free)/work_dict['std_dev'] r_s = [i, work_dict['exp_ret'], work_dict['std_dev'], work_dict['sharpe'], work_dict['port_val']] keys = [[k for k, v in work_dict.items()]] values = [v for k, v in work_dict.items()] key_val = keys + values df_list.append(key_val) ret_sharp.append(r_s) col_names = ['stocks'] + ['stock_' + str(i) for i in range(0, int(json_res.split("_")[-1]))] col_names = col_names + ['exp_ret', 'std_dev', 'port_purse', 'port_pos_val', 'port_val', 'sharpe'] df = pd.DataFrame(df_list, columns=col_names) df.to_csv(dat_loc + json_res + '.csv', index=False) print(len(df.index)) print(df.head()) if plot: ret, _, sharpe = gspc_list ret = (ret+1)*1000000 x = np.array([i[3] for i in ret_sharp]) y = np.array([i[4] for i in ret_sharp]) plt.scatter(x, y) plt.scatter(sharpe, ret, c='red') plt.xlabel('Sharpe') plt.ylabel('Expected Return') plt.show() def prep_gspc_df(dat_loc, risk_free, start, end): gspc_df = pd.read_csv(dat_loc + '^GSPC.csv', usecols=['Date', 'Adj Close']) gspc_df.Date = [pd.to_datetime(x).date() for x in gspc_df.Date] gspc_df = gspc_df[(gspc_df.Date >= start) & (gspc_df.Date <= end)] rets = gspc_df.iloc[:, 1] rets = np.log(rets) - np.log(rets).shift(1) ret = get_ann_ret(rets)/100 std = np.std(rets)*np.sqrt(len(rets)) sharpe = (ret - risk_free)/std return [ret, std, sharpe] <file_sep># Equity Portfolio Tracker and Allocation Optimizer This is one of my first complete python projects. The motivation behind the project was to use historical prices to help me better allocate funds across holdings. I intend to build out other projects that help suggest equities that would improve a portfolio using a variety of techniques, including simple Value Investing, momentum, and knn credit worthiness. This project and readme is under development.
e42f745d787012d6fc23d6a7375d371ea42f6f2d
[ "Markdown", "Python" ]
7
Python
jmdubish1/portfolio_tracker
6be54f237d078d4761429c6a999fb42c68b1e8f0
0cdaa909980ed44539e40f1fdbd0a06dbd04d2c2
refs/heads/master
<file_sep>/******************************************************************************************************************************************************** Title: testTrees Author: <NAME> Created: October 15, 2014 Purpose:This program fills up a tree of your choice(BST, AVL, LazyBST, LazyAVL) and tests it. A myriad of statistics are given, for that tree. Build with: g++ -o testTrees testTrees.cpp Remember! All header files below contain their implementations! ********************************************************************************************************************************************************/ #include <string> #include <vector> #include <iostream> #include <fstream> #include <stack> #include <cmath> #include "sequenceMap.h" #include "BSTDNA.h" #include "AVLDNA.h" #include "BSTLAZYDNA.h" #include "AVLLAZYDNA.h" using namespace std; void fileCheck(ifstream& file);//checks if the file name is valid. template <class T> void fillTree(T& root, ifstream& file);//fills the tree using the file stream. bool checkForLegality(string thisLine);//checks if a string ends in //; a legal string to be used. template <class T> void createSequenceMaps(BinarySearchTree& root, string thisLine);//creates a sequenceMap using the data in thisLine template <class T> void evacuateEveryOtherItem(T& root, string fileName); template <class T> void querySequences(T root, string fileName);//Queries using the file name specified by fileName void flipString(string& tobeFlipped); float calculateRatio(float n, float depth);//calculates the ratio of avg depth/log2(n) int main( int argc, char *argv[] ) { float n = 0, depth = 0; string fileName = argv[1]; string query = argv[2]; sequenceMap queryContainer; ifstream rebase210(fileName); fileCheck(rebase210); //If the parameter matches the if statement, that version of the code will run. string datatype = argv[3]; if(datatype == "BST" ){ BinarySearchTree database; fillTree<BinarySearchTree>(database, rebase210); cout << "calls to insert: " << database.returnInsertionCalls() << endl; n = database.numberOfNodes(); cout << "n, number of nodes is: " << n << endl; depth = database.depth(); cout << "the average depth is: " << depth/n << endl; cout << "The ratio of the average depth to log2("<< n << ") is: " << calculateRatio(n, depth) << endl; cout << "Querying using the specified file..." << endl; querySequences<BinarySearchTree>(database, query); //database.resetContainsCalls(); cout << "Removing every other sequence in your specified file " << endl; evacuateEveryOtherItem<BinarySearchTree>(database, query); n = database.numberOfNodes(); cout << "n, number of nodes after deletion is: " << n << endl; depth = database.depth(); cout << "the average depth, after removal, is: " << depth/n << endl; cout << "The ratio of the average depth to log2("<< n << ") is: " << calculateRatio(n, depth) << endl; querySequences<BinarySearchTree>(database, query); } else if(datatype == "AVL" ){ AvlTree database; fillTree<AvlTree>(database, rebase210); cout << "calls to insert: " << database.returnInsertionCalls() << endl; n = database.numberOfNodes(); cout << "n, number of nodes is: " << n << endl; depth = database.depth(); cout << "the average depth is: " << depth/n << endl; cout << "The ratio of the average depth to log2("<< n << ") is: " << calculateRatio(n, depth) << endl; cout << "Querying using the specified file..." << endl; querySequences<AvlTree>(database, query); database.resetContainsCalls(); cout << "Removing every other sequence in your specified file " << endl; evacuateEveryOtherItem<AvlTree>(database, query); n = database.numberOfNodes(); cout << "n, number of nodes after deletion is: " << n << endl; depth = database.depth(); cout << "the average depth, after removal, is: " << depth/n << endl; cout << "The ratio of the average depth to log2("<< n << ") is: " << calculateRatio(n, depth) << endl; cout << "items in the tree: " << endl; querySequences<AvlTree>(database, query); } else if(datatype == "LazyBST" ) { LazyBinarySearchTree database; fillTree<LazyBinarySearchTree>(database, rebase210); cout << "calls to insert: " << database.returnInsertionCalls() << endl; n = database.numberOfNodes(); cout << "n, number of nodes is: " << n << endl; depth = database.depth(); cout << "the average depth is: " << depth/n << endl; cout << "The ratio of the average depth to log2("<< n << ") is: " << calculateRatio(n, depth) << endl; cout << "Querying using the specified file..." << endl; querySequences<LazyBinarySearchTree>(database, query); database.resetContainsCalls(); cout << "Removing every other sequence in your specified file " << endl; evacuateEveryOtherItem<LazyBinarySearchTree>(database, query); n = database.numberOfNodes(); cout << "n, number of nodes after deletion is: " << n << endl; depth = database.depth(); cout << "the average depth, after removal, is: " << depth/n << endl; cout << "The ratio of the average depth to log2("<< n << ") is: " << calculateRatio(n, depth) << endl; querySequences<LazyBinarySearchTree>(database, query); } else if(datatype == "LazyAVL") { LazyAvlTree database; fillTree<LazyAvlTree>(database, rebase210); cout << "calls to insert: " << database.returnInsertionCalls() << endl; n = database.numberOfNodes(); cout << "n, number of nodes is: " << n << endl; depth = database.depth(); cout << "the average depth is: " << depth/n << endl; cout << "The ratio of the average depth to log2("<< n << ") is: " << calculateRatio(n, depth) << endl; cout << "Querying using the specified file..." << endl; cout << "average depth is " << n << "/" << "logbase2(" << n << ") =" << calculateRatio(n, depth) << endl; cout << "Querying using the specified file..." << endl; querySequences<LazyAvlTree>(database, query); database.resetContainsCalls(); cout << "Removing every other sequence in your specified file " << endl; evacuateEveryOtherItem<LazyAvlTree>(database, query); n = database.numberOfNodes(); cout << "n, number of nodes after deletion is: " << n << endl; depth = database.depth(); cout << "the average depth, after removal, is: " << depth/n << endl; cout << "The ratio of the average depth to log2("<< n << ") is: " << calculateRatio(n, depth) << endl; querySequences<LazyAvlTree>(database, query); } else cout << "Parameter flag not valid" << endl; rebase210.close(); return 0; } //simply put, this function will check if the file is within the same directory as the executable. //Otherwise, the program will end, prompting the changing of location of the file. void fileCheck(ifstream& file) { if(file.fail()) { cerr << "Input file could not be opened. Check if the file is in the same directory" << " as the executable.\n"; exit(1); } } //Using the already opened file stream, this will fill up the tree with the data inside template <class T> void fillTree(T& root, ifstream& file) { string currentLine; bool firstLineFound = 0; while(file>>currentLine) { firstLineFound = checkForLegality(currentLine); if(firstLineFound){ createSequenceMaps(root, currentLine); } } } //A simple check. Since we parse files line by line, we will check if the string ends in //, the accepted format of the recog. sequence. bool checkForLegality(string thisLine) { if(thisLine[thisLine.size() - 2] == '/' && thisLine[(thisLine.size() - 1)] == '/') return true; else return false; } //Using a stack, we create, then insert, a sequenceMap for the current line obtained from filltree template <class T> void createSequenceMaps(T& root, string thisLine) { int currentPos = 0; stack<char> acronym; acronym.push(thisLine[currentPos]);//We insert the string character by character. currentPos++; while(!(acronym.top() == '/'))//Until we spot a /, we will keep inserting characters into our stack { acronym.push(thisLine[currentPos]); currentPos++; } acronym.pop();//We'll pop the / that we received at the end of our while loop. string acronymString; while(!(acronym.empty()))//We pop our string out; it will be backwards. Bear with me. { acronymString += acronym.top(); acronym.pop(); } flipString(acronymString);//We will flip the string obtained from the stack. string sequenceKey; sequenceMap current; current.updateEnzyme_Acronyms(acronymString);//The acronym obtained from the beginning is appended to all sequences do{ //We will search for recognition sequences, up until the final // is encountered. if(!(thisLine[currentPos] == '/' && thisLine[currentPos+1] == '/')) acronym.push(thisLine[currentPos]); else break; currentPos++; while(!(acronym.top() == '/'))//We will search for recognition sequences, up until the final // is encountered. { acronym.push(thisLine[currentPos]); currentPos++; } acronym.pop();//After we find a recognition sequence, we will pop the final / out before the next string. while(!(acronym.empty())) { sequenceKey += acronym.top(); acronym.pop(); } flipString(sequenceKey);//We flip after we pop. current.updateRecognitionSequence(sequenceKey);//We will insert the obtained sequence into an object root.insert(current);//it will be inserted into the tree. sequenceKey.clear(); }while(!(thisLine[currentPos-1] == '/' && thisLine[currentPos] == '/')); } //Exactly what its name is. void flipString(string& tobeFlipped) { char next; string newString; for(int i = tobeFlipped.size()-1; i >= 0 ; i--) { next = tobeFlipped[i]; newString += next; } tobeFlipped = newString; } //Using a file, we will parse through the tree, searching for the sequences. //Assumed is a file with only sequences, and an empty line at the end. template <class T> void querySequences(T root, string fileName) { int successes = 0; ifstream queries(fileName); fileCheck(queries); string current; sequenceMap container; while(queries >> current) { container.updateRecognitionSequence(current); if(root.contains(container))successes++; } int recursiveCalls = 0; recursiveCalls = root.returnContainsCalls(); cout << "Number of recursive accesses: " << recursiveCalls <<endl; cout << "Number of successes: " << successes << endl; queries.close(); } //This will evacuate every other item. If the number is NOT divisible by 2, that is a sequence we will remove template <class T> void evacuateEveryOtherItem(T& root, string fileName) { root.resetContainsCalls(); ifstream queries(fileName); fileCheck(queries); int counter = 0; string current; sequenceMap container; while(queries >> current) { //cout << "item to be evacuated: " << current << endl; if(!root.isEmpty()) { container.updateRecognitionSequence(current); if(counter % 2 != 0)root.remove(container); counter++; } } queries.close(); cout << "Remove calls made: " << root.returnRemoveCalls() << endl; cout << "Successful removes: " << root.returnSuccessfulRemoves() << endl; } //The ratio is calculated. float calculateRatio(float n, float depth) { float averageDepth = depth/n; float logbase2n = log(n); logbase2n = logbase2n/log(2); float ratio = averageDepth/logbase2n; return ratio; } <file_sep>/******************************************************************************************************************************************************** Title: BSTDNA Author: <NAME>(With modifications on the code by <NAME>) Created: October 15, 2014 Purpose:A BST tree specifically designed to handle the sequenceMap data type Build with: g++ -o programname "Your_Main_Function_Holding_File_Here".cpp Given that this is simply a header with implementations inside, just include in your main function file. ********************************************************************************************************************************************************/ #ifndef BINARY_SEARCH_TREE_H #define BINARY_SEARCH_TREE_H #include "dsexceptions.h" #include <algorithm> using namespace std; // BinarySearchTree class // // CONSTRUCTION: zero parameter // // ******************PUBLIC OPERATIONS********************* // void insert( x ) --> Insert x // void find( x ) // void remove( x ) --> Remove x // bool contains( x ) --> Return true if x is present // Comparable findMin( ) --> Return smallest item // Comparable findMax( ) --> Return largest item // boolean isEmpty( ) --> Return true if empty; else false // void makeEmpty( ) --> Remove all items // void printTree( ) --> Print tree in sorted order // ******************ERRORS******************************** // Throws UnderflowException as warranted class BinarySearchTree { public: BinarySearchTree( ) :root{ nullptr } , totalInsertionCalls{0} , totalContainsCalls{0} , totalRemoveCalls{0}, successfulRemoves{0} {} /** * Copy constructor */ BinarySearchTree( BinarySearchTree & rhs ) : root{ nullptr } { totalInsertionCalls = rhs.totalInsertionCalls; totalContainsCalls = rhs.totalContainsCalls; totalRemoveCalls = rhs.totalRemoveCalls; successfulRemoves = rhs.successfulRemoves; root = clone( rhs.root ); } /** * Move constructor */ BinarySearchTree( BinarySearchTree && rhs ) : root{ rhs.root } { rhs.root = nullptr; } /** * Destructor for the tree */ ~BinarySearchTree( ) { makeEmpty( ); } /** * Copy assignment */ BinarySearchTree & operator=( BinarySearchTree & rhs ) { BinarySearchTree copy = rhs; std::swap( *this, copy ); return *this; } /** * Move assignment */ BinarySearchTree & operator=( BinarySearchTree && rhs ) { std::swap( root, rhs.root ); return *this; } /** * Find the smallest item in the tree. * Throw UnderflowException if empty. */ const sequenceMap & findMin( ) const { if( isEmpty( ) ) throw UnderflowException{ }; return findMin( root )->element; } /** * Find the largest item in the tree. * Throw UnderflowException if empty. */ const sequenceMap & findMax( ) const { if( isEmpty( ) ) throw UnderflowException{ }; return findMax( root )->element; } //finds the item, specified by x. void find(sequenceMap x) { find(x, root); } /** * Returns true if x is found in the tree. */ bool contains( sequenceMap x ) { return contains( x, root ); } /** * Test if the tree is logically empty. * Return true if empty, false otherwise. */ bool isEmpty( ) const { return root == nullptr; } /** * Print the tree contents in sorted order. */ void printTree( ) const { if( isEmpty( ) ) cout << "Empty tree" << endl; else printTree( root ); } /** * Make the tree logically empty. */ void makeEmpty( ) { makeEmpty( root ); } /** * Insert x into the tree; duplicates are ignored. */ void insert( sequenceMap & x ) { //cout << "We are going to insert: " << x << endl; insert( x, root ); } /** * Insert x into the tree; duplicates are ignored. */ void insert( sequenceMap && x ) { insert( std::move( x ), root ); } /** * Remove x from the tree. Nothing is done if x is not found. */ void remove( sequenceMap & x ) { remove( x, root ); } /* MODIFICATIONS BELOW These new functions are specific to the assignment; they are all new. */ int returnInsertionCalls() { return totalInsertionCalls; } int returnContainsCalls() { return totalContainsCalls; } int returnRemoveCalls() { return totalRemoveCalls; } int returnSuccessfulRemoves() { return successfulRemoves; } float numberOfNodes() { float value = 0; return numberOfNodes(root, value); } float depth() { float depthsoFar = 0; return depth(root, depthsoFar); } void resetInsertCalls() { totalInsertionCalls = 0; } void resetContainsCalls() { totalContainsCalls = 0; } void resetRemoveCalls() { totalRemoveCalls = 0; } void resetSuccessfulRemoves() { successfulRemoves = 0; } /* END OF MODIFICATIONS */ private: int totalInsertionCalls; int totalContainsCalls; int totalRemoveCalls; int successfulRemoves; struct BinaryNode { sequenceMap element; BinaryNode *left; BinaryNode *right; BinaryNode( sequenceMap & theElement, BinaryNode *lt, BinaryNode *rt ) : element{ theElement }, left{ lt }, right{ rt } { } BinaryNode( sequenceMap && theElement, BinaryNode *lt, BinaryNode *rt ) : element{ std::move( theElement ) }, left{ lt }, right{ rt } { } }; BinaryNode *root; // If the node is found, we use printAcronyms to print it; else, we state its absence void find( sequenceMap x, BinaryNode *t ) { if( t == nullptr ) cout << "not found" << endl; else if( x < t->element ) find( x, t->left ); else if( t->element < x ) find( x, t->right ); else (t->element).printAcronyms(); } /** * Internal method to insert into a subtree. * x is the item to insert. * t is the node that roots the subtree. * Set the new root of the subtree. */ void insert( sequenceMap & x, BinaryNode * & t ) { totalInsertionCalls++; if( t == nullptr ) t = new BinaryNode{ x, nullptr, nullptr }; else if( (x < t->element) ) insert( x, t->left ); else if( (t->element < x) ) insert( x, t->right ); else (t->element).mergeObjects(x); // If the sequence exists already, we append the acronym of our new object to this existing obj. } /** * Internal method to insert into a subtree. * x is the item to insert. * t is the node that roots the subtree. * Set the new root of the subtree. * NOTE: This function is never used. Disregard; it is kept in out of fear of breaking the tree datatype */ void insert( sequenceMap && x, BinaryNode * & t ) { totalInsertionCalls++; if( t == nullptr ) t = new BinaryNode{ std::move( x ), nullptr, nullptr }; else if( (x < t->element) ){ insert( std::move( x ), t->left ); } else if( (t->element < x) ){ insert( std::move( x ), t->right ); } else (t->element).mergeObjects(x); // if the obj exists, append the acronyms of the new obj to it. } /** * Internal method to remove from a subtree. * x is the item to remove. * t is the node that roots the subtree. * Set the new root of the subtree. */ void remove( sequenceMap & x, BinaryNode * & t ) { totalRemoveCalls++; if(t == nullptr) return; // Item not found; do nothing else if( (x < t->element) ){ remove( x, t->left ); } else if( (t->element < x) ){ remove( x, t->right ); } else if( t->left != nullptr && t->right != nullptr ) // Two children { t->element = findMin( t->right )->element; remove( t->element, t->right ); } else { BinaryNode *oldNode = t; t = ( t->left != nullptr ) ? t->left : t->right; delete oldNode; successfulRemoves++; } } /** * Internal method to find the smallest item in a subtree t. * Return node containing the smallest item. */ BinaryNode * findMin( BinaryNode *t ) const { if( t == nullptr ) return nullptr; if( t->left == nullptr ) return t; return findMin( t->left ); } /** * Internal method to find the largest item in a subtree t. * Return node containing the largest item. */ BinaryNode * findMax( BinaryNode *t ) const { if( t != nullptr ) while( t->right != nullptr ) t = t->right; return t; } /** * Internal method to test if an item is in a subtree. * x is item to search for. * t is the node that roots the subtree. */ bool contains( sequenceMap x, BinaryNode *t ) { totalContainsCalls++; if( t == nullptr ){ return false; } else if( x < t->element ){ return contains( x, t->left ); } else if( t->element < x ){ return contains( x, t->right ); } else return true; // Match } /****** NONRECURSIVE VERSION************************* bool contains( const Comparable & x, BinaryNode *t ) const { while( t != nullptr ) if( x < t->element ) t = t->left; else if( t->element < x ) t = t->right; else return true; // Match return false; // No match } *****************************************************/ /** * Internal method to make subtree empty. */ void makeEmpty( BinaryNode * & t ) { if( t != nullptr ) { makeEmpty( t->left ); makeEmpty( t->right ); delete t; } t = nullptr; } /** * Internal method to print a subtree rooted at t in sorted order. */ void printTree( BinaryNode *t ) const { if( t != nullptr ) { printTree( t->left ); cout << t->element << endl; printTree( t->right ); } } /** * Internal method to clone subtree. */ BinaryNode * clone( BinaryNode *t ) const { if( t == nullptr ) return nullptr; else return new BinaryNode{ t->element, clone( t->left ), clone( t->right ) }; } float numberOfNodes(BinaryNode *root, float value) //Recursive function to compute the # of nodes. { if(root == nullptr) return 0; else return numberOfNodes(root->left, value) + numberOfNodes(root->right, value) + 1; } float depth(BinaryNode *root, float depthsoFar) { if(root == nullptr) return 0; else return depth(root->left, depthsoFar+1) + depth(root->right, depthsoFar+1) + depthsoFar; } }; #endif <file_sep>/******************************************************************************************************************************************************** Title: sequenceMap Author: <NAME> Created: October 15, 2014 Purpose:A datatype that holds a key, a recognition Sequence, and a vector of strings, the acronyms associated with the sequence. Build with: g++ -o programname "Your_Main_Function_Holding_File_Here".cpp Given that this is simply a header with implementations inside, just include in your main function file. ********************************************************************************************************************************************************/ #ifndef SEQUENCEMAP_H #define SEQUENCEMAP_H using namespace std; class sequenceMap { public: sequenceMap(); sequenceMap(const sequenceMap& source); sequenceMap(sequenceMap && source); sequenceMap& operator=(const sequenceMap& source); bool operator<( sequenceMap rhs); void setValues(string inputSequence, vector<string>inputEnzymes); void updateRecognitionSequence(string inputSequence); void updateEnzyme_Acronyms(string newAcronym); string& getRecognitionSequence(); vector<string> getAllEnzymeAcronyms(); void mergeObjects(sequenceMap& source); void setRecognitionSequence(string source); void setEnzyme_Acronyms(vector<string> source); void print(); void printAcronyms(); friend ostream& operator<<(ostream& out, sequenceMap& c); //~sequenceMap(); Most likely not necessary. Need to address eventually. private: string recognition_Sequence; vector<string> enzyme_Acronyms; }; sequenceMap::sequenceMap() { } sequenceMap::sequenceMap(const sequenceMap& source) { if( source.recognition_Sequence.length() == 0 ) { //recognition_Sequence = ""; } else { this->enzyme_Acronyms = source.enzyme_Acronyms; this->recognition_Sequence = source.recognition_Sequence; } } sequenceMap::sequenceMap(sequenceMap && source) { recognition_Sequence = source.recognition_Sequence; source.recognition_Sequence = ""; while( !source.enzyme_Acronyms.empty() ) { int i = source.enzyme_Acronyms.size() - 1; this->enzyme_Acronyms.push_back( source.enzyme_Acronyms[i] );//Check if this works. source.enzyme_Acronyms.pop_back(); i--; } } sequenceMap& sequenceMap::operator=(const sequenceMap& source) { if( this != &source ) { this->enzyme_Acronyms = source.enzyme_Acronyms; this->recognition_Sequence = source.recognition_Sequence; return *this; } else return *this; } void sequenceMap::setValues(string inputSequence, vector<string>inputEnzymes) { this->recognition_Sequence = inputSequence; this->enzyme_Acronyms = inputEnzymes; } //If this has been called, source and this sequenceMap share the same sequence. As such, source's acronyms are all loaded into //this sequenceMap void sequenceMap::mergeObjects(sequenceMap& source) { while( !source.enzyme_Acronyms.empty() ) { int i = source.enzyme_Acronyms.size() - 1; this->enzyme_Acronyms.push_back( source.enzyme_Acronyms[i] );//Check if this works. source.enzyme_Acronyms.pop_back(); i--; } } bool sequenceMap::operator<( sequenceMap rhs) { if(recognition_Sequence.compare(rhs.recognition_Sequence) == 0) return false; else if(recognition_Sequence.compare(rhs.recognition_Sequence) < 0) return true; else if(recognition_Sequence.compare(rhs.recognition_Sequence) > 0 ) return false; } void sequenceMap::setRecognitionSequence(string source) { this->recognition_Sequence = source; } void sequenceMap::setEnzyme_Acronyms(vector<string> source) { this->enzyme_Acronyms = source; } void sequenceMap::updateRecognitionSequence(string inputSequence) { this->recognition_Sequence = inputSequence; } void sequenceMap::updateEnzyme_Acronyms(string newAcronym) { enzyme_Acronyms.push_back(newAcronym); } string& sequenceMap::getRecognitionSequence() { return recognition_Sequence; } vector<string> sequenceMap::getAllEnzymeAcronyms() { return this->enzyme_Acronyms; } ostream& operator<<(ostream& out, sequenceMap& c) { out << c.recognition_Sequence; return out; } void sequenceMap::print() { cout << recognition_Sequence << endl; } void sequenceMap::printAcronyms() { cout << "Enzyme Acronyms associated with: " << recognition_Sequence << endl; if(enzyme_Acronyms.size() != 0) { for(int i = 0; i < enzyme_Acronyms.size(); i++) { cout << enzyme_Acronyms[i] << endl; } } } #endif // SEQUENCEMAP_H <file_sep>/******************************************************************************************************************************************************** Title: AVLDNA Author: <NAME>(With modifications on the code by <NAME>) Created: October 15, 2014 Purpose:An AVL tree specifically designed to handle the sequenceMap data type Build with: g++ -o programname "Your_Main_Function_Holding_File_Here".cpp Given that this is simply a header with implementations inside, just include in your main function file. ********************************************************************************************************************************************************/ #ifndef AVL_TREE_H #define AVL_TREE_H #include "dsexceptions.h" #include <algorithm> #include <iostream> using namespace std; // AvlTree class // // CONSTRUCTION: zero parameter // // ******************PUBLIC OPERATIONS********************* // void insert( x ) --> Insert x // void remove( x ) --> Remove x (unimplemented) // bool contains( x ) --> Return true if x is present // Comparable findMin( ) --> Return smallest item // Comparable findMax( ) --> Return largest item // boolean isEmpty( ) --> Return true if empty; else false // void makeEmpty( ) --> Remove all items // void printTree( ) --> Print tree in sorted order // ******************ERRORS******************************** // Throws UnderflowException as warranted class AvlTree { public: AvlTree( ) : root{ nullptr } , totalInsertionCalls{0} , totalContainsCalls{0} , totalRemoveCalls{0}, successfulRemoves{0} { } AvlTree( const AvlTree & rhs ) : root{ nullptr } { totalInsertionCalls = rhs.totalInsertionCalls; totalContainsCalls = rhs.totalContainsCalls; totalRemoveCalls = rhs.totalRemoveCalls; successfulRemoves = rhs.successfulRemoves; root = clone( rhs.root ); } AvlTree( AvlTree && rhs ) : root{ rhs.root } { rhs.root = nullptr; } ~AvlTree( ) { makeEmpty( ); } /** * Deep copy. */ AvlTree & operator=( const AvlTree & rhs ) { AvlTree copy = rhs; std::swap( *this, copy ); return *this; } /** * Move. */ AvlTree & operator=( AvlTree && rhs ) { std::swap( root, rhs.root ); return *this; } /** * Find the smallest item in the tree. * Throw UnderflowException if empty. */ const sequenceMap & findMin( ) const { if( isEmpty( ) ) throw UnderflowException{ }; return findMin( root )->element; } /** * Find the largest item in the tree. * Throw UnderflowException if empty. */ const sequenceMap & findMax( ) const { if( isEmpty( ) ) throw UnderflowException{ }; return findMax( root )->element; } //finds the item, specified by x. void find(sequenceMap x) { find(x, root); } /** * Returns true if x is found in the tree. */ bool contains( sequenceMap x ) { return contains( x, root ); } /** * Test if the tree is logically empty. * Return true if empty, false otherwise. */ bool isEmpty( ) const { return root == nullptr; } /** * Print the tree contents in sorted order. */ void printTree( ) const { if( isEmpty( ) ) cout << "Empty tree" << endl; else printTree( root ); } /** * Make the tree logically empty. */ void makeEmpty( ) { makeEmpty( root ); } /** * Insert x into the tree; duplicates are ignored. */ void insert( sequenceMap & x ) { insert( x, root ); } /** * Insert x into the tree; duplicates are ignored. */ void insert( sequenceMap && x ) { insert( std::move( x ), root ); } /** * Remove x from the tree. Nothing is done if x is not found. */ void remove( sequenceMap & x ) { remove( x, root ); } /* MODIFICATIONS BELOW These new functions are specific to the assignment; they are all new. */ int returnInsertionCalls() { return totalInsertionCalls; } int returnContainsCalls() { return totalContainsCalls; } int returnRemoveCalls() { return totalRemoveCalls; } int returnSuccessfulRemoves() { return successfulRemoves; } void resetInsertCalls() { totalInsertionCalls = 0; } void resetContainsCalls() { totalContainsCalls = 0; } void resetRemoveCalls() { totalRemoveCalls = 0; } void resetSuccessfulRemoves() { successfulRemoves = 0; } float numberOfNodes() { float value = 0; return numberOfNodes(root, value); } float depth() { float depthsoFar = 0; return depth(root, depthsoFar); } private: int totalInsertionCalls; int totalContainsCalls; int totalRemoveCalls; int successfulRemoves; struct AvlNode { sequenceMap element; AvlNode *left; AvlNode *right; int height; AvlNode( const sequenceMap & ele, AvlNode *lt, AvlNode *rt, int h = 0 ) : element{ ele }, left{ lt }, right{ rt }, height{ h } { } AvlNode( sequenceMap && ele, AvlNode *lt, AvlNode *rt, int h = 0 ) : element{ std::move( ele ) }, left{ lt }, right{ rt }, height{ h } { } }; AvlNode *root; void find( sequenceMap x, AvlNode *t ) { if( t == nullptr ) cout << "not found" << endl; else if( x < t->element ) find( x, t->left ); else if( t->element < x ) find( x, t->right ); else (t->element).printAcronyms(); } /** * Internal method to insert into a subtree. * x is the item to insert. * t is the node that roots the subtree. * Set the new root of the subtree. */ void insert( sequenceMap & x, AvlNode * & t ) { totalInsertionCalls++; if( t == nullptr ) t = new AvlNode{ x, nullptr, nullptr }; else if( x < t->element ) insert( x, t->left ); else if( t->element < x ) insert( x, t->right ); else (t->element).mergeObjects(x); balance( t ); } /** * Internal method to insert into a subtree. * x is the item to insert. * t is the node that roots the subtree. * Set the new root of the subtree. */ void insert( sequenceMap && x, AvlNode * & t ) { totalInsertionCalls++; if( t == nullptr ) t = new AvlNode{ x, nullptr, nullptr }; else if( x < t->element ) insert( x, t->left ); else if( t->element < x ) insert( x, t->right ); else (t->element).mergeObjects(x); balance( t ); } /** * Internal method to remove from a subtree. * x is the item to remove. * t is the node that roots the subtree. * Set the new root of the subtree. */ void remove( sequenceMap & x, AvlNode * & t ) { totalRemoveCalls++; if( t == nullptr ) return; // Item not found; do nothing if( x < t->element ) remove( x, t->left ); else if( t->element < x ) remove( x, t->right ); else if( t->left != nullptr && t->right != nullptr ) // Two children { t->element = findMin( t->right )->element; remove( t->element, t->right ); } else { AvlNode *oldNode = t; t = ( t->left != nullptr ) ? t->left : t->right; delete oldNode; successfulRemoves++; } balance( t ); } static const int ALLOWED_IMBALANCE = 1; // Assume t is balanced or within one of being balanced void balance( AvlNode * & t ) { if( t == nullptr ) return; if( height( t->left ) - height( t->right ) > ALLOWED_IMBALANCE ) if( height( t->left->left ) >= height( t->left->right ) ) rotateWithLeftChild( t ); else doubleWithLeftChild( t ); else if( height( t->right ) - height( t->left ) > ALLOWED_IMBALANCE ) if( height( t->right->right ) >= height( t->right->left ) ) rotateWithRightChild( t ); else doubleWithRightChild( t ); t->height = max( height( t->left ), height( t->right ) ) + 1; } /** * Internal method to find the smallest item in a subtree t. * Return node containing the smallest item. */ AvlNode * findMin( AvlNode *t ) const { if( t == nullptr ) return nullptr; if( t->left == nullptr ) return t; return findMin( t->left ); } /** * Internal method to find the largest item in a subtree t. * Return node containing the largest item. */ AvlNode * findMax( AvlNode *t ) const { if( t != nullptr ) while( t->right != nullptr ) t = t->right; return t; } /** * Internal method to test if an item is in a subtree. * x is item to search for. * t is the node that roots the tree. */ bool contains( sequenceMap x, AvlNode *t ) { totalContainsCalls++; if( t == nullptr ){ //cout << "not found" << endl; return false; } //return false; else if( x < t->element ) return contains( x, t->left ); else if( t->element < x ) return contains( x, t->right ); else{ return true; } // Match } /****** NONRECURSIVE VERSION************************* bool contains( const Comparable & x, AvlNode *t ) const { while( t != nullptr ) if( x < t->element ) t = t->left; else if( t->element < x ) t = t->right; else return true; // Match return false; // No match } *****************************************************/ /** * Internal method to make subtree empty. */ void makeEmpty( AvlNode * & t ) { if( t != nullptr ) { makeEmpty( t->left ); makeEmpty( t->right ); delete t; } t = nullptr; } /** * Internal method to print a subtree rooted at t in sorted order. */ void printTree( AvlNode *t ) const { if( t != nullptr ) { printTree( t->left ); cout << t->element << endl; printTree( t->right ); } } /** * Internal method to clone subtree. */ AvlNode * clone( AvlNode *t ) const { if( t == nullptr ) return nullptr; else return new AvlNode{ t->element, clone( t->left ), clone( t->right ), t->height }; } // Avl manipulations /** * Return the height of node t or -1 if nullptr. */ int height( AvlNode *t ) const { return t == nullptr ? -1 : t->height; } int max( int lhs, int rhs ) const { return lhs > rhs ? lhs : rhs; } /** * Rotate binary tree node with left child. * For AVL trees, this is a single rotation for case 1. * Update heights, then set new root. */ void rotateWithLeftChild( AvlNode * & k2 ) { AvlNode *k1 = k2->left; k2->left = k1->right; k1->right = k2; k2->height = max( height( k2->left ), height( k2->right ) ) + 1; k1->height = max( height( k1->left ), k2->height ) + 1; k2 = k1; } /** * Rotate binary tree node with right child. * For AVL trees, this is a single rotation for case 4. * Update heights, then set new root. */ void rotateWithRightChild( AvlNode * & k1 ) { AvlNode *k2 = k1->right; k1->right = k2->left; k2->left = k1; k1->height = max( height( k1->left ), height( k1->right ) ) + 1; k2->height = max( height( k2->right ), k1->height ) + 1; k1 = k2; } /** * Double rotate binary tree node: first left child. * with its right child; then node k3 with new left child. * For AVL trees, this is a double rotation for case 2. * Update heights, then set new root. */ void doubleWithLeftChild( AvlNode * & k3 ) { rotateWithRightChild( k3->left ); rotateWithLeftChild( k3 ); } /** * Double rotate binary tree node: first right child. * with its left child; then node k1 with new right child. * For AVL trees, this is a double rotation for case 3. * Update heights, then set new root. */ void doubleWithRightChild( AvlNode * & k1 ) { rotateWithLeftChild( k1->right ); rotateWithRightChild( k1 ); } float numberOfNodes(AvlNode *root, float value) { if(root == nullptr) return 0; else return numberOfNodes(root->left, value) + numberOfNodes(root->right, value) + 1; } float depth(AvlNode *root, int depthsoFar) { if(root == nullptr) return 0; else return depth(root->left, depthsoFar+1) + depth(root->right, depthsoFar+1) + depthsoFar; } }; #endif <file_sep>/******************************************************************************************************************************************************** Title: lazy BST Tree Author: <NAME>(With modifications on the code by <NAME>) Created: October 15, 2014 Purpose:A lazy deletion class, which marks nodes deleted when removed. Build with: g++ -o programname "Your_Main_Function_Holding_File_Here".cpp Given that this is simply a header with implementations inside, just include in your main function file. ********************************************************************************************************************************************************/ #ifndef LAZY_BINARY_SEARCH_TREE_H #define LAZY_BINARY_SEARCH_TREE_H #include "dsexceptions.h" #include <algorithm> using namespace std; // BinarySearchTree class // // CONSTRUCTION: zero parameter // // ******************PUBLIC OPERATIONS********************* // void insert( x ) --> Insert x // void remove( x ) --> Remove x // bool contains( x ) --> Return true if x is present // Comparable findMin( ) --> Return smallest item // Comparable findMax( ) --> Return largest item // boolean isEmpty( ) --> Return true if empty; else false // void makeEmpty( ) --> Remove all items // void printTree( ) --> Print tree in sorted order // ******************ERRORS******************************** // Throws UnderflowException as warranted class LazyBinarySearchTree { public: LazyBinarySearchTree( ) :root{ nullptr } , totalInsertionCalls{0} , totalContainsCalls{0} , totalRemoveCalls{0}, successfulRemoves{0} {} /** * Copy constructor */ LazyBinarySearchTree( LazyBinarySearchTree & rhs ) : root{ nullptr } { totalInsertionCalls = rhs.totalInsertionCalls; totalContainsCalls = rhs.totalContainsCalls; totalRemoveCalls = rhs.totalRemoveCalls; successfulRemoves = rhs.successfulRemoves; root = clone( rhs.root ); } /** * Move constructor */ LazyBinarySearchTree( LazyBinarySearchTree && rhs ) : root{ rhs.root } { rhs.root = nullptr; } /** * Destructor for the tree */ ~LazyBinarySearchTree( ) { makeEmpty( ); } /** * Copy assignment */ LazyBinarySearchTree & operator=( LazyBinarySearchTree & rhs ) { LazyBinarySearchTree copy = rhs; std::swap( *this, copy ); return *this; } /** * Move assignment */ LazyBinarySearchTree & operator=( LazyBinarySearchTree && rhs ) { std::swap( root, rhs.root ); return *this; } /** * Find the smallest item in the tree. * Throw UnderflowException if empty. */ /* const sequenceMap & findMin( ) const { if( isEmpty( ) ) throw UnderflowException{ }; return findMin( root )->element; } /** * Find the largest item in the tree. * Throw UnderflowException if empty. *//* const sequenceMap & findMax( ) const { if( isEmpty( ) ) throw UnderflowException{ }; return findMax( root )->element; } */ void find(sequenceMap x) { find(x, root); } /** * Returns true if x is found in the tree. */ bool contains( sequenceMap x ) { return contains( x, root ); } /** * Test if the tree is logically empty. * Return true if empty, false otherwise. */ bool isEmpty( ) const { return root == nullptr; } /** * Print the tree contents in sorted order. */ void printTree( ) const { if( isEmpty( ) ) cout << "Empty tree" << endl; else printTree( root ); } /** * Make the tree logically empty. */ void makeEmpty( ) { makeEmpty( root ); } /** * Insert x into the tree; duplicates are ignored. */ void insert( sequenceMap & x ) { //cout << "We are going to insert: " << x << endl; insert( x, root ); } /** * Insert x into the tree; duplicates are ignored. *//* void insert( sequenceMap && x ) { insert( std::move( x ), root ); }*/ /** * Remove x from the tree. Nothing is done if x is not found. */ void remove( sequenceMap & x ) { remove( x, root ); } /* MODIFICATIONS BELOW These new functions are specific to the assignment; they are all new. */ int returnInsertionCalls() { return totalInsertionCalls; } int returnContainsCalls() { return totalContainsCalls; } int returnRemoveCalls() { return totalRemoveCalls; } int returnSuccessfulRemoves() { return successfulRemoves; } float numberOfNodes() { float value = 0; return numberOfNodes(root, value); } float depth() { float depthsoFar = 0; return depth(root, depthsoFar); } void resetInsertCalls() { totalInsertionCalls = 0; } void resetContainsCalls() { totalContainsCalls = 0; } void resetRemoveCalls() { totalRemoveCalls = 0; } void resetSuccessfulRemoves() { successfulRemoves = 0; } /* END OF MODIFICATIONS */ private: int totalInsertionCalls; int totalContainsCalls; int totalRemoveCalls; int successfulRemoves; struct BinaryNode { sequenceMap element; BinaryNode *left; BinaryNode *right; bool active; BinaryNode( sequenceMap & theElement, BinaryNode *lt, BinaryNode *rt, bool nodestatus ) : element{ theElement }, left{ lt }, right{ rt }, active{nodestatus} { } BinaryNode( sequenceMap && theElement, BinaryNode *lt, BinaryNode *rt, bool nodestatus ) : element{ std::move( theElement ) }, left{ lt }, right{ rt }, active{nodestatus} { } void deactivate() { active = false; } void reActivate() { active = true; } }; BinaryNode *root; // If the node is found, we use printAcronyms to print it; else, we state its absence void find( sequenceMap x, BinaryNode *t ) { if( t == nullptr ) cout << "not found" << endl; else if( x < t->element ) find( x, t->left ); else if( t->element < x ) find( x, t->right ); else if(t->active == true) (t->element).printAcronyms(); } /** * Internal method to insert into a subtree. * x is the item to insert. * t is the node that roots the subtree. * Set the new root of the subtree. */ void insert( sequenceMap & x, BinaryNode * & t ) { totalInsertionCalls++; if( t == nullptr ) t = new BinaryNode{ x, nullptr, nullptr, true }; else if(t->active == false) t->reActivate();//If the node exists already, we simply reactivate it. else if( (x < t->element) ) insert( x, t->left ); else if( (t->element < x) ) insert( x, t->right ); else (t->element).mergeObjects(x); //The objects are merged if it exists already, and it's active. } /** * Internal method to insert into a subtree. * x is the item to insert. * t is the node that roots the subtree. * Set the new root of the subtree. */ /* void insert( sequenceMap && x, BinaryNode * & t ) { totalInsertionCalls++; if( t == nullptr ) t = new BinaryNode{ std::move( x ), nullptr, nullptr, true }; else if( (x < t->element) ){ //cout << "TO THE LEFT" << endl; insert( std::move( x ), t->left ); } else if( (t->element < x) ){ //cout << "TO THE RIGHT" << endl; insert( std::move( x ), t->right ); } else (t->element).mergeObjects(x); // Duplicate; do nothing }*/ /** * Internal method to remove from a subtree. * x is the item to remove. * t is the node that roots the subtree. * Set the new root of the subtree. */ void remove( sequenceMap & x, BinaryNode * & t ) { totalRemoveCalls++; if( t == nullptr ) return; // Item not found; do nothing if( (x < t->element) ){ remove( x, t->left ); } else if( (t->element < x) ){ remove( x, t->right ); } //else if(t->active == false) return; //node already deleted; disregard else { //cout << t->active << " should be 1" << endl; //cout << x << " " << t->element << endl; t->deactivate();//We delete the node if it's active. //cout << t->active << " should be 0" << endl; successfulRemoves++; } } /** * Internal method to find the smallest item in a subtree t. * Return node containing the smallest item. */ /*THESE ARE INCLUDED FOR COMPLETION'S SAKE. SINCE IT WILL NOT BE GRADED, IT WON'T WORK. BinaryNode * findMin( BinaryNode *t ) const { if(t == nullptr) return nullptr;//end of tree cout << t->element << endl; BinaryNode *current = findMin(t->left);//Will search for the min as of this node //if(current != nullptr) return current;//If the previous node is not empty, the current node is therefore the smallest if(t->active)return t;//If this node is active, it is therefore the smallest return findMin(t->right);//If the node is inactive, the right node may be the smallest } /** * Internal method to find the largest item in a subtree t. * Return node containing the largest item. BinaryNode * findMax( BinaryNode *t ) const { if(t == nullptr) return nullptr;//End of tree BinaryNode *current = findMax(t->right);//Will search for the max as of this node if(current != nullptr) return current;//If the previous node is not empty, the current node is therefore the biggest if(t->active)return t;//If the node is active, then it is therefore the biggest return findMax(t->left);//If all nodes in the right are deactivated, the left must be searched. } */ /** * Internal method to test if an item is in a subtree. * x is item to search for. * t is the node that roots the subtree. */ bool contains( sequenceMap x, BinaryNode *t ) { totalContainsCalls++; if( t == nullptr ){ return true; } else if( x < t->element ){ return contains( x, t->left ); } else if( t->element < x ){ return contains( x, t->right ); } else { if(t->active == false){ return false;//If the node is deactivated, it technically does not exist. } else return true; //Match } } /****** NONRECURSIVE VERSION************************* bool contains( const Comparable & x, BinaryNode *t ) const { while( t != nullptr ) if( x < t->element ) t = t->left; else if( t->element < x ) t = t->right; else return true; // Match return false; // No match } *****************************************************/ /** * Internal method to make subtree empty. */ void makeEmpty( BinaryNode * & t ) { if( t != nullptr ) { makeEmpty( t->left ); makeEmpty( t->right ); delete t; } t = nullptr; } /** * Internal method to print a subtree rooted at t in sorted order. */ void printTree( BinaryNode *t ) const { //string temp; //temp = (t->element).getRecognitionSequence(); //cout << "temp has: " << temp << endl; if( t != nullptr ) { printTree( t->left ); if(t->active == true)cout << t->element << endl; printTree( t->right ); } } /** * Internal method to clone subtree. */ BinaryNode * clone( BinaryNode *t ) const { if( t == nullptr ) return nullptr; else return new BinaryNode{ t->element, clone( t->left ), clone( t->right ), t->active }; } float numberOfNodes(BinaryNode *root, float value) { if(root == nullptr) return 0; else return numberOfNodes(root->left, value) + numberOfNodes(root->right, value) + 1; } float depth(BinaryNode *root, float depthsoFar) { if(root == nullptr) return 0; else return depth(root->left, depthsoFar+1) + depth(root->right, depthsoFar+1) + depthsoFar; } }; #endif <file_sep># 335_project1 use of trees <file_sep>/******************************************************************************************************************************************************** Title: queryTrees Author: <NAME> Created: October 15, 2014 Purpose:This program fills up a tree of your choice(BST, AVL, LazyBST, LazyAVL) and allows you to search it for sequences. Build with: g++ -o queryTrees queryTrees.cpp Remember! All header files below contain their implementations! ********************************************************************************************************************************************************/ #include <string> #include <vector> #include <iostream> #include <fstream> #include <stack> #include "sequenceMap.h" #include "BSTDNA.h" #include "AVLDNA.h" #include "BSTLAZYDNA.h" #include "AVLLAZYDNA.h" void fileCheck(ifstream& file); template <class T> void fillTree(T& root, ifstream& file); bool checkForLegality(string thisLine); template <class T> void createSequenceMaps(T& root, string thisLine); void flipString(string& tobeFlipped); void newLine();//gets rid of any unecessary characters from input int main( int argc, char *argv[]) { string fileName = argv[1]; string query; char again; sequenceMap queryContainer; ifstream rebase210(fileName); fileCheck(rebase210); string parameter = argv[2]; if(parameter == "BST" ){ BinarySearchTree database; fillTree<BinarySearchTree>(database, rebase210); do{ cout << "query the tree: "; //database.printTree(); cin >> query; //newLine(); queryContainer.updateRecognitionSequence(query); database.find(queryContainer); cout << "Enter Y to query again; otherwise, enter anything else to exit: "; cin >> again; newLine(); }while(again == 'Y'); } else if(parameter == "AVL" ){ AvlTree database; fillTree<AvlTree>(database, rebase210); do{ cout << "query the tree: "; cin >> query; newLine(); queryContainer.updateRecognitionSequence(query); database.find(queryContainer); cout << "Enter Y to query again; otherwise, enter anything else to exit: "; cin >> again; newLine(); }while(again == 'Y'); } else if(parameter == "LazyBST" ) { LazyBinarySearchTree database; fillTree<LazyBinarySearchTree>(database, rebase210); do{ cout << "query the tree: "; cin >> query; newLine(); queryContainer.updateRecognitionSequence(query); database.find(queryContainer); cout << "Enter Y to query again; otherwise, enter anything else to exit: "; cin >> again; newLine(); }while(again == 'Y'); } else if(parameter == "LazyAVL") { do{ LazyAvlTree database; fillTree<LazyAvlTree>(database, rebase210); cout << "query the tree: "; cin >> query; newLine(); queryContainer.updateRecognitionSequence(query); database.find(queryContainer); cout << "Enter Y to query again; otherwise, enter anything else to exit: "; cin >> again; newLine(); }while(again == 'Y'); } else cout << "Parameter flag not valid" << endl; rebase210.close(); return 0; } void fileCheck(ifstream& file) //simply put, this function will check if the file is within the same directory as the executable. //Otherwise, the program will end, prompting the changing of location of the file. { if(file.fail()) { cerr << "Input file could not be opened. Check if the file is in the same directory" << " as the executable.\n"; exit(1); } } template <class T> //Using the already opened file stream, this will fill up the tree with the data inside void fillTree(T& root, ifstream& file) { string currentLine; bool firstLineFound = 0; while(file>>currentLine) { firstLineFound = checkForLegality(currentLine); if(firstLineFound){ createSequenceMaps(root, currentLine); } } } bool checkForLegality(string thisLine) //A simple check. Since we parse files line by line, we will check if the string ends in //, the accepted format of the recog. sequence. { if(thisLine[thisLine.size() - 2] == '/' && thisLine[(thisLine.size() - 1)] == '/') return true; else return false; } template <class T> //Using a stack, we create, then insert, a sequenceMap for the current line obtained from filltree void createSequenceMaps(T& root, string thisLine) { int currentPos = 0; stack<char> acronym; acronym.push(thisLine[currentPos]);//We insert the string character by character. currentPos++; while(!(acronym.top() == '/'))//Until we spot a /, we will keep inserting characters into our stack { acronym.push(thisLine[currentPos]); currentPos++; } acronym.pop();//We'll pop the / that we received at the end of our while loop. string acronymString; while(!(acronym.empty()))//We pop our string out; it will be backwards. Bear with me. { acronymString += acronym.top(); acronym.pop(); } flipString(acronymString);//We will flip the string obtained from the stack. string sequenceKey; sequenceMap current; current.updateEnzyme_Acronyms(acronymString);//The acronym obtained from the beginning is appended to all sequences do{ //We will search for recognition sequences, up until the final // is encountered. if(!(thisLine[currentPos] == '/' && thisLine[currentPos+1] == '/')) acronym.push(thisLine[currentPos]); else break; currentPos++; while(!(acronym.top() == '/'))//We will search for recognition sequences, up until the final // is encountered. { acronym.push(thisLine[currentPos]); currentPos++; } acronym.pop();//After we find a recognition sequence, we will pop the final / out before the next string. while(!(acronym.empty())) { sequenceKey += acronym.top(); acronym.pop(); } flipString(sequenceKey);//We flip after we pop. current.updateRecognitionSequence(sequenceKey);//We will insert the obtained sequence into an object root.insert(current);//it will be inserted into the tree. sequenceKey.clear(); }while(!(thisLine[currentPos-1] == '/' && thisLine[currentPos] == '/'));//And this code will run until a // is encountered. } void flipString(string& tobeFlipped) //Does exactly what you think it does. { char next; string newString; for(int i = tobeFlipped.size()-1; i >= 0 ; i--) { next = tobeFlipped[i]; newString += next; } tobeFlipped = newString; } void newLine() //newLine makes sure any unecessary characters are not read. //EX: if the program asks for n, and the user enters "name name name" //It will only read n and discard the rest. { char symbol; do { cin.get(symbol); } while( symbol != '\n'); }
f2c11994736a1363cbe782d526e2ea576f669adc
[ "Markdown", "C++" ]
7
C++
jseuribe/335_project1
6d4d951ba96dff6774f16364908f94c18cc38179
8243e10ef37b14865ab57ea2f47b5ae28bf9f986
refs/heads/main
<file_sep># This is a sample Python script. # Press ⌃R to execute it or replace it with your code. # Press Double ⇧ to search everywhere for classes, files, tool windows, actions, and settings. import numpy as np from heapq import heapify, heappop, heappush import time def evaluate(heuristic, node): # uniform cost search if heuristic == 1: return 0 # A* with misplaced tiles elif heuristic == 2: match = np.count_nonzero(node == goal_st) if match == puzzle + 1: return 0 return puzzle - match # A* with manhattan distance elif heuristic == 3: dist = 0 for i in range(1, puzzle+1): pos = np.where(node == i) goal_pos = pos_map[i] dist += np.abs(pos[0][0] - goal_pos[0]) + np.abs(pos[1][0] - goal_pos[1]) return dist return -1 def goal_test(node): if np.count_nonzero(node == goal_st) == puzzle + 1: return True return False class State: def __init__(self, state): self.state = state self.parent = None self.gn = 0 self.hn = np.inf self.fn = self.gn + self.hn def __lt__(self, other): return self.fn < other.fn def move_left(self, x, y): left_st = np.copy(self.state) left_st[x][y - 1], left_st[x][y] = left_st[x][y], left_st[x][y - 1] left = State(left_st) left.parent = self left.gn = self.gn+1 left.hn = evaluate(heu, left_st) left.fn = left.gn + left.hn return left def move_right(self, x, y): right_st = np.copy(self.state) right_st[x][y + 1], right_st[x][y] = right_st[x][y], right_st[x][y + 1] right = State(right_st) right.parent = self right.gn = self.gn + 1 right.hn = evaluate(heu, right_st) right.fn = right.gn + right.hn return right def move_up(self, x, y): up_st = np.copy(self.state) up_st[x - 1][y], up_st[x][y] = up_st[x][y], up_st[x - 1][y] up = State(up_st) up.parent = self up.gn = self.gn + 1 up.hn = evaluate(heu, up_st) up.fn = up.gn + up.hn return up def move_down(self, x, y): down_st = np.copy(self.state) down_st[x + 1][y], down_st[x][y] = down_st[x][y], down_st[x + 1][y] down = State(down_st) down.parent = self down.gn = self.gn + 1 down.hn = evaluate(heu, down_st) down.fn = down.gn + down.hn return down def expand(self): ind = np.where(self.state == 0) x, y = ind[0][0], ind[1][0] children = [] if x == 0 and y == 0: children.append(self.move_down(x, y)) children.append(self.move_right(x, y)) elif x == 0 and y == self.state.shape[1] - 1: children.append(self.move_down(x, y)) children.append(self.move_left(x, y)) elif x == self.state.shape[0] - 1 and y == 0: children.append(self.move_up(x, y)) children.append(self.move_right(x, y)) elif x == self.state.shape[0] - 1 and y == self.state.shape[1] - 1: children.append(self.move_up(x, y)) children.append(self.move_left(x, y)) elif x == 0 and 0 < y < self.state.shape[1]: children.append(self.move_down(x, y)) children.append(self.move_left(x, y)) children.append(self.move_right(x, y)) elif x == self.state.shape[0] - 1 and 0 < y < self.state.shape[1]: children.append(self.move_up(x, y)) children.append(self.move_left(x, y)) children.append(self.move_right(x, y)) elif 0 < x < self.state.shape[0] and y == 0: children.append(self.move_down(x, y)) children.append(self.move_up(x, y)) children.append(self.move_right(x, y)) elif 0 < x < self.state.shape[0] and y == self.state.shape[1] - 1: children.append(self.move_down(x, y)) children.append(self.move_up(x, y)) children.append(self.move_left(x, y)) else: children.append(self.move_left(x, y)) children.append(self.move_right(x, y)) children.append(self.move_up(x, y)) children.append(self.move_down(x, y)) return children # default parameters for 8-puzzle problem sz = 3 puzzle = sz**2 - 1 heu = 3 init_st = np.array([[0, 7, 2], [4, 6, 1], [3, 5, 8]], dtype=int) init = State(init_st) goal_st = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 0]], dtype=int) goal = State(goal_st) pos_map = dict() for i in range(1, puzzle+1): ind = np.where(goal_st == i) x, y = ind[0][0], ind[1][0] pos_map[i] = (x, y) def a_star(): nodes_expanded = 0 heap = [init] heapify(heap) max_heap_size = 1 while len(heap) > 0: current = heappop(heap) nodes_expanded = nodes_expanded + 1 if goal_test(current.state): return current, nodes_expanded, max_heap_size children = current.expand() for ch in children: if current.parent is None or np.count_nonzero(ch.state == current.parent.state) < puzzle + 1: heappush(heap, ch) if max_heap_size < len(heap): max_heap_size = len(heap) return None, nodes_expanded, max_heap_size # Press the green button in the gutter to run the script. if __name__ == '__main__': result, nodes_expanded, max_heap_size = None, 0, 0 print("Type input choice:\n1 -> default\n2 -> custom") choice = int(input()) if choice == 1: #start = time.time() result, nodes_expanded, max_heap_size = a_star() #end = time.time() #print("Time elapsed: ", end - start) elif choice == 2: print("Now input elements separated by a space row-by-row") print("first row: ") r1 = input() print("second row: ") r2 = input() print("third row: ") r3 = input() init_st[0] = np.array([int(j) for j in r1.split()]) init_st[1] = np.array([int(j) for j in r2.split()]) init_st[2] = np.array([int(j) for j in r3.split()]) print("Choose the heuristic function:\n1 -> Uniform Cost Search\n2 -> Misplaced Tiles\n3 -> Manhattan Distance") heu = int(input()) result, nodes_expanded, max_heap_size = a_star() else: print("Invalid choice. Exiting!!!") if result is not None: solution_steps = [] st = result while st is not None: solution_steps.append(st) st = st.parent print("Solution Depth: ", result.gn) print("Number of Nodes Expanded: ", nodes_expanded) print("Max Heap Size: ", max_heap_size) print("The solution steps are as follows:") for k in reversed(solution_steps): print("The best state to expand with g(n) = ", str(k.gn), "and h(n) = ", str(k.hn)) print(k.state) # See PyCharm help at https://www.jetbrains.com/help/pycharm/
42a30abdb70f45edee5e237b31482f7b10fdd2cb
[ "Python" ]
1
Python
sakshar/CS205_8puzzle
c4117291efdbc85533459ffd964b267c2ff85335
a00ddc4b8842590570da7ea2f2417c6acb4c98b5
refs/heads/master
<repo_name>gerome-avec-un-g/spark-resume<file_sep>/resume/src/main/java/fr/geromeavecung/resume/materialcomponent/ListItemThreeLineAction.java package fr.geromeavecung.resume.materialcomponent; import java.util.List; import java.util.stream.Collectors; import com.google.auto.value.AutoValue; import fr.geromeavecung.resume.model.RoutePath; @AutoValue public abstract class ListItemThreeLineAction implements MaterialComponent { public static ListItemThreeLineAction create(List<ItemThreeLineAction> elements) { return new AutoValue_ListItemThreeLineAction(elements); } abstract List<ItemThreeLineAction> elements(); @Override public String convertToHtml() { String elems = elements().stream() .map(e -> "<li class=\"mdl-list__item mdl-list__item--three-line\">\n" + " <span class=\"mdl-list__item-primary-content\">\n" + " <span>" + e.title() + "</span>\n" + " <span class=\"mdl-list__item-text-body\">\n" + e.subTitle() + " </span>\n" + " </span>\n" + "<span class=\"mdl-list__item-secondary-content\">\n" + " <a class=\"mdl-list__item-secondary-action\" href=\""+ RoutePath.PROJECT.getPath().replaceFirst(":id", e.id())+"\"><i class=\"material-icons\">chevron_right</i></a>\n" + " </span></li>") .collect(Collectors.joining()); return "<ul class=\"mdl-list\">" + elems + "</ul>"; } } <file_sep>/resume/src/test/java/fr/geromeavecung/resume/materialcomponent/PrintableLayoutTest.java package fr.geromeavecung.resume.materialcomponent; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; import fr.geromeavecung.resume.printable.PrintableComponent; import fr.geromeavecung.resume.printable.PrintableLayout; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import java.util.Collections; import java.util.List; @RunWith(MockitoJUnitRunner.class) public class PrintableLayoutTest { private PrintableLayout systemUnderTest; @Mock private PrintableComponent title; @Mock private PrintableComponent content; @Before public void arrange() { when(title.get()).thenReturn("Lorem ipsum"); when(content.get()).thenReturn("dolor sit amet"); systemUnderTest = PrintableLayout.create(title, Collections.singletonList(content)); } @Test @Ignore public void get() throws Exception { String actual = systemUnderTest.get(); assertThat(actual).isEqualTo("<!DOCTYPE html>" + "<html>" + "<head><title>Lorem ipsum</title>" + "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">" + "<link rel=\"stylesheet\" href=\"http://fonts.googleapis.com/css?family=Roboto:300,400,500,700\">" + "<link rel=\"stylesheet\" href=\"/styles-printable.css\">" + "<script defer src=\"https://code.getmdl.io/1.3.0/material.min.js\"></script>" + "</head>" + "<body class=\"mdl-color--grey-300\">" + "<div class=\"mdl-layout mdl-js-layout\">" + "<header class=\"mdl-layout__header\">" + "<div class=\"mdl-layout-icon\"></div>" + "<div class=\"mdl-layout__header-row\">" + "<span class=\"mdl-layout__title\">Lorem ipsum</span>" + "<div class=\"mdl-layout-spacer\"></div>" + "</div>" + "</header>" + "<div class=\"mdl-layout__drawer\">" + "<span class=\"mdl-layout__title\">Menu</span>" + "<nav class=\"mdl-navigation\">" + "<a class=\"mdl-navigation__link\" href=\"#\">Nav link a</a>" + "<a class=\"mdl-navigation__link\" href=\"#\">Nav link b</a>" + "<a class=\"mdl-navigation__link\" href=\"#\">Nav link c</a>" + "</nav>" + "</div>" + "<main class=\"mdl-layout__content\">" + "dolor sit amet" + "</main>" + "</div>" + "</body>" + "</html>"); } } <file_sep>/resume/README.md #resume POC with spark #dev guidelines * TDD, or at least high code coverage. Aim high coverage of one class by one test, not high coverage of all classes by all tests * no null. use default value, null pattern object. text search of "null" shall not return much except for 3rd party library usages * abstract late to avoid poor abstraction that lead to higher complexity. abstract only when complexity does not increase * small, simple classes with no conditional (or really few, real boolean conditions, not type condition/switch) * lessen dependencies by reducing demeter law and proper package * no singleton that implies static. singleton = 1 new in the app * no static (enum.values ?) * ? method names as verb or noun ? verb reveals internal ? * trully logic-less template. strictly no if. loops might be authorized -> unsafeHtml only manipulates strings #class design * constructor params vs method params * constructors = either singleton class or "pure" data (String, int...) * avoid "pure" data in model classes, abstract each field instead to be an object with a behavior for the app, not stupid data * avoid multiple data field in a class, a class should have maximum 1 data field ? * method params = dynamic data (=user input) not know at app launch * constructor params = configuration ? * avoid new/create in objects except for same object type * return Obj.create is ok ? testable, not hidden. but Obj.create.method is not ok ? * classes as private as possible, expose behavior not data * stupid classes = stupid tests * model for your app, not for the business, don't add (useless) technical complexity * in what order does my classes interact ? does the request fetch data, data transforms to tag, tag to page and page to string ? or does the request render the page, the page renders the tags, the tags fetch the data ? top-down or bottom-up ? * a -> b -> c -> d * bigger interface -> medium interface -> small interface ("size" correspond to difference between interface input and output) * think of function object as "factories" * creating different classes with private constants (configuration) vs generic classes with constructor configuration #exception * use enum for exception message or even go further and use the object/type of the exception to convey meaning ? * under not circumstance use the same error message twice ! 1 exception = 1 catch ! nothing is worst than having the same code used in multiple places, debugging is harder * never ever throw the exception you are catching: was is the point ?! and logs the line of the catch/throw instead of initial throw * don't catch, log and throw new exception: will be logged twice #package * package name should be coutry_iso.company.project.module.whatever * the package is the "adress" of the class * package should be unique to avoid confusion/namespace conflict * this help knowing right away with exception logs what project the class is in #thoughts * programming style/design should be aimed to reduce defects, speed up defect fix * object or function ? field = state = long lived object. no field, no need of toString/equals/hash -> useless in list, short lived object * life is based upon number of instruction 1 = short, other = long (think contructor + setters, or list + successive add) * what does business means ? is it just a combination of filtering, sorting, validation ? id it ever higher level ? * is rendering part of "business" or is it a axiom change ? can change from business to ui only be achieved by low level data maps ? * object are design for the application or for the "business" ? * pages are functional or technical ? * data flux or object tree ? * free text input vs i18n * i18n in property files vs i18n in database ? * locale as part of the user preferences ? so comes from database rather than browser ? * dev should start following workflow not start with easy parts and then build up (so start with login and users ?) #functionalities * display a polymorphic list (forces polymorphic rendering 1 for each sub-entity) * display details (forces multiple rendering 1 for list 1 for detail) * display stats (forces data reading or creation of stats objects) * display form and field verification * display page with selected menu and content (forces rendering of data from independant sources) * display page with tabTitle (forces use of data in multiple part of the rendering) * display multiple pages * display not found page (both for bad url and bad id) * i18n for multiple language * i18n from multiple property files * dynamic (polymorphic) form depending on user choice (1st half of form is common then a droplist drives second half, how to "save" input ? no client-server reload so lot of javascript ? different ui design to ask this kind of choice first ?) * multiuser (forces conditional multiple rendering) #design * highly testable even for html rendering * no templating logic (so no templates) * low conditional complexity (polymorphism) * low null protection (null parttern) * leverage compilation through typing, see compile errors as a successful detection of defect rather than a burden of change #REST API guideline * uri contains noums. use http verb to fully describe the action * GET /clients/1 * POST /clients * noums are in plural form * /users * /users/1 * spinal-case (but maybe snake_case is better because it's closer to java CONSTANT_CONVENTION ?) * CRUD * get * post * put * patch * delete # resources * http://blog.jonathanargentiero.com/material-design-lite-color-classes-list/<file_sep>/resume/src/test/java/fr/geromeavecung/resume/materialcomponent/CardTitleTextTest.java package fr.geromeavecung.resume.materialcomponent; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class CardTitleTextTest { private CardTitleText systemUnderTest; @Mock private MaterialComponent title; @Mock private MaterialComponent supportingText; @Before public void arrange() { when(title.convertToHtml()).thenReturn("Lorem ipsum"); when(supportingText.convertToHtml()).thenReturn("dolor sit amet"); systemUnderTest = CardTitleText.create(title, supportingText); } @Test public void get() throws Exception { String actual = systemUnderTest.convertToHtml(); assertThat(actual).isEqualTo("<div class=\"mdl-card mdl-shadow--2dp\">" + "<div class=\"mdl-card__title mdl-card--expand\">" + "<h2 class=\"mdl-card__title-text\">Lorem ipsum</h2>" + "</div>" + "<div class=\"mdl-card__supporting-text\">" + "dolor sit amet" + "</div>" + "</div>"); } @Test public void get_alt() throws Exception { when(title.convertToHtml()).thenReturn("consectetur adipiscing elit"); when(supportingText.convertToHtml()).thenReturn("sed do eiusmod tempor"); String actual = systemUnderTest.convertToHtml(); assertThat(actual).isEqualTo("<div class=\"mdl-card mdl-shadow--2dp\">" + "<div class=\"mdl-card__title mdl-card--expand\">" + "<h2 class=\"mdl-card__title-text\">consectetur adipiscing elit</h2>" + "</div>" + "<div class=\"mdl-card__supporting-text\">" + "sed do eiusmod tempor" + "</div>" + "</div>"); } } <file_sep>/resume/src/main/java/fr/geromeavecung/resume/materialcomponent/ListItemIcon.java package fr.geromeavecung.resume.materialcomponent; import com.google.auto.value.AutoValue; import java.util.Map; import java.util.stream.Collectors; @AutoValue public abstract class ListItemIcon implements MaterialComponent { public static ListItemIcon create(Map<Icon,String> elements) { return new AutoValue_ListItemIcon(elements); } abstract Map<Icon,String> elements(); @Override public String convertToHtml() { String elems = elements().entrySet().stream().map(e -> "<li class=\"mdl-list__item\">" + "<span class=\"mdl-list__item-primary-content\">" + e.getKey().convertToHtml() + e.getValue() + "</span>" + "</li>").collect(Collectors.joining()); return "<ul class=\"mdl-list\">"+elems+"</ul>"; } } <file_sep>/resume/src/main/java/fr/geromeavecung/resume/printable/PrintableLayout.java package fr.geromeavecung.resume.printable; import java.util.List; import java.util.function.Supplier; import java.util.stream.Collectors; import com.google.auto.value.AutoValue; @AutoValue public abstract class PrintableLayout implements PrintableComponent { public static PrintableLayout create(PrintableComponent title, List<PrintableComponent> pages) { return new AutoValue_PrintableLayout(title, pages); } abstract PrintableComponent title(); abstract List<PrintableComponent> pages(); @Override public String get() { String content = pages().stream().map(Supplier::get).collect(Collectors.joining()); return "<!DOCTYPE html>" + "<html>" + "<head><title>" + title().get() + "</title>" + "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">" + "<link rel=\"stylesheet\" href=\"http://fonts.googleapis.com/css?family=Roboto:300,400,500,700\">" + "<link rel=\"stylesheet\" href=\"/styles-printable.css\">" + "</head>" + "<body\">" + content + "</body>" + "</html>"; } } <file_sep>/resume/src/main/java/fr/geromeavecung/resume/materialcomponent/CardTitleTextAction.java package fr.geromeavecung.resume.materialcomponent; import com.google.auto.value.AutoValue; import fr.geromeavecung.resume.model.RoutePath; @AutoValue public abstract class CardTitleTextAction implements MaterialComponent { public static CardTitleTextAction create(MaterialComponent title, MaterialComponent supportingText, MaterialComponent action) { return new AutoValue_CardTitleTextAction(title, supportingText, action); } abstract MaterialComponent title(); abstract MaterialComponent supportingText(); abstract MaterialComponent action(); @Override public String convertToHtml() { return "<div class=\"mdl-card mdl-shadow--2dp\">" + "<div class=\"mdl-card__title mdl-card--expand\">" + "<h2 class=\"mdl-card__title-text\">" + title().convertToHtml() + "</h2>" + "</div>" + "<div class=\"mdl-card__supporting-text\">" + supportingText().convertToHtml() + "</div><div class=\"mdl-card__actions mdl-card--border\">" + "<a class=\"mdl-button mdl-button--colored mdl-js-button mdl-js-ripple-effect\" href=\"" + RoutePath.PROJECTS.getPath() + "\">" + action().convertToHtml() + "</a>" + "</div>" + "</div>"; } } <file_sep>/resume/src/main/java/fr/geromeavecung/resume/materialcomponent/Text.java package fr.geromeavecung.resume.materialcomponent; import com.google.auto.value.AutoValue; @AutoValue public abstract class Text implements MaterialComponent { public static Text create(String text) { return new AutoValue_Text(text); } abstract String text(); @Override public String convertToHtml() { return text(); } } <file_sep>/resume/src/main/java/fr/geromeavecung/resume/materialcomponent/MaterialPageFactory.java package fr.geromeavecung.resume.materialcomponent; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.IntStream; import com.google.auto.value.AutoValue; import fr.geromeavecung.resume.model.DataFactory; import fr.geromeavecung.resume.model.Label; import fr.geromeavecung.resume.model.Project; import fr.geromeavecung.resume.model.RoutePath; @AutoValue public abstract class MaterialPageFactory { public static MaterialPageFactory create(DataFactory dataFactory) { return new AutoValue_MaterialPageFactory(dataFactory); } abstract DataFactory dataFactory(); public MaterialComponent contact(Locale locale) { Map<Icon, String> elements = contactLines(dataFactory().contact(locale), contactIcons()); Text contact = Text.create(Label.CONTACT.i18n(locale)); return Layout.create(contact, convert(dataFactory().menu(), locale), CardTitleText.create(contact, ListItemIcon.create(elements))); } public MaterialComponent education(Locale locale) { Map<String, String> elements = dataFactory().formations(locale); Text contact = Text.create(Label.EDUCATIONS.i18n(locale)); return Layout.create(contact, convert(dataFactory().menu(), locale), CardTitleText.create(contact, ListItemThreeLine.create(elements))); } public MaterialComponent skills(Locale locale) { Map<String, String> elements = dataFactory().skills(locale); Text contact = Text.create(Label.SKILLS.i18n(locale)); return Layout.create(contact, convert(dataFactory().menu(), locale), CardTitleText.create(contact, ListItemThreeLine.create(elements))); } public MaterialComponent interests(Locale locale) { Map<String, String> elements = dataFactory().interests(locale); Text contact = Text.create(Label.INTERESTS.i18n(locale)); return Layout.create(contact, convert(dataFactory().menu(), locale), CardTitleText.create(contact, ListItemThreeLine.create(elements))); } public MaterialComponent missions(Locale locale) { List<ItemThreeLineAction> items = dataFactory().missions(locale).stream().map(p -> convert(p, locale)).collect(Collectors.toList()); Text contact = Text.create(Label.PROJECTS.i18n(locale)); return Layout.create(contact, convert(dataFactory().menu(), locale), CardTitleText.create(contact, ListItemThreeLineAction.create(items))); } private ItemThreeLineAction convert(Project p, Locale locale) { return ItemThreeLineAction.create(p.title(), p.start(locale) + " &ndash; " + p.end(locale) + " &ndash; " + p.length(locale), p.id()); } private List<NavigationLinkIcon> convert(List<RoutePath> routes, Locale locale) { // FIXME bugged -> need to "filter" by i18n return routes.stream().map(r -> convert(r, locale)).collect(Collectors.toList()); } private NavigationLinkIcon convert(RoutePath r, Locale locale) { return NavigationLinkIcon.create(r.getPath(), r.getIcon(), r.getTitle().i18n(locale)); } public MaterialComponent mission(String id, Locale locale) { Project p = dataFactory().mission(id, locale); Text contact = Text.create(p.title()); return Layout.create(contact, convert(dataFactory().menu(), locale), CardTitleTextAction.create(contact, detail(p, locale), Text.create(Label.BACK.i18n(locale)))); } private MaterialComponent detail(Project p, Locale locale) { return Text.create(p.start(locale) + " &ndash; " + p.end(locale) + " &ndash; " + p.length(locale) + "<br/>" + p.content() + "<br/>" + Label.TECHNICAL_ENVIRONMENT.i18n(locale) + p.technologies()); } public MaterialComponent notFound(Locale locale, String idNotFound) { Text contact = Text.create(Label.NOT_FOUND.i18n(locale)); return Layout.create(contact, convert(dataFactory().menu(), locale), CardTitleText.create(contact, Text.create(Label.NOT_FOUND_TEXT.i18n(locale, idNotFound)))); } public MaterialComponent error(Locale locale, String message) { Text contact = Text.create(Label.SERVER_ERROR.i18n(locale)); return Layout.create(contact, convert(dataFactory().menu(), locale), CardTitleText.create(contact, Text.create(message))); } private Map<Icon, String> contactLines(List<String> contact, List<Icon> icons) { return IntStream.range(0, contact.size()).boxed().collect(Collectors.toMap(icons::get, contact::get)); } private List<Icon> contactIcons() { List<Icon> elements = new ArrayList<>(); elements.add(Icon.SCHOOL); elements.add(Icon.FACE); elements.add(Icon.MAIL_OUTLINE); elements.add(Icon.CALL); elements.add(Icon.CAKE); return elements; } } <file_sep>/resume/src/main/java/fr/geromeavecung/resume/materialcomponent/Icon.java package fr.geromeavecung.resume.materialcomponent; public enum Icon implements MaterialComponent { PERSON, SCHOOL, FACE, MAIL_OUTLINE, CALL, CAKE, BUSINESS_CENTER, NONE, BUILD, LOCAL_MOVIES, PRINT; @Override public String convertToHtml() { return "<i class=\"material-icons mdl-list__item-icon\">" + name().toLowerCase() + "</i>"; } } <file_sep>/resume/src/main/java/fr/geromeavecung/resume/materialcomponent/Layout.java package fr.geromeavecung.resume.materialcomponent; import java.util.List; import java.util.stream.Collectors; import com.google.auto.value.AutoValue; @AutoValue public abstract class Layout implements MaterialComponent { public static Layout create(MaterialComponent title, List<NavigationLinkIcon> links, MaterialComponent content) { return new AutoValue_Layout(title, links, content); } abstract MaterialComponent title(); abstract List<NavigationLinkIcon> links(); abstract MaterialComponent content(); @Override public String convertToHtml() { return "<!DOCTYPE html>" + "<html>" + "<head><title>" + title().convertToHtml() + "</title>" + "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">" + "<link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/icon?family=Material+Icons\">" + "<link rel=\"stylesheet\" href=\"https://code.getmdl.io/1.3.0/material.teal-orange.min.css\">" + "<link rel=\"stylesheet\" href=\"http://fonts.googleapis.com/css?family=Roboto:300,400,500,700\">" + "<link rel=\"stylesheet\" href=\"/styles.css\">" + "<script defer src=\"https://code.getmdl.io/1.3.0/material.min.js\"></script>" + "</head>" + "<body class=\"mdl-color--grey-300\">" + "<div class=\"mdl-layout mdl-js-layout\">" + "<header class=\"mdl-layout__header\">" + "<div class=\"mdl-layout-icon\"></div>" + "<div class=\"mdl-layout__header-row\">" + "<span class=\"mdl-layout__title\">" + title().convertToHtml() + "</span>" + "<div class=\"mdl-layout-spacer\"></div>" + "</div>" + "</header>" + "<div class=\"mdl-layout__drawer\">" + "<span class=\"mdl-layout__title\">Menu</span>" + "<nav class=\"mdl-navigation\">" + nav() + "</nav>" + "</div>" + "<main class=\"mdl-layout__content\">" + content().convertToHtml() + "</main>" + "</div>" + "</body>" + "</html>"; } private String nav() { return links().stream().map(NavigationLinkIcon::convertToHtml).collect(Collectors.joining()); } } <file_sep>/resume/src/main/java/fr/geromeavecung/resume/model/Project.java package fr.geromeavecung.resume.model; import com.google.auto.value.AutoValue; import java.time.LocalDate; import java.time.Period; import java.time.format.DateTimeFormatter; import java.util.Locale; @AutoValue public abstract class Project { public static Project create(String id, String title, LocalDate start, LocalDate end, LocalDate roundedEnd, String content, String technologies) { return new AutoValue_Project(id, title, start, end, roundedEnd, content, technologies); } public abstract String id(); public abstract String title(); abstract LocalDate start(); abstract LocalDate end(); abstract LocalDate roundedEnd(); public abstract String content(); public abstract String technologies(); public String start(Locale locale) { return format(start(), locale); } public String end(Locale locale) { if (LocalDate.now().equals(end())) { return Label.TODAY.i18n(locale); } return format(end(), locale); } private String format(LocalDate date, Locale locale) { String i18nDate = date.format(DateTimeFormatter.ofPattern("MMM yyyy", locale)); /* FR i18n has lower case first letter but EN is upper case */ return i18nDate.substring(0,1).toUpperCase() + i18nDate.substring(1); } public String length(Locale locale) { Period period = Period.between(start(), roundedEnd()); Integer years = period.getYears(); Integer months = period.getMonths(); Integer and = 0; if (years > 0 && months > 0) { and = 1; } return Label.YEAR_MONTH.i18n(locale, years, and, months); } } <file_sep>/resume/src/main/java/fr/geromeavecung/resume/materialcomponent/CardTitleText.java package fr.geromeavecung.resume.materialcomponent; import com.google.auto.value.AutoValue; @AutoValue public abstract class CardTitleText implements MaterialComponent { public static CardTitleText create(MaterialComponent title, MaterialComponent supportingText) { return new AutoValue_CardTitleText(title, supportingText); } abstract MaterialComponent title(); abstract MaterialComponent supportingText(); @Override public String convertToHtml() { return "<div class=\"mdl-card mdl-shadow--2dp\">" + "<div class=\"mdl-card__title mdl-card--expand\">" + "<h2 class=\"mdl-card__title-text\">" + title().convertToHtml() + "</h2>" + "</div>" + "<div class=\"mdl-card__supporting-text\">" + supportingText().convertToHtml() + "</div>" + "</div>"; } } <file_sep>/resume/docker/Dockerfile FROM java:8 EXPOSE 8081 ADD resume-0.0.1-SNAPSHOT-jar-with-dependencies.jar resume-0.0.1-SNAPSHOT-jar-with-dependencies.jar ENTRYPOINT ["/usr/lib/jvm/java-8-openjdk-amd64/bin/java","-jar","resume-0.0.1-SNAPSHOT-jar-with-dependencies.jar"] # check with docker images # docker run -p 8081:8081 dockerspark # docker ps # docker container stop 1fa4ab2cf395<file_sep>/resume/src/test/java/fr/geromeavecung/resume/materialcomponent/ListItemIconTest.java package fr.geromeavecung.resume.materialcomponent; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Before; import org.junit.Test; import java.util.LinkedHashMap; import java.util.Map; public class ListItemIconTest { private ListItemIcon systemUnderTest; private Map<Icon,String> elements; @Before public void arrange() { elements = new LinkedHashMap<>(); elements.put(Icon.PERSON, "Lorem ipsum"); systemUnderTest = ListItemIcon.create(elements); } @Test public void get() throws Exception { String actual = systemUnderTest.convertToHtml(); assertThat(actual).isEqualTo("<ul class=\"mdl-list\"><li class=\"mdl-list__item\">" + "<span class=\"mdl-list__item-primary-content\">" + "<i class=\"material-icons mdl-list__item-icon\">person</i>" + "Lorem ipsum" + "</span>" + "</li></ul>"); } @Test public void get_alt() throws Exception { elements.put(Icon.SCHOOL, "dolor sit amet"); String actual = systemUnderTest.convertToHtml(); assertThat(actual).isEqualTo("<ul class=\"mdl-list\"><li class=\"mdl-list__item\">" + "<span class=\"mdl-list__item-primary-content\">" + "<i class=\"material-icons mdl-list__item-icon\">person</i>" + "Lorem ipsum" + "</span>" + "</li>" + "<li class=\"mdl-list__item\">" + "<span class=\"mdl-list__item-primary-content\">" + "<i class=\"material-icons mdl-list__item-icon\">school</i>" + "dolor sit amet" + "</span>" + "</li></ul>"); } } <file_sep>/resume/src/main/java/fr/geromeavecung/resume/printable/PrintableText.java package fr.geromeavecung.resume.printable; import com.google.auto.value.AutoValue; @AutoValue public abstract class PrintableText implements PrintableComponent { public static PrintableText create(String text) { return new AutoValue_PrintableText(text); } abstract String text(); @Override public String get() { return text(); } }
6378ddb0a425b73da9b30363306281fa3948ccb8
[ "Markdown", "Java", "Dockerfile" ]
16
Java
gerome-avec-un-g/spark-resume
e4820f84180bdfab0d38359eeede021102ef8cc6
4069026910aeb3795fc1e4f16623a2edca62d661
refs/heads/master
<file_sep>from django.db import models from django.utils.translation import ugettext_lazy as _ from sortedm2m.fields import SortedManyToManyField class Photo(models.Model): name = models.CharField(max_length=50) class Meta: verbose_name = _('Photo') verbose_name_plural = _('Photos') def __unicode__(self): return self.name class Gallery(models.Model): name = models.CharField(max_length=50) photos = SortedManyToManyField(Photo) photos2 = SortedManyToManyField(Photo, related_name='gallery2+') class Meta: verbose_name = _('Photo') verbose_name_plural = _('Photos') def __unicode__(self): return self.name <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import os, sys parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_project.settings") import django from django.core.management import execute_from_command_line if django.VERSION < (1, 6): default_test_apps = [ 'sortedm2m_tests', 'test_south_support', ] else: default_test_apps = [ 'sortedm2m_tests', ] # Only test south support for Django 1.6 and lower. if django.VERSION < (1, 7): default_test_apps += [ 'test_south_support', ] def runtests(*args): test_apps = list(args or default_test_apps) execute_from_command_line([sys.argv[0], 'test', '--verbosity=1'] + test_apps) if __name__ == '__main__': runtests(*sys.argv[1:]) <file_sep># -*- coding: utf-8 -*- import os import sys import shutil # Python 2 support. if sys.version_info < (3,): from StringIO import StringIO else: from io import StringIO import django # Django 1.5 support. if django.VERSION >= (1, 6): from django.db.utils import OperationalError, ProgrammingError from django.core.management import call_command from django.test import TestCase from django.test import TransactionTestCase from django.utils import six from sortedm2m.compat import get_apps_from_state from sortedm2m_tests.migrations_tests.models import Gallery, Photo from .compat import skipIf from .utils import capture_stdout str_ = six.text_type @skipIf(django.VERSION < (1, 7), 'New migrations framework only available in Django >= 1.7') class TestMigrateCommand(TransactionTestCase): def test_migrate(self): with capture_stdout(): call_command('migrate', interactive=False) @skipIf(django.VERSION < (1, 7), 'New migrations framework only available in Django >= 1.7') class TestMigrations(TransactionTestCase): def tearDown(self): # Remove created migrations. migrations_path = os.path.join( os.path.dirname(__file__), 'migrations_tests', 'django17_migrations') if os.path.exists(migrations_path): for filename in os.listdir(migrations_path): if filename not in ('__init__.py', '0001_initial.py'): filepath = os.path.join(migrations_path, filename) if os.path.isdir(filepath): shutil.rmtree(filepath) else: os.remove(filepath) def test_defined_migration(self): photo = Photo.objects.create(name='Photo') gallery = Gallery.objects.create(name='Gallery') # photos field is already migrated. self.assertEqual(gallery.photos.count(), 0) # photos2 field is not yet migrated. self.assertRaises((OperationalError, ProgrammingError), gallery.photos2.count) def test_make_migration(self): with capture_stdout(): call_command('makemigrations', 'migrations_tests') call_command('migrate') gallery = Gallery.objects.create(name='Gallery') self.assertEqual(gallery.photos.count(), 0) self.assertEqual(gallery.photos2.count(), 0) def test_stable_sorting_after_migration(self): with capture_stdout(): call_command('makemigrations', 'migrations_tests') call_command('migrate') p1 = Photo.objects.create(name='A') p2 = Photo.objects.create(name='C') p3 = Photo.objects.create(name='B') gallery = Gallery.objects.create(name='Gallery') gallery.photos = [p1, p2, p3] gallery.photos2 = [p3, p1, p2] gallery = Gallery.objects.get(name='Gallery') self.assertEqual(list(gallery.photos.values_list('name', flat=True)), ['A', 'C', 'B']) self.assertEqual(list(gallery.photos2.values_list('name', flat=True)), ['B', 'A', 'C']) gallery.photos = [p3, p2] self.assertEqual(list(gallery.photos.values_list('name', flat=True)), ['B', 'C']) gallery = Gallery.objects.get(name='Gallery') self.assertEqual(list(gallery.photos.values_list('name', flat=True)), ['B', 'C']) @skipIf(django.VERSION < (1, 7), 'New migrations framework only available in Django >= 1.7') class TestAlterSortedManyToManyFieldOperation(TransactionTestCase): def setUp(self): from django.db.migrations.executor import MigrationExecutor from django.db.migrations.loader import MigrationLoader from django.db import connection self.migration_executor = MigrationExecutor(connection) self.migration_loader = MigrationLoader(connection) self.state_0001 = self.migration_loader.project_state( ('altersortedmanytomanyfield_tests', '0001_initial')) self.state_0002 = self.migration_loader.project_state( ('altersortedmanytomanyfield_tests', '0002_alter_m2m_fields')) self.state_0001_apps = get_apps_from_state(self.state_0001) self.state_0002_apps = get_apps_from_state(self.state_0002) # Make sure we are at the latest migration when starting the test. with capture_stdout(): call_command('migrate', 'altersortedmanytomanyfield_tests') def test_apply_migrations_backwards(self): with capture_stdout(): call_command('migrate', 'altersortedmanytomanyfield_tests', '0001') def test_operation_m2m_to_sorted_m2m(self): # Let's start with state after 0001 with capture_stdout(): call_command('migrate', 'altersortedmanytomanyfield_tests', '0001') Target = self.state_0001_apps.get_model( 'altersortedmanytomanyfield_tests', 'target') M2MToSortedM2M = self.state_0001_apps.get_model( 'altersortedmanytomanyfield_tests', 'm2mtosortedm2m') t1 = Target.objects.create(pk=1) t2 = Target.objects.create(pk=2) t3 = Target.objects.create(pk=3) field = M2MToSortedM2M._meta.get_field_by_name('m2m')[0] through_model = field.rel.through # No ordering is in place. self.assertTrue(not through_model._meta.ordering) instance = M2MToSortedM2M.objects.create(pk=1) instance.m2m.add(t3) instance.m2m.add(t1) instance.m2m.add(t2) # We cannot assume any particular order now. # Migrate to state 0002, then we should be able to apply order. with capture_stdout(): call_command('migrate', 'altersortedmanytomanyfield_tests', '0002') Target = self.state_0002_apps.get_model( 'altersortedmanytomanyfield_tests', 'target') M2MToSortedM2M = self.state_0002_apps.get_model( 'altersortedmanytomanyfield_tests', 'm2mtosortedm2m') t1 = Target.objects.get(pk=1) t2 = Target.objects.get(pk=2) t3 = Target.objects.get(pk=3) field = M2MToSortedM2M._meta.get_field_by_name('m2m')[0] through_model = field.rel.through # Now, ordering is there. self.assertTrue(list(through_model._meta.ordering), ['sort_value']) instance = M2MToSortedM2M.objects.get(pk=1) self.assertEqual(list(instance.m2m.order_by('pk')), [t1, t2, t3]) instance.m2m = [t3, t1, t2] self.assertEqual(list(instance.m2m.all()), [t3, t1, t2]) instance.m2m.remove(t1) instance.m2m.remove(t2) instance.m2m.add(t2) instance.m2m.add(t1) self.assertEqual(list(instance.m2m.all()), [t3, t2, t1]) <file_sep># -*- coding: utf-8 -*- from django.conf.urls import include, patterns, url from django.contrib import admin from django.conf import settings from django.http import HttpResponse admin.autodiscover() def handle404(request): return HttpResponse('404') def handle500(request): return HttpResponse('404') handler404 = 'example.urls.handle404' handler500 = 'example.urls.handle500' urlpatterns = patterns('', url(r'^media/(.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}), url(r'^admin/', include(admin.site.urls), name="admin"), url(r'^parkingarea/(?P<pk>\d+)/$', 'example.testapp.views.parkingarea_update', name='parkingarea'), url(r'^', include('django.contrib.staticfiles.urls')), ) <file_sep>__author__ = 'jelle' <file_sep># -*- coding: utf-8 -*- from django.db import models from ..models import Photo from sortedm2m.fields import SortedManyToManyField # this model is not considered in the existing migrations. South will try to # create this model. class CompleteNewPhotoStream(models.Model): name = models.CharField(max_length=30) new_photos = SortedManyToManyField(Photo, sorted=True) def __unicode__(self): return self.name <file_sep># -*- coding: utf-8 -*- from django.db import models from sortedm2m.fields import SortedManyToManyField class Photo(models.Model): name = models.CharField(max_length=30) def __unicode__(self): return self.name class Gallery(models.Model): name = models.CharField(max_length=30) photos = SortedManyToManyField(Photo) def __unicode__(self): return self.name class UnsortedGallery(models.Model): name = models.CharField(max_length=30) photos = SortedManyToManyField(Photo, sorted=False) def __unicode__(self): return self.name <file_sep>[tox] minversion = 1.8 envlist = py26-{15,16}, py27-{15,16,17,18}, py33-{16,17,18}, py34-{16,17,18}, pypy-{15,16,17,18} [testenv] commands = python runtests.py deps = 14: Django >= 1.4, < 1.5 15: Django >= 1.5, < 1.6 16: Django >= 1.6, < 1.7 17: Django >= 1.7, < 1.8 18: Django >= 1.8, < 1.9 master: https://github.com/django/django/tarball/master#egg=Django postgres: psycopg2 mysql: MySQL-python -r{toxinidir}/requirements/tests.txt setenv = DJANGO_SETTINGS_MODULE = test_project.settings postgres: DJANGO_SETTINGS_MODULE = test_project.postgres_settings mysql: DJANGO_SETTINGS_MODULE = test_project.mysql_settings [testenv:vagrant-postgres] # A test environment utilizing a virtual machine for easy testing with # postgresql databases. To run tests using this environment, execute: # # tox -e vagrant-postgres commands = vagrant up vagrant ssh -c "cd /vagrant && DJANGO_SETTINGS_MODULE=test_project.postgres_settings python runtests.py" [testenv:vagrant-mysql] # A test environment utilizing a virtual machine for easy testing with # mysql databases. To run tests using this environment, execute: # # tox -e vagrant-mysql commands = vagrant up vagrant ssh -c "cd /vagrant && DJANGO_SETTINGS_MODULE=test_project.mysql_settings python runtests.py" <file_sep>#!/usr/bin/env python # -*- coding: utf-8 -*- import codecs import os import re import sys from setuptools import setup def find_version(*file_paths): version_file = read(*file_paths) version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError("Unable to find version string.") def read(*parts): return codecs.open(os.path.join(os.path.dirname(__file__), *parts), encoding='utf8').read() try: bytes except NameError: bytes = str class UltraMagicString(object): ''' Taken from http://stackoverflow.com/questions/1162338/whats-the-right-way-to-use-unicode-metadata-in-setup-py ''' def __init__(self, value): if not isinstance(value, bytes): value = value.encode('utf8') self.value = value def __bytes__(self): return self.value def __unicode__(self): return self.value.decode('UTF-8') if sys.version_info[0] < 3: __str__ = __bytes__ else: __str__ = __unicode__ def __add__(self, other): return UltraMagicString(self.value + bytes(other)) def split(self, *args, **kw): return str(self).split(*args, **kw) long_description = UltraMagicString('\n\n'.join(( read('README.rst'), read('CHANGES.rst'), ))) setup( name = 'django-sortedm2m', version = find_version('sortedm2m', '__init__.py'), url = 'http://github.com/gregmuellegger/django-sortedm2m', license = 'BSD', description = 'Drop-in replacement for django\'s many to many field with ' 'sorted relations.', long_description = long_description, author = UltraMagicString('<NAME>'), author_email = '<EMAIL>', packages = ['sortedm2m'], include_package_data = True, zip_safe = False, classifiers = [ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', ], install_requires = [], ) <file_sep># -*- coding: utf-8 -*- import django from django.conf import settings from django.db import router from django.db import transaction from django.db import models from django.db.models import signals from django.db.models.fields.related import add_lazy_relation, create_many_related_manager from django.db.models.fields.related import ManyToManyField, ReverseManyRelatedObjectsDescriptor from django.db.models.fields.related import RECURSIVE_RELATIONSHIP_CONSTANT from django.utils import six from django.utils.functional import curry from .compat import get_foreignkey_field_kwargs from .compat import get_model from .compat import get_model_name from .forms import SortedMultipleChoiceField SORT_VALUE_FIELD_NAME = 'sort_value' if hasattr(transaction, 'atomic'): atomic = transaction.atomic # Django 1.5 support # We mock the atomic context manager. else: class atomic(object): def __init__(self, *args, **kwargs): pass def __enter__(self): pass def __exit__(self, exc_type, exc_val, exc_tb): pass def create_sorted_many_related_manager(superclass, rel): RelatedManager = create_many_related_manager(superclass, rel) class SortedRelatedManager(RelatedManager): def get_queryset(self): # We use ``extra`` method here because we have no other access to # the extra sorting field of the intermediary model. The fields # are hidden for joins because we set ``auto_created`` on the # intermediary's meta options. try: return self.instance._prefetched_objects_cache[self.prefetch_cache_name] except (AttributeError, KeyError): # Django 1.5 support. if not hasattr(RelatedManager, 'get_queryset'): queryset = super(SortedRelatedManager, self).get_query_set() else: queryset = super(SortedRelatedManager, self).get_queryset() return queryset.extra(order_by=['%s.%s' % ( rel.through._meta.db_table, rel.through._sort_field_name, )]) get_query_set = get_queryset if not hasattr(RelatedManager, '_get_fk_val'): @property def _fk_val(self): # Django 1.5 support. if not hasattr(self, 'related_val'): return self._pk_val return self.related_val[0] def get_prefetch_queryset(self, instances, queryset=None): # Django 1.5 support. The method name changed since. if django.VERSION < (1, 6): result = super(SortedRelatedManager, self).get_prefetch_query_set(instances) # Django 1.6 support. The queryset parameter was not supported. elif django.VERSION < (1, 7): result = super(SortedRelatedManager, self).get_prefetch_queryset(instances) else: result = super(SortedRelatedManager, self).get_prefetch_queryset(instances, queryset) queryset = result[0] queryset.query.extra_order_by = [ '%s.%s' % ( rel.through._meta.db_table, rel.through._sort_field_name, )] return (queryset,) + result[1:] get_prefetch_query_set = get_prefetch_queryset def _add_items(self, source_field_name, target_field_name, *objs): # source_field_name: the PK fieldname in join table for the source object # target_field_name: the PK fieldname in join table for the target object # *objs - objects to add. Either object instances, or primary keys of object instances. # If there aren't any objects, there is nothing to do. from django.db.models import Model if objs: # Django uses a set here, we need to use a list to keep the # correct ordering. new_ids = [] for obj in objs: if isinstance(obj, self.model): if not router.allow_relation(obj, self.instance): raise ValueError( 'Cannot add "%r": instance is on database "%s", value is on database "%s"' % (obj, self.instance._state.db, obj._state.db) ) if hasattr(self, '_get_fk_val'): # Django>=1.5 fk_val = self._get_fk_val(obj, target_field_name) if fk_val is None: raise ValueError('Cannot add "%r": the value for field "%s" is None' % (obj, target_field_name)) new_ids.append(self._get_fk_val(obj, target_field_name)) else: # Django<1.5 new_ids.append(obj.pk) elif isinstance(obj, Model): raise TypeError( "'%s' instance expected, got %r" % (self.model._meta.object_name, obj) ) else: new_ids.append(obj) db = router.db_for_write(self.through, instance=self.instance) vals = (self.through._default_manager.using(db) .values_list(target_field_name, flat=True) .filter(**{ source_field_name: self._fk_val, '%s__in' % target_field_name: new_ids, })) for val in vals: if val in new_ids: new_ids.remove(val) _new_ids = [] for pk in new_ids: if pk not in _new_ids: _new_ids.append(pk) new_ids = _new_ids new_ids_set = set(new_ids) if self.reverse or source_field_name == self.source_field_name: # Don't send the signal when we are inserting the # duplicate data row for symmetrical reverse entries. signals.m2m_changed.send(sender=rel.through, action='pre_add', instance=self.instance, reverse=self.reverse, model=self.model, pk_set=new_ids_set, using=db) # Add the ones that aren't there already sort_field_name = self.through._sort_field_name sort_field = self.through._meta.get_field_by_name(sort_field_name)[0] if django.VERSION < (1, 6): for obj_id in new_ids: self.through._default_manager.using(db).create(**{ '%s_id' % source_field_name: self._fk_val, # Django 1.5 compatibility '%s_id' % target_field_name: obj_id, sort_field_name: sort_field.get_default(), }) else: with transaction.atomic(): sort_field_default = sort_field.get_default() self.through._default_manager.using(db).bulk_create([ self.through(**{ '%s_id' % source_field_name: self._fk_val, '%s_id' % target_field_name: v, sort_field_name: sort_field_default + i, }) for i, v in enumerate(new_ids) ]) if self.reverse or source_field_name == self.source_field_name: # Don't send the signal when we are inserting the # duplicate data row for symmetrical reverse entries. signals.m2m_changed.send(sender=rel.through, action='post_add', instance=self.instance, reverse=self.reverse, model=self.model, pk_set=new_ids_set, using=db) return SortedRelatedManager class ReverseSortedManyRelatedObjectsDescriptor(ReverseManyRelatedObjectsDescriptor): @property def related_manager_cls(self): return create_sorted_many_related_manager( self.field.rel.to._default_manager.__class__, self.field.rel ) class SortedManyToManyField(ManyToManyField): ''' Providing a many to many relation that remembers the order of related objects. Accept a boolean ``sorted`` attribute which specifies if relation is ordered or not. Default is set to ``True``. If ``sorted`` is set to ``False`` the field will behave exactly like django's ``ManyToManyField``. ''' def __init__(self, to, sorted=True, **kwargs): self.sorted = sorted self.sort_value_field_name = kwargs.pop( 'sort_value_field_name', SORT_VALUE_FIELD_NAME) super(SortedManyToManyField, self).__init__(to, **kwargs) if self.sorted: self.help_text = kwargs.get('help_text', None) def deconstruct(self): # We have to persist custom added options in the ``kwargs`` # dictionary. For readability only non-default values are stored. name, path, args, kwargs = super(SortedManyToManyField, self).deconstruct() if self.sort_value_field_name is not SORT_VALUE_FIELD_NAME: kwargs['sort_value_field_name'] = self.sort_value_field_name if self.sorted is not True: kwargs['sorted'] = self.sorted return name, path, args, kwargs def contribute_to_class(self, cls, name): if not self.sorted: return super(SortedManyToManyField, self).contribute_to_class(cls, name) # To support multiple relations to self, it's useful to have a non-None # related name on symmetrical relations for internal reasons. The # concept doesn't make a lot of sense externally ("you want me to # specify *what* on my non-reversible relation?!"), so we set it up # automatically. The funky name reduces the chance of an accidental # clash. if self.rel.symmetrical and (self.rel.to == "self" or self.rel.to == cls._meta.object_name): self.rel.related_name = "%s_rel_+" % name super(ManyToManyField, self).contribute_to_class(cls, name) # The intermediate m2m model is not auto created if: # 1) There is a manually specified intermediate, or # 2) The class owning the m2m field is abstract. if not self.rel.through and not cls._meta.abstract: self.rel.through = self.create_intermediate_model(cls) # Add the descriptor for the m2m relation setattr(cls, self.name, ReverseSortedManyRelatedObjectsDescriptor(self)) # Set up the accessor for the m2m table name for the relation self.m2m_db_table = curry(self._get_m2m_db_table, cls._meta) # Populate some necessary rel arguments so that cross-app relations # work correctly. if isinstance(self.rel.through, six.string_types): def resolve_through_model(field, model, cls): field.rel.through = model add_lazy_relation(cls, self, self.rel.through, resolve_through_model) if hasattr(cls._meta, 'duplicate_targets'): # Django<1.5 if isinstance(self.rel.to, six.string_types): target = self.rel.to else: target = self.rel.to._meta.db_table cls._meta.duplicate_targets[self.column] = (target, "m2m") def get_internal_type(self): return 'ManyToManyField' def formfield(self, **kwargs): defaults = {} if self.sorted: defaults['form_class'] = SortedMultipleChoiceField defaults.update(kwargs) return super(SortedManyToManyField, self).formfield(**defaults) ############################### # Intermediate Model Creation # ############################### def get_intermediate_model_name(self, klass): return '%s_%s' % (klass._meta.object_name, self.name) def get_intermediate_model_meta_class(self, klass, from_field_name, to_field_name, sort_value_field_name): managed = True to_model = self.rel.to if isinstance(self.rel.to, six.string_types): if self.rel.to != RECURSIVE_RELATIONSHIP_CONSTANT: def set_managed(field, model, cls): field.rel.through._meta.managed = model._meta.managed or cls._meta.managed add_lazy_relation(klass, self, to_model, set_managed) else: managed = klass._meta.managed else: managed = klass._meta.managed or to_model._meta.managed options = { 'db_table': self._get_m2m_db_table(klass._meta), 'managed': managed, 'auto_created': klass, 'app_label': klass._meta.app_label, 'db_tablespace': klass._meta.db_tablespace, 'unique_together': ((from_field_name, to_field_name),), 'ordering': (sort_value_field_name,), 'verbose_name': '%(from)s-%(to)s relationship' % {'from': from_field_name, 'to': to_field_name}, 'verbose_name_plural': '%(from)s-%(to)s relationships' % {'from': from_field_name, 'to': to_field_name}, } # Django 1.6 support. if hasattr(self.model._meta, 'apps'): options.update({ 'apps': self.model._meta.apps, }) return type(str('Meta'), (object,), options) def get_rel_to_model_and_object_name(self, klass): if isinstance(self.rel.to, six.string_types): if self.rel.to != RECURSIVE_RELATIONSHIP_CONSTANT: to_model = self.rel.to to_object_name = to_model.split('.')[-1] else: to_model = klass to_object_name = to_model._meta.object_name else: to_model = self.rel.to to_object_name = to_model._meta.object_name return to_model, to_object_name def get_intermediate_model_sort_value_field_default(self, klass): def default_sort_value(name): model = get_model(klass._meta.app_label, name) # Django 1.5 support. if django.VERSION < (1, 6): return model._default_manager.count() else: from django.db.utils import ProgrammingError, OperationalError try: # We need to catch if the model is not yet migrated in the # database. The default function is still called in this case while # running the migration. So we mock the return value of 0. with transaction.atomic(): return model._default_manager.count() except (ProgrammingError, OperationalError): return 0 name = self.get_intermediate_model_name(klass) default_sort_value = curry(default_sort_value, name) return default_sort_value def get_intermediate_model_sort_value_field(self, klass): default_sort_value = self.get_intermediate_model_sort_value_field_default(klass) field_name = self.sort_value_field_name field = models.IntegerField(default=default_sort_value) return field_name, field def get_intermediate_model_from_field(self, klass): name = self.get_intermediate_model_name(klass) to_model, to_object_name = self.get_rel_to_model_and_object_name(klass) if self.rel.to == RECURSIVE_RELATIONSHIP_CONSTANT or to_object_name == klass._meta.object_name: field_name = 'from_%s' % to_object_name.lower() else: field_name = get_model_name(klass) field = models.ForeignKey(klass, related_name='%s+' % name, **get_foreignkey_field_kwargs(self)) return field_name, field def get_intermediate_model_to_field(self, klass): name = self.get_intermediate_model_name(klass) to_model, to_object_name = self.get_rel_to_model_and_object_name(klass) if self.rel.to == RECURSIVE_RELATIONSHIP_CONSTANT or to_object_name == klass._meta.object_name: field_name = 'to_%s' % to_object_name.lower() else: field_name = to_object_name.lower() field = models.ForeignKey(to_model, related_name='%s+' % name, **get_foreignkey_field_kwargs(self)) return field_name, field def create_intermediate_model_from_attrs(self, klass, attrs): name = self.get_intermediate_model_name(klass) return type(str(name), (models.Model,), attrs) def create_intermediate_model(self, klass): # Construct and return the new class. from_field_name, from_field = self.get_intermediate_model_from_field(klass) to_field_name, to_field = self.get_intermediate_model_to_field(klass) sort_value_field_name, sort_value_field = self.get_intermediate_model_sort_value_field(klass) meta = self.get_intermediate_model_meta_class( klass, from_field_name, to_field_name, sort_value_field_name) attrs = { 'Meta': meta, '__module__': klass.__module__, from_field_name: from_field, to_field_name: to_field, sort_value_field_name: sort_value_field, '_sort_field_name': sort_value_field_name, '_from_field_name': from_field_name, '_to_field_name': to_field_name, } return self.create_intermediate_model_from_attrs(klass, attrs) # Add introspection rules for South database migrations # See http://south.aeracode.org/docs/customfields.html try: import south except ImportError: south = None if south is not None and 'south' in settings.INSTALLED_APPS: from south.modelsinspector import add_introspection_rules add_introspection_rules( [( (SortedManyToManyField,), [], {"sorted": ["sorted", {"default": True}]}, )], [r'^sortedm2m\.fields\.SortedManyToManyField'] ) # Monkeypatch South M2M actions to create the sorted through model. # FIXME: This doesn't detect if you changed the sorted argument to the field. import south.creator.actions from south.creator.freezer import model_key class AddM2M(south.creator.actions.AddM2M): SORTED_FORWARDS_TEMPLATE = ''' # Adding SortedM2M table for field %(field_name)s on '%(model_name)s' db.create_table(%(table_name)r, ( ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)), (%(left_field)r, models.ForeignKey(orm[%(left_model_key)r], null=False)), (%(right_field)r, models.ForeignKey(orm[%(right_model_key)r], null=False)), (%(sort_field)r, models.IntegerField()) )) db.create_unique(%(table_name)r, [%(left_column)r, %(right_column)r])''' def console_line(self): if isinstance(self.field, SortedManyToManyField) and self.field.sorted: return " + Added SortedM2M table for %s on %s.%s" % ( self.field.name, self.model._meta.app_label, self.model._meta.object_name, ) else: return super(AddM2M, self).console_line() def forwards_code(self): if isinstance(self.field, SortedManyToManyField) and self.field.sorted: return self.SORTED_FORWARDS_TEMPLATE % { "model_name": self.model._meta.object_name, "field_name": self.field.name, "table_name": self.field.m2m_db_table(), "left_field": self.field.m2m_column_name()[:-3], # Remove the _id part "left_column": self.field.m2m_column_name(), "left_model_key": model_key(self.model), "right_field": self.field.m2m_reverse_name()[:-3], # Remove the _id part "right_column": self.field.m2m_reverse_name(), "right_model_key": model_key(self.field.rel.to), "sort_field": self.field.sort_value_field_name, } else: return super(AddM2M, self).forwards_code() class DeleteM2M(AddM2M): def console_line(self): return " - Deleted M2M table for %s on %s.%s" % ( self.field.name, self.model._meta.app_label, self.model._meta.object_name, ) def forwards_code(self): return AddM2M.backwards_code(self) def backwards_code(self): return AddM2M.forwards_code(self) south.creator.actions.AddM2M = AddM2M south.creator.actions.DeleteM2M = DeleteM2M <file_sep>import django try: from django.apps import apps except ImportError: apps = None if apps is not None: get_model = apps.get_model else: from django.db.models import get_model def get_model_name(model): # Django 1.5 support. if not hasattr(model._meta, 'model_name'): return model._meta.object_name.lower() else: return model._meta.model_name def get_foreignkey_field_kwargs(field): # Django 1.5 support. if django.VERSION < (1, 6): return {} else: return dict( db_tablespace=field.db_tablespace, db_constraint=field.rel.db_constraint) def get_field(model, field_name): if django.VERSION < (1, 8): return model._meta.get_field_by_name(field_name)[0] else: return model._meta.get_field(field_name) def get_apps_from_state(migration_state): if django.VERSION < (1, 8): return migration_state.render() else: return migration_state.apps <file_sep># -*- coding: utf-8 -*- from django.db import models from sortedm2m.fields import SortedManyToManyField class Car(models.Model): plate = models.CharField(max_length=50) def __unicode__(self): return self.plate class ParkingArea(models.Model): name = models.CharField(max_length=50) cars = SortedManyToManyField(Car) def __unicode__(self): return self.name @models.permalink def get_absolute_url(self): return 'parkingarea', (self.pk,), {} <file_sep># -*- coding: utf-8 -*- from django.db import models from sortedm2m.fields import SortedManyToManyField class Shelf(models.Model): books = SortedManyToManyField('Book', related_name='shelves') class Book(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return self.name class DoItYourselfShelf(models.Model): books = SortedManyToManyField(Book, sort_value_field_name='diy_sort_number', related_name='diy_shelves') class Store(models.Model): books = SortedManyToManyField('sortedm2m_tests.Book', related_name='stores') class MessyStore(models.Model): books = SortedManyToManyField('Book', sorted=False, related_name='messy_stores') class SelfReference(models.Model): me = SortedManyToManyField('self', related_name='hide+') def __unicode__(self): return unicode(self.pk) <file_sep># -*- coding: utf-8 -*- import django import sys from itertools import chain from django import forms from django.conf import settings from django.db.models.query import QuerySet from django.template.loader import render_to_string from django.utils.encoding import force_text from django.utils.html import conditional_escape, escape from django.utils.safestring import mark_safe from django.forms.util import flatatt from django.utils.translation import ugettext_lazy as _ if sys.version_info[0] < 3: iteritems = lambda d: iter(d.iteritems()) string_types = basestring, str_ = unicode else: iteritems = lambda d: iter(d.items()) string_types = str, str_ = str STATIC_URL = getattr(settings, 'STATIC_URL', settings.MEDIA_URL) class SortedCheckboxSelectMultiple(forms.CheckboxSelectMultiple): class Media: js = ( STATIC_URL + 'sortedm2m/widget.js', STATIC_URL + 'sortedm2m/jquery-ui.js', ) css = {'screen': ( STATIC_URL + 'sortedm2m/widget.css', )} def build_attrs(self, attrs=None, **kwargs): attrs = super(SortedCheckboxSelectMultiple, self).\ build_attrs(attrs, **kwargs) classes = attrs.setdefault('class', '').split() classes.append('sortedm2m') attrs['class'] = ' '.join(classes) return attrs def render(self, name, value, attrs=None, choices=()): if value is None: value = [] has_id = attrs and 'id' in attrs final_attrs = self.build_attrs(attrs, name=name) # Normalize to strings str_values = [force_text(v) for v in value] selected = [] unselected = [] for i, (option_value, option_label) in enumerate(chain(self.choices, choices)): # If an ID attribute was given, add a numeric index as a suffix, # so that the checkboxes don't all have the same ID attribute. if has_id: final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i)) label_for = ' for="%s"' % conditional_escape(final_attrs['id']) else: label_for = '' cb = forms.CheckboxInput(final_attrs, check_test=lambda value: value in str_values) option_value = force_text(option_value) rendered_cb = cb.render(name, option_value) option_label = conditional_escape(force_text(option_label)) item = {'label_for': label_for, 'rendered_cb': rendered_cb, 'option_label': option_label, 'option_value': option_value} if option_value in str_values: selected.append(item) else: unselected.append(item) # re-order `selected` array according str_values which is a set of `option_value`s in the order they should be shown on screen ordered = [] for value in str_values: for select in selected: if value == select['option_value']: ordered.append(select) selected = ordered html = render_to_string( 'sortedm2m/sorted_checkbox_select_multiple_widget.html', {'selected': selected, 'unselected': unselected}) return mark_safe(html) def value_from_datadict(self, data, files, name): value = data.get(name, None) if isinstance(value, string_types): return [v for v in value.split(',') if v] return value if django.VERSION < (1, 7): def _has_changed(self, initial, data): if initial is None: initial = [] if data is None: data = [] if len(initial) != len(data): return True initial_set = [force_text(value) for value in initial] data_set = [force_text(value) for value in data] return data_set != initial_set class SortedMultipleChoiceField(forms.ModelMultipleChoiceField): def __init__(self, *args, **kwargs): if not kwargs.get('widget'): kwargs['widget'] = SortedFilteredSelectMultiple( is_stacked=kwargs.get('is_stacked', False) ) super(SortedMultipleChoiceField, self).__init__(*args, **kwargs) def clean(self, value): queryset = super(SortedMultipleChoiceField, self).clean(value) if value is None or not isinstance(queryset, QuerySet): return queryset object_list = dict(( (str_(key), value) for key, value in iteritems(queryset.in_bulk(value)))) return [object_list[str_(pk)] for pk in value] def _has_changed(self, initial, data): if initial is None: initial = [] if data is None: data = [] if len(initial) != len(data): return True initial_set = [force_text(value) for value in self.prepare_value(initial)] data_set = [force_text(value) for value in data] return data_set != initial_set class SortedFilteredSelectMultiple(forms.SelectMultiple): """ A SortableSelectMultiple with a JavaScript filter interface. Requires jQuery to be loaded. Note that the resulting JavaScript assumes that the jsi18n catalog has been loaded in the page """ def __init__(self, is_stacked, attrs=None, choices=()): self.is_stacked = is_stacked super(SortedFilteredSelectMultiple, self).__init__(attrs, choices) class Media: css = { 'screen': (STATIC_URL + 'sortedm2m/widget.css',) } js = (STATIC_URL + 'sortedm2m/OrderedSelectBox.js', STATIC_URL + 'sortedm2m/OrderedSelectFilter.js', STATIC_URL + 'admin/js/inlines.js') def build_attrs(self, attrs=None, **kwargs): attrs = super(SortedFilteredSelectMultiple, self).\ build_attrs(attrs, **kwargs) classes = attrs.setdefault('class', '').split() classes.append('sortedm2m') if self.is_stacked: classes.append('stacked') attrs['class'] = u' '.join(classes) return attrs def render(self, name, value, attrs=None, choices=()): if attrs is None: attrs = {} if value is None: value = [] admin_media_prefix = STATIC_URL + 'admin/' final_attrs = self.build_attrs(attrs, name=name) output = [u'<select multiple="multiple"%s>' % flatatt(final_attrs)] options = self.render_options(choices, value) if options: output.append(options) output.append(u'</select>') output.append(u'<script>addEvent(window, "load", function(e) {') output.append(u'OrderedSelectFilter.init("id_%s", "%s", %s, "%s") });</script>\n' %\ (name, name.split('-')[-1], int(self.is_stacked), admin_media_prefix)) prefix_name = name.split('-')[0] output.append(u""" <script> (function($) { $(document).ready(function() { var rows = "#%s-group .inline-related"; var updateOrderedSelectFilter = function() { // If any SelectFilter widgets are a part of the new form, // instantiate a new SelectFilter instance for it. if (typeof OrderedSelectFilter != "undefined"){ $(".sortedm2m").each(function(index, value){ var namearr = value.name.split('-'); OrderedSelectFilter.init(value.id, namearr[namearr.length-1], false, "%s"); }); $(".sortedm2mstacked").each(function(index, value){ var namearr = value.name.split('-'); OrderedSelectFilter.init(value.id, namearr[namearr.length-1], true, "%s"); }); } } $(rows).formset({ prefix: "%s", addText: "%s %s", formCssClass: "dynamic-%s", deleteCssClass: "inline-deletelink", deleteText: "Remove", emptyCssClass: "empty-form", added: (function(row) { updateOrderedSelectFilter(); }) }); }); })(django.jQuery) </script>""" % ( prefix_name, admin_media_prefix, admin_media_prefix, prefix_name, _('Add another'), name.split('-')[-1], prefix_name)) return mark_safe(u'\n'.join(output)) def render_option(self, selected_choices, option_value, option_label): option_value = force_text(option_value) selected_html = (option_value in selected_choices) and u' selected="selected"' or '' try: index = list(selected_choices).index(escape(option_value)) selected_html = u'%s %s' % (u' data-sort-value="%s"' % index, selected_html) except ValueError: pass return u'<option value="%s"%s>%s</option>' % ( escape(option_value), selected_html, conditional_escape(force_text(option_label))) def render_options(self, choices, selected_choices): # Normalize to strings. selected_choices = list(force_text(v) for v in selected_choices) output = [] for option_value, option_label in chain(self.choices, choices): if isinstance(option_label, (list, tuple)): output.append(u'<optgroup label="%s">' % escape(force_text(option_value))) for option in option_label: output.append(self.render_option(selected_choices, *option)) output.append(u'</optgroup>') else: output.append(self.render_option(selected_choices, option_value, option_label)) return u'\n'.join(output) def _has_changed(self, initial, data): if initial is None: initial = [] if data is None: data = [] if len(initial) != len(data): return True initial_set = [force_text(value) for value in initial] data_set = [force_text(value) for value in data] return data_set != initial_set
aca4858b81fe8eca0b74c3dbbf4bf1cc87d39f7d
[ "Python", "INI" ]
14
Python
fabrique/django-sortedm2m
cd76c2eb179083b9edf7d772751261a728df0869
74d760e28b642b0519f8a608a5a31c56dc8a9ba0
refs/heads/master
<repo_name>venky-kadiri/venky-<file_sep>/Fifth.java import java.io.*; import java.util.*; class Fifth { public static void main(String[]args) { Scanner sc= new Scanner(System.in); int n=sc.nextInt(); int s[]=new int[n]; for(int i=0;i<n;i++) { s[i]=sc.nextInt(); } int max1=s[0],max2=s[1],temp,min1=s[0],min2=s[1]; if (max1 < max2) { temp = max1; max1 = max2; max2 = temp; } if (min1 > min2) { temp = min1; min1 = min2; min2 = temp; } for(int i=2;i<n;i++) { if(max1<s[i]) { max2=max1; max1=s[i]; } else if (s[i] > max2 && s[i] != max1) { max2 = s[i]; } if(min1>s[i]) { min2=min1; min1=s[i]; } else if(min2>s[i] && s[i]!=min1) { min2 = s[i]; } } System.out.println(max1+"&"+max2+" are max1 and max2"); System.out.println(min1+"&"+min2+" are min1 and min2"); } }<file_sep>/Sixth.java import java.io.*; import java.util.*; class Sixth { public static void main(String[]args) { Scanner sc= new Scanner(System.in); int temp; int n=sc.nextInt(); int s[]=new int[n]; for(int i=0;i<n;i++) { s[i]=sc.nextInt(); } for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++) { if(s[i]>s[j]) { temp=s[i]; s[i]=s[j]; s[j]=temp; } } } for(int k=0;k<n;k++) { System.out.print(s[k]+" "); } } }<file_sep>/SecondArray.java import java.io.*; import java.util.*; class SecondArray { public static void main(String[]args) { Scanner sc= new Scanner(System.in); int n=sc.nextInt(); int a[]=new int[n]; int min=999,max=0; for(int i=0;i<n;i++) { a[i]=sc.nextInt(); if(min>a[i]) { min=a[i]; } if(max<a[i]) { max=a[i]; } } System.out.println("min value:"+min+"\n"+"max value:"+max); }}
1c89949eb49ce005e7af3c03ccfa42f05e6b0f07
[ "Java" ]
3
Java
venky-kadiri/venky-
fe076871d53dbf65d590b22ad5ee5f43c22f372b
0db71966d5654bf6282ac9781dfcc641d84f0837
refs/heads/master
<file_sep>CREATE TABLE users (id serial PRIMARY KEY, email text, token text, username text, image text, bio text); <file_sep>CREATE TABLE tags (id BIGSERIAL PRIMARY KEY, name VARCHAR(30) UNIQUE); <file_sep>-- :name create-user! :<! -- :doc creates a new user record INSERT INTO users (username, email, token, image, bio) VALUES (:username, :email, :token, :image, :bio) RETURNING id -- :name get-user :? :1 -- :doc retrieve a user given the id. SELECT * FROM users WHERE id = :id -- :name delete-user! :! :n -- :doc delete a user given the id DELETE FROM users WHERE id = :id ----------------------- TAGS -------------------- -- :name create-tag! :! :n -- :doc creates a new tag record INSERT INTO tags (name) VALUES (:name) -- :name get-tags :? :* -- :doc retrieve all tags. SELECT * FROM tags -- :name delete-all-tags! :! :n -- :doc utility method to clean test database DELETE FROM tags
40f8215e24aa744f12e7cbe67e294e24ad2e80ec
[ "SQL" ]
3
SQL
marksto/conduit-luminus
060cb4cc225f994ac7c9d70d32e869b772a6bb80
3defdcb4b14bee139fff61d3541378018cc925ea
refs/heads/master
<file_sep># # This file is part of forkexec # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # author: <NAME> <<EMAIL>> # import signal; import json; class MonitorCommand(object): attr_list = list(); id = 0; def get_attributes(self): h = dict(); for a in self.attr_list: h[a] = getattr(self, a); h["__name__"] = self.__class__.__name__ return h; def set_attributes(self, h): h.pop("__name__", None) for a in h.keys(): setattr(self, a, h[a]); def to_json(self): return json.dumps(self.get_attributes()); @classmethod def from_json(klass, json_s): if not json_s: return None; h = json.loads(json_s); name = h.pop("__name__", None); if not name: return None; cls = None; for k in MonitorCommand.__subclasses__(): if k.__name__ == name: cls = k; break; if not cls: return None; cls_i = cls(); cls_i.set_attributes(h); return cls_i; class Touch(MonitorCommand): FILENAME="touch"; class Shutdown(MonitorCommand): attr_list = ["type"]; KILL="kill"; TERM="term"; INIT="init"; def __init__(self, type=None): self.type = type; class Restart(MonitorCommand): pass; class Alias(MonitorCommand): attr_list = ["alias"]; def __init__(self, alias = None): self.alias = alias; class Info(MonitorCommand): pass; class InfoResponse(MonitorCommand): attr_list = ["id", "pid", "started", "init"]; def __init__(self, id = None, pid = None, started = None, init = None): self.id = id; self.pid = pid; self.started = started; self.init = init; class Signal(MonitorCommand): attr_list = ["signal"]; SIGNALS={ 'TERM': signal.SIGTERM, 'KILL': signal.SIGKILL, 'HUP': signal.SIGHUP }; def __init__(self, signal=None): self.signal = signal; class Ping(MonitorCommand): pass; class Pong(MonitorCommand): pass; if __name__ == "__main__": assert MonitorCommand.from_json(ResponsePid(1234).to_json()).pid == 1234; assert MonitorCommand.from_json(Alias("foo").to_json()).alias == "foo"; <file_sep>from forkexec.monitor import Monitor from forkexec.daemonize import Daemon import forkexec.commands as commands class ConsolePrinter: def info(self, *texts): print ' '.join([str(s) for s in texts]); def error(self, *texts): self.info(*texts); def format(self, text, *args): result = list(); i = 0; l = 0; h = 0; for c in text: if c == '?': result.append(text[l:h]); if i < len(args): result.append(str(args[i])); i += 1; else: result.append("<none>"); l = h + 1; h += 1; result.append(text[l:h]); self.info(''.join(result)); class MonitorDaemon(Daemon): def run(self): import signal init = self.args[0]; self.m = Monitor( self.home, init=init ); if not self.m.spawn(): self.m.remove(); sys.exit(1); try: self.m.run(); except Exception, e: import traceback self.m.log(traceback.format_exc()); #def signal_handler(self, signal, frame): # self.m.shutdown(); # sys.exit(0); def get_time(seconds): hours = None; minutes = None; if seconds < 120.0: pass; elif seconds < 3600.0: minutes = int(seconds / 60.0); seconds = seconds % 60; else: hours = int(seconds / 3600.0); minutes = int(seconds / 60.0) % 60; seconds = seconds % 60; parts = list(); if hours: if hours <= 1: parts.append( "%d hour"%( hours ) ); else: parts.append( "%d hours"%( hours ) ); if minutes: if minutes <= 1: parts.append( "%d minute"%( minutes ) ); else: parts.append( "%d minutes"%( minutes ) ); parts.append( "%.2f seconds"%( seconds ) ); return ", ".join( parts ); def print_help(p): p.info( "Author: <NAME> <<EMAIL>>" ) p.info( "License: GPLv3" ) p.info( "" ) p.info( "Usage: fex <command>" ) p.info( "" ) p.info( "Valid <command>s are:" ) p.info( " start <process> - start a new process" ) p.info( " stop <id> - kill a running process" ) p.info( " restart <id> - restart a running process" ) p.info( " ls-run <id> - list running processes" ) p.info( " ls-init <process> - list available init processes" ) p.info( " info <id> - display info about a running process" ) p.info( "" ) p.info( "<id> can also be just the first letters of a long id if there is only a single match" ); p.info( "<process> must be an executable under $FE_HOME/init/<process>" ) p.info( "" ) p.info( "Commands can be matched using '-' as a delimiter, and closest possible match:" ) p.info( " 'l-r' equals list-run (or ls-run)" ) p.info( " 'l-i' equals list-init (or ls-init)" ) p.info( "" ) p.info( "Multiple matches like 's' will give an error" ) p.info( "" ) def match_one_running(p, h, id): r = h.select_runs(id); if len(r) <= 0: p.info( "No match:", id ); return None; if len(r) > 1: p.info( "Too many matches:", id ); for i in r: p.format( "(?)?", id, i[len(id):] ) return None; return r[0]; def c_start(p, h, args): id = None; if len(args) > 0: id = args.pop(); r = h.select_inits(id); if len(r) == 0: p.info( "No matching init files" ) return 1; if len(r) > 1: if id is not None: p.info( "Cannot start, please match only one init file:" ) for f in r: p.info( f ); return 1; match = r.pop(); p.info( "Starting:", match ) MonitorDaemon(h, [match], daemonize=True).start(); def c_stop(p, h, args): if len(args) == 0: p.info( "No processes stopped" ) return 1; while len(args) > 0: id = match_one_running( p, h, args.pop() ); if not id: continue; p.info( "Shutting down:", id ) m = Monitor(h, id); if not m.send( commands.Shutdown( commands.Shutdown.TERM ) ): p.info( "Unable to shutdown, cleaning id:", id ) m.clean(); def c_restart(p, h, args): if len(args) == 0: p.info( "No processes restarted" ) return 1; while len(args) > 0: id = match_one_running( p, h, args.pop() ); if not id: continue; p.info( "Restarting:", id ) m = Monitor(h, id); if not m.send( commands.Restart() ): p.info( "Unable to restart, cleaning id:", id ) h.clean(id); def c_info(p, h, args): if len(args) == 0: return 1; id = match_one_running( p, h, args.pop() ); if not id: return 1; m = Monitor(h, id); result = m.communicate(commands.Info()); if result: p.format("id: ?", result.id ); p.format("init: ?", h.get_init( result.init ).path ); p.format("pid: ?", result.pid ); p.format("running: ?", get_time( result.started ) ); else: p.info( "Unable to get info" ) def c_running(p, h, args): import os; id = None; if len(args) > 0: id = args.pop(); r = h.select_runs(id); for f in r: state = h.get_state(f); if os.path.islink(state.path): p.format( "? -> ?", f, os.path.basename( os.readlink(state.path) ) ) else: p.info( f ) if len(r) == 0: p.info( "No running processes" ) def c_init(p, h, args): id = None; if len(args) > 0: id = args.pop(); r = h.select_inits(id); if len(r) == 0: p.info( "No matching init files" ) else: if id is not None: p.info( "Matching inits:" ) for f in r: p.info( f ); def c_clean(p, h, args): if len(args) > 0: r = h.select_runs(args.pop()); else: r = h.select_runs(); for f in r: m = Monitor( h, f ); result = m.communicate( commands.Ping() ); if result and isinstance( result, commands.Pong ): p.info( "Got Pong:", f ) continue; p.info( "Timeout, removing:", f ) m.remove(); if len(r) == 0: p.info( "Nothing to clean" ) RUNNING=0x1 INIT=0x2 START=0x3 STOP=0x5 RESTART=0x6 CHECK=0x7 CLEAN=0x8 ALIAS=0x9 INFO=0xa COMMANDS={ RUNNING: c_running, INIT: c_init, START: c_start, STOP: c_stop, RESTART: c_restart, CLEAN: c_clean, INFO: c_info }; NAMES={ RUNNING: ["ls-run", "list-run", "lr"], INIT: ["ls-init", "list-init", "li"], START: ["start"], STOP: ["stop"], RESTART: ["restart"], CLEAN: ["clean"], INFO: ["info", "nfo"] }; <file_sep># # This file is part of forkexec # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # author: <NAME> <<EMAIL>> # import sys import os import time import uuid import subprocess import stat try: import setproctitle except ImportError, e: print( str(e) ) print( "Please install setproctitle using:" ) print( " easy_install setproctitle" ) print( "or other applicable method" ) sys.exit(1); import forkexec.main as m from forkexec.workdir import WorkDir MAXFD=1024 class ForkExecException(Exception): pass; def main(): FE_HOME = os.environ.get("FE_HOME", None); p = m.ConsolePrinter(); if not FE_HOME: p.error( "You must set environment variable 'FE_HOME' before you can use forkexec" ) sys.exit(1); # reverse and copy the arguments for simpler handling. args = list(sys.argv[1:]); args.reverse(); if len(args) > 0: command = args.pop().lower(); else: command = None; try: h = WorkDir( FE_HOME, p ); except ForkExecException, e: print( str(e) ) sys.exit(1); command_parts = command.split("-"); # try to match command with alias. matching_aliases = list(); for k, aliases in m.NAMES.items(): for alias in aliases: alias_parts = alias.split("-"); if len(alias_parts) < len(command_parts): continue; match = True; for a_part, c_part in zip( alias_parts, command_parts ): if not a_part.startswith(c_part): match = False; break; # if there already is a similar match in list, skip current. for m_a, m_k in matching_aliases: if m_k == k: match = False; if not match: continue; matching_aliases.append( (alias, k) ); if len(matching_aliases) == 0: p.error( "No commands matching", command ); m.print_help( p ); return 1; if len(matching_aliases) > 1: p.error( "Too many commands matching", command ); for c in matching_aliases: p.error( c[0] ); return 1; matched_alias = matching_aliases.pop(); return m.COMMANDS[matched_alias[1]]( p, h, args ); <file_sep># # This file is part of forkexec # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # author: <NAME> <<EMAIL>> # import sys import os import subprocess import datetime import time import setproctitle from forkexec.commands import * from forkexec.workdir import Session import threading class TimeoutWorker(threading.Thread): def __init__(self, func, *args, **kw): threading.Thread.__init__(self); self.func = func; self.args = args; self.kw = kw; self.exception = None; self.exc_info = None; self.ret = None; def run(self): import sys; try: self.ret = self.func(*self.args, **self.kw); except Exception, e: self.exception = e; self.exc_info = sys.exc_info(); return; def timeout(ms, func, *args, **kw): w = TimeoutWorker(func, *args, **kw); w.start(); w.join(ms); if w.isAlive(): del w; return None; if w.exception is not None: raise w.exc_info[1], None, w.exc_info[2]; return w.ret; class Monitor: """ Internal monitor class for handling the process state. """ def __init__(self, home, id=None, init=None): self.home = home; # if id is specified, this is a client monitor. self.session = Session( home, id ); self.init = init; self.sp = None; self.started = time.time(); self.setproctitle(); #self.log_fd = sys.stdout; self.log_fd = self.open_log(); #sys.stdout = LogWrapper("STDOUT", self); #sys.stderr = LogWrapper("STDERR", self); def open_log(self): bestname = self.session.id; return self.home.open_log( "%s.log"%( bestname ) ) def log(self, *items): d_now = str( datetime.datetime.now() ); self.log_fd.write( "%s %s: %s\n"%( self.session.id, d_now, " ".join([str(i) for i in items]) ) ); self.log_fd.flush(); def run(self): """ Wait for all child processes to die. """ self.running = True; self.session.create(); self.log("Monitor Running"); while self.running: try: c = MonitorCommand.from_json( self.session.recv() ); if not c: self.log( "Got bad command:", repr(s) ); else: self._handle_reception(c); except Exception, e: import traceback self.log( "Exc:", traceback.format_exc() ); if not self._check_process(): self.log("Child exited with returncode:", self.sp.returncode); self.log("Initiating shutdown"); self.stop(); self.session.destroy(); self.log("Monitor Shutting Down"); def _check_process(self): """ Check that process is running. """ self.sp.poll(); if self.sp.returncode is not None: return False; return True; def stop(self): self.sp = None; self.running = False; def _handle_reception(self, c): if not isinstance(c, MonitorCommand): self.log("Received Garbled message"); return; elif isinstance(c, Touch): self.log("Got touch command"); self._cmd_touch() elif isinstance(c, Info): self.log("Got info command"); self._cmd_info(c) elif isinstance(c, Shutdown): self.log("Got command to shut down"); self._cmd_stop(c); elif isinstance(c, Ping): self.log("Got ping"); self._cmd_ping(c) elif isinstance(c, Signal): self.log("Got signal"); self._cmd_signal(c) elif isinstance(c, Restart): self.log("Got restart"); self._cmd_restart(c) def remove( self ): """ Remove all session related stuff. """ self.session.destroy(); def _cmd_stop(self, command): if command.type == command.KILL: self.log("Sending kill signal"); self.sp.kill(); elif command.type == command.TERM: self.log("Sending terminate signal"); self.sp.terminate(); elif command.type == command.INIT: self.log("Running shutdown process"); self._stop_init(); self.log("Closing file descriptors to child process"); self.sp.stdin.close(); self.sp.stdout.close(); self.sp.stderr.close(); self.log("Waiting for child process to give up and die already"); self.sp.wait(); def _stop_init(self): if not self._check_process(): self.log.info( "Process not running, cannot stop" ); return; # start the process that shuts down the child process. stop_p = subprocess.Popen([self.home.get_init(self.init).path, "stop", self.sp.pid]) # wait for process to finish (guarantee return code) stop_p.wait(); def _cmd_info(self, c): if self.send( InfoResponse(self.session.id, self.sp.pid, time.time() - self.started, self.init) ): self.log( "Unable to send info response" ); def _cmd_restart(self, c): self.log("Shutting down process"); self._cmd_stop( Shutdown() ) self.log("Spawning new process"); if self.spawn(): self.started = time.time(); self.log("Process spawned"); else: self.log("Failed to spawn process"); self.stop(); def _cmd_signal(self, c): self.log("Sending signal to process", c.signal); self.sp.send_signal(c.signal); def _cmd_ping(self, c): if self.send( Pong() ): self.log( "Unable to send pong" ); def send( self, command, t=1 ): def sender(session, command): return session.send( command.to_json() ); return timeout( t, sender, self.session, command ); def receive( self, t=1 ): def receiver( session ): return MonitorCommand.from_json( session.recv() ); return timeout( t, receiver, self.session ); def communicate(self, command, timeout=1): """ communicate creates a temporary response channel (fifo) that the monitor can use to return any command. """ if self.send(command, timeout): return self.receive(timeout); return None; def spawn(self): """ Spawn a child whereas the happy monitor will keep running having the child's pid in posession. """ if not self.home.get_init( self.init ).exists(): self.log("Init does not exist:", self.init); return False; self.sp = subprocess.Popen( [self.home.get_init(self.init).path, "start"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # poll for new returncode. self.sp.poll(); # this means that the process is already dead. if self.sp.returncode != None: self.stop(); return False; return True; def setproctitle(self): """ set the process title for the monitor process. """ setproctitle.setproctitle( "forkexec: Monitor Process (%s)"%(str(self.session.id)) ); <file_sep># # This file is part of forkexec # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # author: <NAME> <<EMAIL>> # # Daemonize code based on: # http://code.activestate.com/recipes/278731/ # written by <NAME> # import sys import os import uuid import pickle class ChildState(object): """ This handles the state passed on to the parent (or childless ; )) process. As soon as this state is passed to the parent the child will detach itself. """ def __init__(self, id, pid): self.id = id; self.pid = pid; class Daemon: def __init__(self, home, args, daemonize=True): self.home = home; self.args = args; self.parent = False; self.state = None; self.daemonize = daemonize; self.id = None; def start(self): self.id = str(uuid.uuid1()); if self.daemonize: self.createDaemon(self.home); if self.parent: return self.state; self.run(); def createDaemon(self, home): pr, pw = os.pipe(); p=os.fork() if p != 0: os.close(pw); fr = os.fdopen(pr, "r"); self.state = pickle.loads(fr.read()); self.parent = True; fr.close(); os.wait(); return; os.close(pr); os.setsid(); p = os.fork(); if p != 0: sys.exit(0); # report the current pid to the parent process. fw = os.fdopen(pw, "w"); self.state = ChildState(self.id, os.getpid()) fw.write(pickle.dumps(self.state)); fw.close(); import resource maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1] if (maxfd == resource.RLIM_INFINITY): maxfd = MAXFD # Iterate through and close all file descriptors. for fd in range(0, maxfd): try: os.close(fd) except OSError: pass def run(self): sys.exit(100); <file_sep>import os; import uuid; import stat; class Session: IN_SUFFIX = "-in"; OUT_SUFFIX = "-out"; CLIENT = 1; MONITOR = 2; def __init__( self, home, id=None ): self.home = home; if id: self.role = self.CLIENT; self.id = id; else: self.role = self.MONITOR; self.id = str( uuid.uuid1() ); self.state_file = self.home.get_state( self.id ); self.fifo_in = self.home.get_fifo( self.id + self.IN_SUFFIX ); self.fifo_out = self.home.get_fifo( self.id + self.OUT_SUFFIX ); def create( self ): if self.state_file.exists(): return False; if self.fifo_in.exists(): return False; if self.fifo_out.exists(): return False; try: self.state_file.create(); self.fifo_in.create(); self.fifo_out.create(); except Exception, e: self.state_file.destroy(); self.fifo_in.destroy(); self.fifo_out.destroy(); raise e; def destroy( self ): self.fifo_in.destroy(); self.fifo_out.destroy(); self.state_file.destroy(); def send( self, message ): """ Determine which channel to send through depending on role. """ if self.role == self.CLIENT: return self.send_in( message ); elif self.role == self.MONITOR: return self.send_out( message ); def recv( self ): """ Determine which channel to send through depending on role. """ if self.role == self.CLIENT: return self.recv_out(); elif self.role == self.MONITOR: return self.recv_in(); raise Exception("Invalid Role"); def send_in( self, message ): # this is blocking until a consumer is available f = self.fifo_in.open( "w" ); if not f: return False; try: f.write( message ); finally: f.close(); return True; def recv_in( self ): # this is blocking until a producer is available f = self.fifo_in.open( "r" ); if not f: return None; try: return f.read(); finally: f.close(); def send_out( self, message ): # this is blocking until a consumer is available f = self.fifo_out.open( "w" ); if not f: return False; try: f.write( message ); finally: f.close(); return True; def recv_out( self ): # this is blocking until a producer is available f = self.fifo_out.open( "r" ); if not f: return None; try: return f.read(); finally: f.close(); class File: def __init__( self, path ): self.path = path; def valid( self ): """ Check that the path exists and is an actual fifo. """ return self.exists(); def exists( self ): return os.path.exists( self.path ); def islink( self ): return os.path.islink( self.path ); def readlink( self ): return os.readlink( self.path ); def create( self ): open( self.path, "w" ).close(); def destroy( self ): if self.exists(): os.unlink( self.path ); def open( self, mode ): """ Validate that the fifo already exists. Returns None if unable to verify existing fifo prior to opening. """ if not self.exists(): return None; return open( self.path, mode ); class Fifo(File): def valid( self ): """ Check that the path exists and is an actual fifo. """ return self.exists() and stat.S_ISFIFO( os.stat( self.path ).st_mode ); def create( self ): os.mkfifo( self.path ); class WorkDir: IO="io" RUNNING="running" LOGS="logs" INIT="init" def __init__( self, home, printer ): self.home = home self.printer = printer; if not os.path.isdir(self.home): raise ForkExecException("%s: is not a directory"%(self.home)) self._validate_home(); def _validate_home(self): check = [self.IO, self.RUNNING, self.LOGS, self.INIT]; for c in check: path = self.get_path( c ); try: if not os.path.isdir( path ): self.printer.info( "Creating directory:", path ) os.mkdir( path ); except OSError, e: raise ForkExecException("%s: %s"%( path, str(e)) ); def get_path( self, *parts ): return os.path.join( self.home, *parts ); def get_fifo( self, fifoname ): return Fifo( self.get_path( self.IO, fifoname ) ); def get_state( self, id ): return self.get_file( self.RUNNING, id ); def get_init( self, init ): return self.get_file( self.INIT, init ); def get_file( self, *parts ): return File( self.get_path( *parts ) ) def select_file( self, dir, hint = None ): """ Select a subset of entries from a directory, if any starts with hint. If there is a perfect match, only return that one no matter what. """ result = list(); dir = self.get_path( dir ); for f in os.listdir( dir ): if not hint: result.append(f); continue; if f == hint: return [ f ]; if f.startswith( hint ): result.append( f ); continue; return result; def select_runs(self, id_hint=None): return self.select_file( self.RUNNING, id_hint ); def select_inits( self, id_hint=None ): return self.select_file( self.INIT, id_hint ); def open_log(self, logname): path = self.get_path(self.LOGS, logname); try: return open( path, "a" ); except OSError, e: raise ForkExecException( "%s: %s"%( path, str(e) ) );
90868f21084b2898876429b3577e0aa58ae7747d
[ "Python" ]
6
Python
udoprog/forkexec
892f18f9a5fa8a54301d5d508123b16bfa3b23d6
2c39c589a2862432160d5e50a5a9bd446dc6ba86
refs/heads/master
<repo_name>flyinglove/realworld-nuxtjs<file_sep>/plugins/logrocket.js import LogRocket from 'logrocket'; LogRocket.init('bkseib/test-nuxt');<file_sep>/api/settings.js import {request} from '@/plugins/request' export const updateUser = params => { return request({ method: 'PUT', url: '/api/user', data: params }) }<file_sep>/功能.md 登录,注册 文章详情 - 关注作者 - 点赞 - 发布评论 发布文章 - 支持md - 修改 设置-修改个人信息-推出登录 个人中心 - 个人文章 - 点赞的文章 - 编辑用户资料 - 跳设置 地址: 172.16.17.32:3000 <file_sep>/api/profiles.js import {request} from '@/plugins/request' export function getProfile(username) { return request({ method: 'GET', url: `/api/profiles/${username}`, }) }
eaf2ca6bc71dc7f92a75522f2fa27f74ed2d0016
[ "JavaScript", "Markdown" ]
4
JavaScript
flyinglove/realworld-nuxtjs
38845b6d40a7144f6ca91321516cc27fd9388f10
6e0b952a91410afa5578dc490bb7b7c166a15d42
refs/heads/master
<repo_name>jimsick/protal-project<file_sep>/src/main.js // 引用 vue 没什么要说的 import Vue from 'vue' // 入口文件为 src/App.vue 文件 所以要引用 import App from './App.vue' // 引用路由配置文件 import routes from './config/routes' // 引用API文件 import api from './config/api' // 引用路由 import VueRouter from 'vue-router' // 引入公共样式方法 // import '@/assets/css/reset.css' // 光引用不成,还得使用 Vue.use(VueRouter) // 6.将API方法绑定到全局 Vue.prototype.$api = api // 使用配置文件规则 const router = new VueRouter({ routes }) // 将API方法绑定到全局 Vue.prototype.$api = api // 引用ElementUI import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' Vue.use(ElementUI) // 引入本地存储 import store from 'store' Vue.prototype.$store = store new Vue({ router, el: '#app', render: (h) => h(App) }) <file_sep>/requirement.txt npm install superagent -D npm install vue-router -D ESLint安装配置 npm install -g eslint eslint --init npm install babel-eslint --save store一种本地localStorage管理包 cnpm install store -D 1. 安装 loader 模块: cnpm install style-loader -D cnpm install css-loader -D cnpm install file-loader -D 2. 安装 饿了么 模块 cnpm install element-ui --save 安装sass-loader以及node-sass插件 npm install sass-loader -D 淘宝镜像网站 https://npm.taobao.org/ ElementUI官方文档 http://element-cn.eleme.io/#/zh-CN VUE官网 https://cn.vuejs.org/ 环境搭建教程 https://www.jianshu.com/p/3adc885b67d6 node-sass git网 https://github.com/sass/node-sass 安装node-sass cnpm install node-sass -D cnpm install sass-loader -D ----------------------------------问题解决---------------------------------------- 缓存清理命令 npm cache clean --force 4058错误解决 使用淘宝源
6d2ae4004298e22addb9a28e3059770ce635c7c3
[ "JavaScript", "Text" ]
2
JavaScript
jimsick/protal-project
45673251626c12b2222907ba7ec274132ad51c01
605272e719c04d5ff4b80d83e375f7c5a1da467a
refs/heads/master
<file_sep># prereqs: iterators, hashes, conditional logic # Given a hash with numeric values, return the key for the smallest value def key_for_min_value(name_hash) min_key=nil min_value=nil name_hash.each do |key, value| if min_value == nil || value < min_value min_key=key min_value=value end end min_key end
a9ee8966a03d29d4558053009b62e32da4a94205
[ "Ruby" ]
1
Ruby
brianchz/key-for-min-value-atx01-seng-ft-022221
2b1b81ee91a4a7cdd88817a885edf331e9ec67d4
83ce3900c1d4805684540602ec693c9d32cd33cd
refs/heads/master
<file_sep>package com.oops.AbsractExample; public interface InterfaceEx { int i=101; String name="Monali"; void accept(); default void display() { System.out.println("Hello"); } } <file_sep>package com.oops.AbsractExample; public abstract class AbstractClass { int id; String name; abstract void accept(); static void display() { System.out.println("Concrete method in abstract class"); } public AbstractClass(int id, String name) { System.out.println("Parameterized constructor"); this.id = id; this.name = name; } public AbstractClass() { System.out.println("Abstract Constructor"); } public static void main(String[] args) { AbstractClass ab=new AbstractClass(101,"Monali") { @Override void accept() { // TODO Auto-generated method stub System.out.println("Annoynomous method"); } }; } } <file_sep>package com.oops.AbsractExample; public class InterfaceExample implements InterfaceEx { @Override public void accept() { // TODO Auto-generated method stub System.out.println("Interface method"); System.out.println(i); System.out.println(name); } public static void main(String[] args) { InterfaceExample ie=new InterfaceExample(); ie.accept(); ie.display(); } } <file_sep>package com.oops.AbsractExample; public class AbstractImplementation extends AbstractClass{ public AbstractImplementation(int id, String name) { super(id, name); // TODO Auto-generated constructor stub } public static void main(String[] args) { // TODO Auto-generated method stub AbstractImplementation a=new AbstractImplementation(101,"Monali"); a.accept(); a.display(); } @Override void accept() { // TODO Auto-generated method stub System.out.println("Abtract Method implementation"); } } <file_sep>package com.oops.Innerclass; public class LocalNestedClass { /* * Local Inner Class- * class declared inside method * access all variables of outer class * To access inner class we need to create instance inside method * Local inner class has only abstract and final access modifiers allowed */ int i=10; private String name="Monali"; final String colg="AVCOE"; static int cnt=101; public void m1() { System.out.println("Inner class Inside Method:"); final class Innerclass{ // int i1=102; public void m2() { System.out.println("Inner Class:"); System.out.println("\nPrivate Member:"+name); System.out.println("\ndefault Member:"+i); System.out.println("\nStatic Member:"+cnt); System.out.println("\nFinal Member:"+colg); } } Innerclass ic=new Innerclass(); ic.m2(); } public static void main(String[] args) { // TODO Auto-generated method stub LocalNestedClass ln=new LocalNestedClass(); ln.m1(); } }
15b23f257daab0c9cad312bd85cd3d346764a778
[ "Java" ]
5
Java
RajshriPawase/Nested-Class-Example
6e45f804f0566c7619d76b8a2c425943ec15567a
f0a941d64d56483e4c87535264f6dfe86ecacdd7
refs/heads/master
<repo_name>maziesmith/Air-Reservation-System-CSharp<file_sep>/Air_Reservation_System/CashPaymentPanel.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Air_Reservation_System { public partial class CashPaymentPanel : Form { string cID = ""; string cName = ""; string cGender = ""; string cDOB = ""; string cPN = ""; string cEID = ""; string cPPNo = ""; string cNationality = ""; Form cIF; int flightListNo = 0; int totalAmount = 0; int intoE = 0; int intoB = 0; int sEAvail = 0; int sBAvail = 0; int cCount = 3; int fCount = 1; int aCount = 3; int tbCount = 0; string amount = ""; int payment = 0; Airline_Reservation_SystemDBCDataContext cpD = new Airline_Reservation_SystemDBCDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\<NAME>\Documents\Visual Studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Airline_Reservation_System.mdf;Integrated Security=True;Connect Timeout=30"); public CashPaymentPanel() { InitializeComponent(); } public CashPaymentPanel(Form cIF, int flightListNo, int totalAmount, string cID, string cName, string cGender, string cDOB, string cPN, string cEID, string cPPNo, string cNationality, int intoE, int intoB, int sEAvail, int sBAvail) { InitializeComponent(); this.cIF = cIF; this.flightListNo = flightListNo; this.totalAmount = totalAmount; this.cName = cName; this.cGender = cGender; this.cDOB = cDOB; this.cPN = cPN; this.cEID = cEID; this.cPPNo = cPPNo; this.cNationality = cNationality; this.intoE = intoE; this.intoB = intoB; this.sEAvail = sEAvail; this.sBAvail = sBAvail; this.cID = cID; } private void Cash_Payment_Click(object sender, EventArgs e) { int warning =0; amount=Cash_Amount_TB.Text; bool allDigitCSH = amount.All(char.IsDigit); if (amount == "") { MessageBox.Show("Please Enter the Amount"); } else { if (allDigitCSH == false) { MessageBox.Show("Invalid Amount!!!"); warning = 3; } else { payment=Convert.ToInt32(amount); } if (warning == 0) { if(payment>=totalAmount) { int cusID = Convert.ToInt32(cID); //string path=Path.GetRandomFileName(); //path=path.Replace(".",""); //cCount++; string path = "12345" + cName; Customer_Info ciT = new Customer_Info { CID = cusID, CName = cName, CGender = cGender, CDOB = cDOB, CPhone_Num = cPN, CEmail = cEID, CPassport_No = cPPNo, CNationality = cNationality, //Card_Holder_Name=cHName, //Credit_Card_No=Convert.ToInt32(cCNo), //Card_Expire_Date=cCEd, CPassword = <PASSWORD> }; cpD.Customer_Infos.InsertOnSubmit(ciT); cpD.SubmitChanges(); var x = from a in cpD.Flight_Details where a.Flight_ID == flightListNo select a; string fN = x.First().Flight_Name; x.First().Available_Seat_E_ = sEAvail; x.First().Available_Seat_B_ = sBAvail; cpD.SubmitChanges(); var y = from b in cpD.Flight_Details //where a.Flight_Name == APSearchBox.Text where b.Available_Seat_B_ == 0 && b.Available_Seat_E_ == 0 select b; foreach (Flight_Detail p in y) { cpD.Flight_Details.DeleteOnSubmit(p); } cpD.SubmitChanges(); TicketBooked_Info tbT = new TicketBooked_Info { CID = cusID, CName = cName, Flight_ID = flightListNo, Flight_Name = fN, Business_Seat_Taken = intoB, Economy_Seat_Taken = intoE }; cpD.TicketBooked_Infos.InsertOnSubmit(tbT); cpD.SubmitChanges(); if(payment>totalAmount) { payment = payment - totalAmount; MessageBox.Show("Your return back amount is : "+payment+" BDT"); } MessageBox.Show("Ticket Confirmation is Successfull!! :)\n\nYour User Password is : " + path + "\n\nyou can login with your user name using this password from login panel! "); this.Hide(); AIRRMainFrame mF = new AIRRMainFrame(); mF.Show(); } else if(payment<totalAmount) { MessageBox.Show("Your amount is Insufficient!!"); } } } } private void CashPaymentPanel_Load(object sender, EventArgs e) { TotalAmountTB.Text = totalAmount.ToString(); TotalAmountTB.Enabled = false; } } } <file_sep>/Air_Reservation_System/BothUserAdminForm.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Air_Reservation_System { public partial class BothUserAdminForm : Form { public BothUserAdminForm() { InitializeComponent(); } private void LIA_Admin_Click(object sender, EventArgs e) { AdminLogin aL = new AdminLogin(); this.Hide(); aL.Show(); } private void LIA_User_Click(object sender, EventArgs e) { CustomerLoginPanel cp1=new CustomerLoginPanel(); cp1.Show(); this.Hide(); } } } <file_sep>/Air_Reservation_System/AdminLogin.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Air_Reservation_System { public partial class AdminLogin : Form { //Air_Reservation_DBDataContext aLD = new Air_Reservation_DBDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mzs Munna\documents\visual studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Air_Reservation.mdf;Integrated Security=True;Connect Timeout=30"); Airline_Reservation_SystemDBCDataContext aLD = new Airline_Reservation_SystemDBCDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mzs Munna\Documents\Visual Studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Airline_Reservation_System.mdf;Integrated Security=True;Connect Timeout=30"); public AdminLogin() { InitializeComponent(); } private void AdminLogin_Load(object sender, EventArgs e) { } private void AL_Login_Button_Click(object sender, EventArgs e) { var x = from a in aLD.Admins where a.Admin_Name == AL_UNBox.Text && a.Admin_Password==<PASSWORD> select a; if(x.Any()) { MessageBox.Show("Login Success!"); AdminPanel alp = new AdminPanel(this); this.Hide(); alp.Show(); } else { MessageBox.Show("Login Failed!"); } } } } <file_sep>/Air_Reservation_System/AddFlightPanel.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Text.RegularExpressions; namespace Air_Reservation_System { public partial class AddFlightPanel : Form { //Air_Reservation_DBDataContext aFPD = new Air_Reservation_DBDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mzs Munna\documents\visual studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Air_Reservation.mdf;Integrated Security=True;Connect Timeout=30"); Airline_Reservation_SystemDBCDataContext aFPD = new Airline_Reservation_SystemDBCDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mzs Munna\Documents\Visual Studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Airline_Reservation_System.mdf;Integrated Security=True;Connect Timeout=30"); string status = ""; string fName = ""; string des = ""; string dep = ""; string date = ""; string time = ""; string availES = ""; string availBS = ""; string ecoCost = ""; string bsnsCost = ""; Form cIF; DataGridView apDGV; int flightListNo = -1; int fID = 0; public AddFlightPanel() { InitializeComponent(); } public AddFlightPanel(String status, DataGridView apDGV, int flightListNo) { InitializeComponent(); this.status = status; this.apDGV = apDGV; this.flightListNo = flightListNo; } private void AFP_Add_Flight_Button_Click(object sender, EventArgs e) { int warning = 0; int nameV = 0; string fids = ""; fids = AFP_FIDTB.Text; fName = AFP_Flight_Name_Box.Text; des = AFP_DestinationBox.Text; dep = AFP_DepertureBox.Text; date = AFP_Date.Value.ToString("dd-MM-yyyy"); time = AFP_Time.Value.ToString("H:mm"); availES = AFP_AvailESB.Text; availBS = AFP_AvailBSB.Text; ecoCost = AFP_EcoCostBox.Text; bsnsCost = AFP_BsnsCostBox.Text; bool allDigitAES = availES.All(char.IsDigit); bool allDigitABS = availBS.All(char.IsDigit); bool allDigitEC = ecoCost.All(char.IsDigit); bool allDigitBC = bsnsCost.All(char.IsDigit); bool allDigitFID = fids.All(char.IsDigit); int availES2I = 0; int availBS2I = 0; int ecoCost2I = 0; int bsnsCost2I = 0; if ((fName == "") || (des == "") || (dep == "") || (date == "") || (time == "") || (availES == "") || (availBS == "") || (ecoCost == "") || (bsnsCost == "") || (fids == "")) { MessageBox.Show("Can't skip any field!!! Fill up all to proceed!"); } else { if (allDigitAES == false) { MessageBox.Show("Number of Economy seat is invalid"); warning = 1; } else { availES2I = Convert.ToInt32(availES); } if (allDigitFID == false) { MessageBox.Show("Number of Economy seat is invalid"); warning = 1; } else { fID = Convert.ToInt32(fids); } if (allDigitABS == false) { MessageBox.Show("Number of Business seat is invalid"); warning = 2; } else { availBS2I = Convert.ToInt32(availBS); } if (allDigitEC == false) { MessageBox.Show("Economy Seeat Amount is invalid"); warning = 3; } else { ecoCost2I = Convert.ToInt32(ecoCost); } if (allDigitBC == false) { MessageBox.Show("Business Seat Amount is invalid"); warning = 4; } else { bsnsCost2I = Convert.ToInt32(bsnsCost); } if (Regex.IsMatch(des, @"^[a-zA-Z]+$") == true) //all character { //MessageBox.Show("All are letters"); } else { MessageBox.Show("Not a valid Destination!"); warning = 5; } if (Regex.IsMatch(dep, @"^[a-zA-Z]+$") == true) //all character { //MessageBox.Show("All are letters"); } else { MessageBox.Show("Not a valid Departure!"); warning = 6; } if (Regex.IsMatch(fName, @"^[a-zA-Z ]{2,30}$") == true) { //MessageBox.Show("valid name no number upto 30!"); nameV = 1; } else { //MessageBox.Show("Invalid name"); warning = 1; } if (nameV == 0) { if (Regex.IsMatch(fName, @"^[a-zA-Z ]{2,26}[0-9]{1,4}$") == true) { //MessageBox.Show("at first letter then number up to 5"); warning = 0; } else { MessageBox.Show("Invalid name"); warning = 1; } } } if (status == "Add") { if (warning == 0) { Flight_Detail fdT = new Flight_Detail { Flight_ID = fID, Flight_Name = fName, Destination = des, Departure = dep, Date = date, Time = time, Available_Seat_E_ = availES2I, Available_Seat_B_ = availBS2I, Economy_Cost_BDT_ = ecoCost2I, Business_Cost_BDT_ = bsnsCost2I }; aFPD.Flight_Details.InsertOnSubmit(fdT); aFPD.SubmitChanges(); this.Hide(); apDGV.DataSource = aFPD.Flight_Details; MessageBox.Show("Flight Added Successfully"); } } else if (status == "Update") { var x = from a in aFPD.Flight_Details where a.Flight_ID == flightListNo select a; if (warning == 0) { x.First().Flight_Name = fName; x.First().Destination = des; x.First().Departure = dep; x.First().Date = date; x.First().Time = time; x.First().Available_Seat_E_ = availES2I; x.First().Available_Seat_B_ = availBS2I; x.First().Economy_Cost_BDT_ = ecoCost2I; x.First().Business_Cost_BDT_ = bsnsCost2I; aFPD.SubmitChanges(); apDGV.DataSource = aFPD.Flight_Details; MessageBox.Show("Flight Updated Successfully"); this.Hide(); } else { MessageBox.Show("Something wnt wrong"); } } } private void AddFlightPanel_Load(object sender, EventArgs e) { if(status=="Add") { } else if(status=="Update") { AFP_Add_Flight_Button.Text = "Update Flight"; var x = from a in aFPD.Flight_Details where a.Flight_ID == flightListNo select a; AFP_FIDTB.Text = x.First().Flight_ID.ToString(); AFP_FIDTB.Enabled = false; AFP_Flight_Name_Box.Text=x.First().Flight_Name; AFP_DestinationBox.Text=x.First().Destination; AFP_DepertureBox.Text = x.First().Departure; AFP_Date.Text=x.First().Date; AFP_Time.Text=x.First().Time; AFP_AvailESB.Text=x.First().Available_Seat_E_.ToString(); AFP_AvailBSB.Text = x.First().Available_Seat_B_.ToString(); AFP_EcoCostBox.Text = x.First().Economy_Cost_BDT_.ToString(); AFP_BsnsCostBox.Text = x.First().Business_Cost_BDT_.ToString(); } } private void AFP_Cancel_Click(object sender, EventArgs e) { this.Hide(); } } } <file_sep>/Air_Reservation_System/CustomerInformation.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Text.RegularExpressions; namespace Air_Reservation_System { public partial class CustomerInfoPanel : Form { string cID = ""; string cName = ""; string cGender = ""; string cDOB = ""; string cPN = ""; string cEID = ""; string cPPNo = ""; string cNationality = ""; Form sBF; int flightListNo; int totalAmount = 0; int intoE=0; int intoB=0; int sEAvail = 0; int sBAvail = 0; public CustomerInfoPanel() { InitializeComponent(); } public CustomerInfoPanel(Form sBF, int flightListNo, int totalAmount, int intoE, int intoB, int sEAvail, int sBAvail) { InitializeComponent(); this.sBF = sBF; this.flightListNo = flightListNo; this.totalAmount = totalAmount; this.intoE = intoE; this.intoB = intoB; this.sEAvail = sEAvail; this.sBAvail = sBAvail; } private void CustomerInfoPanel_Load(object sender, EventArgs e) { CustomerGender.Items.AddRange(new string[] { "Male", "Female" }); CustomerGender.SelectedIndex = 0; } private void CI_Next_Click(object sender, EventArgs e) { int warning = 0; int nameV = 0; cID = CIDTB.Text; cName = CustomerName.Text; cGender = CustomerGender.SelectedItem.ToString(); cDOB = CustomerDOB.Value.ToString("dd-MM-yyyy"); cPN = CustomerPN.Text; cEID = CustomerEID.Text; cNationality = CustomerNationality.Text; cPPNo = CustomerPassportNo.Text; bool allDigitPP = cPPNo.All(char.IsDigit); bool allDigitPN = cPN.All(char.IsDigit); bool allDigitCID = cID.All(char.IsDigit); if ((cID == "") || (cName == "") || (cGender == "") || (cDOB == "") || (cPN == "") || (cEID == "") || (cNationality == "") || (cPPNo == "")) { MessageBox.Show("Can't skip any field!!! Fill up all to proceed!"); } else { if (allDigitPP == false) { MessageBox.Show("Invalid Passport Number"); warning = 3; } if (allDigitPN == false) { MessageBox.Show("Invalid Phone Number"); warning = 4; } if (allDigitCID == false) { MessageBox.Show("Invalid ID Number"); warning = 5; } if (Regex.IsMatch(cNationality, @"^[a-zA-Z]+$") == true) //all character { //MessageBox.Show("All are letters"); } else { MessageBox.Show("Not a valid Nation!"); warning = 6; } if (Regex.IsMatch(cName, @"^[a-zA-Z ]{2,30}$") == true) { //MessageBox.Show("valid name no number upto 30!"); nameV = 1; } else { //MessageBox.Show("Invalid name"); warning = 1; } if (nameV == 0) { if (Regex.IsMatch(cName, @"^[a-zA-Z ]{2,26}[0-9]{1,4}$") == true) { //MessageBox.Show("at first letter then number up to 5"); warning = 0; } else { MessageBox.Show("Invalid name"); warning = 1; } } if (Regex.IsMatch(cEID, @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$") == true) { //MessageBox.Show("VALID EMAIL ID"); //warning = 0; } else { MessageBox.Show("Invalid email id"); warning = 2; } if(warning==0) { //MessageBox.Show("Go to next form! :) "+warning); PaymentMethodPanel pMF=new PaymentMethodPanel(this, flightListNo, totalAmount, cID, cName, cGender, cDOB, cPN, cEID, cPPNo, cNationality,intoE,intoB,sEAvail,sBAvail); pMF.Show(); this.Hide(); } } } private void CI_Back_Click(object sender, EventArgs e) { this.Hide(); sBF.Show(); } } } <file_sep>/Air_Reservation_System/FlightDetails.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Air_Reservation_System { public partial class Flight_Details : Form { //FlightDetails_TableDataContext fdt = new FlightDetails_TableDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\mzs munna\documents\visual studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Air_Reservation.mdf;Integrated Security=True;Connect Timeout=30"); //Air_Reservation_DBDataContext fdt = new Air_Reservation_DBDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mzs Munna\Documents\visual studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Air_Reservation.mdf;Integrated Security=True;Connect Timeout=30"); Airline_Reservation_SystemDBCDataContext fdt = new Airline_Reservation_SystemDBCDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mzs Munna\Documents\Visual Studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Airline_Reservation_System.mdf;Integrated Security=True;Connect Timeout=30"); int flightListNo=-1; int economyP = 0; int businessP = 0; int sEAvail = 0; int sBAvail = 0; Form mF; public Flight_Details() { InitializeComponent(); } public Flight_Details(Form mF) { InitializeComponent(); this.mF = mF; } private void Flight_Details_Load(object sender, EventArgs e) { FlightDetailsGridView.DataSource = fdt.Flight_Details; FlightDetailsGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; } private void FlightDetailsGridView_CellClick(object sender, DataGridViewCellEventArgs e) { int index = e.RowIndex; DataGridViewRow selectedRow = FlightDetailsGridView.Rows[index]; flightListNo = Convert.ToInt32(selectedRow.Cells[0].Value.ToString()); sEAvail = Convert.ToInt32(selectedRow.Cells[6].Value.ToString()); sBAvail = Convert.ToInt32(selectedRow.Cells[7].Value.ToString()); economyP = Convert.ToInt32(selectedRow.Cells[8].Value.ToString()); businessP = Convert.ToInt32(selectedRow.Cells[9].Value.ToString()); } private void FlightDetails_Next_Click(object sender, EventArgs e) { if(flightListNo>-1) { Seat_Booking sBF = new Seat_Booking(this,flightListNo,economyP,businessP,sEAvail,sBAvail); sBF.Show(); this.Hide(); } else { MessageBox.Show("Select Anyone from the list to proceed!!!"); } } private void Flight_Details_Back_Click(object sender, EventArgs e) { this.Hide(); mF.Show(); } private void FDB_Search_Button_Click(object sender, EventArgs e) { Airline_Reservation_SystemDBCDataContext fDD = new Airline_Reservation_SystemDBCDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\<NAME>\Documents\Visual Studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Airline_Reservation_System.mdf;Integrated Security=True;Connect Timeout=30"); string searchS = Flight_Booking_SearchBox.Text; var x = from a in fDD.Flight_Details //where a.Flight_Name == APSearchBox.Text where a.Flight_Name.Contains(Flight_Booking_SearchBox.Text) //|| a.Destination == APSearchBox.Text || a.Destination.Contains(Flight_Booking_SearchBox.Text) //|| a.Departure == APSearchBox.Text || a.Departure.Contains(Flight_Booking_SearchBox.Text) //|| a.Date == APSearchBox.Text || a.Date.Contains(Flight_Booking_SearchBox.Text) //|| a.Time == APSearchBox.Text || a.Time.Contains(Flight_Booking_SearchBox.Text) select a; if (x.Any()) { FlightDetailsGridView.DataSource = x.ToList(); FlightDetailsGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; } else { MessageBox.Show("No such result available!! :/"); } } private void Refresh_Display_Click(object sender, EventArgs e) { Airline_Reservation_SystemDBCDataContext fdt = new Airline_Reservation_SystemDBCDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\<NAME>\Documents\Visual Studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Airline_Reservation_System.mdf;Integrated Security=True;Connect Timeout=30"); FlightDetailsGridView.DataSource = fdt.Flight_Details; FlightDetailsGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; } } } <file_sep>/Air_Reservation_System/CustomerLoginPanel.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Air_Reservation_System { public partial class CustomerLoginPanel : Form { //Air_Reservation_DBDataContext uLD = new Air_Reservation_DBDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mzs Munna\documents\visual studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Air_Reservation.mdf;Integrated Security=True;Connect Timeout=30"); Airline_Reservation_SystemDBCDataContext uLD = new Airline_Reservation_SystemDBCDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mzs Munna\Documents\Visual Studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Airline_Reservation_System.mdf;Integrated Security=True;Connect Timeout=30"); //int userID = 12; int userID = 0; public CustomerLoginPanel() { InitializeComponent(); } private void USR_Login_Button_Click(object sender, EventArgs e) { Airline_Reservation_SystemDBCDataContext uLD = new Airline_Reservation_SystemDBCDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mzs Munna\Documents\Visual Studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Airline_Reservation_System.mdf;Integrated Security=True;Connect Timeout=30"); var x = from a in uLD.Customer_Infos where a.CName == USR_UNBox.Text //|| a.CEmail == USR_UNBox.Text && a.CPassword == USR_PassBox.Text select a; if (x.Any()) { userID=x.First().CID; MessageBox.Show("Login Success!"); UserHome uHP = new UserHome(this, userID); uHP.Show(); this.Hide(); //AdminPanel alp = new AdminPanel(this); //this.Hide(); //alp.Show(); } else { MessageBox.Show("Login Failed!"); } } private void USR_Reg_Click(object sender, EventArgs e) { } private void USR_UNBox_TextChanged(object sender, EventArgs e) { } } } <file_sep>/Air_Reservation_System/PaymentMethodPanel.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Air_Reservation_System { public partial class PaymentMethodPanel : Form { string cName = ""; string cGender = ""; string cDOB = ""; string cPN = ""; string cEID = ""; string cPPNo = ""; string cNationality = ""; Form cIF; int flightListNo = 0; int totalAmount = 0; int intoE = 0; int intoB = 0; int sEAvail = 0; int sBAvail=0; string cID; public PaymentMethodPanel() { InitializeComponent(); } public PaymentMethodPanel(Form cIF, int flightListNo, int totalAmount, string cID, string cName, string cGender, string cDOB, string cPN, string cEID, string cPPNo, string cNationality, int intoE, int intoB, int sEAvail, int sBAvail) { InitializeComponent(); this.cIF = cIF; this.flightListNo = flightListNo; this.totalAmount = totalAmount; this.cName = cName; this.cGender = cGender; this.cDOB = cDOB; this.cPN = cPN; this.cEID = cEID; this.cPPNo = cPPNo; this.cNationality = cNationality; this.intoB = intoB; this.intoE = intoE; this.sEAvail = sEAvail; this.sBAvail = sBAvail; this.cID = cID; } private void Cash_Click(object sender, EventArgs e) { // CashPaymentPanel cpPF = new CashPaymentPanel(this, flightListNo, totalAmount, cID, cName, cGender, cDOB, cPN, cEID, cPPNo, cNationality, intoE, intoB, sEAvail, sBAvail); cpPF.Show(); this.Hide(); } private void Credit_Card_Click(object sender, EventArgs e) { CreditCardInfoPanel cCIF = new CreditCardInfoPanel(this, flightListNo, totalAmount, cID, cName, cGender, cDOB, cPN, cEID, cPPNo, cNationality,intoE,intoB,sEAvail,sBAvail); cCIF.Show(); this.Hide(); } private void PM_Back_Click(object sender, EventArgs e) { this.Hide(); cIF.Show(); } } } <file_sep>/Air_Reservation_System/UserHome.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Text.RegularExpressions; namespace Air_Reservation_System { public partial class UserHome : Form { int userID = 0; Form cLF = null; int fID = 0; int addES = 0; int addBS = 0; int esT = 0; int bsT = 0; Airline_Reservation_SystemDBCDataContext uHD = new Airline_Reservation_SystemDBCDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mzs Munna\Documents\Visual Studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Airline_Reservation_System.mdf;Integrated Security=True;Connect Timeout=30"); public UserHome() { InitializeComponent(); } public UserHome(Form cLF, int userID) { InitializeComponent(); this.userID = userID; this.cLF = cLF; } private void CNameL_Click(object sender, EventArgs e) { } private void label1_Click(object sender, EventArgs e) { } private void UserHome_Load(object sender, EventArgs e) { Airline_Reservation_SystemDBCDataContext uHLD = new Airline_Reservation_SystemDBCDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\<NAME>\Documents\Visual Studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Airline_Reservation_System.mdf;Integrated Security=True;Connect Timeout=30"); var x = from a in uHLD.Customer_Infos where a.CID == userID select a; CIDTB.Text = x.First().CID.ToString(); CIDTB.Enabled = false; CustomerName.Text = x.First().CName; string cG = x.First().CGender; CustomerDOB.Text = x.First().CDOB; CustomerPN.Text = x.First().CPhone_Num; CustomerEID.Text = x.First().CEmail; CustomerPassportNo.Text = x.First().CPassport_No; CustomerNationality.Text = x.First().CNationality; CardHolderNameTB.Text = x.First().Card_Holder_Name; CreditCardNoTB.Text = x.First().Credit_Card_No.ToString(); User_Pass_TB.Text = x.First().CPassword; CustomerGender.Items.AddRange(new string[] { "Male", "Female" }); if (cG == "Male") { CustomerGender.SelectedIndex = 0; } else if (cG == "Female") { CustomerGender.SelectedIndex = 1; } int carryON = 0; var y = from b in uHLD.TicketBooked_Infos where b.CID == userID select b; if (y.Any()) { fID = y.First().Flight_ID; UH_Flight_Name_TB.Text = y.First().Flight_ID.ToString(); UH_Flight_Name_TB.Enabled = false; esT = y.First().Economy_Seat_Taken; EconomySeatBox.Text = y.First().Economy_Seat_Taken.ToString(); EconomySeatBox.Enabled = false; bsT = y.First().Business_Seat_Taken; Business_SeatBox.Text = y.First().Business_Seat_Taken.ToString(); Business_SeatBox.Enabled = false; //addES = y.First().Economy_Seat_Taken; //addBS = y.First().Business_Seat_Taken; carryON = 1; } if (carryON == 1) { var z = from c in uHLD.Flight_Details where c.Flight_ID == fID select c; UH_Destination_TB.Text = z.First().Destination; UH_Destination_TB.Enabled = false; UH_Departure_TB.Text = z.First().Departure; UH_Departure_TB.Enabled = false; Time_Schedule_Box.Text = z.First().Time; Time_Schedule_Box.Enabled = false; Date_Schedule_Box.Text = z.First().Date; Date_Schedule_Box.Enabled = false; addES = Convert.ToInt32(z.First().Available_Seat_E_); addBS = Convert.ToInt32(z.First().Available_Seat_B_); } else { UH_Flight_Name_TB.Text = ""; UH_Flight_Name_TB.Enabled = false; EconomySeatBox.Text = ""; EconomySeatBox.Enabled = false; Business_SeatBox.Text = ""; Business_SeatBox.Enabled = false; UH_Destination_TB.Text = ""; UH_Destination_TB.Enabled = false; UH_Departure_TB.Text = ""; UH_Departure_TB.Enabled = false; Time_Schedule_Box.Text = ""; Time_Schedule_Box.Enabled = false; Date_Schedule_Box.Text = ""; Date_Schedule_Box.Enabled = false; UI_Cancel_Reservation.Visible = false; } } private void UI_Cancel_Reservation_Click(object sender, EventArgs e) { Airline_Reservation_SystemDBCDataContext uHCD = new Airline_Reservation_SystemDBCDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\<NAME>\Documents\Visual Studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Airline_Reservation_System.mdf;Integrated Security=True;Connect Timeout=30"); var y = from b in uHCD.TicketBooked_Infos where b.CID == userID select b; //y.First().Flight_ID foreach (TicketBooked_Info p in y) { uHCD.TicketBooked_Infos.DeleteOnSubmit(p); } uHCD.SubmitChanges(); MessageBox.Show("Reservation Canceled"); var z = from c in uHCD.Flight_Details where c.Flight_ID == fID select c; z.First().Available_Seat_E_ = addES + esT; z.First().Available_Seat_B_ = addBS + bsT; uHCD.SubmitChanges(); UH_Flight_Name_TB.Text = ""; UH_Flight_Name_TB.Enabled = false; EconomySeatBox.Text = ""; EconomySeatBox.Enabled = false; Business_SeatBox.Text = ""; Business_SeatBox.Enabled = false; UH_Destination_TB.Text = ""; UH_Destination_TB.Enabled = false; UH_Departure_TB.Text = ""; UH_Departure_TB.Enabled = false; Time_Schedule_Box.Text = ""; Time_Schedule_Box.Enabled = false; Date_Schedule_Box.Text = ""; Date_Schedule_Box.Enabled = false; UI_Cancel_Reservation.Visible = false; } private void UH_Logout_Click(object sender, EventArgs e) { this.Hide(); cLF.Show(); } private void UI_Update_IB_Click(object sender, EventArgs e) { Airline_Reservation_SystemDBCDataContext uHLD = new Airline_Reservation_SystemDBCDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\<NAME>\Documents\Visual Studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Airline_Reservation_System.mdf;Integrated Security=True;Connect Timeout=30"); //string cID = ""; string cName = ""; string cGender = ""; string cDOB = ""; string cPN = ""; string cEID = ""; string cPPNo = ""; string cNationality = ""; string cHName = ""; string cCrdN = ""; string cPass = ""; //x.First().CID = Convert.ToInt32(CIDTB.Text); cName = CustomerName.Text; cGender = CustomerGender.SelectedItem.ToString(); cDOB = CustomerDOB.Text; cPN = CustomerPN.Text; cEID = CustomerEID.Text; cPPNo = CustomerPassportNo.Text; cNationality = CustomerNationality.Text; cHName = CardHolderNameTB.Text; cCrdN = CreditCardNoTB.Text; cPass = User_Pass_TB.Text; bool allDigitPP = cPPNo.All(char.IsDigit); bool allDigitPN = cPN.All(char.IsDigit); bool allDigitCCNo = cCrdN.All(char.IsDigit); int warning = 0; int nameV = 0; if ((cName == "") || (cGender == "") || (cDOB == "") || (cPN == "") || (cEID == "") || (cNationality == "") || (cPPNo == "")) { MessageBox.Show("Can't keep any field blank!!! Fill up all to proceed!"); } else { if (allDigitPP == false) { MessageBox.Show("Invalid Passport Number"); warning = 3; } if (allDigitPN == false) { MessageBox.Show("Invalid Phone Number"); warning = 4; } if (allDigitCCNo == false) { MessageBox.Show("Invalid ID Number"); warning = 5; } if (Regex.IsMatch(cNationality, @"^[a-zA-Z]+$") == true) //all character { //MessageBox.Show("All are letters"); } else { MessageBox.Show("Not a valid Nation!"); warning = 6; } if (Regex.IsMatch(cHName, @"^[a-zA-Z]+$") == true) //all character { //MessageBox.Show("All are letters"); } else { MessageBox.Show("Not a valid Card Holder Name!"); warning = 7; } if (Regex.IsMatch(cName, @"^[a-zA-Z ]{2,30}$") == true) { //MessageBox.Show("valid name no number upto 30!"); nameV = 1; } else { //MessageBox.Show("Invalid name"); warning = 1; } if (nameV == 0) { if (Regex.IsMatch(cName, @"^[a-zA-Z ]{2,26}[0-9]{1,4}$") == true) { //MessageBox.Show("at first letter then number up to 5"); warning = 0; } else { MessageBox.Show("Invalid name"); warning = 1; } } if (Regex.IsMatch(cEID, @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$") == true) { //MessageBox.Show("VALID EMAIL ID"); //warning = 0; } else { MessageBox.Show("Invalid email id"); warning = 2; } if (warning == 0) { //MessageBox.Show("Go to next form! :) "+warning); //PaymentMethodPanel pMF=new PaymentMethodPanel(this, flightListNo, totalAmount, cID, cName, cGender, cDOB, cPN, cEID, cPPNo, cNationality,intoE,intoB,sEAvail,sBAvail); //pMF.Show(); //this.Hide(); var x = from a in uHLD.Customer_Infos where a.CID == userID select a; x.First().CID = Convert.ToInt32(CIDTB.Text); x.First().CName = CustomerName.Text; x.First().CGender = CustomerGender.Text; x.First().CDOB = CustomerDOB.Text; x.First().CPhone_Num = CustomerPN.Text; x.First().CEmail = CustomerEID.Text; x.First().CPassport_No = CustomerPassportNo.Text; x.First().CNationality = CustomerNationality.Text; x.First().Card_Holder_Name = CardHolderNameTB.Text; x.First().Credit_Card_No = Convert.ToInt32(CreditCardNoTB.Text); x.First().CPassword = User_Pass_TB.Text; uHLD.SubmitChanges(); MessageBox.Show("Update Successfull!"); UserHome uH2 = new UserHome(cLF, userID); this.Hide(); uH2.Show(); } } } } } <file_sep>/Air_Reservation_System/Seat_Booking.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Air_Reservation_System { public partial class Seat_Booking : Form { int economyP = 0; int businessP = 0; int flightListNo=0; int ecP = 0; int bsnsP = 0; int totalAmount = 0; int intoE = 0; int intoB = 0; int sEAvail = 0; int sBAvail = 0; Form fDF; string selectedE = ""; string selectedB = ""; public Seat_Booking() { InitializeComponent(); } public Seat_Booking(Form fDF, int flightListNo, int economyP, int businessP, int sEAvail, int sBAvail) { InitializeComponent(); this.fDF = fDF; this.flightListNo = flightListNo; this.economyP = economyP; this.businessP = businessP; this.sEAvail = sEAvail; this.sBAvail = sBAvail; } private void Seat_Booking_Load(object sender, EventArgs e) { EconomySBCB.Items.AddRange(new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" }); BusinessSBCB.Items.AddRange(new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" }); EconomySBCB.SelectedIndex = 0; BusinessSBCB.SelectedIndex = 0; TAB_BDT.Enabled = false; TAB_USD.Enabled = false; } private void EconomySBCB_SelectedIndexChanged(object sender, EventArgs e) { string selectedE = EconomySBCB.SelectedItem.ToString(); intoE = Convert.ToInt32(selectedE); ecP = economyP * intoE; totalAmount = ecP + bsnsP; float tAf = totalAmount / (float)81.15; TAB_BDT.Text = totalAmount.ToString(); TAB_USD.Text = tAf.ToString(); } private void BusinessSBCB_SelectedIndexChanged(object sender, EventArgs e) { selectedB = BusinessSBCB.SelectedItem.ToString(); intoB = Convert.ToInt32(selectedB); bsnsP = businessP * intoB; totalAmount = ecP + bsnsP; float tAf = totalAmount / (float)81.15; TAB_BDT.Text = totalAmount.ToString(); TAB_USD.Text = tAf.ToString(); } private void SeatBooking_Back_Click(object sender, EventArgs e) { this.Hide(); fDF.Show(); } private void SB_Next_Click(object sender, EventArgs e) { if (totalAmount==0) { MessageBox.Show("Select atleast one seat then proceed.....!!!"); } else if(intoE>sEAvail) { MessageBox.Show("That Much Economy seat is not available for the Flight!!!!"); } else if(intoB>sBAvail) { MessageBox.Show("That Much Business seat is not available for the Flight!!!!"); } else { sEAvail = sEAvail - intoE; sBAvail = sBAvail - intoB; CustomerInfoPanel cIF = new CustomerInfoPanel(this, flightListNo, totalAmount, intoE, intoB, sEAvail, sBAvail); this.Hide(); cIF.Show(); } } } } <file_sep>/README.md # Air-Reservation-System I developed this app while learning C# for the 1st time back in 2017. OOP concept was used while building the project. I build this app using Windows Forms. Also used Microsoft SQL Server as well as LINQ Class to create Object relation Mapping with the Dtabase. Is has Admin Panel and User Panel as well. You need Visual Studio 2013 or Higher along with 4.5 or higher vesion of .NET Framework to run this Software. I have also provided a exe file of the software. To execute it either extract the Air_Reservation_System.zip file directly on C drive or create a folder 'Air_Reservation_System' in C Drive and put 'Airline_Reservation_System.mdf' & 'Air_Reservation_System_log.ldf' in that directory and then run the Air_Reservation_System.exe file. There's few bugs. 1st of all not all the exceptions are handled properly and back then in 2017 I couldn't auto increment the table ID in Microsoft SQL Server. SO you have to manually put id for every entry and duplicate entry of same id might cause a runtime error! # Demo Data : #admin username : Mzs, admin password : <PASSWORD> #user name : Munna, user password : <PASSWORD> # Demo View : <img src="demo/basic-view.gif" title="air-reservation-basic"/> # User Panel : <img src="demo/user-panel-view.gif" title="air-reservation-user"/> # Admin Panel : <img src="demo/admin-panell-view.gif" title="air-reservation-admin"/> <file_sep>/Air_Reservation_System/AdminPanel.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Air_Reservation_System { public partial class AdminPanel : Form { //Air_Reservation_DBDataContext aPD = new Air_Reservation_DBDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mzs Munna\documents\visual studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Air_Reservation.mdf;Integrated Security=True;Connect Timeout=30"); int flightListNo=-1; Form alP = null; DataGridViewRow selectedRow=null; string currentGridView = ""; public AdminPanel() { InitializeComponent(); } public AdminPanel(Form alP) { InitializeComponent(); this.alP = alP; } private void button5_Click(object sender, EventArgs e) { } private void AdminPanel_Load(object sender, EventArgs e) { currentGridView = "Flight Details"; //Air_Reservation_DBDataContext aPD = new Air_Reservation_DBDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mzs Munna\documents\visual studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Air_Reservation.mdf;Integrated Security=True;Connect Timeout=30"); Airline_Reservation_SystemDBCDataContext aPD = new Airline_Reservation_SystemDBCDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mzs Munna\Documents\Visual Studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Airline_Reservation_System.mdf;Integrated Security=True;Connect Timeout=30"); AP_Gridview_Display.DataSource = aPD.Flight_Details; AP_Gridview_Display.SelectionMode = DataGridViewSelectionMode.FullRowSelect; } private void AP_Admin_Table_Click(object sender, EventArgs e) { currentGridView = "Admin Table"; //Air_Reservation_DBDataContext aPD = new Air_Reservation_DBDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mzs Munna\documents\visual studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Air_Reservation.mdf;Integrated Security=True;Connect Timeout=30"); Airline_Reservation_SystemDBCDataContext aPD = new Airline_Reservation_SystemDBCDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mzs Munna\Documents\Visual Studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Airline_Reservation_System.mdf;Integrated Security=True;Connect Timeout=30"); AP_Gridview_Display.DataSource = aPD.Admins; AP_Gridview_Display.SelectionMode = DataGridViewSelectionMode.FullRowSelect; } private void AP_Customer_Table_Click(object sender, EventArgs e) { currentGridView = "Customer Information"; //Air_Reservation_DBDataContext aPD = new Air_Reservation_DBDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mzs Munna\documents\visual studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Air_Reservation.mdf;Integrated Security=True;Connect Timeout=30"); Airline_Reservation_SystemDBCDataContext aPD = new Airline_Reservation_SystemDBCDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mzs Munna\Documents\Visual Studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Airline_Reservation_System.mdf;Integrated Security=True;Connect Timeout=30"); AP_Gridview_Display.DataSource = aPD.Customer_Infos; AP_Gridview_Display.SelectionMode = DataGridViewSelectionMode.FullRowSelect; } private void AP_Flight_Details_Table_Click(object sender, EventArgs e) { currentGridView = "Flight Details"; //Air_Reservation_DBDataContext aPD = new Air_Reservation_DBDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mzs Munna\documents\visual studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Air_Reservation.mdf;Integrated Security=True;Connect Timeout=30"); Airline_Reservation_SystemDBCDataContext aPD = new Airline_Reservation_SystemDBCDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mzs Munna\Documents\Visual Studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Airline_Reservation_System.mdf;Integrated Security=True;Connect Timeout=30"); AP_Gridview_Display.DataSource = aPD.Flight_Details; AP_Gridview_Display.SelectionMode = DataGridViewSelectionMode.FullRowSelect; } private void AP_Seat_Booking_Click(object sender, EventArgs e) { currentGridView = "Ticket Booking Details"; //Air_Reservation_DBDataContext aPD = new Air_Reservation_DBDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mzs Munna\documents\visual studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Air_Reservation.mdf;Integrated Security=True;Connect Timeout=30"); Airline_Reservation_SystemDBCDataContext aPD = new Airline_Reservation_SystemDBCDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mzs Munna\Documents\Visual Studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Airline_Reservation_System.mdf;Integrated Security=True;Connect Timeout=30"); AP_Gridview_Display.DataSource = aPD.TicketBooked_Infos; AP_Gridview_Display.SelectionMode = DataGridViewSelectionMode.FullRowSelect; } private void AP_Add_Flight_Click(object sender, EventArgs e) { //Air_Reservation_DBDataContext aPD = new Air_Reservation_DBDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mzs Munna\documents\visual studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Air_Reservation.mdf;Integrated Security=True;Connect Timeout=30"); Airline_Reservation_SystemDBCDataContext aPD = new Airline_Reservation_SystemDBCDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mzs Munna\Documents\Visual Studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Airline_Reservation_System.mdf;Integrated Security=True;Connect Timeout=30"); AddFlightPanel aFF = new AddFlightPanel("Add", AP_Gridview_Display, flightListNo); aFF.Show(); } private void AP_UpdateF_Click(object sender, EventArgs e) { //Air_Reservation_DBDataContext aPD = new Air_Reservation_DBDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mzs Munna\documents\visual studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Air_Reservation.mdf;Integrated Security=True;Connect Timeout=30"); Airline_Reservation_SystemDBCDataContext aPD = new Airline_Reservation_SystemDBCDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\<NAME>\Documents\Visual Studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Airline_Reservation_System.mdf;Integrated Security=True;Connect Timeout=30"); if (currentGridView == "Flight Details") { AddFlightPanel aFF = new AddFlightPanel("Update", AP_Gridview_Display, flightListNo); aFF.Show(); } else { MessageBox.Show("Currently Displaying " + currentGridView + " Table!!"); } } private void AP_Gridview_Display_CellClick(object sender, DataGridViewCellEventArgs e) { //Air_Reservation_DBDataContext aPD = new Air_Reservation_DBDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mzs Munna\documents\visual studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Air_Reservation.mdf;Integrated Security=True;Connect Timeout=30"); Airline_Reservation_SystemDBCDataContext aPD = new Airline_Reservation_SystemDBCDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mzs Munna\Documents\Visual Studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Airline_Reservation_System.mdf;Integrated Security=True;Connect Timeout=30"); int index = e.RowIndex; selectedRow = AP_Gridview_Display.Rows[index]; flightListNo = Convert.ToInt32(selectedRow.Cells[0].Value.ToString()); } private void AP_Cancel_FS_Click(object sender, EventArgs e) { //Air_Reservation_DBDataContext aPD = new Air_Reservation_DBDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mzs Munna\documents\visual studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Air_Reservation.mdf;Integrated Security=True;Connect Timeout=30"); Airline_Reservation_SystemDBCDataContext aPD = new Airline_Reservation_SystemDBCDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mzs Munna\Documents\Visual Studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Airline_Reservation_System.mdf;Integrated Security=True;Connect Timeout=30"); if (currentGridView == "Flight Details") { var x = from a in aPD.Flight_Details where a.Flight_ID == flightListNo select a; foreach (Flight_Detail p in x) { aPD.Flight_Details.DeleteOnSubmit(p); } aPD.SubmitChanges(); AP_Gridview_Display.DataSource = aPD.Flight_Details; AP_Gridview_Display.SelectionMode = DataGridViewSelectionMode.FullRowSelect; } else { MessageBox.Show("Currently Displaying " + currentGridView + " Table!!"); } } private void AP_Search_Click(object sender, EventArgs e) { //Air_Reservation_DBDataContext aPD = new Air_Reservation_DBDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\<NAME>na\documents\visual studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Air_Reservation.mdf;Integrated Security=True;Connect Timeout=30"); Airline_Reservation_SystemDBCDataContext aPD = new Airline_Reservation_SystemDBCDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\<NAME>na\Documents\Visual Studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Airline_Reservation_System.mdf;Integrated Security=True;Connect Timeout=30"); string searchS=APSearchBox.Text; if (currentGridView == "Flight Details") { var x = from a in aPD.Flight_Details //where a.Flight_Name == APSearchBox.Text where a.Flight_Name.Contains(APSearchBox.Text) //|| a.Destination == APSearchBox.Text || a.Destination.Contains(APSearchBox.Text) //|| a.Departure == APSearchBox.Text || a.Departure.Contains(APSearchBox.Text) //|| a.Date == APSearchBox.Text || a.Date.Contains(APSearchBox.Text) //|| a.Time == APSearchBox.Text || a.Time.Contains(APSearchBox.Text) select a; if (x.Any()) { AP_Gridview_Display.DataSource = x.ToList(); AP_Gridview_Display.SelectionMode = DataGridViewSelectionMode.FullRowSelect; } else { MessageBox.Show("No such information stored in our database :/!"); } } else if(currentGridView == "Ticket Booking Details") { var x = from a in aPD.TicketBooked_Infos //where a.Flight_Name == APSearchBox.Text where a.Flight_Name.Contains(APSearchBox.Text) //|| a.Destination == APSearchBox.Text || a.CName.Contains(APSearchBox.Text) //|| a.Departure == APSearchBox.Text || a.CID==Convert.ToInt32(APSearchBox.Text) //|| a.Date == APSearchBox.Text || a.Flight_ID.ToString()==APSearchBox.Text select a; if (x.Any()) { AP_Gridview_Display.DataSource = x.ToList(); AP_Gridview_Display.SelectionMode = DataGridViewSelectionMode.FullRowSelect; } else { MessageBox.Show("No such information stored in our database :/!"); } } else if(currentGridView == "Customer Information") { var x = from a in aPD.Customer_Infos //where a.Flight_Name == APSearchBox.Text where a.CName.Contains(APSearchBox.Text) //|| a.Destination == APSearchBox.Text || a.CNationality.Contains(APSearchBox.Text) //|| a.Departure == APSearchBox.Text || a.CPhone_Num.Contains(APSearchBox.Text) //|| a.Date == APSearchBox.Text || a.Card_Holder_Name.Contains(APSearchBox.Text) //|| a.Time == APSearchBox.Text || a.CEmail.Contains(APSearchBox.Text) || a.CID.ToString() == APSearchBox.Text select a; if (x.Any()) { AP_Gridview_Display.DataSource = x.ToList(); AP_Gridview_Display.SelectionMode = DataGridViewSelectionMode.FullRowSelect; } else { MessageBox.Show("No such information stored in our database :/!"); } } } private void AP_Logout_Click(object sender, EventArgs e) { this.Hide(); alP.Show(); } private void AP_CancelReservation_Click(object sender, EventArgs e) { Airline_Reservation_SystemDBCDataContext aPD = new Airline_Reservation_SystemDBCDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\<NAME>\Documents\Visual Studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Airline_Reservation_System.mdf;Integrated Security=True;Connect Timeout=30"); if(currentGridView == "Ticket Booking Details") { var x = from a in aPD.TicketBooked_Infos where a.CID == flightListNo select a; foreach (TicketBooked_Info p in x) { aPD.TicketBooked_Infos.DeleteOnSubmit(p); } aPD.SubmitChanges(); AP_Gridview_Display.DataSource = aPD.TicketBooked_Infos; AP_Gridview_Display.SelectionMode = DataGridViewSelectionMode.FullRowSelect; } } } } <file_sep>/Air_Reservation_System/AIRRMainFrame.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Air_Reservation_System { public partial class AIRRMainFrame : Form { public AIRRMainFrame() { InitializeComponent(); } private void pictureBox1_Click(object sender, EventArgs e) { } private void MainFLogin_Click(object sender, EventArgs e) { BothUserAdminForm u2= new BothUserAdminForm(); u2.Show(); } private void Main_SeeAvailFlight_Click(object sender, EventArgs e) { Flight_Details fDF = new Flight_Details(this); fDF.Show(); this.Hide(); } private void Main_About_Click(object sender, EventArgs e) { MessageBox.Show("Developped by ........\n\n1. Most. <NAME> [15-30519-3]\n\n2. Sarker, MD.M<NAME> [15-29817-2]\n\n3. Pranti, Most. Pl<NAME> [13-25454-3]\n\n4. <NAME> [14-27170-2]\n\n"); } private void AIRRMainFrame_FormClosed(object sender, FormClosedEventArgs e) { Application.Exit(); } } } <file_sep>/Air_Reservation_System/CreditCardInfoPanel.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Text.RegularExpressions; using System.IO; namespace Air_Reservation_System { public partial class CreditCardInfoPanel : Form { string cID = ""; string cName = ""; string cGender = ""; string cDOB = ""; string cPN = ""; string cEID = ""; string cPPNo = ""; string cNationality = ""; Form cIF; int flightListNo = 0; int totalAmount = 0; int intoE = 0; int intoB = 0; int sEAvail=0; int sBAvail=0; int cCount=3; int fCount=1; int aCount=3; int tbCount=0; string cHName = ""; string cCNo = ""; string cCPc = ""; string cCEd = ""; //Air_Reservation_DBDataContext ciD = new Air_Reservation_DBDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mzs Munna\Documents\visual studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Air_Reservation.mdf;Integrated Security=True;Connect Timeout=30"); Airline_Reservation_SystemDBCDataContext ciD = new Airline_Reservation_SystemDBCDataContext(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Mzs Munna\Documents\Visual Studio 2013\Projects\Air_Reservation_System\Air_Reservation_System\Airline_Reservation_System.mdf;Integrated Security=True;Connect Timeout=30"); public CreditCardInfoPanel() { InitializeComponent(); } public CreditCardInfoPanel(Form cIF, int flightListNo, int totalAmount, string cID, string cName, string cGender, string cDOB, string cPN, string cEID, string cPPNo, string cNationality,int intoE, int intoB, int sEAvail, int sBAvail) { InitializeComponent(); this.cIF = cIF; this.flightListNo = flightListNo; this.totalAmount = totalAmount; this.cName = cName; this.cGender = cGender; this.cDOB = cDOB; this.cPN = cPN; this.cEID = cEID; this.cPPNo = cPPNo; this.cNationality = cNationality; this.intoE = intoE; this.intoB = intoB; this.sEAvail=sEAvail; this.sBAvail=sBAvail; this.cID = cID; } private void CCI_Pay_Click(object sender, EventArgs e) { int warning = 0; cHName = CardHolderNameTB.Text; cCNo = CreditCardNoTB.Text; cCPc = CardPinNoTB.Text; cCEd = CCIEXD.Value.ToString("dd-MM-yyyy"); bool allDigitCCN = cCNo.All(char.IsDigit); bool allDigitCPC = cCPc.All(char.IsDigit); if ((cHName == "") || (cCNo == "") || (cCPc == "") || (cCEd == "")) { MessageBox.Show("Can't skip any field!!! Fill up all to proceed!"); } else { if (allDigitCCN == false) { MessageBox.Show("Invalid Credit Card Number"); warning = 3; } if (allDigitCPC == false) { MessageBox.Show("Invalid Pin Code Number"); warning = 2; } if (Regex.IsMatch(cHName, @"^[a-zA-Z ]{2,30}$") == true) { //MessageBox.Show("valid name no number upto 30!"); //nameV = 1; } else { MessageBox.Show("Invalid Card Holder name"); warning = 1; } if (warning == 0) { int cusID = Convert.ToInt32(cID); //string path=Path.GetRandomFileName(); //path=path.Replace(".",""); //cCount++; string path = "12345" + cName; Customer_Info ciT = new Customer_Info { CID=cusID, CName=cName, CGender=cGender, CDOB=cDOB, CPhone_Num=cPN, CEmail=cEID, CPassport_No=cPPNo, CNationality=cNationality, Card_Holder_Name=cHName, Credit_Card_No=Convert.ToInt32(cCNo), Card_Expire_Date=cCEd, CPassword=<PASSWORD> }; ciD.Customer_Infos.InsertOnSubmit(ciT); ciD.SubmitChanges(); var x = from a in ciD.Flight_Details where a.Flight_ID == flightListNo select a; string fN = x.First().Flight_Name; x.First().Available_Seat_E_ = sEAvail; x.First().Available_Seat_B_ = sBAvail; ciD.SubmitChanges(); var y = from b in ciD.Flight_Details //where a.Flight_Name == APSearchBox.Text where b.Available_Seat_B_ == 0 && b.Available_Seat_E_ == 0 select b; foreach (Flight_Detail p in y) { ciD.Flight_Details.DeleteOnSubmit(p); } ciD.SubmitChanges(); TicketBooked_Info tbT = new TicketBooked_Info { CID=cusID, CName=cName, Flight_ID=flightListNo, Flight_Name=fN, Business_Seat_Taken=intoB, Economy_Seat_Taken=intoE }; ciD.TicketBooked_Infos.InsertOnSubmit(tbT); ciD.SubmitChanges(); MessageBox.Show("Ticket Confirmation is Successfull!! :)\n\nYour User Password is : " + path + "\n\nyou can login with your user name using this password from login panel! "); this.Hide(); AIRRMainFrame mF = new AIRRMainFrame(); mF.Show(); } } } } } <file_sep>/Air_Reservation_System/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace Air_Reservation_System { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //Application.Run(new Flight_Details()); //Application.Run(new Seat_Booking()); //Application.Run(new CustomerInfoPanel()); //Application.Run(new AdminPanel()); //Application.Run(new AdminLogin()); Application.Run(new AIRRMainFrame()); } } }
33032e4e8f7a8ece9b1a8ff4f03ad3f4a0b54d94
[ "Markdown", "C#" ]
15
C#
maziesmith/Air-Reservation-System-CSharp
20e7c444cb5a595cc9bd87743733488045c01bce
a7e278a9edbddcdd0eecdab623490955feade872
refs/heads/master
<file_sep>Sample Facebook Admin Application using Play Framework and restfb ================================================================== + Play Framework v.2.5 + restfb v.1.19.0 + PureCSS + MongoDB 3.2 This application allows you to create 3 types of posts (status messages, photos and videos). You can create unpublished posts, scheduled posts or publish them immediately. The posts created can be managed using a tabular list. The manage options include delete, publish unpublished and view details. The application enables basic authentication (login and logout) <file_sep>package util; import java.net.UnknownHostException; import com.mongodb.DB; import com.mongodb.MongoClient; import com.mongodb.client.MongoDatabase; public class MongoConnect { private MongoClient mongoClient = null; private MongoDatabase db = null; private final static String DB_NAME = "appdb"; /** * Constructor * Creates a mongoClient if it's not yet initialized * * @throws UnknownHostException */ public MongoConnect() throws UnknownHostException { if (mongoClient == null) { mongoClient = getClient("localhost", "27017"); } } /* * Private method to create the mongoclient * @return MongoClient */ private MongoClient getClient(String host, String port) throws UnknownHostException { return new MongoClient(host, Integer.parseInt(port)); } /** * getter method to return the db object * @return MongoDatabase */ public MongoDatabase getDB() { if (db == null) { db = mongoClient.getDatabase(DB_NAME); } return db; } } <file_sep>$.fn.serializeObject = function() { var o = {}; var a = this.serializeArray(); $.each(a, function() { if (o[this.name] !== undefined) { if (!o[this.name].push) { o[this.name] = [o[this.name]]; } o[this.name].push(this.value || ''); } else { o[this.name] = this.value || ''; } }); return o; }; /*$(function() { $('form').submit(function() { //$('#result').text(JSON.stringify($('form').serializeObject())); var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == XMLHttpRequest.DONE) { json = JSON.parse(xhr.responseText); if(json.error!=null) document.getElementById('errormessage').innerHTML = json.error; else if(json.post_id!=null) { //if(json.message!=null) window.location.href = "/postdetails/"+json.post_id; } else if(json.message!=null) document.getElementById('errormessage').innerHTML = json.message; } } xhr.open(postForm.method, postForm.action, true); xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8'); var formData = $('form').serializeObject(); formData['filedata1'] = document.getElementById('filedata'); var message = xhr.send(JSON.stringify(formData)); return false; }); });*/ (function (window, document) { var layout = document.getElementById('layout'), menu = document.getElementById('menu'), menuLink = document.getElementById('menuLink'); function toggleClass(element, className) { var classes = element.className.split(/\s+/), length = classes.length, i = 0; for(; i < length; i++) { if (classes[i] === className) { classes.splice(i, 1); break; } } // The className is not found if (length === classes.length) { classes.push(className); } element.className = classes.join(' '); } menuLink.onclick = function (e) { var active = 'active'; e.preventDefault(); toggleClass(layout, active); toggleClass(menu, active); toggleClass(menuLink, active); }; }(this, this.document)); <file_sep>package util; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; import play.api.i18n.Lang; import scala.concurrent.duration.Duration; import akka.util.Timeout; public interface AppConstants { public static final String APPLICATION_TEXT = "application/text"; public static final String APPLICATION_JSON = "application/json"; public static final String APPLICATION_PDF = "application/pdf"; public static final String APPLICATION_XLS = "application/vnd.ms-excel"; public static Lang lang = new Lang("en", "us"); public static final Timeout TIMEOUT = new Timeout( Duration.create( 60, TimeUnit.SECONDS)); //Error codes public static final String INTERNAL_SERVER_ERROR = "A500"; public static final String CONFIGURATION_ERROR = "A550"; public static final String PARSING_ERROR = "A575"; public static final String BAD_REQUEST_ERROR = "A400"; public static final String NOT_FOUND_ERROR = "A404"; public static final String X_REQUEST_TYPE = "CLIENT_REQUEST_TYPE"; public static final String WEB_CLIENT = "WEB"; public static final Integer PAGE_SIZE = 20; public static final String MESSAGE = "feed"; public static final String PHOTO = "photos"; public static final String VIDEO = "videos"; public static final List<String> ALLOWED_POSTS = Arrays.asList(new String[]{MESSAGE,PHOTO,VIDEO});; } <file_sep>/** * */ package models; import java.util.Date; import java.util.List; import com.restfb.types.Comment; /** * @author dlasrado * */ public class FacebookPosts { private String postType; private String message; private String name; private Date created_time; private String embedHTML; private String picture; private Long likesCount = 0L; private Long sharesCount = 0L; private int commentsCount = 0; private List<Comment> comments; private String postId; private String description; private String source; /** * @return the postType */ public String getPostType() { return postType; } /** * @param postType the postType to set */ public void setPostType(String postType) { this.postType = postType; } /** * @return the message */ public String getMessage() { return message; } /** * @param message the message to set */ public void setMessage(String message) { this.message = message; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the created_time */ public Date getCreated_time() { return created_time; } /** * @param created_time the created_time to set */ public void setCreated_time(Date created_time) { this.created_time = created_time; } /** * @return the embedURL */ public String getEmbedHTML() { return embedHTML; } /** * @param embedURL the embedURL to set */ public void setEmbedHTML(String embedHTML) { this.embedHTML = embedHTML; } /** * @return the picture */ public String getPicture() { return picture; } /** * @param picture the picture to set */ public void setPicture(String picture) { this.picture = picture; } /** * @return the likeCount */ public Long getLikesCount() { return likesCount; } /** * @param likeCount the likeCount to set */ public void setLikesCount(Long likeCount) { if(likeCount == null) likeCount = 0L; this.likesCount = likeCount; } /** * @return the shareCount */ public Long getSharesCount() { return sharesCount; } /** * @param shareCount the shareCount to set */ public void setSharesCount(Long shareCount) { if(shareCount == null) shareCount = 0L; this.sharesCount = shareCount; } /** * @return the commentsCount */ public int getCommentsCount() { return commentsCount; } /** * @param commentsCount the commentsCount to set */ public void setCommentsCount(int commentsCount) { this.commentsCount = commentsCount; } /** * @return the comments */ public List<Comment> getComments() { return comments; } /** * @param comments the comments to set */ public void setComments(List<Comment> comments) { this.comments = comments; } /** * @return the postId */ public String getPostId() { return postId; } /** * @param postId the postId to set */ public void setPostId(String postId) { this.postId = postId; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } /** * @return the source */ public String getSource() { return source; } /** * @param source the source to set */ public void setSource(String source) { this.source = source; } } <file_sep>(function (window, document) { document.getElementById('option-three').onclick = function (e) { field = document.getElementById('scheduledate'); field.disabled = !field.disabled; field.value = "Specify date"; if(this.checked){ field.focus();} } posttypeselect.onchange = function(e) { if(this.value == "events") { document.getElementById('eventschedule').hidden = false; document.getElementById('filepicker').hidden = true; } else if(this.value == "photos" || this.value == "videos") { document.getElementById('eventschedule').hidden = true; document.getElementById('filepicker').hidden = false; document.getElementById('message').required = false; } else { document.getElementById('eventschedule').hidden = true; document.getElementById('filepicker').hidden = true; document.getElementById('message').required = true; } } }(this, this.document)); $(function() { $('form').submit(function() { //$('#result').text(JSON.stringify($('form').serializeObject())); var postType = document.getElementById('posttypeselect').value; if(postType == "photos" || postType == "videos") { if (document.getElementById('filedata').value == null || document.getElementById('filedata').value == "") { setErrorMessage("Please select a "+ postType.substring(0,postType.length-1)); return false; } } if(document.getElementById('option-three').checked && document.getElementById('scheduledate').value == formatDateOnly(new Date())) { if(document.getElementById('scheduletime').value < (zeroFill(new Date().getHours(),2)+":"+zeroFill(new Date().getMinutes(),2))) { setErrorMessage("Please select a future date time"); return false; } } loading(); return true; }); }); function setErrorMessage(message) { document.getElementById('errormessage').innerHTML = message; } $(function(){ $('#scheduledate').datepicker({ dateFormat: 'dd M yy', minDate: 'today' }); }); $(function(){ $('#expirydate').datepicker({ dateFormat: 'dd M yy', }); }); $(function(){ $('#startdate').datepicker({ dateFormat: 'dd M yy', }); }); $(function(){ $('#enddate').datepicker({ dateFormat: 'dd M yy', }); });
645fd298872e041a859ab26f4e35e0d2ca5e6023
[ "Markdown", "Java", "JavaScript" ]
6
Markdown
dlasrado/informazeapp
15f956550bbe89685ff94a11ee1986d1ea6e6dbd
227972984c675910f206a00ab0794b0deee5cde6
refs/heads/master
<repo_name>Srivasavi-vipparla/about-me<file_sep>/script.js function CalcInterest() { var p,t,r,t2,i; var n=1; p=t=r=t2=i=0; p = parseInt(document.getElementById("pr").value); t = parseInt(document.getElementById("te").value); r = parseInt(document.getElementById("rate").value); t2= document.getElementById("Ttype").value; i= document.getElementById("iType").value; switch (t2) { case "i2": n=2;break; case "i4": n=4;break; } alert("Final amount with Simple interest is: "+(p+((p*t*r)/100))); } <file_sep>/README.md # about-me ## Repository Links * [Source Repository :] (https://github.com/Srivasavi-vipparla/about-me) * [Hosted Page:] ( https://Srivasavi-vipparla.github.io/about-me/) ## About This Repo * This repo is created for Engage 02 * In this repo we are adding Source repository and hosted page link * And mentioning the required tools and languages to publish a repo in GitHub Pages ## Tools and languages Tools Required * GitHub * Visual Studio * BitBucket Language Required * html * CSS * Markdown ## Recommended Resources * https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web * https://www.codecademy.com/learn/introduction-to-javascript * https://github.github.com/gfm/ ## Contibutor <NAME> || Masters in Apllied Computer Science ![vasu (2)](https://user-images.githubusercontent.com/69984398/92043937-be9ff580-ed42-11ea-9766-9eb6938fa1ea.jpg) <file_sep>/test/main.test.js QUnit.module('MAIN MODULE', {}) QUnit.test('TEST CalcInterest()', assert => { const input = document.querySelector('#pr') const input = document.querySelector('#te') const input= document.querySelector('#rate') input.value = 45 assert.equal(input.value, -3, 'Bad value assigned') assert.strictEqual(input.checkValidity(), false, 'Correctly fails validation') input.focus() input.blur() assert.strictEqual(warning.innerHTML, 'Invalid input', `Correctly adds warning ${warning}`) }) <file_sep>/interest.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="author" content="<NAME>"> <meta name="description" content="this is my developer page"> <title> SriVasavi</title> <link href="Styles/style.css" rel="stylesheet"> </head> <header> <h1> Web Apps - P2 Styled Site</h1> </header> <br> <br> <nav> <ul> <a href="index.html">Home</a> <a href="contact.html">Contact Form</a> <a href="interest.html">Interest Calculation</a> <img src="vasu.jpg" alt="SriVasavi" align="right" style="width:100px" class="circular--square"></div> </ul> </nav> <br> <br> <head> <meta charset="UTF-8"> <title>Interest Calculator</title> <style> body {color: #2f4f4f;} p { overflow-x: -webkit-marquee; -webkit-marquee-style: alternate; } </style> <script type="text/javascript" src="script.js"></script> </head> <body> <h1>Interest Calculator </h1> &nbsp; Please enter your Principal Amount($) lended: <input type=number id="pr" value="1"><br> &nbsp; Please enter the tenure: <input type=number id="te" value="1"><br> &nbsp; Enter the interest: <input type=number id="rate" value="0">&nbsp; <select name="rate" id="Ttype" > <option selected="selected" value="i1">Yearly</option> <option value="i4">Quarter-Yearly</option> <option value="i2">Half-Yearly</option> </select><br> &nbsp; Pick the Type of interest: <select name="iType" id="iType" > <option selected="selected" id="s">Simple</option> </select> <br><br> <input type="button" about="Calculate" aria-valuetext="Calculate" value="Calculate" onclick="CalcInterest()"> <br><br><br><br> <p>Thanks for using our interest calculator,hope you got your result, See you again!</p> </body> </html>
956bd9c27f3954e5bf91c1229af1aaca5be24496
[ "JavaScript", "HTML", "Markdown" ]
4
JavaScript
Srivasavi-vipparla/about-me
ef3b555769e7ed8bf145c221fc50bee4a60f0b96
b67a720df0050e0566b2365210b6e17a874afac6
refs/heads/master
<file_sep>import { BrowserModule } from '@angular/platform-browser' import { NgModule } from '@angular/core' import { FormsModule } from '@angular/forms' import { ReactiveFormsModule } from '@angular/forms' import { AppRoutingModule } from './app-routing.module' import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http' import { AngularFontAwesomeModule } from 'angular-font-awesome' import { BrowserAnimationsModule } from '@angular/platform-browser/animations' import { ToastrModule } from 'ngx-toastr' import { AppComponent } from './app.component' import { HomeComponent } from './components/home/home.component' import { HeaderComponent } from './components/header/header.component' import { UserListComponent } from './components/users/user-list/user-list.component' import { UserDetailComponent } from './components/users/user-detail/user-detail.component' import { UsersComponent } from './components/users/users.component' import { UserService } from './services/user.service' import { VendorService } from './services/vendor.service' import { ContactComponent } from './components/contact/contact.component' import { VendorListComponent } from './components/vendors/vendor-list/vendor-list.component' import { VendorDetailComponent } from './components/vendors/vendor-detail/vendor-detail.component' import { HttpErrorInterceptor } from './services/http-error.interceptor'; import { ProductListComponent } from './components/products/product-list/product-list.component' import { ProductDetailComponent } from './components/products/product-detail/product-detail.component' import { ProductService } from './services/product.service'; @NgModule({ declarations: [ AppComponent, HomeComponent, HeaderComponent, UserListComponent, UserDetailComponent, UsersComponent, ContactComponent, VendorListComponent, VendorDetailComponent, ProductListComponent, ProductDetailComponent ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, BrowserModule, FormsModule, ReactiveFormsModule, AngularFontAwesomeModule, BrowserAnimationsModule, ToastrModule.forRoot() ], providers: [ UserService, VendorService, ProductService, { provide: HTTP_INTERCEPTORS, useClass: HttpErrorInterceptor, multi: true } ], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { Injectable } from '@angular/core' import { HttpClient } from '@angular/common/http' import { Observable, throwError } from 'rxjs' import { retry, catchError, tap } from 'rxjs/operators' import { IVendor } from '../models/IVendor' @Injectable() export class VendorService { //apiUrl = 'https://api.github.com/users' apiUrl = 'https://localhost:44353/api/Vendors' constructor(private http: HttpClient) { } getVendors(): Observable<IVendor[]> { return this.http.get<IVendor[]>(`${this.apiUrl}`).pipe( tap(data => console.log('Vendors: ' + JSON.stringify(data)) ) ) } getVendor(vendorId: number): Observable<IVendor> { console.log('VendorService:getVendor vendorId', vendorId) let url = `${this.apiUrl}/${vendorId}` console.log('url', url); return this.http.get<IVendor>(url) } updateVendor(vendor: IVendor) { console.log('updatevendor on vendor service is invoked', vendor) return this.http.put(this.apiUrl, vendor) } createVendor(vendor: IVendor): Observable<number> { console.log('createVendor on vendor service is invoked', vendor) return this.http.post<number>(this.apiUrl, vendor) } handleError(error) { let errorMessage = ''; if (error.error instanceof ErrorEvent) { // client-side error errorMessage = `Error: ${error.error.message}`; } else { // server-side error errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`; } window.alert(errorMessage); return throwError(errorMessage); } } <file_sep>import { Injectable } from '@angular/core' import { HttpClient } from '@angular/common/http' import { Observable, throwError } from 'rxjs' import { retry, catchError } from 'rxjs/operators' import {IProduct} from '../models/IProduct' @Injectable() export class ProductService { //apiUrl = 'https://api.github.com/users' apiUrl = 'https://localhost:44353/api/Products' constructor(private http: HttpClient) { } getProducts() { return this.http.get(`${this.apiUrl}`) } getProduct(productId: number) : Observable<IProduct> { console.log('ProductService:getProduct productId', productId) let url = `${this.apiUrl}/${productId}` console.log('url', url); return this.http.get<IProduct>(url) } updateProduct(product: IProduct) { console.log('updateProduct on product service is invoked', product) return this.http.put(this.apiUrl, product) } createProduct(product: IProduct) : Observable<number> { console.log('createProduct on product service is invoked', product) return this.http.post<number>(this.apiUrl, product) } handleError(error) { let errorMessage = ''; if (error.error instanceof ErrorEvent) { // client-side error errorMessage = `Error: ${error.error.message}`; } else { // server-side error errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`; } window.alert(errorMessage); return throwError(errorMessage); } } <file_sep>import { Component, OnInit } from "@angular/core" import { ActivatedRoute } from "@angular/router" import { Location } from '@angular/common' import { FormBuilder, FormGroup, Validators } from '@angular/forms' import { Router } from "@angular/router" import { ToastrService } from 'ngx-toastr' import { VendorService } from '../../../services/vendor.service' import { IVendor } from '../../../models/IVendor' @Component({ selector: 'vendor-detail', templateUrl: './vendor-detail.component.html' }) export class VendorDetailComponent implements OnInit { vendorForm: FormGroup isNew: boolean constructor( private route: ActivatedRoute, private vendorService: VendorService, private location: Location, private formBuilder: FormBuilder, private router: Router, private toastr: ToastrService ) { } ngOnInit(): void { this.getVendor() this.vendorForm = this.formBuilder.group({ vendorID: [''], vendorName: ['', [Validators.required]], vendorPhone: ['', [Validators.required]], email: ['', [Validators.required, Validators.email]] }) } getVendor(): void { const id = + this.route.snapshot.paramMap.get('id') if (id) { this.isNew = false this.vendorService.getVendor(id) .subscribe( (vendor: IVendor) => this.showVendor(vendor) ) } else { this.isNew = true } } //perform work of binding retrived vendor data to form control showVendor(vendor: IVendor) { this.vendorForm.patchValue({ vendorID: vendor.vendorID, vendorName: vendor.vendorName, vendorPhone: vendor.vendorPhone, email: vendor.email }) } createVendor() { if (this.vendorForm.valid) { console.log('Vendor form is valid!!', this.vendorForm.value) this.vendorService.createVendor(this.vendorForm.value) .subscribe((response) => { console.log('create response ', response) this.toastr.success("Vendor information saved") }) } else { //alert('User form is not valid!!') this.toastr.warning("Vendor information is not complete to be saved") } } updateVendor() { if (this.vendorForm.valid) { console.log('Vendor form is valid!!', this.vendorForm.value) this.vendorService.updateVendor(this.vendorForm.value) .subscribe((response) => { console.log('update response ', response) this.toastr.success("Vendor information saved") }) } else { //alert('User form is not valid!!') this.toastr.warning("Vendor information is not complete to be saved") } } onSubmit() { if (this.isNew == false) { this.updateVendor() } else { this.createVendor() } } onCancel() { console.log('cancel clicked ') this.router.navigateByUrl('/vendors') } }<file_sep>export interface IVendor { vendorID: number vendorName: string vendorPhone: string email: string }<file_sep>export interface IUser { userID: number userName: string userPassword: string isActive: boolean roleID: number }<file_sep>export interface IProduct { productID: number productName: string productDescription: string unitsInStock: number sellPrice: number discountPercentage: number unitsMax: number }<file_sep>import { Injectable } from '@angular/core' import { HttpClient } from '@angular/common/http' import { Observable, throwError } from 'rxjs' import { retry, catchError } from 'rxjs/operators' import {IUser} from '../models/IUser' @Injectable() export class UserService { //apiUrl = 'https://api.github.com/users' apiUrl = 'https://localhost:44353/api/Users' constructor(private http: HttpClient) {} getUsers() { //return this.http.get(`${this.apiUrl}?per_page=100`) return this.http.get(`${this.apiUrl}`) } getUser(userId: number) : Observable<IUser> { console.log('UserService:getUser userId', userId) let url = `${this.apiUrl}/${userId}` console.log('url', url); return this.http.get<IUser>(url) } updateUser(user: IUser) { console.log('updatUser on user service is invoked', user) return this.http.put(this.apiUrl, user) } createUser(user: IUser) : Observable<number> { console.log('createUser on user service is invoked', user) return this.http.post<number>(this.apiUrl, user) } handleError(error) { let errorMessage = ''; if (error.error instanceof ErrorEvent) { // client-side error errorMessage = `Error: ${error.error.message}`; } else { // server-side error errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`; } window.alert(errorMessage); return throwError(errorMessage); } } <file_sep>import { Component, OnInit } from "@angular/core" import { ActivatedRoute } from "@angular/router" import { Location } from '@angular/common' import { FormBuilder, FormGroup, Validators } from '@angular/forms' import { Router } from "@angular/router" import { ToastrService } from 'ngx-toastr' import { ProductService } from '../../../services/product.service' import { IProduct } from '../../../models/IProduct' @Component({ selector: 'product-detail', templateUrl: './product-detail.component.html' }) export class ProductDetailComponent implements OnInit { productForm: FormGroup isNew: boolean constructor( private route: ActivatedRoute, private productService: ProductService, private location: Location, private formBuilder: FormBuilder, private router: Router, private toastr: ToastrService ) { } ngOnInit(): void { this.getProduct() this.productForm = this.formBuilder.group({ productID: ['-1'], productName: ['', [Validators.required]], productDescription: ['', [Validators.required]], unitsInStock: ['', [Validators.required]], sellPrice: ['', [Validators.required]], discountPercentage: ['', [Validators.required]], unitsMax: ['', [Validators.required]], }) } getProduct(): void { const id = + this.route.snapshot.paramMap.get('id') if (id) { this.isNew = false this.productService.getProduct(id) .subscribe( (product: IProduct) => this.showProduct(product) ) } else { this.isNew = true } } //perform work of binding retrived vendor data to form control showProduct(product: IProduct) { this.productForm.patchValue({ productID: product.productID, productName: product.productName, productDescription: product.productDescription, unitsInStock: product.unitsInStock, sellPrice: product.sellPrice, discountPercentage: product.discountPercentage, unitsMax: product.unitsMax }) } createProduct() { if (this.productForm.valid) { console.log('Product form is valid!!', this.productForm.value) this.productService.createProduct(this.productForm.value) .subscribe((response) => { console.log('create response ', response) this.toastr.success("Product information saved") }) } else { //alert('User form is not valid!!') this.toastr.warning("Product information is not complete to be saved") } } updateProduct() { if (this.productForm.valid) { console.log('Product form is valid!!', this.productForm.value) this.productService.updateProduct(this.productForm.value) .subscribe((response) => { console.log('update response ', response) this.toastr.success("Product information saved") }) } else { //alert('User form is not valid!!') this.toastr.warning("Product information is not complete to be saved") } } onSubmit() { if (this.isNew == false) { this.updateProduct() } else { this.createProduct() } } onCancel() { console.log('cancel clicked ') this.router.navigateByUrl('/products') } }<file_sep>import { Component, OnInit } from "@angular/core" import { VendorService } from '../../../services/vendor.service' import { IVendor } from '../../../models/IVendor' @Component({ selector: "vendor-list", templateUrl: "./vendor-list.component.html" }) export class VendorListComponent { vendors: IVendor[] constructor(private vendorService: VendorService) { } ngOnInit() { this.vendorService.getVendors().subscribe( data => this.vendors = data ) } }<file_sep>import { Component, OnInit } from "@angular/core" import {ProductService } from '../../../services/product.service' @Component({ selector: "product-list", templateUrl: "./product-list.component.html" }) export class ProductListComponent { products: any constructor(private productService: ProductService) { } ngOnInit() { this.products = this.productService.getProducts(); } }<file_sep>import { NgModule } from '@angular/core' import { Routes, RouterModule } from '@angular/router' import { HomeComponent } from './components/home/home.component' import { ContactComponent } from './components/contact/contact.component' import { UsersComponent } from './components/users/users.component' import { UserDetailComponent } from './components/users/user-detail/user-detail.component' import { UserListComponent } from './components/users/user-list/user-list.component' import { VendorListComponent } from './components/vendors/vendor-list/vendor-list.component' import { VendorDetailComponent } from './components/vendors/vendor-detail/vendor-detail.component' import { ProductListComponent } from './components/products/product-list/product-list.component' import { ProductDetailComponent } from './components/products/product-detail/product-detail.component' const routes: Routes = [ { path: '', pathMatch: 'full', component: HomeComponent }, { path: 'contact', component: ContactComponent }, { path: 'users', component: UserListComponent //loadChildren: 'app/users/users.module#UsersModule' }, { path: 'user/:id', component: UserDetailComponent //loadChildren: 'app/users/users.module#UsersModule' }, { path: 'user', component: UserDetailComponent }, { path: 'vendors', component: VendorListComponent //loadChildren: 'app/vendors/vendors.module#VendorsModule' }, { path: 'vendor', component: VendorDetailComponent }, { path: 'vendor/:id', component: VendorDetailComponent //loadChildren: 'app/users/users.module#UsersModule' }, { path: 'products', component: ProductListComponent //loadChildren: 'app/products/products.module#ProductsModule' }, { path: 'product', component: ProductDetailComponent }, { path: 'product/:id', component: ProductDetailComponent }, ] @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { } <file_sep>import { Component, OnInit } from "@angular/core" import { ActivatedRoute } from "@angular/router" import { Location } from '@angular/common' import { FormBuilder, FormGroup, Validators } from '@angular/forms' import { Router } from "@angular/router" import { ToastrService } from 'ngx-toastr' import { UserService } from '../../../services/user.service' import { IUser } from '../../../models/IUser' @Component({ selector: 'user-detail', templateUrl: './user-detail.component.html' }) export class UserDetailComponent implements OnInit { userForm: FormGroup isNew: boolean constructor( private route: ActivatedRoute, private userService: UserService, private location: Location, private formBuilder: FormBuilder, private router: Router, private toastr: ToastrService ) { } ngOnInit(): void { this.getUser() this.userForm = this.formBuilder.group({ userID: [''], userName: ['', [Validators.required]], userPassword: ['', [Validators.required]], isActive: ['', [Validators.required]], roleID: ['', [Validators.required]] }) } getUser(): void { const id = + this.route.snapshot.paramMap.get('id') if (id) { this.isNew = false this.userService.getUser(id) .subscribe( (user: IUser) => this.showUser(user) ) } else { this.isNew = true } } //perform work of binding retrived vendor data to form control showUser(user: IUser) { this.userForm.patchValue({ userID: user.userID, vuserName: user.userName, vendorPhone: user.userPassword, isActive: user.isActive, roleID: user.roleID, }) } createUser() { if (this.userForm.valid) { console.log('User form is valid!!', this.userForm.value) this.userService.createUser(this.userForm.value) .subscribe((response) => { console.log('create response ', response) this.toastr.success("User information saved") }) } else { //alert('User form is not valid!!') this.toastr.warning("User information is not complete to be saved") } } updateUser() { if (this.userForm.valid) { console.log('User form is valid!!', this.userForm.value) this.userService.updateUser(this.userForm.value) .subscribe((response) => { console.log('update response ', response) this.toastr.success("User information saved") }) } else { //alert('User form is not valid!!') this.toastr.warning("User information is not complete to be saved") } } onSubmit() { if (this.isNew == false) { this.updateUser() } else { this.createUser() } } onCancel() { console.log('cancel clicked ') this.router.navigateByUrl('/users') } }
c7d31539567d8af9c12c659dac3481a2e33c9259
[ "TypeScript" ]
13
TypeScript
gfirzon/Productsweb
af061a641f3461115039548c86560076a689d5d8
10275e185ec6bab7cd5c50822b88d0807d1a7e09
refs/heads/master
<file_sep>using Callboard.App.Data.DataContext; using Callboard.App.General.Entities; using Callboard.App.General.Results; using System; using System.Collections.Generic; namespace Callboard.App.Data.Repositories.Realizations { internal class UserRepository : IRepository<User> { private IDataContext<User> _context; public UserRepository(IDataContext<User> context) { _context = context ?? throw new NullReferenceException(nameof(context)); } public IResult<User> Delete(int id) { return _context.Delete(id); } public IResult<IReadOnlyCollection<User>> GetAll() { return _context.GetAll(); } public IResult<User> GetById(int id) { return _context.GetById(id); } public IResult<User> Save(User obj) { return _context.Save(obj); } } }<file_sep>function saveCategory(nameInputId, categoryContainerId) { let nameInput = $("#" + nameInputId); let categoryName = nameInput.val(); if (categoryName) { let category = { CategoryId: 0, Name: categoryName, ParentId: 0 }; $.post('/Category/SaveCategory', { categoryData: JSON.stringify(category) }, function () { getCategoryList(categoryContainerId); }); } }<file_sep>using Callboard.App.Business.Services.Realizations; using Callboard.App.Data.Services; using Callboard.App.General.Cache.Main; using Callboard.App.General.Entities.Commercial; using Callboard.App.General.ResultExtensions; using Callboard.App.General.Results.Realizations; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System.Collections.Generic; using System.Linq; namespace Callboard.App.Business.Test.ProvidersTest { [TestClass] public class CommercialServiceTest { [TestMethod] public void GetCommercials_CommercialCollection() { List<Commercial> commercials = new List<Commercial> { new Commercial { Id = 1, Image = null }, new Commercial { Id = 2, Image = null } }; var mockStorage = new Mock<ICacheStorage>(); mockStorage.Setup(storage => storage.Get<IReadOnlyCollection<Commercial>>(It.IsAny<string>())) .Returns((string value) => null); var mockCommecrialDataService = new Mock<ICommercialService>(); mockCommecrialDataService.Setup(prov => prov.GetCommercials()) .Returns(new SuccessResult<IReadOnlyCollection<Commercial>>(commercials)); var commercialProvider = new CommercialService(mockStorage.Object, mockCommecrialDataService.Object); var resultCommercials = commercialProvider.GetCommercials().GetSuccessResult(); Assert.AreNotEqual(resultCommercials, null); Assert.AreEqual(resultCommercials.Count, commercials.Count); CollectionAssert.AreEqual(resultCommercials.ToList(), commercials); mockCommecrialDataService.Verify(mock => mock.GetCommercials(), Times.Once()); } [TestMethod] public void GetCommercials_CommercialCollectionFromCache() { List<Commercial> commercials = new List<Commercial> { new Commercial { Id = 1, Image = null }, new Commercial { Id = 2, Image = null } }; var mockStorage = new Mock<ICacheStorage>(); mockStorage.Setup(storage => storage.Get<IReadOnlyCollection<Commercial>>(It.IsAny<string>())) .Returns(commercials); var mockCommecrialDataService = new Mock<ICommercialService>(); var commercialService = new CommercialService(mockStorage.Object, mockCommecrialDataService.Object); var resultCommercials = commercialService.GetCommercials().GetSuccessResult(); Assert.AreNotEqual(resultCommercials, null); Assert.AreEqual(resultCommercials.Count, commercials.Count); CollectionAssert.AreEqual(resultCommercials.ToList(), commercials); mockStorage.Verify(mock => mock.Get<IReadOnlyCollection<Commercial>>(It.IsAny<string>()), Times.Once()); } } }<file_sep>function deleteUserRole(userId, roleId, userRoleContainerId) { if (userId && roleId) { let deleteRoleView = function () { $("#" + userRoleContainerId).remove(); } $.post('/Role/DeleteUserRole', { userId: userId, roleId: roleId }, deleteRoleView); } }<file_sep>using Callboard.App.General.Loggers.Main; using System; using System.Configuration; using System.ServiceModel; using System.ServiceModel.Configuration; using Service = Callboard.App.Data.CommercialService; namespace Callboard.App.Data.ServiceContext.Realizations { internal class ServiceContext<T> : IServiceContext<T> { private ILoggerWrapper _logger; public ServiceContext(ILoggerWrapper logger) { _logger = logger ?? throw new NullReferenceException(nameof(logger)); } public TOut GetData<TOut>(string endpointConfigurationName, Configuration configuration, EndpointAddress remoteAddress, Func<T, TOut> getData) { TOut data = default(TOut); using (var channelFactory = new ConfigurationChannelFactory<T>(endpointConfigurationName, configuration, remoteAddress)) { try { var channel = channelFactory.CreateChannel(); data = getData(channel); channelFactory.Close(); } catch (ConfigurationErrorsException ex) { _logger.WarnFormat($"{ ex.Message }"); } catch (TimeoutException ex) { _logger.WarnFormat($"Cannot connect to { nameof(T) }.\n { ex.Message }"); } catch (FaultException<Service::CommercialNotFound> ex) { _logger.WarnFormat($"{ ex.Message }"); } catch (FaultException ex) { _logger.WarnFormat($"Cannot connect to { nameof(T) }.\n { ex.Message }"); } catch (CommunicationException ex) { _logger.WarnFormat($"Cannot connect to { nameof(T) }.\n { ex.Message }"); } catch (Exception ex) { _logger.WarnFormat($"Cannot connect to { nameof(T) }.\n { ex.Message }"); } } return data; } } }<file_sep>namespace Callboard.App.Business.Auth { public enum RoleType { Admin, Editor, User } }<file_sep>using Callboard.App.Data.Repositories; using Callboard.App.General.Entities; using Callboard.App.General.Exceptions; using Callboard.App.General.Results; using System; using System.Collections.Generic; namespace Callboard.App.Business.Services.Realizations { internal class KindService : IEntityService<Kind> { private IRepository<Kind> _kindRepository; public KindService(IRepository<Kind> kindRepository) { _kindRepository = kindRepository ?? throw new NullReferenceException(nameof(kindRepository)); } public IResult<Kind> Delete(int id) { this.CheckId(id); return _kindRepository.Delete(id); } public IResult<IReadOnlyCollection<Kind>> GetAll() { return _kindRepository.GetAll(); } public IResult<Kind> GetById(int id) { this.CheckId(id); return _kindRepository.GetById(id); } public IResult<Kind> Save(Kind obj) { obj = obj ?? throw new NullReferenceException(nameof(obj)); return _kindRepository.Save(obj); } private void CheckId(int id) { if (id < 1) { throw new InvalidIdException(nameof(id)); } } } }<file_sep>using Callboard.App.Business.Services.Realizations; using Callboard.App.Data.Repositories; using Callboard.App.General.Entities; using Callboard.App.General.Exceptions; using Callboard.App.General.ResultExtensions; using Callboard.App.General.Results.Realizations; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System; using System.Collections.Generic; namespace Callboard.App.Business.Test.ProvidersTest.Ad { [TestClass] public class KindServiceTest { [TestMethod] public void GetAll_KindsCollection() { var kinds = new List<Kind> { new Kind { KindId = 1, Type = "MyType-1" }, new Kind { KindId = 2, Type = "MyType-2" } }; var mockKindRepository = new Mock<IRepository<Kind>>(); mockKindRepository.Setup(repo => repo.GetAll()) .Returns(new SuccessResult<IReadOnlyCollection<Kind>>(kinds)); var kindProvider = new KindService(mockKindRepository.Object); var resultKinds = kindProvider.GetAll().GetSuccessResult(); Assert.AreNotEqual(resultKinds, null); Assert.AreEqual(kinds.Count, resultKinds.Count); mockKindRepository.Verify(mock => mock.GetAll(), Times.Once()); } [TestMethod] public void GetById_ValidId_KindElement() { int validId = 1; var kind = new Kind { KindId = 1, Type = "Product" }; var mockKindRepository = new Mock<IRepository<Kind>>(); mockKindRepository.Setup(repo => repo.GetById(It.IsAny<int>())) .Returns((int id) => { if (id == validId) { return new SuccessResult<Kind>(kind); } return new NoneResult<Kind>(); }); var kindService = new KindService(mockKindRepository.Object); var resultKind = kindService.GetById(validId).GetSuccessResult(); Assert.AreNotEqual(resultKind, null); Assert.AreEqual(resultKind.KindId, validId); Assert.AreEqual(resultKind.Type, kind.Type); mockKindRepository.Verify(mock => mock.GetById(validId), Times.Once()); } [TestMethod] [ExpectedException(typeof(InvalidIdException))] public void GetById_InvalidId_Throws() { int invalidId = 0; var mockKindRepository = new Mock<IRepository<Kind>>(); mockKindRepository.Setup(repo => repo.GetById(It.IsAny<int>())); var kindService = new KindService(mockKindRepository.Object); var resultKind = kindService.GetById(invalidId); mockKindRepository.Verify(mock => mock.GetById(invalidId), Times.Once()); } [TestMethod] public void Save_ValidKindObj_ObjSaved() { var kinds = new List<Kind>(); var kind = new Kind { KindId = 1, Type = "Product" }; var mockKindRepository = new Mock<IRepository<Kind>>(); mockKindRepository.Setup(repo => repo.Save(It.IsAny<Kind>())) .Callback((Kind value) => kinds.Add(value)); var kindService = new KindService(mockKindRepository.Object); kindService.Save(kind); Assert.AreEqual(kinds.Count, 1); Assert.IsTrue(kinds.Contains(kind)); mockKindRepository.Verify(mock => mock.Save(kind), Times.Once()); } [TestMethod] [ExpectedException(typeof(NullReferenceException))] public void Save_Null_Throws() { Kind invalidObj = null; var mockKindRepository = new Mock<IRepository<Kind>>(); mockKindRepository.Setup(repo => repo.Save(It.IsAny<Kind>())); var kindProvider = new KindService(mockKindRepository.Object); kindProvider.Save(invalidObj); mockKindRepository.Verify(mock => mock.Save(invalidObj), Times.Once()); } [TestMethod] public void Delete_ValidId_ObjDeleted() { int validId = 1; var kinds = new List<Kind> { new Kind { KindId = 1, Type = "Product" }, new Kind { KindId = 2, Type = "MyType-2" } }; int countBeforeDelete = kinds.Count; var mockKindRepository = new Mock<IRepository<Kind>>(); mockKindRepository.Setup(repo => repo.Delete(It.IsAny<int>())) .Callback((int id) => { if (id == validId) { kinds.RemoveAll(kind => kind.KindId == id); } }); var kindProvider = new KindService(mockKindRepository.Object); kindProvider.Delete(validId); Assert.AreEqual(kinds.Count, countBeforeDelete - 1); Assert.IsFalse(kinds.Exists(kind => kind.KindId == validId)); mockKindRepository.Verify(mock => mock.Delete(validId), Times.Once()); } [TestMethod] [ExpectedException(typeof(InvalidIdException))] public void Delete_InvalidId_Throws() { int invalidId = 0; var mockKindRepository = new Mock<IRepository<Kind>>(); mockKindRepository.Setup(repo => repo.Delete(It.IsAny<int>())); var kindProvider = new KindService(mockKindRepository.Object); kindProvider.Delete(invalidId); mockKindRepository.Verify(mock => mock.Delete(invalidId), Times.Once()); } } }<file_sep>using Callboard.App.General.Cache.Main; using Callboard.App.General.Cache.Realizations; using Callboard.App.General.Loggers.Main; using Callboard.App.General.Loggers.Realizations; using StructureMap; namespace Callboard.App.General.DependencyResolution { public class GeneralRegistry : Registry { public GeneralRegistry() { Scan(scan => { scan.TheCallingAssembly(); scan.WithDefaultConventions(); }); For<ILoggerWrapper>().Singleton().Use<LoggerWrapper>(); For<ICacheStorage>().Singleton().Use<CacheStorage>(); } } } <file_sep>using Callboard.App.Business.Services; using Callboard.App.General.Entities; using Callboard.App.General.ResultExtensions; using Callboard.App.Web.Attributes; using Newtonsoft.Json; using System; using System.Net; using System.Web.Mvc; namespace Callboard.App.Web.Controllers { public class KindController : Controller { private IEntityService<Kind> _kindService; public KindController(IEntityService<Kind> kindService) { if (kindService == null) { throw new NullReferenceException(nameof(kindService)); } _kindService = kindService; } [AjaxOnly] public ActionResult GetKinds() { var kindsResult = _kindService.GetAll(); if (kindsResult.IsSuccess()) { var kinds = kindsResult.GetSuccessResult(); var kindsData = JsonConvert.SerializeObject(kinds); return Json(new { Kinds = kindsData }, JsonRequestBehavior.AllowGet); } return new HttpStatusCodeResult(HttpStatusCode.NotFound); } [Editor] public ActionResult GetKindEditList() { var kindsResult = _kindService.GetAll(); if (kindsResult.IsSuccess()) { var kinds = kindsResult.GetSuccessResult(); return PartialView("KindEditList", kinds); } return new HttpStatusCodeResult(HttpStatusCode.NotFound); } [Editor] [AjaxOnly] [HttpPost] public ActionResult SaveKind(string kindData) { kindData = kindData ?? string.Empty; var kind = JsonConvert.DeserializeObject<Kind>(kindData); if (kind != null) { var kindSaveResult = _kindService.Save(kind); if (kindSaveResult.IsNone()) { return new HttpStatusCodeResult(HttpStatusCode.OK); } } return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } [Editor] [AjaxOnly] [HttpPost] public ActionResult DeleteKind(int kindId) { var kindDeleteResult = _kindService.Delete(kindId); if (kindDeleteResult.IsNone()) { return new HttpStatusCodeResult(HttpStatusCode.OK); } return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } } }<file_sep>namespace Callboard.App.General.Loggers.Main { public interface ILoggerWrapper { void DebugFormat(string message, params object[] values); void InfoFormat(string message, params object[] values); void WarnFormat(string message, params object[] values); void ErrorFormat(string message, params object[] values); void FatalFormat(string message, params object[] values); } } <file_sep>using Callboard.App.Business.Services; using Callboard.App.Data.DataContext; using Callboard.App.Data.DbContext; using Callboard.App.Data.Repositories; using Callboard.App.Data.ServiceContext; using Callboard.App.General.Cache.Main; using Callboard.App.General.Entities; using Callboard.App.General.Loggers.Main; using StructureMap; using StructureMap.Graph; using Service = Callboard.App.Data.CommercialService; namespace Callboard.App.IoC.DependencyResolution { public static class ContainerBootstrap { private static IContainer _container; public static void Initialize() { _container = new Container( x => x.Scan ( scan => { AddDataDependency(scan); AddBusinessDependency(scan); AddGeneralDependency(scan); scan.LookForRegistries(); } ) ); } private static void AddGeneralDependency(IAssemblyScanner scan) { scan.AssemblyContainingType<ILoggerWrapper>(); scan.AssemblyContainingType<ICacheStorage>(); } private static void AddBusinessDependency(IAssemblyScanner scan) { scan.AssemblyContainingType<ILogginService>(); scan.AssemblyContainingType<IAdDetailsService>(); scan.AssemblyContainingType<IAdService>(); scan.AssemblyContainingType<ICategoryService>(); scan.AssemblyContainingType<IAreaService>(); scan.AssemblyContainingType<ICityService>(); scan.AssemblyContainingType<IRoleService>(); scan.AssemblyContainingType<IMembershipService>(); scan.AssemblyContainingType<ICommercialService>(); scan.AssemblyContainingType<IEntityService<User>>(); scan.AssemblyContainingType<IEntityService<Country>>(); scan.AssemblyContainingType<IEntityService<Kind>>(); scan.AssemblyContainingType<IEntityService<State>>(); } private static void AddDataDependency(IAssemblyScanner scan) { scan.AssemblyContainingType<IDbContext>(); scan.AssemblyContainingType<IServiceContext<Service::ICommercialContract>>(); scan.AssemblyContainingType<IRepository<Kind>>(); scan.AssemblyContainingType<IRepository<State>>(); scan.AssemblyContainingType<IRepository<Country>>(); scan.AssemblyContainingType<IRepository<User>>(); scan.AssemblyContainingType<ICategoryRepository>(); scan.AssemblyContainingType<IRoleRepository>(); scan.AssemblyContainingType<Data.Services.IAreaService>(); scan.AssemblyContainingType<Data.Services.ICityService>(); scan.AssemblyContainingType<Data.Services.IAdDetailsService>(); scan.AssemblyContainingType<Data.Services.IAdService>(); scan.AssemblyContainingType<Data.Services.ICommercialService>(); scan.AssemblyContainingType<Data.Services.IMembershipService>(); scan.AssemblyContainingType<IAdContext>(); scan.AssemblyContainingType<IAdDetailsContext>(); scan.AssemblyContainingType<ICategoryContext>(); scan.AssemblyContainingType<IAreaContext>(); scan.AssemblyContainingType<ICityContext>(); scan.AssemblyContainingType<IMembershipContext>(); scan.AssemblyContainingType<IRoleContext>(); scan.AssemblyContainingType<ICommercialContext>(); scan.AssemblyContainingType<IDataContext<Country>>(); scan.AssemblyContainingType<IDataContext<Kind>>(); scan.AssemblyContainingType<IDataContext<State>>(); scan.AssemblyContainingType<IDataContext<User>>(); } public static IContainer Container { get { return _container; } } } } <file_sep>using Callboard.App.General.Cache.Main; using Callboard.App.General.Entities.Commercial; using Callboard.App.General.ResultExtensions; using Callboard.App.General.Results; using Callboard.App.General.Results.Realizations; using System; using System.Collections.Generic; using Data = Callboard.App.Data.Services; namespace Callboard.App.Business.Services.Realizations { internal class CommercialService : ICommercialService { private Data::ICommercialService _commercialProvider; private ICacheStorage _cacheStorage; private const string CACHE_KEY = "commercials"; private const int CACHE_MINUTES = 15; public CommercialService(ICacheStorage cacheStorage, Data::ICommercialService commercialProvider) { _commercialProvider = commercialProvider ?? throw new NullReferenceException(nameof(commercialProvider)); _cacheStorage = cacheStorage ?? throw new NullReferenceException(nameof(cacheStorage)); } public IResult<IReadOnlyCollection<Commercial>> GetCommercials() { IReadOnlyCollection<Commercial> commercials = _cacheStorage.Get<IReadOnlyCollection<Commercial>>(CACHE_KEY); if (commercials == null) { var commercialResult = _commercialProvider.GetCommercials(); if (commercialResult.IsSuccess()) { commercials = commercialResult.GetSuccessResult(); _cacheStorage.Add(CACHE_KEY, commercials, CACHE_MINUTES); } else { return new NoneResult<IReadOnlyCollection<Commercial>>(); } } return new SuccessResult<IReadOnlyCollection<Commercial>>(commercials); } } }<file_sep>using System.ServiceModel; namespace Callboard.Service.Commercial { [ServiceContract] public interface ICommercialContract { [OperationContract] [FaultContract(typeof(CommercialNotFound))] Commercial[] GetCommercials(); } } <file_sep>using System.Collections.Generic; using System.Data; namespace Callboard.App.Data.DbContext { public interface IDbContext { string ConnectionString { get; set; } DataSet ExecuteProcedure(string procedureName, IDictionary<string, object> values = null); void ExecuteNonQuery(string procedureName, IDictionary<string, object> values = null); } }<file_sep>namespace Callboard.App.General.Entities { public class State { public int StateId { get; set; } public string Condition { get; set; } } }<file_sep>using Callboard.App.Business.Services; using Callboard.App.General.Entities; using Callboard.App.General.ResultExtensions; using Callboard.App.Web.Attributes; using Newtonsoft.Json; using System; using System.Net; using System.Web.Mvc; namespace Callboard.App.Web.Controllers { public class CountryController : Controller { private IEntityService<Country> _countryService; public CountryController(IEntityService<Country> countryService) { if (countryService == null) { throw new NullReferenceException(nameof(countryService)); } _countryService = countryService; } [AjaxOnly] public ActionResult GetCountries() { var countriesResult = _countryService.GetAll(); if (countriesResult.IsSuccess()) { var countries = countriesResult.GetSuccessResult(); var countriesData = JsonConvert.SerializeObject(countries); return Json(new { Countries = countriesData }, JsonRequestBehavior.AllowGet); } return new HttpStatusCodeResult(HttpStatusCode.NotFound); } [Editor] public ActionResult GetCountryEditList() { var countriesResult = _countryService.GetAll(); if (countriesResult.IsSuccess()) { var countries = countriesResult.GetSuccessResult(); return PartialView("CountryEditList", countries); } return new HttpStatusCodeResult(HttpStatusCode.NotFound); } [Editor] [AjaxOnly] [HttpPost] public ActionResult SaveCountry(string countryData) { countryData = countryData ?? string.Empty; var country = JsonConvert.DeserializeObject<Country>(countryData); if (country != null) { var countrySaveResult = _countryService.Save(country); if (countrySaveResult.IsNone()) { return new HttpStatusCodeResult(HttpStatusCode.OK); } } return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } [Editor] [AjaxOnly] [HttpPost] public ActionResult DeleteCountry(int countryId) { var countryDeleteResult = _countryService.Delete(countryId); if (countryDeleteResult.IsNone()) { return new HttpStatusCodeResult(HttpStatusCode.OK); } return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } } }<file_sep>using Callboard.App.Data.DataContext; using Callboard.App.General.Entities; using Callboard.App.General.Results; using System; using System.Collections.Generic; namespace Callboard.App.Data.Services.Realizations { internal class CityService : ICityService { private ICityContext _context; public CityService(ICityContext context) { _context = context ?? throw new NullReferenceException(nameof(context)); } public IResult<City> Delete(int id) { return _context.Delete(id); } public IResult<IReadOnlyCollection<City>> GetAll() { return _context.GetAll(); } public IResult<City> GetById(int id) { return _context.GetById(id); } public IResult<IReadOnlyCollection<City>> GetCitiesByAreaId(int areaId) { return _context.GetCitiesByAreaId(areaId); } public IResult<City> Save(int areaId, City obj) { return _context.Save(areaId, obj); } } }<file_sep>using Callboard.App.Business.Services; using Callboard.App.General.Entities; using Callboard.App.General.ResultExtensions; using Callboard.App.Web.Attributes; using Callboard.App.Web.Models; using System; using System.Collections.Generic; using System.Net; using System.Web.Mvc; namespace Callboard.App.Web.Controllers { public class AdController : Controller { private IAdService _adProvider; public AdController(IAdService adProvider) { if (adProvider == null) { throw new NullReferenceException(nameof(adProvider)); } _adProvider = adProvider; } public ActionResult GetAdList() { IReadOnlyCollection<Ad> ads = new List<Ad>(); var adsResult = _adProvider.GetAds(); if (adsResult.IsSuccess()) { ads = adsResult.GetSuccessResult(); } AdListViewModel model = new AdListViewModel { Ads = ads }; return View("AdList", model); } public ActionResult GetAdsByCategoryId(int categoryId) { IReadOnlyCollection<Ad> ads = new List<Ad>(); var adsResult = _adProvider.GetAdsByCategoryId(categoryId); if (adsResult.IsSuccess()) { ads = adsResult.GetSuccessResult(); } AdListViewModel model = new AdListViewModel { Ads = ads }; return View("AdList", model); } [User] public PartialViewResult GetAdsForUser(int userId) { IReadOnlyCollection<Ad> ads = new List<Ad>(); var adsResult = _adProvider.GetAdsForUser(userId); if (adsResult.IsSuccess()) { ads = adsResult.GetSuccessResult(); } return PartialView("Partial\\AdContainer", ads); } [User] public ActionResult DeleteAd(int adId, string returnUrl) { var adsResult = _adProvider.Delete(adId); if (adsResult.IsNone()) { return RedirectToAction("GetAdList", "Ad"); } return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } } }<file_sep>namespace Callboard.App.General.Cache.Main { public interface ICacheStorage { bool Add<T>(string key, T obj, int minutes) where T : class; T Get<T>(string key) where T : class; void Update<T>(string key, T obj, int minutes) where T : class; void Delete(string key); } } <file_sep>using Callboard.App.General.Entities; using Callboard.App.General.Results; namespace Callboard.App.Data.Services { public interface IAdDetailsService { IResult<AdDetails> GetById(int id); IResult<AdDetails> Save(AdDetails adDetails); } }<file_sep>using Callboard.App.General.Entities.Auth; using Callboard.App.General.Results; namespace Callboard.App.Data.Services { public interface IMembershipService { IResult<MembershipUser> ValidateUser(string login, string password); IResult<MembershipUser> GetUserByLogin(string login); IResult<MembershipUser> CreateUser(string login, string password); } }<file_sep>using Callboard.App.Data.ServiceContext; using Callboard.App.General.Entities.Commercial; using Callboard.App.General.Results; using Callboard.App.General.Results.Realizations; using System.Collections.Generic; using System.Linq; using Service = Callboard.App.Data.CommercialService; namespace Callboard.App.Data.DataContext.Realizations.Service { internal class CommercialServiceContext : EntityServiceContext<Service::ICommercialContract>, ICommercialContext { public CommercialServiceContext(IServiceContext<Service::ICommercialContract> context) : base(context) { } public IResult<IReadOnlyCollection<Commercial>> GetCommercials() { IReadOnlyCollection<Commercial> commercials = null; IResult<IReadOnlyCollection<Commercial>> result = new NoneResult<IReadOnlyCollection<Commercial>>(); commercials = base.GetData("CommercialContractEndpoint", null, this.GetCommercials); if (commercials != null) { result = new SuccessResult<IReadOnlyCollection<Commercial>>(commercials); } return result; } private IReadOnlyCollection<Commercial> GetCommercials(Service::ICommercialContract contract) { return contract.GetCommercials()?.Select(MapCommercial).ToList(); } private Commercial MapCommercial(Service::Commercial commercial) { return new Commercial { Id = commercial.Id, Image = this.MapImage(commercial.Image) }; } private Image MapImage(Service::Image image) { return new Image { Data = image.Data, Extension = image.Extension }; } } }<file_sep>function updateKind(kindId, typeInputId) { let type = $("#" + typeInputId).val(); if (kindId && type) { let kind = { KindId: kindId, Type: type }; $.post('/Kind/SaveKind', { kindData: JSON.stringify(kind) }); } }<file_sep>using Callboard.App.General.Entities; using Callboard.App.General.Results; using System.Collections.Generic; namespace Callboard.App.Data.Repositories { public interface ICategoryRepository : IRepository<Category> { IResult<IReadOnlyCollection<Category>> GetSubcategories(int categoryId); IResult<IReadOnlyCollection<Category>> GetMainCategories(); } }<file_sep>using Callboard.App.Data.DataContext; using Callboard.App.General.Entities.Commercial; using Callboard.App.General.Results; using System; using System.Collections.Generic; namespace Callboard.App.Data.Services.Realizations { internal class CommercialService : ICommercialService { private ICommercialContext _context; public CommercialService(ICommercialContext context) { _context = context ?? throw new NullReferenceException(nameof(context)); } public IResult<IReadOnlyCollection<Commercial>> GetCommercials() { return _context.GetCommercials(); } } }<file_sep>using Callboard.App.General.Entities; using Callboard.App.General.Results; using System.Collections.Generic; namespace Callboard.App.Business.Services { public interface IAreaService { IResult<IReadOnlyCollection<Area>> GetAll(); IResult<Area> GetById(int id); IResult<Area> Save(int countryId, Area obj); IResult<Area> Delete(int id); IResult<IReadOnlyCollection<Area>> GetAreasByCountryId(int countryId); } }<file_sep>function saveUser() { let userModel = getUserModel(); if (userModel.isValid) { $.post('/User/SaveUser', { userData: JSON.stringify(userModel.user) }, showUserSaveResult); } } let showUserSaveResult = function (data) { let saveResultContainer = $("#save-result"); saveResultContainer.removeClass('none'); setTimeout(function () { saveResultContainer.addClass('none'); }, 4000); } function fillPhoto(evt) { let tgt = evt.target || window.event.srcElement; let files = tgt.files; if (FileReader && files && files.length) { var fileReader = new FileReader(); fileReader.onload = function () { let img = $("#photo"); img.attr('src', fileReader.result); } fileReader.readAsDataURL(files[0]); } } let getUserModel = function () { let userId = $("#userId").val(); let name = $("#name").val(); let phonesModel = getPhonesModel(); let mailsModel = getMailsModel(); let photo = getPhoto(); return { user: { UserId: userId, Name: name, PhotoData: photo.photoData, PhotoExtension: photo.extension, Phones: phonesModel.phones, Mails: mailsModel.mails }, isValid: userId && name && phonesModel.isPhoneValid && mailsModel.isMailsValid }; } let getPhoto = function () { let extension = null; let photoBuffer = null; let photoData = $("#photo").attr('src').split(";"); if (photoData.length > 1) { extension = photoData[0].split(":")[1].split("/")[1]; photoBuffer = convertBase64ToByte(photoData[1].split(",")[1]); } return { extension: extension, photoData: photoBuffer }; } let getPhonesModel = function () { let phones = []; let isPhoneValid = true; $("#phones").find("input:text").each(function () { let phoneId = $(this).data('phoneId'); let number = $(this).val(); if (typeof phoneId === 'undefined') { phoneId = 0; } if (isNumberValid(number)) { let phone = { PhoneId: phoneId, Number: number }; phones.push(phone); $(this).removeClass('invalid__field'); } else { $(this).addClass('invalid__field'); isPhoneValid = false; } }); return { phones: phones, isPhoneValid: isPhoneValid }; } let getMailsModel = function () { let mails = []; let isMailsValid = true; $("#emails").find("input:text").each(function () { let mailId = $(this).data('mailId'); let email = $(this).val(); if (typeof mailId === 'undefined') { mailId = 0; } if (isEmailValid(email)) { let mail = { MailId: mailId, Email: email }; mails.push(mail); $(this).removeClass('invalid__field'); } else { $(this).addClass('invalid__field'); isMailsValid = false; } }); return { mails: mails, isMailsValid: isMailsValid }; } let isNumberValid = function (number) { let phoneRegex = /([0-9]{10})|(\([0-9]{3}\)\s+[0-9]{3}\-[0-9]{4})/; return phoneRegex.test(number); } let isEmailValid = function (email) { let emailRegex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/; return emailRegex.test(email); }<file_sep>namespace Callboard.App.General.Results { public interface IResult<T> { } }<file_sep>namespace Callboard.App.General.Results { public interface INoneResult<T> : IResult<T> { } }<file_sep>using Callboard.App.General.Loggers.Main; using System; using System.Web.Mvc; namespace Callboard.App.Web.Controllers { public class ErrorController : Controller { private ILoggerWrapper _logger; public ErrorController(ILoggerWrapper logger) { if (logger == null) { throw new NullReferenceException(nameof(logger)); } _logger = logger; } public ActionResult Index(string errorMessage) { _logger?.ErrorFormat(errorMessage); return View("Error"); } public ActionResult BadRequest() { Response.StatusCode = 400; return View("BadRequest"); } public ActionResult PageNotFound() { Response.StatusCode = 404; return View("NotFoundPage"); } public ActionResult ServerNotResponding() { Response.StatusCode = 500; return View("ServerNotRespondingPage"); } } }<file_sep>using Callboard.App.Business.Services; using Callboard.App.General.Entities; using Callboard.App.General.Entities.Data; using Callboard.App.General.ResultExtensions; using Callboard.App.General.Results; using Callboard.App.Web.Models; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Web.Mvc; namespace Callboard.App.Web.Controllers { public class SearchController : Controller { private IAdService _adProvider; public SearchController(IAdService adProvider) { if (adProvider == null) { throw new NullReferenceException(nameof(adProvider)); } _adProvider = adProvider; } public ActionResult SearchAdsByName(string name) { IReadOnlyCollection<Ad> ads = new List<Ad>(); var adsResult = _adProvider.SearchByName(name); if (adsResult.IsSuccess()) { ads = adsResult.GetSuccessResult(); } SearchViewModel model = new SearchViewModel { Ads = ads, SearchConfiguration = new SearchConfiguration() }; return View("Search", model); } public ActionResult Search() { IReadOnlyCollection<Ad> ads = new List<Ad>(); var adsResult = _adProvider.GetAds(); if (adsResult.IsSuccess()) { ads = adsResult.GetSuccessResult(); } var model = new SearchViewModel { Ads = ads, SearchConfiguration = new SearchConfiguration() }; return View(model); } public ActionResult SearchAds(string searchConfigurationData) { IReadOnlyCollection<Ad> ads = new List<Ad>(); IResult<IReadOnlyCollection<Ad>> adsResult = null; searchConfigurationData = searchConfigurationData ?? string.Empty; var searchConfiguration = JsonConvert.DeserializeObject<SearchConfiguration>(searchConfigurationData); if (searchConfiguration == null) { adsResult = _adProvider.GetAds(); } else { adsResult = _adProvider.Search(searchConfiguration); } if (adsResult.IsSuccess()) { ads = adsResult.GetSuccessResult(); } return PartialView("Partial\\AdContainer", ads); } } }<file_sep>using Callboard.App.Business.Services; using Callboard.App.General.Entities; using Callboard.App.General.Entities.Auth; using Callboard.App.General.ResultExtensions; using Callboard.App.Web.Attributes; using Callboard.App.Web.Models; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Web.Mvc; namespace Callboard.App.Web.Controllers { public class AdDetailsController : Controller { private IAdDetailsService _adDetailsProvider; public AdDetailsController(IAdDetailsService adDetailsProvider) { if (adDetailsProvider == null) { throw new NullReferenceException(nameof(adDetailsProvider)); } _adDetailsProvider = adDetailsProvider; } public ActionResult GetAdDetails(int adId) { var adDetailsResult = _adDetailsProvider.GetById(adId); if (adDetailsResult.IsSuccess()) { AdDetails model = adDetailsResult.GetSuccessResult(); return View("AdDetails", model); } return new HttpStatusCodeResult(HttpStatusCode.NotFound); } [User] public ActionResult CreateAdDetails() { var user = User as UserPrinciple; var adDetailsModel = new AdDetailsViewModel { UserId = user.UserId }; return View("EditAdDetails", adDetailsModel); } [User] public ActionResult EditAdDetails(int adId) { var adDetailsResult = _adDetailsProvider.GetById(adId); if (adDetailsResult.IsSuccess()) { var user = User as UserPrinciple; var adDetails = adDetailsResult.GetSuccessResult(); if (user.UserId == adDetails.User.UserId) { var adDetailsModel = this.MapAdDetailsToViewModel(adDetails); return View("EditAdDetails", adDetailsModel); } } return new HttpStatusCodeResult(HttpStatusCode.NotFound); } [User] [AjaxOnly] [HttpPost] public ActionResult SaveAdDetails(string adDetailsData) { adDetailsData = adDetailsData ?? string.Empty; var adDetailsModel = JsonConvert.DeserializeObject<AdDetailsViewModel>(adDetailsData); if (adDetailsModel != null) { var adDetails = this.MapViewModelToAdDetails(adDetailsModel); var adDetailsResult = _adDetailsProvider.Save(adDetails); if (adDetailsResult.IsNone()) { return new HttpStatusCodeResult(HttpStatusCode.OK); } } return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } private AdDetails MapViewModelToAdDetails(AdDetailsViewModel adDetailsModel) { return new AdDetails { AdId = adDetailsModel.AdId, Name = adDetailsModel.Name, State = adDetailsModel.State, Kind = adDetailsModel.Kind, Price = adDetailsModel.Price, Description = adDetailsModel.Description, Location = new Location { LocationId = adDetailsModel.Location.LocationId }, User = new User { UserId = adDetailsModel.UserId }, AddressLine = adDetailsModel.AddressLine, CreationDate = DateTime.Now, Categories = (IReadOnlyCollection<Category>)adDetailsModel.Categories, Images = (IReadOnlyCollection<Image>)adDetailsModel.Images }; } private AdDetailsViewModel MapAdDetailsToViewModel(AdDetails adDetails) { return new AdDetailsViewModel { AdId = adDetails.AdId, Name = adDetails.Name, State = adDetails.State, Kind = adDetails.Kind, Price = adDetails.Price, Description = adDetails.Description, Location = new Location { LocationId = adDetails.Location.LocationId, Country = adDetails.Location.Country, Area = adDetails.Location.Area, City = adDetails.Location.City }, UserId = adDetails.User.UserId, AddressLine = adDetails.AddressLine, Categories = adDetails.Categories.ToArray(), Images = adDetails.Images.ToArray() }; } } }<file_sep>using Callboard.App.Business.Services; using Callboard.App.General.ResultExtensions; using Callboard.App.Web.Attributes; using Callboard.App.Web.Models; using System; using System.Web.Mvc; namespace Callboard.App.Web.Controllers { public class MembershipController : Controller { private IMembershipService _membershipProvider; public MembershipController(IMembershipService membershipProvider) { if (membershipProvider == null) { throw new NullReferenceException(nameof(membershipProvider)); } _membershipProvider = membershipProvider; } [Admin] public ActionResult CreateUser(string returnUrl) { ViewBag.ReturnUrl = returnUrl; return View(new RegisterViewModel()); } [Admin] [HttpPost] public ActionResult CreateUser(RegisterViewModel registerModel, string returnUrl) { if (!ModelState.IsValid) { return RedirectToAction("CreateUser", registerModel); } var membershipResult = _membershipProvider.CreateUser(registerModel.Login, registerModel.Password); if (membershipResult.IsFailure()) { ViewBag.ErrorMessage = membershipResult.GetFailureMessage(); return View(registerModel); } return RedirectToAction("GetAllUsers", "User"); } } }<file_sep>using System; namespace Callboard.App.General.Results.Realizations { public class FailureResult<T> : IFailureResult<T> { public FailureResult(Exception exception) :this(exception, "") { } public FailureResult(Exception exception, string errorMessage) { this.Exception = exception; this.ErrorMessage = errorMessage; } public Exception Exception { get; private set; } public string ErrorMessage { get; private set; } } }<file_sep>using Callboard.App.Data.DataContext; using Callboard.App.General.Entities; using Callboard.App.General.Results; using System; using System.Collections.Generic; namespace Callboard.App.Data.Repositories.Realizations { internal class StateRepository : IRepository<State> { private IDataContext<State> _context; public StateRepository(IDataContext<State> context) { _context = context ?? throw new NullReferenceException(nameof(context)); } public IResult<State> Delete(int id) { return _context.Delete(id); } public IResult<IReadOnlyCollection<State>> GetAll() { return _context.GetAll(); } public IResult<State> GetById(int id) { return _context.GetById(id); } public IResult<State> Save(State obj) { return _context.Save(obj); } } }<file_sep>using Callboard.App.General.Entities.Auth; using Newtonsoft.Json; using System; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using System.Web.Security; using Auth = Callboard.App.General.Entities.Auth; namespace Callboard.App.Web { public class MvcApplication : HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } protected void Application_PostAuthenticateRequest(object sender, EventArgs arg) { var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; if (cookie != null) { var ticket = FormsAuthentication.Decrypt(cookie.Value); var user = JsonConvert.DeserializeObject<Auth::MembershipUser>(ticket.UserData); var userPrinciple = new UserPrinciple(user.Name) { UserId = user.UserId, Name = user.Name, Roles = user.Roles.Select(x => x.Name).ToArray() }; HttpContext.Current.User = userPrinciple; } } protected void Application_Error(object sender, EventArgs e) { Exception exception = Server.GetLastError(); Response.Clear(); if (exception != null) { Server.ClearError(); Response.Redirect($"~/Error/Index/?errorMessage={ exception.Message.Replace('\n', ' ') }"); } } } } <file_sep>using StructureMap; using StructureMap.Graph; using StructureMap.Graph.Scanning; using StructureMap.Pipeline; using StructureMap.TypeRules; using System; using System.Web.Mvc; namespace Callboard.App.Web.DependencyResolution { public class ControllerConvention : IRegistrationConvention { #region Public Methods and Operators public void Process(Type type, Registry registry) { if (type.CanBeCastTo<Controller>() && !type.IsAbstract) { registry.For(type).LifecycleIs(new UniquePerRequestLifecycle()); } } public void ScanTypes(TypeSet types, Registry registry) { throw new NotImplementedException(); } #endregion } }<file_sep>using Callboard.App.Data.DbContext; using Callboard.App.Data.Mappers; using Callboard.App.General.Entities; using Callboard.App.General.Loggers.Main; using Callboard.App.General.Results; using Microsoft.SqlServer.Server; using System; using System.Collections.Generic; using System.Data; using System.Linq; namespace Callboard.App.Data.DataContext.Realizations.Db { internal class AdDetailsDbContext : EntityDbContext<AdDetails>, IAdDetailsContext { public AdDetailsDbContext(IDbContext context, ILoggerWrapper logger) : base(context, logger) { } public IResult<AdDetails> GetById(int id) { var procedureName = "sp_get_addetails_by_adid"; var values = new Dictionary<string, object> { { "AdId", id } }; var mapper = new Mapper<DataSet, AdDetails> { MapItem = MapAdDetails }; return base.Get(procedureName, mapper, values); } public IResult<AdDetails> Save(AdDetails adDetails) { var procedureName = "sp_save_addetails"; var mapper = new Mapper<DataSet, AdDetails> { MapValues = this.MapAdDetailsToValues }; return base.Save(adDetails, procedureName, mapper); } private IDictionary<string, object> MapAdDetailsToValues(AdDetails adDetails) { return new Dictionary<string, object> { { "AdId", adDetails.AdId }, { "UserId", adDetails.User.UserId }, { "LocationId", adDetails.Location.LocationId }, { "Name", adDetails.Name }, { "State", adDetails.State }, { "Kind", adDetails.Kind }, { "Price", adDetails.Price }, { "CreationDate", adDetails.CreationDate }, { "AddressLine", adDetails.AddressLine }, { "Description", adDetails.Description }, { "Images", this.GetImageRecords(adDetails.Images) }, { "Categories", this.GetCategoriesRecords(adDetails.Categories) } }; } private IReadOnlyCollection<SqlDataRecord> GetImageRecords(IReadOnlyCollection<Image> images) { if (images == null || images?.Count < 1) { return null; } var records = new List<SqlDataRecord>(); var metadata = new SqlMetaData[] { new SqlMetaData("ImageId", SqlDbType.Int), new SqlMetaData("Data", SqlDbType.VarBinary, -1), new SqlMetaData("Extension", SqlDbType.NVarChar, 50), }; foreach (var item in images) { SqlDataRecord record = new SqlDataRecord(metadata); record.SetValue(0, item.ImageId); record.SetValue(1, item.Data); record.SetString(2, item.Extension); records.Add(record); } return records; } private IReadOnlyCollection<SqlDataRecord> GetCategoriesRecords(IReadOnlyCollection<Category> categories) { if (categories == null || categories?.Count < 1) { return null; } var records = new List<SqlDataRecord>(); var metadata = new SqlMetaData[] { new SqlMetaData("CategoryId", SqlDbType.Int) }; foreach (var item in categories) { SqlDataRecord record = new SqlDataRecord(metadata); record.SetValue(0, item.CategoryId); records.Add(record); } return records; } private AdDetails MapAdDetails(DataSet dataSet) { return dataSet.Tables[0].AsEnumerable().Select(adDetails => { var categories = dataSet.Tables[1]; var images = dataSet.Tables[2]; var user = dataSet.Tables[3]; var mails = dataSet.Tables[4]; var phones = dataSet.Tables[5]; return MapAdDetails(adDetails, categories, images, user, mails, phones); }).First(); } private AdDetails MapAdDetails(DataRow row, DataTable categories, DataTable images, DataTable users, DataTable mails, DataTable phones) { int adId = row.Field<int>("AdId"); int userId = row.Field<int>("UserId"); return new AdDetails { AdId = adId, Kind = row.Field<string>("Kind"), State = row.Field<string>("State"), Name = row.Field<string>("Name"), Price = row.Field<decimal>("Price"), CreationDate = row.Field<DateTime>("CreationDate"), AddressLine = row.Field<string>("AddressLine"), Description = row.Field<string>("Description"), Location = new Location { LocationId = row.Field<int>("LocationId"), City = row.Field<string>("City"), Area = row.Field<string>("Area"), Country = row.Field<string>("Country") }, Categories = this.MapCategories(categories, adId), Images = this.MapImages(images, adId), User = this.MapUser(users, mails, phones, userId) }; } private User MapUser(DataTable users, DataTable mails, DataTable phones, int userId) { return users.AsEnumerable().Where(user => user.Field<int>("UserId") == userId) .Select(user => { return new User { UserId = userId, Name = user.Field<string>("Name"), PhotoData = user.Field<byte[]>("PhotoData"), PhotoExtension = user.Field<string>("PhotoExtension"), Mails = this.MapMailCollection(mails, userId), Phones = this.MapPhoneCollection(phones, userId) }; }).FirstOrDefault(); } private IReadOnlyCollection<Phone> MapPhoneCollection(DataTable phones, int userId) { return phones.AsEnumerable() .Where(phone => phone.Field<int>("UserId") == userId) .Select(phone => { return new Phone { PhoneId = phone.Field<int>("PhoneId"), Number = phone.Field<string>("Number") }; }).ToList(); } private IReadOnlyCollection<Mail> MapMailCollection(DataTable mails, int userId) { return mails.AsEnumerable() .Where(mail => mail.Field<int>("UserId") == userId) .Select(mail => { return new Mail { MailId = mail.Field<int>("MailId"), Email = mail.Field<string>("Email") }; }).ToList(); } private IReadOnlyCollection<Image> MapImages(DataTable imagesTable, int adId) { return imagesTable.AsEnumerable() .Where(x => x.Field<int>("AdId") == adId) .Select(this.MapImage).ToList(); } private IReadOnlyCollection<Category> MapCategories(DataTable categoriesTable, int adId) { return categoriesTable.AsEnumerable() .Where(x => x.Field<int>("AdId") == adId) .Select(this.MapCategory).ToList(); } private Category MapCategory(DataRow row) { return new Category { CategoryId = row.Field<int>("CategoryId"), Name = row.Field<string>("Name"), ParentId = row.Field<int?>("ParentId") ?? default(int) }; } private Image MapImage(DataRow row) { return new Image { ImageId = row.Field<int>("ImageId"), Data = row.Field<byte[]>("Data"), Extension = row.Field<string>("Extension") }; } } }<file_sep>using Callboard.App.General.Entities; using Callboard.App.General.Results; using System.Collections.Generic; namespace Callboard.App.Data.Repositories { public interface IRoleRepository : IRepository<Role> { IResult<IReadOnlyCollection<Role>> GetRolesForUser(int userId); IResult<Role> SetRoleForUser(int userId, int roleId); IResult<Role> DeleteUserRole(int userId, int roleId); } }<file_sep>function fillCities(areaId) { getDataAsync({ areaId: areaId }, "/City/GetCitiesByAreaId", renderCities); } function clearCities() { let citiesContainer = getCitiesContainer(); citiesContainer.empty(); let defaultOption = createOption('cityId', 0, "--- Choose city ---"); citiesContainer.append(defaultOption); } let renderCities = function (data) { clearCities(); let citiesContainer = getCitiesContainer(); let cities = JSON.parse(data.Cities); for (let i = 0; i < cities.length; i++) { let option = createOption('cityId', cities[i].CityId, cities[i].Name); citiesContainer.append(option); } } let getCitiesContainer = function () { return $('#cities'); }<file_sep>using Callboard.App.General.Entities; using Callboard.App.General.Results; namespace Callboard.App.Business.Services { public interface IAdDetailsService { IResult<AdDetails> GetById(int id); IResult<AdDetails> Save(AdDetails obj); } }<file_sep>using Callboard.App.General.Entities.Commercial; using Callboard.App.General.Results; using System.Collections.Generic; namespace Callboard.App.Data.DataContext { public interface ICommercialContext { IResult<IReadOnlyCollection<Commercial>> GetCommercials(); } }<file_sep>using Callboard.App.Data.ServiceContext; using Callboard.App.General.Helpers; using System; using System.ServiceModel; namespace Callboard.App.Data.DataContext.Realizations.Service { internal class EntityServiceContext<T> { private IServiceContext<T> _context; public EntityServiceContext(IServiceContext<T> context) { _context = context ?? throw new NullReferenceException(nameof(context)); } public TOut GetData<TOut>(string endpointConfigurationName, EndpointAddress remoteAddress, Func<T, TOut> getData) { var configuration = ConfigurationHelper.GetExecutingAssemblyConfig(this); var commercials = _context.GetData(endpointConfigurationName, configuration, remoteAddress, getData); return commercials; } } }<file_sep>function saveCountry(countryNameInputId, countriesContainerId) { let countryNameInput = $("#" + countryNameInputId); let countryName = countryNameInput.val(); if (countryName) { countryNameInput.removeClass('invalid__field'); let country = { CountryId: 0, Name: countryName }; $.post('/Country/SaveCountry', { countryData: JSON.stringify(country) }, function () { getCountryList(countriesContainerId); }); } else { countryNameInput.addClass('invalid__field'); } }<file_sep>using Callboard.App.General.Results; using System.Collections.Generic; namespace Callboard.App.Data.DataContext { public interface IDataContext<T> { IResult<IReadOnlyCollection<T>> GetAll(); IResult<T> GetById(int id); IResult<T> Save(T obj); IResult<T> Delete(int id); } }<file_sep>using Callboard.App.Data.Repositories; using Callboard.App.General.Entities; using Callboard.App.General.Exceptions; using Callboard.App.General.Results; using System; using System.Collections.Generic; namespace Callboard.App.Business.Services.Realizations { internal class RoleService : IRoleService { private IRoleRepository _roleRepository; public RoleService(IRoleRepository roleRepository) { _roleRepository = roleRepository ?? throw new NullReferenceException(nameof(roleRepository)); } public IResult<Role> Delete(int id) { this.CheckId(id); return _roleRepository.Delete(id); } public IResult<Role> DeleteUserRole(int userId, int roleId) { this.CheckId(userId); this.CheckId(roleId); return _roleRepository.DeleteUserRole(userId, roleId); } public IResult<IReadOnlyCollection<Role>> GetAll() { return _roleRepository.GetAll(); } public IResult<Role> GetById(int id) { this.CheckId(id); return _roleRepository.GetById(id); } public IResult<IReadOnlyCollection<Role>> GetRolesForUser(int userId) { this.CheckId(userId); return _roleRepository.GetRolesForUser(userId); } public IResult<Role> Save(Role obj) { obj = obj ?? throw new NullReferenceException(nameof(obj)); return _roleRepository.Save(obj); } public IResult<Role> SetRoleForUser(int userId, int roleId) { this.CheckId(userId); this.CheckId(roleId); return _roleRepository.SetRoleForUser(userId, roleId); } private void CheckId(int id) { if (id < 1) { throw new InvalidIdException(nameof(id)); } } } }<file_sep>using Callboard.App.General.Helpers; using Callboard.App.General.Loggers.Main; using System; using System.Configuration; namespace Callboard.App.Data.Helpers { internal class ConfigHelper { private const string DB_NAME = "callboardDB"; private ILoggerWrapper _logger; public ConfigHelper(ILoggerWrapper logger) { _logger = logger ?? throw new NullReferenceException(nameof(logger)); } public string ConnectionString { get => GetConnectionString(); } private string GetConnectionString() { var configuration = ConfigurationHelper.GetExecutingAssemblyConfig(this); var connStringsSection = configuration.ConnectionStrings; string connectionString = null; try { connectionString = connStringsSection?.ConnectionStrings[DB_NAME]?.ConnectionString; if (string.IsNullOrEmpty(connectionString)) { throw new NullReferenceException($"Cannot find connection string with name { DB_NAME } in App.Data.dll.config"); } } catch (ConfigurationErrorsException ex) { _logger.ErrorFormat($"{ ex.Message }"); } return connectionString; } } }<file_sep>using System; using System.Configuration; namespace Callboard.App.General.Helpers { public static class ConfigurationHelper { public static Configuration GetExecutingAssemblyConfig<T>(T obj) { var dllPath = new Uri(obj.GetType().Assembly.GetName().CodeBase).LocalPath; return ConfigurationManager.OpenExeConfiguration(dllPath); } } }<file_sep>using Callboard.App.General.Entities; using Callboard.App.General.Exceptions; using Callboard.App.General.Results; using System; using System.Collections.Generic; using Data = Callboard.App.Data.Services; namespace Callboard.App.Business.Services.Realizations { internal class AreaService : IAreaService { private Data::IAreaService _areaRepository; public AreaService(Data::IAreaService areaRepository) { _areaRepository = areaRepository ?? throw new NullReferenceException(nameof(areaRepository)); } public IResult<Area> Delete(int id) { this.CheckId(id); return _areaRepository.Delete(id); } public IResult<IReadOnlyCollection<Area>> GetAll() { return _areaRepository.GetAll(); } public IResult<IReadOnlyCollection<Area>> GetAreasByCountryId(int countryId) { this.CheckId(countryId); return _areaRepository.GetAreasByCountryId(countryId); } public IResult<Area> GetById(int id) { this.CheckId(id); return _areaRepository.GetById(id); } public IResult<Area> Save(int countryId, Area obj) { this.CheckId(countryId); obj = obj ?? throw new NullReferenceException(nameof(obj)); return _areaRepository.Save(countryId, obj); } private void CheckId(int id) { if (id < 1) { throw new InvalidIdException(nameof(id)); } } } }<file_sep>using Callboard.App.General.Entities; using Callboard.App.General.Results; using System.Collections.Generic; namespace Callboard.App.Data.DataContext { public interface IRoleContext : IDataContext<Role> { IResult<IReadOnlyCollection<Role>> GetRolesForUser(int userId); IResult<Role> SetRoleForUser(int userId, int roleId); IResult<Role> DeleteUserRole(int userId, int roleId); } }<file_sep>using System.Configuration; namespace Callboard.Service.Commercial.Config { [ConfigurationCollection(typeof(ImagePathElement), AddItemName = "imagePath")] public class ImagePathCollection : ConfigurationElementCollection { protected override ConfigurationElement CreateNewElement() { return new ImagePathElement(); } protected override object GetElementKey(ConfigurationElement element) { return ((ImagePathElement)(element)).Path; } public ImagePathElement this[int index] { get { return (ImagePathElement)BaseGet(index); } } } } <file_sep>using Callboard.App.General.Results; namespace Callboard.App.General.ResultExtensions { public static class CheckResultExtension { public static bool IsSuccess<T>(this IResult<T> result) { return result is ISuccessResult<T>; } public static bool IsFailure<T>(this IResult<T> result) { return result is IFailureResult<T>; } public static bool IsNone<T>(this IResult<T> result) { return result is INoneResult<T>; } } }<file_sep>using Callboard.App.Data.DataContext; using Callboard.App.General.Entities; using Callboard.App.General.Results; using System; using System.Collections.Generic; namespace Callboard.App.Data.Services.Realizations { internal class AreaService : IAreaService { private IAreaContext _context; public AreaService(IAreaContext context) { _context = context ?? throw new NullReferenceException(nameof(context)); } public IResult<Area> Delete(int id) { return _context.Delete(id); } public IResult<IReadOnlyCollection<Area>> GetAll() { return _context.GetAll(); } public IResult<IReadOnlyCollection<Area>> GetAreasByCountryId(int countryId) { return _context.GetAreasByCountryId(countryId); } public IResult<Area> GetById(int id) { return _context.GetById(id); } public IResult<Area> Save(int countryId, Area obj) { return _context.Save(countryId, obj); } } }<file_sep>using Callboard.App.Web.Attributes; using System.Web.Mvc; namespace Callboard.App.Web.Controllers { public class EditorController : Controller { [Editor] public ActionResult OpenEditorPage() { return View("EditorPage"); } } }<file_sep>function saveSubcategory(nameInputId, parentId, subcategoryContainerId) { let nameInput = $("#" + nameInputId); let categoryName = nameInput.val(); if (categoryName && parentId) { let category = { CategoryId: 0, Name: categoryName, ParentId: parentId }; $.post('/Category/SaveCategory', { categoryData: JSON.stringify(category) }, function () { getSubcategoryList(null, parentId, subcategoryContainerId); }); } }<file_sep>using Callboard.App.Data.DbContext; using Callboard.App.Data.Mappers; using Callboard.App.General.Entities; using Callboard.App.General.Loggers.Main; using Callboard.App.General.Results; using System.Collections.Generic; using System.Data; using System.Linq; namespace Callboard.App.Data.DataContext.Realizations.Db { internal class RoleDbContext : EntityDbContext<Role>, IRoleContext { public RoleDbContext(IDbContext context, ILoggerWrapper logger) : base(context, logger) { } public IResult<Role> Delete(int id) { var procedureName = "sp_delete_role_by_id"; var values = new Dictionary<string, object> { { "RoleId", id } }; return base.Execute(procedureName, values); } public IResult<IReadOnlyCollection<Role>> GetAll() { var procedureName = "sp_select_role"; var mapper = new Mapper<DataSet, Role> { MapCollection = this.MapRoleCollection }; return base.GetAll(procedureName, mapper); } public IResult<Role> GetById(int id) { var procedureName = "sp_get_role_by_id"; var values = new Dictionary<string, object> { { "RoleId", id } }; var mapper = new Mapper<DataSet, Role> { MapItem = this.MapRole }; return base.Get(procedureName, mapper, values); } public IResult<IReadOnlyCollection<Role>> GetRolesForUser(int userId) { var procedureName = "sp_select_role_by_userid"; var values = new Dictionary<string, object> { { "UserId", userId } }; var mapper = new Mapper<DataSet, Role> { MapCollection = this.MapRoleCollection }; return base.GetAll(procedureName, mapper, values); } public IResult<Role> Save(Role obj) { var procedureName = "sp_save_role"; var mapper = new Mapper<DataSet, Role> { MapValues = this.MapRoleValues }; return base.Save(obj, procedureName, mapper); } public IResult<Role> SetRoleForUser(int userId, int roleId) { var procedureName = "sp_set_role_for_user"; var values = new Dictionary<string, object> { { "UserId", userId }, { "RoleId", roleId } }; return base.Execute(procedureName, values); } public IResult<Role> DeleteUserRole(int userId, int roleId) { var procedureName = "sp_delete_user_role"; var values = new Dictionary<string, object> { { "UserId", userId }, { "RoleId", roleId } }; return base.Execute(procedureName, values); } private IDictionary<string, object> MapRoleValues(Role role) { return new Dictionary<string, object> { { "RoleId", role.RoleId }, { "Name", role.Name } }; } private Role MapRole(DataSet dataSet) { return dataSet.Tables[0].AsEnumerable().Select(this.MapRole).FirstOrDefault(); } private IReadOnlyCollection<Role> MapRoleCollection(DataSet dataSet) { return dataSet.Tables[0].AsEnumerable().Select(this.MapRole).ToList(); } private Role MapRole(DataRow row) { return new Role { RoleId = row.Field<int>("RoleId"), Name = row.Field<string>("Name") }; } } }<file_sep>namespace Callboard.App.General.Entities { public class AdDetails : Ad { public User User { get; set; } public string Description { get; set; } public string AddressLine { get; set; } } }<file_sep>namespace Callboard.App.General.Results { public interface ISuccessResult<T> : IResult<T> { T Value { get; } } }<file_sep>using System.Runtime.Serialization; namespace Callboard.Service.Commercial { [DataContract] public class Image { [DataMember] public byte[] Data { get; set; } [DataMember] public string Extension { get; set; } } } <file_sep>using Callboard.App.Data.Repositories; using Callboard.App.General.Entities; using Callboard.App.General.Exceptions; using Callboard.App.General.Results; using System; using System.Collections.Generic; namespace Callboard.App.Business.Services.Realizations { internal class CategoryService : ICategoryService { private ICategoryRepository _categoryRepository; public CategoryService(ICategoryRepository categoryRepository) { _categoryRepository = categoryRepository ?? throw new NullReferenceException(nameof(categoryRepository)); } public IResult<Category> Delete(int id) { this.CheckId(id); return _categoryRepository.Delete(id); } public IResult<IReadOnlyCollection<Category>> GetAll() { return _categoryRepository.GetAll(); } public IResult<Category> GetById(int id) { this.CheckId(id); return _categoryRepository.GetById(id); } public IResult<IReadOnlyCollection<Category>> GetSubcategories(int categoryId) { this.CheckId(categoryId); return _categoryRepository.GetSubcategories(categoryId); } public IResult<IReadOnlyCollection<Category>> GetMainCategories() { return _categoryRepository.GetMainCategories(); } public IResult<Category> Save(Category obj) { obj = obj ?? throw new NullReferenceException(nameof(obj)); return _categoryRepository.Save(obj); } private void CheckId(int id) { if (id < 1) { throw new InvalidIdException(nameof(id)); } } } }<file_sep>using System.Collections.Generic; namespace Callboard.App.General.Entities.Data { public class SearchConfiguration { public string Name { get; set; } public string State { get; set; } public string Kind { get; set; } public decimal MinPrice { get; set; } public decimal MaxPrice { get; set; } public int CountryId { get; set; } public int AreaId { get; set; } public int CityId { get; set; } public IReadOnlyCollection<Category> Categories { get; set; } } }<file_sep>using Callboard.App.Data.Repositories; using Callboard.App.General.Entities.Auth; using Callboard.App.General.ResultExtensions; using Callboard.App.General.Results; using Callboard.App.General.Results.Realizations; using Newtonsoft.Json; using System; using System.Web; using System.Web.Security; using Data = Callboard.App.Data.Services; namespace Callboard.App.Business.Services.Realizations { internal class LogginService : ILogginService { private Data::IMembershipService _membershipProvider; private IRoleRepository _roleRepository; private const int VERSION = 1; public LogginService(Data::IMembershipService membershipProvider, IRoleRepository roleRepository) { _membershipProvider = membershipProvider ?? throw new NullReferenceException(nameof(membershipProvider)); _roleRepository = roleRepository ?? throw new NullReferenceException(nameof(roleRepository)); } public IResult<MembershipUser> Login(string login, string password) { var validResult = this.IsValidUser(login, password); if (validResult.IsSuccess()) { var user = GetUser(login); this.SendCookies(user); return new NoneResult<MembershipUser>(); } return validResult; } public IResult<MembershipUser> Register(string login, string password) { var registerResult = new NoneResult<MembershipUser>(); var userResult = _membershipProvider.CreateUser(login, password); if (userResult.IsSuccess()) { var user = userResult.GetSuccessResult(); this.SendCookies(user); } else if (userResult.IsFailure()) { return userResult; } return registerResult; } public IResult<MembershipUser> Logout() { FormsAuthentication.SignOut(); return new NoneResult<MembershipUser>(); } private void SendCookies(MembershipUser user) { var userData = JsonConvert.SerializeObject(user); var ticket = new FormsAuthenticationTicket(VERSION, user.Name, DateTime.Now, DateTime.Now.AddMinutes(15), false, userData); var encryptTicket = FormsAuthentication.Encrypt(ticket); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptTicket); HttpContext.Current.Response.Cookies.Add(cookie); } private IResult<MembershipUser> IsValidUser(string login, string password) { return _membershipProvider.ValidateUser(login, password); } private MembershipUser GetUser(string login) { MembershipUser membershipUser = null; var userResult = _membershipProvider.GetUserByLogin(login); if (userResult.IsSuccess()) { membershipUser = userResult.GetSuccessResult(); } return membershipUser; } } }<file_sep>using Callboard.App.Data.DbContext; using Callboard.App.Data.Mappers; using Callboard.App.General.Entities; using Callboard.App.General.Loggers.Main; using Callboard.App.General.Results; using System.Collections.Generic; using System.Data; using System.Linq; namespace Callboard.App.Data.DataContext.Realizations.Db { internal class StateDbContext : EntityDbContext<State>, IDataContext<State> { public StateDbContext(IDbContext context, ILoggerWrapper logger) : base(context, logger) { } public IResult<State> Delete(int id) { string procedureName = "sp_delete_state_by_id"; var values = new Dictionary<string, object> { { "StateId", id } }; return base.Execute(procedureName, values); } public IResult<IReadOnlyCollection<State>> GetAll() { string procedureName = "sp_select_state"; var mapper = new Mapper<DataSet, State> { MapCollection = this.MapStateCollection }; return base.GetAll(procedureName, mapper); } public IResult<State> GetById(int id) { string procedureName = "sp_get_state_by_id"; var mapper = new Mapper<DataSet, State> { MapItem = this.MapState }; var values = new Dictionary<string, object> { { "StateId", id } }; return base.Get(procedureName, mapper, values); } public IResult<State> Save(State obj) { string procedureName = "sp_save_state"; var mapper = new Mapper<DataSet, State> { MapValues = this.MapStateValues }; return base.Save(obj, procedureName, mapper); } private IDictionary<string, object> MapStateValues(State state) { return new Dictionary<string, object> { { "StateId", state.StateId }, { "Condition", state.Condition } }; } private State MapState(DataSet dataSet) { return dataSet.Tables[0].AsEnumerable().Select(this.MapState).FirstOrDefault(); } private IReadOnlyCollection<State> MapStateCollection(DataSet dataSet) { return dataSet.Tables[0].AsEnumerable().Select(this.MapState).ToList(); } private State MapState(DataRow row) { return new State { StateId = row.Field<int>("StateId"), Condition = row.Field<string>("Condition") }; } } }<file_sep>using Callboard.App.General.Entities; using Callboard.App.General.Entities.Data; using Callboard.App.General.Results; using System.Collections.Generic; namespace Callboard.App.Data.Services { public interface IAdService { IResult<Ad> Delete(int id); IResult<IReadOnlyCollection<Ad>> GetAll(); IResult<IReadOnlyCollection<Ad>> GetAdsByCategoryId(int categoryId); IResult<IReadOnlyCollection<Ad>> SearchByName(string name); IResult<IReadOnlyCollection<Ad>> Search(SearchConfiguration searchConfiguration); IResult<IReadOnlyCollection<Ad>> GetAdsForUser(int userId); } }<file_sep>using System; using System.ComponentModel; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace Callboard.App.Web.HtmlHelpers { public static class HtmlImageExtension { public static IHtmlString RenderImage(this HtmlHelper helper, byte[] image, string extension, string imgclass = null, object htmlAttributes = null) { var builder = new TagBuilder("img"); builder.MergeAttribute("class", imgclass); builder.MergeAttributes(AnonymousObjectToHtmlAttributes(htmlAttributes)); var imageString = image != null ? Convert.ToBase64String(image) : ""; var img = string.Format("data:image/" + extension + ";base64,{0}", imageString); builder.MergeAttribute("src", img); return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing)); } private static RouteValueDictionary AnonymousObjectToHtmlAttributes(object htmlAttributes) { RouteValueDictionary result = new RouteValueDictionary(); if (htmlAttributes != null) { foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(htmlAttributes)) { result.Add(property.Name.Replace('_', '-'), property.GetValue(htmlAttributes)); } } return result; } } }<file_sep>using Callboard.App.Data.DbContext; using Callboard.App.Data.Mappers; using Callboard.App.General.Entities; using Callboard.App.General.Loggers.Main; using Callboard.App.General.Results; using System; using System.Collections.Generic; using System.Data; using System.Linq; namespace Callboard.App.Data.DataContext.Realizations.Db { internal class CityDbContext : EntityDbContext<City>, ICityContext { public CityDbContext(IDbContext context, ILoggerWrapper logger) : base(context, logger) { } public IResult<City> Delete(int id) { string procedureName = "sp_delete_city_by_id"; var values = new Dictionary<string, object> { { "CityId", id } }; return base.Execute(procedureName, values); } public IResult<IReadOnlyCollection<City>> GetAll() { string procedureName = "sp_select_city"; var mapper = new Mapper<DataSet, City> { MapCollection = this.MapCityCollection }; return base.GetAll(procedureName, mapper); } public IResult<City> GetById(int id) { string procedureName = "sp_get_city_by_id"; var values = new Dictionary<string, object> { { "CityId", id } }; var mapper = new Mapper<DataSet, City> { MapItem = this.MapCity }; return base.Get(procedureName, mapper, values); } public IResult<IReadOnlyCollection<City>> GetCitiesByAreaId(int areaId) { string procedureName = "sp_select_city_by_areaid"; var values = new Dictionary<string, object> { { "AreaId", areaId } }; var mapper = new Mapper<DataSet, City> { MapCollection = this.MapCityCollection }; return base.GetAll(procedureName, mapper, values); } public IResult<City> Save(int areaId, City obj) { string procedureName = "sp_save_city"; var values = this.MapCityValues(areaId, obj); return base.Execute(procedureName, values); } private IDictionary<string, object> MapCityValues(int areaId, City city) { return new Dictionary<string, object> { { "CityId", city.CityId }, { "AreaId", areaId }, { "Name", city.Name } }; } private City MapCity(DataSet dataSet) { return dataSet.Tables[0].AsEnumerable().Select(this.MapCity).FirstOrDefault(); } private IReadOnlyCollection<City> MapCityCollection(DataSet dataSet) { return dataSet.Tables[0].AsEnumerable().Select(this.MapCity).ToList(); } private City MapCity(DataRow row) { return new City { CityId = row.Field<int>("CityId"), Name = row.Field<string>("Name") }; } } }<file_sep>function updateCategory(nameInputId, parentId, categoryId) { let nameInput = $("#" + nameInputId); let categoryName = nameInput.val(); if (categoryName && parentId >= 0 && categoryId) { let category = { CategoryId: categoryId, Name: categoryName, ParentId: parentId }; $.post('/Category/SaveCategory', { categoryData: JSON.stringify(category) }); } }<file_sep>using Callboard.App.Data.DataContext; using Callboard.App.General.Entities; using Callboard.App.General.Results; using System; using System.Collections.Generic; namespace Callboard.App.Data.Repositories.Realizations { internal class RoleRepository : IRoleRepository { private IRoleContext _context; public RoleRepository(IRoleContext context) { _context = context ?? throw new NullReferenceException(nameof(context)); } public IResult<Role> Delete(int id) { return _context.Delete(id); } public IResult<Role> DeleteUserRole(int userId, int roleId) { return _context.DeleteUserRole(userId, roleId); } public IResult<IReadOnlyCollection<Role>> GetAll() { return _context.GetAll(); } public IResult<Role> GetById(int id) { return _context.GetById(id); } public IResult<IReadOnlyCollection<Role>> GetRolesForUser(int userId) { return _context.GetRolesForUser(userId); } public IResult<Role> Save(Role obj) { return _context.Save(obj); } public IResult<Role> SetRoleForUser(int userId, int roleId) { return _context.SetRoleForUser(userId, roleId); } } }<file_sep>using Callboard.App.General.Cache.Main; using System; using System.Runtime.Caching; namespace Callboard.App.General.Cache.Realizations { internal class CacheStorage : ICacheStorage { private MemoryCache _cache; private const string CACHE_NAME = "GeneralCache"; public CacheStorage() { _cache = new MemoryCache(CACHE_NAME); } public bool Add<T>(string key, T obj, int minutes) where T : class { if (obj == null) { return false; } return _cache.Add(key, obj, DateTime.Now.AddMinutes(minutes)); } public void Delete(string key) { if (_cache.Contains(key)) { _cache.Remove(key); } } public T Get<T>(string key) where T : class { object obj = _cache.Get(key); return obj as T; } public void Update<T>(string key, T obj, int minutes) where T : class { if (obj == null) { return; } _cache.Set(key, obj, DateTime.Now.AddMinutes(minutes)); } } } <file_sep>using Callboard.App.General.Results; using System.Collections.Generic; namespace Callboard.App.Data.Repositories { public interface IRepository<T> { IResult<IReadOnlyCollection<T>> GetAll(); IResult<T> GetById(int id); IResult<T> Save(T obj); IResult<T> Delete(int id); } }<file_sep>using Callboard.App.General.Entities.Auth; using Callboard.App.General.Results; namespace Callboard.App.Business.Services { public interface ILogginService { IResult<MembershipUser> Login(string login, string password); IResult<MembershipUser> Logout(); IResult<MembershipUser> Register(string login, string password); } }<file_sep>using System; using System.Collections.Generic; namespace Callboard.App.General.Entities { public class Ad { public int AdId { get; set; } public Location Location { get; set; } public string Name { get; set; } public decimal Price { get; set; } public DateTime CreationDate { get; set; } public string Kind { get; set; } public string State { get; set; } public IReadOnlyCollection<Image> Images { get; set; } public IReadOnlyCollection<Category> Categories { get; set; } } }<file_sep>using System.Linq; using System.Security.Principal; namespace Callboard.App.General.Entities.Auth { public class UserPrinciple : IPrincipal { private string[] _roles; public UserPrinciple(string username) { this.Identity = new GenericIdentity(username); } public int UserId { get; set; } public string Name { get; set; } public string[] Roles { get => _roles; set => _roles = value.Select(x => x.ToLower()).ToArray(); } public IIdentity Identity { get; private set; } public bool IsInRole(string role) { if (_roles == null) { return false; } return _roles.Contains(role.ToLower()); } } } <file_sep>function loadStates() { getDataAsync(null, "/State/GetStates", renderStates); } let renderStates = function (data) { clearStates(); let stateContainer = getStatesContainer(); let states = JSON.parse(data.States); for (let i = 0; i < states.length; i++) { let option = createOption('state', states[i].Condition, states[i].Condition); stateContainer.append(option); } } let clearStates = function () { let stateContainer = getStatesContainer(); stateContainer.empty(); let defaultOption = createOption('state', '', "--- Choose state ---"); stateContainer.append(defaultOption); } let getStatesContainer = function () { return $('#states'); }<file_sep>using Callboard.App.General.Entities; using System.Collections.Generic; namespace Callboard.App.Web.Models { public class CategoryViewModel { public IReadOnlyCollection<Category> Categories { get; set; } } }<file_sep>using Callboard.Service.Commercial.Config; using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.ServiceModel; namespace Callboard.Service.Commercial { public class CommercialContract : ICommercialContract { private IDictionary<string, string> _pathways; private const int COMMERCIAL_COUNT = 3; private const string SECTION_NAME = "commercialSettings"; public CommercialContract() { this.FillPathways(); } private void FillPathways() { _pathways = new Dictionary<string, string>(); var pathwaysSection = this.GetPathwaysSection(); foreach (ImagePathElement item in pathwaysSection) { DirectoryInfo directory = new DirectoryInfo(item.Path); if (!directory.Exists) { CommercialNotFound faultDetails = new CommercialNotFound { Message = "Commercials folder not found. Please, check path to image." }; throw new FaultException<CommercialNotFound>(faultDetails); } FileInfo[] files = directory.GetFiles(); foreach (var fileInfo in files) { _pathways.Add(fileInfo.FullName, fileInfo.Extension); } } } private ImagePathCollection GetPathwaysSection() { var configSection = ConfigurationManager.GetSection(SECTION_NAME) as CommercialConfigSection; var pathwaysSection = configSection?.Pathways; if (pathwaysSection == null) { CommercialNotFound faultDetails = new CommercialNotFound { Message = "Commercial not found. Please, check path to image." }; throw new FaultException<CommercialNotFound>(faultDetails); } return pathwaysSection; } public Commercial[] GetCommercials() { var resultCollection = new List<Commercial>(); Random random = new Random(); for (int i = 0; i < COMMERCIAL_COUNT; i++) { int index = random.Next(0, _pathways.Count); byte[] byteImage = File.ReadAllBytes(_pathways.Keys.ElementAt(index)); Image image = new Image { Data = byteImage, Extension = _pathways.Values.ElementAt(index).TrimStart('.') }; Commercial commercial = new Commercial { Id = i + 1, Image = image }; resultCollection.Add(commercial); } return resultCollection.ToArray(); } } } <file_sep>using Callboard.App.Data.Exceptions; using Callboard.App.General.Loggers.Main; using Microsoft.SqlServer.Server; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; namespace Callboard.App.Data.DbContext.Realizations { internal class SqlDbContext : IDbContext { private ILoggerWrapper _logger; private string _connectionString; public SqlDbContext(ILoggerWrapper logger) { _logger = logger ?? throw new NullReferenceException(nameof(logger)); } public string ConnectionString { get => _connectionString; set => _connectionString = value; } public DataSet ExecuteProcedure(string procedureName, IDictionary<string, object> values = null) { DataSet dataSet = null; using (var connection = this.CreateConnection()) { using (var procedure = this.CreateProcedure(procedureName, values)) { using (var adapter = new SqlDataAdapter(procedure)) { procedure.Connection = connection; try { connection.Open(); dataSet = new DataSet(); adapter.Fill(dataSet); connection.Close(); } catch (InvalidOperationException ex) { string errorMessage = $"{ ex.Message }\nConnection string: { connection.ConnectionString }"; _logger.ErrorFormat(errorMessage); dataSet = null; } catch (SqlException ex) when (ex.Number == 50001) // user login already exists { _logger.InfoFormat(ex.Message); throw new LoginAlreadyExistsException(ex.Message, ex); } catch (SqlException ex) when (ex.Number == 50002) // login is invalid { _logger.InfoFormat(ex.Message); throw new InvalidLoginException(ex.Message, ex); } catch (SqlException ex) when (ex.Number == 50003) // password is invalid { _logger.InfoFormat(ex.Message); throw new InvalidPasswordException(ex.Message, ex); } catch (SqlException ex) { string errorMessage = $"{ ex.Message }\nConnection string: { connection.ConnectionString }"; _logger.ErrorFormat(errorMessage); dataSet = null; } } } } return dataSet; } public void ExecuteNonQuery(string procedureName, IDictionary<string, object> values = null) { using (var connection = this.CreateConnection()) { using (var procedure = this.CreateProcedure(procedureName, values)) { procedure.Connection = connection; try { connection.Open(); procedure.ExecuteNonQuery(); connection.Close(); } catch (InvalidOperationException ex) { string errorMessage = $"{ ex.Message }\nConnection string: { connection.ConnectionString }"; _logger.ErrorFormat(errorMessage); } catch (SqlException ex) { string errorMessage = $"{ ex.Message }\nConnection string: { connection.ConnectionString }"; _logger.ErrorFormat(errorMessage); } } } } private SqlCommand CreateProcedure(string procedureName, IDictionary<string, object> values = null) { SqlCommand command = new SqlCommand { CommandText = procedureName, CommandType = CommandType.StoredProcedure }; if (values != null) { foreach (var item in values) { var parameter = this.CreateParameter(item.Key, item.Value); command.Parameters.Add(parameter); } } return command; } private SqlParameter CreateParameter(string name, object value) { SqlParameter parameter = new SqlParameter { ParameterName = $"@{ name }", Value = value }; if (value is IEnumerable<SqlDataRecord>) { parameter.SqlDbType = SqlDbType.Structured; } return parameter; } private SqlConnection CreateConnection() { if (!string.IsNullOrEmpty(_connectionString)) { return new SqlConnection(_connectionString); } else { throw new EmptyConnectionStringException(); } } } }<file_sep>function loadAreas(countryId, areasContainerId) { callActionAsync({ countryId: countryId }, '/Area/GetAreaEditListByCountryId', areasContainerId); $("#country-id").val(countryId); $("#city-edit-list").empty(); }<file_sep>function saveState(conditionInputId, statesContanerId) { let condition = $("#" + conditionInputId).val(); if (condition) { let state = { StateId: 0, Condition: condition }; $.post('/State/SaveState', { stateData: JSON.stringify(state) }, function () { getStateList(statesContanerId); }); } }<file_sep>function saveCity(areaInputId, cityNameInputId, citiesContainerId) { let cityNameInput = $("#" + cityNameInputId); let cityName = cityNameInput.val(); let areaId = $("#" + areaInputId).val(); if (areaId && cityName) { cityNameInput.removeClass('invalid__field'); let cityModel = { City: { CityId: 0, Name: cityName }, AreaId: areaId }; $.post('/City/SaveCity', { cityViewModelData: JSON.stringify(cityModel) }, function () { getCityList(areaId, citiesContainerId); }); } else { cityNameInput.addClass('invalid__field'); } }<file_sep>function fillAreas(countryId) { if (countryId === 0) { clearAreas(); } else { getDataAsync({ countryId: countryId }, "/Area/GetAreasByCountryId", renderAreas); } } function clearAreas() { clearCities(); let areasContainer = getAreasContainer(); areasContainer.empty(); let defaultOption = createOption('areaId', 0, "--- Choose area ---"); areasContainer.append(defaultOption); } let renderAreas = function (data) { clearAreas(); let areasContainer = getAreasContainer(); let areas = JSON.parse(data.Areas); for (let i = 0; i < areas.length; i++) { let option = createOption('areaId', areas[i].AreaId, areas[i].Name); areasContainer.append(option); } } let getAreasContainer = function () { return $('#areas'); }<file_sep>function saveAdDetails() { let adDetailsModel = getAdDetailsModel(); if (adDetailsModel.isValid) { $.post('/AdDetails/SaveAdDetails', { adDetailsData: JSON.stringify(adDetailsModel.adDetails) }, showAdDetailsSaveResult); } } let showAdDetailsSaveResult = function (data) { let saveResultContainer = $("#save-result"); saveResultContainer.removeClass('none'); setTimeout(function () { saveResultContainer.addClass('none'); }, 4000); } let getAdDetailsModel = function () { let name = getName(); let price = getPrice(); let description = $("#description").val(); let addressLine = $("#addressLine").val(); let kind = $("#kinds").find(":selected").val(); let state = $("#states").find(":selected").val(); let userId = $("#userId").val(); let adId = $("#adId").val(); let locationId = getLocationId(); let categories = getCategoriesList(); let images = getImages(); return { adDetails: { Name: name, Price: price, Description: description, AddressLine: addressLine, Kind: kind, State: state, UserId: userId, AdId: adId, Location: { LocationId: locationId }, Categories: categories, Images: images }, isValid: name && price && userId && adId && locationId && categories.length }; } let getName = function () { let name = $("#name").val(); if (name === '') { name = 'Product'; } return name; } let getPrice = function () { let price = +$("#price").val().replace(',', '.'); if (price <= 0) { price = 1; } return price; } let getLocationId = function () { let locationId = $("#cities").find(":selected").val(); if (typeof locationId === 'undefined') { locationId = $("#locationId").val(); } if (locationId <= 0) { locationId = 1; } return locationId; } let getCategoriesList = function () { let categories = []; $("#categories").find(":checked").each(function () { let category = { CategoryId: $(this).data('categoryId') }; categories.push(category); }); return categories; } let getImages = function () { let images = []; $("#images").find("img").each(function () { let imageSrc = this.src; let imageData = imageSrc.split(";"); let extension = imageData[0].split(":")[1].split("/")[1]; let imageBase64 = imageData[1].split(",")[1]; let imageId = $(this).data('imageId'); if (typeof imageId === 'undefined') { imageId = 0; } let image = { ImageId: imageId, Data: convertBase64ToByte(imageBase64), Extension: extension }; images.push(image); }); return images; }<file_sep>function updateState(stateId, conditionInputId) { let condition = $("#" + conditionInputId).val(); if (stateId && condition) { let state = { StateId: stateId, Condition: condition }; $.post('/State/SaveState', { stateData: JSON.stringify(state) }); } }<file_sep>function createOption(name, value, text) { let option = $('<option></option>'); option.attr('name', name); option.attr('value', value); option.text(text); return option; } function clearContainer(containerId) { $("#" + containerId).empty(); } function backPage() { window.history.back(); } function refreshPage() { location.reload(); } function convertByteToBase64(byteArray) { var base64String = btoa(String.fromCharCode.apply(null, new Uint8Array(byteArray))); return base64String; } function convertBase64ToByte(base64) { var binaryString = window.atob(base64); var length = binaryString.length; var bytes = new Uint8Array(length); for (var i = 0; i < length; i++) { bytes[i] = binaryString.charCodeAt(i); } let byteArray = [].slice.call(bytes); return byteArray; }<file_sep>using Callboard.App.General.Entities; using Callboard.App.General.Entities.Data; using System.Collections.Generic; namespace Callboard.App.Web.Models { public class SearchViewModel { public IReadOnlyCollection<Ad> Ads { get; set; } public SearchConfiguration SearchConfiguration { get; set; } } }<file_sep>using Callboard.App.Business.Services; using Callboard.App.General.ResultExtensions; using Callboard.App.Web.Models; using System; using System.Net; using System.Web.Mvc; namespace Callboard.App.Web.Controllers { public class NavigationController : Controller { private ICategoryService _categoryProvider; public NavigationController(ICategoryService categoryProvider) { if (categoryProvider == null) { throw new NullReferenceException(nameof(categoryProvider)); } _categoryProvider = categoryProvider; } public ActionResult GetCategoryMenu() { var categoriesResult = _categoryProvider.GetMainCategories(); if (categoriesResult.IsSuccess()) { var categories = categoriesResult.GetSuccessResult(); CategoryViewModel model = new CategoryViewModel { Categories = categories }; return PartialView("CategoryMenu", model); } return new HttpStatusCodeResult(HttpStatusCode.NotFound); } public ActionResult GetSubcategoryMenu(int categoryId) { var categoriesResult = _categoryProvider.GetSubcategories(categoryId); if (categoriesResult.IsSuccess()) { var categories = categoriesResult.GetSuccessResult(); CategoryViewModel model = new CategoryViewModel { Categories = categories }; return PartialView("CategoryMenu", model); } return new HttpStatusCodeResult(HttpStatusCode.NotFound); } } }<file_sep>using Callboard.App.Data.Repositories; using Callboard.App.General.Entities; using Callboard.App.General.Exceptions; using Callboard.App.General.Results; using System; using System.Collections.Generic; namespace Callboard.App.Business.Services.Realizations { internal class UserService : IEntityService<User> { private IRepository<User> _userRepository; public UserService(IRepository<User> userRepository) { _userRepository = userRepository ?? throw new NullReferenceException(nameof(userRepository)); } public IResult<User> Delete(int id) { this.CheckId(id); return _userRepository.Delete(id); } public IResult<IReadOnlyCollection<User>> GetAll() { return _userRepository.GetAll(); } public IResult<User> GetById(int id) { this.CheckId(id); return _userRepository.GetById(id); } public IResult<User> Save(User obj) { obj = obj ?? throw new NullReferenceException(nameof(obj)); return _userRepository.Save(obj); } private void CheckId(int id) { if (id < 1) { throw new InvalidIdException(nameof(id)); } } } }<file_sep>function getSubcategories(link, categoryId, updateTargetId) { let subcategoriesLoaded = function () { $(link)[0].onclick = null; $(link).click(function () { $("#" + updateTargetId).slideToggle(); }); $(link).click(); } callActionAsync({ categoryId: categoryId }, '/Category/GetSubcategories', updateTargetId, subcategoriesLoaded); }<file_sep>using System.Collections.Generic; using System.Text; using System.Web; using System.Web.Mvc; namespace Callboard.App.Web.HtmlHelpers { public static class HtmlPartialExtension { public static IHtmlString GetHtmlPartial(this HtmlHelper htmlHelper, string partialViewName, object model) { IDictionary<string, string> removedCharacters = new Dictionary<string, string> { { "\n", "" }, { "\r", "" }, { "\"", "\\\"" }, { "\'", "\\\'" } }; string partialView = System.Web.Mvc.Html.PartialExtensions.Partial(htmlHelper, partialViewName, model).ToString(); StringBuilder partialViewHtml = new StringBuilder(partialView); foreach (var character in removedCharacters) { partialViewHtml.Replace(character.Key, character.Value); } return MvcHtmlString.Create(partialViewHtml.ToString()); } } }<file_sep>namespace Callboard.App.General.Entities { public class Mail { public int MailId { get; set; } public string Email { get; set; } } }<file_sep>using Callboard.App.Data.DataContext; using Callboard.App.General.Entities.Auth; using Callboard.App.General.Results; using System; namespace Callboard.App.Data.Services.Realizations { internal class MembershipService : IMembershipService { private IMembershipContext _context; public MembershipService(IMembershipContext context) { _context = context ?? throw new NullReferenceException(nameof(context)); } public IResult<MembershipUser> GetUserByLogin(string login) { return _context.GetUserByLogin(login); } public IResult<MembershipUser> CreateUser(string login, string password) { return _context.CreateUser(login, password); } public IResult<MembershipUser> ValidateUser(string login, string password) { return _context.ValidateUser(login, password); } } }<file_sep>using Callboard.App.General.Entities; namespace Callboard.App.Web.Models { public class UserViewModel { public User User { get; set; } } }<file_sep>using Callboard.App.General.Entities; using System.Collections.Generic; namespace Callboard.App.Web.Models { public class UserRoleEditViewModel { public int UserId { get; set; } public IReadOnlyCollection<Role> Roles { get; set; } } }<file_sep>namespace Callboard.App.General.Entities { public class Area { public int AreaId { get; set; } public string Name { get; set; } } }<file_sep>function getSubcategoryList(link, categoryId, subcategoryContainerId) { if (categoryId) { let subcategoriesLoaded = function () { if (link) { $(link)[0].onclick = null; $(link).click(function () { $("#" + subcategoryContainerId).slideToggle(); }); } $("#" + subcategoryContainerId).slideDown(); } callActionAsync({ categoryId: categoryId }, '/Category/GetSubcategoryEditList', subcategoryContainerId, subcategoriesLoaded); } }<file_sep>using Callboard.App.Business.Services; using Callboard.App.General.Entities.Commercial; using Callboard.App.General.ResultExtensions; using Callboard.App.Web.Models; using System; using System.Collections.Generic; using System.Web.Mvc; namespace Callboard.App.Web.Controllers { public class CommercialController : Controller { private ICommercialService _commercialProvider; public CommercialController(ICommercialService commercialProvider) { if (commercialProvider == null) { throw new NullReferenceException(nameof(commercialProvider)); } _commercialProvider = commercialProvider; } public ActionResult GetCommercial() { IReadOnlyCollection<Commercial> commercials = new List<Commercial>(); var commercialResult = _commercialProvider.GetCommercials(); if (commercialResult.IsSuccess()) { commercials = commercialResult.GetSuccessResult(); } var model = new CommercialViewModel { Commercials = commercials }; return PartialView("CommercialPartial", model); } } }<file_sep>using Callboard.App.Business.Auth; using Callboard.App.Business.Services; using Callboard.App.General.Entities; using Callboard.App.General.Entities.Auth; using Callboard.App.General.ResultExtensions; using Callboard.App.Web.Attributes; using Callboard.App.Web.Models; using Newtonsoft.Json; using System; using System.Net; using System.Web.Mvc; namespace Callboard.App.Web.Controllers { public class UserController : Controller { private IEntityService<User> _userProvider; public UserController(IEntityService<User> userProvider) { if (userProvider == null) { throw new NullReferenceException(nameof(userProvider)); } _userProvider = userProvider; } public ActionResult GetUser(int userId) { var userResult = _userProvider.GetById(userId); if (userResult.IsSuccess()) { var user = userResult.GetSuccessResult(); return PartialView("Partial\\User", user); } return new HttpStatusCodeResult(HttpStatusCode.NotFound); } [User] public ActionResult OpenProfile(int userId) { var userPrinciple = User as UserPrinciple; if (userPrinciple.UserId == userId || userPrinciple.IsInRole(RoleType.Admin.ToString())) { var userResult = _userProvider.GetById(userId); if (userResult.IsSuccess()) { var user = userResult.GetSuccessResult(); return View("UserProfile", user); } } return new HttpStatusCodeResult(HttpStatusCode.NotFound); } [User] public ActionResult EditProfile(int userId, string returnUrl) { ViewBag.ReturnUrl = returnUrl; var userPrinciple = User as UserPrinciple; if (userPrinciple.UserId == userId || userPrinciple.IsInRole(RoleType.Admin.ToString())) { var userResult = _userProvider.GetById(userId); if (userResult.IsSuccess()) { var user = userResult.GetSuccessResult(); var userModel = new UserViewModel { User = user }; return View("EditProfile", userModel); } } return new HttpStatusCodeResult(HttpStatusCode.NotFound); } [User] public ActionResult EditUser(int userId) { var userPrinciple = User as UserPrinciple; if (userPrinciple.UserId == userId || userPrinciple.IsInRole(RoleType.Admin.ToString())) { var userResult = _userProvider.GetById(userId); if (userResult.IsSuccess()) { var user = userResult.GetSuccessResult(); return PartialView("UserEdit", user); } } return new HttpStatusCodeResult(HttpStatusCode.NotFound); } [User] [AjaxOnly] [HttpPost] public ActionResult SaveUser(string userData) { var user = JsonConvert.DeserializeObject<User>(userData); if (user != null) { var userSaveResult = _userProvider.Save(user); if (userSaveResult.IsNone()) { return new HttpStatusCodeResult(HttpStatusCode.OK); } } return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } [Admin] public ActionResult GetAllUsers() { var usersResult = _userProvider.GetAll(); if (usersResult.IsSuccess()) { var users = usersResult.GetSuccessResult(); return View("UserList", users); } return new HttpStatusCodeResult(HttpStatusCode.NotFound); } [Admin] [HttpPost] public ActionResult DeleteUserById(int userId) { var userDeleteResult = _userProvider.Delete(userId); if (userDeleteResult.IsNone()) { return RedirectToAction("GetAllUsers"); } return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } } }<file_sep>using Callboard.App.Business.Services; using Callboard.App.General.Entities; using Callboard.App.General.ResultExtensions; using Callboard.App.Web.Attributes; using Newtonsoft.Json; using System; using System.Net; using System.Web.Mvc; namespace Callboard.App.Web.Controllers { public class StateController : Controller { private IEntityService<State> _stateService; public StateController(IEntityService<State> stateService) { if (stateService == null) { throw new NullReferenceException(nameof(stateService)); } _stateService = stateService; } [AjaxOnly] public ActionResult GetStates() { var statesResult = _stateService.GetAll(); if (statesResult.IsSuccess()) { var states = statesResult.GetSuccessResult(); var statesData = JsonConvert.SerializeObject(states); return Json(new { States = statesData }, JsonRequestBehavior.AllowGet); } return new HttpStatusCodeResult(HttpStatusCode.NotFound); } [Editor] public ActionResult GetStateEditList() { var statesResult = _stateService.GetAll(); if (statesResult.IsSuccess()) { var states = statesResult.GetSuccessResult(); return PartialView("StateEditList", states); } return new HttpStatusCodeResult(HttpStatusCode.NotFound); } [Editor] [AjaxOnly] [HttpPost] public ActionResult SaveState(string stateData) { stateData = stateData ?? string.Empty; var state = JsonConvert.DeserializeObject<State>(stateData); if (state != null) { var stateSaveResult = _stateService.Save(state); if (stateSaveResult.IsNone()) { return new HttpStatusCodeResult(HttpStatusCode.OK); } } return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } [Editor] [AjaxOnly] [HttpPost] public ActionResult DeleteState(int stateId) { var stateDeleteResult = _stateService.Delete(stateId); if (stateDeleteResult.IsNone()) { return new HttpStatusCodeResult(HttpStatusCode.OK); } return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } } }<file_sep>using Callboard.App.Business.Services; using Callboard.App.General.Entities; using Callboard.App.General.ResultExtensions; using Callboard.App.Web.Attributes; using Newtonsoft.Json; using System; using System.Net; using System.Web.Mvc; namespace Callboard.App.Web.Controllers { public class CategoryController : Controller { private ICategoryService _categoryProvider; public CategoryController(ICategoryService categoryProvider) { if (categoryProvider == null) { throw new NullReferenceException(nameof(categoryProvider)); } _categoryProvider = categoryProvider; } [AjaxOnly] public ActionResult GetAllCategories() { var categoriesResult = _categoryProvider.GetAll(); if (categoriesResult.IsSuccess()) { var categories = categoriesResult.GetSuccessResult(); var categoriesData = JsonConvert.SerializeObject(categories); return Json(new { Categories = categoriesData }, JsonRequestBehavior.AllowGet); } return new HttpStatusCodeResult(HttpStatusCode.NotFound); } public ActionResult GetMainCategories() { var categoriesResult = _categoryProvider.GetMainCategories(); if (categoriesResult.IsSuccess()) { var categories = categoriesResult.GetSuccessResult(); return PartialView("CategoryListBox", categories); } return new HttpStatusCodeResult(HttpStatusCode.NotFound); } public ActionResult GetSubcategories(int categoryId) { var categoriesResult = _categoryProvider.GetSubcategories(categoryId); if (categoriesResult.IsSuccess()) { var categories = categoriesResult.GetSuccessResult(); return PartialView("CategoryListBox", categories); } return new HttpStatusCodeResult(HttpStatusCode.NotFound); } [Editor] public ActionResult GetCategoryEditList() { var categoriesResult = _categoryProvider.GetMainCategories(); if (categoriesResult.IsSuccess()) { var categories = categoriesResult.GetSuccessResult(); return PartialView("CategoryEditList", categories); } return new HttpStatusCodeResult(HttpStatusCode.NotFound); } [Editor] public ActionResult GetSubcategoryEditList(int categoryId) { var categoriesResult = _categoryProvider.GetSubcategories(categoryId); if (categoriesResult.IsSuccess()) { var categories = categoriesResult.GetSuccessResult(); return PartialView("CategoryEditList", categories); } return new HttpStatusCodeResult(HttpStatusCode.NotFound); } [Editor] [AjaxOnly] [HttpPost] public ActionResult DeleteCategory(int categoryId) { var categoriesResult = _categoryProvider.Delete(categoryId); if (categoriesResult.IsNone()) { return new HttpStatusCodeResult(HttpStatusCode.OK); } return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } [Editor] [AjaxOnly] [HttpPost] public ActionResult SaveCategory(string categoryData) { categoryData = categoryData ?? string.Empty; var category = JsonConvert.DeserializeObject<Category>(categoryData); if (category != null) { var categorySaveResult = _categoryProvider.Save(category); if (categorySaveResult.IsNone()) { return new HttpStatusCodeResult(HttpStatusCode.OK); } } return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } } }<file_sep>using Callboard.App.General.Entities; using Callboard.App.General.Results; using System.Collections.Generic; namespace Callboard.App.Data.DataContext { public interface ICityContext { IResult<IReadOnlyCollection<City>> GetAll(); IResult<City> GetById(int id); IResult<City> Save(int areaId, City obj); IResult<City> Delete(int id); IResult<IReadOnlyCollection<City>> GetCitiesByAreaId(int areaId); } }<file_sep>function updateCity(cityId, areaId, cityNameInputId) { let cityNameInput = $("#" + cityNameInputId); let cityName = cityNameInput.val(); if (cityId && areaId && cityName) { cityNameInput.removeClass('invalid__field'); let cityModel = { City: { CityId: cityId, Name: cityName }, AreaId: areaId }; $.post('/City/SaveCity', { cityViewModelData: JSON.stringify(cityModel) }); } else { cityNameInput.addClass('invalid__field'); } }<file_sep>namespace Callboard.App.General.Entities.Commercial { public class Commercial { public int Id { get; set; } public Image Image { get; set; } } } <file_sep>using Callboard.App.General.Entities; using Callboard.App.General.Results; using System.Collections.Generic; namespace Callboard.App.Data.Services { public interface ICityService { IResult<IReadOnlyCollection<City>> GetAll(); IResult<City> GetById(int id); IResult<City> Save(int areaId, City obj); IResult<City> Delete(int id); IResult<IReadOnlyCollection<City>> GetCitiesByAreaId(int areaId); } }<file_sep>using System; using System.Runtime.Serialization; namespace Callboard.App.Data.Exceptions { public class InvalidPasswordException : UserException { public InvalidPasswordException() { } public InvalidPasswordException(string message) : base(message) { } public InvalidPasswordException(string message, Exception innerException) : base(message, innerException) { } protected InvalidPasswordException(SerializationInfo info, StreamingContext context) : base(info, context) { } } } <file_sep>using Callboard.App.Business.Services; using Callboard.App.Business.Services.Realizations; using Callboard.App.General.Entities; using StructureMap; namespace Callboard.App.Business.DependencyResolution { public class BusinessRegistry : Registry { public BusinessRegistry() { For<ILogginService>().Use<LogginService>(); For<IAdDetailsService>().Use<AdDetailsService>(); For<IAdService>().Use<AdService>(); For<ICategoryService>().Use<CategoryService>(); For<IAreaService>().Use<AreaService>(); For<ICityService>().Use<CityService>(); For<IMembershipService>().Use<MembershipService>(); For<IRoleService>().Use<RoleService>(); For<ICommercialService>().Use<CommercialService>(); For<IEntityService<User>>().Use<UserService>(); For<IEntityService<Country>>().Use<CountryProvider>(); For<IEntityService<Kind>>().Use<KindService>(); For<IEntityService<State>>().Use<StateService>(); } } }<file_sep>using Callboard.App.Data.DataContext; using Callboard.App.General.Entities; using Callboard.App.General.Results; using System; using System.Collections.Generic; namespace Callboard.App.Data.Repositories.Realizations { internal class CountryRepository : IRepository<Country> { private IDataContext<Country> _context; public CountryRepository(IDataContext<Country> context) { _context = context ?? throw new NullReferenceException(nameof(context)); } public IResult<Country> Delete(int id) { return _context.Delete(id); } public IResult<IReadOnlyCollection<Country>> GetAll() { return _context.GetAll(); } public IResult<Country> GetById(int id) { return _context.GetById(id); } public IResult<Country> Save(Country obj) { return _context.Save(obj); } } }<file_sep>using Callboard.App.General.Entities; using System.Collections.Generic; namespace Callboard.App.Web.Models { public class AdListViewModel { public IReadOnlyCollection<Ad> Ads { get; set; } } }<file_sep>using Callboard.App.General.Entities; using System.Collections.Generic; namespace Callboard.App.Web.Models { public class ImageViewModel { public IReadOnlyCollection<Image> Images { get; set; } } }<file_sep># **Callboard** *Site for posting and viewing ads* This site is a platform for the sale of goods or services. The site has three modes of operation: user mode, editor mode and admin mode. By default, the following users are created when the database is deployed: | Login | Password | Role | | :---: | :---: | :---: | | user1 | <PASSWORD> | user | | editor1 | editor1 | editor | | admin | admin1 | admin | | editor2 | editor2 | editor | # Deployment of the application #### Step 1: Deployment of the Database To deploy the database to the *database* folder, ypu should run a **startup.bat** file. When it will be run, the database will be deployed. However, you need to change the host name and the name of your SQL Server instance in this file. Open the **startup.bat** file and substitute the following data: ```bat set server="YourHostName\YourSQLServerName" ``` > If SQL authentication is not enabled in your SQL Server, it will be enabled using the script **startup.sql**. In this case, before you start the deployment of the database, change the password of the **sa** (System Administrator) account: > ```sql > ALTER LOGIN sa WITH PASSWORD = '<PASSWORD>'; > GO > ``` #### Step 2: Deployment of the Web Site To run the site, you need to publish the project **Callboard.App.Web** and run it on IIS. > I would like to draw your attention to the fact that the site was developed on the .NET Framework 4.6.1 and requires ASP.NET 4.6 support for its operation. After you run it, you should change the connection string to the database. To do this, go to the **project publishing folder -> bin ->** and find the file **Callboard.App.Data.dll.config**. Change the host name and the name of your SQL Server instance: ```xml <connectionStrings> <add name="callboardDB" connectionString="Data Source=YourHostName\YourSQLServerName;Initial Catalog=callboardDB;Integrated Security=False;Connect Timeout=30;User ID=callboard_admin;Password=<PASSWORD>" providerName="System.Data.SqlClient" /> </connectionStrings> ``` After that, the site will be ready to go. #### Step 3: Deployment of the Commercial Service Now the site is working, but without ads. If you want to add ads to your site, you need to publish the project **Callboard.Service.Commercial** and also run it on IIS. After the startup is done, you need to link the service to our site. To do this, go to **the service publishing folder ->** and find the file **Web.config**. Change the service location port *(default is 4001)*, and also the hostname *(by default localhost)*, if necessary. ```xml <host> <baseAddresses> <add baseAddress="http://localhost:4001/Callboard.Service.Commercial.CommercialContract.svc" /> </baseAddresses> </host> ``` You also need to change the path to pictures with ads. You can specify the path to any folder with pictures. To do this, go to **the service publishing folder ->** and find the file **Web.config**. ```xml <commercialSettings> <pathways> <imagePath path="D:\_projects\_callboard\images" /> </pathways> </commercialSettings> ``` > In the project folder you can find the *ads_images* folder, where there will be a set of 10 pictures for advertising. Now you need to change the same data in the configuration files of our site. To do this, go to the **project publishing folder -> bin ->** and find the file **Callboard.App.Data.dll.config**. Change the service location port *(default is 4001)*, and also the hostname *(by default localhost)*, if necessary. ```xml <client> <endpoint address="http://localhost:4001/Callboard.Service.Commercial.CommercialContract.svc" binding="basicHttpBinding" bindingConfiguration="basicHttpFor2MBMessage" contract="CommercialService.ICommercialContract" name="CommercialContractEndpoint" /> </client> ``` Now the site is advertising.<file_sep>using System; namespace Callboard.App.General.Results { public interface IFailureResult<T> : IResult<T> { string ErrorMessage { get; } Exception Exception { get; } } }<file_sep>CREATE DATABASE [callboardDB]<file_sep>using Callboard.App.Data.DataContext; using Callboard.App.General.Entities; using Callboard.App.General.Results; using System; namespace Callboard.App.Data.Services.Realizations { internal class AdDetailsService : IAdDetailsService { private IAdDetailsContext _context; public AdDetailsService(IAdDetailsContext context) { _context = context ?? throw new NullReferenceException(nameof(context)); } public IResult<AdDetails> GetById(int id) { return _context.GetById(id); } public IResult<AdDetails> Save(AdDetails adDetails) { return _context.Save(adDetails); } } }<file_sep>using Callboard.App.General.Entities.Auth; using Callboard.App.General.Results; namespace Callboard.App.Business.Services { public interface IMembershipService { IResult<MembershipUser> CreateUser(string login, string password); } }<file_sep>function getCategoryList(categoryContainerId) { callActionAsync(null, '/Category/GetCategoryEditList', categoryContainerId); }<file_sep>using System.Runtime.Serialization; namespace Callboard.Service.Commercial { [DataContract] public class CommercialNotFound { [DataMember] public string Message { get; set; } } } <file_sep>using Callboard.App.General.Loggers.Main; using log4net; using log4net.Config; using System; using System.IO; namespace Callboard.App.General.Loggers.Realizations { internal class LoggerWrapper : ILoggerWrapper { private ILog _logger; private const string PATH_CONFIG = "logger.config"; private const string LOGGER_NAME = "LOGGER"; public LoggerWrapper() { _logger = LogManager.GetLogger(LOGGER_NAME); InitLogger(); } private void InitLogger() { var appConfigPath = Path.Combine(AppDomain.CurrentDomain.RelativeSearchPath, PATH_CONFIG); var configFile = new FileInfo(appConfigPath); XmlConfigurator.ConfigureAndWatch(configFile); } public void DebugFormat(string message, params object[] values) { _logger.DebugFormat(message, values); } public void ErrorFormat(string message, params object[] values) { _logger.ErrorFormat(message, values); } public void FatalFormat(string message, params object[] values) { _logger.FatalFormat(message, values); } public void InfoFormat(string message, params object[] values) { _logger.InfoFormat(message, values); } public void WarnFormat(string message, params object[] values) { _logger.WarnFormat(message, values); } } } <file_sep>using System; using System.Runtime.Serialization; namespace Callboard.App.General.Exceptions { public class InvalidIdException : ApplicationException { public InvalidIdException() { } public InvalidIdException(string message) : base(message) { } public InvalidIdException(string message, Exception innerException) : base(message, innerException) { } protected InvalidIdException(SerializationInfo info, StreamingContext context) : base(info, context) { } } } <file_sep>using Callboard.App.Business.Services; using Callboard.App.General.ResultExtensions; using Callboard.App.Web.Attributes; using Callboard.App.Web.Models; using Newtonsoft.Json; using System; using System.Net; using System.Web.Mvc; namespace Callboard.App.Web.Controllers { public class RoleController : Controller { private IRoleService _roleProvider; public RoleController(IRoleService roleProvider) { if (roleProvider == null) { throw new NullReferenceException(nameof(roleProvider)); } _roleProvider = roleProvider; } [Admin] [AjaxOnly] public ActionResult GetRoles() { var rolesResult = _roleProvider.GetAll(); if (rolesResult.IsSuccess()) { var roles = rolesResult.GetSuccessResult(); var rolesData = JsonConvert.SerializeObject(roles); return Json(new { Roles = rolesData }, JsonRequestBehavior.AllowGet); } return new HttpStatusCodeResult(HttpStatusCode.NotFound); } [Admin] public ActionResult GetRolesEditList(int userId) { var rolesResult = _roleProvider.GetRolesForUser(userId); if (rolesResult.IsSuccess()) { var roles = rolesResult.GetSuccessResult(); var rolesModel = new UserRoleEditViewModel { Roles = roles, UserId = userId }; return PartialView("UserRoleEditList", rolesModel); } return new HttpStatusCodeResult(HttpStatusCode.NotFound); } [Admin] [HttpPost] public ActionResult SetRoleForUser(int userId, int roleId) { var rolesResult = _roleProvider.SetRoleForUser(userId, roleId); if (rolesResult.IsNone()) { return new HttpStatusCodeResult(HttpStatusCode.OK); } return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } [Admin] [HttpPost] public ActionResult DeleteUserRole(int userId, int roleId) { var rolesResult = _roleProvider.DeleteUserRole(userId, roleId); if (rolesResult.IsNone()) { return new HttpStatusCodeResult(HttpStatusCode.OK); } return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } } }<file_sep>using Callboard.App.Data.DbContext; using Callboard.App.Data.Mappers; using Callboard.App.General.Entities; using Callboard.App.General.Loggers.Main; using Callboard.App.General.Results; using System.Collections.Generic; using System.Data; using System.Linq; namespace Callboard.App.Data.DataContext.Realizations.Db { internal class CountryDbContext : EntityDbContext<Country>, IDataContext<Country> { public CountryDbContext(IDbContext context, ILoggerWrapper logger) : base(context, logger) { } public IResult<Country> Delete(int id) { string procedureName = "sp_delete_country_by_id"; var values = new Dictionary<string, object> { { "CountryId", id } }; return base.Execute(procedureName, values); } public IResult<IReadOnlyCollection<Country>> GetAll() { string procedureName = "sp_select_country"; var mapper = new Mapper<DataSet, Country> { MapCollection = MapCountryCollection }; return base.GetAll(procedureName, mapper); } public IResult<Country> GetById(int id) { string procedureName = "sp_get_country_by_id"; var values = new Dictionary<string, object> { { "CountryId", id } }; var mapper = new Mapper<DataSet, Country> { MapItem = MapCountry }; return base.Get(procedureName, mapper, values); } public IResult<Country> Save(Country obj) { string procedureName = "sp_save_country"; var mapper = new Mapper<DataSet, Country> { MapValues = MapCountryValues }; return base.Save(obj, procedureName, mapper); } private IDictionary<string, object> MapCountryValues(Country country) { return new Dictionary<string, object> { { "CountryId", country.CountryId }, { "Name", country.Name } }; } private Country MapCountry(DataSet dataSet) { return dataSet.Tables[0].AsEnumerable().Select(this.MapCountry).FirstOrDefault(); } private IReadOnlyCollection<Country> MapCountryCollection(DataSet dataSet) { return dataSet.Tables[0].AsEnumerable().Select(this.MapCountry).ToList(); } private Country MapCountry(DataRow row) { return new Country { CountryId = row.Field<int>("CountryId"), Name = row.Field<string>("Name") }; } } }<file_sep>using Callboard.App.Data.DbContext; using Callboard.App.Data.Mappers; using Callboard.App.General.Entities; using Callboard.App.General.Loggers.Main; using Callboard.App.General.Results; using System; using System.Collections.Generic; using System.Data; using System.Linq; namespace Callboard.App.Data.DataContext.Realizations.Db { internal class CategoryDbContext : EntityDbContext<Category>, ICategoryContext { public CategoryDbContext(IDbContext context, ILoggerWrapper logger) : base(context, logger) { } public IResult<Category> GetById(int id) { string procedureName = "sp_get_category_by_id"; var mapper = new Mapper<DataSet, Category> { MapItem = this.MapCategory }; var values = new Dictionary<string, object> { { "CategoryId", id } }; return base.Get(procedureName, mapper, values); } public IResult<IReadOnlyCollection<Category>> GetAll() { string procedureName = "sp_select_category"; var mapper = new Mapper<DataSet, Category> { MapCollection = this.MapCategoryCollection }; return base.GetAll(procedureName, mapper); } public IResult<IReadOnlyCollection<Category>> GetSubcategories(int categoryId) { var procedureName = "sp_select_subcategory_by_parentid"; var values = new Dictionary<string, object> { { "ParentId", categoryId } }; var mapper = new Mapper<DataSet, Category> { MapCollection = this.MapCategoryCollection }; return base.GetAll(procedureName, mapper, values); } public IResult<IReadOnlyCollection<Category>> GetMainCategories() { string procedureName = "sp_select_main_category"; var mapper = new Mapper<DataSet, Category> { MapCollection = this.MapCategoryCollection }; return base.GetAll(procedureName, mapper); } public IResult<Category> Save(Category obj) { var procedureName = "sp_save_category"; var mapper = new Mapper<DataSet, Category> { MapValues = this.MapCategoryValues }; return base.Save(obj, procedureName, mapper); } public IResult<Category> Delete(int id) { string procedureName = "sp_delete_category_by_id"; var values = new Dictionary<string, object> { { "CategoryId", id } }; return base.Execute(procedureName, values); } private IDictionary<string, object> MapCategoryValues(Category category) { return new Dictionary<string, object> { { "CategoryId", category.CategoryId }, { "Name", category.Name }, { "ParentId", category.ParentId } }; } private IReadOnlyCollection<Category> MapCategoryCollection(DataSet dataSet) { return dataSet.Tables[0].AsEnumerable() .Select(categoryRow => { Category category = null; try { category = this.MapCategory(categoryRow); } catch (InvalidCastException ex) { _logger.ErrorFormat($"Cannot cast Category.\n{ ex.Message }"); } return category; }) .Where(category => category != null) .ToList(); } private Category MapCategory(DataSet dataSet) { return dataSet.Tables[0].AsEnumerable().Select(category => { return MapCategory(category); }).First(); } private Category MapCategory(DataRow row) { return new Category { CategoryId = row.Field<int>("CategoryId"), Name = row.Field<string>("Name"), ParentId = row.Field<int?>("ParentId") ?? default(int) }; } } }<file_sep>using Callboard.App.General.Entities.Commercial; using System.Collections.Generic; namespace Callboard.App.Web.Models { public class CommercialViewModel { public IReadOnlyCollection<Commercial> Commercials { get; set; } } }<file_sep>using Callboard.App.Data.DbContext; using Callboard.App.Data.Mappers; using Callboard.App.General.Entities; using Callboard.App.General.Entities.Data; using Callboard.App.General.Loggers.Main; using Callboard.App.General.Results; using Microsoft.SqlServer.Server; using System; using System.Collections.Generic; using System.Data; using System.Linq; namespace Callboard.App.Data.DataContext.Realizations.Db { internal class AdDbContext : EntityDbContext<Ad>, IAdContext { public AdDbContext(IDbContext context, ILoggerWrapper logger) : base(context, logger) { } public IResult<Ad> Delete(int id) { string procedureName = "sp_delete_ad_by_id"; var values = new Dictionary<string, object> { { "AdId", id } }; return base.Execute(procedureName, values); } public IResult<IReadOnlyCollection<Ad>> GetAdsByCategoryId(int categoryId) { string procedureName = "sp_select_ad_by_categoryid"; var values = new Dictionary<string, object> { { "CategoryId", categoryId } }; var mapper = new Mapper<DataSet, Ad> { MapCollection = MapAdCollection }; return base.GetAll(procedureName, mapper, values); } public IResult<IReadOnlyCollection<Ad>> GetAdsForUser(int userId) { string procedureName = "sp_select_ad_by_userid"; var values = new Dictionary<string, object> { { "UserId", userId } }; var mapper = new Mapper<DataSet, Ad> { MapCollection = MapAdCollection }; return base.GetAll(procedureName, mapper, values); } public IResult<IReadOnlyCollection<Ad>> GetAll() { var procedureName = "sp_select_ad"; var mapper = new Mapper<DataSet, Ad> { MapCollection = MapAdCollection }; return base.GetAll(procedureName, mapper); } public IResult<IReadOnlyCollection<Ad>> SearchByName(string name) { var procedureName = "sp_search_ad_by_name"; var mapper = new Mapper<DataSet, Ad> { MapCollection = MapAdCollection }; var values = new Dictionary<string, object> { { "SearchName", name } }; return base.GetAll(procedureName, mapper, values); } public IResult<IReadOnlyCollection<Ad>> Search(SearchConfiguration searchConfiguration) { string procedureName = "sp_search_ad"; var mapper = new Mapper<DataSet, Ad> { MapCollection = MapAdCollection }; var values = new Dictionary<string, object> { { "Name", searchConfiguration.Name }, { "State", searchConfiguration.State }, { "Kind", searchConfiguration.Kind }, { "CountryId", searchConfiguration.CountryId }, { "AreaId", searchConfiguration.AreaId }, { "CityId", searchConfiguration.CityId }, { "MinPrice", searchConfiguration.MinPrice }, { "MaxPrice", searchConfiguration.MaxPrice }, { "Categories", this.MapCategoriesToValues(searchConfiguration.Categories) } }; return base.GetAll(procedureName, mapper, values); } private IReadOnlyCollection<SqlDataRecord> MapCategoriesToValues(IReadOnlyCollection<Category> categories) { if (categories == null || categories?.Count < 1) { return null; } var records = new List<SqlDataRecord>(); var metadata = new SqlMetaData[] { new SqlMetaData("CategoryId", SqlDbType.Int) }; foreach (var item in categories) { SqlDataRecord record = new SqlDataRecord(metadata); record.SetValue(0, item.CategoryId); records.Add(record); } return records; } private IReadOnlyCollection<Ad> MapAdCollection(DataSet dataSet) { return dataSet.Tables[0].AsEnumerable().Select(ad => { Ad newAd = null; try { newAd = this.MapAd(ad, dataSet.Tables[1], dataSet.Tables[2]); } catch (InvalidCastException ex) { _logger.InfoFormat($"Cannot map Ad.\n{ ex.Message }"); } return newAd; }).Where(x => x != null).ToList(); } private Ad MapAd(DataRow row, DataTable categories, DataTable images) { int adId = row.Field<int>("AdId"); return new Ad { AdId = adId, Kind = row.Field<string>("Kind"), State = row.Field<string>("State"), Name = row.Field<string>("Name"), Price = row.Field<decimal>("Price"), CreationDate = row.Field<DateTime>("CreationDate"), Location = new Location { LocationId = row.Field<int>("LocationId"), City = row.Field<string>("City"), Area = row.Field<string>("Area"), Country = row.Field<string>("Country") }, Categories = this.MapCategories(categories, adId), Images = this.MapImages(images, adId) }; } private IReadOnlyCollection<Image> MapImages(DataTable imagesTable, int adId) { return imagesTable.AsEnumerable() .Where(x => x.Field<int>("AdId") == adId) .Select(this.MapImage).ToList(); } private IReadOnlyCollection<Category> MapCategories(DataTable categoriesTable, int adId) { return categoriesTable.AsEnumerable() .Where(x => x.Field<int>("AdId") == adId) .Select(this.MapCategory).ToList(); } private Category MapCategory(DataRow row) { return new Category { CategoryId = row.Field<int>("CategoryId"), Name = row.Field<string>("Name"), ParentId = row.Field<int?>("ParentId") ?? default(int) }; } private Image MapImage(DataRow row) { return new Image { ImageId = row.Field<int>("ImageId"), Data = row.Field<byte[]>("Data"), Extension = row.Field<string>("Extension") }; } } }<file_sep>function deleteArea(areaId, areaContainerId) { if (areaId) { $.post('/Area/DeleteArea', { areaId: areaId }); } $("#" + areaContainerId).remove(); }<file_sep>using Callboard.App.General.Entities; using Callboard.App.General.Entities.Data; using Callboard.App.General.Exceptions; using Callboard.App.General.Results; using System; using System.Collections.Generic; using Data = Callboard.App.Data.Services; namespace Callboard.App.Business.Services.Realizations { internal class AdService : IAdService { private Data::IAdService _adProvider; public AdService(Data::IAdService adProvider) { _adProvider = adProvider ?? throw new NullReferenceException(nameof(adProvider)); } public IResult<IReadOnlyCollection<Ad>> GetAds() { return _adProvider.GetAll(); } public IResult<IReadOnlyCollection<Ad>> GetAdsByCategoryId(int categoryId) { this.CheckId(categoryId); return _adProvider.GetAdsByCategoryId(categoryId); } public IResult<IReadOnlyCollection<Ad>> SearchByName(string name) { if (string.IsNullOrEmpty(name)) { return null; } return _adProvider.SearchByName(name); } public IResult<IReadOnlyCollection<Ad>> Search(SearchConfiguration searchConfiguration) { searchConfiguration = searchConfiguration ?? throw new NullReferenceException(nameof(searchConfiguration)); return _adProvider.Search(searchConfiguration); } public IResult<Ad> Delete(int id) { this.CheckId(id); return _adProvider.Delete(id); } public IResult<IReadOnlyCollection<Ad>> GetAdsForUser(int userId) { this.CheckId(userId); return _adProvider.GetAdsForUser(userId); } private void CheckId(int id) { if (id < 1) { throw new InvalidIdException(nameof(id)); } } } }<file_sep>using Callboard.App.General.Entities; namespace Callboard.App.Web.Models { public class CityViewModel { public int AreaId { get; set; } public City City { get; set; } } }<file_sep>using Callboard.App.Data.Repositories; using Callboard.App.General.Entities; using Callboard.App.General.Exceptions; using Callboard.App.General.Results; using System; using System.Collections.Generic; namespace Callboard.App.Business.Services.Realizations { internal class StateService : IEntityService<State> { private IRepository<State> _stateRepository; public StateService(IRepository<State> stateRepository) { _stateRepository = stateRepository ?? throw new NullReferenceException(nameof(stateRepository)); } public IResult<State> Delete(int id) { this.CheckId(id); return _stateRepository.Delete(id); } public IResult<IReadOnlyCollection<State>> GetAll() { return _stateRepository.GetAll(); } public IResult<State> GetById(int id) { this.CheckId(id); return _stateRepository.GetById(id); } public IResult<State> Save(State obj) { obj = obj ?? throw new NullReferenceException(nameof(obj)); return _stateRepository.Save(obj); } private void CheckId(int id) { if (id < 1) { throw new InvalidIdException(nameof(id)); } } } }<file_sep>function callActionAsync(obj, url, updateTargetId, complete) { $.ajax({ url: url, type: 'GET', contentType: 'application/json', data: obj, dataType: "html", success: function (data) { $('#' + updateTargetId).html(data); }, error: function () { $('#' + updateTargetId).html("Sorry:( Nothing found"); }, complete: complete }); } function getDataAsync(obj, url, successFunc, errorFunc) { execActionAsync(obj, url, 'GET', successFunc, errorFunc); } function postDataAsync(obj, url, successFunc, errorFunc) { execActionAsync(obj, url, 'POST', successFunc, errorFunc); } function execActionAsync(obj, url, type, successFunc, errorFunc) { $.ajax({ url: url, type: type, contentType: 'application/json', data: obj, dataType: "json", success: successFunc, error: errorFunc }); }<file_sep>using Callboard.App.General.Entities.Auth; using Callboard.App.General.Results; using System; using Data = Callboard.App.Data.Services; namespace Callboard.App.Business.Services.Realizations { internal class MembershipService : IMembershipService { private Data::IMembershipService _membershipProvider; public MembershipService(Data::IMembershipService membershipProvider) { _membershipProvider = membershipProvider ?? throw new NullReferenceException(nameof(membershipProvider)); } public IResult<MembershipUser> CreateUser(string login, string password) { if (string.IsNullOrEmpty(login) || string.IsNullOrEmpty(password)) { return null; } return _membershipProvider.CreateUser(login, password); } } }<file_sep>using Callboard.App.General.Entities; using Callboard.App.General.Exceptions; using Callboard.App.General.Results; using System; using Data = Callboard.App.Data.Services; namespace Callboard.App.Business.Services.Realizations { internal class AdDetailsService : IAdDetailsService { private Data::IAdDetailsService _adDetailsProvider; public AdDetailsService(Data::IAdDetailsService adDetailsProvider) { //_checker = checker ?? throw new NullReferenceException(nameof(checker)); //_checker.CheckForNull(adDetailsProvider); _adDetailsProvider = adDetailsProvider ?? throw new NullReferenceException(nameof(adDetailsProvider)); } public IResult<AdDetails> GetById(int id) { //_checker.CheckId(id); if (id < 1) { throw new InvalidIdException(nameof(id)); } return _adDetailsProvider.GetById(id); } public IResult<AdDetails> Save(AdDetails obj) { //_checker.CheckForNull(obj); if (obj == null) { throw new NullReferenceException(nameof(obj)); } return _adDetailsProvider.Save(obj); } } }<file_sep>using System.Configuration; namespace Callboard.Service.Commercial.Config { public class CommercialConfigSection : ConfigurationSection { [ConfigurationProperty("pathways")] public ImagePathCollection Pathways { get { return ((ImagePathCollection)(base["pathways"])); } } } } <file_sep>function loadRolesOptions() { getDataAsync(null, '/Role/GetRoles', fillRoles); } let fillRoles = function (data) { let select = $("#roles-select"); let roles = JSON.parse(data.Roles); for (let i = 0; i < roles.length; i++) { let option = createOption('', roles[i].RoleId, roles[i].Name); select.append(option); } }<file_sep>namespace Callboard.App.General.Entities { public class Kind { public int KindId { get; set; } public string Type { get; set; } } }<file_sep>using System.Web.Optimization; namespace Callboard.App.Web { public class BundleConfig { public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new StyleBundle("~/bundles/css") .IncludeDirectory("~/Content/css", "*.css", true)); bundles.Add(new ScriptBundle("~/bundles/ajax") .Include("~/Scripts/jquery-1.10.2.min.js") .Include("~/Scripts/jquery.unobtrusive-ajax.min.js") .Include("~/Scripts/ajax-helper.js")); bundles.Add(new ScriptBundle("~/bundles/validate") .Include("~/Scripts/jquery.validate.min.js") .Include("~/Scripts/jquery.validate.unobtrusive.min.js")); bundles.Add(new ScriptBundle("~/search") .IncludeDirectory("~/Scripts/Search", "*.js", false) .Include("~/Scripts/Common/category-load.js")); bundles.Add(new ScriptBundle("~/categoryMenu") .IncludeDirectory("~/Scripts/CategoryMenu", "*.js", false)); bundles.Add(new ScriptBundle("~/categoryListBox") .IncludeDirectory("~/Scripts/CategoryListBox", "*.js", false)); bundles.Add(new ScriptBundle("~/user") .IncludeDirectory("~/Scripts/User", "*.js", false)); bundles.Add(new ScriptBundle("~/location") .IncludeDirectory("~/Scripts/Location", "*.js", false)); bundles.Add(new ScriptBundle("~/addetails") .IncludeDirectory("~/Scripts/AdDetails", "*.js", false) .Include("~/Scripts/Common/category-load.js")); bundles.Add(new ScriptBundle("~/common") .Include("~/Scripts/Common/common.js")); bundles.Add(new ScriptBundle("~/admin") .Include("~/Scripts/Admin/user-edit.js")); bundles.Add(new ScriptBundle("~/roles-list") .IncludeDirectory("~/Scripts/UserRoleEditList", "*.js", false)); bundles.Add(new ScriptBundle("~/countries-edit") .IncludeDirectory("~/Scripts/CountriesEdit", "*.js", false)); bundles.Add(new ScriptBundle("~/areas-edit") .IncludeDirectory("~/Scripts/AreasEdit", "*.js", false)); bundles.Add(new ScriptBundle("~/cities-edit") .IncludeDirectory("~/Scripts/CitiesEdit", "*.js", false)); bundles.Add(new ScriptBundle("~/kinds-edit") .IncludeDirectory("~/Scripts/KindsEdit", "*.js", false)); bundles.Add(new ScriptBundle("~/states-edit") .IncludeDirectory("~/Scripts/StatesEdit", "*.js", false)); bundles.Add(new ScriptBundle("~/categories-edit") .IncludeDirectory("~/Scripts/CategoriesEdit", "*.js", false)); } } }<file_sep>using Callboard.App.General.Entities; using System.Collections.Generic; namespace Callboard.App.Web.Models { public class AreaListViewModel { public int CountryId { get; set; } public IReadOnlyCollection<Area> Areas { get; set; } } }<file_sep>function loadCities(areaId, citiesContainerId) { callActionAsync({ areaId: areaId }, '/City/GetCityEditListByAreaId', citiesContainerId); $("#area-id").val(areaId); }<file_sep>using Callboard.App.Business.Services; using Callboard.App.General.ResultExtensions; using Callboard.App.Web.Attributes; using Callboard.App.Web.Models; using Newtonsoft.Json; using System; using System.Net; using System.Web.Mvc; namespace Callboard.App.Web.Controllers { public class CityController : Controller { private ICityService _cityService; public CityController(ICityService cityService) { if (cityService == null) { throw new NullReferenceException(nameof(cityService)); } _cityService = cityService; } [AjaxOnly] public ActionResult GetCitiesByAreaId(int areaId) { var citiesResult = _cityService.GetCitiesByAreaId(areaId); if (citiesResult.IsSuccess()) { var cities = citiesResult.GetSuccessResult(); var citiesData = JsonConvert.SerializeObject(cities); return Json(new { Cities = citiesData }, JsonRequestBehavior.AllowGet); } return new HttpStatusCodeResult(HttpStatusCode.NotFound); } [Editor] public ActionResult GetCityEditListByAreaId(int areaId) { var citiesResult = _cityService.GetCitiesByAreaId(areaId); if (citiesResult.IsSuccess()) { var cities = citiesResult.GetSuccessResult(); var cityListModel = new CityListViewModel { AreaId = areaId, Cities = cities }; return PartialView("CityEditList", cityListModel); } return new HttpStatusCodeResult(HttpStatusCode.NotFound); } [Editor] [AjaxOnly] [HttpPost] public ActionResult DeleteCity(int cityId) { var cityDeleteResult = _cityService.Delete(cityId); if (cityDeleteResult.IsNone()) { return new HttpStatusCodeResult(HttpStatusCode.OK); } return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } [Editor] [AjaxOnly] [HttpPost] public ActionResult SaveCity(string cityViewModelData) { cityViewModelData = cityViewModelData ?? string.Empty; var cityViewModel = JsonConvert.DeserializeObject<CityViewModel>(cityViewModelData); if (cityViewModel != null) { var citySaveResult = _cityService.Save(cityViewModel.AreaId, cityViewModel.City); if (citySaveResult.IsNone()) { return new HttpStatusCodeResult(HttpStatusCode.OK); } } return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } } }<file_sep>using Callboard.App.General.Entities; using System.Collections.Generic; namespace Callboard.App.Web.Models { public class CityListViewModel { public int AreaId { get; set; } public IReadOnlyCollection<City> Cities { get; set; } } }<file_sep>using Callboard.App.Business.Services; using Callboard.App.General.ResultExtensions; using Callboard.App.Web.Models; using System; using System.Net; using System.Web.Mvc; namespace Callboard.App.Web.Controllers { public class AccountController : Controller { private ILogginService _logginService; public AccountController(ILogginService logginService) { if (logginService == null) { throw new NullReferenceException(nameof(logginService)); } _logginService = logginService; } public ActionResult Login(string returnUrl) { ViewBag.ReturnUrl = returnUrl; return View(new LoginViewModel()); } [HttpPost] public ActionResult Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return View(model); } var logginResult = _logginService.Login(model.Login, model.Password); if (logginResult.IsFailure()) { ViewBag.ErrorMessage = logginResult.GetFailureMessage(); return View(model); } returnUrl = Url.IsLocalUrl(returnUrl) ? returnUrl : "/Home/Index"; return Redirect(returnUrl); } public ActionResult Register(string returnUrl) { ViewBag.ReturnUrl = returnUrl; return View(new RegisterViewModel()); } [HttpPost] public ActionResult Register(RegisterViewModel model, string returnUrl) { if (!ModelState.IsValid) { return View(model); } var logginResult = _logginService.Register(model.Login, model.Password); if (logginResult.IsFailure()) { ViewBag.ErrorMessage = logginResult.GetFailureMessage(); return View(model); } returnUrl = Url.IsLocalUrl(returnUrl) ? returnUrl : "/Home/Index"; return Redirect(returnUrl); } public ActionResult Logout() { var logginResult = _logginService.Logout(); if (logginResult.IsNone()) { return RedirectToAction("Login", "Account"); } return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } } }<file_sep>function addRoleForUser(userId) { let select = $("#roles-select"); let roleId = select.find(':selected').val(); if (roleId) { $.post('/Role/SetRoleForUser', { userId: userId, roleId: roleId }, function () { fillRolesForUser(userId); }); } }<file_sep>function deleteCategory(categoryId, updateTargetId) { if (categoryId) { $.post('/Category/DeleteCategory', { categoryId: categoryId }); } $("#" + updateTargetId).remove(); }<file_sep>function searchByParams() { runPreloader(); let searchConfiguration = getSearchConfiguration(); callActionAsync({ searchConfigurationData: JSON.stringify(searchConfiguration) }, "/Search/SearchAds", "search-result", searchComplete); } let getSearchConfiguration = function () { let name = $("#name").val(); let countryId = $("#countries").find(":selected").val(); let areaId = $("#areas").find(":selected").val(); let cityId = $("#cities").find(":selected").val(); let kind = $("#kinds").find(":selected").val(); let state = $("#states").find(":selected").val(); let minPrice = getMinPrice(); let maxPrice = getMaxPrice(); let categories = getSearchCategories(); let searchConfiguration = { Name: name, CountryId: countryId, AreaId: areaId, CityId: cityId, Kind: kind, State: state, MinPrice: minPrice, MaxPrice: maxPrice, Categories: categories }; return searchConfiguration; } let getMinPrice = function () { let minPrice = $("#min-price").val(); if (minPrice === '') { minPrice = 0; } return minPrice; } let getMaxPrice = function () { let maxPrice = $("#max-price").val(); if (maxPrice === '') { maxPrice = 0; } return maxPrice; } let getSearchCategories = function () { let categories = []; $("#categories").find(":checked").each(function () { let category = { CategoryId: $(this).data('categoryId') }; categories.push(category); }); return categories; } let searchComplete = function () { stopPreloader(); $('.carousel').carousel(); } let runPreloader = function () { let searchResultContainer = $("#search-result"); searchResultContainer.empty(); let preloader = $("#preloader"); preloader.removeClass('none'); preloader.addClass('active'); } let stopPreloader = function () { let preloader = $("#preloader"); preloader.removeClass('active'); preloader.addClass('none'); }<file_sep>function deleteState(stateId, stateContainerId) { if (stateId) { $.post('/State/DeleteState', { stateId: stateId }); } $("#" + stateContainerId).remove(); }<file_sep>namespace Callboard.App.General.Results.Realizations { public class SuccessResult<T> : ISuccessResult<T> { private T _value; public SuccessResult(T value) { _value = value; } public T Value => _value; } }<file_sep>using Callboard.App.Data.DbContext; using Callboard.App.Data.Exceptions; using Callboard.App.Data.Helpers; using Callboard.App.Data.Mappers; using Callboard.App.General.Loggers.Main; using Callboard.App.General.Results; using Callboard.App.General.Results.Realizations; using System; using System.Collections.Generic; using System.Data; namespace Callboard.App.Data.DataContext.Realizations.Db { internal abstract class EntityDbContext<T> where T : class { protected IDbContext _context; protected ILoggerWrapper _logger; public EntityDbContext(IDbContext context, ILoggerWrapper logger) { _context = context ?? throw new NullReferenceException(nameof(context)); _logger = logger ?? throw new NullReferenceException(nameof(logger)); this.InitializeConnection(); } private void InitializeConnection() { var config = new ConfigHelper(_logger); _context.ConnectionString = config.ConnectionString; } protected IResult<IReadOnlyCollection<T>> GetAll(string procedureName, Mapper<DataSet, T> mapper, IDictionary<string, object> values = null) { IReadOnlyCollection<T> entities = null; IResult<IReadOnlyCollection<T>> result = new NoneResult<IReadOnlyCollection<T>>(); try { using (var dataSet = _context.ExecuteProcedure(procedureName, values)) { if (this.CheckDataSet(dataSet)) { entities = mapper?.MapCollection(dataSet); } } } catch (UserException ex) { result = new FailureResult<IReadOnlyCollection<T>>(ex, ex.Message); } if (entities != null) { result = new SuccessResult<IReadOnlyCollection<T>>(entities); } return result; } protected IResult<T> Get(string procedureName, Mapper<DataSet, T> mapper, IDictionary<string, object> values = null) { T obj = default(T); IResult<T> result = new NoneResult<T>(); try { using (var dataSet = _context.ExecuteProcedure(procedureName, values)) { if (this.CheckDataSet(dataSet) && mapper != null) { obj = mapper.MapItem(dataSet); } } } catch (UserException ex) { result = new FailureResult<T>(ex, ex.Message); } if (obj != null) { result = new SuccessResult<T>(obj); } return result; } protected IResult<T> Save(T obj, string procedureName, Mapper<DataSet, T> mapper) { var values = mapper?.MapValues(obj); try { _context.ExecuteNonQuery(procedureName, values); } catch (UserException ex) { return new FailureResult<T>(ex, ex.Message); } return new NoneResult<T>(); } protected IResult<T> Execute(string procedureName, IDictionary<string, object> values = null) { try { _context.ExecuteNonQuery(procedureName, values); } catch (UserException ex) { return new FailureResult<T>(ex, ex.Message); } return new NoneResult<T>(); } private bool CheckDataSet(DataSet dataSet) { if (dataSet != null && dataSet.Tables.Count != 0) { return true; } return false; } } }<file_sep>using System; using System.Collections.Generic; namespace Callboard.App.Data.Mappers { public class Mapper<TInput, TOutput> { public Func<TInput, IReadOnlyCollection<TOutput>> MapCollection { get; set; } public Func<TInput, TOutput> MapItem { get; set; } public Func<TOutput, IDictionary<string, object>> MapValues { get; set; } } }<file_sep>using Callboard.App.General.Entities; using System.ComponentModel.DataAnnotations; using System.Web.Mvc; namespace Callboard.App.Web.Models { public class AdDetailsViewModel { public AdDetailsViewModel() { this.Location = new Location(); } [Required] [HiddenInput(DisplayValue = false)] public int AdId { get; set; } [Required] public Location Location { get; set; } [Required] public string Name { get; set; } [Required] public decimal Price { get; set; } [Required] public string Kind { get; set; } [Required] public string State { get; set; } public Image[] Images { get; set; } public Category[] Categories { get; set; } [Required] public int UserId { get; set; } public string Description { get; set; } public string AddressLine { get; set; } } }<file_sep>function getImageSrc(byteArray, extension) { console.log(byteArray); let base64 = convertByteToBase64(byteArray); let src = "data:image/" + extension + ";base64," + base64; return src; } let getFileInput = function () { let mainDiv = $("<div></div>"); mainDiv.addClass('ad__image_big valign-wrapper file-field'); let btnDiv = $("<div></div>"); btnDiv.addClass('btn green center-auto'); let span = $("<span></span>"); span.append('<i class="material-icons">add</i>') let input = $('<input />'); input.attr('type', 'file'); btnDiv.append(span); btnDiv.append(input); mainDiv.append(btnDiv); return mainDiv; } function addImage(updateTargerId) { let imagesContainer = $("#" + updateTargerId); let fileInput = getFileInput(); fileInput.addClass('col s3'); let img = getImage(); img.on('click', function () { this.remove(); }); fileInput.on('change', function (evt) { let tgt = evt.target || window.event.srcElement; let files = tgt.files; if (FileReader && files && files.length) { var fileReader = new FileReader(); fileReader.onload = function () { img.attr('src', fileReader.result); } fileReader.readAsDataURL(files[0]); imagesContainer.append(img); fileInput.remove(); addImage(updateTargerId); } }); imagesContainer.append(fileInput); } let getImage = function () { let img = $("<img />"); img.addClass('col s3'); img.addClass('ad__image_big'); return img; }<file_sep>using Callboard.App.General.Entities.Commercial; using Callboard.App.General.Results; using System.Collections.Generic; namespace Callboard.App.Business.Services { public interface ICommercialService { IResult<IReadOnlyCollection<Commercial>> GetCommercials(); } }<file_sep>using Callboard.App.General.Entities; using Callboard.App.General.Exceptions; using Callboard.App.General.Results; using System; using System.Collections.Generic; using Data = Callboard.App.Data.Services; namespace Callboard.App.Business.Services.Realizations { internal class CityService : ICityService { private Data::ICityService _cityRepository; public CityService(Data::ICityService cityRepository) { _cityRepository = cityRepository ?? throw new NullReferenceException(nameof(cityRepository)); } public IResult<City> Delete(int id) { this.CheckId(id); return _cityRepository.Delete(id); } public IResult<IReadOnlyCollection<City>> GetAll() { return _cityRepository.GetAll(); } public IResult<City> GetById(int id) { this.CheckId(id); return _cityRepository.GetById(id); } public IResult<IReadOnlyCollection<City>> GetCitiesByAreaId(int areaId) { this.CheckId(areaId); return _cityRepository.GetCitiesByAreaId(areaId); } public IResult<City> Save(int areaId, City obj) { obj = obj ?? throw new NullReferenceException(nameof(obj)); return _cityRepository.Save(areaId, obj); } private void CheckId(int id) { if (id < 1) { throw new InvalidIdException(nameof(id)); } } } }<file_sep>using System; using System.Configuration; using System.ServiceModel; namespace Callboard.App.Data.ServiceContext { public interface IServiceContext<T> { TOut GetData<TOut>(string endpointConfigurationName, Configuration configuration, EndpointAddress remoteAddress, Func<T, TOut> getData); } }<file_sep>using Callboard.App.General.Entities; using Callboard.App.General.Results; using System.Collections.Generic; namespace Callboard.App.Data.DataContext { public interface ICategoryContext : IDataContext<Category> { IResult<IReadOnlyCollection<Category>> GetSubcategories(int categoryId); IResult<IReadOnlyCollection<Category>> GetMainCategories(); } }<file_sep>function getKindList(kindsContainerId) { callActionAsync(null, '/Kind/GetKindEditList', kindsContainerId); }<file_sep>using System.Collections.Generic; namespace Callboard.App.General.Entities { public class User { public int UserId { get; set; } public string Name { get; set; } public byte[] PhotoData { get; set; } public string PhotoExtension { get; set; } public IReadOnlyCollection<Phone> Phones { get; set; } public IReadOnlyCollection<Mail> Mails { get; set; } } }<file_sep>using Callboard.App.IoC.DependencyResolution; namespace Callboard.App.Web.DependencyResolution { using StructureMap; public static class IoC { public static IContainer Initialize() { ContainerBootstrap.Initialize(); return ContainerBootstrap.Container; } } }<file_sep>using Callboard.App.General.Entities; namespace Callboard.App.Web.Models { public class AreaViewModel { public int CountryId { get; set; } public Area Area { get; set; } } }<file_sep>using Callboard.App.Data.DataContext; using Callboard.App.General.Entities; using Callboard.App.General.Results; using System; using System.Collections.Generic; namespace Callboard.App.Data.Repositories.Realizations { internal class CategoryRepository : ICategoryRepository { private ICategoryContext _context; public CategoryRepository(ICategoryContext context) { _context = context ?? throw new NullReferenceException(nameof(context)); } public IResult<Category> Delete(int id) { return _context.Delete(id); } public IResult<IReadOnlyCollection<Category>> GetAll() { return _context.GetAll(); } public IResult<Category> GetById(int id) { return _context.GetById(id); } public IResult<IReadOnlyCollection<Category>> GetSubcategories(int categoryId) { return _context.GetSubcategories(categoryId); } public IResult<IReadOnlyCollection<Category>> GetMainCategories() { return _context.GetMainCategories(); } public IResult<Category> Save(Category obj) { return _context.Save(obj); } } }<file_sep>function loadKinds() { getDataAsync(null, "/Kind/GetKinds", renderKinds); } let renderKinds = function (data) { let kindsContainer = getKindsContainer(); kindsContainer.empty(); let kinds = JSON.parse(data.Kinds); for (let i = 0; i < kinds.length; i++) { let option = createOption('kind', kinds[i].Type, kinds[i].Type); kindsContainer.append(option); } } let getKindsContainer = function () { return $('#kinds'); }<file_sep>function getCityList(areaId, citiesContainerId) { callActionAsync({ areaId: areaId }, '/City/GetCityEditListByAreaId', citiesContainerId); }<file_sep>function loadCountries() { getDataAsync(null, "/Country/GetCountries", renderCountries); } let renderCountries = function (data) { clearCountries(); let countriesContainer = getCountriesContainer(); let countries = JSON.parse(data.Countries); for (let i = 0; i < countries.length; i++) { let option = createOption('countryId', countries[i].CountryId, countries[i].Name); countriesContainer.append(option); } } let clearCountries = function () { clearAreas(); let countriesContainer = getCountriesContainer(); countriesContainer.empty(); let defaultOption = createOption('countryId', 0, "--- Choose country ---"); countriesContainer.append(defaultOption); } let getCountriesContainer = function () { return $('#countries'); }<file_sep>using Callboard.App.Data.DbContext; using Callboard.App.Data.Mappers; using Callboard.App.General.Entities; using Callboard.App.General.Loggers.Main; using Callboard.App.General.Results; using System; using System.Collections.Generic; using System.Data; using System.Linq; namespace Callboard.App.Data.DataContext.Realizations.Db { internal class AreaDbContext : EntityDbContext<Area>, IAreaContext { public AreaDbContext(IDbContext context, ILoggerWrapper logger) : base(context, logger) { } public IResult<Area> Delete(int id) { string procedureName = "sp_delete_area_by_id"; var values = new Dictionary<string, object> { { "AreaId", id } }; return base.Execute(procedureName, values); } public IResult<IReadOnlyCollection<Area>> GetAll() { var procedureName = "sp_select_area"; var mapper = new Mapper<DataSet, Area> { MapCollection = this.MapAreaCollection }; return base.GetAll(procedureName, mapper); } public IResult<IReadOnlyCollection<Area>> GetAreasByCountryId(int countryId) { var procedureName = "sp_select_area_by_countryid"; var values = new Dictionary<string, object> { { "CountryId", countryId } }; var mapper = new Mapper<DataSet, Area> { MapCollection = this.MapAreaCollection }; return base.GetAll(procedureName, mapper, values); } public IResult<Area> GetById(int id) { string procedureName = "sp_get_area_by_id"; var values = new Dictionary<string, object> { { "AreaId", id } }; var mapper = new Mapper<DataSet, Area> { MapItem = this.MapArea }; return base.Get(procedureName, mapper, values); } public IResult<Area> Save(int countryId, Area obj) { string procedureName = "sp_save_area"; var values = this.MapAreaValues(countryId, obj); return base.Execute(procedureName, values); } private IDictionary<string, object> MapAreaValues(int countryId, Area area) { return new Dictionary<string, object> { { "CountryId", countryId }, { "AreaId", area.AreaId }, { "Name", area.Name } }; } private Area MapArea(DataSet dataSet) { return dataSet.Tables[0].AsEnumerable().Select(this.MapArea).FirstOrDefault(); } private IReadOnlyCollection<Area> MapAreaCollection(DataSet dataSet) { return dataSet.Tables[0].AsEnumerable() .Select(this.MapArea) .ToList(); } private Area MapArea(DataRow row) { return new Area { AreaId = row.Field<int>("AreaId"), Name = row.Field<string>("Name") }; } } }<file_sep>using Callboard.App.Data.Repositories; using Callboard.App.General.Entities; using Callboard.App.General.Exceptions; using Callboard.App.General.Results; using System; using System.Collections.Generic; namespace Callboard.App.Business.Services.Realizations { internal class CountryProvider : IEntityService<Country> { private IRepository<Country> _countryRepository; public CountryProvider(IRepository<Country> countryRepository) { _countryRepository = countryRepository ?? throw new NullReferenceException(nameof(countryRepository)); } public IResult<Country> Delete(int id) { this.CheckId(id); return _countryRepository.Delete(id); } public IResult<IReadOnlyCollection<Country>> GetAll() { return _countryRepository.GetAll(); } public IResult<Country> GetById(int id) { this.CheckId(id); return _countryRepository.GetById(id); } public IResult<Country> Save(Country obj) { obj = obj ?? throw new NullReferenceException(nameof(obj)); return _countryRepository.Save(obj); } private void CheckId(int id) { if (id < 1) { throw new InvalidIdException(nameof(id)); } } } }<file_sep>using System.Collections.Generic; namespace Callboard.App.General.Entities.Auth { public class MembershipUser { public MembershipUser() { } public MembershipUser(int id, string name) : this(id, name, null) { } public MembershipUser(int id, string name, IReadOnlyCollection<Role> roles) { this.UserId = id; this.Name = name; this.Roles = roles; } public int UserId { get; set; } public string Name { get; set; } public IReadOnlyCollection<Role> Roles { get; set; } } }<file_sep>function deleteCountry(countryId, countryContainerId) { if (countryId) { $.post('/Country/DeleteCountry', { countryId: countryId }); } $("#" + countryContainerId).remove(); }<file_sep>function fillLocation(updateTargetId) { let locationContainer = $("#" + updateTargetId); locationContainer.empty(); let countrySelect = getCountrySelect(); let areaSelect = getAreaSelect(); let citySelect = getCitySelect(); locationContainer.append(countrySelect); locationContainer.append(areaSelect); locationContainer.append(citySelect); loadCountries(); } let getCountrySelect = function () { let countrySelect = getSelectForLocation(); countrySelect.attr('id', 'countries'); countrySelect.on('change', function () { fillAreas(this.options[this.selectedIndex].value); }); let defaultOption = createOption('', 0, '--- Choose country ---'); defaultOption.attr('selected', 'selected'); countrySelect.append(defaultOption); return countrySelect; } let getAreaSelect = function () { let areaSelect = getSelectForLocation(); areaSelect.attr('id', 'areas'); areaSelect.on('change', function () { fillCities(this.options[this.selectedIndex].value); }); let defaultOption = createOption('', 0, '--- Choose area ---'); defaultOption.attr('selected', 'selected'); areaSelect.append(defaultOption); return areaSelect; } let getCitySelect = function () { let citySelect = getSelectForLocation(); citySelect.attr('id', 'cities'); let defaultOption = createOption('', 0, '--- Choose city ---'); defaultOption.attr('selected', 'selected'); citySelect.append(defaultOption); return citySelect; } let getSelectForLocation = function () { let select = $("<select></select>"); select.addClass('input-field col s4 block'); return select; }<file_sep>using Callboard.App.Data.DbContext; using Callboard.App.Data.Mappers; using Callboard.App.General.Entities; using Callboard.App.General.Entities.Auth; using Callboard.App.General.Loggers.Main; using Callboard.App.General.Results; using System.Collections.Generic; using System.Data; using System.Linq; namespace Callboard.App.Data.DataContext.Realizations.Db { internal class MembershipDbContext : EntityDbContext<MembershipUser>, IMembershipContext { public MembershipDbContext(IDbContext context, ILoggerWrapper logger) : base(context, logger) { } public IResult<MembershipUser> GetUserByLogin(string login) { var procedureName = "sp_get_membership_user_by_login"; var values = new Dictionary<string, object> { { "Login", login } }; var mapper = new Mapper<DataSet, MembershipUser> { MapItem = MapMembershipUser }; return base.Get(procedureName, mapper, values); } public IResult<MembershipUser> ValidateUser(string login, string password) { var procedureName = "sp_get_membership_user_by_login_password"; var values = new Dictionary<string, object> { { "Login", login }, { "Password", <PASSWORD> } }; var mapper = new Mapper<DataSet, MembershipUser> { MapItem = MapMembershipUser }; return base.Get(procedureName, mapper, values); } public IResult<MembershipUser> CreateUser(string login, string password) { var procedureName = "sp_create_membership"; var values = new Dictionary<string, object> { { "Login", login }, { "Password", password } }; var mapper = new Mapper<DataSet, MembershipUser> { MapItem = MapMembershipUser }; return base.Get(procedureName, mapper, values); } private MembershipUser MapMembershipUser(DataSet dataSet) { return dataSet.Tables[0].AsEnumerable().Select(user => { return this.MapMembershipUser(user, dataSet.Tables[1]); }).FirstOrDefault(); } private MembershipUser MapMembershipUser(DataRow row, DataTable roles) { return new MembershipUser { UserId = row.Field<int>("UserId"), Name = row.Field<string>("Name"), Roles = this.MapRoleCollection(roles) }; } private IReadOnlyCollection<Role> MapRoleCollection(DataTable dataTable) { return dataTable.AsEnumerable().Select(this.MapRole).ToList(); } private Role MapRole(DataRow row) { return new Role { RoleId = row.Field<int>("RoleId"), Name = row.Field<string>("Name") }; } } }<file_sep>using Callboard.App.Business.Services; using Callboard.App.General.ResultExtensions; using Callboard.App.Web.Attributes; using Callboard.App.Web.Models; using Newtonsoft.Json; using System; using System.Net; using System.Web.Mvc; namespace Callboard.App.Web.Controllers { public class AreaController : Controller { private IAreaService _areaService; public AreaController(IAreaService areaService) { if (areaService == null) { throw new NullReferenceException(nameof(areaService)); } _areaService = areaService; } [AjaxOnly] public ActionResult GetAreasByCountryId(int countryId) { var areasResult = _areaService.GetAreasByCountryId(countryId); if (areasResult.IsSuccess()) { var areas = areasResult.GetSuccessResult(); var areasData = JsonConvert.SerializeObject(areas); return Json(new { Areas = areasData }, JsonRequestBehavior.AllowGet); } return new HttpStatusCodeResult(HttpStatusCode.NotFound); } [Editor] public ActionResult GetAreaEditListByCountryId(int countryId) { var areasResult = _areaService.GetAreasByCountryId(countryId); if (areasResult.IsSuccess()) { var areas = areasResult.GetSuccessResult(); var areaModel = new AreaListViewModel { CountryId = countryId, Areas = areas }; return PartialView("AreaEditList", areaModel); } return new HttpStatusCodeResult(HttpStatusCode.NotFound); } [Editor] [AjaxOnly] [HttpPost] public ActionResult DeleteArea(int areaId) { var areaDeleteResult = _areaService.Delete(areaId); if (areaDeleteResult.IsNone()) { return new HttpStatusCodeResult(HttpStatusCode.OK); } return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } [Editor] [AjaxOnly] [HttpPost] public ActionResult SaveArea(string areaViewModelData) { areaViewModelData = areaViewModelData ?? string.Empty; var areaViewModel = JsonConvert.DeserializeObject<AreaViewModel>(areaViewModelData); if (areaViewModel != null) { var areaSaveResult = _areaService.Save(areaViewModel.CountryId, areaViewModel.Area); if (areaSaveResult.IsNone()) { return new HttpStatusCodeResult(HttpStatusCode.OK); } } return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } } }<file_sep>using Callboard.App.General.Results; namespace Callboard.App.General.ResultExtensions { public static class ResultExtension { public static T GetSuccessResult<T>(this IResult<T> result) { var successResult = result as ISuccessResult<T>; return successResult != null ? successResult.Value : default(T); } public static string GetFailureMessage<T>(this IResult<T> result) { var failureResult = result as IFailureResult<T>; return failureResult != null ? failureResult.ErrorMessage : string.Empty; } } }<file_sep>using Callboard.App.Data.DbContext; using Callboard.App.Data.Mappers; using Callboard.App.General.Entities; using Callboard.App.General.Loggers.Main; using Callboard.App.General.Results; using System.Collections.Generic; using System.Data; using System.Linq; namespace Callboard.App.Data.DataContext.Realizations.Db { internal class KindDbContext : EntityDbContext<Kind>, IDataContext<Kind> { public KindDbContext(IDbContext context, ILoggerWrapper logger) : base(context, logger) { } public IResult<Kind> Delete(int id) { string procedureName = "sp_delete_kind_by_id"; var values = new Dictionary<string, object> { { "KindId", id } }; return base.Execute(procedureName, values); } public IResult<IReadOnlyCollection<Kind>> GetAll() { string procedureName = "sp_select_kind"; var mapper = new Mapper<DataSet, Kind> { MapCollection = this.MapKindCollection }; return base.GetAll(procedureName, mapper); } public IResult<Kind> GetById(int id) { string procedureName = "sp_get_kind_by_id"; var mapper = new Mapper<DataSet, Kind> { MapItem = this.MapKind }; var values = new Dictionary<string, object> { { "KindId", id } }; return base.Get(procedureName, mapper, values); } public IResult<Kind> Save(Kind obj) { string procedureName = "sp_save_kind"; var mapper = new Mapper<DataSet, Kind> { MapValues = this.MapKindValues }; return base.Save(obj, procedureName, mapper); } private IDictionary<string, object> MapKindValues(Kind kind) { return new Dictionary<string, object> { { "KindId", kind.KindId }, { "Type", kind.Type } }; } private IReadOnlyCollection<Kind> MapKindCollection(DataSet dataSet) { return dataSet.Tables[0].AsEnumerable().Select(this.MapKind).ToList(); } private Kind MapKind(DataSet dataSet) { return dataSet.Tables[0].AsEnumerable().Select(this.MapKind).FirstOrDefault(); } private Kind MapKind(DataRow row) { return new Kind { KindId = row.Field<int>("KindId"), Type = row.Field<string>("Type") }; } } }<file_sep>using Callboard.App.Data.DbContext; using Callboard.App.Data.Mappers; using Callboard.App.General.Entities; using Callboard.App.General.Loggers.Main; using Callboard.App.General.Results; using Microsoft.SqlServer.Server; using System.Collections.Generic; using System.Data; using System.Linq; namespace Callboard.App.Data.DataContext.Realizations.Db { internal class UserDbContext : EntityDbContext<User>, IDataContext<User> { public UserDbContext(IDbContext context, ILoggerWrapper logger) : base(context, logger) { } public IResult<User> Delete(int id) { string procedureName = "sp_delete_user_by_id"; var values = new Dictionary<string, object> { { "UserId", id } }; return base.Execute(procedureName, values); } public IResult<IReadOnlyCollection<User>> GetAll() { string procedureName = "sp_select_user"; var mapper = new Mapper<DataSet, User> { MapCollection = this.MapUserCollection }; return base.GetAll(procedureName, mapper); } public IResult<User> GetById(int id) { string procedureName = "sp_get_user_by_userid"; var values = new Dictionary<string, object> { { "UserId", id } }; var mapper = new Mapper<DataSet, User> { MapItem = this.MapUser }; return base.Get(procedureName, mapper, values); } public IResult<User> Save(User obj) { string procedureName = "sp_save_user"; var mapper = new Mapper<DataSet, User> { MapValues = this.MapUserValues }; return base.Save(obj, procedureName, mapper); } private IDictionary<string, object> MapUserValues(User user) { return new Dictionary<string, object> { { "UserId", user.UserId }, { "Name", user.Name }, { "PhotoData", user.PhotoData }, { "PhotoExtension", user.PhotoExtension }, { "Phones", this.GetPhoneRecords(user.Phones) }, { "Mails", this.GetMailRecords(user.Mails) } }; } private IReadOnlyCollection<SqlDataRecord> GetMailRecords(IReadOnlyCollection<Mail> mails) { if (mails == null || mails?.Count < 1) { return null; } var records = new List<SqlDataRecord>(); var metadata = new SqlMetaData[] { new SqlMetaData("MailId", SqlDbType.Int), new SqlMetaData("Email", SqlDbType.NVarChar, -1) }; foreach (var item in mails) { SqlDataRecord record = new SqlDataRecord(metadata); record.SetValue(0, item.MailId); record.SetValue(1, item.Email); records.Add(record); } return records; } private IReadOnlyCollection<SqlDataRecord> GetPhoneRecords(IReadOnlyCollection<Phone> phones) { if (phones == null || phones?.Count < 1) { return null; } var records = new List<SqlDataRecord>(); var metadata = new SqlMetaData[] { new SqlMetaData("PhoneId", SqlDbType.Int), new SqlMetaData("Number", SqlDbType.NVarChar, 50) }; foreach (var item in phones) { SqlDataRecord record = new SqlDataRecord(metadata); record.SetValue(0, item.PhoneId); record.SetValue(1, item.Number); records.Add(record); } return records; } private User MapUser(DataSet dataSet) { return dataSet.Tables[0].AsEnumerable().Select(user => { return MapUser(user, dataSet.Tables[1], dataSet.Tables[2]); }).FirstOrDefault(); } private IReadOnlyCollection<User> MapUserCollection(DataSet dataSet) { return dataSet.Tables[0].AsEnumerable().Select(user => { return MapUser(user, dataSet.Tables[1], dataSet.Tables[2]); }).ToList(); } private User MapUser(DataRow row, DataTable mails, DataTable phones) { int userId = row.Field<int>("UserId"); return new User { UserId = userId, Name = row.Field<string>("Name"), PhotoData = row.Field<byte[]>("PhotoData"), PhotoExtension = row.Field<string>("PhotoExtension"), Mails = this.MapMailCollection(mails, userId), Phones = this.MapPhoneCollection(phones, userId) }; } private IReadOnlyCollection<Phone> MapPhoneCollection(DataTable phones, int userId) { return phones.AsEnumerable() .Where(phone => phone.Field<int>("UserId") == userId) .Select(phone => { return new Phone { PhoneId = phone.Field<int>("PhoneId"), Number = phone.Field<string>("Number") }; }).ToList(); } private IReadOnlyCollection<Mail> MapMailCollection(DataTable mails, int userId) { return mails.AsEnumerable() .Where(mail => mail.Field<int>("UserId") == userId) .Select(mail => { return new Mail { MailId = mail.Field<int>("MailId"), Email = mail.Field<string>("Email") }; }).ToList(); } } }<file_sep>using Callboard.App.Data.DataContext; using Callboard.App.General.Entities; using Callboard.App.General.Entities.Data; using Callboard.App.General.Results; using System; using System.Collections.Generic; namespace Callboard.App.Data.Services.Realizations { internal class AdService : IAdService { private IAdContext _context; public AdService(IAdContext context) { _context = context ?? throw new NullReferenceException(nameof(context)); } public IResult<IReadOnlyCollection<Ad>> GetAdsByCategoryId(int categoryId) { return _context.GetAdsByCategoryId(categoryId); } public IResult<IReadOnlyCollection<Ad>> GetAll() { return _context.GetAll(); } public IResult<Ad> Delete(int id) { return _context.Delete(id); } public IResult<IReadOnlyCollection<Ad>> SearchByName(string name) { return _context.SearchByName(name); } public IResult<IReadOnlyCollection<Ad>> Search(SearchConfiguration searchConfiguration) { return _context.Search(searchConfiguration); } public IResult<IReadOnlyCollection<Ad>> GetAdsForUser(int userId) { return _context.GetAdsForUser(userId); } } }<file_sep>namespace Callboard.App.General.Results.Realizations { public class NoneResult<T> : INoneResult<T> { } }<file_sep>using Callboard.App.Data.DataContext; using Callboard.App.Data.DataContext.Realizations.Db; using Callboard.App.Data.DataContext.Realizations.Service; using Callboard.App.Data.DbContext; using Callboard.App.Data.DbContext.Realizations; using Callboard.App.Data.Repositories; using Callboard.App.Data.Repositories.Realizations; using Callboard.App.Data.ServiceContext; using Callboard.App.Data.ServiceContext.Realizations; using Callboard.App.Data.Services; using Callboard.App.Data.Services.Realizations; using Callboard.App.General.Entities; using StructureMap; using Service = Callboard.App.Data.CommercialService; namespace Callboard.App.Data.DependencyResolution { public class DataRegistry : Registry { public DataRegistry() { For<IDbContext>().Use<SqlDbContext>(); For<IServiceContext<Service::ICommercialContract>>().Use<ServiceContext<Service::ICommercialContract>>(); For<ICategoryRepository>().Use<CategoryRepository>(); For<IRoleRepository>().Use<RoleRepository>(); For<IRepository<User>>().Use<UserRepository>(); For<IRepository<Country>>().Use<CountryRepository>(); For<IRepository<Kind>>().Use<KindRepository>(); For<IRepository<State>>().Use<StateRepository>(); For<ICityService>().Use<CityService>(); For<IAreaService>().Use<AreaService>(); For<IMembershipService>().Use<MembershipService>(); For<IAdService>().Use<AdService>(); For<IAdDetailsService>().Use<AdDetailsService>(); For<ICommercialService>().Use<Services.Realizations.CommercialService>(); For<ICategoryContext>().Use<CategoryDbContext>(); For<IAreaContext>().Use<AreaDbContext>(); For<ICityContext>().Use<CityDbContext>(); For<IDataContext<Country>>().Use<CountryDbContext>(); For<IDataContext<Kind>>().Use<KindDbContext>(); For<IDataContext<State>>().Use<StateDbContext>(); For<IDataContext<User>>().Use<UserDbContext>(); For<IRoleContext>().Use<RoleDbContext>(); For<IAdContext>().Use<AdDbContext>(); For<IAdDetailsContext>().Use<AdDetailsDbContext>(); For<ICommercialContext>().Use<CommercialServiceContext>(); For<IMembershipContext>().Use<MembershipDbContext>(); } } }
8cbe1df724402bcd6120e20a8e4002d0117c0b6f
[ "JavaScript", "C#", "Markdown", "SQL" ]
173
C#
Sir-MaxBro/callboard
1d81ad089693dfe949ab400b9b75be61b6ce4fa7
d7c4c41fb4500fa3209eb67e5465f0c51dc01d13
refs/heads/master
<repo_name>hoardexchange/HoardCompiler<file_sep>/GolemBuild/IBuildService.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GolemBuild { public enum BuildTaskStatus { None = 0, Queued, Started, Suceeded, Failed } public class BuildTaskStatusChangedArgs : EventArgs { public BuildTaskStatus Status { get; set; } public string Message { get; set; } } public interface IBuildService { event EventHandler<BuildTaskStatusChangedArgs> BuildTaskStatusChanged; void AddTask(CompilationTask task); bool Start(); bool Stop(); } } <file_sep>/GolemBuild/GolemCache.cs using ICSharpCode.SharpZipLib.GZip; using ICSharpCode.SharpZipLib.Tar; using System; using System.Collections.Generic; using System.IO; using System.Security.Cryptography; namespace GolemBuild { class GolemCache { class CompilerPackage { public List<string> compilers; public string hash; public byte[] data; } static List<CompilerPackage> compilerCache = new List<CompilerPackage>(); static Dictionary<string, byte[]> tasksCache = new Dictionary<string, byte[]>(); static public void Reset() { //compilerCache.Clear(); tasksCache.Clear(); } static private void AddDirectoryFilesToTar(TarArchive tarArchive, string sourceDirectory, bool recurse) { // Optionally, write an entry for the directory itself. // Specify false for recursion here if we will add the directory's files individually. TarEntry tarEntry = TarEntry.CreateEntryFromFile(sourceDirectory); tarArchive.WriteEntry(tarEntry, false); // Write each file to the tar. string[] filenames = Directory.GetFiles(sourceDirectory); foreach (string filename in filenames) { if (Path.GetExtension(filename) == ".exe" || Path.GetExtension(filename) == ".dll") { tarEntry = TarEntry.CreateEntryFromFile(filename); tarArchive.WriteEntry(tarEntry, true); } } if (recurse) { string[] directories = Directory.GetDirectories(sourceDirectory); foreach (string directory in directories) AddDirectoryFilesToTar(tarArchive, directory, recurse); } } // This function gathers and caches a CompilerPackage in memory, this CompilerPackage is a tar.gz of (hopefully) all files needed for the compilers passed as parameters. // Please note that everything is kept in memory and we don't save anything to filesystem. static public string GetCompilerPackageHash(List<string> compilers) { // See if we have this list of CompilerPackage cached already foreach(CompilerPackage compilerPackage in compilerCache) { if (compilerPackage.compilers.Count != compilers.Count) continue; bool perfectMatch = true; foreach(string cacheCompiler in compilerPackage.compilers) { bool foundCompiler = false; foreach(string compiler in compilers) { if (cacheCompiler == compiler) { foundCompiler = true; break; } } if (!foundCompiler) { perfectMatch = false; break; } } if (perfectMatch) return compilerPackage.hash; } // Create a new CompilerPackage CompilerPackage newCompilerPackage = new CompilerPackage(); newCompilerPackage.compilers = compilers; // Lets get all the .exe and .dll files in the same directory (including sub directories) as the compiler and tar.gz them. //step 1. tar file using (MemoryStream stream = new MemoryStream()) { //using (GZipOutputStream gzoStream = new GZipOutputStream(stream)) using (TarArchive tarArchive = TarArchive.CreateOutputTarArchive(stream))// gzoStream)) { foreach (string compiler in compilers) { // Package executables and necessary dlls string compilerDir = Path.GetDirectoryName(compiler); tarArchive.RootPath = compilerDir; AddDirectoryFilesToTar(tarArchive, compilerDir, true); } } newCompilerPackage.data = stream.ToArray(); } //step 2. calculate SHA1 hash of tar file using (var cryptoProvider = new SHA1CryptoServiceProvider()) { newCompilerPackage.hash = BitConverter.ToString(cryptoProvider.ComputeHash(newCompilerPackage.data)).Replace("-", string.Empty).ToLower(); } //step 3. zip file (we cannot calculate SHA1 from zip since zip contains timestamps and metadata and each compression process creates different //header for zip file using (MemoryStream stream = new MemoryStream()) { using (GZipOutputStream gzoStream = new GZipOutputStream(stream)) { gzoStream.Write(newCompilerPackage.data,0, newCompilerPackage.data.Length); } newCompilerPackage.data = stream.ToArray(); } // Lets cache this for later so we don't need to redo this every time compilerCache.Add(newCompilerPackage); return newCompilerPackage.hash; } static public bool GetCompilerPackageData(string hash, out byte[] data) { data = null; foreach(CompilerPackage compilerPackage in compilerCache) { if (compilerPackage.hash == hash) { data = compilerPackage.data; return true; } } return false; } static public string RegisterTasksPackage(byte[] data) { string hash = ""; // Calculate the hash of the data using (var cryptoProvider = new SHA1CryptoServiceProvider()) { hash = BitConverter.ToString(cryptoProvider.ComputeHash(data)).Replace("-", string.Empty).ToLower(); } tasksCache[hash] = data; return hash; } static public bool GetTasksPackage(string hash, out byte[] data) { data = null; if (!tasksCache.ContainsKey(hash)) return false; data = tasksCache[hash]; return true; } } } <file_sep>/GolemBuild/DataPackage.cs  namespace GolemBuild { class DataPackage { public byte[] DataStream { get; set; } public string DataHash { get; set; } } } <file_sep>/GolemBuild/CompilationTask.cs using System.Collections.Generic; namespace GolemBuild { public class CompilationTask { public string FilePath { get; set; } public string Compiler { get; set; } public string CompilerArgs { get; set; } public string PrecompiledHeader { get; set; } public string PDB { get; set; } public string OutputPath { get; set; } public string ProjectPath { get; set; } public List<string> IncludeDirs { get; set; } public List<string> Includes { get; set; } public CompilationTask(string filePath, string compiler, string compilerArgs, string pch, string pdb, string outputPath, string projectPath, List<string> includeDirs, List<string> includes) { FilePath = filePath; Compiler = compiler; CompilerArgs = compilerArgs; PrecompiledHeader = pch; PDB = pdb; OutputPath = outputPath; ProjectPath = projectPath; IncludeDirs = includeDirs; Includes = includes; } } } <file_sep>/GolemBuild/GolemBuildService.cs using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Net.NetworkInformation; using System.Threading.Tasks; using GURestApi.Api; using GURestApi.Model; namespace GolemBuild { public class GolemBuildService : IBuildService { public class Configuration { public string GolemHubUrl { get; set; } = "http://10.30.10.121:6162"; public int GolemServerPort { get; set; } = 6000; public override bool Equals(object obj) { return base.Equals(obj as Configuration); } public bool Equals(Configuration input) { if (input == null) return false; return ( GolemHubUrl == input.GolemHubUrl || (GolemHubUrl != null && GolemHubUrl.Equals(input.GolemHubUrl)) ) && ( GolemServerPort == input.GolemServerPort ); } public override int GetHashCode() { int hashCode = 41; if (GolemHubUrl != null) hashCode = hashCode * 59 + GolemHubUrl.GetHashCode(); hashCode = hashCode * 59 + GolemServerPort.GetHashCode(); return hashCode; } } public static GolemBuildService Instance = null; public event EventHandler<BuildTaskStatusChangedArgs> BuildTaskStatusChanged; public string BuildPath = ""; public bool compilationSuccessful = false; public Configuration Options = new Configuration(); public bool IsRunning { get { return mainLoop != null; } } private Task hubInfoLoop = null; private Task mainLoop = null; private System.Threading.CancellationTokenSource cancellationSource = null; private ConcurrentQueue<CompilationTask> taskQueue = null; private int ServerPort = 6000; private string myIP = null; private GolemHttpService httpService = null; public HubInfo HubInfo { get; private set; } private PeerApi golemApi = null; private List<PeerInfo> knownPeers = new List<PeerInfo>(); private ConcurrentQueue<GolemWorker> workerPool = new ConcurrentQueue<GolemWorker>(); private int runningWorkers = 0; public GolemBuildService() { // TODO: Configure API key authorization: serviceToken //Configuration.Default.AddApiKey("X-GU-APIKEY", "YOUR_API_KEY"); // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed // Configuration.Default.AddApiKeyPrefix("X-GU-APIKEY", "Bearer"); // TODO: Configure API key authorization: systemName GURestApi.Client.Configuration.Default.AddApiKey("X-GU-APPNAME", "HoardCompiler"); // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed GURestApi.Client.Configuration.Default.AddApiKeyPrefix("X-GU-APPNAME", "Bearer"); string output = ""; foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces()) { if (item.NetworkInterfaceType == NetworkInterfaceType.Ethernet && item.OperationalStatus == OperationalStatus.Up) { foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses) { if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { output = ip.Address.ToString(); } } } } myIP = output; Instance = this; } internal string GetHttpDownloadUri(string fileName) { return "http://" + myIP + ":" + ServerPort + "/requestID/tasks/" + fileName; } internal string GetHttpUploadUri(string fileName) { return "http://" + myIP + ":" + ServerPort + "/requestID/upload/" + fileName; } public void AddTask(CompilationTask task) { taskQueue.Enqueue(task); } public int GetTaskCount() { return taskQueue.Count; } public bool WaitTasks() { while(!taskQueue.IsEmpty || runningWorkers > 0) { System.Threading.Thread.Sleep(100); } GolemCache.Reset(); return compilationSuccessful; } public bool Start() { if (mainLoop != null) throw new Exception("Service is already running!"); golemApi = new PeerApi(Options.GolemHubUrl); ServerPort = Options.GolemServerPort; taskQueue = new ConcurrentQueue<CompilationTask>(); cancellationSource = new System.Threading.CancellationTokenSource(); //run the hub info loop (peer discovery) hubInfoLoop = GolemHubQueryTask(cancellationSource.Token); //hubInfoLoop.Start(); //run main task loop mainLoop = TaskDispatcher(cancellationSource.Token); //run the http server httpService = new GolemHttpService(); httpService.Start(); return mainLoop!=null; } public bool Stop() { if (cancellationSource!=null) { cancellationSource.Cancel();//this will throw try { hubInfoLoop.Wait(); mainLoop.Wait(); } catch(Exception ex) { Logger.LogError(ex.Message); } } cancellationSource = null; hubInfoLoop = null; mainLoop = null; if (httpService != null) httpService.Stop(); httpService = null; return true; } private async Task GolemHubQueryTask(System.Threading.CancellationToken token) { //first try to connect to the hub HubInfo = await golemApi.GetHubInfoAsync(); Logger.LogMessage($"Connected to Golem Hub\n{HubInfo.ToJson()}"); while (!token.IsCancellationRequested) { try { //get all peers var peers = await golemApi.ListPeersAsync(); //synchronize peers with the knownPeers foreach (var p in peers) { if (!knownPeers.Contains(p)) { //add new workers to workerPool workerPool.Enqueue(new GolemWorker(this, p, await golemApi.GetPeerHardwareAsync(p.NodeId))); } } //TODO: do we need to do sth with workers that are not in the hub anymore? or will they die automatically? knownPeers = peers; await Task.Delay(10 * 1000, token);//do this once per 10 seconds } catch (TaskCanceledException) { } catch (Exception ex) { //probably timed out request Logger.LogMessage(ex.Message); } } } private async Task TaskDispatcher(System.Threading.CancellationToken token) { try { //we need to distribute work from the queue while (true) { while (taskQueue.Count > 0 && !token.IsCancellationRequested) { //get number of available tasks (this can only increase from another thread, so should be fine) int taskQueueSize = taskQueue.Count; //get first available worker GolemWorker worker = null; if (workerPool.TryDequeue(out worker)) { System.Threading.Interlocked.Increment(ref runningWorkers); Logger.LogMessage("Worker " + worker.Peer.NodeId + " started"); worker.ClearTasks(); List<string> compilersUsed = new List<string>(); //get the number of tasks to process int taskCount = Math.Min(worker.TaskCapacity, taskQueueSize); for (int i = 0; i < taskCount; ++i) { CompilationTask task = null; if (taskQueue.TryDequeue(out task)) { if (!compilersUsed.Contains(task.Compiler)) compilersUsed.Add(task.Compiler); worker.AddTask(task); } } string hash = GolemCache.GetCompilerPackageHash(compilersUsed); DeploymentSpecImage specImg = new DeploymentSpecImage("SHA1:" + hash, "http://" + myIP + ":" + ServerPort + "/requestID/compiler/" + hash); //create deployment DeploymentSpec spec = new DeploymentSpec(EnvType.Hd, specImg, "Compiler", new List<string>() { }); worker.Dispatch(golemApi, spec, () => { workerPool.Enqueue(worker); Logger.LogMessage("Worker " + worker.Peer.NodeId + " finished"); System.Threading.Interlocked.Decrement(ref runningWorkers); }); } } await Task.Delay(1000, token); } } catch(TaskCanceledException) { } } } } <file_sep>/GolemBuild/GolemBuild.cs using ICSharpCode.SharpZipLib.Tar; using Microsoft.Build.Evaluation; using Microsoft.Build.Utilities; using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using System.Threading; namespace GolemBuild { public class GolemBuild { const bool runDistributed = true; // TODO: Figure out if we are attached to a broker or not const bool runVerbose = false; // TODO: Add this as a checkbox somewhere private List<CompilationTask> pchTasks = new List<CompilationTask>(); private List<CompilationTask> tasks = new List<CompilationTask>(); private List<CustomBuildTask> customBuildTasks = new List<CustomBuildTask>(); private List<CustomBuildTask> customBuildTasksParallel = new List<CustomBuildTask>(); public static string golemBuildTasksPath = ""; public bool BuildProject(string projPath, string configuration, string platform) { ProjectCollection projColl = new ProjectCollection(); //load the project Project project = projColl.LoadProject(projPath); string projectPath = Path.GetDirectoryName(project.FullPath); string golemBuildPath = Path.Combine(projectPath, "GolemBuild"); Directory.CreateDirectory(golemBuildPath); // Clear GolemBuild directory System.IO.DirectoryInfo di = new DirectoryInfo(golemBuildPath); foreach (FileInfo file in di.GetFiles()) { file.Delete(); } foreach (DirectoryInfo dir in di.GetDirectories()) { dir.Delete(true); } Logger.LogMessage("--- Compiling " + Path.GetFileNameWithoutExtension(projPath) + " " + configuration + " " + platform + " with GolemBuild ---"); if (project != null) { project.SetGlobalProperty("Configuration", configuration); project.SetGlobalProperty("Platform", platform); project.ReevaluateIfNecessary(); CreateCompilationTasks(project, platform); CallPreBuildEvents(project); if (customBuildTasks.Count > 0) { Logger.LogMessage("Running Custom Build Tasks..."); if (!CustomBuildTasks(project)) { Logger.LogError("- Custom Build Tasks failed -"); return false; } } if (pchTasks.Count > 0) { Logger.LogMessage("Compiling Precompiled Headers..."); if (!BuildPCHTasks(project)) { Logger.LogError("- Compilation failed -"); return false; } } if (runDistributed) { /*Logger.LogMessage("Packaging tasks..."); if (!PackageTasks(project)) { Logger.LogError("- Packaging failed -"); return false; }*/ if (tasks.Count > 0) { Logger.LogMessage("Queueing tasks..."); if (!QueuePackagedTasks(project)) { Logger.LogError("- Queueing failed -"); return false; } Logger.LogMessage("Waiting for external build..."); if (!GolemBuildService.Instance.WaitTasks()) { Logger.LogError("- External Compilation failed -"); return false; } } } else { Logger.LogMessage("Compiling..."); if (!BuildTasks(project)) { Logger.LogError("- Compilation failed -"); return false; } } CallPreLinkEvents(project); if (tasks.Count > 0) { Logger.LogMessage("Linking..."); string outputFile; if (!LinkProject(project, platform, out outputFile)) { Logger.LogError("- Linking failed -"); return false; } Logger.LogMessage("-> " + outputFile); } Logger.LogMessage("- Compilation successful -"); CallPostBuildEvents(project); return true; } Logger.LogError("Could not load project " + projPath); return false; } private void AddDirectoryFilesToTar(TarArchive tarArchive, string sourceDirectory, bool recurse) { // Optionally, write an entry for the directory itself. // Specify false for recursion here if we will add the directory's files individually. TarEntry tarEntry = TarEntry.CreateEntryFromFile(sourceDirectory); tarArchive.WriteEntry(tarEntry, false); // Write each file to the tar. string[] filenames = Directory.GetFiles(sourceDirectory); foreach (string filename in filenames) { tarEntry = TarEntry.CreateEntryFromFile(filename); tarArchive.WriteEntry(tarEntry, true); } if (recurse) { string[] directories = Directory.GetDirectories(sourceDirectory); foreach (string directory in directories) AddDirectoryFilesToTar(tarArchive, directory, recurse); } } private bool QueuePackagedTasks(Project project) { string projectPath = Path.GetDirectoryName(project.FullPath); string golemBuildPath = Path.Combine(projectPath, "GolemBuild"); GolemBuildService.Instance.BuildPath = golemBuildPath; GolemBuildService.Instance.compilationSuccessful = true; // Start building packaged tasks for (int i = 0; i < tasks.Count; i++) { GolemBuildService.Instance.AddTask(tasks[i]); } return true; } private bool BuildPackagedTasks(Project project) { string projectPath = Path.GetDirectoryName(project.FullPath); string golemBuildPath = Path.Combine(projectPath, "GolemBuild"); string golemBuildTasksPath = Path.Combine(projectPath, "GolemBuildTasks"); Process[] processes = new Process[tasks.Count]; bool[] hasFinished = new bool[tasks.Count]; bool[] hasErrored = new bool[tasks.Count]; bool compilationSucceeded = true; // Start building packaged tasks for (int i = 0; i < tasks.Count; i++) { string taskPath = Path.Combine(golemBuildTasksPath, Path.GetFileNameWithoutExtension(tasks[i].FilePath)); processes[i] = new Process(); processes[i].StartInfo.FileName = "cmd.exe"; processes[i].StartInfo.WindowStyle = ProcessWindowStyle.Hidden; processes[i].StartInfo.UseShellExecute = false; processes[i].StartInfo.RedirectStandardInput = true; processes[i].StartInfo.RedirectStandardOutput = true; processes[i].StartInfo.RedirectStandardError = true; processes[i].StartInfo.CreateNoWindow = true; processes[i].Start(); int index = i; // Make copy of i, else the lambda captures are wrong... processes[i].OutputDataReceived += (sender, e) => { if (e.Data != null) { string output = e.Data; if (output.Contains(" error") || output.Contains("fatal error")) { Logger.LogError("[ERROR] " + tasks[index].FilePath + ": " + output); hasErrored[index] = true; compilationSucceeded = false; } else if (output.Contains("warning")) { Logger.LogMessage("[WARNING] " + tasks[index].FilePath + ": " + output); } } }; processes[i].ErrorDataReceived += (sender, e) => { if (e.Data != null) { string output = e.Data; Logger.LogError("[ERROR] " + tasks[index].FilePath + ": " + output); hasErrored[index] = true; compilationSucceeded = false; } }; processes[i].BeginOutputReadLine(); processes[i].BeginErrorReadLine(); processes[i].StandardInput.WriteLine("@echo off"); processes[i].StandardInput.WriteLine(taskPath[0] + ":"); // Change drive processes[i].StandardInput.WriteLine("cd \"" + taskPath + "\""); // CD processes[i].StandardInput.WriteLine("golembuild"); // Build processes[i].StandardInput.WriteLine("exit"); } // Finish all compilation processes bool stillRunning = true; while (stillRunning) { bool allFinished = true; for (int i = 0; i < tasks.Count; i++) { if (processes[i].HasExited) { if (!hasFinished[i]) { hasFinished[i] = true; if (!hasErrored[i]) { Logger.LogMessage("[SUCCESS] " + tasks[i].FilePath); // Copy files from output folder to GolemBuild folder string taskPath = Path.Combine(golemBuildTasksPath, Path.GetFileNameWithoutExtension(tasks[i].FilePath)); string outputPath = Path.Combine(taskPath, "output"); foreach (string file in Directory.EnumerateFiles(outputPath)) { File.Copy(file, Path.Combine(golemBuildPath, Path.GetFileName(file))); } } } } else { allFinished = false; } } if (allFinished) stillRunning = false; else Thread.Sleep(25); } return compilationSucceeded; } private bool BuildPCHTasks(Project project) { string projectPath = Path.GetDirectoryName(project.FullPath); // Print tasks for (int i = 0; i < pchTasks.Count; ++i) { var task = pchTasks[i]; Logger.LogMessage(string.Format("PCH Task [#{0}]: {1} {2} {3} {4}", i, task.Compiler, task.CompilerArgs, task.FilePath, task.OutputPath)); } Process[] processes = new Process[pchTasks.Count]; bool[] hasFinished = new bool[pchTasks.Count]; bool[] hasErrored = new bool[pchTasks.Count]; bool compilationSucceeded = true; // Start all compilation processes for (int i = 0; i < pchTasks.Count; i++) { processes[i] = new Process(); processes[i].StartInfo.FileName = "cmd.exe";//task.Compiler; processes[i].StartInfo.WindowStyle = ProcessWindowStyle.Hidden; processes[i].StartInfo.UseShellExecute = false; processes[i].StartInfo.RedirectStandardInput = true; processes[i].StartInfo.RedirectStandardOutput = true; processes[i].StartInfo.RedirectStandardError = true; processes[i].StartInfo.CreateNoWindow = true; processes[i].Start(); int index = i; // Make copy of i, else the lambda captures are wrong... processes[i].OutputDataReceived += (sender, e) => { if (e.Data != null) { string output = e.Data; if (output.Contains(" error") || output.Contains("fatal error")) { Logger.LogError("[ERROR] " + pchTasks[index].FilePath + ": " + output); hasErrored[index] = true; compilationSucceeded = false; } else if (output.Contains("warning")) { Logger.LogMessage("[WARNING] " + pchTasks[index].FilePath + ": " + output); } } }; processes[i].ErrorDataReceived += (sender, e) => { if (e.Data != null) { string output = e.Data; Logger.LogError("[ERROR] " + pchTasks[index].FilePath + ": " + output); hasErrored[index] = true; compilationSucceeded = false; } }; processes[i].BeginOutputReadLine(); processes[i].BeginErrorReadLine(); processes[i].StandardInput.WriteLine(projectPath[0] + ":"); // Change drive processes[i].StandardInput.WriteLine("cd " + projectPath); // CD string compilerArgs = pchTasks[i].CompilerArgs; string includeDirString = ""; foreach (string includeDir in pchTasks[i].IncludeDirs) { if (includeDir.Length > 0) includeDirString += " /I \"" + includeDir + "\""; } compilerArgs += includeDirString; Directory.CreateDirectory(Path.Combine(projectPath, Path.GetDirectoryName(pchTasks[i].OutputPath))); compilerArgs += " /Fp\"" + pchTasks[i].OutputPath + "\" "; compilerArgs += " /Fo\"" + Path.Combine(projectPath, "GolemBuild", Path.ChangeExtension(pchTasks[i].FilePath, ".obj")) + "\" "; processes[i].StandardInput.WriteLine("\"" + pchTasks[i].Compiler + "\" " + compilerArgs + pchTasks[i].FilePath); // Execute task processes[i].StandardInput.WriteLine("exit"); } // Finish all compilation processes bool stillRunning = true; while (stillRunning) { bool allFinished = true; for (int i = 0; i < pchTasks.Count; i++) { if (processes[i].HasExited) { if (!hasFinished[i]) { hasFinished[i] = true; if (!hasErrored[i]) { Logger.LogMessage("[SUCCESS] " + pchTasks[i].FilePath); } } } else { allFinished = false; } } if (allFinished) stillRunning = false; else Thread.Sleep(25); } return compilationSucceeded; } private bool CustomBuildTasks(Project project) { string projectPath = Path.GetDirectoryName(project.FullPath); string golemBuildPath = Path.Combine(projectPath, "GolemBuild"); // Sequential custom build tasks for (int i = 0; i < customBuildTasks.Count; i++) { bool shouldDebugLog = false; // Create batch file string batchPath = Path.Combine(golemBuildPath, "customBuildTask" + i + ".bat"); StreamWriter batch = File.CreateText(batchPath); batch.WriteLine("@echo off"); batch.WriteLine(customBuildTasks[i].Command); batch.Close(); Process process = new Process(); process.StartInfo.FileName = "cmd.exe"; process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.CreateNoWindow = true; process.Start(); if (shouldDebugLog) { Logger.LogError("[DEBUG] " + batchPath); int index = i; // Make copy of i, else the lambda captures are wrong... process.OutputDataReceived += (sender, e) => { if (e.Data != null) { string output = e.Data; if (output.Contains(" error") || output.Contains("fatal error")) { Logger.LogError("[ERROR] " + customBuildTasks[index].FilePath + ": " + output); } else if (output.Contains("warning")) { Logger.LogMessage("[WARNING] " + customBuildTasks[index].FilePath + ": " + output); } } }; process.ErrorDataReceived += (sender, e) => { if (e.Data != null) { string output = e.Data; Logger.LogError("[ERROR] " + customBuildTasks[index].FilePath + ": " + output); } }; } process.BeginOutputReadLine(); process.BeginErrorReadLine(); if (customBuildTasks[i].Message.Length > 0) Logger.LogMessage(customBuildTasks[i].Message); else Logger.LogMessage("CustomBuildTask" + i); process.StandardInput.WriteLine("@echo off"); // Echo off process.StandardInput.WriteLine(projectPath[0] + ":"); // Change drive process.StandardInput.WriteLine("cd \"" + projectPath + "\""); // CD process.StandardInput.WriteLine("\"" + batchPath + "\""); // Execute task process.StandardInput.WriteLine("exit"); process.WaitForExit(); } // Parallel custom build tasks Process[] processes = new Process[customBuildTasksParallel.Count]; bool[] hasFinished = new bool[customBuildTasksParallel.Count]; // Start all custom build processes for (int i = 0; i < customBuildTasksParallel.Count; i++) { bool shouldDebugLog = false; // Create batch file string batchPath = Path.Combine(golemBuildPath, "customBuildTaskParallel" + i + ".bat"); StreamWriter batch = File.CreateText(batchPath); batch.WriteLine("@echo off"); batch.WriteLine(customBuildTasksParallel[i].Command); batch.Close(); processes[i] = new Process(); processes[i].StartInfo.FileName = "cmd.exe"; processes[i].StartInfo.WindowStyle = ProcessWindowStyle.Hidden; processes[i].StartInfo.UseShellExecute = false; processes[i].StartInfo.RedirectStandardInput = true; processes[i].StartInfo.RedirectStandardOutput = true; processes[i].StartInfo.RedirectStandardError = true; processes[i].StartInfo.CreateNoWindow = true; processes[i].Start(); if (shouldDebugLog) { Logger.LogError("[DEBUG] " + batchPath); int index = i; // Make copy of i, else the lambda captures are wrong... processes[i].OutputDataReceived += (sender, e) => { if (e.Data != null) { string output = e.Data; if (output.Contains(" error") || output.Contains("fatal error")) { Logger.LogError("[ERROR] " + tasks[index].FilePath + ": " + output); } else if (output.Contains("warning")) { Logger.LogMessage("[WARNING] " + tasks[index].FilePath + ": " + output); } } }; processes[i].ErrorDataReceived += (sender, e) => { if (e.Data != null) { string output = e.Data; Logger.LogError("[ERROR] " + tasks[index].FilePath + ": " + output); } }; } processes[i].BeginOutputReadLine(); processes[i].BeginErrorReadLine(); if (customBuildTasksParallel[i].Message.Length > 0) Logger.LogMessage("[STARTING] " + customBuildTasksParallel[i].Message); else Logger.LogMessage("[STARTING] CustomBuildTaskParallel" + i); processes[i].StandardInput.WriteLine("@echo off"); // Echo off processes[i].StandardInput.WriteLine(projectPath[0] + ":"); // Change drive processes[i].StandardInput.WriteLine("cd \"" + projectPath + "\""); // CD processes[i].StandardInput.WriteLine("\"" + batchPath + "\""); // Execute task processes[i].StandardInput.WriteLine("exit"); } // Finish all compilation processes bool stillRunning = true; while (stillRunning) { bool allFinished = true; for (int i = 0; i < customBuildTasksParallel.Count; i++) { if (processes[i].HasExited) { if (!hasFinished[i]) { hasFinished[i] = true; if (customBuildTasksParallel[i].Message.Length > 0) Logger.LogMessage("[SUCCESS] " + customBuildTasksParallel[i].Message); else Logger.LogMessage("[SUCCESS] CustomBuildTaskParallel" + i); } } else { allFinished = false; } } if (allFinished) stillRunning = false; else Thread.Sleep(25); } return true; } private bool BuildTasks(Project project) { string projectPath = Path.GetDirectoryName(project.FullPath); for (int i=0;i<tasks.Count;++i) { var task = tasks[i]; Logger.LogMessage(string.Format("Task [#{0}]: {1} {2} {3} {4}", i, task.Compiler, task.CompilerArgs, task.FilePath, task.OutputPath)); } Process[] processes = new Process[tasks.Count]; bool[] hasFinished = new bool[tasks.Count]; bool[] hasErrored = new bool[tasks.Count]; bool compilationSucceeded = true; // Start all compilation processes for (int i = 0; i < tasks.Count; i++) { processes[i] = new Process(); processes[i].StartInfo.FileName = "cmd.exe"; processes[i].StartInfo.WindowStyle = ProcessWindowStyle.Hidden; processes[i].StartInfo.UseShellExecute = false; processes[i].StartInfo.RedirectStandardInput = true; processes[i].StartInfo.RedirectStandardOutput = true; processes[i].StartInfo.RedirectStandardError = true; processes[i].StartInfo.CreateNoWindow = true; processes[i].Start(); int index = i; // Make copy of i, else the lambda captures are wrong... processes[i].OutputDataReceived += (sender, e) => { if (e.Data != null) { string output = e.Data; if (output.Contains(" error") || output.Contains("fatal error")) { Logger.LogError("[ERROR] " + tasks[index].FilePath + ": " + output); hasErrored[index] = true; compilationSucceeded = false; } else if (output.Contains("warning")) { Logger.LogMessage("[WARNING] " + tasks[index].FilePath + ": " + output); } } }; processes[i].ErrorDataReceived += (sender, e) => { if (e.Data != null) { string output = e.Data; Logger.LogError("[ERROR] " + tasks[index].FilePath + ": " + output); hasErrored[index] = true; compilationSucceeded = false; } }; processes[i].BeginOutputReadLine(); processes[i].BeginErrorReadLine(); processes[i].StandardInput.WriteLine(projectPath[0] + ":"); // Change drive processes[i].StandardInput.WriteLine("cd " + projectPath); // CD string compilerArgs = tasks[i].CompilerArgs; string includeDirString = ""; foreach (string includeDir in tasks[i].IncludeDirs) { if (includeDir.Length > 0) includeDirString += " /I \"" + includeDir + "\""; } compilerArgs += includeDirString; compilerArgs += " /Fo\"" + Path.Combine(projectPath, "GolemBuild", Path.ChangeExtension(tasks[i].FilePath, ".obj")) + "\" "; processes[i].StandardInput.WriteLine("\"" + tasks[i].Compiler + "\" " + compilerArgs + " " + tasks[i].FilePath); // Execute task processes[i].StandardInput.WriteLine("exit"); } // Finish all compilation processes bool stillRunning = true; while(stillRunning) { bool allFinished = true; for (int i = 0; i < tasks.Count; i++) { if (processes[i].HasExited) { if (!hasFinished[i]) { hasFinished[i] = true; if (!hasErrored[i]) { Logger.LogMessage("[SUCCESS] " + tasks[i].FilePath); } } } else { allFinished = false; } } if (allFinished) stillRunning = false; else Thread.Sleep(25); } return compilationSucceeded; } bool LinkProject(Project project, string platform, out string outputFile) { string projectPath = Path.GetDirectoryName(project.FullPath); // Linking string configurationType = project.GetPropertyValue("ConfigurationType"); outputFile = ""; string VCTargetsPath = project.GetPropertyValue("VCTargetsPathEffective"); if (string.IsNullOrEmpty(VCTargetsPath)) { Logger.LogError("Failed to evaluate VCTargetsPath variable on " + System.IO.Path.GetFileName(project.FullPath) + ". Is this a supported version of Visual Studio?"); return false; } string BuildDllPath = VCTargetsPath + (VCTargetsPath.Contains("v110") ? "Microsoft.Build.CPPTasks.Common.v110.dll" : "Microsoft.Build.CPPTasks.Common.dll"); Assembly CPPTasksAssembly = Assembly.LoadFrom(BuildDllPath); string linkerPath = ""; object linkTask = null; string linkerOptions = ""; string importLibrary = ""; if (configurationType == "StaticLibrary") { var libDefinitions = project.ItemDefinitions["Lib"]; linkTask = Activator.CreateInstance(CPPTasksAssembly.GetType("Microsoft.Build.CPPTasks.LIB")); linkerOptions = GenerateTaskCommandLine(linkTask, new string[] { "OutputFile" }, libDefinitions.Metadata); outputFile = libDefinitions.GetMetadataValue("OutputFile").Replace('\\', '/'); linkerPath = GetLibPath(project, platform); } else // Exe or DLL { var linkDefinitions = project.ItemDefinitions["Link"]; linkTask = Activator.CreateInstance(CPPTasksAssembly.GetType("Microsoft.Build.CPPTasks.Link")); linkerOptions = GenerateTaskCommandLine(linkTask, new string[] { "OutputFile", "ProfileGuidedDatabase" }, linkDefinitions.Metadata); outputFile = linkDefinitions.GetMetadataValue("OutputFile").Replace('\\', '/'); linkerPath = GetLinkerPath(project, platform); if (configurationType == "DynamicLibrary") { importLibrary = linkDefinitions.GetMetadataValue("ImportLibrary").Replace('\\', '/'); } } Directory.CreateDirectory(Path.Combine(projectPath, Path.GetDirectoryName(outputFile))); bool linkSuccessful = true; Process linkerProcess = new Process(); linkerProcess.StartInfo.FileName = "cmd.exe"; linkerProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; linkerProcess.StartInfo.UseShellExecute = false; linkerProcess.StartInfo.RedirectStandardInput = true; linkerProcess.StartInfo.RedirectStandardOutput = true; linkerProcess.StartInfo.RedirectStandardError = true; linkerProcess.StartInfo.CreateNoWindow = true; linkerProcess.Start(); linkerProcess.OutputDataReceived += (sender, e) => { if (e.Data != null) { string output = e.Data; if (output.Contains(" error") || output.Contains("fatal error")) { Logger.LogError("[LINK ERROR] " + output); linkSuccessful = false; } } }; linkerProcess.ErrorDataReceived += (sender, e) => { if (e.Data != null) { string output = e.Data; Logger.LogError("[LINK ERROR] " + output); linkSuccessful = false; } }; linkerProcess.BeginOutputReadLine(); linkerProcess.BeginErrorReadLine(); linkerProcess.StandardInput.WriteLine("@echo off"); linkerProcess.StandardInput.WriteLine("\"" + GetDevCmdPath(project, platform) + "\""); linkerProcess.StandardInput.WriteLine(projectPath[0] + ":"); // Change drive linkerProcess.StandardInput.WriteLine("cd " + projectPath); // CD string linkCommand = "\"" + linkerPath + "\" " + linkerOptions + " /OUT:\"" + outputFile + "\""; //all pch files foreach (var task in pchTasks) { linkCommand += " \"" + Path.Combine("GolemBuild", Path.ChangeExtension(Path.GetFileName(task.FilePath), ".obj")) + "\""; } //all compiled obj files foreach (var task in tasks) { linkCommand += " \"" + Path.Combine("GolemBuild", Path.ChangeExtension(Path.GetFileName(task.FilePath), ".obj")) + "\""; } Logger.LogMessage(string.Format("Linking Task: {0}", linkCommand)); linkerProcess.StandardInput.WriteLine(linkCommand); // Execute task linkerProcess.StandardInput.WriteLine("exit"); bool exited = linkerProcess.WaitForExit(30000); if (!exited) { Logger.LogError("[LINK ERROR]: Linker timed out after 30 seconds"); } if (linkSuccessful && importLibrary.Length > 0) { Logger.LogMessage("Import library: " + importLibrary); } return linkSuccessful; } private void CreateCompilationTasks(Project project, string platform) { string projectPath = project.DirectoryPath; //in VS2017 this seems to be the proper one string VCTargetsPath = project.GetPropertyValue("VCTargetsPathEffective"); if (string.IsNullOrEmpty(VCTargetsPath)) { Console.WriteLine("Failed to evaluate VCTargetsPath variable on " + System.IO.Path.GetFileName(project.FullPath) + ". Is this a supported version of Visual Studio?"); return; } string BuildDllPath = VCTargetsPath + (VCTargetsPath.Contains("v110") ? "Microsoft.Build.CPPTasks.Common.v110.dll" : "Microsoft.Build.CPPTasks.Common.dll"); Assembly CPPTasksAssembly = Assembly.LoadFrom(BuildDllPath); string compilerPath = GetCompilerPath(project, platform); // Figure out include paths List<string> includePaths = new List<string>(); { string incPath = project.GetProperty("IncludePath").EvaluatedValue; string[] incPaths = incPath.Split(';'); foreach (string path in incPaths) { if (path.Length > 0 && !includePaths.Contains(path)) includePaths.Add(path.Trim('\\')); } } var customBuildItems = project.GetItems("CustomBuild"); foreach (var item in customBuildItems) { string command = item.GetMetadata("Command").EvaluatedValue; string message = item.GetMetadata("Message").EvaluatedValue; bool buildParallel = item.HasMetadata("BuildInParallel") && item.GetMetadata("BuildInParallel").EvaluatedValue == "true"; if (buildParallel) { customBuildTasksParallel.Add(new CustomBuildTask(item.EvaluatedInclude, command, message, buildParallel)); } else { customBuildTasks.Add(new CustomBuildTask(item.EvaluatedInclude, command, message, buildParallel)); } } var cItems = project.GetItems("ClCompile"); //list precompiled headers Logger.LogMessage("Disabling pch tasks as it makes no sense when precompiling cpp files..."); if (false) { foreach (var item in cItems) { if (item.DirectMetadata.Where(dmd => dmd.Name == "AdditionalIncludeDirectories").Any()) { string incPath = item.GetMetadata("AdditionalIncludeDirectories").EvaluatedValue; string[] incPaths = incPath.Split(';'); foreach (string path in incPaths) { if (!string.IsNullOrEmpty(path)) { string tPath = path; if (!Path.IsPathRooted(path)) { tPath = Path.GetFullPath(Path.Combine(project.DirectoryPath, path)); } if (tPath.Length > 0 && !includePaths.Contains(tPath)) { includePaths.Add(tPath.Trim('\\')); } } } } if (item.DirectMetadata.Any()) { if (item.DirectMetadata.Where(dmd => dmd.Name == "ExcludedFromBuild" && dmd.EvaluatedValue == "true").Any()) { //skip continue; } if (item.DirectMetadata.Where(dmd => dmd.Name == "PrecompiledHeader" && dmd.EvaluatedValue == "Create").Any()) { List<string> includes = new List<string>(); //disabled as we are now preprocessing files //IncludeParser.FindIncludes(true, project.DirectoryPath, item.EvaluatedInclude, includePaths, includes); Logger.LogMessage(">> " + item.EvaluatedInclude); var CLtask = Activator.CreateInstance(CPPTasksAssembly.GetType("Microsoft.Build.CPPTasks.CL")); CLtask.GetType().GetProperty("Sources").SetValue(CLtask, new TaskItem[] { new TaskItem() }); string args = GenerateTaskCommandLine(CLtask, new string[] { "PrecompiledHeaderOutputFile", "ProgramDataBaseFileName", "ObjectFileName", "AssemblerListingLocation" }, item.Metadata);//FS or MP? string pchOutputFile = MakeAbsolutePath(projectPath, item.GetMetadataValue("PrecompiledHeaderOutputFile")); string pdbOutputFile = MakeAbsolutePath(projectPath, item.GetMetadataValue("ProgramDataBaseFileName")); pchTasks.Add(new CompilationTask(item.EvaluatedInclude, compilerPath, args, "", pdbOutputFile, pchOutputFile, projectPath, includePaths, includes)); } } } } //list files to compile foreach (var item in cItems) { if (item.HasMetadata("AdditionalIncludeDirectories")) { string incPath = item.GetMetadata("AdditionalIncludeDirectories").EvaluatedValue; string[] incPaths = incPath.Split(';'); foreach (string path in incPaths) { if (!string.IsNullOrEmpty(path)) { string tPath = MakeAbsolutePath(projectPath,path); if (tPath.Length > 0 && !includePaths.Contains(tPath)) { includePaths.Add(tPath.Trim('\\')); } } } } List<string> includes = new List<string>(); bool ExcludePrecompiledHeader = false; if (item.DirectMetadata.Any()) { if (item.DirectMetadata.Where(dmd => dmd.Name == "ExcludedFromBuild" && dmd.EvaluatedValue == "true").Any()) continue; if (item.DirectMetadata.Where(dmd => dmd.Name == "PrecompiledHeader" && dmd.EvaluatedValue == "Create").Any()) continue; if (item.DirectMetadata.Where(dmd => dmd.Name == "PrecompiledHeader" && dmd.EvaluatedValue == "NotUsing").Any()) ExcludePrecompiledHeader = true; } //IncludeParser.FindIncludes(true, project.DirectoryPath, item.EvaluatedInclude, includePaths, includes); Logger.LogMessage(">> " + item.EvaluatedInclude); var Task = Activator.CreateInstance(CPPTasksAssembly.GetType("Microsoft.Build.CPPTasks.CL")); Task.GetType().GetProperty("Sources").SetValue(Task, new TaskItem[] { new TaskItem() }); string args = ""; if (runDistributed) { args = GenerateTaskCommandLine(Task, new string[] { "ObjectFileName", "AssemblerListingLocation", "ProgramDataBaseFileName","AdditionalIncludeDirectories" }, item.Metadata);//FS or MP? } else { args = GenerateTaskCommandLine(Task, new string[] { "ObjectFileName", "AssemblerListingLocation" }, item.Metadata);//FS or MP? } if (Path.GetExtension(item.EvaluatedInclude) == ".c") args += " /TC"; else args += " /TP"; if (!runDistributed) { args += " /FS"; // Force synchronous PDB writes // If we ever want one single pdb file per distributed node, this is how to do it } /*string buildPath = Path.Combine(Path.GetDirectoryName(project.FullPath), "GolemBuild"); if (!Directory.Exists(buildPath)) { Directory.CreateDirectory(buildPath); } args += " /Fd\"GolemBuild\\" + Path.GetFileNameWithoutExtension(item.EvaluatedInclude) + "\"";*/ // Use this for having one pdb per object file, this has issues with pch string pch = ""; if (pchTasks.Count > 0) { pch = MakeAbsolutePath(projectPath, item.GetMetadataValue("PrecompiledHeaderOutputFile")); } string pdb = MakeAbsolutePath(projectPath, item.GetMetadataValue("ProgramDataBaseFileName")); //replace precompiled header file location to absolute if (!string.IsNullOrEmpty(pch)) { Match match = Regex.Match(args, "/Fp\".+?\""); if (match.Success) args = args.Replace(match.Value,$"/Fp\"{pch}\""); } tasks.Add(new CompilationTask(Path.GetFullPath(Path.Combine(project.DirectoryPath, item.EvaluatedInclude)), compilerPath, args, pch, pdb, "", projectPath, includePaths, includes)); } return; } private string MakeAbsolutePath(string rootPath, string path) { if (Path.IsPathRooted(path)) return path; return Path.GetFullPath(Path.Combine(rootPath, path)); } private bool CallPreBuildEvents(Project project) { string projectPath = Path.GetDirectoryName(project.FullPath); var buildEvents = project.GetItems("PreBuildEvent"); foreach(var buildEvent in buildEvents) { string command = buildEvent.GetMetadataValue("Command"); if (command.Length == 0) continue; Process eventProcess = new Process(); eventProcess.StartInfo.FileName = "cmd.exe"; eventProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; eventProcess.StartInfo.UseShellExecute = false; eventProcess.StartInfo.RedirectStandardInput = true; eventProcess.StartInfo.RedirectStandardOutput = true; eventProcess.StartInfo.RedirectStandardError = true; eventProcess.StartInfo.CreateNoWindow = true; eventProcess.Start(); StreamReader eventOutput = eventProcess.StandardOutput; eventProcess.StandardInput.WriteLine("@echo off"); // Echo off eventProcess.StandardInput.WriteLine(projectPath[0] + ":"); // Drive eventProcess.StandardInput.WriteLine("cd \"" + projectPath + "\""); // CD eventProcess.StandardInput.WriteLine("Command:"); eventProcess.StandardInput.WriteLine(command); // Call event eventProcess.StandardInput.WriteLine("exit"); // Exit eventProcess.WaitForExit(); // Print results of command bool startCommand = false; while (eventOutput.Peek() >= 0) { string line = eventOutput.ReadLine(); if (line.EndsWith("Command:")) { startCommand = true; continue; } if (startCommand && line != "exit") { Logger.LogMessage(line); } } } return true; } private bool CallPreLinkEvents(Project project) { string projectPath = Path.GetDirectoryName(project.FullPath); var buildEvents = project.GetItems("PreLinkEvent"); foreach (var buildEvent in buildEvents) { string command = buildEvent.GetMetadataValue("Command"); if (command.Length == 0) continue; Process eventProcess = new Process(); eventProcess.StartInfo.FileName = "cmd.exe"; eventProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; eventProcess.StartInfo.UseShellExecute = false; eventProcess.StartInfo.RedirectStandardInput = true; eventProcess.StartInfo.RedirectStandardOutput = true; eventProcess.StartInfo.RedirectStandardError = true; eventProcess.StartInfo.CreateNoWindow = true; eventProcess.Start(); StreamReader eventOutput = eventProcess.StandardOutput; eventProcess.StandardInput.WriteLine("@echo off"); // Echo off eventProcess.StandardInput.WriteLine(projectPath[0] + ":"); // Drive eventProcess.StandardInput.WriteLine("cd \"" + projectPath + "\""); // CD eventProcess.StandardInput.WriteLine("Command:"); eventProcess.StandardInput.WriteLine(command); // Call event eventProcess.StandardInput.WriteLine("exit"); // Exit eventProcess.WaitForExit(); // Print results of command bool startCommand = false; while (eventOutput.Peek() >= 0) { string line = eventOutput.ReadLine(); if (line.EndsWith("Command:")) { startCommand = true; continue; } if (startCommand && line != "exit") { Logger.LogMessage(line); } } } return true; } private bool CallPostBuildEvents(Project project) { string projectPath = Path.GetDirectoryName(project.FullPath); var buildEvents = project.GetItems("PostBuildEvent"); foreach (var buildEvent in buildEvents) { string command = buildEvent.GetMetadataValue("Command"); if (command.Length == 0) continue; Process eventProcess = new Process(); eventProcess.StartInfo.FileName = "cmd.exe"; eventProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; eventProcess.StartInfo.UseShellExecute = false; eventProcess.StartInfo.RedirectStandardInput = true; eventProcess.StartInfo.RedirectStandardOutput = true; eventProcess.StartInfo.RedirectStandardError = true; eventProcess.StartInfo.CreateNoWindow = true; eventProcess.Start(); StreamReader eventOutput = eventProcess.StandardOutput; eventProcess.StandardInput.WriteLine("@echo off"); // Echo off eventProcess.StandardInput.WriteLine(projectPath[0] + ":"); // Drive eventProcess.StandardInput.WriteLine("cd \"" + projectPath + "\""); // CD eventProcess.StandardInput.WriteLine("Command:"); eventProcess.StandardInput.WriteLine(command); // Call event eventProcess.StandardInput.WriteLine("exit"); // Exit eventProcess.WaitForExit(); // Print results of command bool startCommand = false; while (eventOutput.Peek() >= 0) { string line = eventOutput.ReadLine(); if (line.EndsWith("Command:")) { startCommand = true; continue; } if (startCommand && line != "exit") { Logger.LogMessage(line); } } } return true; } private string GetCompilerPath(Project project, string platform) { var PlatformToolsetVersion = project.GetProperty("PlatformToolsetVersion").EvaluatedValue; string OutDir = project.GetProperty("OutDir").EvaluatedValue; string IntDir = project.GetProperty("IntDir").EvaluatedValue; var vsDir = project.GetProperty("VSInstallDir").EvaluatedValue; var WindowsSDKTarget = project.GetProperty("WindowsTargetPlatformVersion") != null ? project.GetProperty("WindowsTargetPlatformVersion").EvaluatedValue : "8.1"; var sdkDir = project.GetProperty("WindowsSdkDir").EvaluatedValue; var incPath = project.GetProperty("IncludePath").EvaluatedValue; var libPath = project.GetProperty("LibraryPath").EvaluatedValue; var refPath = project.GetProperty("ReferencePath").EvaluatedValue; var temp = project.GetProperty("Temp").EvaluatedValue; var sysRoot = project.GetProperty("SystemRoot").EvaluatedValue; //name depends on comilation platform and source platform string clPath = ""; if (platform == "x64") { clPath = project.GetProperty("VC_ExecutablePath_x64_x64").EvaluatedValue; } else { clPath = project.GetProperty("VC_ExecutablePath_x86_x86").EvaluatedValue; } if (clPath.Contains(";")) { bool foundCl = false; string[] clPaths = clPath.Split(';'); foreach(string path in clPaths) { if (File.Exists(Path.Combine(path, "cl.exe"))) { clPath = path; foundCl = true; break; } } if (!foundCl) { Logger.LogError("Could not find CL.exe!"); } } clPath = Path.Combine(clPath, "cl.exe"); return clPath; } private string GetLinkerPath(Project project, string platform) { string linkPath = ""; if (platform == "x64") { linkPath = project.GetProperty("VC_ExecutablePath_x64_x64").EvaluatedValue; } else { linkPath = project.GetProperty("VC_ExecutablePath_x86_x86").EvaluatedValue; } if (linkPath.Contains(";")) { bool foundLink = false; string[] linkPaths = linkPath.Split(';'); foreach (string path in linkPaths) { if (File.Exists(Path.Combine(path, "link.exe"))) { linkPath = path; foundLink = true; break; } } if (!foundLink) { Logger.LogError("Could not find Link.exe!"); } } linkPath = Path.Combine(linkPath, "link.exe"); return linkPath; } private string GetLibPath(Project project, string platform) { string libPath = ""; if (platform == "x64") { libPath = project.GetProperty("VC_ExecutablePath_x64_x64").EvaluatedValue; } else { libPath = project.GetProperty("VC_ExecutablePath_x86_x86").EvaluatedValue; } if (libPath.Contains(";")) { bool foundLib = false; string[] libPaths = libPath.Split(';'); foreach (string path in libPaths) { if (File.Exists(Path.Combine(path, "lib.exe"))) { libPath = path; foundLib = true; break; } } if (!foundLib) { Logger.LogError("Could not find lib.exe!"); } } libPath = Path.Combine(libPath, "lib.exe"); return libPath; } private string GetDevCmdPath(Project project, string platform) { string vsDir = ""; if (platform == "x64") { vsDir = project.GetProperty("VsInstallRoot").EvaluatedValue; vsDir = Path.Combine(vsDir, "VC", "Auxiliary", "Build", "vcvars64.bat"); } else { vsDir = project.GetProperty("VSInstallDir").EvaluatedValue; vsDir = Path.Combine(vsDir, "Common7", "Tools", "VsDevCmd.bat"); } return vsDir; } public string GetProjectInformation(string projectFile) { ProjectCollection pc = new ProjectCollection(); var proj = pc.LoadProject(projectFile); var cItems = proj.GetItems("ClCompile"); int excludedCount = 0; int precompiledHeadersCount = 0; int filesToCompileCount = 0; foreach (var item in cItems) { if (item.DirectMetadata.Any()) { if (item.DirectMetadata.Where(dmd => dmd.Name == "ExcludedFromBuild" && dmd.EvaluatedValue == "true").Any()) { ++excludedCount; continue; } if (item.DirectMetadata.Where(dmd => dmd.Name == "PrecompiledHeader" && dmd.EvaluatedValue == "Create").Any()) { ++precompiledHeadersCount; continue; } } ++filesToCompileCount; } return string.Format(CultureInfo.CurrentCulture, "Found:\n\t{0} excluded files,\n\t{1} precompiled header,\n\t{2} files to compile", excludedCount, precompiledHeadersCount, filesToCompileCount); } private string GenerateTaskCommandLine(object Task, string[] PropertiesToSkip, IEnumerable<ProjectMetadata> MetaDataList) { foreach (ProjectMetadata MetaData in MetaDataList) { if (PropertiesToSkip.Contains(MetaData.Name)) continue; var MatchingProps = Task.GetType().GetProperties().Where(prop => prop.Name == MetaData.Name); if (MatchingProps.Any() && !string.IsNullOrEmpty(MetaData.EvaluatedValue)) { string EvaluatedValue = MetaData.EvaluatedValue.Trim(); if (MetaData.Name == "AdditionalIncludeDirectories") { EvaluatedValue = EvaluatedValue.Replace("\\\\", "\\"); EvaluatedValue = EvaluatedValue.Replace(System.IO.Path.DirectorySeparatorChar, System.IO.Path.AltDirectorySeparatorChar); } PropertyInfo propInfo = MatchingProps.First(); if (propInfo.PropertyType.IsArray && propInfo.PropertyType.GetElementType() == typeof(string)) { propInfo.SetValue(Task, Convert.ChangeType(EvaluatedValue.Split(';'), propInfo.PropertyType)); } else { propInfo.SetValue(Task, Convert.ChangeType(EvaluatedValue, propInfo.PropertyType)); } } } var GenCmdLineMethod = Task.GetType().GetRuntimeMethods().Where(meth => meth.Name == "GenerateCommandLine").First(); return GenCmdLineMethod.Invoke(Task, new object[] { Type.Missing, Type.Missing}) as string; } public void ClearTasks() { tasks.Clear(); pchTasks.Clear(); } } } <file_sep>/GolemBuild/GolemWorker.cs using GURestApi.Api; using GURestApi.Model; using ICSharpCode.SharpZipLib.Tar; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace GolemBuild { class CompilerArg { public string compiler; public string args; public List<string> files = new List<string>(); public List<string> includeDirs = new List<string>(); } /// <summary> /// Worker for a particular peer. /// </summary> class GolemWorker { public PeerInfo Peer { get; set; } private PeerHardware Hardware { get; set; } private List<CompilationTask> taskList = new List<CompilationTask>(); private DeploymentSpec deployment = null; private string deploymentID = null; private GolemBuildService Service = null; public int TaskCapacity { get { return Hardware.CoreCount; } } public GolemWorker(GolemBuildService service, PeerInfo peer, PeerHardware hardware) { Service = service; Peer = peer; Hardware = hardware; } public void AddTask(CompilationTask task) { taskList.Add(task); } public void ClearTasks() { taskList.Clear(); } public void Dispatch(PeerApi golemApi, DeploymentSpec spec, Action onSuccess) { TaskProc(golemApi, spec).ContinueWith((task) => { onSuccess(); }); } private async Task TaskProc(PeerApi golemApi, DeploymentSpec spec) { try { if (deployment == null) { deployment = spec; deploymentID = await golemApi.CreateDeploymentAsync(Peer.NodeId, deployment); } //1. Take all input files and includes and package them into one TAR package + notify HttpServer about that file string packedFileName = PackFilesPreProcessed(taskList); //2. Create command to compile those source files -> cl.exe .... ExecCommand compileCmd = GenerateCompileCommand(packedFileName, taskList); var results = await golemApi.UpdateDeploymentAsync(Peer.NodeId, deploymentID, new List<Command>() { new DownloadFileCommand(Service.GetHttpDownloadUri(packedFileName), packedFileName+".tar", FileFormat.Tar), compileCmd}); bool error = false; string[] lines = results[0].Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None); foreach (string line in lines) { if (line.Contains(" error") || line.Contains("fatal error")) { Logger.LogError("[ERROR] " + packedFileName + ": " + line); error = true; } else if (line.Contains("warning")) { Logger.LogMessage("[WARNING] " + packedFileName + ": " + line); } } if (!error) { Logger.LogMessage("[SUCCESS] " + packedFileName); // Upload output.zip results = await golemApi.UpdateDeploymentAsync(Peer.NodeId, deploymentID, new List<Command>() { new UploadFileCommand(Service.GetHttpUploadUri(packedFileName), packedFileName + ".tar/output.zip") }); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } private ExecCommand GenerateCompileCommand(string fileName, List<CompilationTask> taskList) { return new ExecCommand(fileName + ".tar\\golembuild.bat", new List<string>()); //return new ExecCommand("cmd.exe", new List<string> { "/k mkdir test" });//cd " + fileName + ".tar && golembuild.bat" }); } private void AddFileToTar(TarArchive archive, string filePath, string entry, List<string> addedEntries) { if (addedEntries.Contains(entry.ToLower())) return; string[] splitPath = entry.Split('/','\\'); for(int i = 1; i < splitPath.Length; i++) { string path = splitPath[0]; for(int j = 1; j < i; j++) { path += Path.DirectorySeparatorChar+splitPath[j]; } if (addedEntries.Contains(path.ToLower())) continue; TarEntry pathEntry = TarEntry.CreateTarEntry(path); pathEntry.TarHeader.Mode = 1003; pathEntry.TarHeader.TypeFlag = TarHeader.LF_DIR; pathEntry.TarHeader.Size = 0; archive.WriteEntry(pathEntry, false); addedEntries.Add(path.ToLower()); } TarEntry fileEntry = TarEntry.CreateEntryFromFile(filePath); fileEntry.Name = entry; archive.WriteEntry(fileEntry, false); addedEntries.Add(entry.ToLower()); } private string PackFiles(List<CompilationTask> taskList) { byte[] package; using (var memoryStream = new MemoryStream()) { using (var archive = TarArchive.CreateOutputTarArchive(memoryStream)) { List<string> addedEntries = new List<string>(); // Package precompiled header if used foreach (CompilationTask task in taskList) { if (task.PrecompiledHeader.Length > 0) { TarEntry entry = TarEntry.CreateEntryFromFile(task.PrecompiledHeader); entry.Name = Path.GetFileName(task.PrecompiledHeader); archive.WriteEntry(entry, false); break; } } foreach (CompilationTask task in taskList) { // Package sourcefiles // not needed since this file is already in the task.Includes // TODO: should it be like this? { TarEntry entry = TarEntry.CreateEntryFromFile(task.FilePath); entry.Name = Path.GetFileName(task.FilePath); archive.WriteEntry(entry, false); } // Package includes string projectPath = task.ProjectPath; string dstLibIncludePath = "includes"; string dstProjectIncludePath = ""; foreach (string include in task.Includes) { string dstFilePath = null; if (include.StartsWith(projectPath)) { string relative = include.Replace(projectPath, "").TrimStart('\\','/'); dstFilePath = Path.Combine(dstProjectIncludePath, relative); } else { for (int i=0;i<task.IncludeDirs.Count;++i) { string srcIncludePath = task.IncludeDirs[i]; if (include.StartsWith(srcIncludePath)) { string relative = include.Replace(srcIncludePath, "").TrimStart('\\', '/'); dstFilePath = Path.Combine(dstLibIncludePath+i.ToString(), relative); break; } } } AddFileToTar(archive, include, dstFilePath, addedEntries); } } // Package build batch TextWriter batch = new StreamWriter("golembuild.bat", false); // CD to the directory the batch file is in batch.WriteLine("cd %~DP0"); // Create output folder batch.WriteLine("mkdir output"); int numberOfIncludeDirs = 0; List<CompilerArg> compilerArgs = new List<CompilerArg>(); foreach (CompilationTask task in taskList) { bool found = false; foreach(CompilerArg compilerArg in compilerArgs) { if (compilerArg.compiler == task.Compiler && compilerArg.args == task.CompilerArgs) { compilerArg.files.Add(Path.GetFileName(task.FilePath)); found = true; break; } } if (found) continue; numberOfIncludeDirs = Math.Max(numberOfIncludeDirs, task.IncludeDirs.Count); CompilerArg newCompilerArg = new CompilerArg(); newCompilerArg.compiler = task.Compiler; newCompilerArg.args = task.CompilerArgs; newCompilerArg.files.Add(Path.GetFileName(task.FilePath)); compilerArgs.Add(newCompilerArg); } // Add compilation commands, once per CompilerArg foreach(CompilerArg compilerArg in compilerArgs) { for(int i=0;i< numberOfIncludeDirs;++i) compilerArg.args += " /I\"includes"+i.ToString()+"\" /FS"; compilerArg.args += " /Fo\"output/\""; compilerArg.args += " /Fd\"output/" + Path.GetFileNameWithoutExtension(compilerArg.files[0]) + ".pdb\""; compilerArg.args += " /MP" + TaskCapacity; batch.Write("\"../" + Path.GetFileName(compilerArg.compiler) + "\" " + compilerArg.args); foreach(string file in compilerArg.files) { batch.Write(" " + file); } batch.WriteLine(); } // Zip output folder batch.WriteLine("powershell.exe -nologo -noprofile -command \"& { Add-Type -A 'System.IO.Compression.FileSystem'; [IO.Compression.ZipFile]::CreateFromDirectory('output', 'output.zip'); }\""); // stop the service batch.WriteLine("\"../mspdbsrv.exe\" -stop"); batch.WriteLine("exit 0");//assume no error batch.Close(); TarEntry batchEntry = TarEntry.CreateEntryFromFile("golembuild.bat"); batchEntry.Name = "golembuild.bat"; archive.WriteEntry(batchEntry, false); } package = memoryStream.ToArray(); string hash = GolemCache.RegisterTasksPackage(package); FileStream debug = new FileStream(hash + ".tar", FileMode.Create); debug.Write(package, 0, package.Length); debug.Close(); return hash; } } private string PackFilesPreProcessed(List<CompilationTask> taskList) { byte[] package; using (var memoryStream = new MemoryStream()) { using (var archive = new TarOutputStream(memoryStream)) { List<string> addedEntries = new List<string>(); //precompiled headers are not used in preprocessed build // Package build batch TextWriter batch = new StreamWriter("golembuild.bat", false); // CD to the directory the batch file is in batch.WriteLine("cd %~DP0"); // Create output folder batch.WriteLine("mkdir output"); List<CompilerArg> compilerArgs = new List<CompilerArg>(); foreach (CompilationTask task in taskList) { bool found = false; string args = task.CompilerArgs; foreach (CompilerArg compilerArg in compilerArgs) { bool includesMatch = task.IncludeDirs.Count == compilerArg.includeDirs.Count; if (includesMatch) { for (int i = 0; i < task.IncludeDirs.Count; ++i) { if (!compilerArg.includeDirs[i].Equals(task.IncludeDirs[i])) { includesMatch = false; break; } } } if (compilerArg.compiler == task.Compiler && compilerArg.args == args && includesMatch) { compilerArg.files.Add(task.FilePath); found = true; break; } } if (found) continue; CompilerArg newCompilerArg = new CompilerArg(); newCompilerArg.compiler = task.Compiler; newCompilerArg.args = args; newCompilerArg.files.Add(task.FilePath); foreach (string e in task.IncludeDirs) newCompilerArg.includeDirs.Add(e); compilerArgs.Add(newCompilerArg); } string tempFolder = "iGolemBuild"+Peer.NodeId; Directory.CreateDirectory(tempFolder); //foreach compilation task, preprocess the cpp file into a temporary folder foreach (CompilerArg compilerArg in compilerArgs) { //preprocess file, grab output, write the file as file to compile on external machine Process proc = new Process(); string args = compilerArg.args; //add includes foreach (string inc in compilerArg.includeDirs) args += " /I\"" + inc + "\" "; //add preprocessing flag args += "/P /Fi" + tempFolder + "\\ "; args += "/MP" + TaskCapacity; //add source files foreach (string srcFile in compilerArg.files) args += " " + srcFile; proc.StartInfo.Arguments = args; proc.StartInfo.FileName = compilerArg.compiler; proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardInput = false; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.CreateNoWindow = true; proc.Start(); System.Text.StringBuilder outputStr = new System.Text.StringBuilder(); proc.OutputDataReceived += (sender, e) => { if (e.Data != null) { string output = e.Data; Logger.LogMessage(output); } }; proc.ErrorDataReceived += (sender, e) => { if (e.Data != null) { outputStr.AppendLine(e.Data); } }; proc.BeginOutputReadLine(); proc.BeginErrorReadLine(); proc.WaitForExit(); Logger.LogMessage(outputStr.ToString()); if (proc.ExitCode == 0) { //now read back the files and add them to tar foreach (string srcFile in compilerArg.files) { //TODO: this might be inside a folder string precompiledFile = tempFolder+"\\" + Path.GetFileNameWithoutExtension(srcFile) + ".i"; TarEntry entry = TarEntry.CreateEntryFromFile(precompiledFile); entry.Name = Path.GetFileName(srcFile); archive.PutNextEntry(entry); using (Stream inputStream = File.OpenRead(precompiledFile)) { writeStreamToTar(archive, inputStream); archive.CloseEntry(); } } } else { Logger.LogError($"Preprocessing of file package failed"); } } Directory.Delete(tempFolder, true); // Add compilation commands, once per CompilerArg foreach (CompilerArg compilerArg in compilerArgs) { //remove precompiled header args /Yu /Fp Match match = Regex.Match(compilerArg.args, "/Yu\".+?\""); if (match.Success) compilerArg.args = compilerArg.args.Remove(match.Index, match.Length); match = Regex.Match(compilerArg.args, "/Fp\".+?\""); if (match.Success) compilerArg.args = compilerArg.args.Remove(match.Index, match.Length); compilerArg.args += " /FS"; compilerArg.args += " /Fo\"output/\""; compilerArg.args += " /Fd\"output/" + Path.GetFileNameWithoutExtension(compilerArg.files[0]) + ".pdb\""; compilerArg.args += " /MP" + TaskCapacity; batch.Write("\"../" + Path.GetFileName(compilerArg.compiler) + "\" " + compilerArg.args); foreach (string file in compilerArg.files) { batch.Write(" " + Path.GetFileName(file)); } batch.WriteLine(); } // Zip output folder batch.WriteLine("powershell.exe -nologo -noprofile -command \"& { Add-Type -A 'System.IO.Compression.FileSystem'; [IO.Compression.ZipFile]::CreateFromDirectory('output', 'output.zip'); }\""); // stop the service batch.WriteLine("\"../mspdbsrv.exe\" -stop"); batch.WriteLine("exit 0");//assume no error batch.Close(); TarEntry batchEntry = TarEntry.CreateEntryFromFile("golembuild.bat"); batchEntry.Name = "golembuild.bat"; using (Stream inputStream = File.OpenRead("golembuild.bat")) { batchEntry.Size = inputStream.Length; archive.PutNextEntry(batchEntry); writeStreamToTar(archive, inputStream); archive.CloseEntry(); } } package = memoryStream.ToArray(); string hash = GolemCache.RegisterTasksPackage(package); FileStream debug = new FileStream(hash + ".tar", FileMode.Create); debug.Write(package, 0, package.Length); debug.Close(); return hash; } } private void writeStreamToTar(TarOutputStream tarOutputStream, Stream inputStream) { // this is copied from TarArchive.WriteEntryCore byte[] localBuffer = new byte[32 * 1024]; while (true) { int numRead = inputStream.Read(localBuffer, 0, localBuffer.Length); if (numRead <= 0) break; tarOutputStream.Write(localBuffer, 0, numRead); } tarOutputStream.Flush(); } } } <file_sep>/GolemBuild/IncludeParser.cs using System; using System.Collections.Generic; using System.IO; namespace GolemBuild { internal class IncludeParser { private static void parseIncludes(string path, Action<bool, string> visitorCB) { StreamReader file = new StreamReader(path); bool isInMultilineComment = false; string line; while ((line = file.ReadLine()) != null) { line = line.Trim(); // Start multiline comment if (line.Contains("/*")) { // End multiline comment if (line.Contains("*/")) { int startComment = line.IndexOf("/*"); int endComment = line.IndexOf("*/") + 1; string newLine = ""; if (startComment != 0) newLine += line.Substring(0, startComment); if (endComment < line.Length - 1) newLine += line.Substring(endComment); line = newLine; } else { int to = line.IndexOf("/*") + 1; line = line.Substring(0, to); isInMultilineComment = true; } } else if (isInMultilineComment && line.Contains("*/")) { int to = line.IndexOf("*/") + 1; if (to < line.Length - 1) line = line.Substring(to); isInMultilineComment = false; } else if (isInMultilineComment) { continue; } // Remove // comments if (line.Contains("//")) { int to = line.IndexOf("//"); line = line.Substring(0, to); } var match = System.Text.RegularExpressions.Regex.Match(line, @"#\s*include"); if (match.Success)//line.Contains("#include")) { if (line.Contains("<") && line.Contains(">")) { // Angle bracket include int from = line.IndexOf("<") + 1; int to = line.LastIndexOf(">"); string includeName = line.Substring(from, to - from); visitorCB(false, includeName); } else if (line.Contains("\"")) { // Quote include int from = line.IndexOf("\"") + 1; int to = line.LastIndexOf("\""); string includeName = line.Substring(from, to - from); visitorCB(true, includeName); } } } } public static void FindIncludes(bool isLocal, string curFolder, string filePath, IEnumerable<string> includePaths, List<string> includes) { bool fileExists = false; string fullPath = null; //if filePath is absolute change cur folder and split path if (Path.IsPathRooted(filePath)) { throw new NotSupportedException($"Could not add an absolute include: {filePath}!\nGU currently does not support absolute file paths! Please change this include to relative one!"); /*if (File.Exists(filePath)) { fullPath = filePath; fileExists = true; }*/ } else { //1. if this is local file, first try to find it relative to the current folder if (isLocal) { fullPath = Path.Combine(curFolder, filePath); if (File.Exists(fullPath)) fileExists = true; } //2. if not found check includes if (!fileExists) { foreach (string includePath in includePaths) { fullPath = Path.Combine(includePath, filePath); if (File.Exists(fullPath)) { curFolder = includePath; fileExists = true; break; } } } } if (!fileExists) { Logger.LogError("Could not find include: " + filePath); return; } //now check if this file has been already processed if (includes.Contains(fullPath)) return; includes.Add(fullPath); //get current folder curFolder = Path.GetDirectoryName(fullPath); //we have found the file, load and parse it, to recursively find all other includes parseIncludes(fullPath, (local, includeName) => { FindIncludes(local, curFolder, includeName, includePaths, includes); }); //-------------------- } } } <file_sep>/GolemBuild/CustomBuildTask.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GolemBuild { class CustomBuildTask { public string FilePath { get; set; } public string Command { get; set; } public string Message { get; set; } public bool BuildParallel { get; set; } public CustomBuildTask(string filePath, string command, string message, bool buildParallel) { FilePath = filePath; Command = command; Message = message; BuildParallel = buildParallel; } } } <file_sep>/GolemBuild/Logger.cs using System; namespace GolemBuild { public static class Logger { public static event Action<string> OnError; public static event Action<string> OnMessage; public static void LogError(string message) { OnError?.Invoke(message); } //TODO: add some verbosity level public static void LogMessage(string message) { OnMessage?.Invoke(message); } } } <file_sep>/GolemBuild/GolemHttpService.cs using System; using System.IO; using System.IO.Compression; using System.Net; using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; namespace GolemBuild { class GolemHttpService { private int ServerPort = 6000; private Task requestLoop = null; private CancellationTokenSource cancellationSource = null; /// <summary> /// Path for built data. TODO: this should be interfaced so it is not strictly data on the filesystem, it might be in memory /// </summary> public string BuildPath { get; set; } public GolemHttpService() { if (!HttpListener.IsSupported) throw new NotSupportedException( "Needs Windows XP SP2, Server 2003 or later."); } public void Start() { cancellationSource = new CancellationTokenSource(); requestLoop = RequestServer(cancellationSource.Token); } public void Stop() { cancellationSource.Cancel(); requestLoop.Wait(); cancellationSource = null; requestLoop = null; } /// <summary> /// All providers will ask this server for files and packages, for now the only supported format is tar.gz /// TODO: try if zip compression is also supported /// </summary> /// <returns></returns> private async Task RequestServer(System.Threading.CancellationToken token) { HttpListener listener = new HttpListener(); //this part is tricky: //either run this as administrator or //run: netsh http add urlacl url=http://+:ServerPort/requestID/ user=DOMAIN\username (as an administrator) listener.Prefixes.Add("http://+:" + ServerPort + "/requestID/"); try { var taskCompletionSource = new TaskCompletionSource<HttpListenerContext>(); token.Register(() => { taskCompletionSource.TrySetCanceled();//this will throw }); listener.Start(); while (true) { try { //get the request HttpListenerContext context = await await Task.WhenAny(listener.GetContextAsync(), taskCompletionSource.Task); _ = Task.Run(() => ProcessRequest(context)); // Discard is used so we don't get warnings about not using await... } catch (TaskCanceledException) { //bail out break; } catch (Exception ex) { //TODO: do sth with this exception Console.WriteLine(ex.Message); } } } catch (Exception ex) { Logger.LogError(ex.Message); } finally { listener.Stop(); listener.Close(); } } private void ProcessRequest(HttpListenerContext context) { HttpListenerRequest request = context.Request; // Are they trying to upload a file? if (request.HttpMethod == "PUT") { System.IO.Stream input = request.InputStream; string test = GolemBuildService.Instance.BuildPath; string test2 = Path.GetFileNameWithoutExtension(request.RawUrl) + ".zip"; string zipName = Path.Combine(test, test2); FileStream fileStream = File.Create(zipName); input.CopyTo(fileStream); fileStream.Close(); input.Close(); // Send back OK HttpListenerResponse response = context.Response; response.Headers.Clear(); response.SendChunked = false; response.StatusCode = 201; response.AddHeader("Content-Location", zipName); //response.AddHeader("Server", String.Empty); //response.AddHeader("Date", String.Empty); response.Close(); ZipFile.ExtractToDirectory(zipName, Path.GetDirectoryName(zipName)); } else // They are trying to download a file { // Obtain a response object. HttpListenerResponse response = context.Response; //let's check ranges long offset = 0; long size = -1; foreach (string header in request.Headers.AllKeys) { if (header == "Range") { string[] values = request.Headers.GetValues(header); string[] tokens = values[0].Split('=', '-'); offset = int.Parse(tokens[1]); size = (int)(int.Parse(tokens[2]) - offset + 1); } } try { // Are they requesting a CompilerPackage? if (request.RawUrl.StartsWith("/requestID/compiler/")) { string compilerHash = request.RawUrl.Replace("/requestID/compiler/", ""); byte[] data; if (GolemCache.GetCompilerPackageData(compilerHash, out data)) { response.AddHeader("ETag", "SHA1:" + compilerHash); if (size == -1) { size = data.Length; } response.ContentLength64 = size; Stream output = response.OutputStream; output.Write(data, (int)offset, (int)size); output.Close(); } } // Or are they requesting a tasks package? else if (request.RawUrl.StartsWith("/requestID/tasks/")) { string tasksPackageHash = request.RawUrl.Replace("/requestID/tasks/", ""); byte[] data; if (GolemCache.GetTasksPackage(tasksPackageHash, out data)) { response.AddHeader("ETag", "SHA1:" + tasksPackageHash); if (size == -1) { size = data.Length; } response.ContentLength64 = size; Stream output = response.OutputStream; output.Write(data, (int)offset, (int)size); output.Close(); } } } catch(HttpListenerException ex) { Logger.LogMessage(ex.Message); } } } private DataPackage GetDataPackage(Uri url, long offset, int size) { string fileName = Path.GetFileNameWithoutExtension(url.AbsolutePath); string tarPath = Path.Combine(GolemBuild.golemBuildTasksPath, fileName + ".tar.gz"); if (!File.Exists(tarPath)) { throw new FileNotFoundException("Could not find the requested " + fileName + "tar.gz"); } DataPackage data = new DataPackage(); if (size == -1) { data.DataStream = File.ReadAllBytes(tarPath); using (var cryptoProvider = new SHA1CryptoServiceProvider()) { data.DataHash = "SHA1:" + BitConverter .ToString(cryptoProvider.ComputeHash(data.DataStream)).Replace("-", string.Empty).ToLower(); } } else { data.DataStream = new byte[size]; FileStream file = new FileStream(tarPath, FileMode.Open, FileAccess.Read, FileShare.Read); file.Seek(offset, SeekOrigin.Begin); file.Read(data.DataStream, 0, size); file.Close(); data.DataHash = "SHA1:abcdef"; } return data; } } } <file_sep>/TestApp/Program.cs using GURestApi.Api; using GURestApi.Model; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; namespace TestApp { class Program { static Thread serverThread = null; static CancellationTokenSource serverToken = null; static void Main(string[] args) { PeerApi peerApi = new PeerApi("http://10.30.10.121:6162"); var info = peerApi.GetHubInfo(); System.Console.WriteLine(info.ToString()); string output = ""; foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces()) { if (item.NetworkInterfaceType == NetworkInterfaceType.Ethernet && item.OperationalStatus == OperationalStatus.Up) { foreach (UnicastIPAddressInformation ip in item.GetIPProperties().UnicastAddresses) { if (ip.Address.AddressFamily == AddressFamily.InterNetwork) { output = ip.Address.ToString(); } } } } var myIP = Dns.GetHostAddresses(Dns.GetHostName()); runServer(); var peers = peerApi.ListPeers(); int myPeer = -1; for (int i = 0; i < peers.Count; i++) { if (peers[i].PeerAddr.Contains("10.30.8.5")) { myPeer = i; break; } } if (myPeer == -1) { return; } { string hash = "SHA1:213fad4e430ded42e6a949f61cf560ac96ec9878"; DeploymentSpecImage specImg = new DeploymentSpecImage(hash, "http://10.30.8.5:6000/generatedID/test1.hdi"); DeploymentSpec spec = new DeploymentSpec(EnvType.Hd, specImg, "compiler",new List<string>() { "dupa"}); var peer = peers[myPeer]; string depId = peerApi.CreateDeployment(peer.NodeId, spec); depId = depId.Replace("\"", ""); // Run batch file var results = peerApi.UpdateDeployment(peer.NodeId, depId, new List<Command>() { new ExecCommand("Debug/golemtest.bat",new List<string>())}); // Upload output.zip results = peerApi.UpdateDeployment(peer.NodeId, depId, new List<Command>() { new UploadFileCommand("http://10.30.8.5:6000/generatedID/", "output.zip") }); peerApi.DropDeployment(peer.NodeId, depId); System.Console.WriteLine(depId); stopServer(); return; } //session { SessionApi sessionApi = new SessionApi("http://10.30.10.121:6162"); //create session var body = new HubSession(); long? sessionId = sessionApi.CreateSession(body); body = sessionApi.GetSession(sessionId); //add peer var res1 = sessionApi.AddSessionPeers(sessionId, new List<string>() { peers[0].NodeId }); var sPeers = sessionApi.ListSessionPeers(sessionId); body = sessionApi.GetSession(sessionId); var deploymentSpec = new DeploymentInfo(); deploymentSpec.Name = "dupa"; string result = sessionApi.CreateDeployment(sessionId, peers[0].NodeId, deploymentSpec); System.Console.WriteLine(result); } } private static void stopServer() { serverToken.Cancel(); serverThread.Join(); } private static void runServer() { serverThread = new Thread(httpServer); serverToken = new CancellationTokenSource(); serverThread.Start(); //serverThread.Join(); } private static void httpServer() { //load file targ.gz for testing var fileBytes = System.IO.File.ReadAllBytes("Debug.tgz"); HttpListener listener = new HttpListener(); listener.Prefixes.Add("http://+:6000/generatedID/"); listener.Start(); while(true) { try { // Note: The GetContext method blocks while waiting for a request. Task<HttpListenerContext> context = listener.GetContextAsync(); context.Wait(serverToken.Token); HttpListenerRequest request = context.Result.Request; // Are they trying to upload a file? if (request.HttpMethod == "PUT") { System.IO.Stream input = request.InputStream; FileStream fileStream = File.Create("testzip.zip"); input.CopyTo(fileStream); fileStream.Close(); input.Close(); } else // They are trying to download a file { // Obtain a response object. HttpListenerResponse response = context.Result.Response; //let's check ranges long offset = 0; long size = fileBytes.Length; foreach (string header in request.Headers.AllKeys) { if (header == "Range") { string[] values = request.Headers.GetValues(header); string[] tokens = values[0].Split('=', '-'); offset = int.Parse(tokens[1]); size = int.Parse(tokens[2]) - offset + 1; } } response.AddHeader("ETag", "675af34563dc-tr34"); // Construct a response. // Get a response stream and write the response to it. response.ContentLength64 = size; response.ContentType = "application/x-gzip"; response.AddHeader("Accept-Ranges", "bytes"); System.IO.Stream output = response.OutputStream; Task ret = output.WriteAsync(fileBytes, (int)offset, (int)size); ret.Wait(); // You must close the output stream. output.Close(); } } catch(OperationCanceledException) { listener.Stop(); return; } catch(Exception ex) { Console.WriteLine(ex.Message); } } } } } <file_sep>/README.md #Hoard Compiler - the plugin for VS2017 & VS 2019 for distributed compilation using Golem Unlimited infrastructure - API version: 1.0.0 - SDK version: 1.0.0 - Build package: org.openapitools.codegen.languages.CSharpClientCodegen <a name="frameworks-supported"></a> ## Frameworks supported - .NET 4.6.1 or later - .NET 4.7.2 or later <a name="dependencies"></a> ## Dependencies - [RestSharp](https://www.nuget.org/packages/RestSharp) - 105.1.0 or later - [Json.NET](https://www.nuget.org/packages/Newtonsoft.Json/) - 7.0.0 or later - [GURestAPI](https://github.com/hoardexchange/GURestApi.git) - latest <a name="installation"></a> ## Installation Just compile the code and run it from Visual Studio. An Experimental version of VS will be spawned and the plugin will be automatically installed. Or you can also build the VSIX package wchich then can be installed using Visual Studio.
12f06cf46e34b5cd045d16d905d6cb7671860181
[ "Markdown", "C#" ]
13
C#
hoardexchange/HoardCompiler
be83cb8710bb79f2814db3fc9b83199e52b9e336
15ec2fb94ee056381723c898f0fbdf58d48f8db4
refs/heads/master
<repo_name>mikibouns/GS1<file_sep>/barcode_gererator.pyw import tkinter as tk from tkinter import filedialog as fd import re import os import xlrd import win32com.client class MainHandler: def __init__(self): self.source_file = None self.target_file = None self.data_dict = {} def create_dict(self): rb = xlrd.open_workbook(self.source_file, formatting_info=True) sheet = rb.sheet_by_index(0) vals = (sheet.row_values(rownum) for rownum in range(sheet.nrows)) for i in vals: if re.search('обои виниловые на', i[4]): format_str = re.findall('\d+', i[4])[3] self.data_dict[format_str] = i[7] def write_data(self): file_name = os.path.basename(self.target_file) xl = win32com.client.Dispatch("Excel.Application") wb = xl.Workbooks.Open(Filename=self.target_file) xl.Application.Run("{}!Module1.Unprotect".format(file_name)) sheet = wb.ActiveSheet last_line = 0 while True: last_line += 1 if sheet.Cells(last_line, 1).value is None: break for item, value in self.data_dict.items(): sheet.Cells(last_line, 1).value = int(item) sheet.Cells(last_line, 2).value = value last_line += 1 xl.Application.Run("{}!Module1.Protect".format(file_name)) xl.Application.Save() xl.Application.Quit() def preview(self): if self.source_file and self.target_file: self.create_dict() return True else: return False def start(self): if self.source_file and self.target_file: if not self.data_dict: self.preview() self.write_data() return True else: return False ######################################################################################################################## app = MainHandler() root = tk.Tk() btn1_open = tk.Button(root, text='open source file', width=20) label1 = tk.Label(root, text='') btn2_open = tk.Button(root, text='open file target', width=20) label2 = tk.Label(root, text='') btn_start = tk.Button(root, text='start', width=20) btn_preview = tk.Button(root, text='preview', width=20) listbox = tk.Listbox(root, height=20, width=80) state_lable = tk.Label(root, text='') def display_data(): listbox.delete(0, listbox.size()) for item, value in app.data_dict.items(): listbox.insert(tk.END, '{}: {}'.format(item, value)) def get_path1(event): file1_path = fd.askopenfilename() label1['text'] = file1_path app.source_file = file1_path def get_path2(event): file2_path = fd.askopenfilename() label2['text'] = file2_path app.target_file = file2_path def preview(event): if state_lable['text'] != 'Data recorded': if app.preview(): state_lable['text'] = 'File read' display_data() else: state_lable['text'] = 'No source or target file specified' def start(evant): if app.start(): display_data() state_lable['text'] = 'Data recorded' else: state_lable['text'] = 'No source or target file specified' btn1_open.bind('<Button-1>', get_path1) btn2_open.bind('<Button-1>', get_path2) btn_preview.bind('<Button-1>', preview) btn_start.bind('<Button-1>', start) btn1_open.grid(row=0, column=0, sticky=tk.W) label1.grid(row=0, column=1, sticky=tk.W) btn2_open.grid(row=1, column=0, sticky=tk.W) label2.grid(row=1, column=1, sticky=tk.W) listbox.grid(row=2, columnspan=5) state_lable.grid(row=3, columnspan=5, sticky=tk.W) btn_preview.grid(row=4, column=0, sticky=tk.W, ipady=10) btn_start.grid(row=4, column=1, sticky=tk.W, ipady=10) if __name__ == '__main__': root.title('GS1_aggregate') root.geometry('500x400') root.mainloop()
3bde5ef3c27655e2675ed85cac4238f5a683a2c6
[ "Python" ]
1
Python
mikibouns/GS1
61a9c0a4801ba115e5beec0bad10ebbd6886dc7b
8169304f765898d2237677081d57347c8de495eb
refs/heads/master
<repo_name>FedericoLevis/JSU<file_sep>/images/Readme.txt Immagini da Installare in /ENEL/Immagini/ Settare in modod analogo in ../etc/ext_conf.js: var PATH_SORT_IMG = "/ENEL/Immagini/"; <file_sep>/core/jsuCmn.js /** @fileOverview ========================================================================================= <BR/> <b>File:</b> core/jsuCmn.js <BR/> <b>Author:</b> <a href="https://www.linkedin.com/in/federicolevis" target="_self"><NAME></a> <BR/> <b>JSU API Doc:</b> <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/JSUAPI.html" target="_self">JSU API Documentation</a> <BR/> <b>Description:</b> JSU Common constant or base API shared by all Features <BR/> <b>REQUIRED:</b> NOTHING<BR/> <b>First Version:</b> ver 1.0 - Jul 2007 <BR/> <b>Current Version:</b> JSU v. 1.10 &nbsp;&nbsp;&nbsp;2018-Jan-14 <BR/> <BR/>-----------------------------------------------------------------------------------<BR/> <b>DISCLAIMER</b> <BR/> Copyright by <NAME> - <a href="https://github.com/JSUtility/JSU" target="_self">JSU</a> <BR/> This file may be freely distributed under the MIT license. <BR/> ========================================================================================= <BR/> */ /*========================================================================== * GLOBAL JSU CONSTANT ========================================================================== */ // displayed in About var JSU_VERSION="JSU v. 1.10 &nbsp;&nbsp;&nbsp;2018-Jan-14"; //----------------------------------------------- var JSU_LOG_FUN_START = "------------------------ START"; var JSU_LOG_FUN_END = "------------------------ END"; /*========================================================================== * GLOBAL JSU FUNCTION ========================================================================== */ /* * call jslog if it is defined * @param msg */ function jsu_log(msg){ if (typeof(jslog) == "function"){ jslog (JSLOG_JSU, msg); } // alert (msg); } /* * call jslogObj if it is defined * @param msg */ function jsu_logObj(msg,obj){ if (typeof(jslogObj) == "function"){ jslogObj (JSLOG_JSU, msg,obj); } } /* * call jslogHtml if it is defined * @param msg */ function jsu_logHtml(msg,szHtml){ if (typeof(jslogHtml) == "function"){ jslogHtml (JSLOG_JSU, msg,szHtml); } } /*----------------------------------------------------------- Get Element By ID and Show Error if required PAR Id in [bShowErr] in true (default) if I want to show Error false if don't want to show Error RETURN el if founded 0 if not founded -----------------------------------------------------------*/ function jsu_getElementById2(Id,bShowErr) { if (bShowErr == undefined){ // bShowErr = true; bShowErr = false; } var el = document.getElementById(Id); if (el == null) { if (bShowErr){ alert("SW ERROR [jsu_getElementById2] NOT FOUND Id=" + Id) ; } return 0; // Not Found } return el; } /* Show/Hide an Element (and its Children) * @param El * @param bShow true if I want to show it -false if I want to hide it * @param [szDisplayIfVisible] {String} display to set if bShow=true e.g "inline" (default= "block") */ function jsu_elementShow(El,bShow,szDisplayIfVisible) { if (El == 0 || El == undefined){ return; } if (szDisplayIfVisible == undefined){ szDisplayIfVisible = "block"; } if (bShow){ El.style.visibility="visible"; /* El.style.display="block"; */ El.style.display=szDisplayIfVisible; }else { El.style.visibility="hidden"; El.style.display="none"; } } /* * Show an Error * @param szErr */ function jsu_err(szMsg){ if (typeof (Popup) != "undefined"){ Popup (POPUP_TYPE.ERR,szMsg); }else { alert (szMsg); } } /*------------------------------------------------------------- Replace all occurrences of from with to @param szOrig in @param from in e.g "&nbsp;" @param to in e.g " " @return --------------------------------------------------------------*/ function jsu_strReplaceAll (szOrig,szFrom,szTo){ var szNew = szOrig; while (szNew.indexOf(szFrom) >=0){ szNew = szNew.replace (szFrom,szTo); } return szNew; } <file_sep>/core/cSortTable.js /** @fileOverview ========================================================================================= <BR/> <b>File:</b> core/cSortTable.js <BR/> <b>Author:</b> <a href="https://www.linkedin.com/in/federicolevis" target="_self"><NAME></a> <BR/> <b>SortTable Doc:</b> <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/HTML/SortTable.html" target="_self">JSU SortTable Documentation</a> <BR/> <b>JSU API Doc:</b> <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/JSUAPI.html" target="_self">JSU API Documentation</a> <BR/> <b>Description:</b> SortTable Class <BR/> <b>REQUIRE:</b> JSU: jsu.js <BR/> <b>First Version:</b> ver 1.0 - Feb 2010 <BR/> <b>Current Version:</b> JSU v. 1.10 &nbsp;&nbsp;&nbsp;2018-Jan-14 <BR/> <BR/>-----------------------------------------------------------------------------------<BR/> <b>DISCLAIMER</b> <BR/> Copyright by <NAME> - <a href="https://github.com/FedericoLevis/JSU" target="_self">JSU</a> <BR/> This file may be freely distributed under the MIT license. <BR/> ========================================================================================= <BR/> */ //--------------------------------------------------------------------------------------------- // GLOBAL CONSTANT //--------------------------------------------------------------------------------------------- /** * SORT_TYPE (Default=STRING) */ var SORT_TYPE = { NONE:'NONE', // NO Sort for This column STRING:'STRING', // Default (used when it is not indicate the SORT_TYPE ) NUMBER:'NUMBER', DATETIME:'DATETIME' // can be used for Date, DateTime, Time. For Format see date.js }; /** * SORT_DIR */ var SORT_DIR = { ASC: "-1", // Ascending (Do not change because this valiue is used By Cognos) DESC: "1", NONE: "NONE" }; // ---------------------- Default Opt var SORT_DEF_COGNOS = false; var SORT_DEF_COGNOS_GLOBAL_SORT_EN = false; //----- NB: see date.js for possible formats //Default Format for SortType=DATETIME if SortInfo is not defined var SORT_DEF_FMT_DATETIME="MM/dd/yyyy HH:mm:ss"; var SORT_DEF_PATH_IMG = JSU_PATH_IMG; var SORT_DEF_IND = 0; var SORT_DEF_DIR = SORT_DIR.ASC; var SORT_DEF_APPLY = false; /** * DEFAULT class that Identify FOOTER Rows for HTML using this class. It Can be passed a different class */ var SORT_TR_CLASS_FOOTER="footer"; /** * ONLY FOR COGNOS: CLASS that identify TR (IE) or TD (Chroome) */ var SORT_CLASS_FOOTER_COGNOS="summary"; var SORT_INFO_ABSENT = ""; // --------------------------------------------------FileName for Sort Icons. The Base Path is configured in ext_conf.js // Fast Local Sort var SORT_IMG_NONE_FAST = "fast_sort_none.jpg"; var SORT_IMG_ASC_FAST = "fast_sort_asc.jpg"; var SORT_IMG_DESC_FAST = "fast_sort_desc.jpg"; // Slow Global Sort var SORT_IMG_NONE_SLOW = "slow_sort_none.jpg"; var SORT_IMG_ASC_SLOW = "slow_sort_asc.jpg"; var SORT_IMG_DESC_SLOW = "slow_sort_desc.jpg"; //Disable Sort var SORT_IMG_NONE_DIS = "disabled_sort_none.jpg"; var SORT_IMG_ASC_DIS = "disabled_sort_asc.jpg"; var SORT_IMG_DESC_DIS = "disabled_sort_desc.jpg"; //wait var SORT_IMG_WAIT = "wait.jpg"; //--------------------------------------------------------------------------------------------- // Internal CONSTANT //--------------------------------------------------------------------------------------------- var SORT_ATTR_SORT_DIR = "SortDirCur"; var SORT_TMO_WAIT_MS = 50; //--------------------------------------------------------------------------------------------- // SORT GLOBAL VAR //--------------------------------------------------------------------------------------------- // the current SortTableEl because the sort function does not work properly var cSortTableElCur = null; //------------------------- // var SORT_CLASSNAME = "sortimg"; //************************************************************************** //GLOBAL CONSTRUCTOR (N.B. at the Top of the file) //************************************************************************** /** @class cSortTable @param {string} szElId Id of the HTML TABLE to sort - If bCognos=true szElId=spanId that enclose the Cognos List to Sort @param {array} arSortCol Array with the SortCol (See Example below) @param objOpt {Object} Options: <ul> <li>iRowHeader {Number} Default =1 Number [1,2,..] of Row Header </li> <li>iRowSortHeader {Number} Default =1 Number [1,2,..] of the Row where we have to put the Sort Icon. e.g 2 if we have 2 row header and we want to put icon in the second row</li> NOTE: you can also define only one of previous. if you set only iRowHeader=2 also iRowSortHeader will be 2 </li> you can define both for particular cases (e.g iRowHeader=2 iRowSortHeader=1 for Filter presence) </li> <li>szSortCol {String} Current Sort Col to be set. <BR/> Default. Par is absent and First Col is Set, without applying the Sort (we suppose Table already Sorted) <BR/> To init without any SortCol, pass szSortCol = "" <ul> <li> a) bCognos=false: First Col is Set </li> <li> b) bCognos=true: Current Col is taken by selectSortCol </li> </ul> </li> <li>szSortDir {String} Current SortDir: SORT_DIR.ASC, SORT_DIR.DESC, SORT_DIR.NONE . <BR/> Default: par is absent and we use: <ul> <li>a) bCognos=false: SORT_DIR.ASC </li> <li> b) bCognos=true: Current Dir is taken by selectSortDir </li> </ul> </li> <li>bSortApply {Boolean} Default=false If true apply the current SortCol/ SortDir </li> <li>szFmtDatetime (String} Fmt to be used for Datetime if the Info is passed for the DATETIME Columns into szSortCol .fmt parameter </li> <li>szPathImg {String} BaseSortPath (e.g "../../../images") to be used instead of the default image Path </li> <li>iTblRowPerPage {Number} If present is the limit of Rows displayed in the Table. For Cognos is the Setting of the List properties RowPerPage <BR/> When not present (default), we consider all the Table always displayed </li> <li>szClassFooter {String} class that identity the TR and/OR TD Footer rows </li> <li>bNoStartupSortIco {Boolean} [false] true to avoid setting a default ico sort at startup (in the First col) <li>bCognos {Boolean} default=false . true for Cognos Sort: in this case szElId identifies the span in front of the Table </li> <li>bCognosGlobalSort {Boolean} Default=false. Only for bCognos=true <BR/> When The Table is displayed and More than one Page is present we cannot make Local Sort: <ul> <li> a) bCognosGlobalSort=false LocalSort is Disable (Gray icons) </li> <li> b) bCognosGlobalSort=false If Click in Icon we re-execute the Report and mnake Global Sort (it can be Slow) </li> <ul> </li> @example // First 3 colums have default type: SORT_TYPE.STRING that is set when .type is not present var arSortCol = [ {col: 'Country'}, {col: '<NAME>'}, {col: 'Email'}, {col:'Payment', type: SORT_TYPE.DATETIME, fmt: 'yyyy/MM/dd HH:mm'}, {col: 'Amount', type: SORT_TYPE.NUMBER, groupSep:',', decimalSep:'.'}] ]; var LIST_ROWS_PER_PAGE=1000; // RowPerPage properties: till 1000 Rec we can make FastSort // Cognos Table with 1000 RowsPerPage. Enable GlobalSort if the Table has More than 1000 Rec var cSortTbl1 = new cSortTable("tblSort",arSortCol,{bCognos=true,bCognosGlobalSort=true,iTblRowPerPage=LIST_ROWS_PER_PAGE); */ cSortTable = function (szElId, arSortCol,objOpt) { var Fn = "[cSortTable] "; jslog(JSLOG_JSU,Fn + JSLOG_FILE_START); // Init Global Var this.iTblRowPerPage = 0; this.iRowSortHeader = 1; // Default. position [1..] of Sort in Header this.iRowHeader = 1; // Default. 1 row for Header this.bCognos = SORT_DEF_COGNOS; this.bCognosGlobalSort=SORT_DEF_COGNOS_GLOBAL_SORT_EN; this.bSortEn = true; this.szFmtDatetime = SORT_DEF_FMT_DATETIME; this.szPathImg = SORT_DEF_PATH_IMG; this.szClassFooter = SORT_TR_CLASS_FOOTER; this.szSortHiddenId = ""; // Path of Sort Img this.szSortPathNone= ""; this.szSortPathAsc=""; this.szSortPathDesc="", this.szSortPathWait= ""; this.bMultiPage = false; // default this.imgTemp = document.createElement("img"); this.arSortImg = new Array(); // Array of SortImg this.tempTextSep = document.createTextNode(" "); this.szSortDecSep = ""; this.szSortDecSepLocale = ""; this.szSortGroupSepLocale = localeGetGroupSep(); this.szSortDecSepLocale = localeGetDecimalSep(); jslog(JSLOG_JSU,Fn + "this.szSortDecSepLocale= " + this.szSortDecSepLocale + " this.szSortGroupSepLocale = " + this.szSortGroupSepLocale); this.iSortColInd=SORT_DEF_IND; // index corrent sort this.szSortDir=SORT_DEF_DIR; // Default this.szSortCol=""; // Default this.bNoStartupSortIco = false; if (arSortCol.length > 0){ this.szSortCol= (arSortCol[0].col != undefined) ? arSortCol[0].col : "" ; } // [OPTIONAL, not used by HTML; DOM Object of Cognos BOX with select with Current SelCol and ColDir this.selectSortCol=0; this.selectSortDir=0; this.inputSortCol=0; this.inputSortDir=0; this.inputSortHiddenCol=0; this.imgSortCur=null; // Current Sort Image this.szSortHintAsc=""; this.szSortHintDesc=""; this.iTblFooterRec=0; // Number of Footer Rows jslog(JSLOG_JSU,Fn + "IN szElId=" + szElId ); jslogObj(JSLOG_JSU,Fn + "IN arSortCol:",arSortCol,true); // Options if (objOpt != undefined){ jslogObj(JSLOG_JSU,Fn + "objOpt", objOpt); // Only if objOpt.szSortCol="" we set false if (objOpt.iRowHeader != undefined){ this.iRowHeader = objOpt.iRowHeader; jslog(JSLOG_JSU,Fn + "OPTION: iRowHeader=" + this.iRowHeader); if (objOpt.iRowSortHeader == undefined){ objOpt.iRowSortHeader = objOpt.iRowHeader; } } if (objOpt.iRowSortHeader != undefined){ this.iRowSortHeader = objOpt.iRowSortHeader; jslog(JSLOG_JSU,Fn + "OPTION: iRowSortHeader=" + this.iRowSortHeader); if (objOpt.iRowHeader == undefined){ objOpt.iRowHeader = objOpt.iRowSortHeader; this.iRowHeader = objOpt.iRowHeader; } } if (objOpt.iTblRowPerPage != undefined){ this.iTblRowPerPage = objOpt.iTblRowPerPage; jslog(JSLOG_JSU,Fn + "OPTION: iTblRowPerPage=" + this.iTblRowPerPage ); } if (objOpt.bCognos != undefined){ this.bCognos=objOpt.bCognos; jslog(JSLOG_JSU,Fn + "OPTION: bCognos=" + this.bCognos); } if (objOpt.bCognosGlobalSort != undefined){ this.bCognosGlobalSort=objOpt.bCognosGlobalSort; jslog(JSLOG_JSU,Fn + "OPTION: bCognosGlobalSort=" + this.bCognosGlobalSort); } if (objOpt.szFmtDatetime != undefined){ this.szFmtDatetime=objOpt.szFmtDatetime; jslog(JSLOG_JSU,Fn + "OPTION: szFmtDatetime=" + this.szFmtDatetime); } if (objOpt.szPathImg != undefined){ this.szPathImg=objOpt.szPathImg; jslog(JSLOG_JSU,Fn + "OPTION: szPathImg=" + this.szPathImg); } if (objOpt.szClassFooter != undefined){ this.szClassFooter=objOpt.szClassFooter; jslog(JSLOG_JSU,Fn + "OPTION: szClassFooter=" + this.szClassFooter); } if (objOpt.bNoStartupSortIco != undefined){ this.bNoStartupSortIco=objOpt.bNoStartupSortIco; jslog(JSLOG_JSU,Fn + "OPTION: bNoStartupSortIco=" + this.bNoStartupSortIco); } } this.tmoSortApply=null; if (this.bCognos){ this.szClassFooter = SORT_CLASS_FOOTER_COGNOS; jslog(JSLOG_JSU,Fn + "For COGNOS ALWAYS szClassFooter=" + this.szClassFooter); } // ------- HTML or COGNOS? if (this.bCognos){ // For COGMOS it is a SPAN containing the TABLE this.tblSort = getElementByTag2("TABLE","tblSort",false); }else { // For HTML the Id is the Id of the Table this.tblSort = getElementById2(szElId,true); } if (this.tblSort == 0){ return; } var iTblRecNum = 0; // Count the number of Records (Skip First row=header Footer with class="summary") this.iTblFooterRec = 0; if (this.tblSort!= undefined && this.tblSort.rows != undefined){ // skip Header Rows for (var i=this.iRowSortHeader; i < this.tblSort.rows.length ; i++){ var szType = this.tblSort.rows[i].firstChild.type; // for Cognos it set into TD // Particular case for Chrome: I have to find type="summary" into outerHTML var bOuterHTMLSummary = false; var szOuterHTML = this.tblSort.rows[i].firstChild.outerHTML; var iPosTypeSummary = -1; if (szOuterHTML != undefined){ iPosTypeSummary = szOuterHTML.indexOf('type="' + this.szClassFooter + '"'); if (iPosTypeSummary >= 0){ bOuterHTMLSummary = true; } } var szClassName = this.tblSort.rows[i].className; // For HTML // jslog (JSLOG_JSU,"ROW [" + i + "] szType=" + szType + " szClassName=" + szClassName + " iPosTypeSummary=" + iPosTypeSummary + " bOuterHTMLSummary=" + bOuterHTMLSummary); if (this.bCognos){ szClassName = szType; } var bFooter = (bOuterHTMLSummary || (szClassName != undefined && szClassName.indexOf(this.szClassFooter) >=0)); // jslog (JSLOG_JSU,"szClassName=" + szClassName + " bOuterHTMLSummary=" + bOuterHTMLSummary + " szClassFooter=" + this.szClassFooter + " --> bFooter=" + bFooter); if (szType != "columnTitle" && !bFooter){ iTblRecNum++; } if (bFooter){ jslog(JSLOG_JSU,"Rec [" + i + "] IS FOOTER" ); if (this.bCognos){ // Set also className to have the same sort algorith and identify footer by classname this.tblSort.rows[i].className = this.szClassFooter; } this.iTblFooterRec++; } } jslog(JSLOG_JSU,Fn + "TABLE iTblRecNum=" + iTblRecNum + " - iRowHeader=" + this.iRowHeader + " iRowSortHeader=" + this.iRowSortHeader + " iTblFooterRec=" + this.iTblFooterRec + " (rows=" + this.tblSort.rows.length + ")"); // For Cognos: check if MultiPage if (this.bCognos){ // bMultiPage true: if we find the Link for Top Down (isMultiPage), or if there are more row that the one of the List this.bMultiPage = ((this.iTblRowPerPage != 0) && (iTblRecNum >= this.iTblRowPerPage)) || isMultiPage(); } jslog(JSLOG_JSU,Fn + "this.bMultiPage=" + this.bMultiPage); } this.iTblRecNum = iTblRecNum; var szSortHintRecNum=""; if (this.bMultiPage){ this.szSortPathNone= this.szPathImg + ((this.bCognosGlobalSort) ? SORT_IMG_NONE_SLOW : SORT_IMG_NONE_DIS); this.szSortPathAsc= this.szPathImg + ((this.bCognosGlobalSort) ? SORT_IMG_ASC_SLOW : SORT_IMG_ASC_DIS); this.szSortPathDesc= this.szPathImg + ((this.bCognosGlobalSort) ? SORT_IMG_DESC_SLOW : SORT_IMG_DESC_DIS); szSortHintRecNum = SORT_HINT_REC_NUM_PART.replace("XXX",iTblRecNum); if (this.bCognosGlobalSort){ this.szSortHintAsc = SORT_HINT_GLOBAL_ASC + "\n\n" + szSortHintRecNum; this.szSortHintDesc = SORT_HINT_GLOBAL_DESC + "\n\n" + szSortHintRecNum; }else{ this.szSortHintAsc = SORT_HINT_DISABLED + "\n\n" + szSortHintRecNum; this.szSortHintDesc = this.szSortHintAsc; } }else{ this.szSortPathNone= this.szPathImg + SORT_IMG_NONE_FAST; this.szSortPathAsc= this.szPathImg + SORT_IMG_ASC_FAST; this.szSortPathDesc= this.szPathImg + SORT_IMG_DESC_FAST; szSortHintRecNum = SORT_HINT_REC_NUM_ALL.replace("XXX",iTblRecNum); this.szSortHintAsc = SORT_HINT_ASC + "\n\n" + szSortHintRecNum; this.szSortHintDesc = SORT_HINT_DESC + "\n\n" + szSortHintRecNum; } this.szSortPathWait= this.szPathImg + SORT_IMG_WAIT; jslog(JSLOG_JSU,Fn + "this.szSortPathNone=" + this.szSortPathNone + " this.szSortPathAsc=" + this.szSortPathAsc + " this.szSortPathDesc=" + this.szSortPathDesc); if (this.bCognos){ jslog(JSLOG_JSU,Fn + "Get select of SORT BOX Otions (e.g for Cognos)"); var fW = getFW(); // get Form Warp this.selectSortCol = fW._oLstChoices_SelectSortCol; this.selectSortCol._cSortTableEl = this; // To be used in Event this.selectSortCol.onchange = this.onchangeSortCol; this.selectSortDir = fW._oLstChoices_SelectSortDir; this.selectSortDir._cSortTableEl = this; // To be used in Event this.selectSortDir.onchange = this.onchangeSortDir; selectRemoveExtraItems(this.selectSortDir); // Remove first 2 Extra Cogns Items this.inputSortCol = fW._textEditBox_SortCol; this.inputSortDir = fW._textEditBox_SortDir; this.inputSortHiddenCol = fW._textEditBox_SortHiddenCol; } //------------------------------------------ jslog(JSLOG_JSU,Fn + "populate this.arcSortItem"); //all the sortItem info this.arcSortItem = new Array(); var iSortNum=0; if (this.selectSortCol){ selectRemoveAll (this.selectSortCol); } // Set default value when not present for (var iAr=0; iAr < arSortCol.length; iAr++) { if (arSortCol[iAr].col == undefined){ arSortCol[iAr].col = (iAr+1); // if objSortCol.col is undefined we set [1,2,....] } if (arSortCol[iAr].type == undefined){ arSortCol[iAr].type = SORT_TYPE.STRING; } if (this.selectSortCol){ appendOptionLast (this.selectSortCol,arSortCol[iAr].col,arSortCol[iAr].col); } iSortNum ++; } this.arSortCol = arSortCol; //jslogObj(JSLOG_JSU,"this.arSortCol", this.arSortCol); //------------------------------------------- if (this.inputSortHiddenCol){ var szSortHidden = this.inputSortHiddenCol.value; // E.G "Country,PLMN" jslog(JSLOG_JSU,"szSortHidden = " + szSortHidden); if (szSortHidden.length){ var ArColHidden = szSortHidden.split(","); this.sorttableSetHiddenCol(ArColHidden); } } //------------------------------------ if (this.selectSortCol){ jslog(JSLOG_JSU, "Align Current Sort Selection to Visible Fields"); selectSelValue(this.selectSortCol,this.inputSortCol.value); selectSelValue(this.selectSortDir,this.inputSortDir.value); jslog(JSLOG_JSU, "Init Global Val form Cognos Hidden Fields"); this.iSortColInd = this.selectSortCol.selectedIndex ; this.szSortDir = this.inputSortDir.value; this.szSortCol = this.inputSortCol.value; } if (this.tblSort){ this.sortInit(); } // If required by objOpt, set Initial Sort if (objOpt != undefined){ if (objOpt.szSortCol || objOpt.szSortDir){ var bSortApply = (objOpt.bSortApply != undefined && objOpt.bSortApply); jslog (JSLOG_JSU,Fn + "Obtional Initial Sort is SET: SortCol=" + objOpt.szSortCol + " szSortDir=" + objOpt.szSortDir + " bSortApply=" + bSortApply); this.setSort (objOpt.szSortCol,objOpt.szSortDir,bSortApply); } } if (this.bMultiPage && !this.bCognosGlobalSort){ this.sorttableDisableSort(); } jslog(JSLOG_JSU,Fn + JSLOG_FILE_END); }; /***************************************************************************************************** ****************************************************************************************************** GLOBAL FUNCTIONS ****************************************************************************************************** *****************************************************************************************************/ /* Set SortCol and SortDir and Apply It @param szSortCol {string} @param szSortDir {string} in SORT_DIR.ASC or SORT_DIR.DESC @param [bResortTable] {Boolean} in Default=true if true the Sort is Resort basing on szSortCol/SzSortDir if false the Sort is only aplied to the SortIcon. Pass bResortTable=false if the Table is already sorted by szSortCol/SzSortDir */ cSortTable.prototype.setSort = function (szSortCol, szSortDir,bResortTable) { var Fn = "[cSortTable.setSort] "; jslog(JSLOG_JSU,Fn + JSLOG_FUN_START); if (bResortTable == undefined || bResortTable == null){ bResortTable = true; // Deafault } jslog(JSLOG_JSU,Fn + "IN szSortCol=" + szSortCol + " szSortDir=" + szSortDir + " (" + SORT_DIR.ASC + "=ASC " + SORT_DIR.DESC + "=DESC ) bResortTable=" + bResortTable); var iSortColInd = this.iSortColInd; // Default if (szSortCol != undefined){ var iSortColInd = this.getSortIndFromSortCol(szSortCol); if (iSortColInd <0){ return; // ERROR } } jslog(JSLOG_JSU,Fn + "iSortColInd=" + iSortColInd); // Get SortImg and var SortImg = this.arSortImg[iSortColInd]; if (bResortTable){ // simulate The state to Obtain with resortTable the desired new state var szSortDirTmp= (szSortDir == SORT_DIR.ASC) ? SORT_DIR.DESC : SORT_DIR.ASC; jslog (JSLOG_JSU,"simulate having for iSortColInd=" + iSortColInd + " The szSortDirTmp=" + szSortDirTmp + "to Obtain with resortTable the desired new szSortDir=" + szSortDir); SortImg.setAttribute(SORT_ATTR_SORT_DIR,szSortDirTmp); this.resortTable (SortImg); }else { // only Update the Sort Icon var td = SortImg.parentNode; var iNewSortCol = td.cellIndex; // current Column [0,1...] if (iNewSortCol != this.iSortColInd && this.imgSortCur != 0){ jslog(JSLOG_JSU,"Changed Sort column from " + this.iSortColInd + " to " + iNewSortCol + " --> Reset Previous Img"); this.imgSortCur.setAttribute(SORT_ATTR_SORT_DIR,SORT_DIR.NONE); this.imgSortCur.setAttribute("title",this.szSortHintDesc); // like it is Desc because clicking it will be ASC this.imgSortCur.setAttribute("src",this.szSortPathNone); } this.iSortColInd = iNewSortCol; // Set Global Var with current Sort Col Ind this.szSortCol = this.arSortCol[this.iSortColInd].col; jslog(JSLOG_JSU,"SET iSortColInd = " + this.iSortColInd + " szSortCol=" + this.szSortCol); this.imgSortCur = SortImg; // Set also New this.szSortDir SortImg.setAttribute(SORT_ATTR_SORT_DIR,szSortDir); this.szSortDir = szSortDir; if (szSortDir == SORT_DIR.ASC){ SortImg.setAttribute("title",this.szSortHintAsc); SortImg.setAttribute("src",this.szSortPathAsc); }else{ SortImg.setAttribute("title",this.szSortHintDesc); SortImg.setAttribute("src",this.szSortPathDesc); } } jslog(JSLOG_JSU,Fn + JSLOG_FUN_END); }; /** FOR COGNOS: Exclude some cols form sorttable management (e.g. becuase they are hidden) @param ArColId [Array] with some ColId e.g ['Country','PLMN'] GLOBAL this.inputSortHiddenCol in/out (set value) this.szSortHiddenId out e.g "Carrier,PLMN" this.arSortCol */ cSortTable.prototype.sorttableSetHiddenCol= function (ArColId) { var Fn = "[cSortTable.sorttableSetHiddenCol] "; jslog(JSLOG_JSU,Fn + JSLOG_FUN_START); arTrace(JSLOG_JSU,ArColId,Fn + "ArColId"); var iSelInd = this.selectSortCol.selectedIndex; jslog(JSLOG_JSU,Fn + "this.selectSortCol iSelInd=" + iSelInd); if (iSelInd < 0){ jslog(JSLOG_JSU,Fn + "return (iSelInd <0)"); return; } // Prepare jslog(JSLOG_JSU,Fn + "Prepare this.szSortHiddenId with the ColId to Hide"); var szSortIdCur = this.selectSortCol[iSelInd].value; // Current SortId jslog(JSLOG_JSU,Fn + "szSortIdCur=" + szSortIdCur); var bSortCurHidden = false ; // true if szSortIdCur has been Hidde var iSize= ArColId.length; this.szSortHiddenId = ""; for(var i=0;i < iSize;i++) { this.szSortHiddenId += ArColId[i]; this.szSortHiddenId += ","; if (ArColId[i] == szSortIdCur){ bSortCurHidden = true; // True if the curent Sort is Hidden } } // e.g. this.szSortHiddenId =IC,COUNTRY,IC_NODE_TYPE,GATEWAY_NODE,GATEWAY_NODE_TYPE,DEST_REGION,TRUNK, jslog(JSLOG_JSU,Fn + "this.szSortHiddenId =" + this.szSortHiddenId); // Populate this.selectSortCol with only the Visible Items selectRemoveAllOption(this.selectSortCol); for (var i=0; i< this.arSortCol.length; i++){ var objSortCol = this.arSortCol[i]; var szId = objSortCol.col; var szCol = szId; // is it in the Hidden Cols? (N.B append "," at the end to avoid problem ID containing other id (e.g IC IC_NODE) var bVisible = (this.szSortHiddenId.indexOf(szId + ",") == -1); // jslog(JSLOG_JSU,Fn + "szId =" + szId + " szCol=" + szCol + " bVisible=" + bVisible); if (bVisible){ // szId is not in the Hidden Ones --> I add it appendOptionSelLast(this.selectSortCol,szCol,szId,(szId == szSortIdCur)); } } this.inputSortHiddenCol.value = this.szSortHiddenId; // if current SortCol is in the szColsExcluded reset to default Sort (FirstCol Ascending) if (bSortCurHidden){ jslog(JSLOG_JSU,Fn + "Previous SortCol Has been Hidden --> Set DefaultSort (First Col Asc)"); this.selectSortCol.selectedIndex = 0; this.selectSortDir.selectedIndex = 0; } jslog(JSLOG_JSU,Fn + JSLOG_FUN_END); }; /** * @returns Current SortCol label */ cSortTable.prototype.getSortCol= function () { return this.szSortCol; }; /** * @returns Current SortDir SORT_DIR.ASC,... */ cSortTable.prototype.getSortDir= function () { return this.szSortDir; }; /** * @returns Current SortDirLabel (Only For Cognos) */ cSortTable.prototype.getSortDirLabel= function () { if (this.selectSortDir){ return selectGetSelText(this.selectSortDir); }else{ return this.szSortDir; } }; //************************************************************************** //************************************************************************** //LOCAL FUNCTIONS (N.B prototype and using this) //************************************************************************** //************************************************************************** /*----------------------------------------------------------- Init Sort -- Create sort icons and set them ASC/DESC/NONE basing on this. variables ------------------------------------------------------------*/ cSortTable.prototype.sortInit = function () { var Fn = "[cSortTable.sortInit] "; jslog(JSLOG_JSU,Fn + JSLOG_FUN_START); jslog(JSLOG_JSU,Fn + JSLOG_FUN_START); var szId="", szCol="", szType=""; if (this.tblSort == 0){ return jslog(JSLOG_JSU,Fn + "Nothing to DO: there is NOT Table to Sort in this Page",JSLOG_FUN_START); } jslog(JSLOG_JSU,"CURRENT SORT: iSortColInd=" + this.iSortColInd + " szSortColCur=" + this.szSortCol + " szSortDirCur=" + this.szSortDir); // this.tblSort.rows = object with all the rows of the this.tblSort. The first row is Header if (this.tblSort.rows && this.tblSort.rows.length >= this.iRowSortHeader) { var sortRow = this.tblSort.rows[this.iRowSortHeader-1]; } if (!sortRow) { jslog(JSLOG_JSU,Fn + "Table without Rows to Sort. iRowSortHeader=" + this.iRowSortHeader + " NumRow=" + this.tblSort.rows.length); return; } //--------- manage click on Header when the cell is selected var iColVis = sortRow.childNodes.length; var numColHidden = 0; if (this.inputSortHiddenCol){ //when number of visible column > number of sort column var szSortHidden = this.inputSortHiddenCol.value; var ArColHidden = szSortHidden.split(","); for(var y = 0; y < ArColHidden.length; y++){ if(ArColHidden[y]!= "" && ArColHidden[y]!= null)numColHidden++; } jslog(JSLOG_JSU,Fn + "numColHidden="+numColHidden); } // Only Visible Columns will be sorted. sort ar could contains more elements (in some reports I could remove elements after) var iSortColNum = this.arSortCol.length; var iColSort = (iColVis < iSortColNum) ? iColVis : (iSortColNum - numColHidden); jslog(JSLOG_JSU,Fn + "iColVis="+iColVis + " iSortColNum=" + iSortColNum + " ---> iColSort="+iColSort); jslog(JSLOG_JSU,Fn + " Prepare icons (arSortImg), events and set Current Sort"); for (var i=0;i<iColSort;i++) { var CurCell = sortRow.cells[i]; // var txt = ts_getInnerText(CurCell); var TextSep = this.tempTextSep.cloneNode(false); // var SortImg = this.imgTemp.cloneNode(false); // SortImg.className = SORT_CLASSNAME; SortImg._cSortTableEl = this; // To be used in Event SortImg.onclick = this.onclickSortImg; var CurDir=this.szSortDir; var CurHint=this.szSortHintDesc; // LIke it is Desc, because clicking it will become Asc var CurImgPath=this.szSortPathNone; if (i == this.iSortColInd && !this.bNoStartupSortIco) { this.imgSortCur = SortImg; // Global Var // Current Sort Column if (this.szSortDir == SORT_DIR.ASC){ CurImgPath=this.szSortPathAsc; CurHint=this.szSortHintAsc; } else{ CurImgPath=this.szSortPathDesc; CurHint=this.szSortHintDesc; } } else { CurDir=SORT_DIR.NONE; } this.bNoStartupSortIco = false; // only at startup we want this flag SortImg.setAttribute(SORT_ATTR_SORT_DIR, CurDir); SortImg.setAttribute("src", CurImgPath); SortImg.setAttribute("title", CurHint); if (this.arSortCol[i].type != SORT_TYPE.NONE){ jslog(JSLOG_JSU,Fn + "ADD to Col [" + i + "] the SORT IMG - Attribute (" + SORT_ATTR_SORT_DIR + ") = " + CurDir ); CurCell.appendChild(TextSep); CurCell.appendChild(SortImg); } // Save SortImg in Global Array this.arSortImg[i] = SortImg; } jslog(JSLOG_JSU,Fn + JSLOG_FUN_END); }; /*----------------------------------------------------------- Disable SortImages (for example when the layout of Sort has changed due to filter selection) ------------------------------------------------------------*/ cSortTable.prototype.sorttableDisableSort = function () { var Fn = "[cSortTable.sorttableDisableSort] "; jslog(JSLOG_JSU,Fn + JSLOG_FUN_START); if (this.tblSort == 0){ jslog(JSLOG_JSU,Fn + "tblSort NOT VISIBLE" + JSLOG_FUN_END); return; } var ImgList = this.tblSort.getElementsByTagName("IMG"); if (ImgList == null || !ImgList.length) { jslog(JSLOG_JSU,Fn + "ImgList is Empty. Nothing to do"+ JSLOG_FUN_END); return; } this.bSortEn =false; for(var i=0; i<ImgList.length; i++) { var ImgEl = ImgList[i]; jslog(JSLOG_JSU,Fn + "className=" + ImgEl.className); if (ImgEl.className == SORT_CLASSNAME){ jslog(JSLOG_JSU,Fn + "Disable ImgEl[" + i +"]"); // NOTE we prefer to mantain it enabled and show the message SORT_HINT_DISABLED when someone click // ImgEl.disabled = true; // (this.szSortHintAsc and this.szSortHintDesc are the same in this case) ImgEl.setAttribute("title", this.szSortHintAsc); } } jslog(JSLOG_JSU,Fn + JSLOG_FUN_END); }; /* ----------------------------------------------------- NB: we have to use global var cSortTableElCur, this does not work here @param a row @param b row GLOBAL cSortTableElCur ----------------------------------------------------- */ cSortTable.prototype.ts_sort_numeric = function (a,b) { var Fn = "[cSortTable.ts_sort_numeric] "; var iSortColInd = cSortTableElCur.iSortColInd; var aCellEl = a.cells[iSortColInd]; var bCellEl = b.cells[iSortColInd]; // For FOOTER case if (bCellEl == undefined || aCellEl== undefined){ if (cSortTableElCur.szSortDirCur == SORT_DIR.ASC){ return 1; }else { return -1; } } aNumStr = ts_getInnerText(aCellEl); bNumStr = ts_getInnerText(bCellEl); //jslog (JSLOG_JSU, Fn + " aNumStr=" + aNumStr + " bNumStr="+ bNumStr); // Particular Cases to manage aNumStr and bNumStr=0 if (aNumStr.length == 0){ // jslog(JSLOG_JSU,Fn + " aNumStr=" + aNumStr + " bNumStr=" + bNumStr + " ---> return -1"); return -1; } if (bNumStr.length == 0){ // jslog(JSLOG_JSU,Fn + " aNumStr=" + aNumStr + " bNumStr=" + bNumStr + " ---> return 1"); return 1; } aNum = str2Num(aNumStr,cSortTableElCur.szSortGroupSep,cSortTableElCur.szSortDecSep); bNum = str2Num(bNumStr,cSortTableElCur.szSortGroupSep,cSortTableElCur.szSortDecSep); var iRet = 0; iRet = aNum-bNum; // jslog(JSLOG_JSU,Fn + " aNumStr=" + aNumStr + " aNum=" + aNum + " bNumStr=" + bNumStr + " bNum=" + bNum + " ---> return " + iRet); return iRet; }; /* ----------------------------------------------------- sort for DATETIME NB: we have to use global var cSortTableElCur, this does not work here @param a row @param b row GLOBAL cSortTableElCur ----------------------------------------------------- */ cSortTable.prototype.ts_sort_datetime = function (a,b) { var Fn = "[cSortTable.ts_sort_datetime] "; // jslog(JSLOG_JSU,Fn + JSLOG_FUN_START); var iSortColInd = cSortTableElCur.iSortColInd; var aCellEl = a.cells[iSortColInd]; var bCellEl = b.cells[iSortColInd]; // For FOOTER case if (bCellEl == undefined || aCellEl== undefined){ if (this.szSortDir == SORT_DIR.ASC){ return 1; }else { return -1; } } var DateTxt1 = ts_getInnerText(aCellEl); var DateTxt2 = ts_getInnerText(bCellEl); // jslog(JSLOG_JSU,Fn + " DateTxt1=" + DateTxt1 + " DateTxt2=" + DateTxt2); // Convert To date var iTime1 = getTimeFromFormat(DateTxt1,cSortTableElCur.szFmtDatetime); var iTime2 = getTimeFromFormat(DateTxt2,cSortTableElCur.szFmtDatetime); // jslog(JSLOG_JSU,Fn + " DateTxt1=" + DateTxt1 + " (" + iTime1 + ") DateTxt2=" + DateTxt2 + " (" + iTime2 + ")"); if (iTime1==iTime2) return 0; if (iTime1<iTime2) return -1; return 1; }; /* ----------------------------------------------------- sort for CURRENCY NB: we have to use global var cSortTableElCur, this does not work here @param a row @param b row GLOBAL cSortTableElCur ----------------------------------------------------- */ cSortTable.prototype.ts_sort_currency = function (a,b) { var iSortColInd = cSortTableElCur.iSortColInd; var aCellEl = a.cells[iSortColInd]; var bCellEl = b.cells[iSortColInd]; // For FOOTER case if (bCellEl == undefined || aCellEl== undefined){ if (this.szSortDir == SORT_DIR.ASC){ return 1; }else { return -1; } } aa = ts_getInnerText(aCellEl).replace(/[^0-9.]/g,''); bb = ts_getInnerText(bCellEl).replace(/[^0-9.]/g,''); return parseFloat(aa) - parseFloat(bb); }; /* ----------------------------------------------------- sort for STRING NB: we have to use global var cSortTableElCur, this does not work here @param a row @param b row GLOBAL cSortTableElCur ----------------------------------------------------- */ cSortTable.prototype.ts_sort_caseinsensitive = function (a,b) { var Fn = "[cSortTable.ts_sort_caseinsensitive] "; var iSortColInd = cSortTableElCur.iSortColInd; var aCellEl = a.cells[iSortColInd]; var bCellEl = b.cells[iSortColInd]; // For FOOTER case if (bCellEl == undefined || aCellEl== undefined){ jslog(JSLOG_JSU,Fn + " FOOTER ROW"); if (this.szSortDir == SORT_DIR.ASC){ return 1; }else { return -1; } } aa = ts_getInnerText(aCellEl).toLowerCase(); bb = ts_getInnerText(bCellEl).toLowerCase(); var iRet =0; if (aa==bb) { iRet = 0; }else if (aa<bb){ iRet = -1; }else { iRet = 1; } // jslog(JSLOG_JSU,Fn + " aa=" + aa + " bb=" + bb + " return " + iRet); return iRet; }; /*------------------------------------------------------------- Get SortId from iColInd. NOTE ar_sort_id_col is ordered but some Col can be Hidden @param iColInd in 0,1...N @return szSortId e.g "Total Roamers" GLOBAL this.arSortCol this.szSortHiddenId //Possible Hidden SortId e.g "Carrier,PLMN," -------------------------------------------------------------*/ cSortTable.prototype.getSortId = function (iColInd) { var Fn = "[cSortTable.sorttable.getSortId] "; var iColCur=-1; for (var i=0;i < this.arSortCol.length; i++){ var szSortId = this.arSortCol[i].col; if (this.szSortHiddenId.indexOf(szSortId+",") == -1){ // szId is not Hidden iColCur++; } if (iColCur == iColInd){ // jslog(JSLOG_JSU,Fn + " IN: this.szSortHiddenId=" + this.szSortHiddenId + " iColInd=" + iColInd + " OUT: szSortId=" + szSortId); return szSortId; } } return showErr (Fn + "SW ERROR: this.iSortColInd=" + this.iSortColInd + " NOT Visible iColInd=" + iColInd,1); }; /*------------------------------------------------------------- Get SortInfo from iColInd. @param iColInd in 0,1...N @return obhSortCol GLOBAL this.arSortCol -------------------------------------------------------------*/ cSortTable.prototype.getSortObj = function (iColInd) { var Fn = "[cSortTable.getSortObj] "; var szSortId = this.getSortId(iColInd); for (var i=0;i < this.arSortCol.length; i++){ var objSortCol = this.arSortCol[i]; if (objSortCol.col == szSortId){ return objSortCol; } } return showErr (Fn + "SW ERROR: this.iSortColInd=" + this.iSortColInd + " NOT Found SortId=" + szSortId,1); }; /*------------------------------------------------------------- Get SortId from iColInd. NOTE ar_sort_id_col is ordered but some Col can be Hidden @param szSortCol in e.g '<NAME>' @return iSortInd e.g 0.. -------------------------------------------------------------*/ cSortTable.prototype.getSortIndFromSortCol = function (szSortCol) { var Fn = "[cSortTable.sorttable.getSortIndFromSortCol] "; for (var i=0;i < this.arSortCol.length; i++){ var objSortCol = this.arSortCol[i]; // jslog (JSLOG_JSU,"szSortColCur=" + szSortColCur + " szSortCol=" + szSortCol); if (objSortCol.col == szSortCol){ return i; } } return showErr (Fn + "SW ERROR: szSortCol=" + szSortCol + " NOT FOUND",1); }; /*------------------------------------------------------------- It does the sort. @param SortImg in SortImg clicked -------------------------------------------------------------*/ cSortTable.prototype.resortTable = function (SortImg) { var Fn = "[cSortTable.resortTable] "; jslog(JSLOG_JSU,Fn + JSLOG_FUN_START); var td = SortImg.parentNode; var iNewSortCol = td.cellIndex; // current Column [0,1...] jslog(JSLOG_JSU,"Clicked on column=" + iNewSortCol + " Previous SortCol=" + this.iSortColInd); if (iNewSortCol != this.iSortColInd && this.imgSortCur != 0 && this.imgSortCur != undefined){ jslog(JSLOG_JSU,"Changed Sort column from " + this.iSortColInd + " to " + iNewSortCol + " --> Reset Previous Img"); this.imgSortCur.setAttribute(SORT_ATTR_SORT_DIR,SORT_DIR.NONE); this.imgSortCur.setAttribute("title",this.szSortHintDesc); // like it is Desc because clicking it will be ASC this.imgSortCur.setAttribute("src",this.szSortPathNone); } this.iSortColInd = iNewSortCol; // Set Global Var with current Sort Col Ind this.szSortCol = this.arSortCol[this.iSortColInd].col; jslog(JSLOG_JSU,"SET iSortColInd = " + this.iSortColInd + " szSortCol=" + this.szSortCol); this.imgSortCur = SortImg; // Set also New this.szSortDir var szAttrSortDir = SortImg.getAttribute(SORT_ATTR_SORT_DIR); jslog(JSLOG_JSU,Fn + "szAttrSortDir=" + szAttrSortDir ); if (szAttrSortDir == SORT_DIR.ASC) { // ASC become DESC jslog(JSLOG_JSU,Fn + "Previous Sort was ASC - TOGGLE to Dir=DESC" ); this.szSortDir = SORT_DIR.DESC; }else{ // NONE or DESC: become ASC jslog(JSLOG_JSU,Fn + "Previous Sort was NOT ASC- SET Dir=ASC" ); this.szSortDir = SORT_DIR.ASC; } SortImg.setAttribute("src", this.szSortPathWait); SortImg.setAttribute("title", "Please Wait..."); cSortTableElCur = this; // GLOBAL this.tmoSortApply = setTimeout(this.sortApply, SORT_TMO_WAIT_MS); jslog(JSLOG_JSU,Fn + JSLOG_FUN_END); }; /*----------------------------------------------------------- Only for Cognos: Set Sort Label in Header, only if the Header is Present ------------------------------------------------------------*/ cSortTable.prototype.headSetSortLbl = function () { var Fn="[cSortTable.headSetSortLbl] "; jslog(JSLOG_JSU,Fn + JSLOG_FUN_START); // NB: bShowErr False because This is an Optional Feature (spanHeaSortCol can be absent) var SpanHeaSortCol = getElementById2("spanHeaSortCol",false); var SpanHeaSortDir = getElementById2("spanHeaSortDir",false); if (SpanHeaSortCol == 0 || SpanHeaSortDir == 0){ return jslog(JSLOG_JSU,Fn + "Nothing to DO: SORTHeader is not present " + JSLOG_FUN_END); } // Set var szSortCol = this.getSortCol(); var szSortDirLabel = this.getSortDirLabel(); spanSetText(SpanHeaSortCol,szSortCol); spanSetText(SpanHeaSortDir,szSortDirLabel); jslog(JSLOG_JSU,Fn + JSLOG_FUN_END); }; /*------------------------------------------------------------- It does the sort. Called after a Timeout, to show Wait Image @param cSortTableEl in Current cSortTableEl (DO NOT use 'this' here) GLOBAL cSortTableElCur -------------------------------------------------------------*/ cSortTable.prototype.sortApply = function () { var Fn = "[cSortTable.sortApply] "; var sortfn; var dStart = new Date(); var cSortTableEl=cSortTableElCur; clearTimeout (cSortTableEl.tmoSortApply); jslog(JSLOG_JSU,Fn + JSLOG_FUN_START); jslog(JSLOG_JSU,Fn + "Doing SORT: Current iSortColInd=" + cSortTable.iSortColInd + " szSortDir=" + cSortTable.szSortDir + " bMultiPage=" + cSortTable.bMultiPage ); cSortTableEl.szSortCol = cSortTableEl.getSortId(cSortTableEl.iSortColInd); // If Present, put into Select new sort settings if (cSortTableEl.selectSortCol){ selectSelValue(cSortTableEl.selectSortCol,cSortTableEl.szSortCol); selectSelValue(cSortTableEl.selectSortDir,cSortTableEl.szSortDir); // save also into Hidden field jslog (JSLOG_JSU,Fn + "save current szSortColCur=" + cSortTableEl.szSortCol + " and szSortDirCur=" + cSortTableEl.szSortDir); cSortTableEl.inputSortCol.value = cSortTableEl.szSortCol; cSortTableEl.inputSortDir.value = cSortTableEl.szSortDir; } if (cSortTableEl.bCognosGlobalSort && cSortTableEl.bMultiPage) { // GLOBAL SORT jslog(JSLOG_JSU,Fn + "============= GLOBAL SORT ===="); // it is Like a click on OK Button return cognosActionFINISH(); } jslog(JSLOG_JSU,Fn + "============= LOCAL SORT ===="); var td = cSortTableEl.imgSortCur.parentNode; var iNewSortCol = td.cellIndex; // current Column [0,1...] jslog(JSLOG_JSU,Fn + "Clicked on column=" + iNewSortCol + " Previous SortCol=" + cSortTableEl.iSortColInd); var tblSort = cSortTableEl.tblSort; var objSortCol= cSortTableEl.getSortObj(cSortTableEl.iSortColInd); jslog(JSLOG_JSU,"NEW Sort for cSortTableEl.iSortColInd=" + cSortTableEl.iSortColInd + " SortId=" + cSortTableEl.getSortId(cSortTableEl.iSortColInd)); jslogObj(JSLOG_JSU,"objSortCol:", objSortCol); if (objSortCol.type == SORT_TYPE.NUMBER){ sortfn = cSortTableEl.ts_sort_numeric; cSortTableEl.szSortGroupSep = (objSortCol.groupSep == undefined) ? cSortTableEl.szSortGroupSepLocale : objSortCol.groupSep; cSortTableEl.szSortDecSep = (objSortCol.decimalSep == undefined) ? cSortTableEl.szSortDecSepLocale : objSortCol.decimalSep; jslog(JSLOG_JSU,"sortfn = ts_sort_numeric - Using szSortGroupSep=" + cSortTableEl.szSortGroupSep + " szSortDecSep=" + cSortTableEl.szSortDecSep); } else if (objSortCol.type == SORT_TYPE.STRING){ sortfn = cSortTableEl.ts_sort_caseinsensitive; } else if (objSortCol.type == SORT_TYPE.DATETIME){ sortfn = cSortTableEl.ts_sort_datetime; cSortTableEl.szFmtDatetime = (objSortCol.fmt == undefined) ? SORT_DEF_FMT_DATETIME : objSortCol.fmt ; jslog(JSLOG_JSU,"sortfn = ts_sort_datetime - Using cSortTableEl.szFmtDatetime=" + cSortTableEl.szFmtDatetime); } else { return showErr (Fn + "SW ERROR: Invalid SortType=" + szSortType,1); } jslog(JSLOG_JSU,"Set the attribute in the Image to indicate the direction"); var CurImgPath,CurHint; if (cSortTableEl.szSortDir == SORT_DIR.ASC){ CurImgPath=cSortTableEl.szSortPathAsc; CurHint=cSortTableEl.szSortHintAsc; } else{ CurImgPath=cSortTableEl.szSortPathDesc; CurHint=cSortTableEl.szSortHintDesc; } jslog(JSLOG_JSU,Fn + "IMG setAttribute (" + SORT_ATTR_SORT_DIR + ") = " + cSortTableEl.szSortDir); cSortTableEl.imgSortCur.setAttribute(SORT_ATTR_SORT_DIR,cSortTableEl.szSortDir); cSortTableEl.imgSortCur.setAttribute("src", CurImgPath); cSortTableEl.imgSortCur.setAttribute("title", CurHint); var newRows = new Array(); var headerRows = new Array(); // ---------------------------------- Header jslog (JSLOG_JSU,Fn + "Prepare newRow with the Row to Sort - We skip First HEADER Rows=" + cSortTableEl.iRowHeader); for (var j=cSortTableEl.iRowHeader, i=0;j<tblSort.rows.length ;j++, i++) { newRows[i] = tblSort.rows[j]; } // SORT jslog(JSLOG_JSU,"Start Sort Ascending..."); // salvo la var globale cSortTableElCur = cSortTableEl; newRows.sort(sortfn); jslog(JSLOG_JSU,"Sort Ascending done"); if (cSortTableEl.szSortDir == SORT_DIR.DESC){ newRows.reverse(); jslog(JSLOG_JSU,"Reverse done - Sort Descending Done"); } // We appendChild rows that already exist to the tbody, so it moves them rather than creating new ones // we don't do it for SORT_TBL_CLASS_FOOTER rows for (i=0;i<newRows.length;i++) { var szClassName = newRows[i].className; var bFooter = (szClassName != undefined && szClassName.indexOf(cSortTableEl.szClassFooter) >=0); if (!bFooter){ tblSort.tBodies[0].appendChild(newRows[i]); } } // do SORT_TBL_CLASS_FOOTER rows only for (i=0;i<newRows.length;i++) { var szClassName = newRows[i].className; var bFooter = (szClassName != undefined && szClassName.indexOf(cSortTableEl.szClassFooter) >=0); if (bFooter) { tblSort.tBodies[0].appendChild(newRows[i]); } } // --------------------- if (cSortTableEl.bCognos){ cSortTableEl.headSetSortLbl(); // Align Sort Label in Header if Present Sort Section } jslogElapsedTime (JSLOG_JSU,Fn + "DONE in ",dStart); jslog(JSLOG_JSU,Fn + JSLOG_FUN_END); }; cSortTable.prototype.getParent = function (el, pTagName) { if (el == null) return null; else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase()) // Gecko bug, supposed to be uppercase return el; else return this.getParent(el.parentNode, pTagName); }; /*----------------------------------------------------------- onchange selectSortCol ------------------------------------------------------------*/ cSortTable.prototype.onchangeSortCol = function (ev) { var Fn = "[cSortTable.onchangeSortCol] "; jslog(JSLOG_JSU,Fn + JSLOG_FUN_START); var cSortTableEl = cSortTable.getSortTableElFromEv(Fn,ev); var szSortId = selectGetSelVal(cSortTableEl.selectSortCol); jslog(JSLOG_JSU,Fn + "Save into this.inputSortCol the selected szSortId=" + szSortId); cSortTableEl.inputSortCol.value = szSortId; jslog(JSLOG_JSU,Fn + JSLOG_FUN_END); }; /*----------------------------------------------------------- onchange selectSortDir ------------------------------------------------------------*/ cSortTable.prototype.onchangeSortDir = function (ev) { var Fn = "[cSortTable.onchangeSortDir] "; jslog(JSLOG_JSU,Fn + JSLOG_FUN_START); var cSortTableEl = cSortTable.getSortTableElFromEv(Fn,ev); var iSortDir = selectGetSelVal(cSortTableEl.selectSortDir); jslog(JSLOG_JSU,Fn + "Save into this.inputSortDir the selected iSortDir=" + iSortDir); cSortTableEl.inputSortDir.value = iSortDir; jslog(JSLOG_JSU,Fn + JSLOG_FUN_END); }; /*------------------------------------------------------------- this.bSortEn = false. the click on images will display the Hint this.bSortEn = true Toggle sort and Sort the table basing on GLOBAL this.bSortEn in --------------------------------------------------------------*/ cSortTable.prototype.onclickSortImg= function (ev) { var Fn = "[cSortTable.onclickSortImg] "; jslog(JSLOG_JSU,Fn + JSLOG_FUN_START); var cSortTableEl = cSortTable.getSortTableElFromEv(Fn,ev); // this is the current element clicked var TagName = this.tagName; var CurImg; jslog(JSLOG_JSU,Fn + "this=" + this +" tagName=" + TagName); if (typeof (TagName) != 'undefined' && TagName.toUpperCase() == "IMG"){ // Normal "Working" Click CurImg = this; } else { // WorkAround for IE: when it is selected the cell Header, "this" variable is not the td. In this case I use imgSortCur if (cSortTableEl.imgSortCur){ jslog(JSLOG_JSU,Fn + "Workaround for IE Header Seleted: Use imgSortCur"); CurImg = cSortTableEl.imgSortCur; } else { jslog(JSLOG_ERR,Fn + "imgSortCur=null CANNOT Apply workaround for IE"); return; } } if (cSortTableEl.bSortEn){ cSortTableEl.resortTable (CurImg); }else { showInfo (cSortTableEl.szSortHintAsc); } jslog(JSLOG_JSU,Fn + JSLOG_FUN_END); }; //********************************************************************************************* // LOCAL FUNCTION //********************************************************************************************* /*----------------------------------------------------------- Get Current SortTable instance from Event PAR Fn in Function name calling this function ev in Event ------------------------------------------------------------*/ cSortTable.getSortTableElFromEv = function(Fn,ev) { var Fn = "[cSortTable.getSortTableElFromEv] "; jslog(JSLOG_JSU,Fn + JSLOG_FUN_START); // get current element var El = cSortTable.getElement(ev); // N.B Get Current cSortTable instance (cSortTableEl) var cSortTableEl = El._cSortTableEl; if (typeof (cSortTableEl) == "undefined"){ showErr (Fn + "SW ERROR: cSortTableEl is undefined in " + Fn,1); }else { // Log one member jslog(JSLOG_JSU, Fn + "cSortTableEl.szSortPathAsc=" + cSortTableEl.szSortPathAsc); } jslog(JSLOG_JSU,Fn + JSLOG_FUN_END); return cSortTableEl; }; //************************************************************************** //************************************************************************** //Utility Function (NO Prototype) //************************************************************************** //************************************************************************** cSortTable.getElement = function(ev) { var f = cSortTable.is_ie ? window.event.srcElement : ev.currentTarget; while (f.nodeType != 1 || /^div$/i.test(f.tagName)) f = f.parentNode; return f; }; /// detect a special case of "web browser" cSortTable.is_ie = ( /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent) ); <file_sep>/core/util.js /** @fileOverview ========================================================================================= <BR/> <b>File:</b> core/util.js <BR/> <b>Author:</b> <a href="https://www.linkedin.com/in/federicolevis" target="_self"><NAME></a> <BR/> <b>LoadingDiv Doc:</b> <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/HTML/LoadingDiv.html" target="_self">JSU LoadingDiv Documentation</a> <BR/> <b>JSU API Doc:</b> <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/JSUAPI.html" target="_self">JSU API Documentation</a> <BR/> <b>Description:</b> common JSU utility API:<ul> <li> select* API for select </li> <li> ..... other common API </li> </ul> <b>REQUIRE:</b> JSU: jslog.js dom-drag.js <BR/> <b>First Version:</b> ver 1.0 - Jul 2007 <BR/> <b>Current Version:</b> JSU v. 1.10 &nbsp;&nbsp;&nbsp;2018-Jan-14 <BR/> <BR/>-----------------------------------------------------------------------------------<BR/> <b>DISCLAIMER</b> <BR/> Copyright by <NAME> - <a href="https://github.com/JSUtility/JSU" target="_self">JSU</a> <BR/> This file may be freely distributed under the MIT license. <BR/> ========================================================================================= <BR/> */ // ================================================= LANGUAGE For alert of User Error (SW ERROR are always in English) // can be change with utilSetLanMsg var SW_DEBUG_ENABLE = 0; // 1 during SW DEBUG. KEEP ALWAYS 0- in release var LAN_MSG_EN = "EN"; var LAN_MSG_ITA = "ITA"; var lan_msg = LAN_MSG_EN; // per funzioni arPmt var SELECT_VALUE_ID_SEP = "."; // separator between ID in a select var SELECT_NOVALUE_SEL = "-1"; //------------ var TAG_SELECT = "SELECT"; //Prefix used by Cognos var ID_PREFIX_SELECT = "selectList"; // Optionally you can add a Div with a loading Image, that you can show/hide during long operation with setLoading API var ID_DIV_LOADING_IMG = "jsuLoading"; //navigator.appName values var APP_NAME_FIREFOX="Netscape"; // FIREFOX var APP_NAME_IE="Microsoft Internet Explorer"; // IE //'&nbsp;' CODE var NBSP_CODE = 160; // Default number separators var DEF_COGNOS_GROUP_SEP = ","; var DEF_COGNOS_DECIMAL_SEP = "."; //Used in inputxxxxChecked ,.. var VAL_CB_CHECKED = "1"; var VAL_CB_UNCHECKED = "0"; var BROWSER_TYPE ={ IE: "IE", FIREFOX: "FIREFOX", OTHER: "OTHER" }; //************************************************************************** // ERROR WARN FUNCTIONS //************************************************************************** /* * * Replace in str di tutte le occorrenze di strFrom, che vengono sostituite con strTo * @param str es: "questa frase contiene Pippo 2 volte perche` alla fine ripeto Pippo" * @param strFrom es: "Pippo" * @param strTo es: "Paperino" * @returns str es: "questa frase contiene Paperino 2 volte perche` alla fine ripeto Paperino" */ function replaceAll(str,strFrom,strTo) { if (typeof(str) == "undefined"){ return ""; } while (str.indexOf(strFrom)>-1) { str = str.replace(strFrom,strTo); } return str; } function obj2Html(obj){ var szHtml = JSON.stringify(obj,null,4); szHtml = replaceAll (szHtml,"\n","<BR/>"); return replaceAll (szHtml," ","&nbsp;&nbsp;"); } /** * * @param szMsgHtml * @returns szMsg in Text Format, that can be displayed by alert */ function msgHtml2Str(szMsgHtml){ // ------- \n instead of specific TAG var szMsg= szMsgHtml.replace(/<BR\/>/gi, '\n'); szMsg= szMsg.replace(/<ul/gi, '\n<ul'); // BUllet szMsg= szMsg.replace(/<li>/gi, ' \u2022 '); szMsg= szMsg.replace(/<li /gi, ' \u2022 <li '); szMsg= szMsg.replace(/<\/li>/gi, '\n'); szMsg= szMsg.replace(/<\/ul>/gi, '\n'); // Table // Table Header szMsg= szMsg.replace(/<th /gi, '\n<th '); szMsg= szMsg.replace(/<th>/gi, '\n<th>'); // Table Row szMsg= szMsg.replace(/<tr /gi, '\n \u2024 <tr '); szMsg= szMsg.replace(/<tr>/gi, '\n \u2024 '); szMsg= szMsg.replace(/<\/td>/gi, ' - '); // var szMsg= szMsg.replace(/<(?:.|\n)*?>/gm, ''); szMsg= szMsg.replace(/<[^>]*>?/gm, ''); var arLetter = ['a','A','e','E','u','U','o','O','i','I']; var arType =["grave", "acute", "tilde", "dierese"]; for (var iLetter=0; iLetter < arLetter.length; iLetter ++){ for (var iType=0; iType < arType.length; iType ++){ var szFrom = "&" + arLetter[iLetter] + arType[iType] + ';'; var szTo = arLetter[iLetter] + "`"; // E.G: szMsg= strReplaceAll(szMsg,"&ograve;", "o`"); szMsg = strReplaceAll (szMsg,szFrom, szTo); } } return szMsg; } /** * Replace strange char to allow display as Text * * @param szStr * @returns szStr without Strange Char */ /* UNDER WORK * function str2DisplayText(szStr){ var szStr2 =szStr; var ar2Replace = [[/À/g,"\A`"], [/à/g,"a`"], [/[ÀÁÂÃÅ]/g,"\A`"], [/è/g,"e`"], [/ì/g,"i`"], [/ò/g,"o`"], [/ù/g,"u`"] ]; for (var i=0;i<ar2Replace.length; i++){ var szPatt = new RegExp(ar2Replace[i][0]); szStr2 = szStr2.replace (szPatt,ar2Replace[i][1]); } return szStr2; } */ /*----------------------------------------------------------- Check if Popup function is defined (e.g IEPopup.js is loaded) RETURN true if Popup function is defined -----------------------------------------------------------*/ function popupIsDefined (){ return (typeof (Popup) == 'function'); } /*----------------------------------------------------------- Show an alert and return iRetVal PAR szMsgHtml in Msg to show Can contain also Html Tag iRetVal in RETURN iRetVal -----------------------------------------------------------*/ function showAlert(szMsgHtml, iRetVal){ alert (msgHtml2Str(szMsgHtml)); return iRetVal; } /*----------------------------------------------------------- Show a Info @param szMsgHtml in Msg to show Can contain also Html Tag @param [objOpt] {Object} Optional Object for Popup API if used -----------------------------------------------------------*/ function showInfo (szMsgHtml, objOpt){ jslog(JSLOG_INFO,szMsgHtml) ; if (popupIsDefined()){ Popup (POPUP_TYPE.INFO,szMsgHtml,objOpt); }else { showAlert (szMsgHtml,0); } } /*----------------------------------------------------------- Show a Warning and return iRetVal @param szMsgHtml in Msg to show Can contain also Html Tag @param iRetVal in Value to Return @param [objOpt] {Object} Optional Object for Popup API if used @return iRetVal -----------------------------------------------------------*/ function showWarn (szMsgHtml,iRetVal, objOpt){ jslog(JSLOG_INFO,szMsgHtml) ; if (popupIsDefined()){ Popup (POPUP_TYPE.WARN,szMsgHtml, objOpt); }else { showAlert (szMsgHtml,iRetVal); } return iRetVal; } /*----------------------------------------------------------- Show an Error and return iRetVal PAR @param szMsgHtml in Msg to show Can contain also Html Tag @param [iRetVal] {NUmber} [1] in Value to Return @param [objOpt] {Object} Optional Object for Popup API if used @return iRetVal -----------------------------------------------------------*/ function showErr (szMsgHtml, iRetVal, objOpt){ jslog(JSLOG_ERR,szMsgHtml) ; if (iRetVal == undefined){ iRetVal =1; } if (popupIsDefined()){ Popup (POPUP_TYPE.ERR,szMsgHtml,objOpt); }else { showAlert (szMsgHtml,iRetVal); } return iRetVal; } /*----------------------------------------------------------- 8.4 Show an Error if required (bShowErr = true) PAR bShowErr in true if I want to show Error false if don't want to show Error szMsgErr in Msg to show iRetVal in Value to Return RETURN iRetVal -----------------------------------------------------------*/ function showErrIfRequired (bShowErr,szMsgErr,iRetVal){ if (bShowErr){ showErr (szMsgErr,iRetVal); } return iRetVal; } /** * @returns {String} BROWSER_TYPE.IE, BROWSER_TYPE.FIREFOX, BROWSER_TYPE.OTHER */ function getBrowser(){ var Fn = "[Popup.js PopupGetBrowser] "; var szAppName = navigator.appName; var szBrowser = BROWSER_TYPE.OTHER; // if (navigator.appName == APP_NAME_FIREFOX ){ if (typeof InstallTrigger !== 'undefined'){ szBrowser = BROWSER_TYPE.FIREFOX; } else if ((navigator.appName == APP_NAME_IE) || ((navigator.appName == APP_NAME_IE_11) && (new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})").exec(navigator.userAgent) != null))){ szBrowser = BROWSER_TYPE.IE; } jslog(JSLOG_TEST,Fn + "szBrowser=" + szBrowser + " - navigator.appCodeName=" + navigator.appCodeName + " navigator.appName=" + navigator.appName); return szBrowser; } /*----------------------------------------------------------- Check if the Current Browser is Firefox RETURN true is Mozilla Firefox false it is not Mozilla Firefox -----------------------------------------------------------*/ function isFirefox() { return (getBrowser() == BROWSER_TYPE.FIREFOX); } /** * * @returns {Boolean} true if the window is inside an Iframe */ function isInIframe(){ try { return (window.self !== window.top); }catch(e){ return true; } } /*----------------------------------------------------------- Check if the Current Browser is IE RETURN true is IE false it is not IE -----------------------------------------------------------*/ function isIE() { return (getBrowser() == BROWSER_TYPE.IE); } //DAFARE portare in util.js e mettere warining se non c'e` la var con Popup che dice NOn supportata nella Demo versione //fare anche quella che fa Object function cookieSetVar(szCookieName, szCookieValue) { document.cookie = szCookieName + "=" + szCookieValue; alert ("document.cookie=" + document.cookie); } function cookieGetVar(szCookieName) { var name = szCookieName + "="; alert ("document.cookie=" + document.cookie); var ca = document.cookie.split(';'); for(var i=0; i<ca.length; i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1); if (c.indexOf(name) == 0) return c.substring(name.length, c.length); } return ""; } //************************************************************************** // Get Element //************************************************************************** /*----------------------------------------------------------- Get Element By ID and Show Error if required PAR Id in [bShowErr] in true (default) if I want to show Error false if don't want to show Error RETURN el if founded 0 if not founded -----------------------------------------------------------*/ function getElementById2(Id,bShowErr) { if (bShowErr == undefined){ bShowErr = false; } var el = document.getElementById(Id); if (el == null) { if (bShowErr && SW_DEBUG_ENABLE){ // TODO some problem with IE Debugger alert("SW ERROR [util.js getElementById2] NOT FOUND Id=" + Id) ; } return 0; // Not Found } return el; } /*----------------------------------------------------------- Get Element By ID and Show Error if required PAR Id in bShowErr in true if I want to show Error false if don't want to show Error Fn in Fn calling, to be added in ErrMsg RETURN el if founded 0 if not founded -----------------------------------------------------------*/ function getElementById3(Id,bShowErr,Fn) { var el = document.getElementById (Id); if (el == null) { if (bShowErr){ showErr("SW ERROR [util.js getElementById3] NOT FOUND Id=" + Id) ; } return 0; // Not Found } return el; } /* */ function getElementById(Id) { return getElementById2(Id,true); } function getElementByTag2(szTag,szSpanId,bShowErr) { return getElementBySpanId2(szSpanId,szTag,bShowErr); } function getFirstFsByBlock(szBlock,bShowErr) { var Fn = "[util.js getFieldset2] "; var block = getElementById2 (szBlock,bShowErr); if (!block){ return 0; } // Get List of all elements with tag try { var fsList = block.getElementsByTagName("FIELDSET"); if (!fsList.length){ return 0; } return fsList[0]; } catch (e){} if (bShowErr) { jslog(JSLOG_ERR,Fn + "NOT FOUND FiledSet in Block=" + szBlock); } } /*----------------------------------------------------------- Get a DOM element of a specific Tag using the SpanId of the Span that is before the element PAR szSpanId in szTag in e.g "INPUT", "SELECT",.. bShowErr in true if I want to show Error false if don't want to show Error RETURN DomEl if found 0 if not found -----------------------------------------------------------*/ function getElementBySpanId2(szSpanId, szTag, bShowErr) { if(szTag.toLowerCase()=="button"){ var button = getButtonBySpanId2(szSpanId, bShowErr); if(button) return button; } var Fn = "[util.js getElementBySpanId2] "; // jslog(JSLOG_JSU, Fn + JSLOG_FUN_START); var SpanEl = document.getElementById (szSpanId); if (SpanEl == null) { return showErrIfRequired (bShowErr,Fn + " NOT FOUND SpanId=" + szSpanId,0); } // Get List of all elements with tag var ElList = SpanEl.getElementsByTagName(szTag); if (ElList == null || !ElList.length) { return showErrIfRequired (bShowErr,Fn + " NOT FOUND Elements with Tag=" + szTag + " for SpanId=" + szSpanId,0); } var El = ElList[ElList.length-1]; // jslog(JSLOG_JSU, Fn + "IN: SpanId=" + szSpanId + " Tag=\"" + szTag + "\"" + " OUT: El Id=" + El.id + " Name=" + El.name); // jslog(JSLOG_JSU,Fn + JSLOG_FUN_END); return El; } /*----------------------------------------------------------- Get a DOM element of a specific Tag and Clas using the SpanId of the Span that is before the element PAR szSpanId in szTag in e.g "INPUT", "SELECT",.. szClass in e.g 'clsSelectDateEditBox' to get the INPUT that show the Date in a pickdateControl bShowErr in true if I want to show Error false if don't want to show Error RETURN DomEl if found 0 if not found -----------------------------------------------------------*/ function getElementOfClassBySpanId2(szSpanId, szTag, szClass, bShowErr) { var Fn = "[util.js getElementOfClassBySpanId2] "; // jslog(JSLOG_JSU, Fn + JSLOG_FUN_START); var SpanEl = document.getElementById (szSpanId); if (SpanEl == null) { return showErrIfRequired (bShowErr,Fn + " NOT FOUND SpanId=" + szSpanId,0); } // Get List of all elements with tag var ElList = SpanEl.getElementsByTagName(szTag); if (ElList == null || !ElList.length) { return showErrIfRequired (bShowErr,Fn + " NOT FOUND Elements with Tag=" + szTag + " for SpanId=" + szSpanId,0); } // look for class var bFound = false; var El = 0; for (var i=0; !bFound && i< ElList.length; i++){ El = ElList[i]; if (El.className == szClass){ bFound = true; } } if (!bFound){ return showErrIfRequired (bShowErr,Fn + " NOT FOUND Elements with Tag=" + szTag + " and Class=" + szClass + " for SpanId=" + szSpanId,0); } // jslog(JSLOG_JSU, Fn + "IN: SpanId=" + szSpanId + " Tag=\"" + szTag + "\"" + " OUT: El Id=" + El.id + " Name=" + El.name); // jslog(JSLOG_JSU,Fn + JSLOG_FUN_END); return El; } /*----------------------------------------------------------- Get a Block using the SpanId of the Span that is before the element PAR szSpanId in bShowErr in true if I want to show Error false if don't want to show Error RETURN BlockEl if founded 0 if not founded -----------------------------------------------------------*/ function getBlockBySpanId2(szSpanId, bShowErr) { var Fn = "[util.js getBlockBySpanId2] "; var span = getElementById2(szSpanId, bShowErr); if (!span ){ return 0; } return span.firstChild; } function getButtonBySpanId2(szSpanId, bShowErr) { var Fn = "[util.js getButtonBySpanId2] "; jslog(JSLOG_JSU, Fn + JSLOG_FUN_START); jslog(JSLOG_JSU, Fn + "IN: SpanId=" + szSpanId + "\""); var SpanEl = document.getElementById (szSpanId); if (SpanEl == null) { return showErrIfRequired (bShowErr,Fn + " NOT FOUND SpanId=" + szSpanId,0); } // Get List of all elements with tag var ElList = SpanEl.getElementsByTagName("INPUT"); if (ElList == null || !ElList.length) { ElList = SpanEl.getElementsByTagName("BUTTON"); } if (ElList == null || !ElList.length) { return showErrIfRequired (bShowErr,Fn + " NOT FOUND Elements with Tag=INPUT/BUTTON for SpanId=" + szSpanId,0); } for(var i = 0; i < ElList.length; i++) { try{ if(ElList[i].type.toLowerCase() == "button"){ jslog(JSLOG_JSU,Fn + "OUT: El Id=" + ElList[i].id + " Name=" + ElList[i].name); return ElList[i]; } } catch(err){ } } showErrIfRequired (bShowErr,Fn + " NOT FOUND Button for SpanId=" + szSpanId,0); return 0; } /* * @param Caption * @param bShowErr * @returns */ function getFieldset2(Caption,bShowErr) { var Fn = "[util.js getFieldset2] "; // Get List of all elements with tag try { var o = document.getElementsByTagName("FIELDSET"); // jslog(JSLOG_JSU,Fn + "getFieldset o.length=" + o.length); for (var i=0; i<o.length; i++) { var el = o[i]; var firstChild = el.firstChild; //legend if (firstChild) { // Look for "fieldSetCaption" "LEGEND" var TagName = firstChild.tagName; if (TagName == "LEGEND"){ // var TextContent = String(firstChild.textContent); var CurCaption = String(firstChild.innerHTML); if (CurCaption.split(Caption).length > 1) { jslog(JSLOG_JSU,Fn + "FOUND Caption=" + Caption + " in textContent=" + CurCaption) ; return o[i]; // N.B: if return el is wrong, all point to the same! } } } } } catch (e){} if (bShowErr) { jslog(JSLOG_ERR,Fn + "NOT FOUND Caption=" + Caption); } return 0; } /** * get FieldSet by Caption * @param Caption * @returns {Object} */ function getFieldset(Caption) { return getFieldset2(Caption,false); } //************************************************************************** // locale //************************************************************************** /*------------------------------------------------------------- Return Group Separator used for Current locale RETURN e.g "," --------------------------------------------------------------*/ function localeGetGroupSep() { var Fn = "[util.js localeGetGroupSep] "; //jslog(JSLOG_JSU,Fn + JSLOG_FUN_START); var Num=1234; var NumStr=Num.toLocaleString(); var Sep = NumStr.charAt(1); if (Sep == "2"){ Sep = ""; // Group separator can be absent } jslog(JSLOG_JSU,Fn + "GroupSeparetor=" + Sep); return Sep; } /*------------------------------------------------------------- Return Decimal Separator t used for Current locale RETURN e.g "." --------------------------------------------------------------*/ function localeGetDecimalSep() { var Fn = "[util.js localeGetDecimalSep] "; var Num=1.23; // this is always a number with decimal var NumStr=Num.toLocaleString(); var Sep = NumStr.charAt(1); if (Sep == "2"){ Sep = "."; //default jslog(JSLOG_ERR,Fn + "DecimalSeparetor NOT found. Used default = " + Sep); } jslog(JSLOG_JSU,Fn + "DecimalSeparetor=" + Sep); return Sep; } //************************************************************************** // Conversion //************************************************************************** /*------------------------------------------------------------- Replace all occurrences of from with to @param szOrig in @param from in e.g "&nbsp;" @param to in e.g " " @return --------------------------------------------------------------*/ function strReplaceAll (szOrig,szFrom,szTo){ var szNew = szOrig; while (szNew.indexOf(szFrom) >=0){ szNew = szNew.replace (szFrom,szTo); } return szNew; } /*------------------------------------------------------------- 8.4 PARAMETER NumStr in e.g "1,234.56" GroupSep in e.g "," DecimalSep in e.g "." RETURN Float e.g 1234.55 --------------------------------------------------------------*/ function str2Num(NumStr,GroupSep,DecimalSep) { NumStr2 = NumStr; if (typeof(GroupSep) != 'undefined' && GroupSep.length){ while (NumStr2.indexOf(GroupSep) > -1){ NumStr2 = NumStr2.replace(GroupSep,""); } } // Replace DecimalSeparetor with "." if (typeof(DecimalSep) != 'undefined' && DecimalSep != "."){ NumStr2 = NumStr2.replace(DecimalSep,"."); } Num = parseFloat(NumStr2); if (isNaN(Num)) Num = 0; return Num; } /** * @param iNum e.g 123 * @param szPad "0" * @param iLenWithPad 5 * @returns "00123 */ function num2StrPad(iNum,szPad, iLenWithPad) { var iZeroPad = iLenWithPad - iNum.toString().length + 1; return Array(+(iZeroPad > 0 && iZeroPad)).join("0") + iNum; } /*------------------------------------------------------------- 8.4 Get String from Cognos Text. For example convert "&nbsp;" into " " &nbsp; is the entity used to represent a non-breaking space PAR Text in e.g "NNN&nbsp;dd,&nbsp;yyyy&nbsp;HH:mm" RETURN String e.g "NNN dd, yyyy HH:mm" --------------------------------------------------------------*/ function html2Str(Text) { var Fn = "[util.js html2Str] "; var Text2 = new String(""); // replace "&nbsp;" with " " // First we try with String Text=strReplaceAll(Text,"&nbsp;"," "); // Second: Try to Replace The Single CODE for (var i=0; i < Text.length; i++){ var Code = Text.charCodeAt(i); var Ch= Text.charAt(i); if (Code == NBSP_CODE){ // jslog(JSLOG_JSU,Fn + "Found " + Code+ " at pos=" + i); // it is '&nbsp;' Ch=' '; } Text2 = Text2 + Ch; } // jslog(JSLOG_JSU,Fn + "IN=" + Text + " OUT=" + Text2); return Text2; } /* ==================================================================================================================== * Object Serialize - Deserialize ==================================================================================================================== */ /*----------------------------------------------------------- Serialize an object into a String NOTE: Use objDeserialize to get the object from String @param obj {Object} in The object to serialize EXAMPLE obj.objFilterR.bTensioneDis=false obj.objFilterR.iBloccoEnNum=1 obj.objFilterR.szIsoDataDa":"2016-01-01" obj will be serialized as: {"objFilterR":{"bTensioneDis":false,"iBloccoEnNum":1,"szIsoDataA":"2016-02-23"}} ------------------------------------------------------------*/ function objSerialize(obj) { return JSON.stringify(obj,null,0); } /*----------------------------------------------------------- Deserialize an object that was serialized with objSerialize @param szObj {String} in Example: {"objFilterR":{"bTensioneDis":false,"iBloccoEnNum":1,"szIsoDataA":"2016-02-23"}} @return obj {Object} The object that was serialized into szobj ------------------------------------------------------------*/ function objDeserialize(szObj) { var obj; if (szObj == undefined || szObj.length == 0){ obj = new Object(); // Empty Object }else { obj = JSON.parse(szObj); } return obj; } /*----------------------------------------------------------- Serialize an object into a String and then Encode it into URI NOTE: Use objFromURI to get the object from URI @param obj {Object} in The object to serialize Es {szAlertType='Info',.....} @return szObjURIQueryString es ?%7B%22szAlertType%22%3A%22Info....... ------------------------------------------------------------*/ function obj2URI(obj) { return encodeURIComponent(objSerialize(obj)); } /*----------------------------------------------------------- Deserialize an object that was serialized and Encoded into URI with obj2URI @param szObj {String} in Example: '{"szAlertType"="Info",.....}' @return obj {Object} The object that was serialized into szobj. Ex: {szAlertType='Info',.....} ------------------------------------------------------------*/ function objFromURI(szObjURI) { var Fn = "[util.js objFromURI]"; var obj; var szObj = szObjURI; if (szObj == undefined || szObj.length == 0){ obj = new Object(); // Empty Object }else { var szObj = decodeURIComponent(szObjURI); obj = objDeserialize(szObj); } // alert (Fn + "obj=" + JSON.stringify(obj,null,0)); return obj; } /*----------------------------------------------------------- Serialize an object into a String and Encode it into URI QuesryString NOTES: - like obj2URI with also ? added ad the beginning - Use objFromURIQueryString to Get the Object @param obj {Object} in The object to serialize Es {szAlertType='Info',.....} @return szObjURIQueryString e.g. ?%7B%22szAlertType%22%3A%22Info....... ------------------------------------------------------------*/ function obj2URIQueryString(obj) { var szObjURI = encodeURIComponent(objSerialize(obj)); if (szObjURI.length){ return "?" + szObjURI; }else { return ""; } } /*----------------------------------------------------------- Deserialize an object that was serialized and Encoded into URI with obj2URI @param szObjURIQueryString e.g. ?%7B%22szAlertType%22%3A%22Info....... @return obj {Object} The object that was serialized into szobj. Ex: {szAlertType='Info',.....} null if Error or szObjURIQueryString Empty ------------------------------------------------------------*/ function objFromURIQueryString(szURIQueryString) { var obj; if (szURIQueryString.length){ return objFromURI(szURIQueryString.substr(1)); }else{ return null; } } //************************************************************************** // SELECT FUNCTION //************************************************************************** /* -------------------------------------------------------------------------------- Get Index of First Opt with Value Containing szValue PAR Select in szValue in value to Find RETURN -1 if Not Found Not Found (or Error) 0.. Index of First Opt Containing Value -------------------------------------------------------------------------------- */ function selectGetFirstIndWithVal(Select,szValue) { var Fn = "[util.js selectGetFirstIndWithVal] "; if (!Select){ jslog(JSLOG_JSU,Fn + " Select is NULL!"); return -1; } for (i=0; i < Select.options.length ; i++) { Opt = Select[i]; if (Opt.value.indexOf(szValue) > -1){ jslog(JSLOG_JSU,Fn + " Value=" + szValue + " First contained in opt[" + i + "]"); return i; } } jslog(JSLOG_JSU,Fn + " Value=" + szValue + " is not contained in any opt of select"); return -1; } /* -------------------------------------------------------------------------------- populate ArOpt with all the Option of a select PAR Select in ArOpt in/out Array of cOpt RETURN -1 if Not Found Not Found (or Error) N Number of Optiion (ArOpt Size) -------------------------------------------------------------------------------- */ function select2ar(Select,ArOpt) { var Fn = "[util.js select2ar] "; // Clear ArOpt for (i = 0; i < ArOpt.length; i++){ ArOpt.pop(); } if (!Select){ jslog(JSLOG_JSU,Fn + " Select is NULL!"); return -1; } for (i=0; i < Select.options.length ; i++) { Opt = Select[i]; ArOpt[i] = new cOpt(Opt.text,Opt.value); } return ArOpt.length; } /* -------------------------------------------------------------------------------- populate ArOpt with the Option of a select starting from iStartInd PAR Select in iSelectStartInd in _ArOpt out Array of cOpt RETURN -1 if Not Found Not Found (or Error) N Number of Option (ArOpt Size) -------------------------------------------------------------------------------- */ function select2arFromInd(Select,iSelectStartInd,_ArOpt) { var Fn = "[util.js select2arFromInd] "; jslog(JSLOG_JSU,Fn + JSLOG_FUN_START); jslog(JSLOG_JSU,Fn + " IN iSelectStartInd=" + iSelectStartInd); // Clear ArOpt for (i = 0; i < _ArOpt.length; i++){ _ArOpt.pop(); } if (!Select){ jslog(JSLOG_JSU,Fn + " Select is NULL!"); return -1; } for (iAr=0, i=iSelectStartInd; i < Select.options.length ; i++, iAr++) { Opt = Select[i]; _ArOpt[iAr] = new cOpt(Opt.text,Opt.value); } jslog(JSLOG_JSU,Fn + " RETURN _ArOpt.length=" + _ArOpt.length); jslog(JSLOG_JSU,Fn + JSLOG_FUN_END); return _ArOpt.length; } /* -------------------------------------------------------------------------------- populate ArOpt with the Option of a select Till iEndInd (With also iSelectEndInd) PAR Select in iSelectEndInd in _ArOpt out Array of cOpt RETURN -1 if Not Found Not Found (or Error) N Number of Option (ArOpt Size) -------------------------------------------------------------------------------- */ function select2arTillInd(Select,iSelectEndInd,_ArOpt) { var Fn = "[util.js select2arFromInd] "; jslog(JSLOG_JSU,Fn + JSLOG_FUN_START); jslog(JSLOG_JSU,Fn + " IN iSelectEndInd=" + iSelectEndInd); // Clear ArOpt for (i = 0; i < _ArOpt.length; i++){ _ArOpt.pop(); } if (!Select){ jslog(JSLOG_JSU,Fn + " Select is NULL!"); return -1; } for (iAr=0, i=0; (i < Select.options.length && i <= iSelectEndInd) ; i++, iAr++) { Opt = Select[i]; _ArOpt[iAr] = new cOpt(Opt.text,Opt.value); } jslog(JSLOG_JSU,Fn + " RETURN _ArOpt.length=" + _ArOpt.length); jslog(JSLOG_JSU,Fn + JSLOG_FUN_END); return _ArOpt.length; } /* -------------------------------------------------------------------------------- Get Number of Selected Items in Select PAR Select in RETURN N Number of Itemns selected 0 No Items Selected -1 if Select Not Found (or Error) -------------------------------------------------------------------------------- */ function selectGetSelectedNum(Select) { var Fn = "[util.js selectGetSelectedNum] "; if (!Select){ jslog(JSLOG_ERR,Fn + " Select is NULL!"); return -1; } var iSelNum=0; var iOptNum=Select.options.length; for (var i=0; i < iOptNum; i++) { var Opt = Select[i]; if (Opt.selected){ iSelNum++; } } return iSelNum; } /* Look for value in select and return relative text. If not found set to DefText PAR Select i sel object Value i String that identify value DefText i Default Value to return if not found Value */ function selectGetTextFromValue(Select,Value,DefText) { var Fn = "[util.js selectGetTextFromValue] "; //jslog(JSLOG_JSU,Fn + JSLOG_FUN_START); if (!Select){ jslog(JSLOG_JSU,Fn + " Select is NULL - RETURN DefText=" + DefText); return DefText; } // jslog(JSLOG_JSU,"[util.js selectGetTextFromValue] size=" + Select.options.length); for (var i=0; i < Select.options.length; i++) { var CurValue = html2Str (Select[i].value); if (CurValue == Value) { var CurText = html2Str (Select[i].text); jslog(JSLOG_JSU,Fn + "Value=" +Value + " FOUND - RETURN Text=" + CurText); return CurText; } } // It is not an Error, it is allowed. return DefText jslog(JSLOG_JSU,Fn + " Value=" +Value + " NOT FOUND - RETURN DefText=" + DefText); return DefText; } /*================================================================== Remove All Option (Items) ==================================================================*/ function selectRemoveAllOption(Select) { if (Select != 0){ for (i = Select.length - 1; i >= 0; i--) { Select[i] = null; } } } /*================================================================== Remove All Option (Items), preserving First N ==================================================================*/ function selectRemoveOption(Select,iPreserveFirstN) { if (Select != 0){ for (i = Select.length - 1; i >= iPreserveFirstN; i--) { Select[i] = null; } } } /* 8.4 Look for first occurence of Value in a select and select it if found RETURN SelIndex if found and selected -1 if Not Found */ function selectSelValue(Select,Value) { var Fn = "[util.js selectSelValue] "; if (!Select){ jslog(JSLOG_ERR,Fn + " Select is NULL!"); return -1; } for (var i=0; i < Select.options.length; i++) { var Opt = Select[i]; var CurValue = html2Str (Opt.value ); if (CurValue == Value) { // jslog(JSLOG_JSU,Fn + " Found Value=" + Value + " in " + Select.name + " Text=" + Opt.text + "\nRETURN SelInd=" + i); Opt.selected = true; Select.selectedIndex = i; return i; } } // This is not an Error: if I try to select a value not present I simply trace it and return -1 jslog(JSLOG_JSU,Fn + " NOT FOUND Value=" + Value + " in " + Select.name); return -1; } // if Select != 0 Remove first 2 elements (dded by Cognos), only if they are present function selectRemoveCognosEl(Select) { removeExtraItems(Select); /* if (Select){ Select.remove(1); Select.remove(0); Select.removeAttribute("hasLabel"); } */ } /* 8.4 Look for first occurrence of Value in a select and remove it if found RETURN SelIndex if found -1 if Not Found */ function selectRemoveValue(Select,Value) { var Fn = "[util.js selectRemoveValue] "; if (!Select){ jslog(JSLOG_ERR,Fn + " Select is NULL!"); return -1; } for (var i=0; i < Select.options.length; i++) { var Opt = Select[i]; var CurValue = html2Str (Opt.value ); if (CurValue == Value) { jslog(JSLOG_JSU,Fn + " Found Value=" + Value + " in " + Select.name + " Text=" + Opt.text + "\n SelInd=" + i + " NOW REMOVING IT"); Select[i]=null; return i; } } jslog(JSLOG_JSU,Fn + " NOT FOUND Value=" + Value + " in " + Select.name); return -1; } /* --------------------------------------------------- Remove All Options of a Select ---------------------------------------------------*/ function selectRemoveAll(Select) { var Fn = "[util.js selectRemoveAll] "; var i=0; if (!Select){ jslog(JSLOG_ERR,Fn + " Select is NULL!"); return -1; } for (i = Select.length - 1; i >= 0; i--) { Select[i] = null; } } /* --------------------------------------------------- RETURN TRUE selet is MultiSelect FALSE selet is NOT MultiSelect ---------------------------------------------------*/ function selectIsMulti(Select) { var Fn = "[util.js selectIsMulti] "; return Select.multiple; } /* --------------------------------------------------- if they are present We remove the 2 Extra items added to the beggining of the select by Cognos e.g. FilterTimeMode --------------- PAR Select in --------------------------------------------------- */ function selectRemoveExtraItems(Select) { var Fn = "[util.js selectGetTextFromValue] "; if(!Select || Select.options.length < 1) { return; } // jslog(JSLOG_JSU,Fn + "Removing 2 Extra Items from Select" + Select.name); try{ var szText = Select.childNodes[1].text; if(szText.match("----")){ Select.remove(1); Select.remove(0); Select.removeAttribute("hasLabel"); jslog(JSLOG_JSU,Fn + "Succesfully Removed 2 Extra Items from Select " + Select.name); return; } } catch(err){ //ignore it } } /* Look for first occurence of Text in a select and select it if found RETURN SelIndex if found and selected -1 if Not Found */ function selectSelText(Select,Text) { var Fn = "[util.js selectSelText] "; if (!Select){ jslog(JSLOG_ERR,Fn + " Select is NULL!"); return -1; } // jslog(JSLOG_JSU,Fn + Select.name + " len=" + Select.options.length); for (var i=0; i < Select.options.length; i++) { var Opt = Select[i]; var CurText = html2Str (Opt.text); // jslog(JSLOG_JSU,Fn + " CurText=" + CurText + " len= " + CurText.length + ") Looking for Text=" + Text + " (len=" + Text.length + ")"); if (CurText == Text) { jslog(JSLOG_JSU,Fn + " SELECT Found Text=" + Text + " in " + Select.name + "\nValue=" + Opt.value+ "\nRETURN SelInd=" + i); Opt.selected = true; return i; } } jslog(JSLOG_JSU,Fn + " NOT FOUND Text=" + Text + " in " + Select.name); return -1; } /* Get Text of Opt with Value PAR Select in Value in RETURN Text related to Opt with Value */ function selectGetTextOfValue(Select,Value) { var Fn = "[util.js selectGetTextOfValue] "; if (!Select){ jslog(JSLOG_ERR,Fn + " Select is NULL!"); return "Select is NULL"; } for (var i=0; i < Select.options.length; i++) { var Opt = Select[i]; var CurValue = html2Str (Opt.value); if (CurValue == Value) { var Text = html2Str (Opt.text); jslog(JSLOG_JSU,Fn + " Found Value=" + Value + " Text=" + Text); return Text; } } return Value + " NOT FOUND"; } /* Get value of Opt with Text PAR Select in Text in RETURN Value related to Opt with Text */ function selectGetValueOfText(Select,Text) { var szText1 = html2Str (Text); var Fn = "[util.js selectGetValueOfText] "; if (!Select){ jslog(JSLOG_ERR,Fn + " Select is NULL!"); return "Select is NULL"; } for (var i=0; i < Select.options.length; i++) { var Opt = Select[i]; var CurText = html2Str (Opt.text); if (CurText == szText1) { var Value = html2Str (Opt.value); jslog(JSLOG_JSU,Fn + " Found Text=" + szText1+ " Value=" + Value); return Value; } } return Text + " NOT FOUND"; } /* Get Sel Status of OPt with value=Value PAR Select in Value in RETURN SelStatus (true or false) */ function selectGelSelectedStatus(Select,Value) { var Fn = "[util.js selectSelValue] "; var SelectedStatus = false; if (!Select){ jslog(JSLOG_ERR,Fn + " Select is NULL!"); return SelectedStatus; } for (var i=0; i < Select.options.length; i++) { var Opt = Select[i]; var CurValue = html2Str (Opt.value ); if (CurValue == Value) { //jslog(JSLOG_JSU,Fn + " Found Value=" + Value + " in " + Select.name + " Text=" + Opt.text + " Selected=" + Opt.selected); return Opt.selected; } } return SelectedStatus; } /* Get a String with the List of text values of a select (useful for Debug) */ function selectGetDesc(Select) { var Desc = new String("name: " + Select.name + "\n\ntext value\n\n"); for (var i=0; i < Select.options.length; i++) { var Opt = Select[i]; var Line = new String("\n" + Opt.text + " " + Opt.value); Desc += Line; } return Desc; } function appendOptionLast(Select,Text,Value) { var Opt = new Option(Text, Value); Select[Select.length] = Opt; Opt.dv = Text; } function appendOptionSelLast(Select,Text,Value,bSel) { appendOptionLast(Select,Text,Value); if (bSel){ var Opt = Select[Select.length-1]; Opt.selected = true; } } /*---------------------------------------------------------------------------------------------- Get the List of Elements of a Multi Select PAR Select in _ArId out Array with the IDs (value) RETURN _ArId.length ----------------------------------------------------------------------------------------------*/ function selectGetList (Select,_ArId){ var Fn = "[util.js selectGetList] "; // jslog(JSLOG_JSU,Fn + JSLOG_FUN_START); if (!Select){ return jslog(JSLOG_JSU,Fn + "Select =0 NOTHING to DO"); } _ArId.length=0; var iAr=0; for (var iOpt=0; iOpt < Select.options.length; iOpt ++){ var Opt = Select.options[iOpt]; _ArId[iAr++] = Opt.value; } // jslog(JSLOG_JSU,Fn + " return _ArId.length=" +_ArId.length + " " + JSLOG_FUN_START); return _ArId.length; } /*---------------------------------------------------------------------------------------------- Get the List of Elements Selected in a Multi Select PAR Select in _ArSelId out Array with the IDs (value) selected RETURN _ArSelId.length (Number of Element Selected) ----------------------------------------------------------------------------------------------*/ function selectGetSelList (Select,_ArSelId){ var Fn = "[util.js selectGetSelList] "; if (!Select){ return jslog(JSLOG_JSU,Fn + "Select =0 NOTHING to DO"); } // jslog(JSLOG_JSU,Fn + JSLOG_FUN_START); _ArSelId.length=0; var iAr=0; for (var iOpt=0; iOpt < Select.options.length; iOpt ++){ var Opt = Select.options[iOpt]; if (Opt.selected){ _ArSelId[iAr++] = Opt.value; } } // jslog(JSLOG_JSU,Fn + " return _ArSelId.length=" +_ArSelId.length + " " + JSLOG_FUN_START); return _ArSelId.length; } /*---------------------------------------------------------------------------------------------- Get the Number of Elements Selected PAR Select in RETURN iSelNum -1 ERR ----------------------------------------------------------------------------------------------*/ function selectGetSelNum (Select){ var Fn = "[util.js selectGetSelNum] "; var iSelNum = 0; if (!Select){ jslog(JSLOG_JSU,Fn + "Select =0 NOTHING to DO"); return 0; } for (var iOpt=0; iOpt < Select.options.length; iOpt ++){ var Opt = Select.options[iOpt]; if (Opt.selected){ iSelNum ++; } } jslog(JSLOG_JSU,Fn + " return iSelNum=" + iSelNum); return iSelNum; } /*---------------------------------------------------------------------------------------------- Get the Number of Items (Options) in Select PAR Select in RETURN iItemNum -1 ERR ----------------------------------------------------------------------------------------------*/ function selectGetOptNum (Select){ var Fn = "[util.js selectGetOptNum ] "; if (!Select){ jslog(JSLOG_JSU,Fn + "Select =0 return 0"); return 0; } return Select.options.length; } /*---------------------------------------------------------------------------------------------- Get the Number of Elements that will be considered in Filter basing on current selection: PAR Select in RETURN iNumFilterEl: - if iSelNum > 0 : iNumFilterEl = iSelNum - if iSelNum=0 : iNumFilterEl = iNumItem (ALL entries will be considered in Filter) ----------------------------------------------------------------------------------------------*/ function selectGetNumFilterEl (Select){ var Fn = "[util.js selectGetNumFilterEl] "; var iSelNum = selectGetSelNum (Select); if (iSelNum < 0) { return 0; } var iNumFilterEl = (iSelNum > 0) ? iSelNum : Select.options.length; jslog(JSLOG_JSU,Fn + "iSelNNum=" + iSelNum + " return iNumFilterEl=" +iNumFilterEl); return iNumFilterEl; } /*---------------------------------------------------------------------------------------------- Get the Labels of the Elements Selected in a Multi Select. They can be displayed in Report Heading PAR Select in RETURN e.g 2degrees - GSM 900/1800 - NEW ZEALAND, 3 - 3G 2100 - SWEDEN ----------------------------------------------------------------------------------------------*/ function selectGetSelLabels (Select){ var Fn = "[util.js selectGetSelList] "; var szSelLabels = ""; var bFirst = true; if (!Select){ return jslog(JSLOG_JSU,Fn + "Select =0 NOTHING to DO"); } for (var iOpt=0; iOpt < Select.options.length; iOpt ++){ var Opt = Select.options[iOpt]; if (Opt.selected){ if (bFirst){ szSelLabels = Opt.text; bFirst = false; } else { szSelLabels = szSelLabels + ", " + Opt.text; } } } return szSelLabels; } /*---------------------------------------------------------------------------------------------- Get the values of the Elements Selected in a Multi Select. e.g. They can be used in a Where condition or to find a Value PAR Select in bValueAsString in [false] true if the values must be considered as String, adding '' RETURN e.g bValueAsString=false 1, 4, 12 e.g bValueAsString=false MT, BT e.g bValueAsString=true 'MT', 'BT' ----------------------------------------------------------------------------------------------*/ function selectGetSelValues (Select,bValueAsString){ var Fn = "[util.js selectGetSelValues] "; var szSelValues = ""; var bFirst = true; if (bValueAsString == undefined){ bValueAsString = false; } if (!Select){ return jslog(JSLOG_JSU,Fn + "Select =0 NOTHING to DO"); } for (var iOpt=0; iOpt < Select.options.length; iOpt ++){ var Opt = Select.options[iOpt]; if (Opt.selected){ var szSelVal = Opt.value; if (bValueAsString){ szSelVal = "'" + szSelVal + "'"; } if (bFirst){ szSelValues = szSelVal; bFirst = false; } else { szSelValues = szSelValues + ", " + szSelVal; } } } return szSelValues; } /*---------------------------------------------------------------------------------------------- Get the values of the Elements in a Multi Select. e.g. They can be used in a Where condition or to find a Value PAR Select in bValueAsString in [false] true if the values must be considered as String, adding '' RETURN e.g bValueAsString=false 1, 4, 12 e.g bValueAsString=false MT, BT e.g bValueAsString=true 'MT', 'BT' ----------------------------------------------------------------------------------------------*/ function selectGetValues (Select, bValueAsString){ var Fn = "[util.js selectGetValues] "; var szValues = ""; var bFirst = true; if (bValueAsString == undefined){ bValueAsString = false; } if (!Select){ return jslog(JSLOG_JSU,Fn + "Select =0 NOTHING to DO"); } for (var iOpt=0; iOpt < Select.options.length; iOpt ++){ var Opt = Select.options[iOpt]; var szVal = Opt.value; if (bValueAsString){ szVal = "'" + szVal + "'"; } if (bFirst){ szValues = szVal; bFirst = false; } else { szValues = szValues + ", " + szVal; } } return szValues; } /*---------------------------------------------------------------------------------------------- Deselect All Item in a Multi Select PAR Select in ----------------------------------------------------------------------------------------------*/ function selectDeselectAll (Select){ var Fn = "[util.js selectDeselectAll] "; if (!Select){ return jslog(JSLOG_JSU,Fn + "Select =0 NOTHING to DO"); } if (Select.selectedIndex != -1){ Select.selectedIndex = -1; } /* for (var iOpt=0; iOpt < Select.options.length; iOpt ++){ var Opt = Select.options[iOpt]; Opt.selected = false; } */ } /*---------------------------------------------------------------------------------------------- select All Item in a Multi Select PAR Select in ----------------------------------------------------------------------------------------------*/ function selectSelectAll (Select){ var Fn = "[util.js selectSelectAll] "; if (!Select){ return jslog(JSLOG_JSU,Fn + "Select =0 NOTHING to DO"); } for (var iOpt=0; iOpt < Select.options.length; iOpt ++){ var Opt = Select.options[iOpt]; Opt.selected = true; } } /*---------------------------------------------------------------------------------------------- Get the Value Selected in selectedIndex PAR Select in bValueAsString in [false] true if the values must be considered as String, adding '' RETURN SelValue or "-1" if Nothing Selected (SELECT_NOVALUE_SEL) Es: bValueAsString=true "'MT'" Es: bValueAsString=true "" (ALL Item selected) ----------------------------------------------------------------------------------------------*/ function selectGetSelVal (Select,bValueAsString){ var Fn = "[util.js selectGetSelVal] "; var szSelVal = SELECT_NOVALUE_SEL; if (bValueAsString == undefined){ bValueAsString = false; } if (!Select){ return szSelVal; } var iSelInd = Select.selectedIndex; if (iSelInd < 0){ return szSelVal; } szSelVal = html2Str(Select.options[iSelInd].value); if (bValueAsString){ // NOTE: if "" it is ALL item. we mantain it without adding ' if (szSelVal.length){ szSelVal = "'" + szSelVal + "'"; } } return szSelVal; } /*---------------------------------------------------------------------------------------------- Get the Value Selected in a Single select PAR Select in RETURN SelValue or "-1" if Nothing Selected (SELECT_NOVALUE_SEL) ----------------------------------------------------------------------------------------------*/ function selectGetSelText (Select){ var Fn = "[util.js selectGetSelText] "; var szSelText = SELECT_NOVALUE_SEL; if (!Select){ return szSelText; } var iSelInd = Select.selectedIndex; if (iSelInd < 0){ return szSelText; } return html2Str(Select.options[iSelInd].text); } /** * Populate an empty select * @param select * @param arOpt * @param szSelVal */ function selectPopulate(select, arOpt, szSelVal){ if (select == null || select == 0){ return; } for (var i=0; i< arOpt.length; i++){ var el = arOpt[i]; var bSel = (el[0] == szSelVal); appendOptionSelLast (select,el[1],el[0],bSel); } } /*----------------------------------------------------------- Read Select and if it has Items selected, it Adds "AND condition" PAR Select in szDbId in e.g "ROAMINGTYPE" szFilter in Current Filter e.g "PLMNCARRIERID=1001 AND DIRECTION = 1" RETURN szFilter (with the new condition) e.g "PLMNCARRIERID=1001 AND DIRECTION = 1 ANd ROAMINGTYPE IN (1,2)" ------------------------------------------------------------*/ function selectAddFilterCond(Select,szDbId,szFilter) { var szFilterAnd = (szFilter.length < 4) ? " " : " AND "; var Fn = "[util.js selectAddFilterCond] "; jslog(JSLOG_JSU,Fn + JSLOG_FUN_START); jslog(JSLOG_JSU,Fn + "IN: szFilter=" + szFilter); var ArSelId= new Array(); var ArId= new Array(); var iFilterNum = selectGetSelList (Select,ArSelId); if (iFilterNum == 1){ szFilter += szFilterAnd + szDbId + " = " + ArSelId[0]; } else if (iFilterNum > 1){ szFilter += szFilterAnd + szDbId +" IN (" + ar2List(ArSelId) + ")"; } jslog(JSLOG_JSU,Fn + "OUT: szFilter=" + szFilter); jslog(JSLOG_JSU,Fn + JSLOG_FUN_END); return szFilter; } /*----------------------------------------------------------- Get the Select All and Deselect All Elements in a Block having a Select List PAR szBlockId in Span containing the Block with the select _ArSelAllEl out Array with [SelectAll,DeselectAll] bShowEr in RETURN 0 OK Other Error ------------------------------------------------------------*/ function getSelAllEl(szBlockId,_ArEl,bShowEr) { var Fn = "[util.js getSelAllEl] "; jslog(JSLOG_JSU,Fn + JSLOG_FUN_START); jslog(JSLOG_JSU,Fn + "IN szBlockId=" + szBlockId); var iSize = 0; var BlockEl = document.getElementById (szBlockId); if (BlockEl == null) { return showErrIfRequired (bShowEr,Fn + " NOT FOUND BlockId=" + szBlockId,1); } // Get List of all elements with tag 'A' ("Select All" "Delect All"), Present only if it is a MultiSelect ElList = BlockEl.getElementsByTagName("A"); if (ElList == null || ElList.length != 2) { return showErrIfRequired (bShowEr,Fn + " NOT FOUND the 2 Elements with Tag A for BlockId=" + szBlockId,1); } _ArEl[iSize++] = ElList[0]; _ArEl[iSize++] = ElList[1]; jslog(JSLOG_JSU,Fn + JSLOG_FUN_END); return 0; // OK } /*----------------------------------------------------------- Move the Select/Deselect All object of a filter to the Right (instead of below) PAR szFilterNameId in e.g "TrType" --> "blockFilterTrType", "spanSelectAllTrType","spanDeselectAllTrType" bShowEr in RETURN 0 OK Other Error ------------------------------------------------------------*/ function filterSelAllEl2R(szFilterNameId,bShowEr) { var Fn = "[util.js filterSelAllEl2R] "; jslog(JSLOG_JSU,Fn + JSLOG_FUN_START); jslog(JSLOG_JSU,Fn + "IN szFilterNameId=" + szFilterNameId); var ArSelEl = new Array(); // Get "Select All" and "Deselect All" Object getSelAllEl ("blockFilter" + szFilterNameId,ArSelEl,bShowEr); // Move the object into the spans on the right var ArSpanEl = new Array("spanSelectAll" + szFilterNameId,"spanDeselectAll" + szFilterNameId); for (iAr=0; iAr < 2;iAr++){ var Span = getElementById2(ArSpanEl[iAr],bShowEr); Span.appendChild (ArSelEl [iAr]); ArSelEl [iAr].style.fontSize = "8pt"; } return 0; // OK } //************************************************************************** // Loading and Cursor Wait //************************************************************************** function setCursorWait(bWait) { // jslog(JSLOG_JSU,"setCursorWait " + bWait); var Cursor = bWait ? 'wait' : 'default'; document.body.style.cursor = Cursor; // ------------------------ set Wait cursor also for all the elements var TagAr = new Array("IMG","TD","INPUT","BUTTON","SELECT"); for (var ArInd=0; ArInd < TagAr.length; ArInd++) { var Tag = TagAr[ArInd]; var o = document.getElementsByTagName(Tag); for (var i=0; i<o.length; i++) { var el = o[i]; el.style.cursor = Cursor; } } } /** * Show/Hide the Load Image into a specific element, on its right * @param szElId {String} e.g "inputEl1" * @param bShow {Boolean} true to set Loading Image */ function loadingShowIn1ElId(szElId,bShow){ var el = getElementById2(szElId,true); loadingShowIn1El (el,bShow); } /** * Show/Hide the Load Image into a specific element, on its right * @param el {Object} e.g * @param bShow {Boolean} true to set Loading Image */ function loadingShowIn1El(el,bShow){ if (el){ classAdd (el,'jsuLoadingEl',bShow); } } /** * @return {Object} The Loading Div or 0 if Not present */ function loadingGetEl(){ return getElementById2(ID_DIV_LOADING_IMG,false); } /** * Show/Hide the Loading Div Image * @param el {Object} the div with the Loading Image * @param bShow {Boolean} true to set Loading Image */ function loadingShowByEl(el,bShow){ if (el){ classAdd (el,'jsuLoading',bShow); elementShow(el,bShow); } } /** * Show/Hide the Loading Div Image * @param bShow {Boolean} true to set Loading Image */ function loadingShow(bShow){ setCursorWait (bShow); var el = getElementById2(ID_DIV_LOADING_IMG,false); if (el){ classAdd (el,'jsuLoading',bShow); elementShow(el,bShow); } } /** * Show/Hide the Alarm Image into a specific element, on its right * @param szElId {String} e.g "inputEl1" * @param bLoading {Boolean} true to set Loading Image * @return 1 */ function alarmShowIn1ElId(szElId,bShow){ var el = getElementById2(szElId,true); return alarmShowIn1El (el,bShow); } /** * Show/Hide the Alarm Image into a specific element, on its right * @param el {Object} e.g * @param bShow {Boolean} true to set Loading Image * @return 1 */ function alarmShowIn1El(el,bShow){ if (el){ classAdd (el,'jsuAlarmingEl',bShow); } return 1; } /** * @param el {Object} DOM el * @param szClass {String} Class To add or remove * @param bAdd {Boolean} true=Add false=remove */ function classAdd (el, szClass, bAdd){ var Fn = "[util.js classAdd] "; var szClassCur = el.className; if (szClassCur == undefined){ szClassCur = ""; } var bPresent = szClassCur.indexOf (szClass) >=0; if (bAdd){ if (!bPresent){ // we have to add it if (szClassCur == ""){ szClassCur = szClass; }else{ szClassCur = szClassCur + " " + szClass; } } }else { // Remove szClassCur = szClassCur.replace(" " + szClass, ""); szClassCur = szClassCur.replace(szClass, ""); } el.className = szClassCur; // jslog (JSLOG_TEST,Fn + "IN szClass=" + szClass + " bAdd=" + bAdd + " - el.id=" + el.id + " class SET FROM + '" + szClassCur + "' TO '" + el.className + "'"); } function ts_getInnerText(el) { if (typeof el == "string") return el; if (typeof el == "undefined") { return el; } if (el.innerText) return el.innerText; //Not needed but it is faster var str = ""; var cs = el.childNodes; var l = cs.length; for (var i = 0; i < l; i++) { switch (cs[i].nodeType) { case 1: //ELEMENT_NODE str += ts_getInnerText(cs[i]); break; case 3: //TEXT_NODE str += cs[i].nodeValue; break; } } return str; } /*----------------------------------------------------------- Show/Hide an Element (and its Children) PAR szSpan in e.g 'sectFilterIntPrev' bShow in true if I want to show it false if I want to hide it ------------------------------------------------------------*/ function elementShowBySpan(szSpan,bShow) { var Fn = "[util.js elementShowBySpan ]"; var El = getElementById2 (szSpan,false); // jslog(JSLOG_JSU,Fn + "szSpan=" + szSpan + " bShow=" +bShow + " getElementById2 return El=" + El + " (NOTE: El can be 0, in this case nothing to do)"); if (El){ elementShow(El,bShow); } } /*----------------------------------------------------------- Check if an Element is Visible PAR szSpan in e.g 'sectFilterIntPrev' RETURN true if it is visible false if it is not visible ------------------------------------------------------------*/ function elementIsVisibleBySpan(szSpan) { var Fn = "[util.js elementIsVisibleBySpan ]"; var bVisible = false; var El = getElementById2 (szSpan,false); if (El){ bVisible = (El.style.visibility != "hidden"); } return bVisible; } /*----------------------------------------------------------- Show/Hide an Element (and its Children) PAR El in Object bShow in true if I want to show it false if I want to hide it ------------------------------------------------------------*/ /** * @param El * @param bShow * @param [szDisplayIfVisible] {String} display to set if bShow=true e.g "inline" (default= "block") */ function elementShow(El,bShow,szDisplayIfVisible) { var Fn = "[util.js elementShow ]"; if (El == 0 || El == undefined){ return; } if (szDisplayIfVisible == undefined){ szDisplayIfVisible = "block"; } if (bShow){ El.style.visibility="visible"; /* El.style.display="block"; */ El.style.display=szDisplayIfVisible; }else { El.style.visibility="hidden"; El.style.display="none"; } } /** * @param szElId {String} id of El * @param bShow {Boolean} * @param [szDisplayIfVisible] {String} display to set if bShow=true e.g "inline" (default= "block") */ function elementShowById(szElId,bShow,szDisplayIfVisible) { // var Fn = "[util.js elementShowById ]"; var El = getElementById2(szElId,false); elementShow (El,bShow,szDisplayIfVisible); } /** * @param elem * @returns {Object} .top .left .height .width */ function elementGetWinCoords(elem) { // crossbrowser version var box = elem.getBoundingClientRect(); var body = document.body; var docEl = document.documentElement; var scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop; var scrollLeft = window.pageXOffset || docEl.scrollLeft || body.scrollLeft; var clientTop = docEl.clientTop || body.clientTop || 0; var clientLeft = docEl.clientLeft || body.clientLeft || 0; var top = box.top + scrollTop - clientTop; var left = box.left + scrollLeft - clientLeft; return { top: Math.round(top), left: Math.round(left), height: elem.clientHeight, width: elem.clientWidth }; } /*** * add on page load events */ function addLoadEvent(func) { var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { oldonload(); func(); }; } } /*** * set cookie for a page * * @parameter: name: the name of the cookie * @parameter: days: days of expiration */ function createCookie(name,value,days) { var expires = ""; if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); expires = "; expires="+date.toGMTString(); } try{ document.cookie = name+"="+value+expires+"; path=/"; }catch(err){ // ignore it } } /*** * read the cookie of a page * @parameter: name: the name of the cookie * @return: the value of the cookie */ function readCookie(name) { var nameEQ = name + "="; try{ var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } }catch(err){ // ignore it } return null; } /*** * erase the cookie of a page * @parameter: name: the name of the cookie */ function eraseCookie(name) { createCookie(name,"",-1); } /*** * get the paramter from the url query string * @parmater name: the name of the paramter * @return: the value in the url (the first one) */ function getRequestParameter( name ) { name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); var regexS = "[util.js \\?&]"+name+"=([^&#]*)"; var regex = new RegExp( regexS ); var plainString = unescape(window.location.href); var results = regex.exec( plainString ); if( results == null ) return ""; else return results[1]; } /** * Find all elements with same id ( which exists on static view report) * paramter id: the element id * return array of elements with the same id */ function getElementsWithSameId(id){ var nodes = []; var tmpNode = document.getElementById(id); while(tmpNode){ nodes.push(tmpNode); tmpNode.id = ""; tmpNode = document.getElementById(id); } for(var x=0; x<nodes.length; x++){ nodes[x].id = id; } return nodes; } /*----------------------------------------------------------- Set Text in a Span PAR Span in szText in -----------------------------------------------------------*/ function spanSetTextById(szSpanId,szText,bShowErr) { var SpanId = getElementById2 (szSpanId,bShowErr); if (SpanId){ spanSetText(SpanId, szText); } } /*----------------------------------------------------------- Get Text from a Span PAR Span in RETURN szText -----------------------------------------------------------*/ function spanGetTextById(szSpanId,bShowErr) { var SpanId = getElementById2 (szSpanId,bShowErr); if (SpanId){ return spanGetText(SpanId); } else { return ("szSpanId=" + szSpanId + " NOT FOUND"); } } /*----------------------------------------------------------- Set Text in a Span PAR Span in szText in -----------------------------------------------------------*/ function spanSetText(Span,szText) { var Fn = "[util.js spanSetText] "; // jslog(JSLOG_JSU,Fn + JSLOG_FUN_START); // jslog(JSLOG_JSU,Fn + "IN szTxt=" + szText); if (Span){ // Span.firstChild.textContent=szText; Span.firstChild.innerHTML = szText; } // jslog(JSLOG_JSU,Fn + JSLOG_FUN_END); } /*----------------------------------------------------------- Get Text From a Span PAR Span in RETURN szText -----------------------------------------------------------*/ function spanGetText(Span) { if (Span == 0 || Span.firstChild == 0){ return ""; } var szText = Span.firstChild.innerHTML; return szText.replace ("&nbsp;",""); } /*************************************************************************************************************** BLOCK FUNCTION ***************************************************************************************************************/ /*----------------------------------------------------------- Set Padding to a Block PAR szBlock in span identifying the Block e.g "blockFilterService" szPAD IN pADDING Top Right Bottom Left" bShowEr in RETURN 0 OK Other Error ------------------------------------------------------------*/ function blockSetPad(szBlock,szPad) { var Fn = "[util.js blockSetPad] "; // jslog(JSLOG_JSU,Fn + JSLOG_FUN_START); // jslog(JSLOG_JSU,Fn + " IN: szBlock=" + szBlock + " szPad=" + szPad); var Block = getBlockBySpanId2(szBlock,true); if (Block == 0){ // ERROR return showErr(Fn + "NOT Find szBlock=" + szBlock,1); } Block.style.padding=szPad; // jslog(JSLOG_JSU,Fn + JSLOG_FUN_END); return 0; // OK } /* ------------------------------------------------------------------------- Reset a TextBox contained in the Block identified by szBlockName PAR szBlock in e.g. "blockKpiVal" bShowEr in ------------------------------------------------------------------------- */ function blockRangeReset(szBlock,bShowEr) { var Fn = "[util.js blockRangeReset] "; jslog(JSLOG_JSU,Fn + JSLOG_FUN_START); jslog(JSLOG_JSU,Fn + " IN: szBlock=" + szBlock); var BlockEl = document.getElementById (szBlock); if (BlockEl == null) { return showErrIfRequired (bShowEr,Fn + " NOT FOUND szBlock=" + szBlock,1); } // Get List of all elements with tag 'INPUT' var ElList = BlockEl.getElementsByTagName("INPUT"); if (ElList == null || !ElList.length) { return showErrIfRequired (bShowEr,Fn + " NOT FOUND Elements with Tag INPUT for szBlock=" + szBlock,1); } var iSize = ElList.length - 1; var ArRb = new Array(); var ArText = new Array(); var iArRb = 0, iArText = 0; for (var iEl=0; iEl < ElList.length; iEl++){ var El = ElList[iEl]; if (El.type == "radio"){ ArRb[iArRb++]=El; } else if (El.type == "text"){ ArText[iArText++]=El; } } jslog(JSLOG_JSU,Fn + " Found " + iArRb + " RB and " + iArText + " TEXT"); if ((iArRb != 4) || (iArText != 2)){ jslog(JSLOG_JSU,Fn + " Wrong Number of RB or TEXT, cannot continue"); return 1; } ArRb[1].checked = true; ArRb[3].checked = true; ArText[0].value = ""; ArText[1].value = ""; jslog(JSLOG_JSU,Fn + JSLOG_FUN_END); return 0; // OK } //************************************************************************** //************************************************************************** // Array Functions //************************************************************************** //************************************************************************** /*----------------------------------------------------------- From an Array of IDs to the List of IDs PAR ArId in e.g [11,15,76] RETURN szList e.g '11,15,76' ------------------------------------------------------------*/ function ar2List(ArId) { var Fn = "[util.js ar2List] "; var szList = ""; var iLen = ArId.length; // jslog(JSLOG_JSU,Fn + JSLOG_FUN_START); if (!iLen){ return szList; } szList = ArId[0]; for (var i=1; i < iLen; i++){ szList += ("," + ArId[i]); } // jslog(JSLOG_JSU,Fn + JSLOG_FUN_END); return szList; } /*----------------------------------------------------------- Trace an Array of "Single Element" that can be traced PAR iTrLev in TraceLev Ar in e.g [11,15,76] e.g ["elem1","elem2"] szArName in e.g "ArSel" ------------------------------------------------------------*/ function arTrace(iTrLev,Ar,szArName) { var iLen = Ar.length; jslog(iTrLev,szArName + ".length = " + iLen); for (var iAr=0; iAr < iLen; iAr++){ jslog(iTrLev,szArName + "[util.js " + iAr + "] = " + Ar[iAr]); } } /*************************************************************************************************************** CHECK FUNCTION ***************************************************************************************************************/ /*----------------------------------------------------------- Check that a Filter doesn't contain more than iMaxItem selected - If there are more Items selected an Error is displayed and the function return 1 - Else if OK it return 0 For example with ORACLE: - ORA-01704 (string literal too long ) with String longer than 4000 - MaxItem was 1000 in the IN Clause (Maybe now it have been removed, but we should verify that Cognos doesn't crash) NOTE: check only select-multiple Filters, if single is not required PAR szFilterName in e.g "COUNTRY" szFilterItemsName in e.g "Countries" Select in iMinItem in e.g 0 or 1... iMaxItem in e.g 200 bNoSelLikeAllSel in if true 0 sel is considered like All Selected RETURN 0 OK 1 Err -----------------------------------------------------------*/ function selectCheckNumItem (szFilterName,szFilterItemsName,Select,iMinItem,iMaxItem,bNoSelLikeAllSel) { var Fn = "[util.js filterCheckNumItem] "; jslog(JSLOG_JSU,Fn + JSLOG_FUN_START); if (Select == 0){ return showErr ("Fn=" + Fn + " Select is null",1); } // if it is MultiSelect var szType = Select.type; if (szType == 'undefined' || szType != "select-multiple"){ jslog(JSLOG_JSU,Fn + "NOTHING to CHECK: szFilterName=" + szFilterName + " Is Not select-multiple. (select has select.type=" + szType + ")"); return 0; } var iSelNum = selectGetSelectedNum (Select); if (iSelNum == 0 && bNoSelLikeAllSel){ iSelNum = Select.options.length; jslog(JSLOG_JSU,Fn + "0 Selected - We set iSel = NumOfOptions=" + iSelNum ); } jslog(JSLOG_JSU,"szFilterName=" + szFilterName + " iSelNum=" + iSelNum + " iMinItem=" + iMinItem + " iMaxItem=" + iMaxItem); if (iSelNum > iMaxItem || iSelNum < iMinItem){ var szEr = ERR_FILTER_MAX_ITEM_1 + iSelNum + ERR_FILTER_MAX_ITEM_2 + szFilterName + ERR_FILTER_MAX_ITEM_3 + iMinItem + ".." + iMaxItem + "]"; if (iMinItem == 0){ szEr += ERR_FILTER_MAX_ITEM_4 + szFilterName + ERR_FILTER_MAX_ITEM_5+ szFilterItemsName + ERR_FILTER_MAX_ITEM_6; } return showErr (szEr,1); } jslog(JSLOG_JSU,Fn + JSLOG_FUN_END); return 0; // OK } /* ----------------------------------------------------- Contain text and Value of an Option of a select PAR szText text of select szValue value of select Calling Example var cOptEl = new cOpt(Opt.text,Opt.value); ----------------------------------------------------- */ function cOpt(szText, szValue) { this.text = szText; this.value = szValue; } /* ------------------------------------------------------------------------------------ Show all the SPAN or DIV fields" having class="debug" or id="debug" @param bShow (Boolean} in true=show false=hide ------------------------------------------------------------------------------------ */ function showDebugFields(bShow) { var TAG_DEBUG = ["SPAN","DIV"]; jslog(JSLOG_INFO, "showDebugFields bShow=" + bShow); for (var iTag=0; iTag < TAG_DEBUG.length; iTag++){ var ElList = document.getElementsByTagName(TAG_DEBUG[iTag]); for (var i=0; i < ElList.length; i++){ var El = ElList [i]; if (El.id == "debug" || El.className == "debug"){ elementShow (El,bShow); } } } } /** * Check that obj is defined * @param obj it must be differenbt form undefined or 0 * @param objName label to show in case of Error */ function checkObjDefined(obj,objName) { if (obj){ return 0; // OK }else{ return showErr ("SW ERROR: " + objName + " undefined",1); } } /** * Check that szVal is one of the Values of arVal. * ShowEr if not present * @param szVal * @param arVal * @param [szEr] Optional additional ErMsg * @returns {Number} 0 OK 1 ERR */ function checkArVal(szVal,arVal,szEr) { for (var i=0; i< arVal.length; i++){ if (szVal == arVal[i]){ return 0; //OK } } // ERROR var szMsg = "ERROR:\n " + "Value=" + szVal + "\nIS NOT one of the Possible Values: [ "; // Prepare szEr if there will be an Error for (var i=0; i< arVal.length; i++){ szMsg += arVal[i]; if (i< (arVal.length-1)){ szMsg += " , "; } } szMsg += " ]"; if (szEr != undefined){ szMsg += "\n\n" + szEr; } return showErr(szMsg,1); } /*----------------------------------------------------------- Get SQL Condition for The select, using the useValues selected in select select can be either multiSElect or singleSelect IF NO SElection (MUltiSelect) or Selected the First Cognos Item for ALL we return "" PAR szDbCol in DB Col Name (e.g. COD_CATEG_BLOCCO) select in select DOM object bValueAsString in true if Value get from CB are String (else they are Number) [bOnlySel] in [true] if true get only iteme selected, else Get all Item RETURN Example for bValueAsString=true --------------------------------------------- e.g (ALL is Selected) "" e.g (1 Item Selected) "TENSIONE = 'AM'" e.g (2 Items Selected) "TENSIONE IN ('AM','MT')" Example for bValueAsString=false --------------------------------------------- e.g (0 Item Selected) "" e.g (1 Item Selected) "TENSIONE = 1" e.g (3 Items Selected) "TENSIONE IN (1,4)" ------------------------------------------------------------*/ function sqlCondSelect(szDbCol,select,bValueAsString, bOnlySel) { var Fn = "[util.js sqlCondSelect] "; var szSql = ""; // jslog(JSLOG_DEBUG,Fn + JSLOG_FUN_START); if (bOnlySel == undefined){ bOnlySel = true; } if (bOnlySel){ // Get Only Selected Items if (selectIsMulti (select)){ szSql = selectGetSelValues (select,bValueAsString); }else { szSql = selectGetSelVal (select,bValueAsString); } }else { // Get All Items szSql = selectGetValues (select,bValueAsString); } if (szSql.length){ var bInCond = szSql.indexOf(',') > 0; if (bInCond){ szSql = szDbCol + " IN (" + szSql + ")"; }else{ szSql = szDbCol + " = " + szSql; } } jslog(JSLOG_JSU,Fn + "OUT szSql: " + szSql); // jslog(JSLOG_DEBUG,Fn + JSLOG_FUN_END); return szSql; } /*--------------------------------------------------------------------- Get SQL Condition for From..To Cognos Pickdate Prompt Controls PAR szDbCol in DB Col Name (e.g. COD_BLOCCO) pmtDateFrom in Cognos Prompt for DateFrom pmtDateFrom in Cognos Prompt for DateTo RETURN e.g "COD_BLOCCO >= TO_DATE('2016-01-26','YYYY-MM-DD') AND COD_BLOCCO <= TO_DATE('2016-04-17','YYYY-MM-DD')" e.g "" if no Value is set ------------------------------------------------------------*/ function sqlCondFromToDate (szDbCol,pmtDateFrom,pmtDateTo){ var Fn = "[util.js sqlCondFromTo] "; var szSql = ""; jslog(JSLOG_TEST,Fn + JSLOG_FUN_START); // eg. Get '2016-01-26' or '' var szFromDateVal = promptDateGetVal(pmtDateFrom); var szToDateVal = promptDateGetVal(pmtDateTo); //-- var bFrom = (szFromDateVal.length > 0); var bTo = (szToDateVal.length > 0); var szSqlFrom = ""; if (bFrom){ szSqlFrom = szDbCol + " >= TO_DATE('" + szFromDateVal + "','YYYY-MM-DD')"; } var szSqlTo = ""; if (bTo){ szSqlTo = szDbCol + " <= TO_DATE('" + szToDateVal + "','YYYY-MM-DD')"; } if (bFrom && bTo){ szSql = szSqlFrom + " AND " + szSqlTo; }else if (bFrom){ szSql = szSqlFrom; }else if (bTo){ szSql = szSqlTo; } jslog(JSLOG_TEST,Fn + "return szSql=" + szSql); jslog(JSLOG_TEST,Fn + JSLOG_FUN_END); return szSql; } /*----------------------------------------------------------- Add a New SqlCondition managing the need of adding or NOT AND PAR szCurCond in Current Sql Condition szCond in Sql Condition to Add RETURN NewSqlCond Example szCurCond szCond RETURN -------------------------------------------------------------- '' "COL1 = 10" "COL1=10" "COL0 IN (1,2)" "COL1 = 10" "COL0 IN (1,2) AND COL1=10" ------------------------------------------------------------*/ function sqlAddCond(szCurCond,szCond,bValueAsString) { // var Fn = "[util.js sqlAddCond] "; if (szCurCond.length > 0 && szCond.length > 0){ return szCurCond + " AND " + szCond; }else if (szCond.length > 0){ return szCond; }else { return szCurCond; } } /** * get URL ParVal if present * @param szParName ParName. e.g jslog * @returns value of szParName if present in the URL. Else return "" */ function urlGetParVal(szParName){ var szName; if(szName=(new RegExp('[?&]'+encodeURIComponent(szParName)+'=([^&]*)')).exec(location.search)){ return decodeURIComponent(szName[1]); } else{ return ""; } } /*--------------------------------------------------------------------- Change Language for User Error Msg (e.g validation). Default is LAN_MSG_EN @param szLanMsg in LAN_MSG_ITA for Italian LAN_MSG_EN for English (Default) GLOBAL lan_msg out LAN_MSG_ITA, LAN_MSG_EN ------------------------------------------------------------*/ function utilSetLanMsg (szLanMsg){ var Fn = "[util.js utilSetLanMsg] "; lan_msg = szLanMsg; jslog (JSLOG_INFO,Fn + "lan_msg=" + lan_msg); } /*--------------------------------------------------------------------- Get dateIso: First Day of Current YEar RETURN Example: "2016-01-01" ------------------------------------------------------------*/ function dateIsoGetFirstDayCurYear(){ var dd = new Date(); // Format ISO: YYYY-M-D return dd.getFullYear()+"-01-01"; } /*--------------------------------------------------------------------- Get dateIso: Last Day of Last YEar RETURN Example: "2016-01-01" ------------------------------------------------------------*/ function dateIsoGetLastDayLastYear(){ var dd = new Date(); // Format ISO: YYYY-M-D return (dd.getFullYear() -1 )+"-12-31"; } /*--------------------------------------------------------------------- Get dateIso: First Day of Current YEar RETURN Example: "2016-07-27" ------------------------------------------------------------*/ function dateIsoGetCurDay(){ var dd = new Date(); // getMonth return 0..11 var iMonth = dd.getMonth() + 1; var szMonth = (iMonth >=10) ? ("" + iMonth) : ("0" + iMonth); var iDay = dd.getDate(); var szDay = (iDay >=10) ? ("" + iDay) : ("0" + iDay); return dd.getFullYear()+ "-" + szMonth + "-" + szDay; } /** * Get array of prompt from Select * @param selectAll contains value = szId1.szId2 text=... * @returns {Array} Array of obj for dynamic prompt * @example * { * "szId1": "DD01", * "szId2": "DH", * "szTxt2": "DH - Dip. <NAME> - Marche" * } */ function arPmtFromSelect(selectAll) { var Fn = "[util.arPmtFromSelect] "; jslog(JSLOG_JSU,Fn + JSLOG_FILE_START); var iOptNum = selectAll.options.length; jslog(JSLOG_JSU,Fn + "iOptNum=" + iOptNum); var arAll = new Array(); for (var iOpt=0; iOpt < iOptNum; iOpt ++){ var opt = selectAll.options[iOpt]; var objPmt = new Object(); // split di value nei 2 ID var arId = opt.value.split(SELECT_VALUE_ID_SEP); // ricavo obj da usare per i Prompt dinamici objPmt.szId1 = arId[0]; objPmt.szId2 = arId[1]; objPmt.szTxt2 = opt.text; // jslog (JSLOG_TRACE,Fn + "[" + iOpt + "]=" + objPmt.szId1 + " " + objPmt.szId2 + " " + objPmt.szTxt2); arAll.push(objPmt); } jslog(JSLOG_JSU,Fn + "return arAll.length= " + arAll.length); jslog(JSLOG_JSU,Fn + JSLOG_FILE_END); return arAll; } /* * @param arPmt {Array} array of objec to populate selectPmt * { * "szId1": "DD01", * "szId2": "DH", * "szTxt2": "DH - Dip. <NAME> - Marche" * } * ... * { * "szId1": "DEVA", * "szId2": "VV", * "szTxt2": "VV - Dip. DEVAL S.p.A.(Val d'aosta)" * } * @param szId1 filter for arPmt. Only el with szId1 will be used . Es: "DD01" * @param selectPmt select da Popolare con szId2 e szTxt2 used * @param bTutti true se sono presenti le 2 Entries iniziali (Tutti "----"), da preservare * */ function arPmt2Select(arPmt,szId1,selectPmt,bTutti) { var Fn = "[util.arPmt2Select] "; jslog(JSLOG_JSU,Fn + JSLOG_FILE_START); var iArLen = arPmt.length; jslog(JSLOG_JSU,Fn + "IN szId1=" + szId1 + " arPmt with Len=" + iArLen); var iPreserveFirstN = (bTutti) ? 2 : 0; jslog(JSLOG_JSU,Fn + "Clear selectPmt bTutti=" + bTutti + " iPreserveFirstN=" + iPreserveFirstN); selectRemoveOption(selectPmt,iPreserveFirstN); //------- jslog(JSLOG_JSU,Fn + "INSERT Entry matching szId1=" + szId1); for (var i=0; i < iArLen; i ++){ var objPmt = arPmt[i]; var bAdd = (objPmt.szId1 == szId1); if (bAdd){ jslog (JSLOG_JSU,Fn + "[" + i + "]=" + objPmt.szId1 + " - ADDED: " + objPmt.szId2 + " " + objPmt.szTxt2); appendOptionLast(selectPmt,objPmt.szTxt2,objPmt.szId2); }else{ jslog (JSLOG_TRACE,Fn + "[" + i + "]=" + objPmt.szId1 + " - NOT ADDED: " + objPmt.szId2 + " " + objPmt.szTxt2); } } selectPmt.selectedIndex = 0; selectPmt.disabled = false; jslog(JSLOG_JSU,Fn + JSLOG_FILE_END); } /** * @param arMap eg [["name1",1],["name_7",23]] couple of values (either string or int) * @param val1 eg "name_7" * @param bShowEr * @returns eg 23 null if not found */ function mapVal1ToVal2(arMap, val1, bShowEr){ var val2 = null; var bFound = false; var szListVal1 = ""; for (var i=0; !bFound && i < arMap.length; i++){ var val1Cur = arMap[i][0]; var val2Cur = arMap[i][1]; if (val1Cur == val1){ val2 = val2Cur; bFound = 1; }else { if (i>0){ szListVal1 += " , "; } szListVal1 += val2Cur; } } if (!bFound && bShowEr){ showErr ("SW ERROR: " + val1 + " NOT FOUND in the List of Possible Values [ " + szListVal1 + " ]",-1); } return val2; } function tipAddEvent (arClass){ var TAG_TIP = ["IMG","INPUT"]; for (var iTag=0; iTag < TAG_TIP.length; iTag++){ var elList = document.getelementsByTagName(TAG_TIP[iTag]); for (var iel=0; iel < elList.length; iel++){ var el = elList [iel]; var szClass = el.className; // check if el ha className in arClass var bFound = false; for (var i=0; !bFound && i < arClass.length; i++){ if (szClass == szClass[i]){ bFound = true; } } if (bFound){ // add Event el.onmouseover=function(){ Tip (this.tip); }; el.onmouseout=function(){ UnTip(); }; } } } } <file_sep>/core/loadingDiv.js /** @fileOverview ========================================================================================= <BR/> <b>File:</b> core/loadingDiv.js <BR/> <b>Author:</b> <a href="https://www.linkedin.com/in/federicolevis" target="_self"><NAME></a> <BR/> <b>LoadingDiv Doc:</b> <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/HTML/LoadingDiv.html" target="_self">JSU LoadingDiv Documentation</a> <BR/> <b>JSU API Doc:</b> <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/JSUAPI.html" target="_self">JSU API Documentation</a> <BR/> <b>Description:</b> JSU LoadingDiv API: loadingDivShow loadingDivHide <BR/> <b>REQUIRED:</b> JSU: jsu.css locale-core.js jsuCmn.js <BR/> <b>OPTIONAL:</b> JSU: jslog.js, dom-drag.js to use also jslog <BR/> <b>First Version:</b> ver 1.0 - Jul 2007 <BR/> <b>Current Version:</b> JSU v. 1.10 &nbsp;&nbsp;&nbsp;2018-Jan-14 <BR/> <BR/>-----------------------------------------------------------------------------------<BR/> <b>DISCLAIMER</b> <BR/> Copyright by <NAME> - <a href="https://github.com/JSUtility/JSU" target="_self">JSU</a> <BR/> This file may be freely distributed under the MIT license. <BR/> ========================================================================================= <BR/> */ /*========================================================================== * loadingDiv API ========================================================================== */ /* * LoadingDiv DEFAULT */ var LOADING_DIV_DEF = { szTitleHtml: "", // {String}: [""] if != "" Show a Title Section with szTitle szMsgHtml: "", // {String} [""] if not empty, we will show this Msg (HTML) instead of Default bShowGif: true, // {Boolean}: [true] show the Loading Gif szUrlGif: "", // {String Url}: [""] if not empty, it is used this URL instead of CSS default bShowElapsedSec: false, // {Boolean} [false[ if true show a Footer with Elapsed Time (sec) bResetElapsedSec: true, // {Boolean} [true] if true reset timer iDivWidth: null, // if different from null, set this Div Width instead of using Default Width (CSS) iGifWidth: null, // if different from null, set this Gif Width instead of using Default Width (CSS) bShowCancel: false, // {Boolean}: [false] show the Cancel Btn szCancelLabel: "Cancel" , // {String}: [""] Label to set to Cancel Button - default is LOADING_DIV_MSG.cancelBtn szBackgroundColor: null, // {String} Div BackgroundColor, if different from null or "", bRecalcBestPos: true // bRecalcBestPos: {Boolean} [true] reCalculate BestPosition basing on WindowSize, Scrollbar. You can use false during Window LOad to avoid movement }; var LOADING_DIV_DEF_OPT ={ szTitleHtml: LOADING_DIV_DEF.szTitle, // {String}: [""] if != "" Show Title szMsgHtml: LOADING_DIV_DEF.szMsgHtml, // {String} [""] if not empty, we will show this Msg (HTML) instead of Default bShowGif: LOADING_DIV_DEF.bShowGif, // {Boolean}: [true] show the Loading Gif szUrlGif: LOADING_DIV_DEF.szUrlGif, // {String Url}: [""]if not empty, it is used this URL instead of CSS default bShowElapsedSec: LOADING_DIV_DEF.bShowElapsedSec, // {Boolean} [false] if true show a Footer with Elapsed Time (sec) bResetElapsedSec: LOADING_DIV_DEF.bResetElapsedSec, // {Boolean} [true] if true reset timer iDivWidth: LOADING_DIV_DEF.iDivWidth, // if different from null, set this Div Width instead of using DEfault Width (CSS) iGifWidth: LOADING_DIV_DEF.iGifWidth, // if different from null, set this Gif Width instead of using DEfault Width (CSS) bShowCancel: LOADING_DIV_DEF.bShowCancel, // {Boolean}: [false] show the Cancel Btn szCancelLabel: "" , // {String}: [""] Label to set to Cancel Button - default is LOADING_DIV_MSG.cancelBtn szBackgroundColor: LOADING_DIV_DEF.szBackgroundColor, // {String} Div BackgroundColor, if different from null or "", fnCancelCallback: null, // called when click Cancel bRecalcBestPos: true // bRecalcBestPos: {Boolean} [true] reCalculate BestPosition basing on WindowSize, Scrollbar. You can use false during Window LOad to avoid movement }; var JSU_LOADING_DIV = '<div id="loadingDivContainer" class="loadingDivContainer" >' + ' <table width="100%" height="100%">' + ' <tr> <td align="center" valign="center">' + ' <div id="loadingDiv" class="loadingDiv">' + ' <table id="loadingDivTable" class="loadingDiv" width="100%" style="z-index: 110;">' + ' <tr class="loadingDivTitle">' + ' <td colspan="2" id="loadingDivTitle" class="loadingDivTitle" >Title Test</td>' + ' </tr>' + ' <tr> ' + ' <td id="loadingDivTdGif" align="left" width="80px">' + ' <div id="loadingDivGif" class="loadingDivGif"> </div>' + ' </td> ' + ' <td id="loadingDivMsg" class="loadingDivMsg" align="left" style="padding-left:0px">' + ' <b>Working</b></BR>Please Wait...' + ' </td>' + ' </tr>' + ' <tr>' + ' <td colspan="2" align="center" class="loadingDivBtn" id="loadingDivBtnTd" >' + ' <input type="button" class="loadingDivBtn" id="loadingDivBtn" value="Stop" onclick="loadingDivCancel();" />' + ' </td>' + ' </tr>' + ' <tr>' + ' <td colspan="2" id="loadingDivFooter" class="loadingDivFooter" style="display:none">' + ' Elapsed Time: 10 sec' + ' </td>' + ' </tr>' + ' </table>' + ' </div>' + ' </td> </tr>' + ' </table>' + '</div>'; // Global var with current status var var_ld_div = { elFooter: null, // td el with Footer tmoElapsedSec : null, // tmo for ld_div to update ElapsedSec iElapsedSec : 0, // elapsed sec fnCancelCallback: null, // called when click Cancel // PREV Values to restore prev : { scrollLeft : 0, // Previous Val to Restore scrollTop : 0, // Previous Val to Restore scroll : 0, overflow : "auto" } }; /*========================================================================== * PRIVATE ========================================================================== */ var LOADING_APP_NAME_IE="Microsoft Internet Explorer"; // IE var LOADING_APP_NAME_IE_11="Netscape"; // IE 11 /* * Different object to be used if IE/Firefox or Chrome */ function ld_getScrollEl(){ var Fn = "[loadingDiv.js ld_getScrollEl()] "; // For Firefox or IE if ((typeof InstallTrigger !== 'undefined') || (navigator.appName == LOADING_APP_NAME_IE) || ((navigator.appName == LOADING_APP_NAME_IE_11) && (new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})").exec(navigator.userAgent) != null))){ jsu_log(Fn + "Firefox/IE"); return document.documentElement; } else { // NOT Firefox/IE (e.g CHROME) jsu_log(Fn + "NOT Firefox/IE (e.g CHROME)"); return document.body; } } /* * Click on Cancel */ function loadingDivCancel(){ loadingDivHide(); if (var_ld_div.fnCancelCallback != undefined){ var_ld_div.fnCancelCallback(); } } /* * Tmo elapsed */ function loadingDivTmo(){ var dEnd = new Date(); var iElapsedSec= Math.round((dEnd.getTime() - var_ld_div.iStartTime)/1000); var_ld_div.elFooter.innerHTML = LOADING_DIV_MSG.startTime + var_ld_div.szStartTime + LOADING_DIV_MSG.elapsed + iElapsedSec + LOADING_DIV_MSG.sec; } /*========================================================================== * loadingDiv API ========================================================================== */ /** Show loadingDiv @param [objOpt] {Object} <table class="jsDoc" border="2" cellpadding="2" cellspacing="2"> <tr><td class="jsDocTitle">OPTIONS</td></tr> <tr><td class="jsDocParam"> <ul> <li>szTitleHtml: {String}: [""] if != "" Show Title </li> <li>bShowGif: {Boolean}: [true] show the Loading Gif </li> <li>szUrlGif: {String Url}: [null] if different form null use this URL instead of CSS default </li> <li>bShowElapsedSec: {Boolean} [false] if true show a Footer with Elapsed Time (sec) </li> <li>bResetElapsedSec: {Boolean} [false] if true reset timer </li> <li>szMsgHtml: {String} if different from null, show this Msg (HTML) instead of Default </li> <li>iDivWidth: {Number} if different from null, set this Div Width instead of using DEfault Width (CSS) </li> <li>iGifWidth: {Number} if different from null, set this Gif Width instead of using DEfault Width (CSS) </li> <li>bShowCancel: {Boolean}: [false] show the Cancel Btn </li> <li>szCancelLabel: {String} ["Cancel"] Label to set to Cancel Button <li>szBackgroundColor:{String} Div BackgroundColor, if different from null or "", </li> <li>fnCancelCallback: {function} [null] called when Cancel button is clicked </li> <li>bRecalcBestPos: {Boolean} [true] reCalculate BestPosition basing on WindowSize, Scrollbar. You can use false during Window LOad to avoid movement </li> </ul> </td></tr> </table> */ function loadingDivShow(objOpt){ var Fn = "[loadingDiv.js loadingDivStart()] "; jsu_log(Fn + JSU_LOG_FUN_START); if (var_ld_div.tmoElapsedSec){ clearTimeout (var_ld_div.tmoElapsedSec); } if (objOpt == undefined){ var objOpt = LOADING_DIV_DEF_OPT; }else { if (objOpt.szTitleHtml == undefined) {objOpt.szTitleHtml = LOADING_DIV_DEF.szTitleHtml;} if (objOpt.bShowGif == undefined) {objOpt.bShowGif = LOADING_DIV_DEF.bShowGif;} if (objOpt.szUrlGif == undefined) {objOpt.szUrlGif = LOADING_DIV_DEF.szUrlGif;} if (objOpt.bShowElapsedSec == undefined) {objOpt.bShowElapsedSec = LOADING_DIV_DEF.bShowElapsedSec;} if (objOpt.bResetElapsedSec == undefined) {objOpt.bResetElapsedSec = LOADING_DIV_DEF.bResetElapsedSec;} if (objOpt.iDivWidth == undefined) {objOpt.iDivWidth = LOADING_DIV_DEF.iDivWidth;} if (objOpt.iGifWidth == undefined) {objOpt.iGifWidth = LOADING_DIV_DEF.iGifWidth;} if (objOpt.szBackgroundColor == undefined) {objOpt.szBackgroundColor = LOADING_DIV_DEF.szBackgroundColor;} if (objOpt.bShowCancel== undefined) {objOpt.bShowCancel = LOADING_DIV_DEF.bShowCancel;} if (objOpt.szCancelLabel== undefined) {objOpt.szCancelLabel = LOADING_DIV_DEF.szCancelLabel;} if (objOpt.szMsgHtml == undefined) {objOpt.szMsgHtml = LOADING_DIV_DEF.szMsgHtml;} if (objOpt.bRecalcBestPos == undefined) {objOpt.bRecalcBestPos = LOADING_DIV_DEF.bRecalcBestPos;} } var_ld_div.fnCancelCallback = objOpt.fnCancelCallback; jsu_logObj(Fn + "objOpt",objOpt); var divMain = jsu_getElementById2 ("loadingDivMain",false); if (divMain){ document.body.removeChild (divMain); } jsu_log(Fn + "add JSU_LOADING_DIV to document.body"); divMain = document.createElement("div"); divMain.id = "loadingDivMain"; divMain.innerHTML = JSU_LOADING_DIV; document.body.appendChild(divMain); var loadingDiv = jsu_getElementById2 ("loadingDiv"); if (objOpt.iDivWidth != null){ loadingDiv.style.width = objOpt.iDivWidth + "px"; } jsu_log( Fn + "Set Visible element depending on objOpt"); var elTitle = jsu_getElementById2 ("loadingDivTitle"); var bTitle = (objOpt.szTitleHtml && objOpt.szTitleHtml != ""); jsu_elementShow (elTitle,bTitle,""); if (bTitle){elTitle.innerHTML = objOpt.szTitleHtml;} //------ var elMsgHtml = jsu_getElementById2 ("loadingDivMsg",false); if (!elMsgHtml){ return; // WorkAround } var szMsgHtml = LOADING_DIV_MSG.working; if (objOpt.szMsgHtml && objOpt.szMsgHtml != ""){ szMsgHtml = objOpt.szMsgHtml; } elMsgHtml.innerHTML = szMsgHtml; //------ var elCancelBtn = jsu_getElementById2 ("loadingDivBtn"); elCancelBtn.value = objOpt.szCancelLabel; jsu_elementShow (jsu_getElementById2 ("loadingDivBtnTd"),objOpt.bShowCancel,""); //------ var elGif = jsu_getElementById2 ("loadingDivGif"); if (objOpt.szUrlGif != undefined && objOpt.szUrlGif != ""){ elGif.style.backgroundImage = "url('" + objOpt.szUrlGif + "')"; } if (objOpt.iDivWidth != null){ elGif.style.width = objOpt.iGifWidth + "px"; } jsu_elementShow (jsu_getElementById2 ("loadingDivTdGif"),objOpt.bShowGif,""); //------ if (objOpt.szBackgroundColor && objOpt.szBackgroundColor != ""){ loadingDiv.style.backgroundColor = objOpt.szBackgroundColor; jsu_getElementById2 ("loadingDivMsg").style.backgroundColor = objOpt.szBackgroundColor; jsu_getElementById2 ("loadingDivTdGif").style.backgroundColor = objOpt.szBackgroundColor; jsu_getElementById2 ("loadingDivBtnTd").style.backgroundColor = objOpt.szBackgroundColor; } //------------------ var bShowElapsedSec = (objOpt.bShowElapsedSec != undefined && objOpt.bShowElapsedSec); jsu_elementShow (elTitle,bTitle,""); var_ld_div.elFooter = jsu_getElementById2 ("loadingDivFooter"); jsu_elementShow (var_ld_div.elFooter ,bShowElapsedSec,""); if (bShowElapsedSec){ if (objOpt.bResetElapsedSec){ jsu_log( Fn + "Start Timeout for Elapsedsec"); var dStart = new Date(); var_ld_div.iStartTime = dStart.getTime(); var_ld_div.szStartTime = num2StrPad(dStart.getHours(),'0',2) + ":" + num2StrPad(dStart.getMinutes(),'0',2) + ":" + num2StrPad(dStart.getSeconds(),'0',2); } loadingDivTmo(); // simulate Tmo to show currente Elapsed Time var_ld_div.tmoElapsedSec = setInterval(loadingDivTmo,1000); } // ---------------------------------- Set the Size if Required if (objOpt.bRecalcBestPos){ jsu_log(Fn + "Recalculate Best Postion"); var divContainer = jsu_getElementById2 ("loadingDivContainer",true); var bd = ld_getScrollEl(); // Scroll = total dimensione, also if some is not bvisible var hScroll= bd.scrollHeight; var wScroll= bd.scrollWidth; var xScroll= bd.scrollLeft; var yScroll= bd.scrollTop; // Visible part var wClient= window.innerWidth; var hClient= window.innerHeight; jsu_log(Fn + "scroll: xScroll=" + xScroll + " yScroll=" + yScroll + " wScroll=" + wScroll + " hScroll="+hScroll); jsu_log(Fn + "Client: wClient=" + wClient + " hClient="+hClient); divContainer.style.height = hScroll + 100+ "px"; divContainer.style.width = wScroll + 100 + "px"; var xScrollNew = (100 + wScroll - wClient)/2 ; var yScrollNew = (100 + hScroll - hClient)/2 ; jsu_log(Fn + "SET NEW SCROLL =" + xScrollNew + " y=" + yScrollNew); if (xScrollNew > 0){ var_ld_div.prev.scrollLeft = bd.scrollLeft; // Value to restore bd.scrollLeft = xScrollNew; }else { var_ld_div.prev.scrollLeft = -1; // Nothing to restore } if (yScrollNew > 0){ var_ld_div.prev.scrollTop = bd.scrollTop; // Value to restore bd.scrollTop = yScrollNew; }else{ var_ld_div.prev.scrollTop = -1; // Nothing to restore } // Save previous value var_ld_div.prev.scroll = bd.scroll; // IE Only bd.scroll = "no"; // ie only if (document.documentElement != undefined){ var_ld_div.prev.overflow = document.documentElement.style.overflow; // Firefox, Chrome document.documentElement.style.overflow = 'hidden'; // firefox, chrome }else { var_ld_div.prev.overflow = null; } } jsu_elementShow (divMain,true); jsu_elementShow (loadingDiv,true); jsu_log(Fn + JSU_LOG_FUN_END); } /** * Hide loadindgDiv */ function loadingDivHide(){ var Fn = "[loadingDiv.js loadingDivHide()] "; jsu_log(Fn + JSU_LOG_FUN_START); if (var_ld_div.tmoElapsedSec){ clearTimeout (var_ld_div.tmoElapsedSec); } var bd = ld_getScrollEl(); if (var_ld_div.prev.scrollLeft != -1){ jsu_log(Fn + "RESTORE scrollLeft=" + var_ld_div.prev.scrollLeft); bd.scrollLeft = var_ld_div.prev.scrollLeft; } if (var_ld_div.prev.scrollTop != -1){ jsu_log(Fn + "RESTORE scrollTop=" + var_ld_div.prev.scrollTop); bd.scrollTop = var_ld_div.prev.scrollTop; } bd.scroll = var_ld_div.prev.scroll; // IE Only if (var_ld_div.prev.overflow != null && document.documentElement != undefined){ document.documentElement.style.overflow = var_ld_div.prev.overflow ; // Firefox, Chrome } var divContainer = jsu_getElementById2 ("loadingDivContainer",false); jsu_elementShow (divContainer,false); jsu_log(Fn + JSU_LOG_FUN_END); } <file_sep>/core/date.js /** @fileOverview ========================================================================================= <BR/> <b>File:</b> core/date.js <BR/> <b>Author:</b> <a href="https://www.linkedin.com/in/federicolevis" target="_self"><NAME></a> <BR/> <b>LoadingDiv Doc:</b> <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/HTML/LoadingDiv.html" target="_self">JSU LoadingDiv Documentation</a> <BR/> <b>JSU API Doc:</b> <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/JSUAPI.html" target="_self">JSU API Documentation</a> <BR/> <b>Description:</b> common JSU date API <BR/> ------------------------------------------------------------------ <BR/> These functions use the same 'format' strings as the <BR/> java.text.SimpleDateFormat class, with minor exceptions. <BR/> The format string consists of the following abbreviations: <BR/> <BR/> Field | Full Form | Short Form <BR/> -------------+--------------------+----------------------- <BR/> Year | yyyy (4 digits) | yy (2 digits), y (2 or 4 digits) <BR/> Month | MMM (name or abbr.)| MM (2 digits), M (1 or 2 digits) <BR/> | NNN (abbr.) | <BR/> Day of Month | dd (2 digits) | d (1 or 2 digits) <BR/> Day of Week | EE (name) | E (abbr) <BR/> Hour (1-12) | hh (2 digits) | h (1 or 2 digits) <BR/> Hour (0-23) | HH (2 digits) | H (1 or 2 digits) <BR/> Hour (0-11) | KK (2 digits) | K (1 or 2 digits) <BR/> Hour (1-24) | kk (2 digits) | k (1 or 2 digits) <BR/> Minute | mm (2 digits) | m (1 or 2 digits) <BR/> Second | ss (2 digits) | s (1 or 2 digits) <BR/> AM/PM | a | <BR/> <BR/> ----- Examples <BR/> NNN dd, yyyy HH:mm:ss <BR/> yyyy-MM-dd <BR/> <BR/> NOTE THE DIFFERENCE BETWEEN MM and mm! Month=MM, not mm! <BR/> Examples: <BR/> "MMM d, y" matches: January 01, 2000 <BR/> Dec 1, 1900 <BR/> Nov 20, 00 <BR/> "M/d/yy" matches: 01/20/00 <BR/> 9/2/00 <BR/> "MMM dd, yyyy hh:mm:ssa" matches: "January 01, 2000 12:30:45AM" <BR/> ------------------------------------------------------------------ <BR/> <b>REQUIRE:</b> JSU: jslog.js dom-drag.js <BR/> <b>First Version:</b> ver 1.0 - Jul 2007 <BR/> <b>Current Version:</b> JSU v. 1.10 &nbsp;&nbsp;&nbsp;2018-Jan-14 <BR/> <BR/>-----------------------------------------------------------------------------------<BR/> <b>DISCLAIMER</b> <BR/> Copyright by <NAME> - <a href="https://github.com/JSUtility/JSU" target="_self">JSU</a> <BR/> This file may be freely distributed under the MIT license. <BR/> ========================================================================================= <BR/> */ var MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'); var DAY_NAMES=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat'); function LZ(x) {return(x<0||x>9?"":"0")+x;} /* ------------------------------------------------------------------ PAR szDate in e.g "10-25-2008 10:00" szFormat in e.g "MM-dd-yyyy HH:mm" RETURN true it is a Date in the specified format false it is not a Date in the specified format NOTE hour minutes and seconds are not mandatory. e.g szDate in "10-25-2008" szFormat in "MM-dd-yyyy HH:mm" RETURN true ------------------------------------------------------------------*/ function isDate(szDate,szFormat) { // var Fn = "[isDate] "; // jslog(JSLOG_TEST,Fn + " IN szDate=" + szDate+ " szFormat=" + szFormat); var iTime=getTimeFromFormat(szDate,szFormat); if (iTime==0) { return false; } return true; } /* ------------------------------------------------------------------ Compare two date strings to see which is greater. Both date must be NOT Empty PAR szDate1 in e.g "10-25-2008 10:00" szDate2 in e.g "10-26-2008 10:00" szFormat in e.g "MM-dd-yyyy HH:mm" bShowErr in if True and there is an Error, Show Error RETURN 1 szDate1 > szDate2 (szDate1 is more recent) 0 if they are the same 2 szDate1 < szDate2 -1 ERROR: invalid format ------------------------------------------------------------------*/ function compareDates(szDate1,szDate2,szFormat,bShowErr) { var Fn = "[compareDates] "; var iRet = 0; jslog(JSLOG_TEST,Fn + "IN szDate1=" + szDate1 + " szDate2=" + szDate2 + " szFormat=" +szFormat); if (szDate1.length == 0 && szDate2.length == 0) { return 0; // No Problem: one or Both are empty } if (szDate1.length == 0) { return 2; // No Problem: First is Empty } if (szDate2.length == 0) { return 1; // No Problem: Second is Empty } var iTime1=getTimeFromFormat(szDate1,szFormat); if (iTime1 == 0){ if (bShowErr){ showErr (szDate1 + "\n\n" + ERR_DATE_FMT + szFormat,-2); } return -2; // Invalid Format } var iTime2=getTimeFromFormat(szDate2,szFormat); if (iTime2 == 0){ if (bShowErr){ showErr (szDate2 + "\n\n" + ERR_DATE_FMT + szFormat,-2); } return -2; // Invalid Format } if (iTime1 > iTime2) { return 1; } if (iTime1 < iTime2) { return 2; } return 0; // They are equal } /* ------------------------------------------------------------------ Change the Format if a date PAR szDate1 in e.g "25-10-2008" szFmt1 in e.g "dd-MM-yyyy" szFmt2 in e.g "MM-dd-yyyy HH:mm" bShowErr in if true show errore if any RETURN szDate (as string with szFmt2 format. e.g: "10-25-2008 00:00") ------------------------------------------------------------------*/ function szDateChangeFmt(szDate1,szFmt1,szFmt2,bShowErr) { var Fn = "[szDateChangeFmt] "; var szDate2=""; jslog(JSLOG_TEST, Fn + JSLOG_FUN_START); jslog(JSLOG_TEST,Fn + "IN szDate1=" + szDate1 + " szFmt1=" + szFmt1 + " szFmt2=" +szFmt2); if (szFmt1 == szFmt2){ return szDate1; // The format is the same, return szDate1 } // I have to change Format if (szDate1.length == 0){ jslog(JSLOG_TEST, "OUT: szDate2=" + szDate2); return szDate2; // OK Empty String } var iTime1=getTimeFromFormat(szDate1,szFmt1); if (iTime1 == 0){ if (bShowErr){ showErr (szDate1 + "\n\n" + ERR_DATE_FMT + szFmt1,1); } jslog(JSLOG_TEST, "OUT: szDate2=" + szDate2); return szDate2; } var Date1 = new Date(); Date1.setTime(iTime1); var szDate2= formatDate (Date1,szFmt2); jslog(JSLOG_TEST, "OUT: szDate2=" + szDate2); jslog(JSLOG_TEST, Fn + JSLOG_FUN_END); return szDate2; } /** Returns a date in the output format specified. The format string uses the same abbreviations as in getTimeFromFormat() * @param date {Date} * @param format {String} dateFormat e.g "dd-MM-yyyy HH:MM:SS' see File Header for Format description * @return {String} string with format. e.g: "10-25-2008 10:00" */ function formatDate(date,szFmt) { var Fn = "[formatDate] "; // jslog(JSLOG_TEST, Fn + JSLOG_FUN_START); // jslog(JSLOG_TEST,Fn + "IN date=" + date + " szFmt=" + szFmt); szFmt=szFmt+""; var result=""; var i_szFmt=0; var c=""; var token=""; var y=date.getYear()+""; var M=date.getMonth()+1; var d=date.getDate(); var E=date.getDay(); var H=date.getHours(); var m=date.getMinutes(); var s=date.getSeconds(); // jslog(JSLOG_TEST,"y=" + y + " M=" + M + " d=" + d + " E=" + E + " H=" +H + " m=" + m + " s=" + s); var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k; // Convert real date parts into szFmtted versions var value=new Object(); if (y.length < 4) {y=""+(y-0+1900);} value["y"]=""+y; value["yyyy"]=y; value["yy"]=y.substring(2,4); value["M"]=M; value["MM"]=LZ(M); value["MMM"]=MONTH_NAMES[M-1]; value["NNN"]=MONTH_NAMES[M+11]; value["d"]=d; value["dd"]=LZ(d); value["E"]=DAY_NAMES[E+7]; value["EE"]=DAY_NAMES[E]; value["H"]=H; value["HH"]=LZ(H); if (H==0){value["h"]=12;} else if (H>12){value["h"]=H-12;} else {value["h"]=H;} value["hh"]=LZ(value["h"]); if (H>11){value["K"]=H-12;} else {value["K"]=H;} value["k"]=H+1; value["KK"]=LZ(value["K"]); value["kk"]=LZ(value["k"]); if (H > 11) { value["a"]="PM"; } else { value["a"]="AM"; } value["m"]=m; value["mm"]=LZ(m); value["s"]=s; value["ss"]=LZ(s); while (i_szFmt < szFmt.length) { c=szFmt.charAt(i_szFmt); token=""; while ((szFmt.charAt(i_szFmt)==c) && (i_szFmt < szFmt.length)) { token += szFmt.charAt(i_szFmt++); } // jslog(JSLOG_TEST,"token=" + token); if (value[token] != null) { result=result + value[token]; } else { result=result + token; } } // jslog(JSLOG_TEST, Fn + JSLOG_FUN_END); return result; } // ------------------------------------------------------------------ // Utility functions for parsing in getTimeFromFormat() // ------------------------------------------------------------------ function _isInteger(val) { var digits="1234567890"; for (var i=0; i < val.length; i++) { if (digits.indexOf(val.charAt(i))==-1) { return false; } } return true; } /* ------------------------------------------------------------------ ------------------------------------------------------------------*/ function _getInt(str,i,minlength,maxlength) { for (var x=maxlength; x>=minlength; x--) { var token=str.substring(i,i+x); if (token.length < minlength) { return null; } if (_isInteger(token)) { return token; } } return null; } /* ------------------------------------------------------------------ This function takes a date string and a format string. It matches If the date string matches the format string, it returns the getTime() of the date. If it does not match, it returns 0. PAR szDate in e.g "10-25-2008 10:00" format in e.g "MM-dd-yyyy HH:mm" RETURN 0 if date is not in format or date is empty... Time (date.getTime()) NOTE Time (hour minutes and seconds) are not mandatory e.g szDate in "10-25-2008" szFormat in "MM-dd-yyyy HH:mm" RETURN Time (as it was "10-25-2008 00:00") ------------------------------------------------------------------*/ function getTimeFromFormat(szDate,format) { var Fn = "[getTimeFromFormat] "; //jslog(JSLOG_TEST,Fn + JSLOG_FUN_START); //jslog(JSLOG_TEST,"IN: szDate=" + szDate + " (Len=" + szDate.length + ") format=" + format); szDate=szDate+""; var iDateLen = szDate.length; // Skip possible Blank at the end of szDate var bEnd=false; for (var i= szDate.length-1; !bEnd && i--; i>=0){ var szChar = szDate.charAt(i); if (szChar != " "){ bEnd = true; }else { iDateLen--; } } format=format+""; if (iDateLen < 2) {return 0;} var iDate=0; var i_format=0; var c=""; var token=""; var token2=""; var x,y; var now=new Date(); var year=now.getYear(); var month=now.getMonth()+1; var date=1; var hh=0, mm=0, ss=0; var ampm=""; var bDateWithoutTime = false; while (i_format < format.length && !bDateWithoutTime) { // Get next token from format string c=format.charAt(i_format); token=""; while ((format.charAt(i_format)==c) && (i_format < format.length)) { token += format.charAt(i_format++); } // Extract contents of szDate based on format token //jslog(JSLOG_TEST,"token=" + token + " iDate=" + iDate + " iDateLen=" + iDateLen); // if it is a Token Relative to Time Part (or a blank separator) and Date has ended, it is OK and we use hh=0, mm=0, ss=0; if ((iDate == iDateLen) && (token==" " || token==" " || token=="HH"||token=="H" || token=="HH"||token=="H" || token=="KK"||token=="K" || token=="kk"||token=="k" || token=="mm"||token=="m" || token=="ss"||token=="s" || token=="a")) { bDateWithoutTime = true; } else { if (token=="yyyy" || token=="yy" || token=="y") { if (token=="yyyy") { x=4;y=4; } if (token=="yy") { x=2;y=2; } if (token=="y") { x=2;y=4; } year=_getInt(szDate,iDate,x,y); if (year==null) { return 0; } iDate += year.length; if (year.length==2) { if (year > 70) { year=1900+(year-0); } else { year=2000+(year-0); } } //jslog(JSLOG_TEST,"year = " + year); } else if (token=="MMM"||token=="NNN"){ month=0; for (var i=0; i<MONTH_NAMES.length; i++) { var month_name=MONTH_NAMES[i]; if (szDate.substring(iDate,iDate+month_name.length).toLowerCase()==month_name.toLowerCase()) { if (token=="MMM"||(token=="NNN"&&i>11)) { month=i+1; if (month>12) { month -= 12; } iDate += month_name.length; break; } } } //jslog(JSLOG_TEST,"month = " + month ); if ((month < 1)||(month>12)){return 0;} } else if (token=="EE"||token=="E"){ for (var i=0; i<DAY_NAMES.length; i++) { var day_name=DAY_NAMES[i]; if (szDate.substring(iDate,iDate+day_name.length).toLowerCase()==day_name.toLowerCase()) { iDate += day_name.length; break; } } } else if (token=="MM"||token=="M") { month=_getInt(szDate,iDate,token.length,2); if(month==null||(month<1)||(month>12)){return 0;} iDate+=month.length; //jslog(JSLOG_TEST,"month=" + month ); } else if (token=="dd"||token=="d") { date=_getInt(szDate,iDate,token.length,2); if(date==null||(date<1)||(date>31)){return 0;} iDate+=date.length; } else if (token=="hh"||token=="h") { hh=_getInt(szDate,iDate,token.length,2); if(hh==null||(hh<1)||(hh>12)){return 0;} iDate+=hh.length; //jslog(JSLOG_TEST,"hh=" + hh); } else if (token=="HH"||token=="H") { hh=_getInt(szDate,iDate,token.length,2); if(hh==null||(hh<0)||(hh>23)){return 0;} iDate+=hh.length; //jslog(JSLOG_TEST,"hh=" + hh); } else if (token=="KK"||token=="K") { hh=_getInt(szDate,iDate,token.length,2); if(hh==null||(hh<0)||(hh>11)){return 0;} iDate+=hh.length;} else if (token=="kk"||token=="k") { hh=_getInt(szDate,iDate,token.length,2); if(hh==null||(hh<1)||(hh>24)){return 0;} iDate+=hh.length;hh--;} else if (token=="mm"||token=="m") { mm=_getInt(szDate,iDate,token.length,2); if(mm==null||(mm<0)||(mm>59)){return 0;} iDate+=mm.length; //jslog(JSLOG_TEST,"mm=" + mm); } else if (token=="ss"||token=="s") { ss=_getInt(szDate,iDate,token.length,2); if(ss==null||(ss<0)||(ss>59)){return 0;} iDate+=ss.length;} else if (token=="a") { if (szDate.substring(iDate,iDate+2).toLowerCase()=="am") {ampm="AM";} else if (szDate.substring(iDate,iDate+2).toLowerCase()=="pm") {ampm="PM";} else {return 0;} iDate+=2;} else { if (szDate.substring(iDate,iDate+token.length)!=token) { jslog(JSLOG_INFO,"LEN ERROR"); return 0; } else {iDate+=token.length;} } } } // end while // If there are any trailing characters left in the szDate, it doesn't match //jslog(JSLOG_TEST,"month=" + month + " date=" + date + " year=" +year); if (iDate != iDateLen) { return 0; } // Is date szDateid for month? if (month==2) { // Check for leap year if ( ( (year%4==0)&&(year%100 != 0) ) || (year%400==0) ) { // leap year if (date > 29){ return 0; } } else { if (date > 28) { return 0; } } } if ((month==4)||(month==6)||(month==9)||(month==11)) { if (date > 30) { return 0; } } // Correct hours szDateue if (hh<12 && ampm=="PM") { hh=hh-0+12; } else if (hh>11 && ampm=="AM") { hh-=12; } var newdate=new Date(year,month-1,date,hh,mm,ss); //jslog(JSLOG_TEST,"OUT newdate=" + newdate); //jslog(JSLOG_TEST,Fn + JSLOG_FUN_END); return newdate.getTime(); } // ------------------------------------------------------------------ // parseDate( date_string [, prefer_euro_format] ) // // This function takes a date string and tries to match it to a // number of possible date formats to get the value. It will try to // match against the following international formats, in this order: // y-M-d MMM d, y MMM d,y y-MMM-d d-MMM-y MMM d // M/d/y M-d-y M.d.y MMM-d M/d M-d // d/M/y d-M-y d.M.y d-MMM d/M d-M // A second argument may be passed to instruct the method to search // for formats like d/M/y (european format) before M/d/y (American). // Returns a Date object or null if no patterns match. // ------------------------------------------------------------------ function parseDate(val) { var preferEuro=(arguments.length==2)?arguments[1]:false; generalFormats=new Array('y-M-d','MMM d, y','MMM d,y','y-MMM-d','d-MMM-y','MMM d'); monthFirst=new Array('M/d/y','M-d-y','M.d.y','MMM-d','M/d','M-d'); dateFirst =new Array('d/M/y','d-M-y','d.M.y','d-MMM','d/M','d-M'); var checkList=new Array('generalFormats',preferEuro?'dateFirst':'monthFirst',preferEuro?'monthFirst':'dateFirst'); var d=null; for (var i=0; i<checkList.length; i++) { var l=window[checkList[i]]; for (var j=0; j<l.length; j++) { d=getTimeFromFormat(val,l[j]); if (d!=0) { return new Date(d); } } } return null; } // function getDateFromFormat(szDate,szFmt) { return getTimeFromFormat(szDate,szFmt); } <file_sep>/core/jslog.js /** @fileOverview ========================================================================================= <BR/> <b>File:</b> core/jslog.js <BR/> <b>Author:</b> <a href="https://www.linkedin.com/in/federicolevis" target="_self"><NAME></a> <BR/> <b>JS Log Doc:</b> <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/HTML/jslog.html" target="_self">JSU JS Log Documentation</a> <BR/> <b>JSU API Doc:</b> <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/JSUAPI.html" target="_self">JSU API Documentation</a> <BR/> <b>Description:</b> jslog API: jslog* <BR/> <b>REQUIRE:</b> JSU: dom-drag.js <BR/> <b>First Version:</b> ver 1.0 - Nov 2008 <BR/> <b>Current Version:</b> JSU v. 1.10 &nbsp;&nbsp;&nbsp;2017-Ott-14 <BR/> <BR/>-----------------------------------------------------------------------------------<BR/> <b>DISCLAIMER</b> <BR/> Copyright by <NAME> - <a href="https://github.com/FedericoLevis/JSU" target="_self">JSU</a> <BR/> This file may be freely distributed under the MIT license. <BR/> ========================================================================================= <BR/> */ //************************************************************************** // CONSTANT //************************************************************************** // -------------------------------- Log Level /** * JSLOG_ERR = 0 ERRORS: always enable when jslog is visible */ var JSLOG_ERR = 0; /** * JSLOG_INFO = 1 Important Information */ var JSLOG_INFO = 1; /** * JSLOG_DEBUG = 2 DEBUG Information */ var JSLOG_DEBUG = 2; /** * JSLOG_TRACE = 4 DUMP Large Data (usually for json or object) */ var JSLOG_TRACE = 4; /** * JSLOG_TEST = 8 Feature under TEST */ var JSLOG_TEST = 8; /** * JSLOG_JSU = 16 JSU Functionality (usually stable) */ var JSLOG_JSU = 16; // --------------------------------------------- For compatibility with previous version var JSLOG_BASE = JSLOG_JSU ; var JSLOG_DUMP = JSLOG_TEST; // e.g JSON var JSLOG_CORE = JSLOG_JSU; // CORE Functionality (CORE Common Function, usually stable) // ---------------- NOTE: you can add also whatever New Levels to JSLOG_xxx /** * id of input that can be optionally provided in the page, to store jslogCfg and retrieve it at startup when page is reloaded */ var JSLOG_ID_CFG = "jslogCfg"; /** * You can also choose to save opnly LOgLev: optionally provided ythis input is in the page, to store LogLev and retrieve it at startup when page is reloaded */ var JSLOG_ID_LOGLEV = "jslogLev"; /** * jslog_init (JSLOG_LEV_AUTO) special Value to get iLogLev automatically: 1) From input "jslogCfg" if present, 2) From URL */ var JSLOG_LEV_AUTO = "AUTO_DETECT"; /** * jslog_init (JSLOG_LEV_URL) special Value to get jj_var.iLogLev from URL parameter jslog */ var JSLOG_LEV_URL = "URL"; /** * Parameter to add to URL to set LogLev: JSLOG_LEV_URL_PAR = "jslog" * @example // init jslog reading URL parameter jslog, if present // For example // a) LogLev will be set to 3 and jslogWindow will be displayed: // URL=https://rawgit.com/FedericoLevis/JSU/master/samples/Sort/SortSample.html?jslog=3 // a) LogLev will be set to 0 and jslogWindow will NOT be displayed: // URL=https://rawgit.com/FedericoLevis/JSU/master/samples/Sort/SortSample.html jslog_init('URL'); * */ var JSLOG_LEV_URL_PAR = "jslog"; var JSLOG_ID_DEBUG = "debug"; // id/class that identify yje element that can be Show/Hide by jslog Button //------------ Option: Default value var JSLOG_DEF_LOG_TIME = false; var JSLOG_DEF_PATH_IMG = "../../images/"; // Default (for samples) if (typeof (JSU_PATH_IMG) != "undefined"){ JSLOG_DEF_PATH_IMG = JSU_PATH_IMG; } //--------------------------------------- var JSLOG_FUN_START = "-------------------- START"; var JSLOG_FUN_END = "-------------------- END"; var JSLOG_FILE_START = " ============================= START"; var JSLOG_FILE_END = " ============================= END"; var JSLOG_DELIMITER= '<span style="color: #f00">-----------------------------------------------------------------------------------------------------------------------</span>'; // For jslogDomEl var JSLOG_DEF_DOM_EL_COL_NUM = 150; var JSLOG_MAX_TEXT_BOX_ROW_NUM = 10; // Max, then we will use scrollbar var JSLOG_DEF_TEXT_BOX_WIDTH = "800px"; var JSLOG_DEF_TEXT_BOX_HEIGHT = "300px"; var JSU_URL_ALL_SAMPLE = "https://rawgit.com/FedericoLevis/JSU/master/samples/AllSamples.html"; //------------------------ POSITION var JSLOG_POS_TOPLEFT="TopLeft"; var JSLOG_POS_BOTTOMRIGHT="BottomRight"; var JSLOG_POS_TOP="Top"; var JSLOG_POS_LEFT="Left"; var JSLOG_POS_RIGTH="Right"; var JSLOG_POS_BOTTOM="Bottom"; //------------------------ SIZE /** * Size of the log Window<ul> <li>JSLOG_SIZE.XS:"XS" </li> <li>JSLOG_SIZE.S:"S" </li> <li>JSLOG_SIZE.M:"M" </li> <li>JSLOG_SIZE.L:"L" </li> <li>JSLOG_SIZE.XL:"XL" </li> </ul> */ var JSLOG_SIZE = { XS:"XS", S:"S", M:"M", L:"L", XL:"XL" }; //------------------------ ObjOpt Flag /** * For ObjOpt Fields. e.g OpjOpt.style <ul> <li>JSLOG_STYLE.NONE:"NONE" </li> <li>JSLOG_STYLE.ONLY_MEANINGFUL:"ONLY_MEANINGFUL" </li> <li>JSLOG_STYLE.ALL:"ALL" </li> </ul> */ var JSLOG_STYLE = { NONE:"NONE", ONLY_MEANINGFUL:"ONLY_MEANINGFUL", ALL:"ALL" }; //dimensioni iniziali. Attenzione ad TOP perche` poi viene settato insieme a SIZE_DEF var WIN_JSLOG_TOP='370px'; //settata var JSLOG_SIZE_DEF = JSLOG_SIZE.L; // Temporanee var WIN_JSLOG_H='400px'; var WIN_JSLOG_W='1200px'; //************************************************************************** // GLOBAL VARIABLE //************************************************************************** var jj_var ={ iLogLev : 0, bLogTime: JSLOG_DEF_LOG_TIME, // True to Log Time szPathImg: JSLOG_DEF_PATH_IMG, // Default szSize: JSLOG_SIZE_DEF, console: null }; // //************************************************************************** // GLOBAL API //************************************************************************** /** * Init jslog and Show jslog Window if jsLogLev > 0 * @param jsLogLev {Number|String} 2 option: <ul> <li> 'URL' (JSLOG_LEV_URL_PAR='URL') To get jslog parameter from URL (if absent in the URL a LogLev of 0 will be used, that means NO jsLog) </li> <li> iLogLev is a BITMASK to Enable the various Level. Level=0 (JSLOG_ERR) is always enabled when jslog is visible Example of Levels Enable with various settings: <ul> <li> jsLogLev=3 to Enable JSLOG_INFO(1) and JSLOG_DEBUG(2) <li> jsLogLev=4 to Enable only JSLOG_TEST(4) </ul> <table class="jsDoc" border="2" cellpadding="2" cellspacing="2"> <tr><td class="jsDocTitle">jsLogLev BITMASK Values</td></tr> <tr><td class="jsDocParam"> <ul> <li> JSLOG_ERR = 0 ERRORS: always enable when jslog is visible </li> <li> JSLOG_INFO = 1 INFO: Important Information </li> <li> JSLOG_DEBUG = 2 DEBUG Information </li> <li> JSLOG_TRACE = 4 TRACE (e.g. Large Data like JSON) </li> <li> JSLOG_TEST = 8 You can use this value for Specific isolated Feature under TEST/Development </li> <li> JSLOG_JSU = 16 JSU Functionality (usually stable) </li> </ul> </td></tr> </table> </li> </ul> @param [objOpt] {Object} Option <table class="jsDoc" border="2" cellpadding="2" cellspacing="2"> <tr><td class="jsDocTitle">OPTIONS</td></tr> <tr><td class="jsDocParam"> <ul> <li> .bLogTime {Boolean} [def=false] true to log also the Time in format [HH:MM:SS.ms] </li> <li> . szPathImg {String} BaseSortPath (e.g "../../../images") to be used instead of the one configured in conf.js <BR/> Example "/portalDtct0/images/" "../../images/" </li> <li> . szSize {String} [JSLOG_SIZE.M] JSLOG_SIZE.XS, JSLOG_SIZE.M, ..... &nbsp;see <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/jslog.js/global.html#JSLOG_SIZE" target="_self">JSLOG_SIZE</a> </li> <li> iTop {Number} Top to set to JSLog Window </li> </ul> </td></tr> </table> @example // init jslog reading URL parameter jslog, if present // For example // a) LogLev will be set to 3 and jslogWindow will be displayed: // URL=https://rawgit.com/FedericoLevis/JSU/master/samples/Sort/SortSample.html?jslog=3 // a) LogLev will be set to 0 and jslogWindow will NOT be displayed: // URL=https://rawgit.com/FedericoLevis/JSU/master/samples/Sort/SortSample.html jslog_init('URL'); @example // init jslog with Level=3 to Enable JSLOG_ERR (0), JSLOG_INFO(1) and JSLOG_DEBUG(2) jslog_init(3); @example // init jslog with Level=4 to Enable JSLOG_ERR (0) JSLOG_TEST(4) jslog_init(4); */ function jslog_init(jsLogLev,objOpt) { try{ var iLogLev = 0; // Default if (jsLogLev == JSLOG_LEV_AUTO){ // 1) Check if there is the optional input with jslogCfg (optionally provided by page developer) var elIdCfg = document.getElementById (JSLOG_ID_CFG); var elIdLogLev = document.getElementById (JSLOG_ID_LOGLEV); if (elIdCfg != null){ var jsonCfg = elIdCfg.value; if (jsonCfg != null && jsonCfg != ""){ // retrieve cfg var objCfg = JSON.parse(jsonCfg); /* * ES: objCfg ={ iLogLev : 7, bLogTime: true, szPathImg: JSLOG_DEF_PATH_IMG, szSize: .. } */ jsLogLev = objCfg.iLogLev; if (objOpt == undefined){ objOpt = new Object(); } // Set the CFG Staore objOpt.bLogTime = objCfg.bLogTime; objOpt.szPathImg = objCfg.szPathImg; objOpt.szSize = objCfg.szSize; }else { jsLogLev = JSLOG_LEV_URL; } }else if (elIdLogLev != null){ val = elIdLogLev.value; if (val != ""){ jsLogLev = parseInt(elIdLogLev.value); }else { jsLogLev = JSLOG_LEV_URL; } }else { jsLogLev = JSLOG_LEV_URL; } } if (jsLogLev == JSLOG_LEV_URL){ function getPar(name){ if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search)) return decodeURIComponent(name[1]); } var urlLogLev = getPar (JSLOG_LEV_URL_PAR); // alert ("PAR urlLogLev=" + urlLogLev); var szNameLogLev = JSLOG_LEV_URL_PAR + "="; if (typeof (urlLogLev) != 'undefined'){ // Save in Session window.name window.name = szNameLogLev + urlLogLev; }else{ // Retrieve jsLog from window.name if it has been set previously var szLogLev = window.name; if (szLogLev.indexOf(szNameLogLev ) > -1){ urlLogLev = parseInt(szLogLev.substr (szNameLogLev.length)); } } if ((typeof (urlLogLev) != 'undefined')){ iLogLev = urlLogLev; }else { iLogLev =0; } }else { iLogLev = parseInt(jsLogLev); } jj_consoleStart(iLogLev,objOpt); if (objOpt != null && objOpt.szSize != null){ jslogSetSize(objOpt.szSize); } }catch (ex){ console.error (ex); } } /** Change jslogLev @param iLogLev {Number} iLogLev &nbsp;see <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/jslog.js/global.html#jslog" target="_self">iLogLev Parameter</a> <div class="jsDocNote"> <b>Implementation NOTES:</b> <ul> <li>GLOBAL VAR: jj_var.iLogLev set with par iLogLev</li> </ul> </div> */ function jslogLevSet(iLogLev) { jj_var.iLogLev = iLogLev; if (iLogLev == 0){ jslog_end(); }else if (jj_var.console){ jj_var.console.selectLogLev.selectedIndex = iLogLev; jj_setTitle(iLogLev); } jj_saveCfg(); } /** * Set Title * @param iLogLev */ function jj_setTitle(iLogLev){ var szJsuHelp = '<a style="margin-left:30px" class="tipLink" href="' + JSU_URL_ALL_SAMPLE + '" target="_blank">JSU Sample (by <NAME>)</a>' var szTitle = "Level=" + iLogLev + " " + szJsuHelp; jj_var.console.labelTitle.innerHTML = szTitle; } /** Set jslog Window SIZE @param szSize JSLOG_SIZE.XS, JSLOG_SIZE.M, ..... &nbsp;see <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/jslog.js/global.html#JSLOG_SIZE" target="_self">JSLOG_SIZE <div class="jsDocNote"> <b>Implementation NOTES:</b> <ul> <li>GLOBAL VAR: jj_var</li> </ul> </div> */ function jslogSetSize(szSize) { if (jj_var.console != null){ jj_var.console.setSize (szSize); } } /** Set jslog Window SIZE @param iTop {Number} (e.g. 800) Set top of jslog Window <div class="jsDocNote"> <b>Implementation NOTES:</b> <ul> <li>GLOBAL VAR: jj_var</li> </ul> </div> */ function jslogSetTop(iTop) { if (jj_var.console != null && jj_var.console.window!= null){ jj_var.console.window.style.top = iTop + "px"; } } /** Clear jslog Window */ function jslogClear(){ if (jj_var.console){ jj_var.console.clearWindow(); } } /** Get jslogLev @return jj_var.iLogLev {Number} Current jslogLev <div class="jsDocNote"> <b>Implementation NOTES:</b> <ul> <li>GLOBAL VAR: jj_var</li> </ul> </div> */ function jslogGetLogLev() { return jj_var.iLogLev; } /** * Get All Current Option * @return {Object} OBJECT with current jslog option: <ul> * <li> .iLogLev </li> * <li> .bLogTime </li> * <li> .szPathImg </li> * <li> .szSize </li> * </ul> */ function jslogGetOpt() { return { iLogLev : jj_var.iLogLev, bLogTime: jj_var.bLogTime, szPathImg: jj_var.szPathImg, szSize: jj_var.szSize }; } /** * LOG OBJECT: <BR/> * If jslog CONSOLE is Present, Log OBJECT in the jslog CONSOLE if Level is enable <BR/> * If jslog was initialized with Level=0 or if iLogLev is not enabled, this function does not log @param iLogLev {Number} iLogLev &nbsp;see <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/jslog.js/global.html#jslog" target="_self">iLogLev Parameter</a> * @param szMsg {String} Message To log before JSON * @param obj {Object} OBJECT To log * @param [bLogCompact] {Boolean} in Default=false if true log Obj in a compact way * @returns 0 * @example // Prepare object to log var author ={ szFirstName: "Federico", szLastName : "Levis", szCity : "Padova", szNation : "Italy", height: 176 }; // Log Object author at Level JSLOG_TEST=8 jslogObj(JSLOG_TEST,"Log at Level 2 of a JS Object - author:", author); */ function jslogObj(Level,szMsg, obj, bLogCompact) { if (bLogCompact == undefined || bLogCompact == null){ bLogCompact = false; } var iNumSep = (bLogCompact) ? 0 : 2; var szSep = (bLogCompact) ? ": " : "\n"; // WE make the Check here to avoid executing JSON.stringify when Level is not Enable if(isLogLevEnable(Level) && jj_var.console){ jj_var.console.send(Level, szMsg + szSep + JSON.stringify(obj,null,iNumSep)); } return 0; } /** * LOG HTML: log a Text contanint HTML. We log it into a TextBox <BR/> * If jslog CONSOLE is Present, Log main szHtml into a TextArea of the jslog CONSOLE if Level is enable <BR/> * If jslog was initialized with Level=0 or if iLogLev is not enabled, this function does not log @param iLogLev {Number} iLogLev &nbsp;see <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/jslog.js/global.html#jslog" target="_self">iLogLev Parameter</a> * @param szMsg {String} Initial Message * @param szHtml {String} Message To log that can contain HTML TAGs * @param [objOpt] {Object} Options: <ul> * <li> .iColNum TextArea ColNum to use instead of JSLOG_DEF_DOM_EL_COL_NUM </li> * <li> .iRowNum TextArea RowNum to use instead of the rows automatically calculated (MAX is JSLOG_MAX_TEXT_BOX_ROW_NUM) </li> * </ul> * @returns 0 * @example jslogHTML (JSLOG_TEST,'selectTest',getElementById('selectTest').innerHTML); LOGGED: selectTest: <select class="detFilter" id="googleAnalType" title="Initial Analytics TYPE displayed. Then it can be changed form Google Analitycs page" style="width:100%;" onchange="tt_onchangeGoogleAnalType();" > <option class="detFilter" value="all" selected >All Time</option> <option class="detFilter" value="month" >Last Month</option> <option class="detFilter" value="week" >Last Week</option> <option class="detFilter" value="day" >Last Day</option> <option class="detFilter" value="two_hours" >Last 2 Hours</option> */ function jslogHtml(iLogLev,szMsg,szHtml, objOpt) { // WE make the Check here to avoid executing JSON.stringify when Level is not Enable if(!isLogLevEnable(iLogLev) || jj_var.console == undefined){ return; } if (objOpt == undefined){ objOpt = new Object(); } if (objOpt.iColNum == undefined){ objOpt.iColNum = JSLOG_DEF_DOM_EL_COL_NUM; } if (objOpt.iRowNum == undefined){ // if not passed objOpt.iRowNum, we use the number of /n inserted. objOpt.iRowNum = jj_getHtmlRowNum(szHtml); } // prepare szTxtArea var szTxtArea= szMsg + ":<BR\>" + '<textarea style="width: ' + JSLOG_DEF_TEXT_BOX_WIDTH + '"; height: ' + JSLOG_DEF_TEXT_BOX_HEIGHT + '";" rows="' + objOpt.iRowNum + '" cols="' + objOpt.iColNum + '">' + szHtml + '</textarea><BR\>'; jslog (iLogLev,szTxtArea); return 0; } /** * LOG DOM ELEMENT: log main fields (nodeName, attributes,...) of DOM Element <BR/> * Optionally you can Log also Style using objOpt.style parameter <BR/> * If jslog CONSOLE is Present, Log main fields of DOM Elements into a TextArea of the jslog CONSOLE if Level is enable <BR/> * If jslog was initialized with Level=0 or if iLogLev is not enabled, this function does not log @param iLogLev {Number} iLogLev &nbsp;see <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/jslog.js/global.html#jslog" target="_self">iLogLev Parameter</a> * @param szMsg {String} Message To log before DOM Element * @param el {Object} DOM OBJECT To log * @param [objOpt] {Object} Options: <ul> * <li> .iColNum TextArea ColNum to use instead of JSLOG_DEF_DOM_EL_COL_NUM </li> * <li> .iRowNum TextArea RowNum to use instead of the rows automatically calculated (MAX is JSLOG_MAX_TEXT_BOX_ROW_NUM) </li> * <li> .style [JSLOG_STYLE.NONE] To Log also Style set JSLOG_STYLE.ONLY_MEANINGFUL or JSLOG_STYLE.ALL &nbsp;see <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/jslog.js/global.html#JSLOG_STYLE" target="_self">JSLOG_STYLE</a> </li> * </ul> * @returns 0 * @example jslogDomEl (JSLOG_TEST,"DOM ELEMENT tipJS1Lev1",getElementById2("tipJS1Lev1"),{style:JSLOG_STYLE.ONLY_MEANINGFUL}); LOG: DOM ELEMENT tipJS1Lev1: nodeName=INPUT class=tipJSFixed id=tipJS1Lev1 onclick=TipJSFixedClicked (JS1_LEV1,event,{iJSColNum:140}); type=button ...... ---------------------------- meaningful style alignContent = 'stretch' alignItems = 'stretch' alignSelf = 'auto' alignmentBaseline = 'auto' backfaceVisibility = 'visible' backgroundAttachment = 'scroll' backgroundClip = 'border-box' backgroundColor = 'rgb(224, 224, 224)' */ function jslogDomEl(iLogLev,szMsg, el, objOpt) { if (el == null || el == 0){ return; } // WE make the Check here to avoid executing JSON.stringify when Level is not Enable if(!isLogLevEnable(iLogLev) || jj_var.console == undefined){ return; } if (objOpt == undefined){ objOpt = new Object(); } if (objOpt.iColNum == undefined){ objOpt.iColNum = JSLOG_DEF_DOM_EL_COL_NUM; } if (objOpt.style == undefined){ objOpt.style = JSLOG_STYLE.NONE ; } var szEl="nodeName=" + el.nodeName + "\n"; for (var i=0; i<el.attributes.length; i++){ var attr = el.attributes[i]; szEl += attr.name + "=" + attr.value + "\n"; } szEl += "outerHTML=" + jj_replaceAll(el.outerHTML,"><",">\n<"); if (objOpt.style != JSLOG_STYLE.NONE ){ var st = el.style; var cs = window.getComputedStyle(el, null); szEl += "\n\n--------------------------------------- "; if (objOpt.style == JSLOG_STYLE.ONLY_MEANINGFUL){ szEl += "meaningful style \n"; }else{ szEl += "style \n"; } for (x in st) { var bLog = true; if (objOpt.style == JSLOG_STYLE.ONLY_MEANINGFUL){ if ((st[x] == 0 && cs[x] == undefined) || (st[x] == false && cs[x] == undefined) || (st[x] == '' && cs[x] == '') || (x.indexOf('animation')>=0 || x.indexOf('accelerator')>=0 ) || (st[x] != undefined && (typeof(st[x]) == 'function')) ) { bLog = false; } } if (bLog){ var szStyle = st[x]; if (szStyle == 0 || szStyle =='') { szStyle = cs[x]; } szEl += " " + x + " = '" + szStyle + "'\n"; } } } if (objOpt.iRowNum == undefined){ // if not passed objOpt.iRowNum, we use the number of /n inserted. objOpt.iRowNum = jj_getHtmlRowNum(szEl); } // prepare szTxtArea var szTxtArea= szMsg + ":<BR\>" + '<textarea rows="' + objOpt.iRowNum + '" cols="' + objOpt.iColNum + '" readonly>' + szEl + '</textarea><BR\>'; jslog (iLogLev,szTxtArea); return 0; } /** * LOG DOM ELEMENT: log main fields (nodeName, attributes,...) of DOM Element <BR/> * Optionally you can Log also Style using objOpt.style parameter <BR/> * If jslog CONSOLE is Present, Log main fields of DOM Elements into a TextArea of the jslog CONSOLE if Level is enable <BR/> * If jslog was initialized with Level=0 or if iLogLev is not enabled, this function does not log @param iLogLev {Number} iLogLev &nbsp;see <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/jslog.js/global.html#jslog" target="_self">iLogLev Parameter</a> * @param szMsg {String} Message To log before DOM Element * @param el {Object} DOM OBJECT To log * @param [objOpt] {Object} Options: <ul> * <li> .iColNum TextArea ColNum to use instead of JSLOG_DEF_DOM_EL_COL_NUM </li> * <li> .iRowNum TextArea RowNum to use instead of the rows automatically calculated (MAX is JSLOG_MAX_TEXT_BOX_ROW_NUM) </li> * <li> .style [JSLOG_STYLE.NONE] To Log also Style set JSLOG_STYLE.ONLY_MEANINGFUL or JSLOG_STYLE.ALL &nbsp;see <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/jslog.js/global.html#JSLOG_STYLE" target="_self">JSLOG_STYLE</a> </li> * </ul> * @returns 0 * @example jslogDomEl (JSLOG_TEST,"DOM ELEMENT tipJS1Lev1","tipJS1Lev1",{style:JSLOG_STYLE.ONLY_MEANINGFUL}); LOG: DOM ELEMENT tipJS1Lev1: nodeName=INPUT class=tipJSFixed id=tipJS1Lev1 onclick=TipJSFixedClicked (JS1_LEV1,event,{iJSColNum:140}); type=button ...... ---------------------------- meaningful style alignContent = 'stretch' alignItems = 'stretch' alignSelf = 'auto' alignmentBaseline = 'auto' backfaceVisibility = 'visible' backgroundAttachment = 'scroll' backgroundClip = 'border-box' backgroundColor = 'rgb(224, 224, 224)' */ function jslogDomElById(Level,szMsg, szId,objOpt) { return jslogDomEl(Level,szMsg,document.getElementById(szId), objOpt); } /** PAR json i Json obj @returns String for jslog */ function json2jslogStr(json) { // N.B: devo cambiare qualcosa nei replace o si inluppa var szJson = jj_replaceAll(JSON.stringify(json),"},","} ,\n "); szJson = jj_replaceAll (szJson,":[",":\n[\n "); szJson = jj_replaceAll (szJson,"[{","[\n {"); return jj_replaceAll (szJson,"}]","}\n]\n "); } /** * LOG JSON: <BR/> * If jslog CONSOLE is Present, Log json in the jslog CONSOLE if Level is enable <BR/> * If jslog was initialized with Level=0 or if iLogLev is not enabled, this function does not log @param iLogLev {Number} iLogLev &nbsp;see <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/jslog.js/global.html#jslog" target="_self">iLogLev Parameter</a> * @param szMsg {String} Message To log before JSON * @param json {String} JSON To log * * @returns 0 * @example // Prepare json var jsonEx = {"total":5,"rows":[ {"day":"21/04/2015","daration_sec":15,"err_num":7}, {"day":"22/04/2015","daration_sec":0,"err_num":1}, {"day":"23/04/2015","daration_sec":3,"err_num":3}, {"day":"24/04/2015","daration_sec":3,"err_num":2}, {"day":"25/04/2015","daration_sec":3,"err_num":14} ]}; // log json at Level JSLOG_DEBUG=2 jslogJson(JSLOG_DEBUG,"Log at Level 2 of a JS Object. jsonEx:", jsonEx); */ function jslogJson(iLogLev,szMsg, json) { // WE make the Check here to avoid executing JSON.stringify when iLogLev is not Enable if(isLogLevEnable(iLogLev)){ jj_var.console.send(iLogLev,szMsg + "\n" + json2jslogStr(json)); } return 0; } /** * Log the Elapsed Time From dStart to Now @param iLogLev {Number} iLogLev &nbsp;see <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/jslog.js/global.html#jslog" target="_self">iLogLev Parameter</a> * @param szMsg {String} Message To log * @param dStart Start date * @return 0 */ function jslogElapsedTime (iLogLev,szMsg,dStart){ if(isLogLevEnable(iLogLev) && jj_var.console) { var dEnd = new Date(); var iDeltaMs = dEnd.getTime() - dStart.getTime(); var szDurata = (iDeltaMs > 1000) ? ((iDeltaMs/1000) + " sec") : (iDeltaMs + " msec"); jj_var.console.send(iLogLev,szMsg + szDurata); } return 0; } /** * LOG a STRING: <BR/> * If jslog CONSOLE is Present, Log Msg in the jslog CONSOLE if Level is enable <BR/> * If jslog was initialized with Level=0 or if iLogLev is not enabled, this function does not log * @param iLogLev {Number} iLogLev is a BITMASK to Enable the various Level. Level=0 (JSLOG_ERR) is always enabled when jslog is visible. Example of Levels Enable with various settings: <ul> <li> jsLogLev=3 to Enable JSLOG_INFO(1) and JSLOG_DEBUG(2) <li> jsLogLev=4 to Enable only JSLOG_TEST(4) </ul> <table class="jsDoc" border="2" cellpadding="2" cellspacing="2"> <tr><td class="jsDocTitle">jsLogLev BITMASK Values</td></tr> <tr><td class="jsDocParam"> <ul> <li> JSLOG_ERR = 0 ERRORS: always enable when jslog is visible </li> <li> JSLOG_INFO = 1 INFO: Important Information </li> <li> JSLOG_DEBUG = 2 DEBUG Information </li> <li> JSLOG_TRACE = 4 TRACE (e.g. Large Data like JSON) </li> <li> JSLOG_TEST = 8 You can use this value for Specific isolated Feature under TEST/Development </li> <li> JSLOG_JSU = 16 JSU Functionality (usually stable) </li> </ul> </td></tr> </table> * @param szMsg {String} Message To log * @returns 0 <div class="jsDocNote"> <b>Implementation NOTES:</b> <ul> <li>GLOBAL VAR: jj_var</li> </ul> </div> * @example // Prepare szMsg: var szName = "<NAME>"; var iHeight = 177; var now = new Date(); //LOG at Level JSLOG_INFO=1 jslog(JSLOG_INFO,"This a Log at Level 1. My name is " + szName + ", Height=" + iHeight + " cm - Current Time is: " + now); * * */ function jslog(iLogLev,szMsg) { if(isLogLevEnable(iLogLev) && jj_var.console) { jj_var.console.send(iLogLev,szMsg); } return 0; } /** * jslog END: destroy the JSLOG window if present */ function jslog_end() { if (jj_var.console){ jj_var.console.killWindow(); } } /** * Check if iLogLev is Enabled @param iLogLev {Number} iLogLev &nbsp;see <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/jslog.js/global.html#jslog" target="_self">iLogLev Parameter</a> * @returns {Boolean} true if iLogVel is Enabled */ function isLogLevEnable(iLogLev) { return ((jj_var.iLogLev & iLogLev || iLogLev == 0) && jj_var.console != null ); } /********************************************************************************************************** * PRIVATE ******************************************************************************************************/ function jj_getHtmlRowNum(szHtml){ if (typeof(szHtml) != "string"){ return 0; } var iRowNum = 1 + (szHtml.match(/\n/g) || []).length; if (iRowNum > JSLOG_MAX_TEXT_BOX_ROW_NUM){ iRowNum = JSLOG_MAX_TEXT_BOX_ROW_NUM; } return iRowNum; } /* * * Replace in str di tutte le occorrenze di strFrom, che vengono sostituite con strTo * @param str es: "questa frase contiene Pippo 2 volte perche` alla fine ripeto Pippo" * @param strFrom es: "Pippo" * @param strTo es: "Paperino" * @returns str es: "questa frase contiene Paperino 2 volte perche` alla fine ripeto Paperino" */ function jj_replaceAll(str,strFrom,strTo) { if (typeof(str) == "undefined"){ return ""; } while (str.indexOf(strFrom)>-1) { str = str.replace(strFrom,strTo); } return str; } /* * Save jslogCfg to jhslogCfg input id, if present */ function jj_saveCfg(){ var el = document.getElementById (JSLOG_ID_CFG); if (el != null){ var objCfg = { iLogLev: jj_var.iLogLev, bLogTime: jj_var.bLogTime, szPathImg: jj_var.szPathImg, szSize: jj_var.szSize } var jsonCfg = JSON.stringify(objCfg,null,0); el.value = jsonCfg; }else { // In your page You can choose to save only iLogVel var el = document.getElementById (JSLOG_ID_LOGLEV); if (el != null){ el.value = jj_var.iLogLev; } } } /* * @param iLogLev {Number} iLogLev &nbsp;see <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/jslog.js/global.html#jslog" target="_self">iLogLev Parameter</a> * @param [objOpt] {Object} see jslog_init */ function jj_consoleStart(iLogLev,objOpt){ var szSize = JSLOG_SIZE_DEF; jslog_end(); // End previous jj_var.console if present jj_var.iLogLev = iLogLev; if (jj_var.iLogLev ==0){ return; } if (objOpt != undefined){ if (objOpt.szPathImg != undefined){ // save in Global jj_var.szPathImg = objOpt.szPathImg; } if (objOpt.bLogTime != undefined){ // save in Global jj_var.bLogTime = objOpt.bLogTime; } /* NOT STIL WORKING if (objOpt.szSize != undefined){ // save in Global jj_var.szSize = objOpt.szLogSize; szSize = jj_var.szSize; } */ } jj_var.console = { /*---------------------------------------------------------------------------- Core Functionality ----------------------------------------------------------------------------*/ // vars debugging_on: false, window: null, viewport: null, buffer: '', debugVisible: false, // Status related to showDebug Button (debugVisible= true after click) arBtnDebug: new Array(), //Btn for Debug (2 Buttons) // initialization init: function(){ if( !document.getElementsByTagName || !document.getElementById || !document.createElement || !document.createTextNode ) return; var domBody = document.getElementsByTagName( 'body' )[0]; if (typeof (domBody) == 'undefined'){ return; } jj_var.console.createWindow(); jj_var.console.getCookie(); jj_var.console.debugging_on = true; jj_var.console.setSize (szSize); }, // jj_var.console window creation createWindow: function(){ jj_var.console.window = document.createElement( 'div' ); // the window jj_var.console.window.style.background = '#000'; jj_var.console.window.style.font = '9pt "Lucida Grande", "Lucida Sans Unicode", sans-serif'; jj_var.console.window.style.padding = '2px'; jj_var.console.window.style.position = 'absolute'; jj_var.console.window.style.top = WIN_JSLOG_TOP; jj_var.console.window.style.left = '0px'; jj_var.console.window.style.height = WIN_JSLOG_H; jj_var.console.window.style.zIndex = '100'; jj_var.console.window.style.minHeight = '40px'; jj_var.console.window.style.width = WIN_JSLOG_W; jj_var.console.window.style.minWidth = '150px'; var x = document.createElement('span'); // the closer x.style.border = '1px solid #000'; x.style.cursor = 'pointer'; x.style.color = '#000'; x.style.display = 'block'; x.style.lineHeight = '.5em'; x.style.padding = '0 0 3px'; x.style.position = 'absolute'; x.style.top = '4px'; x.style.right = '4px'; x.setAttribute( 'title', 'Close jj_var.console Debugger' ); x.appendChild( document.createTextNode( 'x' ) ); jj_var.console.addEvent( x, 'click', function(){ jj_var.console.killWindow(); } ); jj_var.console.window.appendChild( x ); var sh = document.createElement('div'); // the stretcher holder sh.style.position = 'absolute'; sh.style.bottom = '3px'; sh.style.right = '3px'; var sg = document.createElement('span'); // the stretcher grip sg.style.border = '5px solid #ccc'; sg.style.borderLeftColor = sg.style.borderTopColor = '#000'; sg.style.cursor = 'pointer'; sg.style.color = '#ccc'; sg.style.display = 'block'; sg.style.height = '0'; sg.style.width = '0'; sg.style.overflow = 'hidden'; sg.setAttribute( 'title', 'Resize the jj_var.console Debugger' ); if( typeof( Drag ) != 'undefined' ){ // make it draggable sg.xFrom = 0; sg.yFrom = 0; Drag.init( sg, null, null, null, null, null, true, true ); sg.onDrag = function( x, y ){ jj_var.console.resizeX( x, this ); jj_var.console.resizeY( y, this ); jj_var.console.adjustViewport(); }; sg.onDragEnd = function(){ jj_var.console.setCookie(); }; sh.appendChild( sg ); jj_var.console.window.appendChild( sh ); } var header = document.createElement( 'h3' ); header.className = "jslog"; header.style.textAlign = "left"; jj_var.console.appendAllBtn(header,false); //-------------------------------------- header.appendChild( jj_var.console.getGroupSep(" ")); jj_var.console.labelTitle = document.createElement( 'label' ); jj_var.console.labelTitle.className = "jslog"; jj_setTitle(jj_var.iLogLev); header.appendChild(jj_var.console.labelTitle); jj_var.console.window.appendChild( header ); //------------------------ var footer = document.createElement( 'div' ); // additional footer holder footer.className = "jslogFooter"; jj_var.console.appendAllBtn(footer,true); jj_var.console.window.appendChild( footer); // STYLE jj_var.console.viewport = document.createElement( 'pre' ); jj_var.console.viewport.style.border = '1px solid #ccc'; jj_var.console.viewport.style.color = '#ebebeb'; jj_var.console.viewport.style.color = 'white'; jj_var.console.viewport.style.backgroundColor = 'black'; jj_var.console.viewport.style.textAlign = 'left'; jj_var.console.viewport.style.fontSize = '1.2em'; jj_var.console.viewport.style.margin = '0'; jj_var.console.viewport.style.padding = '0 3px'; jj_var.console.viewport.style.position = 'absolute'; jj_var.console.viewport.style.top = '25px'; jj_var.console.viewport.style.left = '2px'; jj_var.console.viewport.style.overflow = 'auto'; jj_var.console.adjustViewport(); jj_var.console.window.appendChild( jj_var.console.viewport ); document.getElementsByTagName( 'body' )[0].appendChild( jj_var.console.window ); if( typeof( Drag ) != 'undefined' ){ // make it draggable Drag.init( header, jj_var.console.window ); jj_var.console.window.onDragEnd = function(){ jj_var.console.setCookie(); }; } }, // resizing stuff resizeX: function( x, grip ){ var width = parseInt( jj_var.console.window.style.width ); var newWidth = Math.abs( width - ( x - grip.xFrom ) ) + 'px'; if( parseInt( newWidth ) < parseInt( jj_var.console.window.style.minWidth ) ) newWidth = jj_var.console.window.style.minWidth; jj_var.console.window.style.width = newWidth; grip.xFrom = x; }, resizeY: function( y, grip ){ var height = parseInt( jj_var.console.window.style.height ); var newHeight = Math.abs( height - ( y - grip.yFrom ) ) + 'px'; if( parseInt( newHeight ) < parseInt( jj_var.console.window.style.minHeight ) ) newHeight = jj_var.console.window.style.minHeight; jj_var.console.window.style.height = newHeight; grip.yFrom = y; }, // adjust viewport adjustViewport: function(){ jj_var.console.viewport.style.width = ( parseInt( jj_var.console.window.style.width ) - 8 ) + 'px'; jj_var.console.viewport.style.height = ( parseInt( jj_var.console.window.style.height ) - 50 ) + 'px'; }, // send data too the window send: function(iLevel, text ){ if (iLevel == JSLOG_ERR){ console.error (text); } // Replace "/n" with <br> // look for "\n" and replace with <BR> text = text + "<br/>"; // if textarea we do not replace \n if (text.indexOf("<textarea rows") < 0){ while (text.indexOf("\n")>-1) { text = text.replace("\n","<br/>"); } } var szTime =""; if (jj_var.bLogTime){ var d = new Date(); szTime = jj_var.console.num2StrPad(d.getHours(),'0',2) + ":" + jj_var.console.num2StrPad(d.getMinutes(),'0',2) + ":" + jj_var.console.num2StrPad(d.getSeconds(),'0',2) + "." + jj_var.console.num2StrPad(d.getMilliseconds(),'0',3) + " "; } // for delimiter we pass null if (iLevel != null){ text = szTime + "[" + iLevel + "] " + text; } if( jj_var.console.viewport == null ){ /* store in the buffer if the viewport has not yet been built */ jj_var.console.buffer += text; } else { jj_var.console.viewport.innerHTML += text; jj_var.console.scrollWithIt(); } }, // send the buffer to the window sendBuffer: function(){ if( jj_var.console.viewport == null ){ jj_var.console.timer = window.setTimeout( 'jj_var.console.sendBuffer()', 500 ); } else { jj_var.console.viewport.innerHTML += jj_var.console.buffer; jj_var.console.scrollWithIt(); jj_var.console.killTimer(); } }, // adjust the viewport to keep pace with the latest entries scrollWithIt: function(){ jj_var.console.viewport.scrollTop = jj_var.console.viewport.scrollHeight; }, // kill the window killWindow: function() { jj_var.console.window.parentNode.removeChild( jj_var.console.window ); jj_var.console.debugging_on = false; jj_var.console = null; window.name = JSLOG_LEV_URL_PAR + "=0"; }, // cookie handlers setCookie: function(){ var posn = jj_var.console.window.style.top + ' ' + jj_var.console.window.style.left; var size = jj_var.console.window.style.height + ' ' + jj_var.console.window.style.width; document.cookie = 'jj_var.console=' + escape( posn + ' ' + size ); }, getCookie: function(){ if( !document.cookie ) return; var all_cookies = document.cookie; var found_at = all_cookies.indexOf('jj_var.console='); if( found_at != -1 ){ var start = found_at + 'jj_var.console='.length; var end = all_cookies.indexOf( ';', start ); var value = ( end != -1 ) ? all_cookies.substring( start, end ) : all_cookies.substring( start ); value = unescape( value ); var vals = value.split( ' ' ); // start with position jj_var.console.window.style.top = vals[0]; jj_var.console.window.style.left = vals[1]; // then size jj_var.console.window.style.height = vals[2]; jj_var.console.window.style.width = vals[3]; jj_var.console.adjustViewport(); } }, // generic timer setup (if needed) timer: null, killTimer: function(){ clearTimeout( jj_var.console.timer ); }, // event handlers addEvent: function( obj, type, fn ){ if (obj.addEventListener) obj.addEventListener( type, fn, false ); else if (obj.attachEvent) { obj["e"+type+fn] = fn; obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }; obj.attachEvent( "on"+type, obj[type+fn] ); } }, removeEvent: function ( obj, type, fn ) { if (obj.removeEventListener) obj.removeEventListener( type, fn, false ); else if (obj.detachEvent) { obj.detachEvent( "on"+type, obj[type+fn] ); obj[type+fn] = null; obj["e"+type+fn] = null; } }, /*================================================================================================ * @param parent {Object} the parent that will be added the Btn * @param bFooter {Boolean} true for Footer ===============================================================================================*/ appendAllBtn: function (parent,bFooter) { var listBtn = new Array(); parent.appendChild( jj_var.console.getImgPos("arrowTopLeft.jpg","Move JSConsole to TOP LEFT CORNER",JSLOG_POS_TOPLEFT)); parent.appendChild( jj_var.console.getImgPos("arrowBottomRight.jpg","Move JSConsole to BOTTOM RIGHT LEFT CORNER",JSLOG_POS_BOTTOMRIGHT)); parent.appendChild( jj_var.console.getImgPos("arrowLeft.jpg","Move JSConsole to LEFT SIDE",JSLOG_POS_LEFT)); parent.appendChild( jj_var.console.getImgPos("arrowRight.jpg","Move JSConsole to the RIGHT SIDE",JSLOG_POS_RIGTH)); // parent.appendChild( jj_var.console.getBtnSep()); parent.appendChild( jj_var.console.getImgPos("arrowTop.jpg","Move JSConsole to the TOP",JSLOG_POS_TOP)); parent.appendChild( jj_var.console.getImgPos("arrowBottom.jpg","Move JSConsole to the BOTTOM",JSLOG_POS_BOTTOM)); //-------------------------------------- SIZE parent.appendChild( jj_var.console.getGroupSep("")); var listBtnSize = new Array(); var w=30; listBtnSize.push( [ 'XS', w,'Size SX', function(){ jj_var.console.setSize(JSLOG_SIZE.XS); } ] ); listBtnSize.push( [ 'S', w,'Size S', function(){ jj_var.console.setSize(JSLOG_SIZE.S); } ] ); listBtnSize.push( [ 'M', w,'Size M', function(){ jj_var.console.setSize(JSLOG_SIZE.M); } ] ); listBtnSize.push( [ 'L', w,'Size L', function(){ jj_var.console.setSize(JSLOG_SIZE.L); } ] ); listBtnSize.push( [ 'XL', w,'Size XL', function(){ jj_var.console.setSize(JSLOG_SIZE.XL); } ] ); // ========================== Add buttons for(var i=0; i < listBtnSize.length; i++ ){ var btn = jj_var.console.getBtn(listBtnSize[i]); parent.appendChild( btn); parent.appendChild( jj_var.console.getBtnSep()); } // ----------------------------------------- define any Other Add-on Buttons parent.appendChild( jj_var.console.getGroupSep("")); listBtn.push( [ 'Clear', 60, 'Clear the Window', function(){ jj_var.console.clearWindow(); } ] ); listBtn.push( [ 'Delimiter', 70, 'Add a Separator Delimet', function(){ jj_var.console.sendDelimiter(); }] ); if (jj_var.console.isIE()){ listBtn.push( [ 'CopyToClipboard',120, 'Copy To Clipboard All the contain of the Window', function(){ jj_var.console.copy2Clipboard(); } ] ); }else{ listBtn.push( [ 'SelectAll',70, 'Select ALL', function(){ jj_var.console.selectAll(); } ] ); } // ========================== Add buttons for(var i=0; i < listBtn.length; i++ ){ var btn = jj_var.console.getBtn(listBtn[i]); parent.appendChild( btn); parent.appendChild( jj_var.console.getBtnSep()); } parent.appendChild( jj_var.console.getGroupSep("")); var btnDebug = jj_var.console.getBtn( [ 'Show debug Fields', 150, 'Show hidden fields having class="debug" or id="debug"', function(){ var szBtnValue, szBtnTitle; if (jj_var.console.debugVisible){ // Debug are visible. We hide them jj_var.console.debugVisible = false; szBtnValue = 'Show ' + JSLOG_ID_DEBUG + ' Fields'; szBtnTitle = 'Show hidden fields having class="' + JSLOG_ID_DEBUG + '" or id="' + JSLOG_ID_DEBUG + '"'; }else{ // Debug are visible. We Show them them jj_var.console.debugVisible = true; szBtnValue = 'Hide ' + JSLOG_ID_DEBUG + 'Fields'; szBtnTitle = 'Hide again Debug fields having class="' + JSLOG_ID_DEBUG + '" or id="' +JSLOG_ID_DEBUG + '"'; } // Change value and title of the array (2) of btnDebug for (var i=0; i<jj_var.console.arBtnDebug.length; i++){ var btnDebug = jj_var.console.arBtnDebug[i]; btnDebug.value = szBtnValue; btnDebug.title = szBtnTitle; } // Get List of all elements with tag SPAN and id= "debug" var TAG_DEBUG = ["SPAN","DIV","TABLE"]; for (var iTag=0; iTag < TAG_DEBUG.length; iTag++){ var ElList = document.getElementsByTagName(TAG_DEBUG[iTag]); for (var i=0; i < ElList.length; i++){ var El = ElList [i]; if (El.id == "debug" || El.className == "debug"){ if (jj_var.console.debugVisible){ // El.style.visibility="visible"; El.style.display="block"; }else { // El.style.visibility="hidden"; El.style.display="none"; } } } } }] ); parent.appendChild(btnDebug); // add to the list of btnDebug jj_var.console.arBtnDebug.push (btnDebug); parent.appendChild( jj_var.console.getGroupSep("")); parent.appendChild( jj_var.console.getGroupSep("")); // CLOSE JSLOG BTN var btnClose = jj_var.console.getBtn( [ 'CLOSE JSLOG', 120, 'Close JSLog Window', function(){ jslog_end(); } ] ); parent.appendChild(btnClose); //-------------------------------- Select with logLev // We add Only in Footer because they do not work in H3 if (bFooter ){ var label = document.createElement( 'label' ); label.className = "jslogFooter"; label.innerHTML = "SETTINGS: "; parent.appendChild(label); var selectLogLev = document.createElement( 'select'); selectLogLev.className ='jslog'; for (var i=0; i <= 31; i++){ var szText = "LogLevel=" + i; if (i==0){ szText = "CLOSE JSLOG"; } var elOpt = new Option(szText,i); elOpt.dv = szText; elOpt.selected = (jj_var.iLogLev == i); selectLogLev[selectLogLev.length] = elOpt; } jj_var.console.addEvent(selectLogLev, 'change', function(){ jslogLevSet (this.selectedIndex); } ); parent.appendChild(selectLogLev); jj_var.console.selectLogLev = selectLogLev; //------------------------------------------------------- var selectLogTime = document.createElement( 'select'); selectLogTime.className ='jslog'; var arOpt =[["0","NO Time"],["1","Log Time"]]; for (var i=0; i < arOpt.length; i++){ var szText = arOpt[i][1]; var elOpt = new Option(szText,arOpt[i][0]); elOpt.dv = szText; elOpt.selected = ((!jj_var.bLogTime && i==0) || (jj_var.bLogTime && i==1)); selectLogTime[selectLogTime.length] = elOpt; } jj_var.console.addEvent(selectLogTime, 'change', function(){ jj_var.bLogTime = (this.selectedIndex ==1); jj_saveCfg(); } ); parent.appendChild(selectLogTime); } }, /*---------------------------------------------------------------------------- Footer Functions ----------------------------------------------------------------------------*/ // send a delimiter to the window sendDelimiter: function(){ jj_var.console.send(null, JSLOG_DELIMITER); }, selectAll: function() { if (document.selection) { var range = document.body.createTextRange(); range.moveToElementText(jj_var.console.window); range.select(); } else if (window.getSelection) { var range = document.createRange(); range.selectNode(jj_var.console.window); window.getSelection().addRange(range); } }, // copy 2 Clipboard (only IE) copy2Clipboard: function(){ var i=0; // look for <BR> and <br> and replace with "\n" // Get Current String with trace var NewString = "" + jj_var.console.viewport.innerHTML; while (NewString.indexOf("<BR>")>-1) { NewString = NewString.replace("<BR>","\n"); i++; } while (NewString.indexOf("<br>")>-1) { NewString = NewString.replace("<br>","\n"); i++; } // Now NetString has NewLines // for clipboard var textArea = document.createElement( 'TextArea'); // textArea.innerText = Text; textArea.innerText = NewString; if (typeof(textArea.createTextRange) == "undefined"){ alert("copy2Clipboard NOT supported for This Browser - Supported Browser for COPY to Clipboard: IE." + "To Copy to Clipboard Please use SelectAll or CTRL-C CTRL-V"); return; } Copied = textArea.createTextRange(); Copied.execCommand("RemoveFormat"); Copied.execCommand("Copy"); // alert("ALL Rows Copied to Clipdoard "); }, isIE: function() { try{ return ((navigator.appName == 'Microsoft Internet Explorer') || ((navigator.appName == 'Netscape') && (new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})").exec(navigator.userAgent) != null))); } catch(err){ return false; } }, getBtn: function(arDesc){ var btn = document.createElement( 'input'); btn.className = 'jslogButton'; btn.setAttribute( 'type', 'button' ); btn.setAttribute( 'value', arDesc[0] ); btn.style.width = arDesc[1] + 'px'; btn.setAttribute( 'title', arDesc[2] ); jj_var.console.addEvent( btn, 'click', arDesc[3] ); return btn; }, getTxtSep: function(txt){ var sep = document.createElement( 'span' ); sep.style.color = '#ffffff'; sep.style.fontWeight= 'bold'; sep.style.padding = '0 2px 0px 10px'; sep.style.textAlign = "right"; sep.appendChild(document.createTextNode( txt )); return sep; }, getBtnSep: function(){ var sep = document.createElement( 'span' ); sep.style.color = '#ffffff'; sep.style.padding = '0 3px 0px 0px'; return sep; }, getGroupSep: function(){ var sep = document.createElement( 'span' ); sep.style.color = '#ffffff'; sep.style.padding = '0 10px 0px 0px'; return sep; }, getImgPos: function(src,tip,Pos){ var img = document.createElement( 'img' ); img.style.padding = '0px 2px'; img.style.cursor = 'pointer'; img.src = jj_var.szPathImg + src; img.height = 15; img.width = 15; img.align = "top"; img.title= tip; img.style.border = '1px solid black'; // Set Border Yellow when mouse is Over Img jj_var.console.addEvent( img, 'mouseenter', function(){this.style.border = '1px solid yellow'; }); jj_var.console.addEvent( img, 'mouseleave', function(){this.style.border = '1px solid black';}); jj_var.console.addEvent( img, 'click', function(){jj_var.console.setPos(Pos);}); // return img; }, /* * Set Console Position * @param szSize JSLOG_POS_XS... */ setSize: function(szSize){ jj_var.szSize = szSize; jj_saveCfg(); var hMax=0; var wMax=0; var w=0; var h=0; if (typeof(window.innerHeight) != 'undefined'){ //Some Space for scrollbar (if present) hMax= window.innerHeight-30; wMax= window.innerWidth-30; }else{ // Particular cases hMax= window.screen.height-150; wMax= window.screen.width-30; } if (szSize == JSLOG_SIZE.XS){ w =1100; h=150; } else if (szSize == JSLOG_SIZE.S){ h = parseInt (hMax *0.3); w = parseInt (wMax *0.8); } else if (szSize == JSLOG_SIZE.M){ h = parseInt (hMax *0.5); w = parseInt (wMax *1); } else if (szSize == JSLOG_SIZE.L){ h = parseInt (hMax *0.6); w = parseInt (wMax *1); } else if (szSize == JSLOG_SIZE.XL){ jj_var.console.window.style.top = '0px'; jj_var.console.window.style.left = '0px'; h = parseInt (hMax *1); w = parseInt (wMax *1); } if (w < 1100){ w = 1100; } jj_var.console.window.style.width = w + 'px'; jj_var.console.window.style.height = h + 'px'; jj_var.console.adjustViewport(); }, /* * Set Console Position * @param pos JSLOG_POS_TOPLEFT... */ setPos: function(pos){ var top = 0; var left = 0; if (typeof(window.innerHeight) != 'undefined'){ //Some Space for scrollbar (if present) top= window.innerHeight - 50; left= window.innerWidth - 150; }else{ // Particular cases top= window.screen.height-100; left= window.screen.width-200; } if (pos == JSLOG_POS_TOPLEFT){ jj_var.console.window.style.top = '0px'; jj_var.console.window.style.left = '0px'; } else if (pos == JSLOG_POS_BOTTOMRIGHT){ jj_var.console.window.style.top = top + 'px'; jj_var.console.window.style.left = left + 'px'; } else if (pos == JSLOG_POS_TOP){ jj_var.console.window.style.top = '0px'; } else if (pos == JSLOG_POS_BOTTOM){ // var h = jj_var.console.window.style.height.replace('px',''); jj_var.console.window.style.top = top + 'px'; } else if (pos == JSLOG_POS_LEFT){ jj_var.console.window.style.left = '0px'; } else if (pos == JSLOG_POS_RIGTH){ // var w = jj_var.console.window.style.width.replace('px',''); jj_var.console.window.style.left = left + 'px'; } }, clearWindow: function(){ jj_var.console.viewport.innerHTML = ''; }, /** * @param iNum e.g 123 * @param szPad "0" * @param iLenWithPad 5 * @returns "00123 */ num2StrPad: function (iNum,szPad, iLenWithPad) { var iZeroPad = iLenWithPad - iNum.toString().length + 1; return Array(+(iZeroPad > 0 && iZeroPad)).join("0") + iNum; } }; // jj_var.console.addEvent( window, 'load', jj_var.console.init ); // jj_var.console.addEvent( window, 'load', jj_var.console.sendBuffer ); jj_var.console.init(); if (objOpt && objOpt.iTop){ jslogSetTop (objOpt.iTop); } } <file_sep>/JQPopup/Popup.js /** @fileOverview ========================================================================================= <BR/> <b>File:</b> JQPopup/Popup.js <BR/> <b>Author:</b> <a href="https://www.linkedin.com/in/federicolevis" target="_self"><NAME></a> <BR/> <b>JSPopup Doc:</b> <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/HTML/JSPopup.html" target="_self">JSU JSPopup Documentation</a> <BR/> <b>JSU API Doc:</b> <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/JSUAPI.html" target="_self">JSU API Documentation</a> <BR/> <b>Description:</b> jquery Popup API, generic for ALL Browsers (IE, Mozilla, Chrome, ..) <BR/> <b>REQUIRED:</b> From JSU: <ul> <li><b>jsu/externalPlugin/jquery:</b> jquery-ui.css jquery.js jquery-ui.js </li> <li><b>CSS:</b> jsu.css </li> <li><b>JS</b> jsuCmn.js util.js </li> <li><b>OPTIONAL JS:</b> jslog.js, dom-drag.js (required only to enable jslog)</li> </ul> <b>First Version:</b> 1.0 Jan 2015 <BR/> <b>Current Version:</b> JSU v. 1.10 &nbsp;&nbsp;&nbsp;2018-Jan-14 <BR/> <BR/>-----------------------------------------------------------------------------------<BR/> <b>DISCLAIMER</b> <BR/> Copyright by <NAME> - <a href="https://github.com/FedericoLevis/JSU" target="_self">JSU</a> <BR/> This file may be freely distributed under the MIT license. <BR/> ========================================================================================= <BR/> */ /* ==================================================================================================== * GLOBAL COSTANT ====================================================================================================*/ /** * POPUP_TYPE used in Popup() API as szPopupType par, to identify the PopupType to display: <ul> <li> POPUP_TYPE.INFO: "Info", </li> <li> POPUP_TYPE.CONFIRM: "Confirm", </li> <li> POPUP_TYPE.ERR:"Error", </li> <li> POPUP_TYPE.ALARM:"Alarm", </li> <li> POPUP_TYPE.WARN:"Warning", </li> <li> POPUP_TYPE.QUESTION:"Question", // Question with YES NO </li> <li> POPUP_TYPE.QUESTION_3:"Question_3Btn", // Question with YES NO CANCEL </li> <li> POPUP_TYPE.PROMPT:"Prompt", // Prompt to insert one value </li> <li> POPUP_TYPE.CHOICE:"Choice" // Choice in a select </li> </ul> <div class="jsDocNote"> <b>Imlementation NOTE</b> <ul> <li>DO NOT Change this values: they are used also to compose the img class e.g PopupInfo, PopupConfirm,..</li> </ul> </div> */ var POPUP_TYPE = { INFO: "Info", CONFIRM: "Confirm", ERR:"Error", ALARM:"Alarm", WARN:"Warning", QUESTION:"Question", // Question with YES NO QUESTION_3:"Question_3Btn", // Question with YES NO CANCEL PROMPT:"Prompt", // Prompt to insert one value CHOICE:"Choice" // Choice in a select }; /** * Option iPromptType for POPUP_TYPE.PROMPT <ul> <li> PROMPT_TYPE.NUMBER: "number" </li> <li> PROMPT_TYPE.STRING: "string" </li> </ul> */ var PROMPT_TYPE = { NUMBER: "number", STRING: "string" }; /** * Return value of Popup() and PopupChoice() API: POPUP_BTN indicate the Button clicked or ESC or click into x <ul> <li> POPUP_BTN.CLOSE: "CLOSE" // Close with ESC or x of Window </li> <li> POPUP_BTN.CONFIRM: "CONFIRM" // Clicked Confirm Button </li> <li> POPUP_BTN.NO: "NO" // Clicked NO Button </li> <li> POPUP_BTN.CANCEL: "CANCEL" // Clicked CANCEL Button </li> </ul> */ var POPUP_BTN = { CLOSE: "CLOSE", /* Close on x of Window */ CONFIRM: "CONFIRM", /* BTN OK (YES) */ NO: "NO", /* BTN NO */ CANCEL: "CANCEL" /* BTN CANCEL */ }; /* ==================================================================================================== * DEFAULT CONFIGURATION: see description of objOpt in Popup(szPopupType, szMsgHtml,objOpt) API ====================================================================================================*/ var POPUP_DEF_WIDTH = 600; //iWidth {Number} var POPUP_DEF_MULTICHOICE_SIZE = 5; //iChoiceMultiSize {Number} var POPUP_DEF_SHOW_IMG = true; //bShowImg {Boolean} (show/hide Image (Info, Warn,..) On the Left of Message //Default var POPUP_DEF_RESIZE = true; // bResize {Boolean} var POPUP_DEF_CLOSE_ON_ESCAPE = true; // bCloseOnEscape {Boolean} // For DEVELOPER: you can set false var POPUP_DEF_MODAL = true; // bModal {Boolean} var POPUP_DEF_POSITION = { my: "center", at: "center"}; // "center" "top" "left" "right" var POPUP_DEF_PROMPT_NUMBER_W = 50; var POPUP_DEF_PROMPT_STRING_W = 200; var POPUP_DEF_BTN_WIDTH = 120; //Width of Btn when it is not set /* ==================================================================================================== * INTERNAL CONSTANT ====================================================================================================*/ var POPUP_IMG_CLASS_PREFIX = "PopupImg"; // e.g PopupImgInfo, PopupImgConfirm,.. var POPUP_TBLMSG_CLASS_PREFIX = "PopupTblMsg"; // e.g PopupTblMsgInfo, var POPUP_TITLE_CLASS_PREFIX = "PopupTitle"; // e.g PopupTitleInfo, var POPUP_MSG_MIN_HEIGHT = 160; /* Becaase we Need space for Image and Button */ var POPUP_FS_CHOICE_MIN_WIDTH=200; // Min width to allow SelectAll DeselectAll var POPUP_DIV_EMPTY = '<div id="PopupDiv" class="Popup" style="display:none;"></div> '; // The html of the Div var POPUP_DIV_HTML = '<table id="PopupTblHea" class="PopupTitleInfo" style="display:none" width="100%" >'+ ' <tr><td id="PopupTitle" class="PopupTitle" width="100%">INFORMATION</td> </tr>'+ ' </table> '+ ' <table id="PopupTblMsg" class="PopupTblMsgInfo" style="min-height:80px;" width="100%">'+ ' <tr>'+ ' <td id="PopupImg" class="PopupImgConfirm" height="100%" width="80px">'+ ' </td>'+ ' <td>'+ ' <table class="PopupMsg">'+ ' <tr>'+ ' <td id="PopupMsg" class="PopupMsg" >'+ ' </td>'+ ' </tr>'+ ' <tr>'+ ' <!-- Section for PopupPrompt -->'+ ' <td id="PopupPromptSect" class="PopupPrompt" style="display:none">'+ ' <table>' + ' <tr>' + ' <td><label id="PopupPromptLabel" class="PopupPrompt"></label></td>'+ ' <td><input id="PopupPromptInput" class="PopupPrompt" onfocus="pp_OnFocusPromptInput();"/></td>'+ ' </tr>' + ' <tr>' + ' <td></td>' + ' <td><label id="PopupPromptError" class="PopupPromptError"/></td>'+ ' </tr>' + ' </table>' + ' </td>'+ ' </tr>'+ ' <tr>'+ ' <!-- Section for PopupChoice Single -->'+ ' <td id="PopupChoiceSingleSect" class="PopupChoiceSingle" style="display:none">'+ ' <label id="PopupChoiceSingleLabel" class="PopupChoiceSingle">Choice:</label>'+ ' <select id="PopupChoiceSingleSelect" class="PopupChoiceSingle"></select> '+ ' </td>'+ ' </tr>'+ ' <tr>'+ ' <!-- Section for PopupChoice Multi -->'+ ' <td id="PopupChoiceMultiSect" class="PopupChoiceMulti" style="display:none;text-align:center;">'+ ' <fieldset id="PopupChoiceMultiFS" class="PopupChoiceMulti">'+ ' <legend id="PopupChoiceMultiLabel" class="PopupChoiceMulti">Multi</legend>'+ ' <select id="PopupChoiceMultiSelect" class="PopupChoiceMulti" multiple=true></select>'+ ' <div style="margin-top:10px; margin-bottom:10px;">'+ ' <a id="PopupSelectAll" href="javascript:pp_SelectAll();" class="Popup">SELECT All</a>'+ ' <a id="PopupDeselectAll" href="javascript:pp_DeselectAll();" class="Popup" style="padding-left:15px;">DESELECT All</a>'+ ' </div>'+ ' </fieldset>'+ ' </td>'+ ' </tr>'+ ' <tr><td class="tipr" id="pp_f"></td></tr>' + ' </table>'+ ' </td>'+ ' </tr>'+ ' </table>'; /* ==================================================================================================== * GLOBAL VAR ====================================================================================================*/ // Current Dlg Status var jsPopup_bScroll = false; //=================================================================================== // LOCAL FUNCTION //=================================================================================== /* * MAIN Local Function. Depending on BRowser and Configuration. * * @param szPopupType {String} POPUP_TYPE.INFO, POPUP_TYPE.WARN, POPUP_TYPE.ERR, ...... * @param szMsgHtml {String} HTML TAG are Accepted (e.g <b>, <br/>,..) also /n is present is accepted as NewLine * @param [objOpt] [Object]} Optional Object with the Option - see Popup() * * @return {Object} retObj * Example: * { * retBtn {String} POPUP_BTN.CLOSE, POPUP_BTN.CONFIRM, POPUP_BTN.NO, POPUP_BTN.CANCEL * } */ function pp_Show(szPopupType,szMsgHtml,objOpt){ var fn = "[Popup.js pp_Show] "; jsu_log(fn + JSU_LOG_FUN_START); jsu_log(fn + "IN: szPopupType=" + szPopupType); jsu_logObj(fn + "IN: objOpt=" , objOpt); jsu_logHtml(fn + "IN: szMsgHtml=" , szMsgHtml); pp_Init(); // Replace /n with <BR/> // Init var iWidth = POPUP_DEF_WIDTH; var height = "auto"; // Default var bModal = POPUP_DEF_MODAL; var bResize = POPUP_DEF_RESIZE; var bShowImg = POPUP_DEF_SHOW_IMG; var bCloseOnEscape = POPUP_DEF_CLOSE_ON_ESCAPE; var position = POPUP_DEF_POSITION; var bLog = (jslogGetLogLev() > 0); if (bLog){ bResize = true; } var jqePopup = jQuery( "#PopupDiv" ); jqePopup[0].fnCallback = undefined; // DEfault var bOpt = (objOpt != undefined && objOpt != null ); var bShowBtnSect = true; //default if (bOpt){ if (objOpt.bNewlineConversion!= undefined && objOpt.bNewlineConversion){ szMsgHtml = jsu_strReplaceAll(szMsgHtml,"\n","<BR/>"); } if (objOpt.iWidth != undefined && objOpt.iWidth != null && objOpt.iWidth){ iWidth = objOpt.iWidth; } if (objOpt.iHeight != undefined && objOpt.iHeight != null){ height = objOpt.iHeight; } if (objOpt.position != undefined){ position = objOpt.position; } if (objOpt.bModal != undefined && objOpt.bModal != null){ bModal = objOpt.bModal; } if (objOpt.bResize != undefined && objOpt.bResize != null){ bResize = objOpt.bResize; } if (objOpt.bShowImg != undefined && objOpt.bShowImg != null){ bShowImg = objOpt.bShowImg; } if (objOpt.bCloseOnEscape != undefined && objOpt.bCloseOnEscape != null){ bCloseOnEscape = objOpt.bCloseOnEscape; } if (objOpt.bShowBtnSect != undefined && objOpt.bShowBtnSect != null){ bShowBtnSect = objOpt.bShowBtnSect; } if (objOpt.fnCallback != undefined){ jsu_log(fn + "fnCallback is defined"); jqePopup[0].fnCallback = objOpt.fnCallback; } } jqePopup.dialog("destroy"); // destroy previous, to make jquery recalculating Size with new one var szTitle = pp_getTitle (szPopupType,objOpt); var buttons = null; if (bShowBtnSect){ var buttons = pp_GetBtn (szPopupType,objOpt); } jsu_logObj(fn + "buttons", buttons); jqePopup.dialog({ autoOpen: false, modal: bModal, dialogClass: "PopupDialog", title: szTitle, position: position, resizable: bResize, // resize: function(event, ui) { pp_OnResize(event,ui);}, // FUTURE width: iWidth, height: height, minHeight: POPUP_MSG_MIN_HEIGHT, closeOnEscape: bCloseOnEscape, buttons: buttons, close: function( event, ui ) {pp_OnClose(event);} }); /* Set className of button */ var arIdBtn = ['#PopupConfirm','#PopupNo','#PopupCancel']; for (var i=0;i < arIdBtn.length; i++){ var elBtn = jQuery(arIdBtn[i])[0]; // Not all the Btn are always created, so we must check if elBtn si present if (elBtn){ elBtn.className = "PopupBtn"; } } // pp_ClassInit (szPopupType,jqePopup); pp_idShow ("PopupImg", bShowImg); pp_ChoiceInit (szPopupType,objOpt); // Init Section Choice pp_PromptInit (szPopupType,objOpt); // Init Section Prompt var jqeMsg = jQuery('#PopupMsg'); jqeMsg.html (szMsgHtml); jQuery( "#PopupDiv" ).dialog( "open" ); jsu_log(fn + JSU_LOG_FUN_END); } /* * Add the Popup Div to document, if it is not already presente * - Reset Div to default empty state * - Init dialog */ function pp_Init(){ var fn = "[Popup.js pp_Init] "; jsu_log(fn + JSU_LOG_FUN_START); var elPopup = document.getElementById ("PopupDiv"); if (elPopup == null){ jsu_log(fn + "'PopupDiv' NOT present - we add it to document"); jQuery('body,html').append (POPUP_DIV_EMPTY); } // Set initial Empty Layout var jqePopup = jQuery( "#PopupDiv"); jqePopup.hide(); jqePopup.html (POPUP_DIV_HTML); jqePopup.dialog({ autoOpen: false }); jsu_log(fn + JSU_LOG_FUN_END); } /* * Init Class of Layout Objects * @param szPopupType {String} in * @param jqepopup {jquery Object} */ function pp_ClassInit(szPopupType, jqePopup){ var fn = "[Popup.js pp_ClassInit] "; jsu_log(fn + JSU_LOG_FUN_START); // Get Class var szClassId = szPopupType; if (szPopupType == POPUP_TYPE.QUESTION_3){ szClassId = POPUP_TYPE.QUESTION; // Mapped to the same Class } //--------------- var szTitleClassName = POPUP_TITLE_CLASS_PREFIX + szClassId; jsu_log(fn + "set PopupTblHea className=" + szTitleClassName); jsu_getElementById2("PopupTblHea").className = szTitleClassName; // Set className of TitleBar var elTitleBar = jqePopup.siblings('.ui-dialog-titlebar')[0]; var szClassName = szTitleClassName + " " + elTitleBar.className; elTitleBar.className =szClassName; // Get the css and set to the TitleBar elTitleBar.style.backgroundColor = jQuery('#PopupTblHea').css( "background-color" ); elTitleBar.style.textAlign = "center"; elTitleBar.style.fontSize = jQuery('#PopupTblHea').css( "font-size" ); elTitleBar.style.fontWeight= jQuery('#PopupTblHea').css( "font-weight" ); elTitleBar.style.color= jQuery('#PopupTblHea').css( "color" ); //--------------- var szImgClassName = POPUP_IMG_CLASS_PREFIX + szClassId; jsu_log(fn + "set PopupImg className=" + szImgClassName); jsu_getElementById2("PopupImg").className = szImgClassName; //--------------- var szTblMsgClassName = POPUP_TBLMSG_CLASS_PREFIX + szClassId; jsu_log(fn + "set PopupTblMsg className=" + szTblMsgClassName); jsu_getElementById2("PopupTblMsg").className = szTblMsgClassName; jsu_log(fn + JSU_LOG_FUN_END); } /* * @param el * @param bShow */ function pp_idIsVisible (szId){ var fn = "[Popup.js pp_idIsVisible] "; var el = jsu_getElementById2(szId); if (el == null){ return alert (fn + "SW ERROR szId=" + szId + " NOT FOUND"); } return el.style.display != "none"; } /* * Only if bShow = false we Hide szId * @param szId * @param bShow */ function pp_idShow (szId, bShow){ var jqId = '#' + szId; var jqEl = jQuery(jqId); if (bShow){ jqEl.show(); }else{ jqEl.hide(); } } /* * Gget the Btn depending on szPopupType and objOpt if present * @param szPopupType {String} in * @param objOpt {Object} in * * @return buttons {Object} e.g: * { "OK" : { text: "OK", id: "PopupConfirm", click: function(){ pp_OnClickConfirm(); } }, "NO" : { text: "This is Custom Label", width: 200, id: "PopupNo", click: function(){pp_OnClickNo(); } }, "CANCEL" : { text: "Cancel", id: "PopupCancel", click: function(){pp_OnClickCancel(); } } } * */ function pp_GetBtn (szPopupType,objOpt){ var fn = "[Popup.js pp_BtnInit] "; jsu_log(fn + JSU_LOG_FUN_START); var bQuestion = (szPopupType == POPUP_TYPE.QUESTION || szPopupType == POPUP_TYPE.QUESTION_3); var bQuestion3 = (szPopupType == POPUP_TYPE.QUESTION_3); var bOpt = (objOpt != undefined && objOpt != null); // Default var szConfirmLabel = (bQuestion) ? POPUP_BTN_LABEL. QUESTION_CONFIRM : POPUP_BTN_LABEL. CONFIRM; var szNoLabel = POPUP_BTN_LABEL. QUESTION_NO; var szCancelLabel = POPUP_BTN_LABEL. QUESTION_CANCEL; jsu_log(fn + "Default Label: szConfirmLabel=" + szConfirmLabel + " szNoLabel=" + szNoLabel + " szCancelLabel=" + szCancelLabel); if (objOpt != null){ if (objOpt.szConfirmLabel != undefined && objOpt.szConfirmLabel != ""){ szConfirmLabel = objOpt.szConfirmLabel; } if (objOpt.szNoLabel != undefined && objOpt.szNoLabel != ""){ szNoLabel = objOpt.szNoLabel; } if (objOpt.szCancelLabel != undefined && objOpt.szCancelLabel != ""){ szCancelLabel = objOpt.szCancelLabel; } } var objBtnConfirm = { text: szConfirmLabel, id: "PopupConfirm", click: function(){ pp_OnClickConfirm(); } }; if (bOpt && objOpt.iConfirmWidth!= undefined && objOpt.iConfirmWidth!= null){ objBtnConfirm.width = objOpt.iConfirmWidth; }else { objBtnConfirm.width = POPUP_DEF_BTN_WIDTH; } //------- var objBtnNo = { text: szNoLabel, id: "PopupNo", click: function(){ pp_OnClickNo(); } }; if (bOpt && objOpt.iNoWidth!= undefined && objOpt.iNoWidth!= null){ objBtnNo.width = objOpt.iNoWidth; }else { objBtnNo.width = POPUP_DEF_BTN_WIDTH; } //------- var objBtnCancel = { text: szCancelLabel, id: "PopupCancel", click: function(){ pp_OnClickCancel(); } }; if (bOpt && objOpt.iCancelWidth!= undefined && objOpt.iCancelWidth!= null){ objBtnCancel.width = objOpt.iCancelWidth; }else { objBtnCancel.width = POPUP_DEF_BTN_WIDTH; } var buttons = new Object(); buttons.confirm = objBtnConfirm; if (szPopupType == POPUP_TYPE.QUESTION){ buttons.no = objBtnNo; }else if (szPopupType == POPUP_TYPE.QUESTION_3){ buttons.no = objBtnNo; buttons.cancel = objBtnCancel; }else if (szPopupType == POPUP_TYPE.CHOICE || szPopupType == POPUP_TYPE.PROMPT){ buttons.cancel = objBtnCancel; } jsu_log(fn + JSU_LOG_FUN_END); return buttons; } /* * Init Section of Choice * @param szPopupType {String} in * @param parIn {Object} in */ function pp_ChoiceInit(szPopupType,objOpt){ var fn = "[Popup.js pp_ChoiceInit] "; jsu_log(fn + JSU_LOG_FUN_START); pp_idShow ("PopupChoiceMultiSect", false); pp_idShow ("PopupChoiceSingle", false); if (szPopupType == POPUP_TYPE.CHOICE && objOpt != null){ jsu_log(fn + "objOpt.bChoiceMultiSel=" + objOpt.bChoiceMultiSel); szId = objOpt.bChoiceMultiSel ? "PopupChoiceMulti" : "PopupChoiceSingle"; pp_idShow (szId + "Sect", true); jsu_getElementById2(szId + "Label").innerHTML = objOpt.szChoiceLabel; // Populate selectChoice var selectChoice = jsu_getElementById2(szId + "Select"); if (objOpt.bChoiceMultiSel){ var iChoiceMultiSize = POPUP_DEF_MULTICHOICE_SIZE; if (objOpt.iChoiceMultiSize != undefined && objOpt.iChoiceMultiSize != null){ iSize = objOpt.iChoiceMultiSize; } selectChoice.size = iSize; // Label var aElSelectAll = jsu_getElementById2("PopupSelectAll"); aElSelectAll.childNodes[0].textContent = POPUP_SELECT_ALL; var aElDeselectAll = jsu_getElementById2("PopupDeselectAll"); aElDeselectAll.childNodes[0].textContent=POPUP_DESELECT_ALL; } for (var i=0; i < objOpt.arChoice.length; i++){ var objOptItem = objOpt.arChoice[i]; var elOpt = new Option(objOptItem.szText,objOptItem.value); elOpt.dv = objOptItem.szText; elOpt.selected = objOptItem.bSel; selectChoice[selectChoice.length] = elOpt; } // ------------- adjust width var elFS= jsu_getElementById2("PopupChoiceMultiFS"); var iWidth = selectChoice.clientWidth + 15; if (iWidth < POPUP_FS_CHOICE_MIN_WIDTH){ iWidth = POPUP_FS_CHOICE_MIN_WIDTH; } elFS.style.width = iWidth + "px"; jsu_log(fn + "We have SET elFS.style.width=" + elFS.style.width); } jsu_log(fn + JSU_LOG_FUN_END); } /* * Init Section of Prompt * @param szPopupType {String} in * @param parIn {Object} in */ function pp_PromptInit(szPopupType, objOpt){ var fn = "[Popup.js pp_PromptInit] "; jsu_log(fn + JSU_LOG_FUN_START); pp_idShow ("PopupPromptSect", false); if (szPopupType == POPUP_TYPE.PROMPT){ pp_idShow ("PopupPromptSect", true); if (objOpt != null){ if (objOpt.szPromptLabel && objOpt.szPromptLabel.length){ jsu_getElementById2("PopupPromptLabel").innerHTML = objOpt.szPromptLabel; } var elInput = jsu_getElementById2("PopupPromptInput"); if (objOpt.szPromptValue && objOpt.szPromptValue.length){ jsu_log(fn + "Set Default PromptValue=" + objOpt.szPromptValue); elInput.value = objOpt.szPromptValue; } szPromptType = (objOpt.szPromptType) ? objOpt.szPromptType : PROMPT_TYPE.STRING; var bNumber = (szPromptType == PROMPT_TYPE.NUMBER); elInput.setAttribute ("type",szPromptType); var iMin=null, iMax=null; var bMin=false, bMax=false; if (objOpt.iPromptWidth && !isNaN(objOpt.iPromptWidth)){ elInput.setAttribute ("style","width:" + objOpt.iPromptWidth + "px;"); }else { elInput.setAttribute ("style","width:" + (bNumber ? POPUP_DEF_PROMPT_NUMBER_W : POPUP_DEF_PROMPT_STRING_W )+ "px;"); } if (objOpt.iPromptMax && !isNaN(objOpt.iPromptMax)){ bMax = true; iPromptMax=objOpt.iPromptMax; elInput.setAttribute ("max",iPromptMax); if (!bNumber){ elInput.setAttribute ("maxlength",iPromptMax); } } else { elInput.removeAttribute ("max"); elInput.removeAttribute ("maxlength"); } if (objOpt.iPromptMin && !isNaN(objOpt.iPromptMin)){ bMin = true; iPromptMin=objOpt.iPromptMin; elInput.setAttribute ("min",iPromptMin); }else{ elInput.removeAttribute ("min"); } elInput.focus(); // ------------ Tip var szTitle = (bNumber) ? POPUP_PROMPT_TIP.NUMBER : POPUP_PROMPT_TIP.STRING; if (bMin || bMax) { szTitle = (bNumber) ? POPUP_PROMPT_TIP.NUMBER_RANGE : POPUP_PROMPT_TIP.STRING_RANGE; if (bMin && bMax){ szTitle += "[" + iPromptMin + ".." + iPromptMax + "]"; }else if (bMax){ szTitle += "[" + 0 + ".." + iPromptMax + "]"; }else if (bMin){ szTitle += "[" + iPromptMin + "..]"; } } elInput.setAttribute ("title",szTitle); } } jsu_log(fn + JSU_LOG_FUN_END); } /* * Uses canvas.measureText to compute and return the width of the given text of given font in pixels. * * @param {String} text The text to be rendered. * @param {String} font The css font descriptor that text is to be rendered with (e.g. "bold 14px verdana"). * * @see http://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/21015393#21015393 */ function getTextWidth(text, font) { // re-use canvas object for better performance var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas")); if (canvas == undefined || canvas.getContext == undefined){ return 0; } var context = canvas.getContext("2d"); context.font = font; var metrics = context.measureText(text); return metrics.width; }; /*==================================================================== ====================================================================*/ /* * @param objOpt {Object} * @return szTitle to Use */ function pp_getTitle(szPopupType,objOpt){ var szTitle = (objOpt) ? objOpt.szTitle: null; if (typeof(szTitle) == undefined || szTitle == null || szTitle == ""){ if (szPopupType == POPUP_TYPE.INFO){ return POPUP_DEF_TITLE.INFO; }else if (szPopupType == POPUP_TYPE.WARN){ return POPUP_DEF_TITLE.WARN; }else if (szPopupType == POPUP_TYPE.ERR){ return POPUP_DEF_TITLE.ERR; }else if (szPopupType == POPUP_TYPE.ALARM){ return POPUP_DEF_TITLE.ALARM; }else if (szPopupType == POPUP_TYPE.CONFIRM){ return POPUP_DEF_TITLE.CONFIRM; }else if (szPopupType == POPUP_TYPE.PROMPT){ return POPUP_DEF_TITLE.PROMPT; }else if (szPopupType == POPUP_TYPE.CHOICE){ return POPUP_DEF_TITLE.CHOICE; }else if (szPopupType == POPUP_TYPE.QUESTION || szPopupType == POPUP_TYPE.QUESTION_3){ return POPUP_DEF_TITLE.QUESTION; } }else { return szTitle; } } /* * @param elInput * @return 0 if OK 1 if ERR */ function pp_ValidateInput(elInput){ var fn = "[Popup.js pp_ValidateInput] "; jsu_log(fn + JSU_LOG_FUN_START); var promptValue = elInput.value; jsu_log(fn + "Prompt=" + promptValue); // Is required Validation? var szType = elInput.getAttribute ("type"); var bNumber = (szType == PROMPT_TYPE.NUMBER); var iLen= (promptValue) ? promptValue.length :0; var iMin = parseInt(elInput.getAttribute ("min")); var iMax = parseInt(elInput.getAttribute ("max")); if (isNaN(iMin)){ iMin = null;} if (isNaN(iMax)){ iMax = null;} if (bNumber){ promptValue = parseInt (promptValue); } var bErr = false; if (bNumber){ jsu_log(fn + "VALIDATION is required for PROMPT NUMBER - We check that promptValue=" + promptValue + " is a NUMBER"); bErr = (isNaN(promptValue)); } if (!bErr && iMin){ jsu_log(fn + "VALIDATION required for iMin=" + iMin + " - PROMPT szType=" + szType); if (bNumber && iMin > promptValue){ bErr = true;} if (!bNumber && iMin > iLen){ bErr = true;} } if (!bErr && iMax){ jsu_log(fn + "VALIDATION required for iMax=" + iMax + " - PROMPT szType=" + szType); if (bNumber && iMax < promptValue){ bErr = true;} if (!bNumber && iMax < iLen){ bErr = true;} } if (bErr){ // Show the Error Element var szTitle = elInput.getAttribute ("title"); jsu_log(fn + "VALIDATION ERROR for promptValue=" + promptValue + " Show Err: " + szTitle); var elErr = jsu_getElementById2("PopupPromptError"); elErr.innerHTML = szTitle; elementShow(elErr,true,"inline"); // elInput.setAttribute ("class","PopupPromptError"); // Change class to show alarm gif return 1; } return jsu_log(fn + JSU_LOG_FUN_END); } /* * Intercept Close to manage ESC or x * * @param event */ function pp_OnClose(event){ var fn = "[Popup.js pp_OnClose] "; jsu_log(fn + JSU_LOG_FUN_START); if(event.originalEvent ){ jsu_log(fn + "Clicking on dialog box X or ESC"); // triggered by clicking on dialog box X or pressing ESC pp_Close ({retBtn : POPUP_BTN.CLOSE}); } jsu_log(fn + JSU_LOG_FUN_END); } /* * - validate (if POPUP_TYPE.PROMPT) * - Close Dlg and return retObj * @param retObj { * retBtn {Number or Object} in Example: {Number} JTPOPUP_BTN.CONFIRM, POPUP_BTN.NO, POPUP_BTN.CANCEL or whetever Custom NUmber * Example: {Object} Custom Object * ....... * } * */ function pp_Close(retObj){ var fn = "[Popup.js pp_Close] "; jsu_log(fn + JSU_LOG_FUN_START); // true if clicked on OK Button var bConfirm = (retObj && retObj.retBtn == POPUP_BTN.CONFIRM); jsu_log(fn + "bConfirm=" + bConfirm ); if (bConfirm){ // -------------- Check if Prompt is Visible var bPrompt = pp_idIsVisible("PopupPromptSect"); if (bPrompt){ var elInput = jsu_getElementById2("PopupPromptInput"); if (pp_ValidateInput (elInput)){ return; } retObj.promptValue = elInput.value; } // -------------- Check if Choice is Visible var bChoiceSingle = pp_idIsVisible("PopupChoiceSingleSect"); var bChoiceMulti = pp_idIsVisible("PopupChoiceMultiSect"); if (bChoiceSingle || bChoiceMulti){ jsu_log(fn + "Get Choice Selection"); var szEl = (bChoiceSingle) ? "PopupChoiceSingleSelect" : "PopupChoiceMultiSelect"; var selectChoice = jsu_getElementById2(szEl); // Read All and prepare arChoice var arChoice = new Array(); var szChoiceValue = ""; var szChoiceText= ""; var szSep = ""; for (var iOpt=0; iOpt < selectChoice.options.length; iOpt ++){ var Opt = selectChoice.options[iOpt]; var arItem = { value: Opt.value, szText: Opt.text, bSel: Opt.selected }; if (Opt.selected){ szChoiceValue += (szSep + Opt.value); szChoiceText += (szSep + Opt.text); if (szSep == ""){ szSep = ", "; } } arChoice.push(arItem); } retObj.choiceValue = szChoiceValue; retObj.choiceText = szChoiceText; retObj.arChoice = arChoice; } } jsu_logObj(fn + "retObj", retObj); var jqePopup = jQuery("#PopupDiv" ); jsu_log(fn + "close and destroy Dialog"); var fnCallback = jqePopup[0].fnCallback; jqePopup.dialog("destroy"); if (typeof (UnTip) == "function"){ UnTip(); /// if there is any Tip in the Dialog we UnTip it (to avoid the risk of leave it open) } if (fnCallback != undefined){ jsu_log(fn + "call fncallback"); fnCallback (retObj); } jsu_log(fn + JSU_LOG_FUN_END); } /*==================================================================== EVENT FROM Popup Dlg ====================================================================*/ /* * Focus on 'PromptPromptInput' Element * Set standard Class to remove Validation Class Error if present */ function pp_OnFocusPromptInput(){ var elInput = jsu_getElementById2("PopupPromptInput"); elInput.setAttribute('class','PopupPromptInput'); var elErr = jsu_getElementById2("PopupPromptError"); elementShow (elErr,false); } /* * Called at click on Button OK or YES * - Close Dlg and return retObj.bOk = true */ function pp_OnClickConfirm(){ var fn = "[Popup.js pp_OnClickConfirm] "; pp_Close ({retBtn : POPUP_BTN.CONFIRM}); } /* * Deselect All Items in PopupChoiceMultiSelect */ function pp_DeselectAll(){ var selectChoice = jsu_getElementById2("PopupChoiceMultiSelect"); for (var iOpt=0; iOpt < selectChoice.options.length; iOpt ++){ selectChoice.options[iOpt].selected = false; } } /* * For JSU FREE Protection * * @param objId {id, acr, min, max} */ function pp_getId(objId){ objId[0] = 1000 + objId[1] + (objId[2] + Math.floor(Math.random() * objId[3])); // id random } /* * Select All Items in PopupChoiceMultiSelect */ function pp_SelectAll(){ var selectChoice = jsu_getElementById2("PopupChoiceMultiSelect"); for (var iOpt=0; iOpt < selectChoice.options.length; iOpt ++){ selectChoice.options[iOpt].selected = true; } } /* * Called at click on Button No or NO * - Close Dlg and return retObj.bConfirm = false */ function pp_OnClickNo(){ var fn = "[Popup.js pp_OnClickNo] "; pp_Close ({retBtn : POPUP_BTN.NO}); } /* * Called at click on Button3 * - Close Dlg and return retObj.bConfirm = false */ function pp_OnClickCancel(){ var fn = "[Popup.js pp_OnClickNo] "; pp_Close ({retBtn :POPUP_BTN.CANCEL}); } /* * FUTURE */ function pp_OnResize(event, ui){ var fn = "[Popup.js pp_onResize] "; try{ var jqeMsg = jQuery('#PopupMsg'); jsu_log (fn ); var w1 = jqeMsg.dialog( "option", "width" ); var w = jqeMsg[0].offsetWidth; var h = jqeMsg[0].offsetHeight; if (w != undefined && h != undefined){ jsu_log (fn + "Window size: width=" + w + ", height=" + h); } }catch (e) { jsu_log (fn + "EXCEPTION " + e.message); } } /*================================================================================================== GLOBAL API ==================================================================================================*/ /** * Show the Popup * @param szPopupType {String} POPUP_TYPE.INFO, POPUP_TYPE.WARN, .. &nbsp;see <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/JQPopup.js/global.html#POPUP_TYPE" target="_self">POPUP_TYPE</a> * * @param szMsgHtml {String} HTML TAG are Accepted. Newline if present is converted to HTML Newline (default); no conversion if bNewlineConversion=false * @param [objOpt] {Object} <table class="jsDoc" border="2" cellpadding="2" cellspacing="2" width="100%"> <tr><td class="jsDocTitle">OPTIONS</td></tr> <tr><td class="jsDocParam"> <ul> <li> szTitle: {String} change default Title </li> <li> fnCallback: {function} callback function, called when Popup is closed </li> <li> position: {Object} jQuery ui position. Default {my: "center", at: "center"} Example: {at: "top"} </li> <li> iWidth: {Number} Optional PopupWidth: if it passed it is used<BR/> Else Default is used </li> <li> iHeight: {Number} Optional PopupHeight: if it passed it is Set<BR/> Else is automarically calculated </li> <li> szConfirmLabel: {String} Label of Confirm Button </li> <li> iConfirmWidth: {Number} Width of Confirm Button </li> <li> szConfirmLabel: {String} Label of Confirm Button </li> <li> iConfirmWidth: {Number} Width of Confirm Button </li> <li> szCancelLabel: {String} Label of Cancel Button </li> <li> iCancelWidth: {Number} Width of Cancel Button </li> <li> szNoLabel: {String} Label of No Button </li> <li> iNoWidth: {Number} Width of No Button </li> <li> bShowImg: {Boolean} true to show Image (Default=true) </li> <li> bShowBtnSect: {Boolean} [true] false to hide all the Button Section (used in embedded HTML pages) </li> <li> bResize: {Boolean} true to allow Resize Dialog (Default=true) </li> <li> bModal: {Boolean} true=modal (default) </li> <li> bCloseOnEscape: {Boolean} Default true </li> <li> bNewlineConversion: {Boolean} Default true. if true Newline if present is converted to HTML Newline </li> <li> <b>ONLY For POPUP_TYPE.CHOICE</b>: <ul> <li> bChoiceMultiSel: {Boolean} true if MultiSelect,else single select. Default false </li> <li> iChoiceMultiSize: {Number} if bChoiceMultiSel=true: size (Num item) to display without Scrollbar </li> </ul> </li> <li> <b>ONLY For POPUP_TYPE.PROMPT</b>: <ul> <li> szPromptType: {String} [PROMPT_TYPE.STRING] PROMPT_TYPE.NUMBER PROMPT_TYPE.STRING &nbsp;see <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/JQPopup.js/global.html#PROMPT_TYPE" target="_self">PROMPT_TYPE</a> </li> <li> szPromptLabel: {String} Label in Front of Prompt </li> <li> szPromptValue: {String} Default Value to set </li> <li> iPromptWidth: {Number} Width (px) of the Prompt Item </li> <li> iPromptMin: {Number} Min (MinValue for PROMPT_TYPE.NUMBER, MinLen for PROMPT_TYPE.STRING) </li> <li> iPromptMax: {Number} Max (MaxValue for PROMPT_TYPE.NUMBER, MaxLen for PROMPT_TYPE.STRING) </li> </ul> </li> </ul> </td></tr> </table> * * @return {Object} retObj <BR/> Example: <ul> * { <BR/> * <li> retBtn {String} POPUP_BTN.CLOSE, POPUP_BTN.CONFIRM, POPUP_BTN.NO, POPUP_BTN.CANCEL &nbsp;see <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/JQPopup.js/global.html#POPUP_BTN" target="_self">POPUP_BTN</a> </li> <li> <b>ONLY For POPUP_TYPE.CHOICE</b>: <ul> * <li> choiceSelValue Value chosen in selectChoice (valueSel1, valueSel2, .. for MultiSel)</li> * <li> choiceSelText Text chosen in selectChoice (textSel1, textSel2,.. for MultiSel) </li> * <li> choiceSelText Text chosen in selectChoice (textSel1, textSel2,.. for MultiSel) </li> * <li> arChoice like input with the bSel=true/false depending on selected state </li> * </ul> * </li> * } <BR/> * </ul> * */ function Popup(szPopupType, szMsgHtml,objOpt){ return pp_Show (szPopupType,szMsgHtml,objOpt); } /** * Show a Popup for Choice with Default Btn: POPUP_BTN.CONFIRM, POPUP_BTN.CANCEL * * @param szMsgHtml {String} HTML TAG are Accepted - Newline if present is converted to HTML Newline * @param szChoiceLabel {String} Label of the selectChoice * @param arChoice {Array} Array to populate the selectChoice: Example <BR/> * [{value:1,szText:"1 - Not Good",bSel:false}, <BR/> * {value:2,szText:"2 - Good",bSel:false}, <BR/> * {value:3,szText:"3 - Very Good",bSel:true}] <BR/> * @param [objOpt] {Object} OPTIONS * &nbsp;see <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/JQPopup.js/global.html#Popup" target="_self">Popup()</a> * @return {Object} retObj <BR/> Example: <ul> * { <BR/> * <li> retBtn {String} POPUP_BTN.CLOSE, POPUP_BTN.CONFIRM, POPUP_BTN.NO, POPUP_BTN.CANCEL &nbsp;see <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/JQPopup.js/global.html#POPUP_BTN" target="_self">POPUP_BTN</a> </li> <li> <b>ONLY For POPUP_TYPE.CHOICE</b>: <ul> * <li> choiceSelValue Value chosen in selectChoice (valueSel1, valueSel2, .. for MultiSel)</li> * <li> choiceSelText Text chosen in selectChoice (textSel1, textSel2,.. for MultiSel) </li> * <li> choiceSelText Text chosen in selectChoice (textSel1, textSel2,.. for MultiSel) </li> * <li> arChoice like input with the bSel=true/false depending on selected state </li> * </ul> * </li> * } <BR/> * </ul> * */ function PopupChoice(szMsgHtml,szChoiceLabel,arChoice,objOpt){ if (objOpt == undefined || objOpt == null){ objOpt = new Array(); } // Create the Option for Choice and push it into objOpt objOpt.szChoiceLabel = szChoiceLabel; objOpt.arChoice = arChoice; return pp_Show (POPUP_TYPE.CHOICE,szMsgHtml,objOpt); } /** * Return false to indicate to JSU User that this Popup.js Interface is NOT the IEPopup (that works only in IE) <BR/> * The same function is Present in JQPopup/Popup.js where it return true <BR/> * This API is used if the html does not know what popup.js interface is loaded by require.js configuration file, where it can be changed because <BR/> * both IEPopup/Popup.js and JQPopup/Popup.js share the same interface * * @returns {Boolean} false to indicate that This popup.js interfaca is not the IEPopup/popup.js */ function isIEPopup(){ return false; } <file_sep>/core/tooltip.js /** @fileOverview ========================================================================================= <BR/> <b>File:</b> core/tooltip.js <BR/> <b>Author:</b> <a href="https://www.linkedin.com/in/federicolevis" target="_self"><NAME></a> <BR/> <b>Tip Doc:</b> <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/HTML/Tooltip.html" target="_self">JSU Tip Documentation</a> <BR/> <b>JSU API Doc:</b> <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/JSUAPI.html" target="_self">JSU API Documentation</a> <BR/> <b>Description:</b> JSU Tip API: Tip* UnTip* <BR/> <b>REQUIRED:</b> JSU: jsu.css locale-core.js jsuCmn.js <BR/> <b>OPTIONAL:</b> JSU: prettify: prettify-jsu.js prettify-jsu.css if you want show JS Hightlighted <BR/> <b>OPTIONAL:</b> JSU: jslog.js dom-drag.js if you want to use jslog <BR/> <b>First Version:</b> ver 1.0 - Feb 2014 <BR/> <b>Current Version:</b> JSU v. 1.10 &nbsp;&nbsp;&nbsp;2018-Jan-14 <BR/> <BR/>-----------------------------------------------------------------------------------<BR/> <b>DISCLAIMER</b> <BR/> Copyright by <NAME> - <a href="https://github.com/FedericoLevis/JSU" target="_self">JSU</a> <BR/> This file may be freely distributed under the MIT license. <BR/> ========================================================================================= <BR/> */ /*========================================================================================= * GLOBAl CONST ========================================================================================= */ /** * Optional TipType */ var TIP_TYPE={ Floating: "Floating", // Floating Fixed: "Fixed", // Fixed NONE: "NONE" // NO Tip diaplayed }; /** * Optional TipFixPos */ var TIP_FIXED_POS={ LEFT:"left", // left of the Clicked Object CENTER: "center", // center of the Clicked Object (default) RIGHT: "right" // right of the Clicked Object }; var TIP_DEF_CLOSE_BTN = true; // default: Close Btn present for FIXED Tip var TIP_DEF_WIDTH = 800; // default var TIP_DEF_COL_NUM = 100; // default: 100 col for TextArea var TIP_DEF_ROW_NUM = 20; // default: 25 rows for TextArea var TIP_DEF_MAXH_MCODE = 400; //for MultiCode var TIP_DEF_MCODE_TITLE = "Code"; var TIP_DEF_TEXTBOX_TITLE = "Source Code"; var TIP_MAX_TEXT_BOX_ROW_NUM = 20; // if more there will be scrollbar var TIP_KEYCODE_ESC = 27; var TIP_Z_INDEX= 10000; // Very Hight value to be sure to overwrite whatever window /*========================================================================================= * CONFIG CONST ========================================================================================= */ /** * Default Config of Floating Tip */ var TIP_CFG_FLOATING={ FollowMouse: true, //false or true - tooltip follows the mouse DelayMs: 400, // Time span in ms until tooltip shows up FadeMs: 100, CenterMouse: false, // false or true - center the tip horizontally BorderStyle: 'dotted', // Any permitted CSS value, but I recommend 'solid', 'dotted' or 'dashed' BorderWidth: 2, CloseBtn: false, // false or true - closebutton in titlebar JumpHorz: true, // false or true - jump Horizontal if required JumpVert: true, // false or true - jump vertically if required Title: '', // Default title text applied to all tips (no default title: empty string '') Fix: null,// Fixated position, two modes. Mode 1: x- an y-coordinates in brackets, e.g. [210, 480]. Mode 2: Show tooltip at a position related to an HTML element: [ID of HTML element, x-offset, y-offset from HTML element], e.g. ['SomeID', 10, 30]. Value null (default) for no fixated positioning. OffsetY: 20 // Offset relative to Mouse position }; /** * Default Config of Fixed Tip */ var TIP_CFG_FIXED={ FollowMouse: false, //Must be false DelayMs: 0, // Time span in ms until tooltip shows up FadeMs: 0, CenterMouse: true, // false or true - center the tip horizontally BorderStyle: 'dashed', // Any permitted CSS value, but I recommend 'solid', 'dotted' or 'dashed' BorderWidth: 3, CloseBtn: true, // false or true - closebutton in titlebar JumpHorz: false, // false or true - jump Horizontal if required JumpVert: false, // Always false: we want the tip always below Title: '', // Default title text applied to all tips (no default title: empty string '') Fix: null, // it will be set run-time: e.g ['tipSortFeature',0,20] OffsetY: 0 // it is set run-time using other variables. Tis on eis not considered }; //Global For TipFix (see TipFix() objPar) var tt_tipFix = { objClass : { // Classes to use for Up/Down Down : undefined, Up : undefined }, yIncDelta: 0, // can be used for particualar case to inc DeltaOffset tipImg : undefined // the tipImg where the user has click to show tipFix (can also be undefined) }; /*========================================================================================= * LOCAL CONST ========================================================================================= */ // ------------------------------ Fixed Up/Down classes. See core.css. To add new class, add similar code referring to another existing class // TOGGLE IMAGES. If the immage is not in these class, NO TOGGLE is done var tt_arToggleClass = [ { Down: "tipFix", Up: "tipFixUp"}, { Down: "tipFixArrow", Up: "tipFixArrowUp"}, { Down: "googleAnalList", Up: "googleAnalListUp"}, { Down: "tipFixJS", Up: "tipFixJSUp"}, { Down: "tipFixCode", Up: "tipFixCodeUp"}, { Down: "jsuOpt", Up: "jsuOptUp"} ]; var APP_NAME_FIREFOX="Netscape"; // FIREFOX var APP_NAME_IE="Microsoft Internet Explorer"; // IE var APP_NAME_IE_11="Netscape"; // IE 11 var config = new Object(); var tip_img_fixed = null; // Current tip Img Fixed var TT_X_MIN = 10; var TT_ABOVE_DELTA_Y = 10; // DElta Y added when Tip Above, for particular cases //=================== GLOBAL TOOLTIP CONFIGURATION =========================// var tt_init_done=false; var tip_type = TIP_TYPE.NONE; // Current Tip displayed var tt_Enabled = true; // Allows to (temporarily) suppress tooltips, e.g. by providing the user with a button that sets this global variable to false var TagsToTip = true; // false or true - if true, HTML elements to be converted to tooltips via TagToTip() are automatically hidden; // if false, you should hide those HTML elements yourself // For each of the following config variables there exists a command, which is // just the variablename in uppercase, to be passed to Tip() or TagToTip() to // configure tooltips individually. Individual commands override global // configuration. Order of commands is arbitrary. // Example: onmouseover="Tip('Tooltip text', LEFT, true, BGCOLOR, '#FF9900', FADEIN, 400)" config. Padding = 10; // NB: Spacing between border and content config. Delay = TIP_CFG_FLOATING.DelayMs; // Time span in ms until tooltip shows up config. Above = false; // false or true - tooltip above mousepointer config. BgColor = '#FFFFCC'; // NB: TIP BACK COLOR Background color (HTML colour value, in quotes) Yellow config. BgImg = ''; // Path to background image, none if empty string '' // Black Border config. BorderColor = '#000000'; config. BorderStyle = TIP_CFG_FLOATING.BorderStyle; config. BorderWidth = TIP_CFG_FLOATING.BorderWidth; // NB: Border 1 or 2 for example config. CenterMouse = TIP_CFG_FLOATING.CenterMouse; // false or true - center the tip horizontally below (or above) the mousepointer config. ClickClose = false; // false or true - close tooltip if the user clicks somewhere config. ClickSticky = false; // false or true - make tooltip sticky if user left-clicks on the hovered element while the tooltip is active config. CloseBtn = TIP_CFG_FLOATING.CloseBtn; // false or true - closebutton in titlebar config. CloseBtnColors = [' ', '#FFFFFF','#FF5858' , '#FFFFFF']; // [Background, text, hovered background, hovered text] - use empty strings '' to inherit title colours // config. CloseBtnColors = ['#E5E4E4', '#000000','#BFBEBE' , '#000000']; // [Background, text, hovered background, hovered text] - use empty strings '' to inherit title colours config. CloseBtnText = '&nbsp;X&nbsp;'; // Close button text (may also be an image tag) config. CopyContent = true; // When converting a HTML element to a tooltip, copy only the element's content, rather than converting the element by its own config. Duration = 0; // Time span in ms after which the tooltip disappears; 0 for infinite duration, < 0 for delay in ms _after_ the onmouseout until the tooltip disappears config. Exclusive = false; // false or true - no other tooltip can appear until the current one has actively been closed config. FadeIn = TIP_CFG_FLOATING.FadeMs; // Fade-in duration in ms, e.g. 400; 0 for no animation config. FadeOut = TIP_CFG_FLOATING.FadeMs; config. FadeInterval = 30; // Duration of each fade step in ms (recommended: 30) - shorter is smoother but causes more CPU-load config. Fix = TIP_CFG_FLOATING.Fix; // Fixated position, two modes. Mode 1: x- an y-coordinates in brackets, e.g. [210, 480]. Mode 2: Show tooltip at a position related to an HTML element: [ID of HTML element, x-offset, y-offset from HTML element], e.g. ['SomeID', 10, 30]. Value null (default) for no fixated positioning. config. FollowMouse = TIP_CFG_FLOATING.FollowMouse; // false or true - tooltip follows the mouse // --------------------- Default Font (used also for Footer) config. FontColor = '#000000'; config. FontFace = 'Verdana'; config. FontSize = '8pt'; // E.g. '9pt' or '12px' - unit is mandatory config. FontWeight = 'normal'; // 'normal' or 'bold'; // config. Height = 0; // Tooltip height; 0 for automatic adaption to tooltip content, < 0 (e.g. -100) for a maximum for automatic adaption config. JumpHorz = TIP_CFG_FLOATING.JumpHorz; // false or true - jump horizontally to other side of mouse if tooltip would extend past clientarea boundary config. JumpVert = TIP_CFG_FLOATING.JumpVert; config. Left = false; // false or true - tooltip on the left of the mouse config. OffsetX = 14; // Horizontal offset of left-top corner from mousepointer config. OffsetY = TIP_CFG_FLOATING.OffsetY; // Vertical offset config. Opacity = 100; // Integer between 0 and 100 - opacity of tooltip in percent config. Shadow = true; // false or true config. ShadowColor = '#C0C0C0'; config. ShadowWidth = 10; config. Sticky = false; // false or true - fixate tip, ie. don't follow the mouse and don't hide on mouseout config. TextAlign = 'left'; // 'left', 'right' or 'justify' //-------------------------------------------------- TITLE config. Title = TIP_CFG_FLOATING.Title; // Default title text applied to all tips (no default title: empty string '') config. TitleAlign = 'center'; // 'left' 'center' or 'right' - text alignment inside the title bar config. TitleBgColor = '#000000'; // backgroundColor of the Title section . If empty string '', BorderColor will be used config. TitleFontColor = '#ffffff'; // Color of title text - if '', BgColor (of tooltip body) will be used config. TitleFontFace = 'bold'; // If '' use FontFace (boldified) config. TitleFontSize = '12pt'; // If '' use FontSize config. TitlePadding = 1; config. Footer = ''; // Default Footer text applied to all tips (no default title: empty string '') config. Width = 0; // Tooltip width; 0 for automatic adaption to tooltip content; < -1 (e.g. -240) for a maximum width for that automatic adaption; // -1: tooltip width confined to the width required for the titlebar //======= END OF TOOLTIP CONFIG, DO NOT CHANGE ANYTHING BELOW ==============// var tt_aElt = new Array(10), // Container DIV, outer title & body DIVs, inner title & body TDs, closebutton SPAN, shadow DIVs, and IFRAME to cover windowed elements in IE tt_aV = new Array(), // Caches and enumerates config data for currently active tooltip tt_sContent, // Inner tooltip text or HTML tt_t2t, tt_t2tDad, // Tag converted to tip, and its DOM parent element tt_musX, tt_musY, tt_over, tt_x, tt_y, tt_w, tt_h; // Position, width and height of currently displayed tooltip //===================== PUBLIC =============================================// /** * GLOBAL USE: Display a FloatingTip. Called by User only with tipType = TIP_TYPE.Floating to disaplay a Floating Tip<BR/> * Call Untip() to Hide the tooltip <BR/> * NOTE: it is also used internally with other tipType * * @param tipMsgHtml {String} HTML Message to display in the Tip. It can containts whatver HTML TAG (also to display Img, Gig, Video,...) * @param [tipType] {String} [TIP_TYPE.Floating] when called by User * @param [objOpt] Option: <BR/> - bNL2BR: {Boolean} Default true. if true Newline if present is converted to HTML Newline </li> * - bNL2BR [true] if true convert NewLine to <BR/> * * GLOBAL * Set tip_type = tipType */ function Tip(tipMsgHtml,tipType,objOpt) { var fn = "[tooltip.js Tip()] "; jsu_log ( fn + JSU_LOG_FUN_START); tt_init(); // init, if not already done if (tip_type == TIP_TYPE.Fixed){ return jsu_log ( fn + "Nothing to do: a TipFix is currently diaplyed" + JSU_LOG_FUN_END); } if (objOpt == undefined){ var objOpt = {bNL2BR: true}; } if (objOpt.bNL2BR == undefined || objOpt.bNL2BR){ tipMsgHtml = tt_NL2BR (tipMsgHtml); // Replace /n with <BR/>,... } var bShow = true; if (tipType == undefined){ tipType = TIP_TYPE.Floating; } tip_type = tipType; jsu_log (fn + "SET tip_type=" + tip_type); //---------- set config Option var objCfg = (tip_type == TIP_TYPE.Fixed) ? TIP_CFG_FIXED : TIP_CFG_FLOATING; tt_SetCfg (objCfg); //--------------------- tt_showTip(tipMsgHtml); tip_type = tipType; // workaround. we have to set again this global var because tt_Hide has resetted it jsu_log ( fn + JSU_LOG_FUN_END); } /** * @param tipMsgHtml {String} HTML Message to display in the Tip. It can containts whatver HTML TAG (also to display Img, Gig, Video,...) * @param [event] {Object} Usually pass the event of the onclick. if null you have to pass pass objOpt.szRefElId * @param [objOpt] {Object} <table class="jsDoc" border="2" cellpadding="2" cellspacing="2"> <tr><td class="jsDocTitle">OPTIONS</td></tr> <tr><td class="jsDocParam"> <ul> <li> szTitle{String} default: '' </li> <li> bCloseBtn {Boolean} default: true(if true show a Close Button on the Bottom) </li> <li> iTipMaxHeight {Number}: [0] Max Height of the Tip (Scroll will be used if required). If 0 the height is automatically calculated to show all the Tip... Default =0 NO SCROLL </li> <li> iTipWidth {Number}: [undefined] TipWidth - do not pass it to automatically set it basing on content. </li> <li> tipFixedPos: TipPosition using TIP_FIXED_POS possible values (TIP_FIXED_POS.CENTER,...) n (e.g -100) default=TIP_FIXED_POS.CENTER </li> <li> bNL2BR= [true] if true /n are converted to </li> ------ <b>FOLLOW FIELDS are for ADVANCED use. Usually they are ever used </b> <li> bNL2BR: {Boolean} Default true. if true Newline if present is converted to HTML Newline </li> <li> objClass: {Object} {Down: {String}, Up: {String}} 2 Classes that identify The 2 states <BR/> To be used when you have 2 classes not that are not already defined into the TIP_TOGGLE_CLASS_xxx constants of this file <BR/> e.g. objClass: {Down: 'downloadFree', Up: 'downloadFreeUp'} </li> <li>szRefElId: Id of the Reference ElementImage. It can be used instead of event, to display the Tip below this szRefEl </li> </ul> </td></tr> </table> <div class="jsDocNote"> <b>Implementation NOTES:</b> <ul> <li>GLOBAL VAR: tt_tipFix </li> <li>All the other tiFixXXX call this funcion</li> </ul> </div> */ function TipFix(tipMsgHtml,event, objOpt) { var fn = "[tooltip.js TipFix] "; jsu_log ( fn + JSU_LOG_FUN_START); jsu_logObj (fn + "IN objOpt", objOpt); tt_init(); // init, if not already done if (objOpt == undefined){ var objOpt = {bNL2BR: true}; } if (objOpt.bNL2BR == undefined || objOpt.bNL2BR){ tipMsgHtml = tt_NL2BR (tipMsgHtml); // Replace /n with <BR/>,... } if (objOpt.bCloseBtn == undefined){ objOpt.bCloseBtn = TIP_DEF_CLOSE_BTN; } // set this global var, to be used when they are not undefined tt_tipFix.objClass = objOpt.objClass; tt_tipFix.yIncDelta = 0; // default var szTitle = ""; // -- Option if (objOpt){ if (objOpt.szTitle){ szTitle = objOpt.szTitle; } var szMaxHeight = "", szMaxWidth = ""; var bDivScroll = false; if (objOpt.iTipMaxHeight){ szMaxHeight = 'max-height: ' +objOpt.iTipMaxHeight + 'px;'; bDivScroll = true; } if (objOpt.iTipWidth == undefined ){ // in this case we set only max-width but we do not set width: so it is automatically set basing on content szMaxWidth = 'max-width: ' +TIP_DEF_WIDTH+ 'px;'; }else { // only if explicitly required, we se also width szMaxWidth = 'max-width: ' +objOpt.iTipWidth+ 'px; width:' +objOpt.iTipWidth + 'px;'; } bDivScroll = true; var szDivHTML = ""; /* if (!bDivScroll){ szMaxWidth = 'max-width: ' + tt_w + 'px;'; } */ jsu_log ( fn + "SET style='" + szMaxHeight + szMaxWidth + "'"); // Add Div for scroll // e.g "<div style='max-height: 200px;overflow: auto;'>" tipMsgHtml = '<div id="divTipContainer" align="center" style="' + szMaxHeight + szMaxWidth + ' border: 1px solid;background-color: white; overflow: auto; ">' + tipMsgHtml + '</div>'; // -- Optional Close Button if (objOpt.bCloseBtn != undefined && objOpt.bCloseBtn){ // szTip += '<table class="tipNoBorder" width="100%"><tr><td><input type="button" value="Close" onclick="UnTip(event)" /> </td></tr></table>'; tipMsgHtml += '<BR/><div id="divTipMain" align="center" width="100%"><input type="button" class="tipBtnClose" value="' + TIP_BTN_CLOSE + '" title="' + TIP_BTN_CLOSE_TITLE + '" onclick="UnTipFix()" /> </div>'; } } TIP_CFG_FIXED.Title = szTitle; var bOpenTip = true; // see if the TipFix is already disalyed. In this case we Close it because the user has click again t close it var tipFixedPos = TIP_FIXED_POS.CENTER; // default if (objOpt != undefined && objOpt.tipFixedPos != undefined){ tipFixedPos = objOpt.tipFixedPos; } jsu_log ( fn + "IN: tipFixedPos=" + tipFixedPos); var tipImg = null; if (objOpt.szRefElId != undefined){ tipImg = document.getElementById (objOpt.szRefElId); if (tipImg.bTipFixOpen == undefined || tipImg.bTipFixOpen== false){ jsu_log ( fn + "OPEN TipFix Over szRefElId=" + objOpt.szRefElId); tipImg.bTipFixOpen = true; // New properties used to identify the Tip Status tt_tipFix.yIncDelta = TT_ABOVE_DELTA_Y; }else { jsu_log ( fn + "CLOSE TipFix that was OPEN Over szRefElId=" + objOpt.szRefElId); bOpenTip = false; // Close } }else { var event = event || window.event; if (event != undefined){ tipImg = event.target || event.srcElement; } } tt_tipFix.tipImg = tipImg; // var deltaY = 35; // Default if (tipImg != undefined){ // --------------------------------------------------------------------- get Toggle Class if present (it is not mandatory to toggle image) var className = tipImg.className; var szId = tipImg.id; if (szId == undefined || szId.length == 0){ return tt_Err(fn + "SW ERROR tipImg has id=null \n tipImg used with TipFix must have an id"); } var bToggled = false; //default //---------------------- TOGGLE IMAGE jsu_log ( fn + "OLD classname=" + className); for (i=0; i< tt_arToggleClass.length; i++){ var objToggle = tt_arToggleClass[i]; if (className == objToggle.Down){ className = objToggle.Up; bToggled = true; jsu_log ( fn + "TOGGLE From " + objToggle.Down + " TO " + objToggle.Up); }else if (className == objToggle.Up){ className = objToggle.Down; jsu_log ( fn + "TOGGLE From " + objToggle.Up + " TO " + objToggle.Down); bOpenTip = false; bToggled = true; } } if (tt_tipFix.objClass != undefined && tt_tipFix.objClass.Down != undefined && tt_tipFix.objClass.Up != undefined){ jsu_logObj ( fn + "CASE of CUSTOM objClass" + tt_tipFix.objClass); // Custom Class passed by User if (className == tt_tipFix.objClass.Up){ className = tt_tipFix.objClass.Down; bToggled = true; bOpenTip = false; }else if (className == tt_tipFix.objClass.Down ){ className = tt_tipFix.objClass.Up; bToggled = true; } } if (bToggled){ jsu_log ( fn + "TOGGLE TO NEW classname=" + className); } else{ jsu_logObj ( fn + "Current className=" + className + " NOT implemented as TOGGLE IMage: SO NO IMAGE TOGGLE is DONE" ); } tipImg.className = className; } jsu_log ( fn + "bOpenTip=" + bOpenTip); if (bOpenTip && tip_img_fixed){ jsu_log ( fn + "Particular case: Click to open a new TipFix while another is still open. So we close the TipFix that was stil open"); // To manage the case of switch beween different Fixed img. We untip previous UnTipFix(); // false becuase we do not want to resize: there is alread a new FixedTip Open } if (bOpenTip && tipImg){ jsu_log ( fn + "---------------------- OPEN TipFix"); tip_img_fixed = tipImg; // save in global TIP_CFG_FIXED.Fix = [tipImg.id,tipFixedPos,5]; jsu_logObj ( fn + "SET TIP_CFG_FIXED.Fix=", TIP_CFG_FIXED.Fix); Tip(tipMsgHtml,TIP_TYPE.Fixed, objOpt); var el = document.getElementById ("WzTiTl"); var szWidth = el.style.width; jsu_log (fn + "reduce width of the header that was " + szWidth); iWidth = parseInt (szWidth.replace ("px","")) - 6; el.style.width = iWidth + "px"; }else { // User has click over the image arrow Up to close the TipFix jsu_log ( fn + "---------------------- CLOSE TipFix"); UnTipFix(); } jsu_log ( fn + JSU_LOG_FUN_END); } /** * Call this function to Hide the Tip after Tip() Call <BR/> * If currently a TipFix is displayed, it is not closed (to manage both TipFix at Click and Tip/Untip * <div class="jsDocNote"> <b>Implementation NOTES:</b> <ul> <li>tip_type Set it to TIP_TYPE.NONE</li> </ul> </div> * */ function UnTip() { var fn = "[tooltip.js UnTip()] "; jsu_log ( fn + JSU_LOG_FUN_START); jsu_log(fn + "CURRENT tip_type=" + tip_type); if (tip_type == TIP_TYPE.Fixed){ return jsu_log ( fn + "Nothing to do: a TipFix is still displayed" + JSU_LOG_FUN_END); } tt_init(); // init, if not already done tt_SetCfg(TIP_CFG_FLOATING); tt_OpReHref(); if(tt_aV[DURATION] < 0 && (tt_iState & 0x2)) tt_tDurt.Timer("tt_HideInit()", -tt_aV[DURATION], true); else if(!(tt_aV[STICKY] && (tt_iState & 0x2))) tt_HideInit(); tt_RestoreImgFixed(); // Restore previous Image Fixed if required tip_type = TIP_TYPE.NONE; jsu_log ( fn + JSU_LOG_FUN_END); } /** * Call this function to UnTip after TipFixxx(). E.g in Close Button, ESC,... <BR/> * Used internally, but it can also be called form external */ function UnTipFix(){ var fn = "[tooltip.js UnTipFix()] "; jsu_log ( fn + JSU_LOG_FUN_START); jsu_log(fn + "CURRENT tip_type=" + tip_type); tt_SetCfg(TIP_CFG_FLOATING); tt_OpReHref(); if(tt_aV[DURATION] < 0 && (tt_iState & 0x2)) tt_tDurt.Timer("tt_HideInit()", -tt_aV[DURATION], true); else if(!(tt_aV[STICKY] && (tt_iState & 0x2))) tt_HideInit(); tt_RestoreImgFixed(); // Restore previous Image Fixed if required tip_type = TIP_TYPE.NONE; if (tt_tipFix.tipImg != undefined){ tt_tipFix.tipImg.bTipFixOpen = false; } jsu_log ( fn + JSU_LOG_FUN_END); } /** * Display a Fixed Tip with Code Hightlighted with JSU core/prettify/prettify-jsu.js <BR/> * Example of supported language: <b>js, java, perl, pl, pm, bsh, csh, sh, c, cpp, rb, py, cv, cs ,json, ..</b> <BR/> * See prettify-jsu.js for the detail of supported languages <BR/> * * @param szCode {String} jsCode to display, with \n for newline. <BR/> * <label class="tipWarn">szCode with HTML is not supported by this function. To show HTML Code you can use TipFixMultiCode or TipFixTextArea</label> * @param event <table class="jsDoc" border="2" cellpadding="2" cellspacing="2"> <tr><td class="jsDocTitle">OPTIONS</td></tr> <tr><td class="jsDocParam"> <ul> <li> szTitle{String} default: TIP_DEF_CODE_TITLE </li> <li> iTipWidth {Number}: [undefined] TipWidth - do not pass it to automatically set it basing on content. </li> <li> iTipMaxHeight {Number}: [0] Max Height of the Tip (Scroll will be used if required). If 0 the height is automatically calculated to show all the Tip. . Default =0 NO SCROLL </li> <li> bCloseBtn {Boolean} default: true (if true show a Close Button on the Bottom) </li> <li> tipFixedPos: TipPosition using TIP_FIXED_POS possible values (TIP_FIXED_POS.CENTER,...) n default=TIP_FIXED_POS.CENTER </li> </ul> </td></tr> </table> @example function sample3b(event){ var szCode = 'public class Factorial \n'+ '{ \n'+ ' public static void main(String[] args) \n'+ ' { final int NUM_FACTS = 100; \n'+ ' for(int i = 0; i < NUM_FACTS; i++) \n'+ ' System.out.println( i + "! is " + factorial(i)); \n'+ ' } \n'+ ' \n'+ ' public static int factorial(int n) \n'+ ' { int result = 1; \n'+ ' for(int i = 2; i <= n; i++) \n'+ ' result *= i; \n'+ ' return result; \n'+ ' } '; TipFixCode(szCode,event, {iTipWidth:1000, iTipMaxHeight:600, szTitle:'Tip Sample with Java Code Hightlighted' }); } */ function TipFixCode(szCode, event, objOpt){ var fn = "[tooltip.js TipFixCode] "; jsu_log (fn + JSU_LOG_FUN_START); if (objOpt == undefined){ objOpt = new Object(); } if (objOpt.szTitle == undefined){ objOpt.szTitle = TIP_DEF_CODE_TITLE; } if (objOpt.bCloseBtn == undefined){ objOpt.bCloseBtn = TIP_DEF_CLOSE_BTN; } // if (objOpt.iTipWidth == undefined){ objOpt.iTipWidth = TIP_DEF_WIDTH; } tt_init(); // init, if not already done // Check if prettify is enabled if (tt_isPrettifyPresent()){ var szCodeDiv = '<div id="divTipJS" align="left" class="prettify" style="width:"' + objOpt.iTipWidth + '"px;"> <pre class="prettyprint"><code>' + szCode + '</code></pre></div>'; TipFix (szCodeDiv,event,objOpt); jsuPrettyPrint(); // Hightlight with prettify-jsu the code between <pre> </pre> }else{ TipFixTextArea(szCode, event, objOpt); } jsu_log (fn + JSU_LOG_FUN_END); } /** * Display a Fixed Tip with Code Hightlighted with JSU core/prettify/prettify-jsu.js <BR/> * Example of supported language: <b>js, java, perl, pl, pm, bsh, csh, sh, c, cpp, rb, py, cv, cs ,json, ..</b> <BR/> * See prettify-jsu.js for the detail of supported languages <BR/> * * @param arObjCode {Array} Array of Obj with the info of the code display. ESech Obj of the Array can have follwoing fields: <ul> * <li> szTitle {String} e.g "JS" - Title of the Section</li> * <li> szCode {String} The Code to diaply in section</li> * <li> bPrettify {Boolean} [true] true if szCode must be prettified. If szCode contains HTML Tags you have to set bPrettify=false if you wnat to see the Text with HTMLTags into a TextArea, witout prettify it</li> * <li> iRowNum {Number} [undefined] Only for Obj.bPrettify=false. If it is not present (default), the Rows of TextArea are automatically calculated basing on /n. If passed iRowNum is used</li> * <li> iMaxHeight {Number}: Only for Obj.bPrettify=true Max Height (px) of the Div - If Undefined there is no max <li/> * </ul> * See example below <BR/> * @param event <table class="jsDoc" border="2" cellpadding="2" cellspacing="2"> <tr><td class="jsDocTitle">OPTIONS</td></tr> <tr><td class="jsDocParam"> <ul> <li> szTitle{String} default: 'Source Code' <li/> <li> iTipWidth {Number}: [undefined] TipWidth - do not pass it to automatically set it basing on content. </li> <li> iTipMaxHeight {Number}: Max Height (px) of the Tip . Default =0 NO SCROLL <li/> <li> iColNum {Number} default: 80 Can be used to change the colnum of all the TextArea of the Tip <li/> <li> bCloseBtn {Boolean} default: true (if true show a Close Button on the Bottom) <li/> <li> tipFixedPos: TipPosition using TIP_FIXED_POS possible values (TIP_FIXED_POS.CENTER,...) default=TIP_FIXED_POS.CENTER <li/> </ul> </td></tr> </table> @example function sampleCode1b(event){ var JS_CODE_1b_JS = '//Define in JS a constant (e.g. JSU_TIP_HTML) with the MsgHtml to show in the Tip: \n'+ 'var JSU_TIP_HTML="<b>Simple Tooltip</b> with <i>HTML tags</i><br/>Tip (You can use <u>whatever HTML TAG</u>";'; var JS_CODE_1b_HTML = '// To add whatever HTML FloatingTip to whatever HTML Item: \n'+ '// - onmouseover="Tip(HtmlMsg);" \n'+ '// - onmouseout="UnTip();" \n'+ '// In This example: \n'+ '<input type="text" value="HTML Tip" style="width:60px;" \n' + ' onmouseover="Tip(JSU_TIP_HTML);" \n'+ ' onmouseout="UnTip(event);"/>'; // 2 Codes, both contain HTML TAGS TipFixMultiCode([ {szTitle:"JS: TipSample.js", szCode: JS_CODE_1b_JS, bPrettify:false}, {szTitle:"HTML: TipSample.html", szCode: JS_CODE_1b_HTML, bPrettify:false} ], event, { szTitle:"SAMPLE_1 HTML Tip - Source Code" , iTipWidth: 1000 } ); } */ function TipFixMultiCode(arObjCode, event, objOpt){ var fn = "[tooltip.js TipFixMultiCode] "; jsu_log (fn + JSU_LOG_FUN_START); jsu_logObj (fn + "IN arObjCode",arObjCode); jsu_logObj (fn + "IN objOpt",objOpt); if (objOpt == undefined){ objOpt = new Object(); } if (objOpt.szTitle == undefined){ objOpt.szTitle = TIP_DEF_CODE_TITLE; } if (objOpt.bCloseBtn == undefined){ objOpt.bCloseBtn = TIP_DEF_CLOSE_BTN; } // if (objOpt.iTipWidth == undefined){ objOpt.iTipWidth = TIP_DEF_WIDTH; } if (objOpt.iColNum == undefined){ objOpt.iColNum = TIP_DEF_COL_NUM; } var iTxtAreaWidth = objOpt.iTipWidth - 40; // some space for padding and borders tt_init(); // init, if not already done var bPrettifyEn = tt_isPrettifyPresent(); var szCodeDiv = '<table class="detNoBorder" >\n'; for (var i=0; i < arObjCode.length;i++){ var objCode = arObjCode[i]; var szWidth = ""; if (objCode.bPrettify== undefined){ objCode.bPrettify= false; } if (!bPrettifyEn){ objCode.bPrettify= false; } var szClassPrettify = (objCode.bPrettify) ? "prettifyCode" : ""; // extra Class var szClassTitlePrettify = (objCode.bPrettify) ? " prettifyTitle " : ""; // extra Class var szTbl = '<tr><td><table class="det ' + szClassPrettify + '" ' + szWidth + '" BORDER="2" cellspacing="0" cellpadding="2" >\n'; if (objCode.iTipMaxHeight== undefined){ objCode.iTipMaxHeight= TIP_DEF_MAXH_MCODE; } if (objCode.szTitle == undefined){ objCode.szTitle = TIP_DEF_MCODE_TITLE; } jsu_log (fn + 'arObjCode[' + i + '] bPrettify=' + objCode.bPrettify); szTbl+= ' <tr class="detTitle ' + szClassTitlePrettify + szClassPrettify + '"><td width="100%" class="detTitle ' + szClassTitlePrettify + szClassPrettify + '">' + objCode.szTitle + '</td></tr>\n'; szTbl+= ' <tr class="det ' + szClassPrettify + '" ><td class="tipl ' + szClassPrettify + '" width="100%">\n'; var id = "tipCode_" + i; if (!objCode.bPrettify){ if (objCode.iRowNum == undefined){ // if not passed we calculate RowNum basing on /n objCode.iRowNum = tt_getHtmlRowNum(objCode.szCode); } // HTML must be put into a TextArea szTbl+=' <textarea id="' + id + '" rows="' + objCode.iRowNum + '" cols="' + objOpt.iColNum + '" >' + objCode.szCode + '</textarea>\n'; }else{ // This Code must be prettified var iWidth = (objOpt.iTipWidth == undefined) ? TIP_DEF_WIDTH : objOpt.iTipWidth; var bContainer = false; // check if is required MaxHeight var szMaxHeight = ""; var iMaxHeight = objOpt.iTipMaxHeight; // can be undefined if (objCode.iMaxHeight != undefined){ iMaxHeight = objCode.iMaxHeight; } if (iMaxHeight != undefined && iMaxHeight > 0){ bContainer = true; } //----------------------- if (bContainer){ var szMaxHeightCont = 'max-height:' + iMaxHeight + 'px;'; var szWidthCont = 'width:' + iWidth -100 + 'px;'; var szWidth = 'width:' + (iWidth -130) + 'px;'; // ------ jsu_log (fn + "For code[" + i + "] we have to put an extra div container - szMaxHeightCont=" + szMaxHeightCont); var szDivPretty = '<div style="' + szMaxHeightCont + szWidthCont + ' border: 1px solid; overflow: auto; background-color: white; ">' + ' <div id="' + id + '" class="prettify" style="' + szWidth + '"> <pre class="prettyprint"><code>' + objCode.szCode + '</code></pre></div>' + '</div>'; jsu_logHtml (fn + "szDivPretty", szDivPretty); }else { var szWidth = 'width:' + iWidth + 'px;'; var szDivPretty = ' <div id="' + id + '" class="prettify" style="' + szWidth + '"> <pre class="prettyprint"><code>' + objCode.szCode + '</code></pre></div>\n'; } szTbl += szDivPretty; } szTbl+= ' </td></tr></table>\n'; szCodeDiv += szTbl; szCodeDiv += '</td></tr>' if (i < (arObjCode.length-1)){ // Empty row szCodeDiv += '<tr class="detSep"><td></td></tr>'; } } szCodeDiv += '</table>'; // jsu_logHtml(fn + "szCodeDiv", szCodeDiv); objOpt.bNL2BR = false; // we do not want to replace \n with <BR/>. Everythong is already well formatted TipFix (szCodeDiv,event,objOpt); if (bPrettifyEn){ jsuPrettyPrint(); // Hightlight with prettify-jsu the code between <pre> </pre> } // NOTE: we have to change the width of TextArea basing on TipWidth. If set during TextArea creation it is not considered var iTipWidth = (objOpt.iTipWidth != undefined) ? objOpt.iTipWidth : TIP_DEF_WIDTH; var iWidth = iTipWidth - 40; // keep some space for Padding,.. jsu_log (fn + "TipWidth=" + iTipWidth + " - We set " + arObjCode.length + " CodeEl with width=" + iWidth + " to adapt them to the Div Container"); for (var i=0; i < arObjCode.length; i++){ var el = document.getElementById("tipCode_" + i); el.style.width = iWidth + 'px'; } jsu_log (fn + JSU_LOG_FUN_END); } /** * Display whatever Text (also HTML TAGs) in a TextArea of a FixedTip. For Example this function is used to display mixed JS and HTML code * @param szTxt {String} szTxt to display, with \n for newline * @param event <table class="jsDoc" border="2" cellpadding="2" cellspacing="2"> <tr><td class="jsDocTitle">OPTIONS</td></tr> <tr><td class="jsDocParam"> <ul> * <li> szTitle{String} default: 'Text' </li> * <li> iColNum{Number} default=100 Number of Column for TextArea </li> * <li> iRowNum{Number} default=20 Number of Rows for TextArea (if more rows are present, scrollbar will be created). * Usually do not pass iRowNum, so it is automatically calculatd</li> * <li> bCloseBtn {Boolean} default: true (if true show a Close Button on the Bottom) </li> * <li> iTipWidth {Number}: [undefined] TipWidth - do not pass it to automatically set it basing on content. </li> * <li> iTipMaxHeight {Number}: [0] Max Height of the Tip (Scroll will be used if required). If 0 the height is automatically calculated to show all the Tip. . Default =0 NO SCROLL </li> * <li> tipFixedPos: TipPosition using TIP_FIXED_POS possible values (TIP_FIXED_POS.CENTER,...) n default=TIP_FIXED_POS.CENTER </li> * </ul> * @example //This is an example of MIXED Code: JS and also HTML. // HTML TAGs cannot be displayed with TipJSFixedClick(), but you should use TipTextAreaFixedClick() //--------------------------------------------------------- JS var JS_CODE_SORT_SAMPLE=...; //<input> object with: // - class="tipFixed" type="button" // - value=Text to display in the button // - set whatever unique id // - onclick="TipJSFixedClicked(msg,event,objOpt)" // - objOpt = {iTipMaxHeight:300} for Optional MaxHeight (Vertical Scrollbar) //--------------------------------------------------------- HTML <input type="button" class="tipFixed" style="color:blue;" value="JS Source Code" id="tipBtnJSFixedSample" onclick="TipJSFixedClicked(JS_CODE_SORT_SAMPLE,event,{iTipMaxHeight:300});" /> ; */ function TipFixTextArea(szTxt, event, objOpt){ var fn = "[tooltip.js TipFixTextArea] "; jsu_log (fn + JSU_LOG_FUN_START); jsu_logObj (fn + "IN objOpt", objOpt); if (objOpt == undefined){ objOpt = new Object(); } if (objOpt.szTitle == undefined){ objOpt.szTitle = TIP_DEF_TEXTBOX_TITLE; } if (objOpt.bCloseBtn == undefined){ objOpt.bCloseBtn = TIP_DEF_CLOSE_BTN; } if (objOpt.iColNum == undefined){ objOpt.iColNum = TIP_DEF_COL_NUM; } if (objOpt.iRowNum == undefined){ objOpt.iRowNum = tt_getHtmlRowNum(szTxt) } tt_init(); // init, if not already done var szTxtBox='<textarea id="tipTextArea" rows="' + objOpt.iRowNum + '" cols="' + objOpt.iColNum + '" >' + szTxt + '</textarea><BR/>'; objOpt.bNL2BR = false; // we do not want to replace \n with <BR/> TipFix (szTxtBox,event,objOpt); // NOTE: we have to change the width of TextArea basing on TipWidth. If set during TextArea creation it is not considered var iTipWidth = (objOpt.iTipWidth != undefined) ? objOpt.iTipWidth : TIP_DEF_WIDTH; var iTextAreaWidth = iTipWidth - 40; // keep some space for Padding,.. jsu_log (fn + "TipWidth=" + iTipWidth + " - We set TextArea with width=" + iTextAreaWidth + " to adapt it to the Div Container"); var el = document.getElementById("tipTextArea"); el.style.width = iTextAreaWidth + 'px'; jsu_log (fn + JSU_LOG_FUN_END); } /* ========================================================================================== LOCAL FUNCTION ========================================================================================== */ /* * Check if szClass is a TipFix Class * @param szClass */ function tt_isClassFixed(szClass){ var bTipFix = false; var fn="[tooltip.js tt_isClassFixed()] "; for (i=0; i< tt_arToggleClass.length; i++){ if (tt_arToggleClass[i].Up == szClass){ bTipFix = true; } } if (tt_tipFix.objClass != undefined && tt_tipFix.objClass.Down != undefined && tt_tipFix.objClass.Up != undefined){ // Custom Class passed by User if (szClass == tt_tipFix.objClass.Up){ bTipFix = true; } } jsu_log (fn + "IN: szClass=" + szClass + " OUT bTipFix=" + bTipFix); return bTipFix; } /* * Restore the Original Image class (From Up to down) if tip_img_fixed != null */ function tt_RestoreImgFixed() { var fn="[tooltip.js tt_RestoreImgFixed()] "; if (tip_img_fixed != null){ var szClass = ""; // Change img of tip_fixed if present for (i=0; i< tt_arToggleClass.length; i++){ if (tt_arToggleClass[i].Up == tip_img_fixed.className){ szClass = tt_arToggleClass[i].Down ; } } if (tt_tipFix.objClass != undefined && tt_tipFix.objClass.Down != undefined && tt_tipFix.objClass.Up != undefined){ // Custom Class passed by User if (tip_img_fixed.className == tt_tipFix.objClass.Up){ szClass = tt_tipFix.objClass.Down; } } if (szClass != ""){ jsu_log (fn + "tip_img_fixed.id=" + tip_img_fixed.id + " - Change className=" + tip_img_fixed.className + " To " + szClass); tip_img_fixed.className = szClass; } tip_img_fixed = null; } } /*----------------------------------------------------------- Get Element By ID and Show Error if required PAR Id in [bShowErr] in true (default) if I want to show Error false if don't want to show Error RETURN el if founded 0 if not founded -----------------------------------------------------------*/ function tt_getElementById2(Id,bShowErr) { if (bShowErr == undefined){ // bShowErr = true; bShowErr = false; // use false beacause some fileds are not present } var el = document.getElementById(Id); if (el == null) { if (bShowErr){ alert("SW ERROR [tt_getElementById2] NOT FOUND Id=" + Id) ; } return 0; // Not Found } return el; } function tt_showTip() { var fn = "[tooltip.js tt_showTip()] "; jsu_log ( fn + JSU_LOG_FUN_START); tt_Tip(arguments, null); jsu_log ( fn + JSU_LOG_FUN_END); } function TagToTip() { var t2t = tt_GetElt(arguments[0]); if(t2t) tt_Tip(arguments, t2t); } /* * Set some Cfg config specifyc for Floating or Fixed * @param objCfg */ function tt_SetCfg(objCfg){ config.FollowMouse = objCfg.FollowMouse; config.Delay = objCfg.DelayMs; config.FadeIn = objCfg.FadeMs; config.FadeOut = objCfg.FadeMs; config.CenterMouse =objCfg.CenterMouse; config.BorderStyle = objCfg.BorderStyle; config.BorderWidth = objCfg.BorderWidth; config.CloseBtn = objCfg.CloseBtn; config.JumpVert = objCfg.JumpVert; config.Title = objCfg.Title; config.Fix = objCfg.Fix; config.OffsetY = objCfg.OffsetY; } function tt_Extension() { tt_ExtCmdEnum(); tt_aExt[tt_aExt.length] = this; return this; } /* * Set TipPos * * Modify: Apr 2016 if x is too left or to right to seet porperly the tip, we adljust it * * @param x * @param y */ function tt_SetTipPos(x, y) { var fn = "[tooltip.js tt_SetTipPos] "; var css = tt_aElt[0].style; //if x is too left or to right to set porperly the tip, we adljust it if (x <TT_X_MIN){ jsu_log (fn + "change x from" + x + " to xMin=" + TT_X_MIN); x = TT_X_MIN; }else { var xRight = x + tt_w -20; var xMax = tt_GetClientW(); var xDelta = (xRight - xMax); if (xDelta > 0){ x -= xDelta; if (x <TT_X_MIN){ x = TT_X_MIN; } jsu_log (fn + "x was too on the right. Set x=" + x); } } tt_x = x; tt_y = y; css.left = x + "px"; css.top = y + "px"; if(tt_ie56) { var ifrm = tt_aElt[tt_aElt.length - 1]; if(ifrm) { ifrm.style.left = css.left; ifrm.style.top = css.top; } } } function tt_HideInit() { if(tt_iState) { tt_ExtCallFncs(0, "HideInit"); tt_iState &= ~(0x4 | 0x8); if(tt_flagOpa && tt_aV[FADEOUT]) { tt_tFade.EndTimer(); if(tt_opa) { var n = Math.round(tt_aV[FADEOUT] / (tt_aV[FADEINTERVAL] * (tt_aV[OPACITY] / tt_opa))); tt_Fade(tt_opa, tt_opa, 0, n); return; } } tt_tHide.Timer("tt_Hide();", 1, false); } } function tt_Hide() { var fn = "[tooltip.js tt_tt_Hide()] "; jsu_log (fn + JSU_LOG_FUN_START); if(tt_db && tt_iState) { tt_OpReHref(); if(tt_iState & 0x2) { tt_aElt[0].style.visibility = "hidden"; tt_ExtCallFncs(0, "Hide"); } tt_tShow.EndTimer(); tt_tHide.EndTimer(); tt_tDurt.EndTimer(); tt_tFade.EndTimer(); if(!tt_op && !tt_ie) { tt_tWaitMov.EndTimer(); tt_bWait = false; } if(tt_aV[CLICKCLOSE] || tt_aV[CLICKSTICKY]) tt_RemEvtFnc(document, "mouseup", tt_OnLClick); tt_ExtCallFncs(0, "Kill"); // In case of a TagToTip tip, hide converted DOM node and // re-insert it into DOM if(tt_t2t && !tt_aV[COPYCONTENT]) tt_UnEl2Tip(); tt_iState = 0; tt_over = null; tt_ResetMainDiv(); if(tt_aElt[tt_aElt.length - 1]) tt_aElt[tt_aElt.length - 1].style.display = "none"; } jsu_log (fn + JSU_LOG_FUN_END); } function tt_GetElt(id) { return(document.getElementById ? tt_getElementById2(id) : document.all ? document.all[id] : null); } function tt_GetDivW(el) { return(el ? (el.offsetWidth || el.style.pixelWidth || 0) : 0); } function tt_GetDivH(el) { return(el ? (el.offsetHeight || el.style.pixelHeight || 0) : 0); } function tt_GetScrollX() { return(window.pageXOffset || (tt_db ? (tt_db.scrollLeft || 0) : 0)); } function tt_GetScrollY() { return(window.pageYOffset || (tt_db ? (tt_db.scrollTop || 0) : 0)); } function tt_GetClientW() { return tt_GetWndCliSiz("Width"); } function tt_GetClientH() { return tt_GetWndCliSiz("Height"); } function tt_GetEvtX(e) { return (e ? ((typeof(e.pageX) != tt_u) ? e.pageX : (e.clientX + tt_GetScrollX())) : 0); } function tt_GetEvtY(e) { return (e ? ((typeof(e.pageY) != tt_u) ? e.pageY : (e.clientY + tt_GetScrollY())) : 0); } function tt_AddEvtFnc(el, sEvt, PFnc) { if(el) { if(el.addEventListener) el.addEventListener(sEvt, PFnc, false); else el.attachEvent("on" + sEvt, PFnc); } } function tt_RemEvtFnc(el, sEvt, PFnc) { if(el) { if(el.removeEventListener) el.removeEventListener(sEvt, PFnc, false); else el.detachEvent("on" + sEvt, PFnc); } } function tt_GetDad(el) { return(el.parentNode || el.parentElement || el.offsetParent); } function tt_MovDomNode(el, dadFrom, dadTo) { if(dadFrom) dadFrom.removeChild(el); if(dadTo) dadTo.appendChild(el); } //====================== PRIVATE ===========================================// var tt_aExt = new Array(), // Array of extension objects tt_db, tt_op, tt_ie, tt_ie56, tt_bBoxOld, // Browser flags tt_body, tt_ovr_, // HTML element the mouse is currently over tt_flagOpa, // Opacity support: 1=IE, 2=Khtml, 3=KHTML, 4=Moz, 5=W3C tt_maxPosX, tt_maxPosY, tt_iState = 0, // Tooltip active |= 1, shown |= 2, move with mouse |= 4, exclusive |= 8 tt_opa, // Currently applied opacity tt_bJmpVert, tt_bJmpHorz,// Tip temporarily on other side of mouse tt_elDeHref, // The tag from which we've removed the href attribute // Timer tt_tShow = new Number(0), tt_tHide = new Number(0), tt_tDurt = new Number(0), tt_tFade = new Number(0), tt_tWaitMov = new Number(0), tt_bWait = false, tt_u = "undefined"; function tt_init() { var fn = "[tooltip.js tt_init] "; if (tt_init_done){ return; // already done } jsu_log (fn + "Init tooltip.js"); // ESC is considered as UnTip of TipFix document.onkeydown = function(e){ if(e != null && e.keyCode === TIP_KEYCODE_ESC){ UnTipFix(); } }; tt_MkCmdEnum(); // Send old browsers instantly to hell if(!tt_Browser() || !tt_MkMainDiv()) return; tt_IsW3cBox(); tt_OpaSupport(); tt_AddEvtFnc(document, "mousemove", tt_Move); // In Debug mode we search for TagToTip() calls in order to notify // the user if they've forgotten to set the TagsToTip config flag if(TagsToTip ) tt_SetOnloadFnc(); // Ensure the tip be hidden when the page unloads tt_AddEvtFnc(window, "unload", tt_Hide); tt_init_done = true; } // Creates command names by translating config variable names to upper case function tt_MkCmdEnum() { var n = 0; for(var i in config) eval("window." + i.toString().toUpperCase() + " = " + n++); tt_aV.length = n; } function tt_Browser() { var n, nv, n6, w3c; n = navigator.userAgent.toLowerCase(), nv = navigator.appVersion; var szAppName = navigator.appName; tt_op = (document.defaultView && typeof(eval("w" + "indow" + "." + "o" + "p" + "er" + "a")) != tt_u); // tt_ie = n.indexOf("msie") != -1 && document.all && !tt_op; tt_ie = ((navigator.appName == APP_NAME_IE) || ((navigator.appName == APP_NAME_IE_11) && (new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})").exec(navigator.userAgent) != null))); if(tt_ie) { var ieOld = (!document.compatMode || document.compatMode == "BackCompat"); tt_db = !ieOld ? document.documentElement : (document.body || null); if(tt_db) tt_ie56 = parseFloat(nv.substring(nv.indexOf("MSIE") + 5)) >= 5.5 && typeof document.body.style.maxHeight == tt_u; } else { tt_db = document.documentElement || document.body || (document.getElementsByTagName ? document.getElementsByTagName("body")[0] : null); if(!tt_op) { n6 = document.defaultView && typeof document.defaultView.getComputedStyle != tt_u; w3c = !n6 && document.getElementById; } } tt_body = (document.getElementsByTagName ? document.getElementsByTagName("body")[0] : (document.body || null)); if(tt_ie || n6 || tt_op || w3c) { if(tt_body && tt_db) { if(document.attachEvent || document.addEventListener) return true; } else tt_Err("tooltip.js must be included INSIDE the body section," + " immediately after the opening <body> tag."); } tt_db = null; return false; } function tt_MkMainDiv() { // Create the tooltip DIV if(tt_body.insertAdjacentHTML) tt_body.insertAdjacentHTML("afterBegin", tt_MkMainDivHtm()); else if(typeof tt_body.innerHTML != tt_u && document.createElement && tt_body.appendChild) tt_body.appendChild(tt_MkMainDivDom()); if(window.tt_GetMainDivRefs /* FireFox Alzheimer */ && tt_GetMainDivRefs()) return true; tt_db = null; return false; } function tt_MkMainDivHtm() { return( '<div id="ttDivContainer"></div>' + (tt_ie56 ? ('<iframe id="WzTtIfRm" src="javascript:false" scrolling="no" frameborder="0" style="filter:Alpha(opacity=0);position:absolute;top:0px;left:0px;display:none;"></iframe>') : '') ); } function tt_MkMainDivDom() { var el = document.createElement("div"); if(el) el.id = "ttDivContainer"; return el; } function tt_GetMainDivRefs() { tt_aElt[0] = tt_GetElt("ttDivContainer"); if(tt_ie56 && tt_aElt[0]) { tt_aElt[tt_aElt.length - 1] = tt_GetElt("WzTtIfRm"); if(!tt_aElt[tt_aElt.length - 1]) tt_aElt[0] = null; } if(tt_aElt[0]) { var css = tt_aElt[0].style; css.visibility = "hidden"; css.position = "absolute"; css.overflow = "hidden"; return true; } return false; } function tt_ResetMainDiv() { var fn = "[tooltip.js tt_ResetMainDiv()] "; // jsu_log (fn + "Called"); tt_SetTipPos(0, 0); tt_aElt[0].innerHTML = ""; tt_aElt[0].style.width = "0px"; tt_h = 0; } function tt_IsW3cBox() { var css = tt_aElt[0].style; css.padding = "10px"; css.width = "40px"; tt_bBoxOld = (tt_GetDivW(tt_aElt[0]) == 40); css.padding = "0px"; tt_ResetMainDiv(); } function tt_OpaSupport() { var css = tt_body.style; tt_flagOpa = (typeof(css.KhtmlOpacity) != tt_u) ? 2 : (typeof(css.KHTMLOpacity) != tt_u) ? 3 : (typeof(css.MozOpacity) != tt_u) ? 4 : (typeof(css.opacity) != tt_u) ? 5 : (typeof(css.filter) != tt_u) ? 1 : 0; } // Ported from http://dean.edwards.name/weblog/2006/06/again/ // (<NAME> et al.) function tt_SetOnloadFnc() { tt_AddEvtFnc(document, "DOMContentLoaded", tt_HideSrcTags); tt_AddEvtFnc(window, "load", tt_HideSrcTags); if(tt_body.attachEvent) tt_body.attachEvent("onreadystatechange", function() { if(tt_body.readyState == "complete") tt_HideSrcTags(); } ); if(/WebKit|KHTML/i.test(navigator.userAgent)) { var t = setInterval(function() { if(/loaded|complete/.test(document.readyState)) { clearInterval(t); tt_HideSrcTags(); } }, 10); } } function tt_HideSrcTags() { if(!window.tt_HideSrcTags || window.tt_HideSrcTags.done) return; window.tt_HideSrcTags.done = true; if(!tt_HideSrcTagsRecurs(tt_body)) tt_Err("There are HTML elements to be converted to tooltips.\nIf you" + " want these HTML elements to be automatically hidden, you" + " must edit tooltip.js, and set TagsToTip in the global" + " tooltip configuration to true."); } function tt_HideSrcTagsRecurs(dad) { var ovr, asT2t; // Walk the DOM tree for tags that have an onmouseover or onclick attribute // containing a TagToTip('...') call. // (.childNodes first since .children is bugous in Safari) var a = dad.childNodes || dad.children || null; for(var i = a ? a.length : 0; i;) {--i; if(!tt_HideSrcTagsRecurs(a[i])) return false; ovr = a[i].getAttribute ? (a[i].getAttribute("onmouseover") || a[i].getAttribute("onclick")) : (typeof a[i].onmouseover == "function") ? (a[i].onmouseover || a[i].onclick) : null; if(ovr) { asT2t = ovr.toString().match(/TagToTip\s*\(\s*'[^'.]+'\s*[\),]/); if(asT2t && asT2t.length) { if(!tt_HideSrcTag(asT2t[0])) return false; } } } return true; } function tt_HideSrcTag(sT2t) { var id, el; // The ID passed to the found TagToTip() call identifies an HTML element // to be converted to a tooltip, so hide that element id = sT2t.replace(/.+'([^'.]+)'.+/, "$1"); el = tt_GetElt(id); if(el) { if(!TagsToTip) return false; else el.style.display = "none"; } else tt_Err("Invalid ID\n'" + id + "'\npassed to TagToTip()." + " There exists no HTML element with that ID."); return true; } function tt_Tip(arg, t2t) { if(!tt_db || (tt_iState & 0x8)) return; if(tt_iState) tt_Hide(); if(!tt_Enabled) return; tt_t2t = t2t; if(!tt_ReadCmds(arg)) return; tt_iState = 0x1 | 0x4; tt_AdaptConfig1(); tt_MkTipContent(arg); tt_MkTipSubDivs(); tt_FormatTip(); tt_bJmpVert = false; tt_bJmpHorz = false; tt_maxPosX = tt_GetClientW() + tt_GetScrollX() - tt_w - 1; tt_maxPosY = tt_GetClientH() + tt_GetScrollY() - tt_h - 1; tt_AdaptConfig2(); // Ensure the tip be shown and positioned before the first onmousemove tt_OverInit(); tt_ShowInit(); tt_Move(); } function tt_ReadCmds(a) { var i; // First load the global config values, to initialize also values // for which no command is passed i = 0; for(var j in config) tt_aV[i++] = config[j]; // Then replace each cached config value for which a command is // passed (ensure the # of command args plus value args be even) if(a.length & 1) { for(i = a.length - 1; i > 0; i -= 2) tt_aV[a[i - 1]] = a[i]; return true; } tt_Err("Incorrect call of Tip() or TagToTip().\n" + "Each command must be followed by a value."); return false; } function tt_AdaptConfig1() { tt_ExtCallFncs(0, "LoadConfig"); // Inherit unspecified title formattings from body if(!tt_aV[TITLEBGCOLOR].length) tt_aV[TITLEBGCOLOR] = tt_aV[BORDERCOLOR]; if(!tt_aV[TITLEFONTCOLOR].length) tt_aV[TITLEFONTCOLOR] = tt_aV[BGCOLOR]; if(!tt_aV[TITLEFONTFACE].length) tt_aV[TITLEFONTFACE] = tt_aV[FONTFACE]; if(!tt_aV[TITLEFONTSIZE].length) tt_aV[TITLEFONTSIZE] = tt_aV[FONTSIZE]; if(tt_aV[CLOSEBTN]) { // Use title colours for non-specified closebutton colours if(!tt_aV[CLOSEBTNCOLORS]) tt_aV[CLOSEBTNCOLORS] = new Array("", "", "", ""); for(var i = 4; i;) {--i; if(!tt_aV[CLOSEBTNCOLORS][i].length) tt_aV[CLOSEBTNCOLORS][i] = (i & 1) ? tt_aV[TITLEFONTCOLOR] : tt_aV[TITLEBGCOLOR]; } // Enforce titlebar be shown if(!tt_aV[TITLE].length) tt_aV[TITLE] = " "; } // Circumvents broken display of images and fade-in flicker in Geckos < 1.8 if(tt_aV[OPACITY] == 100 && typeof tt_aElt[0].style.MozOpacity != tt_u && !Array.every) tt_aV[OPACITY] = 99; // Smartly shorten the delay for fade-in tooltips if(tt_aV[FADEIN] && tt_flagOpa && tt_aV[DELAY] > 100) tt_aV[DELAY] = Math.max(tt_aV[DELAY] - tt_aV[FADEIN], 100); } function tt_AdaptConfig2() { if(tt_aV[CENTERMOUSE]) { tt_aV[OFFSETX] -= ((tt_w - (tt_aV[SHADOW] ? tt_aV[SHADOWWIDTH] : 0)) >> 1); tt_aV[JUMPHORZ] = false; } } // Expose content globally so extensions can modify it function tt_MkTipContent(a) { if(tt_t2t) { if(tt_aV[COPYCONTENT]) tt_sContent = tt_t2t.innerHTML; else tt_sContent = ""; } else tt_sContent = a[0]; tt_ExtCallFncs(0, "CreateContentString"); } function tt_MkTipSubDivs() { var sCss = 'position:relative;margin:0px;padding:0px;border-width:0px;left:0px;top:0px;line-height:normal;width:auto;', sCssCloseBtn = 'position:relative;margin:0px;padding:0px;border-width:0px;left:0px;top:0px;line-height:normal;width:10px;', sTbTrTd = ' cellspacing="0" cellpadding="0" border="0" style="' + sCss + '"><tbody style="' + sCss + '"><tr><td '; var sHeaCss = 'position:relative;margin:0px;padding:0px;border-width:0px;;left:0px;top:0px;line-height:normal;width:auto;' // WzTiTl e` il div che contiene Header tt_aElt[0].style.width = tt_GetClientW() + "px"; tt_aElt[0].innerHTML = ('' + (tt_aV[TITLE].length ? ('<div id="WzTiTl" class="ttTitle" style="position:relative;z-index:1;">' + '<table id="WzTiTlTb"' + sTbTrTd + 'id="WzTiTlI" style="' + sHeaCss + '">' + tt_aV[TITLE] + '</td>' // -------------------- Close Section X + (tt_aV[CLOSEBTN] ? ('<td align="right" style="' + sCssCloseBtn + ';text-align:right;">' + '<span id="WzClOsE" class="ttClose" style="position:relative;right:6px;padding-left:2px;padding-right:2px;' + 'cursor:' + (tt_ie ? 'hand' : 'pointer') + ';" onmouseover="tt_OnCloseBtnOver(1)" onmouseout="tt_OnCloseBtnOver(0)" onclick="UnTipFix()">' + tt_aV[CLOSEBTNTEXT] + '</span></td>') : '') + '</tr></tbody></table></div>') : '') + '<div id="WzBoDy" style="position:relative;z-index:0;">' + '<table' + sTbTrTd + 'id="WzBoDyI" style="' + sCss + '">' + tt_sContent // FUTURE FOOTER // + '</td></tr></tbody></table></div>' + '</td></tr>' // + (tt_aV[FOOTER].length ? '<tr><td><' + tt_aV[FOOTER] + '</td></tr>' : '') + (tt_aV[FOOTER].length ? '<tr><td class="tipfooter">' + tt_aV[FOOTER] + '</td></tr>' : '') + '</tbody></table></div>' + (tt_aV[SHADOW] ? ('<div id="WzTtShDwR" style="position:absolute;overflow:hidden;"></div>' + '<div id="WzTtShDwB" style="position:relative;overflow:hidden;"></div>') : '') ); tt_GetSubDivRefs(); // Convert DOM node to tip if(tt_t2t && !tt_aV[COPYCONTENT]) tt_El2Tip(); tt_ExtCallFncs(0, "SubDivsCreated"); // jsu_logHtml('WzTiTl', tt_aElt[0].innerHTML); } function tt_GetSubDivRefs() { var aId = new Array("WzTiTl", "WzTiTlTb", "WzTiTlI", "WzClOsE", "WzBoDy", "WzBoDyI", "WzTtShDwB", "WzTtShDwR"); for(var i = aId.length; i; --i) tt_aElt[i] = tt_GetElt(aId[i - 1]); } /* * Format the Tip: Calculate width, height,.. */ function tt_FormatTip() { var fn = "[tooltip.js tt_FormatTip] "; var css, w, h, pad = tt_aV[PADDING], padT, wBrd = tt_aV[BORDERWIDTH], iOffY, iOffSh, iAdd = (pad + wBrd) << 1; //--------- Title DIV ---------- if(tt_aV[TITLE].length) { padT = tt_aV[TITLEPADDING]; css = tt_aElt[1].style; css.background = tt_aV[TITLEBGCOLOR]; css.paddingTop = css.paddingBottom = padT + "px"; css.paddingLeft = css.paddingRight = (padT + 2) + "px"; css = tt_aElt[3].style; css.color = tt_aV[TITLEFONTCOLOR]; if(tt_aV[WIDTH] == -1) css.whiteSpace = "nowrap"; css.fontFamily = tt_aV[TITLEFONTFACE]; css.fontSize = tt_aV[TITLEFONTSIZE]; css.fontWeight = "bold"; css.textAlign = tt_aV[TITLEALIGN]; // Close button DIV if(tt_aElt[4]) { css = tt_aElt[4].style; css.background = tt_aV[CLOSEBTNCOLORS][0]; css.color = tt_aV[CLOSEBTNCOLORS][1]; css.fontFamily = tt_aV[TITLEFONTFACE]; css.fontSize = tt_aV[TITLEFONTSIZE]; css.fontWeight = "bold"; } if(tt_aV[WIDTH] > 0) tt_w = tt_aV[WIDTH]; else { tt_w = tt_GetDivW(tt_aElt[3]) + tt_GetDivW(tt_aElt[4]); // Some spacing between title DIV and closebutton if(tt_aElt[4]) tt_w += pad; // Restrict auto width to max width if(tt_aV[WIDTH] < -1 && tt_w > -tt_aV[WIDTH]) tt_w = -tt_aV[WIDTH]; } // Ensure the top border of the body DIV be covered by the title DIV iOffY = -wBrd; } else { tt_w = 0; iOffY = 0; } //-------- Body DIV ------------ css = tt_aElt[5].style; css.top = iOffY + "px"; if(wBrd) { css.borderColor = tt_aV[BORDERCOLOR]; css.borderStyle = tt_aV[BORDERSTYLE]; css.borderWidth = wBrd + "px"; } if(tt_aV[BGCOLOR].length) css.background = tt_aV[BGCOLOR]; if(tt_aV[BGIMG].length) css.backgroundImage = "url(" + tt_aV[BGIMG] + ")"; css.padding = pad + "px"; css.textAlign = tt_aV[TEXTALIGN]; if(tt_aV[HEIGHT]) { css.overflow = "auto"; if(tt_aV[HEIGHT] > 0) css.height = (tt_aV[HEIGHT] + iAdd) + "px"; else tt_h = iAdd - tt_aV[HEIGHT]; } // TD inside body DIV css = tt_aElt[6].style; css.color = tt_aV[FONTCOLOR]; css.fontFamily = tt_aV[FONTFACE]; css.fontSize = tt_aV[FONTSIZE]; css.fontWeight = tt_aV[FONTWEIGHT]; css.textAlign = tt_aV[TEXTALIGN]; if(tt_aV[WIDTH] > 0) w = tt_aV[WIDTH]; // Width like title (if existent) else if(tt_aV[WIDTH] == -1 && tt_w) w = tt_w; else { // Measure width of the body's inner TD, as some browsers would expand // the container and outer body DIV to 100% w = tt_GetDivW(tt_aElt[6]); // Restrict auto width to max width if(tt_aV[WIDTH] < -1 && w > -tt_aV[WIDTH]) w = -tt_aV[WIDTH]; } if(w > tt_w) tt_w = w; tt_w += iAdd; //--------- Shadow DIVs ------------ if(tt_aV[SHADOW]) { tt_w += tt_aV[SHADOWWIDTH]; iOffSh = Math.floor((tt_aV[SHADOWWIDTH] * 4) / 3); // Bottom shadow css = tt_aElt[7].style; css.top = iOffY + "px"; css.left = iOffSh + "px"; css.width = (tt_w - iOffSh - tt_aV[SHADOWWIDTH]) + "px"; css.height = tt_aV[SHADOWWIDTH] + "px"; css.background = tt_aV[SHADOWCOLOR]; // Right shadow css = tt_aElt[8].style; css.top = iOffSh + "px"; css.left = (tt_w - tt_aV[SHADOWWIDTH]) + "px"; css.width = tt_aV[SHADOWWIDTH] + "px"; css.background = tt_aV[SHADOWCOLOR]; } else iOffSh = 0; //-------- Container DIV ------- tt_SetTipOpa(tt_aV[FADEIN] ? 0 : tt_aV[OPACITY]); tt_FixSize(iOffY, iOffSh); } // Fixate the size so it can't dynamically change while the tooltip is moving. function tt_FixSize(iOffY, iOffSh) { var wIn, wOut, h, add, pad = tt_aV[PADDING], wBrd = tt_aV[BORDERWIDTH], i; tt_aElt[0].style.width = tt_w + "px"; tt_aElt[0].style.pixelWidth = tt_w; wOut = tt_w - ((tt_aV[SHADOW]) ? tt_aV[SHADOWWIDTH] : 0); // Body wIn = wOut; if(!tt_bBoxOld) wIn -= (pad + wBrd) << 1; tt_aElt[5].style.width = wIn + "px"; // Title if(tt_aElt[1]) { wIn = wOut - ((tt_aV[TITLEPADDING] + 2) << 1); if(!tt_bBoxOld) wOut = wIn; tt_aElt[1].style.width = wOut + "px"; tt_aElt[2].style.width = wIn + "px"; } // Max height specified if(tt_h) { h = tt_GetDivH(tt_aElt[5]); if(h > tt_h) { if(!tt_bBoxOld) tt_h -= (pad + wBrd) << 1; tt_aElt[5].style.height = tt_h + "px"; } } tt_h = tt_GetDivH(tt_aElt[0]) + iOffY; // Right shadow if(tt_aElt[8]) tt_aElt[8].style.height = (tt_h - iOffSh) + "px"; i = tt_aElt.length - 1; if(tt_aElt[i]) { tt_aElt[i].style.width = tt_w + "px"; tt_aElt[i].style.height = tt_h + "px"; } } function tt_DeAlt(el) { var aKid; if(el) { if(el.alt) el.alt = ""; if(el.title) el.title = ""; aKid = el.childNodes || el.children || null; if(aKid) { for(var i = aKid.length; i;) tt_DeAlt(aKid[--i]); } } } // This hack removes the native tooltips over links in Opera function tt_OpDeHref(el) { if(!tt_op) return; if(tt_elDeHref) tt_OpReHref(); while(el) { if(el.hasAttribute && el.hasAttribute("href")) { el.t_href = el.getAttribute("href"); el.t_stats = window.status; el.removeAttribute("href"); el.style.cursor = "hand"; tt_AddEvtFnc(el, "mousedown", tt_OpReHref); window.status = el.t_href; tt_elDeHref = el; break; } el = tt_GetDad(el); } } function tt_OpReHref() { if(tt_elDeHref) { tt_elDeHref.setAttribute("href", tt_elDeHref.t_href); tt_RemEvtFnc(tt_elDeHref, "mousedown", tt_OpReHref); window.status = tt_elDeHref.t_stats; tt_elDeHref = null; } } function tt_El2Tip() { var css = tt_t2t.style; // Store previous positioning tt_t2t.t_cp = css.position; tt_t2t.t_cl = css.left; tt_t2t.t_ct = css.top; tt_t2t.t_cd = css.display; // Store the tag's parent element so we can restore that DOM branch // when the tooltip is being hidden tt_t2tDad = tt_GetDad(tt_t2t); tt_MovDomNode(tt_t2t, tt_t2tDad, tt_aElt[6]); css.display = "block"; css.position = "static"; css.left = css.top = css.marginLeft = css.marginTop = "0px"; } function tt_UnEl2Tip() { // Restore positioning and display var css = tt_t2t.style; css.display = tt_t2t.t_cd; tt_MovDomNode(tt_t2t, tt_GetDad(tt_t2t), tt_t2tDad); css.position = tt_t2t.t_cp; css.left = tt_t2t.t_cl; css.top = tt_t2t.t_ct; tt_t2tDad = null; } function tt_OverInit() { if(window.event) tt_over = window.event.target || window.event.srcElement; else tt_over = tt_ovr_; tt_DeAlt(tt_over); tt_OpDeHref(tt_over); } function tt_ShowInit() { tt_tShow.Timer("tt_Show()", tt_aV[DELAY], true); if(tt_aV[CLICKCLOSE] || tt_aV[CLICKSTICKY]) tt_AddEvtFnc(document, "mouseup", tt_OnLClick); } function tt_Show() { var css = tt_aElt[0].style; // Override the z-index of the topmost wz_dragdrop.js D&D item // css.zIndex = Math.max((window.dd && dd.z) ? (dd.z + 2) : 0, 1010); css.zIndex = TIP_Z_INDEX; if(tt_aV[STICKY] || !tt_aV[FOLLOWMOUSE]) tt_iState &= ~0x4; if(tt_aV[EXCLUSIVE]) tt_iState |= 0x8; if(tt_aV[DURATION] > 0) tt_tDurt.Timer("tt_HideInit()", tt_aV[DURATION], true); tt_ExtCallFncs(0, "Show"); css.visibility = "visible"; tt_iState |= 0x2; if(tt_aV[FADEIN]) tt_Fade(0, 0, tt_aV[OPACITY], Math.round(tt_aV[FADEIN] / tt_aV[FADEINTERVAL])); tt_ShowIfrm(); } function tt_ShowIfrm() { if(tt_ie56) { var ifrm = tt_aElt[tt_aElt.length - 1]; if(ifrm) { var css = ifrm.style; css.zIndex = tt_aElt[0].style.zIndex - 1; css.display = "block"; } } } function tt_Move(e) { if(e) tt_ovr_ = e.target || e.srcElement; e = e || window.event; if(e) { tt_musX = tt_GetEvtX(e); tt_musY = tt_GetEvtY(e); } if(tt_iState & 0x4) { // Prevent jam of mousemove events if(!tt_op && !tt_ie) { if(tt_bWait) return; tt_bWait = true; tt_tWaitMov.Timer("tt_bWait = false;", 1, true); } if(tt_aV[FIX]) { tt_iState &= ~0x4; tt_PosFix(); } else if(!tt_ExtCallFncs(e, "MoveBefore")) tt_SetTipPos(tt_Pos(0), tt_Pos(1)); tt_ExtCallFncs([tt_musX, tt_musY], "MoveAfter"); } } function tt_Pos(iDim) { var iX, bJmpMod, cmdAlt, cmdOff, cx, iMax, iScrl, iMus, bJmp; // Map values according to dimension to calculate if(iDim) { bJmpMod = tt_aV[JUMPVERT]; cmdAlt = ABOVE; cmdOff = OFFSETY; cx = tt_h; iMax = tt_maxPosY; iScrl = tt_GetScrollY(); iMus = tt_musY; bJmp = tt_bJmpVert; } else { bJmpMod = tt_aV[JUMPHORZ]; cmdAlt = LEFT; cmdOff = OFFSETX; cx = tt_w; iMax = tt_maxPosX; iScrl = tt_GetScrollX(); iMus = tt_musX; bJmp = tt_bJmpHorz; } if(bJmpMod) { if(tt_aV[cmdAlt] && (!bJmp || tt_CalcPosAlt(iDim) >= iScrl + 16)) iX = tt_PosAlt(iDim); else if(!tt_aV[cmdAlt] && bJmp && tt_CalcPosDef(iDim) > iMax - 16) iX = tt_PosAlt(iDim); else iX = tt_PosDef(iDim); } else { iX = iMus; if(tt_aV[cmdAlt]) iX -= cx + tt_aV[cmdOff] - (tt_aV[SHADOW] ? tt_aV[SHADOWWIDTH] : 0); else iX += tt_aV[cmdOff]; } // Prevent tip from extending past clientarea boundary if(iX > iMax) iX = bJmpMod ? tt_PosAlt(iDim) : iMax; // In case of insufficient space on both sides, ensure the left/upper part // of the tip be visible if(iX < iScrl) iX = bJmpMod ? tt_PosDef(iDim) : iScrl; return iX; } function tt_PosDef(iDim) { var fn = "[tooltip.js tt_PosDef] "; if(iDim) tt_bJmpVert = tt_aV[ABOVE]; else tt_bJmpHorz = tt_aV[LEFT]; return tt_CalcPosDef(iDim); } function tt_PosAlt(iDim) { if(iDim) tt_bJmpVert = !tt_aV[ABOVE]; else tt_bJmpHorz = !tt_aV[LEFT]; return tt_CalcPosAlt(iDim); } function tt_CalcPosDef(iDim) { var fn = "[tooltip.js tt_CalcPosDef] "; var iRet = iDim ? (tt_musY + tt_aV[OFFSETY]) : (tt_musX + tt_aV[OFFSETX]); return iRet; } function tt_CalcPosAlt(iDim) { var cmdOff = iDim ? OFFSETY : OFFSETX; var dx = tt_aV[cmdOff] - (tt_aV[SHADOW] ? tt_aV[SHADOWWIDTH] : 0); if(tt_aV[cmdOff] > 0 && dx <= 0) dx = 1; return((iDim ? (tt_musY - tt_h) : (tt_musX - tt_w)) - dx); } /* * JSU Modify */ function tt_PosFix() { var fn = "[tooltip.js tt_PosFix] "; var iX=0, iY; var iXPos; var bXPosRelative = false; if(typeof(tt_aV[FIX][0]) == "number") { iX = tt_aV[FIX][0]; iY = tt_aV[FIX][1]; } else { // -------------- First is id if(typeof(tt_aV[FIX][0]) == "string") el = tt_GetElt(tt_aV[FIX][0]); // First slot in array is direct reference to HTML element else el = tt_aV[FIX][0]; iXPos = tt_aV[FIX][1]; bXPosRelative = (iXPos == TIP_FIXED_POS.LEFT || iXPos == TIP_FIXED_POS.CENTER || iXPos == TIP_FIXED_POS.RIGHT); jsu_log (fn + "iXPos=" + iXPos + " bXPosRelative=" + bXPosRelative); if (!bXPosRelative){ iX=iXPos; } iY = tt_aV[FIX][2]; // By default, vert pos is related to bottom edge of HTML element if(!tt_aV[ABOVE] && el) iY += tt_GetDivH(el); for(; el; el = el.offsetParent) { iX += el.offsetLeft || 0; iY += el.offsetTop || 0; } // if (bXPosRelative){ jsu_log (fn + "iXPos=" + iXPos + " Calculate new iX From iX=" + iX+ " tt_w=" + tt_w); // +25 for workaround to align better if (iXPos == TIP_FIXED_POS.LEFT){ iX = iX -tt_w + 25; }else if (iXPos == TIP_FIXED_POS.CENTER){ iX = iX - (tt_w/2) + 20; } } } // For a fixed tip positioned above the mouse, use the bottom edge as anchor if(tt_aV[ABOVE]){ iY -= tt_h; }else{ jsu_log (fn + "TIP BELOW: Add DeltaY=" + tt_tipFix.yIncDelta); iY += tt_tipFix.yIncDelta; } jsu_log (fn + "SET iX=" + iX + " iY=" + iY); tt_SetTipPos(iX, iY); } function tt_Fade(a, now, z, n) { if(n) { now += Math.round((z - now) / n); if((z > a) ? (now >= z) : (now <= z)) now = z; else tt_tFade.Timer( "tt_Fade(" + a + "," + now + "," + z + "," + (n - 1) + ")", tt_aV[FADEINTERVAL], true ); } now ? tt_SetTipOpa(now) : tt_Hide(); } function tt_SetTipOpa(opa) { // To circumvent the opacity nesting flaws of IE, we set the opacity // for each sub-DIV separately, rather than for the container DIV. tt_SetOpa(tt_aElt[5], opa); if(tt_aElt[1]) tt_SetOpa(tt_aElt[1], opa); if(tt_aV[SHADOW]) { opa = Math.round(opa * 0.8); tt_SetOpa(tt_aElt[7], opa); tt_SetOpa(tt_aElt[8], opa); } } function tt_OnCloseBtnOver(iOver) { var css = tt_aElt[4].style; iOver <<= 1; css.background = tt_aV[CLOSEBTNCOLORS][iOver]; css.color = tt_aV[CLOSEBTNCOLORS][iOver + 1]; } function tt_OnLClick(e) { // Ignore right-clicks e = e || window.event; if(!((e.button && e.button & 2) || (e.which && e.which == 3))) { if(tt_aV[CLICKSTICKY] && (tt_iState & 0x4)) { tt_aV[STICKY] = true; tt_iState &= ~0x4; } else if(tt_aV[CLICKCLOSE]) tt_HideInit(); } } function tt_Int(x) { var y; return(isNaN(y = parseInt(x)) ? 0 : y); } Number.prototype.Timer = function(s, iT, bUrge) { if(!this.value || bUrge) this.value = window.setTimeout(s, iT); }; Number.prototype.EndTimer = function() { if(this.value) { window.clearTimeout(this.value); this.value = 0; } }; function tt_GetWndCliSiz(s) { var db, y = window["inner" + s], sC = "client" + s, sN = "number"; if(typeof y == sN) { var y2; return( // Gecko or Opera with scrollbar // ... quirks mode ((db = document.body) && typeof(y2 = db[sC]) == sN && y2 && y2 <= y) ? y2 // ... strict mode : ((db = document.documentElement) && typeof(y2 = db[sC]) == sN && y2 && y2 <= y) ? y2 // No scrollbar, or clientarea size == 0, or other browser (KHTML etc.) : y ); } // IE return( // document.documentElement.client+s functional, returns > 0 ((db = document.documentElement) && (y = db[sC])) ? y // ... not functional, in which case document.body.client+s // is the clientarea size, fortunately : document.body[sC] ); } function tt_SetOpa(el, opa) { var css = el.style; tt_opa = opa; if(tt_flagOpa == 1) { if(opa < 100) { // Hacks for bugs of IE: // 1.) Once a CSS filter has been applied, fonts are no longer // anti-aliased, so we store the previous 'non-filter' to be // able to restore it if(typeof(el.filtNo) == tt_u) el.filtNo = css.filter; // 2.) A DIV cannot be made visible in a single step if an // opacity < 100 has been applied while the DIV was hidden var bVis = css.visibility != "hidden"; // 3.) In IE6, applying an opacity < 100 has no effect if the // element has no layout (position, size, zoom, ...) css.zoom = "100%"; if(!bVis) css.visibility = "visible"; css.filter = "alpha(opacity=" + opa + ")"; if(!bVis) css.visibility = "hidden"; } else if(typeof(el.filtNo) != tt_u) // Restore 'non-filter' css.filter = el.filtNo; } else { opa /= 100.0; switch(tt_flagOpa) { case 2: css.KhtmlOpacity = opa; break; case 3: css.KHTMLOpacity = opa; break; case 4: css.MozOpacity = opa; break; case 5: css.opacity = opa; break; } } } function tt_Err(szErr) { if (typeof (showErr) == "function"){ showErr (szErr); }else{ alert(szErr); } } //============ EXTENSION (PLUGIN) MANAGER ===============// function tt_ExtCmdEnum() { var s; // Add new command(s) to the commands enum for(var i in config) { s = "window." + i.toString().toUpperCase(); if(eval("typeof(" + s + ") == tt_u")) { eval(s + " = " + tt_aV.length); tt_aV[tt_aV.length] = null; } } } /*------------------------------------------------------------- Replace all occurrences of from with to @param szOrig in @param from in e.g "&nbsp;" @param to in e.g " " @return --------------------------------------------------------------*/ function tt_replaceAll (szOrig,szFrom,szTo){ var szNew = szOrig; while (szNew.indexOf(szFrom) >=0){ szNew = szNew.replace (szFrom,szTo); } return szNew; } /* * Convert NewLine to <BR/> * @param szMsg * @returns */ function tt_NL2BR(szMsg){ return tt_replaceAll (szMsg,"\n","<BR/>"); } function tt_ExtCallFncs(arg, sFnc) { var b = false; for(var i = tt_aExt.length; i;) {--i; var fnc = tt_aExt[i]["On" + sFnc]; // Call the method the extension has defined for this event if(fnc && fnc(arg)) b = true; } return b; } // function getMouseXY(e, obj) { var e = (!e) ? window.event : e; //find mouse coordinates if (e.pageX || e.pageY) { posX = e.pageX; posY = e.pageY; } else if (e.clientX || e.clientY) { if (document.body.scrollLeft || document.body.scrollTop) { posX = e.clientX + document.body.scrollLeft; posY = e.clientY + document.body.scrollTop; } else { posX = e.clientX + document.documentElement.scrollLeft; posY = e.clientY + document.documentElement.scrollTop; } } else { posX = 0; posY = 0; } //find image coordinates if (obj.offsetLeft || obj.offsetTop) { xOffset = obj.offsetLeft; yOffset = obj.offsetTop; parentObj = obj.offsetParent; while(parentObj != null) { xOffset += parentObj.offsetLeft; yOffset += parentObj.offsetTop; parentObj = parentObj.offsetParent; } } else if (obj.x || obj.y) { xOffset = obj.x; yOffset = obj.y; } else { xOffset = 0; yOffset = 0; } var imgPosY = (posY - yOffset - 2); var imgPosX = (posX - xOffset - 2); return { x: imgPosX, y: imgPosY }; } function tt_is_IE(){ var APP_NAME_IE="Microsoft Internet Explorer"; // IE var APP_NAME_IE_11="Netscape"; // IE 11 if ((navigator.appName == APP_NAME_IE) || ((navigator.appName == APP_NAME_IE_11) && (new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})").exec(navigator.userAgent) != null))){ return true; }else { return false; } } /* * Check if prettify has been loaded * @returns {Boolean} */ function tt_isPrettifyPresent(){ var fn = "[tooltip.js tt_isPrettifyPresent()] "; var bPrettifyLoaded = (typeof(jsuPrettyPrint) != "undefined"); var bPrettifyCode = false; // Code present. Default = false (FREE version) bPrettifyCode = true; var bPrettifyEn = (bPrettifyLoaded && bPrettifyCode); jsu_log (fn + "bPrettifyLoaded=" + bPrettifyLoaded + " bPrettifyCode=" + bPrettifyCode + " RETURN bPrettifyEn=" + bPrettifyEn); return bPrettifyEn; } /* * * @param szHtml * @returns Number of /n */ function tt_getHtmlRowNum(szHtml){ var iRowNum = 1 + (szHtml.match(/\n/g) || []).length; if (iRowNum > TIP_MAX_TEXT_BOX_ROW_NUM){ iRowNum = TIP_MAX_TEXT_BOX_ROW_NUM; } return iRowNum; } <file_sep>/core/googleAnal.js /** @fileOverview ========================================================================================= <BR/> <b>File:</b> core/googleAnal.js <BR/> <b>Author:</b> <a href="https://www.linkedin.com/in/federicolevis" target="_self"><NAME></a> <BR/> <b>Google Analytics Doc:</b> <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/HTML/GoogleAnalytics.html" target="_self">JSU GoogleAnalytics Documentation</a> <BR/> <b>JSU API Doc:</b> <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/JSUAPI.html" target="_self">JSU API Documentation</a> <BR/> <b>Description:</b> JSU Google Analytics API <BR/> <b>REQUIRED:</b> JSU: jsu.css locale-core.js jsuCmn.js tooltip.js <BR/> <b>OPTIONAL:</b> JSU: jslog.js dom-drag.js if you want to use jslog <BR/> <b>First Version:</b> ver 1.0 - Feb 2014 <BR/> <b>Current Version:</b> JSU v. 1.10 &nbsp;&nbsp;&nbsp;2018-Jan-14 <BR/> <BR/>-----------------------------------------------------------------------------------<BR/> <b>DISCLAIMER</b> <BR/> Copyright by <NAME> - <a href="https://github.com/FedericoLevis/JSU" target="_self">JSU</a> <BR/> This file may be freely distributed under the MIT license. <BR/> ========================================================================================= <BR/> */ /*========================================================================================= * GLOBAl CONST ========================================================================================= */ /** * Parameter szParTime of gai.js API: * <ul> * <li>GA_PAR_TIME.all_time</li> * <li>GA_PAR_TIME.month</li> * <li>GA_PAR_TIME.week</li> * <li>GA_PAR_TIME.day</li> * <li>GA_PAR_TIME.two_hours</li> * </ul> */ var GA_PAR_TIME={ all_time:'all_time', month: 'month', week: 'week', day: 'day', two_hours: 'two_hours' }; /** * Default Value of googleAnal.js par */ var GA_DEF = { JSPOPUP: false, ALL_LINK: true, // default: Present the Link to display all the pages of Google analytics together WIDTH: 700, // Box Width TBL_MAX_HEIGHT: 300, // if more lines there will be scroolbar SHOW_CB_SHORT_URL: true, // Show CB SHOW_CB_LONG_URL: true, // Show CB SHORT_URL: false, LONG_URL: false, PAR_TIME: GA_PAR_TIME.all_time, NEW_WINDOW: true }; /*========================================================================================= * LOCAL CONST ========================================================================================= */ var TMO_GA_CLICK_SIMUL_MS = 200; // Global For GoogleAnal var ga_var = { arObjGaList: null, // arObjGaList received as PAR bShortUrl: false, bLongUrl: false, iTipWidth: 700, iVisibleLink: 0, //used by onclickBtnAllGoogle arszIdVis: new Array(), iSelFilterCat: 0 , // Current FilterCat szParTime: GA_PAR_TIME.all_time, // Current FilterType iLinkClickCur:0, // for Click Simulation in case of OPERA/SAFARI: current index (we have to arrivi till iVisibleLink-1 tmoClick: null }; var GA_LINK_SEP="&nbsp;&nbsp;&nbsp;"; var GALOG_FUN_START = " ------------- START"; var GALOG_FUN_END = " ------------- END"; // Div with hidden anchor var GA_DIV_HIDDEN_ID = "jsuDivHidden"; var GA_HREF_HIDDEN_ID = "jsuHrefHidden"; // init to whatver href, then it will be changed run-time var GA_HREF_HIDDEN = '<a id="' + GA_HREF_HIDDEN_ID +'" target="_self" style="display:none" href="https://goo.gl/HnNqnM" >HIDDEN</a>'; //===================== PUBLIC =============================================// /** * Display in a FixedTip/JQPopup an UserFriendly Table with the Link to Google Analytics of Short Url gaa.gl. The Table is UserFriendly (Sort, Filters, Show/Hide Columns,..) * @param arObjGaList {Array} Array of Object that identify the Google Analytics. See Exmple Below * @param event * @param [objOpt] {Object} <table class="jsDocGood" border="3" cellpadding="2" cellspacing="2"> <tr ><td class="jsDocTitleGood">OPTION Always Available (FREE and FULL JSU)</td></tr> <tr><td class="jsDocParam"> <ul> <li> bJQPopup {Boolean} [false] <ul> <li> false: with his default value, the Box will be open in a FixedTip</li> <li> true: the Box will be open inside a JQPopup </li> </ul> <li> iWidth {Number}: [GA_DEF.WIDTH] Width default GA_DEF.WIDTH (1200) </li> <li> iTblMaxHeight {Number}: [GA_DEF.TBL_MAX_HEIGHT] You can set this max-height of the Tbl to limit the Height of the Box, that is automatically. </li> <li> szTitle{String} default: 'Google Analytics' </li> <li> bShowCbShortUrl {Boolean} [true] CheckBox to Show the column with ShortUrl: if true the CheckBox is visible <li> bShowCbLongUrl {Boolean} [true] CheckBox to Show Show the colum with LongUrl: if true the CheckBox is visible <li> bShortUrl {Boolean} [false] Initial value of the CheckBox to Show the column with ShortUrl <li> bLongUrl {Boolean} [false] Initial value of the CheckBox to Show the column with ShortUrl <li> szHeaderTxt {String}: [DEF_GA_LABEL.HEADER] Message to put before the Table of Link to Analytics. You can set "" to remove it <li> szFooterTxt {String}: [DEF_GA_LABEL.FOOTER] Message to put after the Table of Link to Analytics. You can set "" to remove it <li> szParTime {String}: [GA_PAR_TIME.all_time] Default ParTime ar Startup. &nbsp;see <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/googleAnal.js/global.html#GA_PAR_TIME" target="_self">GA_PAR_TIME</a> </li> </ul> </td></tr> </table> @example //--------------------------------------------------------- HTML <input type="button" class="googleAnalList" id="googleAnalList1" onclick="jsuGoogleAnalList(event)" /> // --------------------------------- JS function jsuGoogleAnalList(event){ var GA_CAT_DOWN = "JSU DOWNLOAD"; var GA_CAT_SAMPLE_FREE = "JSU FREE - SAMPLES"; var GA_CAT_DOC_FREE = "JSU FREE - DOC"; // Prepare arObjGaList: only shortUrl is mandatory // In this case we populate all fields var arObjGaList = [ {shortUrl: JSU_SHORT_URL_DOWNLOAD_FREE, longUrl: JSU_LONG_URL_DOWNLOAD_PAGE_FREE , cat:GA_CAT_DOWN,desc:'Download JSU.ZIP FREE'}, {shortUrl: JSU_SHORT_URL_SAMPLE_ALL, longUrl: JSU_LONG_URL_SAMPLE_ALL,cat:GA_CAT_SAMPLE_FREE, desc:'Main JSU Sample'}, {shortUrl: JSU_SHORT_URL_SAMPLE_TIP, longUrl: JSU_LONG_URL_SAMPLE_TIP,cat:GA_CAT_SAMPLE_FREE, desc:'Tooltip Sample'}, {shortUrl: JSU_SHORT_URL_SAMPLE_LOADING, longUrl: JSU_LONG_URL_SAMPLE_LOADING, cat:GA_CAT_SAMPLE_FREE,desc:'LoadingDiv Sample'}, {shortUrl: JSU_SHORT_URL_SAMPLE_JSLOG, longUrl: JSU_LONG_URL_SAMPLE_JSLOG, cat:GA_CAT_SAMPLE_FREE,desc:'JSLog Sample'}, {shortUrl: JSU_SHORT_URL_SAMPLE_SORT, longUrl: JSU_LONG_URL_SAMPLE_SORT, cat:GA_CAT_SAMPLE_FREE, desc:'SortTable Sample'}, {shortUrl: JSU_SHORT_URL_SAMPLE_IEPOPUP, longUrl: JSU_LONG_URL_SAMPLE_IEPOPUP, cat:GA_CAT_SAMPLE_FREE,desc:'IE Popup Sample'}, // -------------------------- {shortUrl: JSU_SHORT_URL_DOC, longUrl: JSU_LONG_URL_DOC, cat:GA_CAT_DOC_FREE,desc:'JSU Documentation'}, {shortUrl: JSU_SHORT_URL_DOC_TIP, longUrl: JSU_LONG_URL_DOC_TIP, cat:GA_CAT_DOC_FREE,desc:'JSU Tooltip Documentation'}, {shortUrl: JSU_SHORT_URL_DOC_LOADING, longUrl: JSU_LONG_URL_DOC_LOADING, cat:GA_CAT_DOC_FREE,desc:'JSU LoadingDiv Documentation'}, {shortUrl: JSU_SHORT_URL_DOC_JSLOG, longUrl: JSU_LONG_URL_DOC_JSLOG, cat:GA_CAT_DOC_FREE,desc:'JSU JSLog Doc'}, {shortUrl: JSU_SHORT_URL_DOC_SORT, longUrl: JSU_LONG_URL_DOC_SORT, cat:GA_CAT_DOC_FREE,desc:'JSU SortTable Documentation'}, {shortUrl: JSU_SHORT_URL_DOC_IEPOPUP, longUrl: JSU_LONG_URL_DOC_IEPOPUP, cat:GA_CAT_DOC_FREE,desc:'JSU IE Popup Doc'} ]; // show the TipFix with the List of Link gaShortUrlList(arObjGaList,event,{ bJQPopup: false, szTitle:'JSU Google Analitycs', iWidth: opt_ga_list.iWidth, // Width of the Box iTblMaxHeight: opt_ga_list.iTblMaxHeight, // Max Height of the Table with the LIst of Google Analitycs Links szParTime: opt_ga_list.szParTime, // Initial Par Time bShortUrl: opt_ga_list.bShortUrl, // ShortUrl true or False bLongUrl: opt_ga_list.bLongUrl // LongUrl true or False }); } */ function gaShortUrlList(arObjGaList, event, objOpt){ var fn = "[googleAnal.js gaShortUrlList()] "; jsu_log (fn + GALOG_FUN_START); jsu_logObj (fn + "IN arObjGaList", arObjGaList); jsu_logObj (fn + "IN objOpt", objOpt); // -------- FREE/FULL JSU Management - only some Options are available in FREE Version: iWidth iTblMaxWidth // We Setup objOptTmp with default values, useful for FREE JSU case var objOptSet = { iTipWidth: GA_DEF.WIDTH, iWidth: GA_DEF.WIDTH, bJQPopup: GA_DEF.JSPOPUP, szTitle: GA_LABEL.DEF_TITLE, // --- only in FULL bAllBtn : GA_DEF.ALL_LINK, szHeaderTxt : GA_LABEL.DEF_HEADER, szFooterTxt : GA_LABEL.DEF_FOOTER, bShowCbShortUrl: GA_DEF.SHOW_CB_SHORT_URL, bShowCbLongUrl : GA_DEF.SHOW_CB_LONG_URL, bShortUrl: GA_DEF.SHORT_URL, bLongUrl : GA_DEF.LONG_URL, bShortUrl: GA_DEF.SHORT_URL, bLongUrl : GA_DEF.LONG_URL, iTblMaxHeight : GA_DEF.TBL_MAX_HEIGHT, szParTime : GA_DEF.PAR_TIME } if (objOpt == undefined){ objOpt = new Object(); } //----------- Set Fields Available also in FREE JSU if (objOpt.iTblMaxHeight != undefined){ objOptSet.iTblMaxHeight = objOpt.iTblMaxHeight; } if (objOpt.iWidth != undefined){ // set the 2 different fields objOptSet.iTipWidth= objOpt.iWidth; objOptSet.iWidth= objOpt.iWidth; } if (objOpt.bJQPopup != undefined){objOptSet.bJQPopup = objOpt.bJQPopup; } if (objOpt.szTitle != undefined){ objOptSet.szTitle = objOpt.szTitle; } if (objOpt.bAllGoogleAnalLink != undefined){ objOptSet.bAllBtn = objOpt.bAllBtn; } if (objOpt.szHeaderTxt != undefined){ objOptSet.szHeaderTxt = objOpt.szHeaderTxt; } if (objOpt.szFooterTxt != undefined){ objOptSet.szFooterTxt = objOpt.szFooterTxt; } if (objOpt.bShortUrl != undefined){ objOptSet.bShortUrl= objOpt.bShortUrl; } if (objOpt.bLongUrl != undefined){ objOptSet.bLongUrl = objOpt.bLongUrl; } if (objOpt.bShowCbShortUrl != undefined){ objOptSet.bShowCbShortUrl= objOpt.bShowCbShortUrl; } if (objOpt.bShowCbLongUrl != undefined){ objOptSet.bShowCbLongUrl = objOpt.bShowCbLongUrl; } if (objOpt.szParTime != undefined){ objOptSet.szParTime = objOpt.szParTime; } jsu_logObj (fn + "objOptSet", objOptSet); if (objOptSet.bJQPopup){ // ------------- Specific options for Popup // First of ALL: we check if Popup can be used: if (typeof(Popup) == undefined || isIEPopup()){ return alert ("SW ERROR: gaShortUrlList() with bJQPopup option set, but JQPopup is not loaded!"); } jsu_log ("JQPopup MODE is required. Popup() will be open"); }else{ // ------------- Specific options for TipFix objOptSet.bCloseBtn = true; objOptSet.iTipWidth = objOptSet.iWidth; } UnTip(event); // Untip (if a Tip was currently displayed) jsu_log ("Prepare HTML Msg with the Box Layout that will be displayed..."); // Set Global var ga_var.iTblWidth = objOptSet.iWidth - 20; // -20 for some lateral space ga_var.iTblMaxHeight = objOptSet.iTblMaxHeight; ga_var.bShortUrl = objOptSet.bShortUrl; ga_var.bLongUrl = objOptSet.bLongUrl; ga_var.szParTime = objOptSet.szParTime; ga_var.arObjGaList = arObjGaList; // Set in Global // Get the possible categories, for filter var arCat = new Array(); arCat.push (GA_LABEL.FILTER_CAT_ALL); for (var i=0; i< arObjGaList.length; i++){ var szCat = arObjGaList[i].cat; var bPresent = false; for (var k=0;k < arCat.length && !bPresent; k++){ if (arCat[k] == szCat){ bPresent = true; } } jsu_log (fn + "szCat=" + szCat + " bPresent=" + bPresent); if (!bPresent){ arCat.push(szCat); } } jsu_logObj (fn + "arCat=", arCat); ga_var.bJQPopup = objOptSet.bJQPopup; ga_var.arFilterCat = arCat; ga_var.iSelFilterCat = 0; // ALL var szTbl = '<table class="detNoBorder">'; // --------------------------- HEADER var szCbShortUrl = ""; var szCbLongUrl = ""; jsu_log ("Prepare CB Short URL - bShowCbShortUrl=" + objOptSet.bShowCbShortUrl); if (objOptSet.bShowCbShortUrl){ var szShortChecked = (ga_var.bShortUrl) ? "checked" : ""; szCbShortUrl = '<input type="checkbox" id="cbShortUrl" ' + szShortChecked + ' onclick="ga_onclickShortUrl();"/>Show ShortUrl '; } jsu_log ("Prepare CB Short URL - bShowCbLongUrl=" + objOptSet.bShowCbLongUrl); if (objOptSet.bShowCbLongUrl){ var szLongChecked = (ga_var.bLongUrl) ? "checked" : ""; szCbLongUrl = '<input style="margin-left:20px" type="checkbox" id="cbLongUrl" ' + szLongChecked + ' onclick="ga_onclickLongUrl();" />Show LongUrl'; } szTbl += '<tr style="padding-top:5px;">' + '<td class="tiplBold" width="300px" style="padding-bottom:10px">'+ szCbShortUrl + szCbLongUrl + '</td>' + '<td class="tipr" style="padding-right:10px;padding-bottom:10px">' + objOptSet.szHeaderTxt + '</td>' + '</tr>'; // Prepare the div that will contain the GoogleTable szTbl += '<tr><td colspan="2"> <div id="divTblGA" style="width:' + ga_var.iTblWidth + 'px;max-height:' + ga_var.iTblMaxHeight + 'px;overflow:auto;border: 1px solid;"></div></td></tr>' + // Row for All Google Analytics Link '<tr><td colspan="2"> <div id="divAllGA" align="left" width="100%" style="width:100%;margin-top:10px;"></div></td></tr>'; // Footer if present if (objOptSet.szFooterTxt != ""){ var szTblNote = '<table class="note gaFooter"><tr> ' + ' <td><input class="note"></td> ' + ' <td> ' + objOptSet.szFooterTxt +'</td> ' + ' </tr></table> '; szTbl += '<tr style="padding-top:7px;padding-bottom:7px;"><td colspan="2" class="tipl">' + szTblNote + '</td></tr>'; } szTbl += '</table>'; if (objOptSet.bJQPopup){ Popup (POPUP_TYPE.INFO,szTbl,{ bShowImg:false, // always false szTitle: objOptSet.szTitle, iWidth: parseInt(objOptSet.iWidth)+30 // +30 for best layout and avoid scroolbar }); } else{ // Show Tip With Empty Table TipFix (szTbl,event,objOptSet); } ga_varTblShow(); jsu_log (fn + GALOG_FUN_END); } /** * Display the Page with Google analytics related to szShortUrl * @param szShortUrl {String} Short URL generated with <a class="tipLink" href="https://goo.gl/">https://goo.gl/</a> * @param [objOpt] {Object} * @param [objOpt] {Object} <table class="jsDoc" border="2" cellpadding="2" cellspacing="2"> <tr><td class="jsDocTitle">OPTION</td></tr> <tr><td class="jsDocParam"> <ul> <li> szParTime {String}: [GA_PAR_TIME.all_time] Default ParTime ar Startup. &nbsp;see <a href="https://rawgit.com/FedericoLevis/JSUDoc/master/googleAnal.js/global.html#GA_PAR_TIME" target="_self">GA_PAR_TIME</a> </li> <li> bNewWindow {Boolean} [true] if true show Google Analytics in a new Page </li> </ul> </td></tr> </table> @example //--------------------------------------------------------- HTML <input type="button" class="googleAnal" id="googleAnal" onclick="jsuGoogleAnalPage(event)" /> // --------------------------------- JS */ function gaShortUrlPage(szShortUrl, objOpt){ var fn = "[googleAnal.js gaShortUrlPage()] "; jsu_log (fn + GALOG_FUN_START); jsu_log (fn + "IN szShortUrl", szShortUrl); jsu_logObj (fn + "IN objOpt", objOpt); if (objOpt == undefined){ objOpt = new Object(); } //----------- Set Fields Available also in FREE JSU if (objOpt.szParTime == undefined){ objOpt.szParTime = GA_DEF.PAR_TIME; } if (objOpt.bNewWindow == undefined){ objOpt.bNewWindow = GA_DEF.NEW_WINDOW; } var szGaUrl = szShortUrl.replace('goo.gl','goo.gl/#analytics/goo.gl') + '/' + objOpt.szParTime; ga_GoToURL (szGaUrl,objOpt.bNewWindow); jsu_log (fn + GALOG_FUN_END); } /* -------------------------------------------------------------------------------------------------------------------------------------------------- * LOCAL FUNCTION --------------------------------------------------------------------------------------------------------------------------------------------------- */ /* * Show the Table with the Link to GoogleAnalytics, basing on current Filter * GLOBAL ga_var */ function ga_varTblShow (){ var fn = "[googleAnal.js ga_varTblShow()] "; jsu_log (fn + GALOG_FUN_START); var bSort = typeof (cSortTable) != "undefined"; // can we add cSortTable? Is It Loaded? var szTbl = '<table id="tblGoogle" class="det" BORDER="2" cellspacing="0" cellpadding="5" width="100%">'; // Table with COLUMN Desc, Long URL, Short URL, Go To Google Analytics var szTblHea = '<tr class="detTitle" >'; if (ga_var.bShortUrl){ szTblHea += '<td class="tipc detTitle" width="15%">' + GA_LABEL.SHORT_URL + '</td> '; } if (ga_var.bLongUrl){ szTblHea += '<td class="tipc detTitle" width="30%">' + GA_LABEL.LONG_URL + '</td> '; } szTblHea += '<td class="tipc detTitle" width="16%">' + GA_LABEL.CAT + '</td> '+ '<td class="tipc detTitle" width="21%">' + GA_LABEL.DESC + '</td> '+ '<td class="tipc detTitle" width="14%">' + GA_LABEL.ANAL + '</td> '+ '</tr>'; szTbl += szTblHea; // -------------------------- HEADER_2 with Filter e AnalMode iRowHeader = 2; var szSelectFilter = '<select class="detFilter" id="gaCat" title="' + GA_LABEL.FILTER_CAT_TITLE + '" style="width:100%;" onchange="ga_onchangeCat();">'; var arCat = ga_var.arFilterCat; for (var i=0;i<arCat.length; i++){ var szCat = arCat[i]; var szSelected = (i == ga_var.iSelFilterCat) ? "selected" : ""; var szOpt = '\n<option class="detFilter" value="' + szCat +'" ' + szSelected + ' >' + szCat + '</option>'; szSelectFilter +=szOpt; } szSelectFilter += '\n</select>'; //--- Filter for GoogleAnal Type (day,...) var szSelectParTime = '<select class="detFilter" id="gaFilterTime" title="' + GA_LABEL.PAR_TIME_TITLE + '" style="width:100%;" onchange="ga_onchangeTime();" > '; var arTypeOpt = [{value: GA_PAR_TIME.all_time, text:GA_LABEL.PAR_TIME_ALL}, {value: GA_PAR_TIME.month, text:GA_LABEL.PAR_TIME_MONTH}, {value: GA_PAR_TIME.week, text:GA_LABEL.PAR_TIME_WEEK}, {value: GA_PAR_TIME.day, text:GA_LABEL.PAR_TIME_DAY}, {value: GA_PAR_TIME.two_hours, text:GA_LABEL.PAR_TIME_2HOURS} ]; for (var i=0; i<arTypeOpt.length; i++){ var objOpt = arTypeOpt[i]; var szSelected = (objOpt.value == ga_var.szParTime) ? "selected" : ""; var szOpt = '\n<option class="detFilter" value="' + objOpt.value +'" ' + szSelected + ' >' + objOpt.text + '</option> '; szSelectParTime +=szOpt; } szSelectParTime += '\n</select>'; // jsu_logHtml (fn + "szSelectParTime",szSelectParTime); // ------------------------ add FilterCat var iColUrl = 0; if (ga_var.bShortUrl){ iColUrl++;} if (ga_var.bLongUrl){ iColUrl++;} var szTr = '<tr class="detFilter">'; if (iColUrl > 0){ szTr += '<td class="detFilter" colSpan="' + iColUrl + '" align="right" style="font-weight:normal;padding-right:5px;">' + // GA_LABEL.FILTER_CAT_HEADER + '</td>'; } szTr += '<td class="detFilter">' + szSelectFilter + '</td>' + '<td class="detFilter" align="right" font-weight:normal;style="padding-right:5px;">' + // GA_LABEL.PAR_TIME_HEADER + '</td>' + '<td class="detFilter">' + szSelectParTime + '</td>' + '</tr>'; szTbl += szTr; // --------------------------------------------- Insert the Link Rows // Insert only if Filter Match and SET Global .iVisibleLink ga_var.iVisibleLink = 0; // Global jsu_logObj (fn , "iSelFilterCat =" + ga_var.iSelFilterCat); var arObj = ga_var.arObjGaList; var szCatSel = ga_var.arFilterCat[ga_var.iSelFilterCat]; jsu_logObj (fn + "szCatSel=" + szCatSel + " arFilterCat=", ga_var.arFilterCat); for (var i=0; i< arObj.length; i++){ var objGoogle = arObj[i]; var szCat = objGoogle.cat; // Check if we haev to show this cat: bFilterCat must be set and the cat must match the Filter (iSelFilterCat=0 means ALL Categories FILTER) var bShow = (ga_var.iSelFilterCat == 0 || szCat == szCatSel); jsu_log (fn + "FilterSel=" + szCatSel + " Cur cat=" + szCat + " --> bShow=" + bShow); if (bShow){ var szId = "a_ga" + ga_var.iVisibleLink; ga_var.arszIdVis[ga_var.iVisibleLink] = szId; // e.g From https://goo.gl/HnNqnM to https://goo.gl/#analytics/goo.gl/HnNqnM/week var szHref = objGoogle.shortUrl.replace('goo.gl','goo.gl/#analytics/goo.gl') + '/' + ga_var.szParTime; var szTr = '<tr>'; if (ga_var.bShortUrl){ szTr += '<td class="tipc">' + objGoogle.shortUrl + '</td> '; } if (ga_var.bLongUrl){ szTr += '<td class="tipl">' + objGoogle.longUrl + '</td> '; } szTr += '<td class="tipcBold">' + objGoogle.cat + '</td> '+ '<td class="tiplBold">' + objGoogle.desc + '</td> '+ '<td class="tipc"><a id="' + szId + '" class="tipLink" href="'+ szHref + '" target="_blank" >' + GA_LABEL.ANAL + GA_LINK_SEP + ga_var.szParTime + '</a></td> '+ '</tr>'; szTbl += szTr; ga_var.iVisibleLink ++; } } szTbl += '</table></td></tr>'; var div = document.getElementById('divTblGA'); div.innerHTML = szTbl; jsu_logObj (fn + "ga_var.iVisibleLink=" + ga_var.iVisibleLink + " ga_var.arszIdVis", ga_var.arszIdVis); if (ga_var.iVisibleLink > 1){ // Add Div with ALL Google Analytics var szLabel = GA_LABEL.ALL_TITLE.replace ('GOOGLE_ANAL_NUM',ga_var.iVisibleLink); var szLinkAll = '<label><b>' + szLabel +'</b></label>' + '<a id="a_gaAll" class="tipLink" href="javascript:ga_onclickAll();">' + GA_LABEL.ANAL_ALL + GA_LINK_SEP + ga_var.szParTime + '</a>'; var div = document.getElementById('divAllGA'); div.innerHTML = szLinkAll; } // Create Sort only if cSortTable is loaded if (bSort){ jsu_log (fn + "Create SortTable bShortUrl=" + ga_var.bShortUrl + " ga_var.bLongUrl=" + ga_var.bLongUrl); var arSortCol = new Array(); /* var arSortCol = [ {col: GA_LABEL.SHORT_URL}, {col: GA_LABEL.LONG_URL}, {col: GA_LABEL.CAT}, {col:GA_LABEL.DESC}, {col: GA_LABEL.ANAL}]; */ if (ga_var.bShortUrl){ arSortCol.push({col: GA_LABEL.SHORT_URL}); } if (ga_var.bLongUrl){ arSortCol.push({col: GA_LABEL.LONG_URL}); } arSortCol.push({col: GA_LABEL.CAT}); arSortCol.push({col: GA_LABEL.DESC}); arSortCol.push({col: GA_LABEL.ANAL}); var cSortTbl1 = new cSortTable("tblGoogle",arSortCol,{ iRowHeader:2, iRowSortHeader:1, bNoStartupSortIco:true }); } jsu_log (fn + GALOG_FUN_END); } /* * onclick in GoogleAnalytics cbShortUrl * Re design the Table of Google Analitycs basing on the cbShortUrl selected */ function ga_onclickShortUrl(){ var fn = "[googleAnal.js ga_onclickShortUrl] "; jsu_log (fn + GALOG_FUN_START); // Toggle ga_var.bShortUrl = (ga_var.bShortUrl) ? false : true; // redesign Tbl ga_varTblShow(); jsu_log (fn + GALOG_FUN_END); } /* * onclick in GoogleAnalytics cbLongUrl * Re design the Table of Google Analitycs basing on the cbShortUrl selected */ function ga_onclickLongUrl(){ var fn = "[googleAnal.js ga_onclickLongUrl] "; jsu_log (fn + GALOG_FUN_START); // Toggle ga_var.bLongUrl = (ga_var.bLongUrl) ? false : true; // redesign Tbl ga_varTblShow(); jsu_log (fn + GALOG_FUN_END); } /* * onchange in GoogleAnalytics FilterCat * Re design the Table of Google Analitycs basing on the FilterCat selected */ function ga_onchangeCat(){ var fn = "[googleAnal.js ga_onchangeCat()] "; jsu_log (fn + GALOG_FUN_START); var select = document.getElementById ("gaCat"); ga_var.iSelFilterCat = select.selectedIndex; jsu_log (fn + "iSelFilterCat=" + ga_var.iSelFilterCat); ga_varTblShow(); jsu_log (fn + GALOG_FUN_END); } /* * onchange in GoogleAnalytics FilterType * Change global var and align href of the GoogleAnal Links */ function ga_onchangeTime(){ var fn = "[googleAnal.js ga_onchangeTime()t] "; jsu_log (fn + GALOG_FUN_START); var select = document.getElementById ("gaFilterTime"); // e.g week ga_var.szParTime = select[select.selectedIndex].value; ga_var.szParTimeText = select[select.selectedIndex].text; jsu_log (fn + "szParTime=" + ga_var.szParTime + " szParTimeText=" + ga_var.szParTimeText); //--------------- align href var arObj = ga_var.arObjGaList; jsu_log (fn + "SET href for the " + arObj.length + " URLs that are currently displayed"); for (var i=0; i< arObj.length; i++){ var objGoogle = arObj[i]; var szId = "a_ga" + i; var aEl = document.getElementById (szId); if (aEl != null){ // e.g From https://goo.gl/HnNqnM to https://goo.gl/#analytics/goo.gl/HnNqnM/week var szHref = objGoogle.shortUrl.replace('goo.gl','goo.gl/#analytics/goo.gl') + '/' + ga_var.szParTime; aEl.href = szHref; aEl.innerHTML = GA_LABEL.ANAL + GA_LINK_SEP + ga_var.szParTimeText; jsu_log (fn + "szId=" + szId + " - SET aEl.innerHTML " + aEl.innerHTML); } } var aEl = document.getElementById ('a_gaAll'); aEl.innerHTML = GA_LABEL.ANAL_ALL + GA_LINK_SEP + ga_var.szParTimeText; jsu_log (fn + "SET a_gaAll aEl.innerHTML=" + aEl.innerHTML); jsu_log (fn + GALOG_FUN_END); } /* * * Open all the Google analytics pages */ function ga_onclickAll(){ var fn = "[googleAnal.js ga_onclickAll()] "; jsu_log (fn + GALOG_FUN_START); ga_var.iLinkClickCur = 0; ga_clickSimulate(ga_var.iLinkClickCur); if (ga_var.iVisibleLink == 1){ jsu_log (fn + "Only one anchor. Finish click simulation"); }else { jsu_log (fn + "Create Timer of " + TMO_GA_CLICK_SIMUL_MS +" for Next Click Simulate"); ga_var.tmoClick = setTimeout (ga_timerClickSimul,TMO_GA_CLICK_SIMUL_MS); } jsu_log (fn + GALOG_FUN_END); } /* * Simulate a Click on anchor * * @param iLink 0,1... */ function ga_clickSimulate(iLink){ var fn = "[googleAnal.js ga_clickSimulate()] "; jsu_log (fn + GALOG_FUN_START); jsu_logObj (fn + "ga_var.iVisibleLink=" + ga_var.iVisibleLink + " ga_var.arszIdVis", ga_var.arszIdVis); var szId = ga_var.arszIdVis[iLink]; var aEl = document.getElementById (szId); jsu_log (fn + "simulate Click on anchor["+ iLink + "] with id=" + szId + " - href=" + aEl.href); if (aEl.click != undefined){ jsu_log (fn + "a.click is defined. We call it"); aEl.click(); }else { jsu_log (fn + "a.click is NOT defined in this Browser"); if(document.createEvent) { // e.g SAFARI or OPERA jsu_log (fn + "el [" + i + "] of " + ga_var.iVisibleLink + " - We create the event to simulate the FIRST click. "); var evt = document.createEvent("MouseEvents"); evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); var allowDefault = aEl.dispatchEvent(evt); } } jsu_log (fn + GALOG_FUN_END); } /* * Timer Elapsed */ function ga_timerClickSimul(){ var fn = "[googleAnal.js ga_timerClickSimul()] "; jsu_log (fn + GALOG_FUN_START); clearTimeout (ga_var.tmoClick ); // for security. // e.g SAFARI or OPERA ga_clickSimulate(++ga_var.iLinkClickCur); if (ga_var.iLinkClickCur >= (ga_var.iVisibleLink- 1)){ jsu_log (fn + "Click simulation COMPLETED for all " + ga_var.iVisibleLink + " anchors"); }else { jsu_log (fn + "Create Timer of " + TMO_GA_CLICK_SIMUL_MS +" for Next Click Simulate"); ga_var.tmoClick = setTimeout (ga_timerClickSimul,TMO_GA_CLICK_SIMUL_MS); } jsu_log (fn + GALOG_FUN_END); } /** * WE use an Hidden a tag, for compatibility with MObile (instead of using window.open) * * @param szUrl * @param [bNewWindow] {Boolean} default true */ function ga_GoToURL(szUrl,bNewWindow){ var fn = "[googleAnal.js ga_GoToURL()] "; try{ jsu_log (fn + GALOG_FUN_START); if (bNewWindow == undefined){ bNewWindow = true; } jsu_log (fn + "bNewWindow=" + bNewWindow); var aEl = document.getElementById(GA_HREF_HIDDEN_ID); if (aEl == undefined){ jsu_log(fn + "add " + GA_HREF_HIDDEN_ID + " HIDDEN div and anchor to document.body"); divHidden = document.createElement("div"); divHidden.id = GA_DIV_HIDDEN_ID; divHidden.innerHTML = GA_HREF_HIDDEN; document.body.appendChild(divHidden); aEl = document.getElementById(GA_HREF_HIDDEN_ID); } aEl.href = szUrl; jsu_log (fn + "aEl.href=" + aEl.href); aEl.target = (bNewWindow)? "_blank" : "_self"; if (aEl.click){ jsu_log(fn + "a.click is defined. We call it"); aEl.click(); } else { jsu_log(fn + "aEl.click is NOT defined in this Browser"); if(document.createEvent) { // e.g SAFARI jsu_log(fn + "document.createEvent is defined in this Browser. We create the event to simulate the click"); var evt = document.createEvent("MouseEvents"); evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); var allowDefault = aEl.dispatchEvent(evt); // you can check allowDefault for false to see if // any handler called evt.preventDefault(). // Firefox will *not* redirect to anchorObj.href // for you. However every other browser will. } } jsu_log (fn + GALOG_FUN_END); }catch (e){ jsu_err (fn + "EXCEPTION: " + e.message); } }
8303865b89e1e6ad5a587e3c21cd9f414c8dd8c3
[ "JavaScript", "Text" ]
10
Text
FedericoLevis/JSU
ff33a00812038c17eaaee1044046b1e477b6b3c7
04ae827cfc43a708af3bf517c43dc891e9691591
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TrackerLibrary.Models; namespace TrackerLibrary.DataAcess { /// <summary> /// Implements a contract to help our application to standardize how /// we actually do the things whatever the database is selected. /// </summary> public interface IDataConnection { /// <summary> /// A contract clausule. Implements the method to create a new prize in the database. /// </summary> /// <param name="model"></param> /// <returns></returns> PrizeModel CreatePrize(PrizeModel model); /// <summary> /// A contract clausule. Implements the method to create a new person in the database. /// </summary> /// <param name="model"></param> /// <returns></returns> PersonModel CreatePerson(PersonModel model); /// <summary> /// A contract clausule. Implements the method to create a new Team in the database. /// </summary> /// <param name="model"></param> /// <returns></returns> TeamModel CreateTeam(TeamModel model); /// <summary> /// A contract clausule. Implements the method to create a new Tournament in the database. /// </summary> /// <param name="model"></param> /// <returns></returns> void CreateTournament(TournamentModel model); /// <summary> /// A contract clausule. Implements the method to get all the teams available in the database /// </summary> /// <returns></returns> List<TeamModel> GetTeam_All(); /// <summary> /// A contract clausule. Implements the method to get all the person available in the database. /// </summary> /// <returns></returns> List<PersonModel> GetPerson_All(); } } <file_sep>using System; using System.Collections.Generic; using System.Text; using TournamentLibrary.DataAcess; namespace TournamentLibrary { /// <summary> /// Implements a Global Configuration, visible everyone. /// Help to decide how kind of database source is available. /// </summary> public static class GlobalConfig { /// <summary> /// A list of Connections, holds everything that implements an IDataConnection Interface /// </summary> public static List<IDataConnection> Connections { get; private set; } = new List<IDataConnection>(); /// With that we actually can put in our list of connections any connection that implements this Interface /// <summary> /// Help the application to determine what kind of database source is /// actually available. /// </summary> /// <param name="database"></param> /// <param name="textfiles"></param> public static void InitializeConnections(bool database, bool textfiles) { if(database) { //TODO - Set up the SQL Connector properly SqlConnector MySqlConnector = new SqlConnector(); Connections.Add(MySqlConnector); } if(textfiles) { //TODO Create the Text Connection TextConnector MyTextConnector = new TextConnector(); Connections.Add(MyTextConnector); } } /// <summary> /// Contains the connection string available on the app.config file. /// </summary> /// <param name="name"></param> /// <returns></returns> public static string CnnString(string name) { return ConfigurationManager.ConnectionStrings[name].ConnectionString; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TrackerLibrary.Models; namespace frmDashboard { /// <summary> ///Implements a contract to help our application to standardize how ///we actually take back from the frmCreateTeam the team created. /// </summary> public interface ITeamRequester { /// <summary> /// A contract clausule. Implements the method used to help a form to call /// and take back the team from the frmCreateTeam. /// </summary> /// <param name="model"></param> void TeamComplete(TeamModel model); } } <file_sep>using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; using TrackerLibrary.DataAcess; namespace TrackerLibrary { /// <summary> /// Implements a Global Configuration, visible everyone. /// Help to decide how kind of database source is available. /// </summary> public class GlobalConfig { /// <summary> /// A connection established in the app.config file. /// </summary> public static IDataConnection Connection { get; private set; } /// With that we actually can put in our list of connections any connection that implements this Interface /// <summary> /// Help the application to determine what kind of database source is /// actually available. /// </summary> /// <param name="database"></param> /// <param name="textfiles"></param> public static void InitializeConnections(DataBaseType db) { if (db == DataBaseType.Sql) { SqlConnector MySqlConnector = new SqlConnector(); Connection = MySqlConnector; } else if (db == DataBaseType.TextFile) { //TODO Create the Text Connection TextConnector MyTextConnector = new TextConnector(); Connection = MyTextConnector; } } /// <summary> /// Contains the connection string available on the app.config file. /// </summary> /// <param name="name"></param> /// <returns></returns> public static string CnnString(string name) { return ConfigurationManager.ConnectionStrings["Tournaments"].ConnectionString; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using TrackerLibrary; using TrackerLibrary.Models; namespace frmDashboard { public partial class frmCreateTeam : Form { private List<PersonModel> availableTeamMembers = GlobalConfig.Connection.GetPerson_All(); private List<PersonModel> selectedTeamMembers = new List<PersonModel>(); /// <summary> /// Store whatever is passed in to our constructor. /// </summary> private ITeamRequester callingForm; /// <summary> /// The Caller parameter allows us to know who is calling the form. /// It allow us to pass back the created team. /// </summary> /// <param name="caller"></param> public frmCreateTeam(ITeamRequester caller) { InitializeComponent(); callingForm = caller; //CreateSampleData(); WireUpLists(); } #region Just a test /// <summary> /// Sample data to test a func. /// </summary> private void CreateSampleData() { availableTeamMembers.Add(new PersonModel { FirstName = "Henrique", LastName = "Martins" }); availableTeamMembers.Add(new PersonModel { FirstName = "Vitor", LastName = "França" }); selectedTeamMembers.Add(new PersonModel { FirstName = "Marie", LastName = "Martins" }); selectedTeamMembers.Add(new PersonModel { FirstName = "Keyt", LastName = "Martins" }); } #endregion /// <summary> /// Initialize the lists used in the form. /// </summary> private void WireUpLists() { //It makes the bind actually work and refresh the data selectTeamMemberDropDown.DataSource = null; selectTeamMemberDropDown.DataSource = availableTeamMembers; selectTeamMemberDropDown.DisplayMember = "FullName"; selectTeamMemberDropDown.Refresh(); //It makes the bind actually work and refresh the data teamMemberListBox.DataSource = null; teamMemberListBox.DataSource = selectedTeamMembers; teamMemberListBox.DisplayMember = "FullName"; teamMemberListBox.Refresh(); } private void createMemberButton_Click(object sender, EventArgs e) { if (ValidateForm()) { PersonModel p = new PersonModel(); p.FirstName = firstNameValue.Text; p.LastName = lastNameValue.Text; p.EmailAddress = emailValue.Text; p.CellPhoneNumber = cellPhoneValue.Text; p = GlobalConfig.Connection.CreatePerson(p); selectedTeamMembers.Add(p); WireUpLists(); firstNameValue.Text = ""; lastNameValue.Text = ""; emailValue.Text = ""; cellPhoneValue.Text = ""; if (p.Id != 0) { MessageBox.Show("Member Sucessfully created!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Information); } } else { MessageBox.Show("You need to fill in all of the fields to create a new team member.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Information); } } private bool ValidateForm() { if (firstNameValue.Text.Length == 0) { return false; } if (lastNameValue.Text.Length == 0) { return false; } if (emailValue.Text.Length == 0) { return false; } if (cellPhoneValue.Text.Length == 0) { return false; } return true; } private void addMemberButton_Click(object sender, EventArgs e) { PersonModel p = (PersonModel)selectTeamMemberDropDown.SelectedItem; if (p != null) { availableTeamMembers.Remove(p); selectedTeamMembers.Add(p); } WireUpLists(); } private void RemoveSelectedTeamButton_Click(object sender, EventArgs e) { PersonModel p = (PersonModel)teamMemberListBox.SelectedItem; if (p != null) { selectedTeamMembers.Remove(p); availableTeamMembers.Add(p); } WireUpLists(); } private void createTeambutton_Click(object sender, EventArgs e) { TeamModel t = new TeamModel { TeamName = teamNameValue.Text, TeamMembers = selectedTeamMembers }; GlobalConfig.Connection.CreateTeam(t); callingForm.TeamComplete(t); MessageBox.Show("Team sucessfully created!", "Team Created", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Close(); } } } <file_sep>using System; using System.Collections.Generic; using System.Text; using TournamentLibrary.Models; namespace TournamentLibrary.DataAcess { /// <summary> /// Implements a contract to help our application to standardize how /// we actually do the things whatever the database is selected. /// </summary> public interface IDataConnection { /// <summary> /// A contract clausule. Implements the method to create a new prize in the database /// </summary> /// <param name="model"></param> /// <returns></returns> PrizeModel CreatePrize(PrizeModel model); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TrackerLibrary.Models { /// <summary> /// This class represents the basical class of the application. And it means /// the team member that will fill the team. /// </summary> public class PersonModel { /// <summary> /// The unique identifier for the person /// </summary> public int Id { get; set; } /// <summary> /// First name of the person /// </summary> public string FirstName { get; set; } /// <summary> /// Last name of the person /// </summary> public string LastName { get; set; } /// <summary> /// The email address of the person /// </summary> public string EmailAddress { get; set; } /// <summary> /// The CellPhone number of the person /// </summary> public string CellPhoneNumber { get; set; } /// <summary> /// A full name for a person based on his first and last name /// </summary> public string FullName { get { return $"{ FirstName} { LastName }"; } } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using TrackerLibrary; using TrackerLibrary.Models; using TrackerLibrary.DataAcess; namespace frmDashboard { public partial class frmCreatePrize : Form { /// <summary> /// Store whatever is passed in to our constructor. /// </summary> IPrizeRequester callingForm; /// <summary> /// The Caller parameter allows us to know who is calling the form. /// It allow us to pass back the created prize. /// </summary> /// <param name="caller"></param> public frmCreatePrize(IPrizeRequester caller) { InitializeComponent(); callingForm = caller; } private void createPrizebutton_Click(object sender, EventArgs e) { if (ValidateForm()) { PrizeModel model = new PrizeModel( placeNameValue.Text, placeNumberValue.Text, prizeAmountValue.Text, prizePercentageValue.Text); GlobalConfig.Connection.CreatePrize(model); //Pass back the already created and vallidated form back from the caller. callingForm.PrizeComplete(model); MessageBox.Show("Prize created successfully!", "Prize created", MessageBoxButtons.OK, MessageBoxIcon.Information); CleanFormFields(); this.Close(); } else { MessageBox.Show("An error ocurr during the attempt to save the prize.\nReview the information and try again.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } #region Method to validate the form /// <summary> /// Validates the form assuring the information is correctly. /// </summary> private bool ValidateForm() { bool output = true; int placeNumber = 0; bool placeNumberValidNumber = int.TryParse(placeNumberValue.Text, out placeNumber); if (!placeNumberValidNumber) { output = false; placeNumberValue.Focus(); } if (placeNumber < 1) { output = false; placeNumberValue.Focus(); } decimal prizeAmount = 0; double prizePercentage = 0; bool prizeAmountValid = decimal.TryParse(prizeAmountValue.Text, out prizeAmount); bool prizePercentageValid = double.TryParse(prizePercentageValue.Text, out prizePercentage); if (!prizeAmountValid || !prizePercentageValid) { output = false; prizeAmountValue.Focus(); } if (prizeAmount <= 0 && prizePercentage <= 0) { output = false; prizePercentageValue.Focus(); } if (prizePercentage < 0 || prizePercentage > 100) { output = false; } return output; } #endregion #region Method to Clean the text fields of the form private void CleanFormFields() { placeNameValue.Clear(); placeNumberValue.Clear(); prizeAmountValue.Text = "0"; prizePercentageValue.Text = "0"; } #endregion } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TrackerLibrary.Models; namespace frmDashboard { /// <summary> ///Implements a contract to help our application to standardize how ///we actually take a prize back from the frmCreatePrize /// </summary> public interface IPrizeRequester { /// <summary> /// A contract clausule. Implements the method used to help a form to call /// and take back a prize from the frmCreatePrize. /// </summary> /// <param name="model"></param> void PrizeComplete(PrizeModel model); } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using TrackerLibrary; using TrackerLibrary.Models; namespace frmDashboard { public partial class frmCreateTournament : Form, IPrizeRequester, ITeamRequester { List<TeamModel> availableTeams = GlobalConfig.Connection.GetTeam_All(); List<TeamModel> selectedTeam = new List<TeamModel>(); List<PrizeModel> selectedPrizes = new List<PrizeModel>(); public frmCreateTournament() { InitializeComponent(); WireUpLists(); } /// <summary> /// Initialize the lists used in the form. /// </summary> private void WireUpLists() { selectTeamDropDown.DataSource = null; selectTeamDropDown.DataSource = availableTeams; selectTeamDropDown.DisplayMember = "TeamName"; tournamentTeamsListBox.DataSource = null; tournamentTeamsListBox.DataSource = selectedTeam; tournamentTeamsListBox.DisplayMember = "TeamName"; PrizesListBox.DataSource = null; PrizesListBox.DataSource = selectedPrizes; PrizesListBox.DisplayMember = "PlaceName"; } private void addTeamButton_Click(object sender, EventArgs e) { TeamModel t = (TeamModel)selectTeamDropDown.SelectedItem; if(t != null) { availableTeams.Remove(t); selectedTeam.Add(t); WireUpLists(); } } private void createPrizeButton_Click(object sender, EventArgs e) { //Call the CreatePrizeForm frmCreatePrize frm = new frmCreatePrize(this); frm.ShowDialog(); } public void PrizeComplete(PrizeModel model) { //Get back from the form a PrizeModel //Take the PrizeModel and put it into our list of selected prizes selectedPrizes.Add(model); WireUpLists(); } public void TeamComplete(TeamModel model) { selectedTeam.Add(model); WireUpLists(); } private void newTeamLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { frmCreateTeam frm = new frmCreateTeam(this); frm.ShowDialog(); } private void removeSelectedPlayerButton_Click(object sender, EventArgs e) { TeamModel t = (TeamModel)tournamentTeamsListBox.SelectedItem; if(t != null) { selectedTeam.Remove(t); availableTeams.Add(t); } WireUpLists(); } private void removeSelectedPrizeButton_Click(object sender, EventArgs e) { PrizeModel p = (PrizeModel)PrizesListBox.SelectedItem; if(p != null) { selectedPrizes.Remove(p); } WireUpLists(); } private void createTournamentbutton_Click(object sender, EventArgs e) { //Validate data decimal fee = 0; bool feeAcceptable = decimal.TryParse(entryFeeValue.Text, out fee); if (!feeAcceptable) { MessageBox.Show("You need to enter a valid Entry Fee", "Invalid Fee", MessageBoxButtons.OK, MessageBoxIcon.Error); entryFeeValue.Focus(); return; } //Create tournament model TournamentModel tm = new TournamentModel(); tm.TournamentName = tournamentNameValue.Text; tm.EntryFee = fee; tm.Prizes = selectedPrizes; tm.EnteredTeams = selectedTeam; //Wire our matchups //Create tournament Entry //Create all of the prizes entries //create all of team entries GlobalConfig.Connection.CreateTournament(tm); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TrackerLibrary.Models { /// <summary> /// This class descibres the matchup that will fill the list of list of matchups and as we know /// it means the rounds inside the tournament. /// </summary> public class MatchupModel { /// <summary> /// The unique identifier for the Matchup /// </summary> public int Id { get; set; } /// <summary> /// The list of Participants inside a tournament /// </summary> public List<MatchupEntryModel> Entries { get; set; } = new List<MatchupEntryModel>(); /// <summary> /// The winner of a tournament /// </summary> public TeamModel Winner { get; set; } /// <summary> /// The rounds' number /// </summary> public int MatchupRound { get; set; } } } <file_sep>using Dapper; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using TrackerLibrary.Models; namespace TrackerLibrary.DataAcess { /// <summary> /// The SQLConnector to access the TournamentTracker SQL Database /// </summary> public class SqlConnector : IDataConnection { /// <summary> /// The constant that represents our CnnString Value. Used to avoid magic strings. /// </summary> private const string db = "Tournaments"; /// <summary> /// Create a new person entry in the TournamentTracker SQL DataBase /// </summary> /// <param name="model"></param> /// <returns></returns> public PersonModel CreatePerson(PersonModel model) { //Stabilish the use of a connection inside the Using statement //When this block of code is already executed then this connection //will be automatic destroyed using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(GlobalConfig.CnnString(db))) { var p = new DynamicParameters(); p.Add("@FirstName", model.FirstName); p.Add("@LastName", model.LastName); p.Add("@EmailAddress", model.EmailAddress); p.Add("@CellPhoneNumber", model.CellPhoneNumber); p.Add("@Id", 0, dbType: DbType.Int32, direction: ParameterDirection.Output); connection.Execute("dbo.spPeople_Insert", p, commandType: CommandType.StoredProcedure); model.Id = p.Get<int>("@Id"); return model; } } /// <summary> /// Create a new prize in the TournamentTracker SQL DataBase /// </summary> /// <param name="model">The prize information</param> /// <returns>The prize information, including the unique identifier</returns> public PrizeModel CreatePrize(PrizeModel model) { using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(GlobalConfig.CnnString(db))) { var p = new DynamicParameters(); p.Add("@PlaceNumber", model.PlaceNumber); p.Add("@PlaceName", model.PlaceName); p.Add("@PrizeAmount", model.PrizeAmount); p.Add("@PrizePercentage", model.PrizePercentage); //This line allow us to modify the ParameterDirection to get the ID back after // the query execution on to database p.Add("@Id", 0, dbType: DbType.Int32, direction: ParameterDirection.Output); connection.Execute("dbo.spPrize_Insert", p, commandType: CommandType.StoredProcedure); //Get the ID in the parameter list after it is filled out by the query model.Id = p.Get<int>("@Id"); return model; } } /// <summary> /// Create a new Team in the TournamentTracker SQL DataBase, saves every person like a TeamMember, in the TeamMember's table /// </summary> /// <param name="model"></param> /// <returns></returns> public TeamModel CreateTeam(TeamModel model) { using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(GlobalConfig.CnnString(db))) { var p = new DynamicParameters(); p.Add("@TeamName", model.TeamName); p.Add("@Id", 0, dbType: DbType.Int32, direction: ParameterDirection.Output); connection.Execute("dbo.spTeams_Insert", p, commandType: CommandType.StoredProcedure); model.Id = p.Get<int>("@Id"); foreach (PersonModel tm in model.TeamMembers) { p = new DynamicParameters(); p.Add("@TeamId", model.Id); p.Add("@PersonId", tm.Id); connection.Execute("dbo.spTeamMembers_Insert", p, commandType: CommandType.StoredProcedure); } return model; } } /// <summary> /// Create a new Tournament in the TournamentTracker SQL DataBase. Saves the related data about prizes and teams too. /// </summary> /// <param name="model"></param> /// <returns></returns> public void CreateTournament(TournamentModel model) { using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(GlobalConfig.CnnString(db))) { SaveTournament(connection, model); SaveTournamentPrizes(connection, model); SaveTournamentEntries(connection, model); } } /// <summary> /// Saves the Tournament into the SQL Database /// </summary> /// <param name="connection"></param> /// <param name="model"></param> private void SaveTournament(IDbConnection connection ,TournamentModel model) { var p = new DynamicParameters(); p.Add("@TournamentName", model.TournamentName); p.Add("@EntryFee", model.EntryFee); p.Add("@Id", 0, dbType: DbType.Int32, direction: ParameterDirection.Output); connection.Execute("dbo.spTournament_Insert", p, commandType: CommandType.StoredProcedure); //We are not returning the Model back because we've actually changed it, //throught the "address" of the object it means, the object reference. model.Id = p.Get<int>("@Id"); } /// <summary> /// Save the Tournament Prizes Entries into related SQL database. /// </summary> /// <param name="connection"></param> /// <param name="model"></param> private void SaveTournamentPrizes(IDbConnection connection, TournamentModel model) { foreach (PrizeModel pz in model.Prizes) { var p = new DynamicParameters(); p.Add("@TournamentId", model.Id); p.Add("@PrizeId", pz.Id); p.Add("@Id", 0, dbType: DbType.Int32, direction: ParameterDirection.Output); connection.Execute("dbo.spTournamentPrize_Insert", p, commandType: CommandType.StoredProcedure); } } /// <summary> /// Save the Tournament Entries (Teams participating) into related SQL database. /// </summary> /// <param name="connection"></param> /// <param name="model"></param> private void SaveTournamentEntries(IDbConnection connection, TournamentModel model) { foreach (TeamModel tm in model.EnteredTeams) { var p = new DynamicParameters(); p.Add("@TournamentId", model.Id); p.Add("@TeamId", tm.Id); p.Add("@Id", 0, dbType: DbType.Int32, direction: ParameterDirection.Output); connection.Execute("dbo.spTournamentEntries_Insert", p, commandType: CommandType.StoredProcedure); } } /// <summary> /// Get all the People available in the Members table on SQL DataBase. /// </summary> /// <returns></returns> public List<PersonModel> GetPerson_All() { List<PersonModel> output; using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(GlobalConfig.CnnString(db))) { output = connection.Query<PersonModel>("dbo.spPeople_GetAll").ToList(); } return output; } /// <summary> /// Get all the teams available in the team's table on SQL DataBase. /// </summary> /// <returns></returns> public List<TeamModel> GetTeam_All() { List<TeamModel> output; using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(GlobalConfig.CnnString(db))) { output = connection.Query<TeamModel>("dbo.spTeam_GetAll").ToList(); foreach (TeamModel team in output) { var p = new DynamicParameters(); p.Add("@TeamId", team.Id); team.TeamMembers = connection.Query<PersonModel>("dbo.spTeamMembers_GetByTeam", p, commandType: CommandType.StoredProcedure).ToList(); } } return output; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace TournamentLibrary.Models { /// <summary> /// This class is used to create a team in our application /// </summary> public class TeamModel { /// <summary> /// A list of members that will fill the team /// </summary> public List<PersonModel> TeamMembers { get; set; } = new List<PersonModel>(); //This ability to declare a list by this way is something introduced in C# 6.0 //before it we must declare a constructor that instantiate the list like a new list /// <summary> /// The Team's name. /// </summary> public string TeamName { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace TournamentLibrary.Models { /// <summary> /// This class represents the basical class of the application. And it means /// the team member that will fill the team. /// </summary> public class PersonModel { /// <summary> /// First name of the person /// </summary> public string FirstName { get; set; } /// <summary> /// Last name of the person /// </summary> public string LastName { get; set; } /// <summary> /// The email address of the person /// </summary> public string EmailAddress { get; set; } /// <summary> /// The CellPhone number of the person /// </summary> public string CellPhone { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TrackerLibrary.Models { /// <summary> /// This class represents the entry of a team participating on to the tournament.) /// </summary> public class MatchupEntryModel { /// <summary> /// The team that will participate in a tournament /// </summary> public TeamModel TeamCompeting { get; set; } /// <summary> /// The Score acquired in a matchup /// </summary> public double Score { get; set; } /// <summary> /// I don't kown, need to review at <NAME>'s videos. /// </summary> public MatchupModel ParentMatchup { get; set; } } } <file_sep># TournamentTracker This repository keeps the code of my online course "C# From Start To Finish" provided by <NAME> in his youtube's channel. <file_sep>using System; using System.Collections.Generic; using System.Text; using TournamentLibrary.Models; namespace TournamentLibrary.DataAcess { /// <summary> /// The SQLConnector to access the TournamentTracker SQL Database /// </summary> public class SqlConnector : IDataConnection { // TODO - Make the create prize method actually save to the database /// <summary> /// Create a new prize in the TournamentTracker SQL DataBase /// </summary> /// <param name="model">The prize information</param> /// <returns>The prize information, including the unique identifier</returns> public PrizeModel CreatePrize(PrizeModel model) { model.Id = 1; return model; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TrackerLibrary.Models; using TrackerLibrary.DataAcess.TextHelpers; namespace TrackerLibrary.DataAcess { /// <summary> /// The TextConnector to access the TournamentTracker Text Database /// </summary> public class TextConnector : IDataConnection { /// <summary> /// The name of the file that keeps the data of the prizes created /// </summary> private const string PrizesFile = "PrizeModels.csv"; /// <summary> /// The name of the file that keeps the data of the people created /// </summary> private const string PeopleFile = "PersonModels.csv"; /// <summary> /// The name of the file that keeps the data of the Teams created /// </summary> private const string TeamFile = "TeamModels.csv"; /// <summary> /// The name of the file that keeps the data of the Tournaments created /// </summary> private const string TournamentFile = "TournamentModels.csv"; /// <summary> /// Create a new person in the TournamentTracker Text DataBase /// </summary> /// <param name="model"></param> /// <returns></returns> public PersonModel CreatePerson(PersonModel model) { List<PersonModel> people = PeopleFile.FullFilePath().LoadFile().ConvertToPersonModels(); int currentId = 1; if(people.Count > 0) { currentId = currentId = people.OrderByDescending(x => x.Id).First().Id + 1; } model.Id = currentId; people.Add(model); people.SavePeopleFile(PeopleFile); return model; } /// <summary> /// Create a new prize in the TournamentTracker Text DataBase /// </summary> /// <param name="model">The prize information</param> /// <returns>The prize information, including the unique identifier</returns> public PrizeModel CreatePrize(PrizeModel model) { //Load the text file //Convert the text file to a List<PrizeModel> List<PrizeModel> prizes = PrizesFile.FullFilePath().LoadFile().ConvertToPrizeModels(); // Find the max ID int currentId = 1; if(prizes.Count > 0) { currentId = currentId = prizes.OrderByDescending(x => x.Id).First().Id + 1; } model.Id = currentId; // Add the new record with the new ID ( max ID + 1) prizes.Add(model); // Convert the Prizes to a list of a List<string> // Save the List<string> to the text file prizes.SaveToPrizeFile(PrizesFile); return model; } /// <summary> /// Create a new Team in the TournamentTracker Text DataBase /// </summary> /// <param name="model"></param> /// <returns></returns> public TeamModel CreateTeam(TeamModel model) { List<TeamModel> Teams = TeamFile.FullFilePath().LoadFile().ConvertToTeamModels(PeopleFile); //Find Max ID int currentID = 1; if (Teams.Count > 0) { currentID = Teams.OrderByDescending(x => x.Id).First().Id + 1; } model.Id = currentID; Teams.Add(model); Teams.SaveToTeamFile(TeamFile); return model; } /// <summary> /// Create a new Tournament in the TournamentTracker Text DataBase, saves the related data about prizes /// and participating teams in different files. /// </summary> /// <param name="model"></param> /// <returns></returns> public void CreateTournament(TournamentModel model) { List<TournamentModel> tournaments = TournamentFile. FullFilePath(). LoadFile(). ConvertToTournamentModels(TeamFile, PeopleFile, PrizesFile); int CurrentId = 1; if(tournaments.Count > 0) { CurrentId = tournaments.OrderByDescending(x => x.Id).First().Id + 1; } model.Id = CurrentId; tournaments.Add(model); tournaments.SaveTournamentFile(TournamentFile); } /// <summary> /// Get all the People available in the Member's file on Text DataBase. /// </summary> /// <returns></returns> public List<PersonModel> GetPerson_All() { return PeopleFile.FullFilePath().LoadFile().ConvertToPersonModels(); } /// <summary> /// Get all the Teams available in the Team's file on Text DataBase. /// </summary> /// <returns></returns> public List<TeamModel> GetTeam_All() { return TeamFile.FullFilePath().LoadFile().ConvertToTeamModels(PeopleFile); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TrackerLibrary.Models { /// <summary> /// This class represents a tournament unit inside our tournament tracker /// </summary> public class TournamentModel { /// <summary> /// The unique identifier for the Tournament /// </summary> public int Id { get; set; } /// <summary> /// The tournament's name /// </summary> public string TournamentName { get; set; } /// <summary> /// The amount of the entry fee that the members of the tournament need to pay /// </summary> public decimal EntryFee { get; set; } /// <summary> /// A list of team that will participate in the tournament /// </summary> public List<TeamModel> EnteredTeams { get; set; } = new List<TeamModel>(); /// <summary> /// The list of prizes offered for the participants of the tournament /// </summary> public List<PrizeModel> Prizes { get; set; } = new List<PrizeModel>(); /// <summary> /// The list of list of Matchup Entries, that means the rounds of the tournament /// </summary> public List<List<MatchupModel>> Rounds { get; set; } = new List<List<MatchupModel>>(); } }
1a5aea2df94610dbf3d4dda5b4a4af011c9f0381
[ "Markdown", "C#" ]
19
C#
SouzaHenrique/TournamentTracker
d0b2907daa789ca06a02a450dcda6c6102bf2f3a
bd62b81d904d564a96a0c5d9331dc8983319aaf0
refs/heads/master
<file_sep># # Author:: <NAME> <<EMAIL>> # Copyright (c) 2013, Opscode, Inc. <<EMAIL>> # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # actions :create, :delete, :create_if_missing default_action :create attribute :path, :name_attribute => true attribute :access_key, :kind_of => String, :default => nil, :required => true attribute :backup, :kind_of => [String, Fixnum], :default => 5 attribute :config, :kind_of => Hash, :default => {} attribute :cookbook, :kind_of => String, :default => "s3cfg" attribute :group, :kind_of => String, :default => nil attribute :host_bucket, :kind_of => String, :default => "%(bucket)s.s3.amazonaws.com" attribute :install_s3cmd, :kind_of => [FalseClass, TrueClass, NilClass], :default => true attribute :mode, :kind_of => [String, Fixnum], :default => 00600 attribute :owner, :kind_of => String, :default => nil attribute :secret_key, :kind_of => String, :default => nil, :required => true attribute :source, :kind_of => String, :default => "s3cfg.erb" attribute :variables, :kind_of => Hash, :default => {} <file_sep># s3cfg Cookbook This cookbook provides a resource, `s3cfg` that can be used to manage `.s3cfg` configuration files for s3cmd. http://s3tools.org/ ## Requirements ## Attributes * `node['s3cfg']['config']` - hash of s3cfg configuration options and their values. ## Resource: s3cfg The `s3cfg` resource can be used to render a `.s3cfg` config file in the specified location. ### Actions The allowed actions are passed to a `template` resource rendered at the path specified by the name or path attribute. * `:create` - Default * `:delete` * `:create_if_missing` ### Attributes * `path` - path to the s3cfg file to render * `access_key` - AWS access key id * `secret_key` - AWS secret access key * `host_bucket` - Override the default bucket name. Should be the full FQDN, e.g., `mybucket.s3.amazonaws.com`. * `install_s3cmd` - Whether the `s3cmd` package should be installed. The default package manager must be able to install a package named `s3cmd`. * `backup` - passed to the `backup` attribute of the template, default `5` * `group` - passed to the `group` attribute of the template, default `nil` (group will be the group of the user running Chef) * `mode` - passed to the `mode` attribute of the template, default `00600` (read only by owner) * `owner` - passed to the `owner` attribute of the template, default `nil` (owner will be the user running Chef) * `cookbook` - passed to the `cookbook` attribute of the template, default `s3cfg` * `source` - passed to the `source` attribute of the template, default `s3cfg.erb` * `config` - Hash of configuration overrides that will be merged with the `node['s3cfg']['config']` attributes to dynamically render in `s3cfg.erb`. Note that `access_key`, `secret_key` and `host_bucket` are added to this. ## Usage Use the resource in your *own* cookbooks' recipes where applicable. Be sure to set a dependency in your cookbook on this cookbook, in the metadata e.g.: ```ruby depends "s3cfg" ``` If you're using chef-vault for storing AWS secrets (see example below), also depend on it: ```ruby depends "chef-vault" ``` To render a config file for the root user, but don't install s3cmd: ```ruby s3cfg "/root/.s3cfg" do access_key "Don't put secrets in recipes..." secret_key "Use chef-vault for that instead." install_s3cmd false end ``` To use chef-vault to load an AWS item, and ensure that the s3cmd package is installed: ```ruby include_recipe "chef-vault" aws_creds = chef_vault_item("vault", "aws-credentials")["data"] s3cfg "/root/.s3cfg" do access_key aws_creds['aws_access_key_id'] secret_key aws_creds['aws_secret_access_key'] end ``` ## License and Authors Authors: <NAME> <<EMAIL>> Copyright (c) 2013, Opscode, Inc. <<EMAIL>> License:: Apache License, Version 2.0 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. <file_sep># # Author:: <NAME> <<EMAIL>> # Copyright (c) 2013, Opscode, Inc. <<EMAIL>> # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # This is a test recipe. Don't use it on a real node. return unless node['s3cfg']['test_allowed'] s3cfg "/tmp/s3cfg-#{cookbook_name}-#{recipe_name}" do access_key "Don't put secrets in recipes..." secret_key "Use chef-vault for that instead." install_s3cmd false end <file_sep># # Author:: <NAME> <<EMAIL>> # Copyright (c) 2013, Opscode, Inc. <<EMAIL>> # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # These attributes are passed into the s3cfg resource which are # rendered in the s3cfg.erb template. default['s3cfg']['config'] = { "access_key" => "", "acl_public" => "False", "bucket_location" => "US", "cloudfront_host" => "cloudfront.amazonaws.com", "cloudfront_resource" => "/2010-07-15/distribution", "default_mime_type" => "binary/octet-stream", "delete_removed" => "False", "dry_run" => "False", "encoding" => "UTF-8", "encrypt" => "False", "force" => "False", "get_continue" => "False", "gpg_command" => "/usr/bin/gpg", "gpg_decrypt" => "%(gpg_command)s -d --verbose --no-use-agent --batch --yes --passphrase-fd %(passphrase_fd)s -o %(output_file)s %(input_file)s", "gpg_encrypt" => "%(gpg_command)s -c --verbose --no-use-agent --batch --yes --passphrase-fd %(passphrase_fd)s -o %(output_file)s %(input_file)s", "gpg_passphrase" => "", "guess_mime_type" => "True", "host_base" => "s3.amazonaws.com", "host_bucket" => "%(bucket)s.s3.amazonaws.com", "human_readable_sizes" => "False", "list_md5" => "False", "preserve_attrs" => "True", "progress_meter" => "True", "proxy_host" => "", "proxy_port" => "0", "recursive" => "False", "recv_chunk" => "4096", "secret_key" => "", "send_chunk" => "4096", "simpledb_host" => "sdb.amazonaws.com", "skip_existing" => "False", "urlencoding_mode" => "normal", "use_https" => "True", "verbosity" => "WARNING" } <file_sep># # Author:: <NAME> <<EMAIL>> # Copyright (c) 2013, Opscode, Inc. <<EMAIL>> # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # We should be on Chef 11, but in case we're not, dragons may lie in # wait to devour our flock of resources below. use_inline_resources if defined?(:use_inline_resources) action :delete do file new_resource.path do action :delete end end action :create_if_missing do render_s3cfg_template(:create_if_missing) end action :create do package 's3cmd' if new_resource.install_s3cmd render_s3cfg_template(:create) end def render_s3cfg_template(_action) template "s3cfg-#{new_resource.name}" do path new_resource.path source new_resource.source cookbook new_resource.cookbook owner new_resource.owner group new_resource.group mode new_resource.mode action _action sensitive true variables :config_options => config_options end end def config_options new_resource.config['access_key'] = new_resource.access_key new_resource.config['secret_key'] = new_resource.secret_key new_resource.config['host_bucket'] = new_resource.host_bucket node['s3cfg']['config'].to_hash.merge!(new_resource.config) end <file_sep>name 's3cfg' maintainer '<NAME>' maintainer_email '<EMAIL>' license 'Apache v2' description 'Manages config files for s3cmd' version '0.1.0'
65f0c639dbb529bdda94e3d3c94d761fe6dc9d30
[ "Markdown", "Ruby" ]
6
Ruby
eheydrick/s3cfg-cookbook
e905e708effb65f12b11aeb9bab043e09c69a629
07c6e4abe0c616748bcc75674daabb2ef58359bd
refs/heads/master
<repo_name>mateogiarrocco/Tp0<file_sep>/tp0.c #include "tp0.h" #include <stdio.h> void swap (int *x, int *y) { int aux = *x; *x = *y; *y = aux; } int maximo(int vector[], int n){ if(n <= 0) return -1; int pos = 0; for(int i = 0; i < n; i ++){ if(vector[i] > vector[pos]) pos = i; } return pos; } int comparar(int vector1[], int n1, int vector2[], int n2) { for (int i=0,j=0; i<n1 || j<n2; i++, j++){ if ((i == n1) && (j < n2)) return -1; if ((j == n2) && (i < n1)) return 1; if (vector1[i] < vector2[j]) return -1; if (vector1[i] > vector2[j]) return 1; } return 0; } void seleccion(int vector[], int n) { for(int i = n-1; i >= 0; i --){ int max = maximo(vector, i+1); swap(&vector[max], &vector[i]); } }
1804d96a4323ae05b62d89d4dc6e1a25c33babae
[ "C" ]
1
C
mateogiarrocco/Tp0
bd849f02907b083c19f6ef87f409ea434477e65c
70a2814cce49da89022a493770e7d2991056467f
refs/heads/main
<file_sep>const data = [ { Cheese: 22.2, CHOCOLATE: 10.3, Impulse: 1.5, period: '2021_26', }, { Cheese: 21.8, CHOCOLATE: 9.8, Impulse: 1.5, period: '2021_27', }, { Cheese: 21.2, CHOCOLATE: 9.7, Impulse: 1.4, period: '2021_28', }, ]; const calculateTotal = (array) => array.map((e) => { e.total = Object.values(e).reduce( (accumulator, currentValue) => (accumulator += currentValue), 0 ) / 3; return e; }); const groupData = (keys, dataWithTotal) => keys .filter((k) => k !== 'period') .map((k) => { let temp = { label: k, data: [], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', ], }; temp.data = dataWithTotal.map((elt) => elt[k]); return temp; }); (function generateGraph() { let dataWithTotal = []; let filterdData = [...data].map((elm) => { const { period, ...rest } = elm; return rest; }); dataWithTotal = calculateTotal(filterdData); const labels = data.map((element) => element['period']); let keys = Object.keys(dataWithTotal[0]); const graphValues = groupData(keys, dataWithTotal); const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { type: 'line', data: { labels: labels, datasets: graphValues, }, }); })();
cd9b7242fe948e6e14c111c1d1031effcbeb36cc
[ "JavaScript" ]
1
JavaScript
oussamabouchikhi/js_de_test
287fde7f3a2701a607a20a22a7bf61c5398370a1
9ad80119b0e8c0c0593669ad04081b1eb26775cc
refs/heads/master
<file_sep>import React from 'react'; import PropTypes from 'prop-types'; import copy from 'copy-to-clipboard'; import { Box, Stack } from '@coreym/benchmark'; import { createUrl } from '../util/'; import PreviewButton from './PreviewButton.js'; import StaticCodeBlock from './StaticCodeBlock.js'; function CodePreview({ code }) { function handleClickCopy() { copy(code); } function handleClickPlayroom() { const baseUrl = process.env.PLAYROOM_URL; const url = createUrl({ baseUrl, code }); window.open(url, '_blank'); } return ( <Box sx={{ position: 'relative' }}> <StaticCodeBlock style={{ marginBottom: 0, borderRadius: 0 }}> {code} </StaticCodeBlock> <Box sx={{ position: 'absolute', right: 0, top: '4px', padding: '4px' }}> <Stack direction="row" spacing="1"> <PreviewButton onClick={handleClickCopy}>Copy</PreviewButton> <PreviewButton onClick={handleClickPlayroom}>Playroom</PreviewButton> </Stack> </Box> </Box> ); } CodePreview.propTypes = { code: PropTypes.string, }; export default CodePreview; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import { RovingTabIndexProvider } from 'react-roving-tabindex'; import { Box, Text, Flex } from '../Base'; import ToolbarGroup from './ToolbarGroup'; import { ToolbarButton, ToolbarToggleButton, PrevButton, NextButton } from './ToolbarButtons.js'; import ToolbarScratchButton from './ToolbarScratchButton'; import ToolbarTimerButton from './ToolbarTimerButton'; const Toolbar = ({ // dom id, label, // data blockTitle, itemTitle, language = 'en', progress = 50, // disable buttons isDisabled, isHelpDisabled, isThemeDisabled, isZoomInDisabled, isZoomOutDisabled, isLangDisabled, isTTSDisabled, isScratchDisabled, isPencilDisabled, isHighlighterDisabled, isEraserDisabled, isClearDisabled, isMathKeyboardDisabled, isCalculatorDisabled, isTimerDisabled, isPrevDisabled, isNextDisabled, // toggle button state isHelpActive, isTTSActive, isMathKeyboardActive, isCalculatorActive, isScratchActive, isPencilActive, isHighlighterActive, isEraserActive, isTimerActive, // hide & show buttons hasMathKeyboard = true, hasCalculator = true, hasTTS = true, hasTimer = true, hasProgress = true, // events onClickNext, onClickPrev, onClickScratch, onClickPencil, onClickHighlighter, onClickEraser, onClickClear, onClickTimer, onClickHelp, onClickMathKeyboard, onClickCalculator, onClickLang, onClickTTS }) => { return ( <Flex id={id} role="toolbar" aria-label={label} bg="n.100" borderBottom={1} borderBottomColor="n.400" > <RovingTabIndexProvider> {/* HELP */} <ToolbarGroup> <ToolbarToggleButton id="help-btn" title="Help. Shows help and directions." icon="question-circle" isActive={isHelpActive} onClick={onClickHelp} isDisabled={isDisabled || isHelpDisabled} /> </ToolbarGroup> {/* VIEW */} <ToolbarGroup> <ToolbarButton id="theme-btn" title="Change Theme. Changes the colors used on the screen." icon="change-theme" isDisabled={isDisabled || isThemeDisabled} /> <ToolbarButton id="zoomout-btn" title="Zoom Out. Makes the words and images smaller." icon="zoom-out" isDisabled={isDisabled || isZoomOutDisabled} /> <ToolbarButton title="Zoom In. Makes the words and images larger." id="zoomin-btn" icon="zoom-in" isDisabled={isDisabled || isZoomInDisabled} /> <ToolbarButton id="lang-btn" icon={language === 'es' ? 'lang-es' : 'lang-en'} title={ // todo: should the I be capitalized in inglés? language === 'es' ? 'Cambiar a inglés.' : 'Change to Spanish.' } onClick={onClickLang} isDisabled={isDisabled || isLangDisabled} sx={{ transition: 'transform .4s' }} /> </ToolbarGroup> {/* UTILITIES */} <ToolbarGroup> {hasTTS && ( <ToolbarToggleButton id="tts-btn" title="Read Aloud. Turns on read aloud mode. You can tap any box to hear the text read out loud." icon="read-aloud" isActive={isTTSActive} onClick={onClickTTS} isDisabled={isDisabled || isTTSDisabled} /> )} <ToolbarScratchButton title="Scratchwork. Turns on scratchwork mode. This lets you write on the screen. You must turn scratchwork off to answer questions." isScratchActive={isScratchActive} onClickScratch={onClickScratch} isDisabled={isDisabled || isScratchDisabled} > <ToolbarToggleButton id="pencil-btn" title="Pencil. Turns on write mode. This lets you write on the screen." icon="pencil" onClick={onClickPencil} isActive={isPencilActive} isDisabled={isPencilDisabled} size="sm" /> <ToolbarToggleButton id="highlighter-btn" title="Highlighter. Turns on highlight mode. This lets you highlight parts of the screen." icon="highlighter" onClick={onClickHighlighter} isActive={isHighlighterActive} isDisabled={isHighlighterDisabled} size="sm" /> <ToolbarToggleButton id="eraser-btn" title="Eraser. Turns on erase mode. This lets you erase any of your drawings and highlights." icon="eraser" isActive={isEraserActive} isDisabled={isEraserDisabled} onClick={onClickEraser} size="sm" /> <ToolbarButton id="clear-scratch-btn" icon="clear" title="Clear Scratchwork. Clears all scratchwork on the screen." onClick={onClickClear} isDisabled={isClearDisabled} size="sm" /> </ToolbarScratchButton> {hasMathKeyboard && ( <ToolbarToggleButton title="Math Keyboard. Shows the on-screen math keyboard." id="math-btn" icon="equation-editor" isActive={isMathKeyboardActive} isDisabled={isDisabled || isMathKeyboardDisabled} onClick={onClickMathKeyboard} /> )} {hasCalculator && ( <ToolbarToggleButton title="Calculator. Shows the calculator." id="calc-btn" icon="calculator" isActive={isCalculatorActive} isDisabled={isDisabled || isCalculatorDisabled} onClick={onClickCalculator} /> )} </ToolbarGroup> {/* TITLE */} <ToolbarGroup flex={1} justifyContent="space-evenly" direction="column" overflow="hidden" spacing={0} > {itemTitle && ( <Box id="accnum" sx={{ fontSize: 2, whiteSpace: 'nowrap' }} > {itemTitle} </Box> )} {blockTitle && ( <Box id="block" sx={{ fontSize: 2, whiteSpace: 'nowrap' }} > {blockTitle} </Box> )} </ToolbarGroup> {/* TIMER */} {hasTimer && ( <ToolbarGroup display={['none', 'none', 'none', 'flex']}> <ToolbarTimerButton id="timer-btn" isTimerActive={isTimerActive} onClickTimer={onClickTimer} isDisabled={isDisabled || isTimerDisabled} /> </ToolbarGroup> )} {/* PROGRESS */} {hasProgress && ( <ToolbarGroup justifyContent="space-evenly" alignItems="stretch" direction="column" px="3" > <Text fontSize={2}>Progress</Text> <Box id="progress" border={2} bg="white" borderColor="n.400" borderRadius={3} width="100%" height="18px" title="Progress. This is how far you are in the section." role="progressbar" aria-valuenow={progress} aria-valuemin="0" aria-valuemax="100" sx={{ width: '100%' }} > <Box width={progress + '%'} height="100%" bg="green.500"></Box> </Box> </ToolbarGroup> )} {/* NAVIGATION */} <ToolbarGroup borderRight="none"> <PrevButton id="prev-btn" title="Back. Returns to the previous screen." onClick={onClickPrev} isDisabled={isDisabled || isPrevDisabled} /> <NextButton id="next-btn" title="Next. Moves to the next screen." onClick={onClickNext} isDisabled={isDisabled || isNextDisabled} /> </ToolbarGroup> </RovingTabIndexProvider> </Flex> ); }; Toolbar.propTypes = { // dom id: PropTypes.string, label: PropTypes.string, // data blockTitle: PropTypes.string, itemTitle: PropTypes.string, language: PropTypes.string, progress: PropTypes.number, // disable buttons isDisabled: PropTypes.bool, // disabled all buttons isHelpDisabled: PropTypes.bool, isThemeDisabled: PropTypes.bool, isZoomInDisabled: PropTypes.bool, isZoomOutDisabled: PropTypes.bool, isLangDisabled: PropTypes.bool, isTTSDisabled: PropTypes.bool, isScratchDisabled: PropTypes.bool, isPencilDisabled: PropTypes.bool, isHighlighterDisabled: PropTypes.bool, isEraserDisabled: PropTypes.bool, isClearDisabled: PropTypes.bool, isMathKeyboardDisabled: PropTypes.bool, isCalculatorDisabled: PropTypes.bool, isTimerDisabled: PropTypes.bool, isPrevDisabled: PropTypes.bool, isNextDisabled: PropTypes.bool, // toggle buttons isHelpActive: PropTypes.bool, isTTSActive: PropTypes.bool, isCalculatorActive: PropTypes.bool, isScratchActive: PropTypes.bool, isPencilActive: PropTypes.bool, isHighlighterActive: PropTypes.bool, isEraserActive: PropTypes.bool, isTimerActive: PropTypes.bool, // toggle ui elements hasMathKeyboard: PropTypes.bool, hasCalculator: PropTypes.bool, hasTTS: PropTypes.bool, hasTimer: PropTypes.bool, hasProgress: PropTypes.bool, // events onClickNext: PropTypes.func, onClickPrev: PropTypes.func, onClickScratch: PropTypes.func, onClickPencil: PropTypes.func, onClickHighlighter: PropTypes.func, onClickEraser: PropTypes.func, onClickClear: PropTypes.func, onClickTimer: PropTypes.func, onClickHelp: PropTypes.func, onClickCalculator: PropTypes.func, onClickLang: PropTypes.func, onClickTTS: PropTypes.func, onClickMathKeyboard: PropTypes.func }; export default Toolbar; <file_sep>import React, { Children, isValidElement } from 'react'; import { Flex, Box } from '../Base'; const Stack = ({ direction = 'column', children, align, justify, spacing = 2, ...props }) => { // Sometimes a child will not be a react element. For // example if the child uses conditional rendering with // the && operator it's value will be 'false'. // https://reactjs.org/docs/conditional-rendering.html#inline-if-with-logical--operator // // We need to filter out any children that are not a react // element. This ensures that we are applying the spacing // to the react elements only. const childrenElements = Children.toArray(children).filter(isValidElement); return ( <Flex alignItems={align} justifyContent={justify} flexDirection={direction} {...props} > {childrenElements.map((child, index) => { let isLastChild = (childrenElements.length || 1) === index + 1; let spacingProps = direction === 'row' ? { mr: isLastChild ? null : spacing } : { mb: isLastChild ? null : spacing }; return ( <Box key={index} {...spacingProps}> {child} </Box> ); })} </Flex> ); }; export default Stack; <file_sep>import React, { useState } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import { ThemeProvider, themes } from '@coreym/benchmark'; import PreviewButton from './PreviewButton.js'; import css from './PreviewFrame.module.css'; const themeArray = Object.keys(themes).map((key) => { return themes[key]; }); function PreviewFrame({ children, onToggleCode, hasSwitchTheme = false }) { const [theme, setTheme] = useState(0); function handleThemeChange() { setTheme((theme + 1) % themeArray.length); } return ( <div className={classnames(css.codeframe, global.base)}> <ThemeProvider theme={themeArray[theme]}> <div className={css.toolbar}> <div className={css.codeUtils}> <PreviewButton onClick={onToggleCode}>Code</PreviewButton> {hasSwitchTheme && ( <PreviewButton onClick={handleThemeChange}>Theme</PreviewButton> )} </div> </div> <div className={css.content}>{children}</div> </ThemeProvider> </div> ); } PreviewFrame.propTypes = { children: PropTypes.any, hasSwitchTheme: PropTypes.bool, onToggleCode: PropTypes.func, }; export default PreviewFrame; <file_sep>--- title: Usage path: /developers/usage group: Developers status: In Progress --- ## Getting Started Install benchmark and it's dependencies. ```bash npm install @coreym/benchmark npm install @emotion/core @emotion/styled emotion-theming ``` Add the ThemeProvider to the root of your app and start using the components! ```jsx // App.js import React from 'react'; import { Box, ThemeProvider } from '@coreym/benchmark'; export default function App() { return ( <ThemeProvider> <Box bg="blue.100">Hello World</Box> </ThemeProvider> ); } ``` <file_sep>--- title: Button path: /components/button group: Components status: In Progress updated: '2019-09-01' owner: CM --- Buttons are simple controls for executing specific on-page actions and code. Buttons are most commonly used in forms, dialogs, and modals to facilitate required user actions. ## Usage - **Do** make sure the label conveys a clear purpose of the button to the user. - **Do not** use generic labels like "Ok," especially in the case of an error; errors are never "Ok." ## Variations ```jsx live=true <Stack direction="row"> <Button variant="primary">Primary</Button> <Button variant="secondary">Secondary</Button> </Stack> ``` ## Accessibility ## Properties ## See Also ## References - [Material UI](https://material.io/components/buttons/) - [WCAG Submit Button](https://www.w3.org/WAI/WCAG21/Techniques/general/G80) - [Just use button -- A11ycasts #05](https://www.youtube.com/watch?v=CZGqnp06DnI) <file_sep>import React, { useState } from 'react'; import PropTypes from 'prop-types'; import { LiveProvider, LiveError, LivePreview } from 'react-live'; import * as Components from '@coreym/benchmark'; import { Box } from '@coreym/benchmark'; import PreviewFrame from './PreviewFrame.js'; import CodePreview from './CodePreview.js'; import codeTheme from './themes/default.js'; function LiveCodeBlock({ children, render, renderTheme = 'Default' }) { const [isCodeOpen, setCodeOpen] = useState(false); const code = children.trim(); if (render) { return ( <Box border="1" borderColor="n.300"> <LiveProvider code={code}> <PreviewFrame onToggleCode={() => setCodeOpen(!isCodeOpen)}> <LivePreview style={{ display: 'flex', justifyContent: 'center', paddingTop: '16px', }} /> </PreviewFrame> </LiveProvider> </Box> ); } return ( <Box border="1" borderRadius="lg" borderColor="n.200" overflow="hidden" mb="4" mt="2" > <LiveProvider code={code} scope={{ ...Components }} theme={codeTheme}> <PreviewFrame onToggleCode={() => setCodeOpen(!isCodeOpen)} theme={renderTheme} > <Box sx={{ position: 'relative' }}> <LivePreview style={{ display: 'flex', justifyContent: 'center', paddingTop: '16px', }} /> </Box> </PreviewFrame> {isCodeOpen ? <CodePreview code={code} /> : null} <LiveError /> </LiveProvider> </Box> ); } LiveCodeBlock.propTypes = { children: PropTypes.any, render: PropTypes.func, renderTheme: PropTypes.string, }; export default LiveCodeBlock; <file_sep>import React, { useState } from 'react'; import { useArrayToggle } from '../../util/hooks'; import { Box } from '../Base'; import Stack from '../Stack'; import SingleSelect, { SingleSelectChoice, SingleSelectClear } from './SingleSelect'; export default { title: 'Item Types/SingleSelect', component: SingleSelect }; export function Basic() { return ( <SingleSelect> <SingleSelectChoice>Option A</SingleSelectChoice> <SingleSelectChoice>Option B</SingleSelectChoice> <SingleSelectChoice>Option C</SingleSelectChoice> </SingleSelect> ); } export function CustomLayout() { return ( <SingleSelect hasCustomLayout> <Stack> <Stack direction="row"> <SingleSelectChoice>Option A</SingleSelectChoice> <SingleSelectChoice>Option B</SingleSelectChoice> <SingleSelectChoice>Option C</SingleSelectChoice> </Stack> <SingleSelectClear>Clear Answer!</SingleSelectClear> </Stack> </SingleSelect> ); } export function NoEliminate() { return ( <SingleSelect hasEliminate={false}> <SingleSelectChoice>Option A</SingleSelectChoice> <SingleSelectChoice>Option B</SingleSelectChoice> <SingleSelectChoice>Option C</SingleSelectChoice> </SingleSelect> ); } export function NoLabels() { return ( <SingleSelect labelType="none"> <SingleSelectChoice>Option A</SingleSelectChoice> <SingleSelectChoice>Option B</SingleSelectChoice> <SingleSelectChoice>Option C</SingleSelectChoice> </SingleSelect> ); } export function OptionDisabled() { const [selected, setSelected] = useState(); const [eliminated, toggleEliminated] = useArrayToggle(); function handleEliminate(value) { toggleEliminated(value); if (selected === value) { setSelected(); } } function handleChange(value) { setSelected(value); if (eliminated.includes(value)) { toggleEliminated(value); } } return ( <SingleSelect onClear={() => setSelected()} onEliminate={option => handleEliminate(option)} onChange={option => handleChange(option)} selected={selected} eliminated={eliminated} > <SingleSelectChoice>Option A</SingleSelectChoice> <SingleSelectChoice isDisabled>Option B</SingleSelectChoice> <SingleSelectChoice>Option C</SingleSelectChoice> </SingleSelect> ); } export function Disabled() { const [selected, setSelected] = useState(); const [eliminated, toggleEliminated] = useArrayToggle(); function handleEliminate(value) { toggleEliminated(value); if (selected === value) { setSelected(); } } function handleChange(value) { setSelected(value); if (eliminated.includes(value)) { toggleEliminated(value); } } return ( <SingleSelect onClear={() => setSelected()} onEliminate={option => handleEliminate(option)} onChange={option => handleChange(option)} selected={selected} eliminated={eliminated} isDisabled={true} > <SingleSelectChoice>Option A</SingleSelectChoice> <SingleSelectChoice>Option B</SingleSelectChoice> <SingleSelectChoice>Option C</SingleSelectChoice> </SingleSelect> ); } export function LongOptions() { const [selected, setSelected] = useState(); const [eliminated, toggleEliminated] = useArrayToggle(); function handleEliminate(value) { toggleEliminated(value); if (selected === value) { setSelected(); } } function handleChange(value) { setSelected(value); if (eliminated.includes(value)) { toggleEliminated(value); } } return ( <Box width="400px"> <SingleSelect onClear={() => setSelected()} onEliminate={option => handleEliminate(option)} onChange={option => handleChange(option)} selected={selected} eliminated={eliminated} > <SingleSelectChoice> This is a really long label to test how well the text wraps </SingleSelectChoice> <SingleSelectChoice> It is in a really small container </SingleSelectChoice> <SingleSelectChoice>Small option</SingleSelectChoice> </SingleSelect> </Box> ); } <file_sep>--- title: TTS path: /components/tts group: Components status: Pending --- <file_sep>import React from 'react'; import LiveCodeBlock from './LiveCodeBlock.js'; import StaticCodeBlock from './StaticCodeBlock.js'; export default ({ children, render, className, live = false }) => { return live ? ( <LiveCodeBlock render={render}>{children}</LiveCodeBlock> ) : ( <StaticCodeBlock className={className}>{children}</StaticCodeBlock> ); }; <file_sep>--- title: Table path: /components/table group: Components status: In Progress updated: '2020-08-12' owner: CM --- ## Variations ### Default ```jsx live=true <Table> <TableCaption> <Text>LOREM IPSUM DOLOR SIT CONSECTETUR</Text> </TableCaption> <TableHead> <TableRow> <TableHeader>Day</TableHeader> <TableHeader>A</TableHeader> <TableHeader>B</TableHeader> <TableHeader>C</TableHeader> </TableRow> </TableHead> <TableBody> <TableRow> <TableCell>Monday</TableCell> <TableCell>25</TableCell> <TableCell>25</TableCell> <TableCell>25</TableCell> </TableRow> <TableRow> <TableCell>Tuesday</TableCell> <TableCell>33</TableCell> <TableCell>33</TableCell> <TableCell>33</TableCell> </TableRow> <TableRow> <TableCell>Wednesday</TableCell> <TableCell>8</TableCell> <TableCell>8</TableCell> <TableCell>8</TableCell> </TableRow> <TableRow> <TableCell>Thursday</TableCell> <TableCell>33</TableCell> <TableCell>33</TableCell> <TableCell>33</TableCell> </TableRow> <TableRow> <TableCell>Friday</TableCell> <TableCell>77</TableCell> <TableCell>77</TableCell> <TableCell>77</TableCell> </TableRow> </TableBody> </Table> ``` ### Striped Rows ```jsx live=true <Table striped="rows"> <TableCaption> <Text>LOREM IPSUM DOLOR SIT CONSECTETUR</Text> </TableCaption> <TableHead> <TableRow> <TableHeader>Day</TableHeader> <TableHeader>A</TableHeader> <TableHeader>B</TableHeader> <TableHeader>C</TableHeader> </TableRow> </TableHead> <TableBody> <TableRow> <TableCell>Monday</TableCell> <TableCell>25</TableCell> <TableCell>25</TableCell> <TableCell>25</TableCell> </TableRow> <TableRow> <TableCell>Tuesday</TableCell> <TableCell>33</TableCell> <TableCell>33</TableCell> <TableCell>33</TableCell> </TableRow> <TableRow> <TableCell>Wednesday</TableCell> <TableCell>8</TableCell> <TableCell>8</TableCell> <TableCell>8</TableCell> </TableRow> <TableRow> <TableCell>Thursday</TableCell> <TableCell>33</TableCell> <TableCell>33</TableCell> <TableCell>33</TableCell> </TableRow> <TableRow> <TableCell>Friday</TableCell> <TableCell>77</TableCell> <TableCell>77</TableCell> <TableCell>77</TableCell> </TableRow> </TableBody> </Table> ``` ### Striped Columns ```jsx live=true <Table striped="columns"> <TableCaption> <Text>LOREM IPSUM DOLOR SIT CONSECTETUR</Text> </TableCaption> <TableHead> <TableRow> <TableHeader>Day</TableHeader> <TableHeader>A</TableHeader> <TableHeader>B</TableHeader> <TableHeader>C</TableHeader> </TableRow> </TableHead> <TableBody> <TableRow> <TableCell>Monday</TableCell> <TableCell>25</TableCell> <TableCell>25</TableCell> <TableCell>25</TableCell> </TableRow> <TableRow> <TableCell>Tuesday</TableCell> <TableCell>33</TableCell> <TableCell>33</TableCell> <TableCell>33</TableCell> </TableRow> <TableRow> <TableCell>Wednesday</TableCell> <TableCell>8</TableCell> <TableCell>8</TableCell> <TableCell>8</TableCell> </TableRow> <TableRow> <TableCell>Thursday</TableCell> <TableCell>33</TableCell> <TableCell>33</TableCell> <TableCell>33</TableCell> </TableRow> <TableRow> <TableCell>Friday</TableCell> <TableCell>77</TableCell> <TableCell>77</TableCell> <TableCell>77</TableCell> </TableRow> </TableBody> </Table> ``` ### Compact ```jsx live=true <Table isCompact> <TableCaption> <Text>LOREM IPSUM DOLOR SIT CONSECTETUR</Text> </TableCaption> <TableHead> <TableRow> <TableHeader>Day</TableHeader> <TableHeader>A</TableHeader> <TableHeader>B</TableHeader> <TableHeader>C</TableHeader> </TableRow> </TableHead> <TableBody> <TableRow> <TableCell>Monday</TableCell> <TableCell>25</TableCell> <TableCell>25</TableCell> <TableCell>25</TableCell> </TableRow> <TableRow> <TableCell>Tuesday</TableCell> <TableCell>33</TableCell> <TableCell>33</TableCell> <TableCell>33</TableCell> </TableRow> <TableRow> <TableCell>Wednesday</TableCell> <TableCell>8</TableCell> <TableCell>8</TableCell> <TableCell>8</TableCell> </TableRow> <TableRow> <TableCell>Thursday</TableCell> <TableCell>33</TableCell> <TableCell>33</TableCell> <TableCell>33</TableCell> </TableRow> <TableRow> <TableCell>Friday</TableCell> <TableCell>77</TableCell> <TableCell>77</TableCell> <TableCell>77</TableCell> </TableRow> </TableBody> </Table> ``` ## Accessibility ## Properties ## See Also ## References - [WAI-ARIA Authoring Practices: Table](https://www.w3.org/TR/wai-aria-practices-1.1/#table) <file_sep>--- title: Markup path: /guidelines/markup group: Guidelines status: In Progress --- ## Domain Language A design systems allows us to define our own Domain Specific Language (DSL). This is the common language used by developers, designers and content authors. When a "primary button" is used all parties know: - What it looks like - It's intent - How it behaves - It's accessibility implications The following guidelines are to keep the benchmark DSL universally accessible. The primary goal is to provide a language with as little friction as possible in conversation, code and tooling. --- ### Universal Markup should be readable by someone that is non-technical. ```jsx // BAD: What does this mean for a non-technical person? <TD><TD/> // GOOD: Clear intent <TableCell><TableCell/> ``` --- ### Clear Markup should avoid ambiguity. ```jsx // BAD: The "2" value is ambiguous. // It could imply a pixel/percent value. <Stack spacing="2"><Stack/> // GOOD: The spacing scale is clear of conflicts. <Stack spacing="small"><Stack/> ``` --- ### Self Describing Markup should be readable by someone who is new to the system. ```jsx // BAD: Without any context it is not clear what this does. <MCMS><MCMS/> // GOOD: Clearly states <MultipleSelect><MultipleSelect/> ``` --- ### Consistent Markup should be consistent. Pick one word per concept. ```jsx // BAD: Two props with the same effect but named differently. <Switch disabled /> <TextInput isDisabled /> // GOOD: Consistent naming. <Switch isDisabled /> <TextInput isDisabled /> ``` --- ### Sensible Defaults The most common use case for a component should be usable without having to specify props. ```jsx // BAD: The first button is a "bare" button with no styling applied. // The "bare" button is a rare use case and the most common use // case should be shown instead. <Button /> // GOOD: The primary button is the default. // Bare buttons can still be accessed by specifying it in the variant. <Button /> <Button variant="bare" /> ``` --- ### Property Inference Props should having naming conventions to help infer what type of data they accept. ```jsx // Boolean props should be prefixed with either is, can or has. // GOOD: // "is" for visual variations <Modal isActive /> // "can" for behvior variations <Modal canExpand /> // "has" to toggle UI elements <Modal hasCloseButton /> ``` ```jsx // Events should be prefixed with "on". // GOOD: // "on" for events <MultipleSelect onSelect /> ``` --- ### References 1. [Clean Code](https://www.goodreads.com/book/show/3735293-clean-code) 2. [How to name props for React components](https://dlinau.wordpress.com/2016/02/22/how-to-name-props-for-react-components/) <file_sep>import React from 'react'; import Stack from '../Stack'; import Button from '../Button'; import ScrollButton from '../ScrollButton'; import { ToolbarButton, ToolbarToggleButton, NextButton, PrevButton } from '../Toolbar/ToolbarButtons.js'; import ToolbarGroup from '../Toolbar/ToolbarGroup.js'; import ToolbarScratchButton from '../Toolbar/ToolbarScratchButton.js'; import ToolbarTimerButton from '../Toolbar/ToolbarTimerButton.js'; import { Box, Flex } from '../Base'; export default { title: 'Elements/Button', component: Button }; export function Basic() { return ( <Stack spacing={3} p="3"> <Stack spacing="2" direction="row"> <Button>Primary</Button> <Button isDisabled>Primary</Button> <Button variant="secondary">Secondary</Button> <Button variant="secondary" isDisabled> Secondary </Button> </Stack> <Stack> <Box> <Button variant="secondary">Clear Answer</Button> </Box> </Stack> <Stack direction="row"> <Box> <ScrollButton /> </Box> <Box> <ScrollButton isDisabled /> </Box> <Box> <ScrollButton direction="up" /> </Box> <Box> <ScrollButton direction="up" isDisabled /> </Box> </Stack> <Stack direction="row" bg="n.100" p={1}> <PrevButton /> <PrevButton isDisabled /> <NextButton /> <NextButton isDisabled /> </Stack> <Flex bg="n.100" p={1}> <ToolbarButton /> <ToolbarButton isDisabled /> </Flex> <Flex bg="n.100"> <ToolbarGroup> <ToolbarButton /> <ToolbarButton /> <ToolbarButton /> </ToolbarGroup> <ToolbarGroup> <ToolbarButton /> <ToolbarButton /> </ToolbarGroup> <ToolbarGroup> <ToolbarButton /> </ToolbarGroup> </Flex> <Stack direction="row" bg="n.100" p={1}> <ToolbarToggleButton isActive={false} /> <ToolbarToggleButton isActive={true} /> <ToolbarToggleButton isActive={false} isDisabled /> <ToolbarToggleButton isActive={true} isDisabled /> </Stack> <Stack direction="row" bg="n.100" p={1}> <ToolbarScratchButton isScratchActive={false} /> <ToolbarScratchButton title="Scratchwork. Turns on scratchwork mode. This lets you write on the screen. You must turn scratchwork off to answer questions." isScratchActive={true} > <ToolbarToggleButton id="pencil-btn" title="Pencil. Turns on write mode. This lets you write on the screen." size="sm" /> <ToolbarToggleButton id="highlighter-btn" title="Highlighter. Turns on highlight mode. This lets you highlight parts of the screen." size="sm" /> <ToolbarToggleButton id="eraser-btn" title="Eraser. Turns on erase mode. This lets you erase any of your drawings and highlights." size="sm" /> <ToolbarButton id="clear-scratch-btn" title="Clear Scratchwork. Clears all scratchwork on the screen." size="sm" /> </ToolbarScratchButton> </Stack> <Stack direction="row" bg="n.100" p={1}> <ToolbarTimerButton isTimerActive={false} /> <ToolbarTimerButton isTimerActive={true} /> </Stack> </Stack> ); } <file_sep>import React from 'react'; import { Box } from '@coreym/benchmark'; export default function PreviewButton({ children, ...props }) { return ( <Box as="button" sx={{ fontSize: 0, fontFamily: 'mono', cursor: 'pointer', border: 0, padding: 1, color: 'n.900', bg: 'transparent', borderRadius: 'md', textDecoration: 'none', ':hover': { textDecoration: 'underline', bg: 'n.50', }, ':visited': { color: 'inherit', }, }} {...props} > {children} </Box> ); } <file_sep>import React, { useState } from 'react'; import { Box, Flex } from '../Base'; import Stack from '../Stack'; import { useToggle } from '../../util/hooks.js'; import Toolbar from './Toolbar.js'; import ToolbarGroup from './ToolbarGroup.js'; import ToolbarScratchButton from './ToolbarScratchButton.js'; import ToolbarTimerButton from './ToolbarTimerButton.js'; import { ToolbarButton, ToolbarToggleButton, PrevButton, NextButton } from './ToolbarButtons.js'; export default { title: 'Toolbar', component: Toolbar }; function ToolbarExample({ ...props }) { // active buttons const [helpActive, setHelpActive] = useToggle(); const [timerActive, setTimerActive] = useToggle(); const [ttsActive, setTTSActive] = useToggle(); const [mathKeyboardActive, setMathKeyboardActive] = useToggle(); const [scratchActive, setScratchActive] = useToggle(); const [calculatorActive, setCalculatorActive] = useToggle(); const [pencilActive, setPencilActive] = useToggle(); const [highlighterActive, setHighlighterActive] = useToggle(); const [eraserActive, setEraserActive] = useToggle(); // data const [language, setLanguage] = useState('en'); const progress = 50; const itemTitle = 'VH12345'; const blockTitle = 'Block Title'; return ( <Box sx={{ width: '100vw', top: '0', left: '0', position: 'absolute' }} > <Toolbar // data progress={progress} language={language} itemTitle={itemTitle} blockTitle={blockTitle} // toggle button states isHelpActive={helpActive} isTTSActive={ttsActive} isTimerActive={timerActive} isScratchActive={scratchActive} isPencilActive={pencilActive} isEraserActive={eraserActive} isHighlighterActive={highlighterActive} isCalculatorActive={calculatorActive} isMathKeyboardActive={mathKeyboardActive} // event handlers onClickHelp={setHelpActive} onClickTTS={setTTSActive} onClickScratch={setScratchActive} onClickPencil={setPencilActive} onClickHighlighter={setHighlighterActive} onClickMathKeyboard={setMathKeyboardActive} onClickEraser={setEraserActive} onClickCalculator={setCalculatorActive} onClickTimer={setTimerActive} onClickLang={() => setLanguage(language === 'en' ? 'es' : 'en')} {...props} /> </Box> ); } export function Basic() { return <ToolbarExample />; } export function HideButtons() { return ( <ToolbarExample hasCalculator={false} hasTTS={false} hasMathKeyboard={false} /> ); } export function HideTimer() { return <ToolbarExample hasTimer={false} />; } export function HideProgress() { return <ToolbarExample hasProgress={false} />; } export function NoBlockTitle() { return <ToolbarExample blockTitle={null} />; } export function NoItemTitle() { return <ToolbarExample itemTitle={null} />; } export function DisableButtons() { return ( <ToolbarExample isHelpDisabled={true} isThemeDisabled={true} isZoomInDisabled={true} isZoomOutDisabled={true} isLangDisabled={true} isCalculatorDisabled={true} isScratchDisabled={true} isMathKeyboardDisabled={true} isTTSDisabled={true} isPencilDisabled={true} isHighlighterDisabled={true} isEraserDisabled={true} isClearDisabled={true} isTimerDisabled={true} isNextDisabled={true} isPrevDisabled={true} /> ); } export function DisableAll() { return <ToolbarExample isDisabled />; } export function Buttons() { return ( <Stack spacing={3} p="3"> <Stack direction="row" bg="n.100" p={1}> <PrevButton /> <PrevButton disabled /> <NextButton /> <NextButton disabled /> </Stack> <Flex bg="n.100" p={1}> <ToolbarButton /> <ToolbarButton isDisabled={true} /> </Flex> <Flex bg="n.100"> <ToolbarGroup> <ToolbarButton /> <ToolbarButton /> <ToolbarButton /> </ToolbarGroup> <ToolbarGroup> <ToolbarButton /> <ToolbarButton /> </ToolbarGroup> <ToolbarGroup> <ToolbarButton /> </ToolbarGroup> </Flex> <Stack direction="row" bg="n.100" p={1}> <ToolbarToggleButton isActive={false} /> <ToolbarToggleButton isActive={true} /> <ToolbarToggleButton isActive={false} disabled /> <ToolbarToggleButton isActive={true} disabled /> </Stack> <Stack direction="row" bg="n.100" p={1}> <ToolbarScratchButton isScratchActive={false} /> <ToolbarScratchButton isDisabled={true} /> <ToolbarScratchButton title="Scratchwork. Turns on scratchwork mode. This lets you write on the screen. You must turn scratchwork off to answer questions." isScratchActive={true} > <ToolbarToggleButton id="pencil-btn" icon="pencil" title="Pencil. Turns on write mode. This lets you write on the screen." size="sm" /> <ToolbarToggleButton id="highlighter-btn" icon="highlighter" title="Highlighter. Turns on highlight mode. This lets you highlight parts of the screen." size="sm" /> <ToolbarToggleButton id="eraser-btn" icon="eraser" title="Eraser. Turns on erase mode. This lets you erase any of your drawings and highlights." size="sm" /> <ToolbarButton id="clear-scratch-btn" icon="clear" title="Clear Scratchwork. Clears all scratchwork on the screen." size="sm" /> </ToolbarScratchButton> <ToolbarScratchButton title="Scratchwork. Turns on scratchwork mode. This lets you write on the screen. You must turn scratchwork off to answer questions." isScratchActive={true} > <ToolbarToggleButton id="pencil-btn" icon="pencil" title="Pencil. Turns on write mode. This lets you write on the screen." size="sm" isDisabled={true} /> <ToolbarToggleButton id="highlighter-btn" icon="highlighter" title="Highlighter. Turns on highlight mode. This lets you highlight parts of the screen." size="sm" isDisabled={true} /> <ToolbarToggleButton id="eraser-btn" icon="eraser" title="Eraser. Turns on erase mode. This lets you erase any of your drawings and highlights." size="sm" isDisabled={true} /> <ToolbarButton id="clear-scratch-btn" icon="clear" title="Clear Scratchwork. Clears all scratchwork on the screen." size="sm" isDisabled={true} /> </ToolbarScratchButton> </Stack> <Stack direction="row" bg="n.100" p={1}> <ToolbarTimerButton isTimerActive={false} /> <ToolbarTimerButton isTimerActive={true} /> </Stack> </Stack> ); } <file_sep>const yellow = { 50: '#fffff0', 100: '#fefcbf', 200: '#faf089', 300: '#f6e05e', 400: '#ecc94b', 500: '#d69e2e', 600: '#b7791f', 700: '#975a16', 800: '#744210', 900: '#5F370E', }; const green = { 50: '#f0fff4', 100: '#c6f6d5', 200: '#9ae6b4', 300: '#68d391', 400: '#48bb78', 500: '#38a169', 600: '#2f855a', 700: '#276749', 800: '#22543d', 900: '#1C4532', }; const red = { 50: '#fff5f5', 100: '#fed7d7', 200: '#feb2b2', 300: '#fc8181', 400: '#f56565', 500: '#e53e3e', 600: '#c53030', 700: '#9b2c2c', 800: '#822727', 900: '#63171b', }; const whiteAlpha = { 50: 'rgba(255, 255, 255, 0.04)', 100: 'rgba(255, 255, 255, 0.06)', 200: 'rgba(255, 255, 255, 0.08)', 300: 'rgba(255, 255, 255, 0.16)', 400: 'rgba(255, 255, 255, 0.24)', 500: 'rgba(255, 255, 255, 0.36)', 600: 'rgba(255, 255, 255, 0.48)', 700: 'rgba(255, 255, 255, 0.64)', 800: 'rgba(255, 255, 255, 0.80)', 900: 'rgba(255, 255, 255, 0.92)', }; const blackAlpha = { 50: 'rgba(0, 0, 0, 0.04)', 100: 'rgba(0, 0, 0, 0.06)', 200: 'rgba(0, 0, 0, 0.08)', 300: 'rgba(0, 0, 0, 0.16)', 400: 'rgba(0, 0, 0, 0.24)', 500: 'rgba(0, 0, 0, 0.36)', 600: 'rgba(0, 0, 0, 0.48)', 700: 'rgba(0, 0, 0, 0.64)', 800: 'rgba(0, 0, 0, 0.80)', 900: 'rgba(0, 0, 0, 0.92)', }; const orange = { 50: '#FFFAF0', 100: '#FEEBC8', 200: '#FBD38D', 300: '#F6AD55', 400: '#ED8936', 500: '#DD6B20', 600: '#C05621', 700: '#9C4221', 800: '#7B341E', 900: '#652B19', }; const teal = { 50: '#E6FFFA', 100: '#B2F5EA', 200: '#81E6D9', 300: '#4FD1C5', 400: '#38B2AC', 500: '#319795', 600: '#2C7A7B', 700: '#285E61', 800: '#234E52', 900: '#1D4044', }; const blue = { 50: '#E3F2FD', 100: '#BBDEFB', 200: '#90CAF9', 300: '#63b3ed', 400: '#4299e1', 500: '#3182ce', 600: '#2a69ac', 700: '#1e4e8c', 800: '#153e75', 900: '#1a365d', }; const cyan = { 50: '#EDFDFD', 100: '#C4F1F9', 200: '#9DECF9', 300: '#76E4F7', 400: '#0BC5EA', 500: '#00B5D8', 600: '#00A3C4', 700: '#0987A0', 800: '#086F83', 900: '#065666', }; const purple = { 50: '#faf5ff', 100: '#e9d8fd', 200: '#d6bcfa', 300: '#b794f4', 400: '#9f7aea', 500: '#805ad5', 600: '#6b46c1', 700: '#553c9a', 800: '#44337a', 900: '#322659', }; const pink = { 50: '#fff5f7', 100: '#fed7e2', 200: '#fbb6ce', 300: '#f687b3', 400: '#ed64a6', 500: '#d53f8c', 600: '#b83280', 700: '#97266d', 800: '#702459', 900: '#521B41', }; // primary colors // https://gka.github.io/palettes/#/9|s|2478cc|ffffe0,ff005e,93003a|0|0 const p = { 100: '#b0e8ff', 200: '#90cbff', 300: '#70aeff', 400: '#4e93ea', 500: '#2478cc', 600: '#005eaf', 700: '#004693', 800: '#003077', 900: '#001b5d', }; // neutral // http://www.colorbox.io/#steps=10#hue_start=0#hue_end=0#hue_curve=easeInQuad#sat_start=0#sat_end=0#sat_curve=easeOutQuad#sat_rate=130#lum_start=94#lum_end=5#lum_curve=easeOutQuad#minor_steps_map=0 const n = { '0': '#fff', '25': '#f7f7f7', '50': '#eeeeee', '100': '#ebebeb', '200': '#e4e4e4', '300': '#d8d8d8', '400': '#c7c7c7', '500': '#afafaf', '600': '#909090', '700': '#696969', '800': '#3c3c3c', '900': '#0d0d0d', '1000': '#000', }; export const colors = { // PALETTES p, // primary n, // neutral yellow, green, whiteAlpha, blackAlpha, orange, blue, cyan, purple, pink, teal, // MAIN transparent: 'transparent', current: 'currentColor', black: n['1000'], white: n['0'], bg: n['0'], text: n['800'], // FEEDBACK primary: p['500'], primaryAlt: n['0'], warning: yellow['300'], warningAlt: n['800'], success: green['300'], successAlt: n['800'], danger: red['300'], dangerAlt: n['80'], }; export const base = { fontSizes: [12, 14, 16, 18, 24, 30, 36, 42, 50], space: [0, 4, 8, 16, 32, 64, 128, 256], radii: { none: '0', default: '0.25rem', sm: '2px', md: '4px', lg: '6px', full: '9999px', }, fonts: { body: 'system-ui, sans-serif', mono: 'Menlo, monospace', }, shadows: { sm: '0 1px 2px rgba(0,0,0,.20)', md: '0 2px 3px rgba(0,0,0,.25)', lg: '0 3px 4px rgba(0,0,0,.25)', none: 'none', }, fontWeights: { hairline: 100, thin: 200, light: 300, normal: 400, medium: 500, semibold: 600, bold: 700, extrabold: 800, black: 900, }, borders: { none: 0, '1': '1px solid', '2': '2px solid', '4': '4px solid', }, buttons: { primary: { fontSize: 2, fontWeight: 'bold', color: 'white', bg: 'p.500', borderRadius: 'md', borderWidth: 0, ':hover': { bg: 'p.400', boxShadow: 'md', }, ':active': { bg: 'p.600', boxShadow: 'none', }, }, secondary: { fontSize: 2, color: 'p.500', fontWeight: 'bold', bg: 'white', borderRadius: 'md', border: 2, borderColor: 'n.400', ':hover': { boxShadow: 'md', borderColor: 'p.400', color: 'p.400', }, ':active': { bg: 'n.50', border: 'n.700', boxShadow: 'none', }, }, }, }; export default { ...base, colors, }; <file_sep>--- title: SingleSelect path: /components/singleselect group: Components status: Pending --- ## Overview The single select response type allows test takers to respond to an item by selecting from an array of options. These options can be any arbitary element such as text, images and MathML. ## Considerations Current Considerations: - Uses a light blue background color to distinguish the input (radio/checkbox) from the option content. ## Behaviour - When an eliminated option is selected it clears the eliminated state. - When a selected option is eliminated it will no longer be selected. - Clearing the answer clears both the selected option and eliminations. ## Usage ```javascript live=true <SingleSelect> <SingleSelectChoice>Option A</SingleSelectChoice> <SingleSelectChoice>Option B</SingleSelectChoice> <SingleSelectChoice>Option C</SingleSelectChoice> </SingleSelect> ``` ## Component Props <!-- ```javascript function ExampleB() { const [state, dispatch] = React.useReducer( SingleSelect.reducer, SingleSelect.initialState ); return ( <SingleSelect selected={state.selected} eliminated={state.eliminated} onChange={optionId => dispatch({ type: 'MCSS_SELECT', optionId })} onEliminate={optionId => dispatch({ type: 'MCSS_ELIMINATE', optionId })} onClear={() => dispatch({ type: 'MCSS_CLEAR' })} > <SingleSelectChoice value="a">Option A</SingleSelectChoice> <SingleSelectChoice value="b">Option B</SingleSelectChoice> <SingleSelectChoice value="c">Option C</SingleSelectChoice> </SingleSelect> ); } ``` --> <!-- ```javascript function Example() { return ( <SingleSelect> <SingleSelectChoice value="a">Option A</SingleSelectChoice> <SingleSelectChoice value="b">Option B</SingleSelectChoice> <SingleSelectChoice value="c">Option C</SingleSelectChoice> </SingleSelect> ); } ``` --> <file_sep>import React from 'react'; import { useArrayToggle } from '../../util/hooks'; import { Box } from '../Base'; import Stack from '../Stack'; import MultipleSelect, { MultipleSelectChoice, MultipleSelectClear } from './MultipleSelect'; export default { title: 'Item Types/MultipleSelect', component: MultipleSelect }; function useExampleProps() { const [selected, toggleSelected, resetSelected] = useArrayToggle(); const [eliminated, toggleEliminated] = useArrayToggle(); function onClear() { resetSelected(); } function onEliminate(value) { toggleEliminated(value); if (selected.includes(value)) { toggleSelected(value); } } function onChange(value) { toggleSelected(value); if (eliminated.includes(value)) { toggleEliminated(value); } } return { selected, eliminated, onClear, onEliminate, onChange, maxChoices: 2 }; } export function Basic() { const exampleProps = useExampleProps(); return ( <MultipleSelect {...exampleProps}> <MultipleSelectChoice>Option A</MultipleSelectChoice> <MultipleSelectChoice>Option B</MultipleSelectChoice> <MultipleSelectChoice>Option C</MultipleSelectChoice> </MultipleSelect> ); } export function CustomLayout() { const exampleProps = useExampleProps(); return ( <MultipleSelect {...exampleProps} hasCustomLayout> <Stack> <Stack direction="row"> <MultipleSelectChoice>Option A</MultipleSelectChoice> <MultipleSelectChoice>Option B</MultipleSelectChoice> <MultipleSelectChoice>Option C</MultipleSelectChoice> </Stack> <MultipleSelectClear>Clear Answer!</MultipleSelectClear> </Stack> </MultipleSelect> ); } export function NoEliminate() { const exampleProps = useExampleProps(); return ( <MultipleSelect {...exampleProps} hasEliminate={false}> <MultipleSelectChoice>Option A</MultipleSelectChoice> <MultipleSelectChoice>Option B</MultipleSelectChoice> <MultipleSelectChoice>Option C</MultipleSelectChoice> </MultipleSelect> ); } export function NoLabels() { const exampleProps = useExampleProps(); return ( <MultipleSelect {...exampleProps} labelType="none"> <MultipleSelectChoice>Option A</MultipleSelectChoice> <MultipleSelectChoice>Option B</MultipleSelectChoice> <MultipleSelectChoice>Option C</MultipleSelectChoice> </MultipleSelect> ); } export function Disabled() { const exampleProps = useExampleProps(); return ( <MultipleSelect {...exampleProps} isDisabled={true}> <MultipleSelectChoice>Option A</MultipleSelectChoice> <MultipleSelectChoice>Option B</MultipleSelectChoice> <MultipleSelectChoice>Option C</MultipleSelectChoice> </MultipleSelect> ); } export function OptionDisabled() { const exampleProps = useExampleProps(); return ( <MultipleSelect {...exampleProps}> <MultipleSelectChoice isDisabled={true}>Option A</MultipleSelectChoice> <MultipleSelectChoice>Option B</MultipleSelectChoice> <MultipleSelectChoice>Option C</MultipleSelectChoice> </MultipleSelect> ); } export function LongOptions() { const exampleProps = useExampleProps(); return ( <Box width="400px"> <MultipleSelect {...exampleProps}> <MultipleSelectChoice> This is a really long label to test how well the text wraps </MultipleSelectChoice> <MultipleSelectChoice> It is in a really small container </MultipleSelectChoice> <MultipleSelectChoice>Small option</MultipleSelectChoice> </MultipleSelect> </Box> ); }
9a1f50f8650c494aa59dd7151412a7c687b31aed
[ "JavaScript", "Markdown" ]
18
JavaScript
coreymcg/benchmark
dbf9ccfbce294d86968f521768830de1ca3ec5ac
665a433a006a0caf037cf693c135133e1166b350
refs/heads/main
<repo_name>Sona0817/tripfullproj<file_sep>/src/main/java/com/tjoeunit/biz/hotel/Impl/HotelDAO.java package com.tjoeunit.biz.hotel.Impl; import java.util.List; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.tjoeunit.biz.common.PagingVO; import com.tjoeunit.biz.flight.FlightVO; import com.tjoeunit.biz.hotel.HotelVO; @Repository public class HotelDAO { @Autowired private SqlSessionTemplate mybatis; public int insertHotel(HotelVO vo){ return mybatis.insert("hotelDAOTemplate.insertHotel", vo); } public int updateHotel(HotelVO vo){ return mybatis.update("hotelDAOTemplate.updateHotel", vo); } public int deleteHotel(HotelVO vo){ return mybatis.delete("hotelDAOTemplate.deleteHotel", vo); } public HotelVO getHotel(HotelVO vo) { return mybatis.selectOne("hotelDAOTemplate.getHotel", vo); }// 값을 반환하는 셀렉문 , 하나만 반환하면 selectOne public List<HotelVO> getHotelList(HotelVO vo) { return mybatis.selectList("hotelDAOTemplate.getHotelList", vo); } //페이징처리를 위해 생성 public int countHotel() { return mybatis.selectOne("hotelDAOTemplate.countHotel"); } //페이징처리를 위해 생성 public List<HotelVO> selectHotel(PagingVO vo) { return mybatis.selectList("hotelDAOTemplate.selectHotel", vo); } } <file_sep>/src/main/java/com/tjoeunit/view/qna/QnaController.java package com.tjoeunit.view.qna; import java.io.IOException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import com.tjoeunit.biz.common.PagingVO; import com.tjoeunit.biz.qna.QnaService; import com.tjoeunit.biz.qna.QnaVO; @Controller public class QnaController { @Autowired private QnaService qnaService; // 글 목록 보기 @RequestMapping(value="/qna/getQnaList.do", method = RequestMethod.GET) public String qnaListPaging(PagingVO vo, Model model, @RequestParam(value="nowPage", required=false) String nowPage, @RequestParam(value="cntPerPage", required=false) String cntPerPage) { int total = qnaService.countQna(); if (nowPage == null && cntPerPage == null) { nowPage = "1"; cntPerPage = "20"; } else if (nowPage == null) { nowPage = "1"; } else if (cntPerPage == null) { cntPerPage = "20"; } vo = new PagingVO(total, Integer.parseInt(nowPage), Integer.parseInt(cntPerPage)); model.addAttribute("paging", vo); model.addAttribute("qnaList", qnaService.selectQna(vo)); System.out.println("QNA 목록 뷰"); return "qna/getQnaList"; } // 글 상세 조회 @RequestMapping(value="/qna/getQna.do", method = RequestMethod.GET) public String getQna(QnaVO vo, Model model) { System.out.println("QNA 상세 조회 처리"); QnaVO qna = qnaService.getQna(vo); model.addAttribute("qna", qna); return "qna/getQna"; } // 글 등록 페이지 불러오기 @RequestMapping(value="/qna/insertQnaPage.do", method=RequestMethod.GET) public String insertStoryPage() throws IOException { System.out.println("QNA 등록 페이지 호출"); return "qna/insertQnaPage"; } // 글 등록 @RequestMapping(value="/qna/insertQna.do", method=RequestMethod.POST) public String insertQna(QnaVO vo, Model model) throws Exception { System.out.println("QNA 등록 처리"); int cnt = qnaService.insertQna(vo); String msg="QNA 등록 실패", url="/qna/insertQnaPage.do"; if(cnt>0) { msg="등록되었습니다."; url="/qna/getQnaList.do"; } model.addAttribute("msg", msg); model.addAttribute("url", url); return "common/message"; } // 글 수정 페이지 불러오기 @RequestMapping(value="/qna/updateQnaPage.do", method=RequestMethod.GET) public String updateQnaPage(QnaVO vo, Model model) throws IOException { System.out.println("QNA 수정 페이지 호출"); QnaVO qna = qnaService.getQna(vo); model.addAttribute("qna", qna); return "qna/updateQnaPage"; } // 글 수정 @RequestMapping(value="/qna/updateQna.do", method = RequestMethod.POST) public String updateQna(QnaVO vo, Model model) throws Exception { System.out.println("QNA 수정 처리"); int cnt = qnaService.updateQna(vo); String msg="수정 실패", url="/qna/updateQnaPage.do"; if(cnt>0) { msg="수정되었습니다."; url="/qna/getQna.do?qna_no="+vo.getQna_no(); } model.addAttribute("msg", msg); model.addAttribute("url", url); return "common/message"; } // 글 삭제 @RequestMapping("/qna/deleteQna.do") public String deleteQna(QnaVO vo, Model model) throws Exception { System.out.println("QNA 삭제 처리"); qnaService.deleteQna(vo); String msg="삭제되었습니다."; String url="/qna/getQnaList.do"; model.addAttribute("msg", msg); model.addAttribute("url", url); return "common/message"; } /* 관리자 컨트롤 ========================== */ //관리자 QNA 목록보기 @RequestMapping(value="/adminQna/adminQna.do", method = RequestMethod.GET) public String adminQnaListPaging(PagingVO vo, Model model, @RequestParam(value="nowPage", required=false) String nowPage, @RequestParam(value="cntPerPage", required=false) String cntPerPage) { int total = qnaService.countQna(); if (nowPage == null && cntPerPage == null) { nowPage = "1"; cntPerPage = "20"; } else if (nowPage == null) { nowPage = "1"; } else if (cntPerPage == null) { cntPerPage = "20"; } vo = new PagingVO(total, Integer.parseInt(nowPage), Integer.parseInt(cntPerPage)); model.addAttribute("paging", vo); model.addAttribute("qnaList", qnaService.selectQna(vo)); System.out.println("관리자 QNA 목록 뷰"); return "adminQna/adminQna"; } //관리자 QNA 상세보기 @RequestMapping(value="/adminQna/adminQnaDetail.do", method = RequestMethod.GET) public String adminQnaDetail(QnaVO vo, Model model) { System.out.println("관리자 QNA 상세 조회 처리"); QnaVO qna = qnaService.getQna(vo); model.addAttribute("qna", qna); return "adminQna/adminQnaDetail"; } //관리자 QNA 수정페이지로 이동 @RequestMapping(value="/adminQna/adminQnaUpdate.do", method = RequestMethod.GET) public String adminQnaUpdatePage(QnaVO vo, Model model) { System.out.println("관리자 답변 페이지 호출"); QnaVO qna = qnaService.getQna(vo); model.addAttribute("qna", qna); return "adminQna/adminQnaUpdate"; } //관리자 QNA 수정하기 @RequestMapping(value="/adminQna/adminQnaUpdate.do", method = RequestMethod.POST) public String adminQnaUpdate(QnaVO vo, Model model) throws Exception { System.out.println("관리자 QNA 답변 처리"); int cnt = qnaService.updateQna(vo); String msg="답변 실패", url="/adminQna/adminQna.do"; if(cnt>0) { msg="답변했습니다."; url="/adminQna/adminQnaDetail.do?qna_no="+vo.getQna_no(); } model.addAttribute("msg", msg); model.addAttribute("url", url); return "common/message"; } // 관리자 QNA 삭제하기 @RequestMapping("/adminQna/adminQnaDelete.do") public String adminQnaDelete(QnaVO vo, Model model) throws Exception { System.out.println("관리자 QNA 삭제 처리"); qnaService.deleteQna(vo); String msg="삭제되었습니다."; String url="/adminQna/adminQna.do"; model.addAttribute("msg", msg); model.addAttribute("url", url); return "common/message"; } /* 하단 서비스센터 컨트롤 ===========================================*/ @RequestMapping(value = "/index/termService.do", method = RequestMethod.GET) public String termService() { System.out.println("이용약관 보기"); return "index/termService"; } @RequestMapping(value = "/index/privacyPolicy.do", method = RequestMethod.GET) public String privacyPolicy() { System.out.println("개인정보 처리방침 보기"); return "index/privacyPolicy"; } @RequestMapping(value = "/index/cancelRefund.do", method = RequestMethod.GET) public String cancelRefund() { System.out.println("취소 및 환불 정책 보기"); return "index/cancelRefund"; } } <file_sep>/src/main/webapp/sql/0429_leta99p.sql alter table payment modify payment_bookdate varchar2(300); alter table payment modify payment_bookdate default(null); alter table payment drop constraint fk_activity_to_payment; alter table payment drop constraint fk_flight_to_payment; alter table payment drop constraint fk_hotel_to_payment; alter table payment drop constraint fk_lantrip_to_payment; alter table payment drop constraint fk_members_to_payment; alter table payment add flight_title varchar2(600); alter table payment add hotel_title varchar2(600); alter table payment add activity_title varchar2(600); alter table payment add lantrip_title varchar2(600); alter table payment add product_category varchar2(600); <file_sep>/src/main/webapp/sql/0427_QnaReply_sona.sql -- QNA 댓글 기능 추가를 위한 테이블 생성 CREATE TABLE QNAREPLY( QREPLY_NO NUMBER NOT NULL, /* 댓글 번호 */ MEMBERS_ID VARCHAR2(300), /* 멤버 아이디(작성자) */ QNA_NO NUMBER, /* QNA 게시글 번호 */ QREPLY_TEXT VARCHAR2(3000), /* 댓글 내용 */ QREPLY_DATE DATE default sysdate /* 댓글 작성일 */ ); ALTER TABLE QNAREPLY ADD CONSTRAINT PK_QNAREPLY PRIMARY KEY ( QREPLY_NO ); -- 게시글이 삭제될 때 댓글도 삭제될 수 있도록 외래키 설정 ALTER TABLE QNAREPLY ADD CONSTRAINT FK_QNA FOREIGN KEY (QNA_NO) REFERENCES QNA(QNA_NO);<file_sep>/src/main/java/com/tjoeunit/view/admin/AdminController.java package com.tjoeunit.view.admin; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.tjoeunit.biz.admin.AdminService; import com.tjoeunit.biz.admin.AdminVO; import com.tjoeunit.biz.lantrip.LanTripService; @Controller /* @RequestMapping("/adminLogin") */ public class AdminController { @Autowired private AdminService adminService; @RequestMapping(value="/adminLogin/adminLogin_View.do", method=RequestMethod.GET) public String adminLoginPage() { System.out.println("관리자 로그인 페이지"); return "adminLogin/adminLogin"; } //관리자 로그인 처리 @RequestMapping(value="/adminLogin/adminLogin.do", method=RequestMethod.POST) public ModelAndView adminLoginCheck(AdminVO vo, HttpSession session, ModelAndView mav) { System.out.println("관리자 로그인 확인"); String result = adminService.adminLoginCheck(vo); if(result != null){//로그인이 성공했을시 출력되는 구문 session.setAttribute("admin_id", vo.getAdmin_id()); session.setAttribute("admin_name", vo.getAdmin_name()); mav.setViewName("admin/adminIndex"); //admin페이지를 보여줌 mav.addObject("message", "success"); //mav안에 있는 addObject()메소드를 사용해 message라는 키에 sucess라는 value를 담아 보낸다 System.out.println("관리자 로그인 체크성공"); }else { //로그인이 실패했을 시에 다시 관리자 로그인 페이지로 이동함 mav.setViewName("adminLogin/adminLogin"); //뷰에 전달할 값 mav.addObject("message", "관리자의 아이디 혹은 비밀번호가 일치하지 않습니다."); } System.out.println("관리자 로그인 확인2"); return mav; } @RequestMapping(value="/admin/adminIndex.do", method=RequestMethod.GET) public String adminIndex() { System.out.println("관리자 메인페이지로 이동"); return "admin/adminIndex"; } //관리자 로그아웃 @RequestMapping("/adminLogin/adminLogout.do") public String logout(HttpSession session) { session.invalidate(); //로그아웃을 시키려면 session에 있는 데이터를 삭제시켜야 하기 때문에 invalidate()메소드를 사용해서 //안에 있는 데이터를 초기화 시킨다. System.out.println("관리자 로그아웃"); return "redirect:/adminLogin/adminLogin_View.do"; } } <file_sep>/src/main/webapp/sql/DB_Delete_0422-1.sql /* 테이블 삭제 */ /* cascade constraints : 외래키 무시하고 그냥 삭제 */ /* purge : 휴지통에 저장되지 않고 바로 삭제 */ drop table activity cascade constraints purge; drop table flight cascade constraints purge; drop table hotel cascade constraints purge; drop table lantrip cascade constraints purge; drop table story cascade constraints purge; drop table practice cascade constraints purge; drop table review cascade constraints purge; drop table admin cascade constraints purge; drop table members cascade constraints purge; drop table payment cascade constraints purge; /* 시퀀스 삭제 */ drop sequence activity_seq; drop sequence flight_seq; drop sequence hotel_seq; drop sequence lantrip_seq; drop sequence story_seq; drop sequence practice_seq; drop sequence review_seq; drop sequence members_seq; drop sequence payment_seq; commit<file_sep>/src/main/java/com/tjoeunit/biz/hotel/Impl/HotelServiceImpl.java package com.tjoeunit.biz.hotel.Impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.tjoeunit.biz.common.PagingVO; import com.tjoeunit.biz.hotel.HotelService; import com.tjoeunit.biz.hotel.HotelVO; @Service public class HotelServiceImpl implements HotelService { @Autowired private HotelDAO hotelDAO; @Override public int insertHotel(HotelVO vo) { return hotelDAO.insertHotel(vo); } @Override public List<HotelVO> getHotelList(HotelVO vo) { List<HotelVO> list = hotelDAO.getHotelList(vo); return list; } @Override public HotelVO getHotel(HotelVO vo) { HotelVO hotel = hotelDAO.getHotel(vo); return hotel; } @Override public int updateHotel(HotelVO vo) { return hotelDAO.updateHotel(vo); } @Override public int deleteHotel(HotelVO vo) { return hotelDAO.deleteHotel(vo); } //페이징처리를 위해 생성 @Override public int countHotel() { return hotelDAO.countHotel(); } //페이징처리를 위해 생성 @Override public List<HotelVO> selectHotel(PagingVO vo) { return hotelDAO.selectHotel(vo); } } <file_sep>/src/main/java/com/tjoeunit/biz/qna/QnaVO.java package com.tjoeunit.biz.qna; import java.util.Date; public class QnaVO { private int qna_no; private int members_no; private String qna_title; private String qna_content; private String qna_writer; private Date qna_date; public int getQna_no() { return qna_no; } public void setQna_no(int qna_no) { this.qna_no = qna_no; } public int getMembers_no() { return members_no; } public void setMembers_no(int members_no) { this.members_no = members_no; } public String getQna_title() { return qna_title; } public void setQna_title(String qna_title) { this.qna_title = qna_title; } public String getQna_content() { return qna_content; } public void setQna_content(String qna_content) { this.qna_content = qna_content; } public String getQna_writer() { return qna_writer; } public void setQna_writer(String qna_writer) { this.qna_writer = qna_writer; } public Date getQna_date() { return qna_date; } public void setQna_date(Date qna_date) { this.qna_date = qna_date; } } <file_sep>/src/main/java/com/tjoeunit/biz/flight/Impl/FlightDAO.java package com.tjoeunit.biz.flight.Impl; import java.util.List; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.tjoeunit.biz.common.PagingVO; import com.tjoeunit.biz.flight.FlightVO; @Repository public class FlightDAO { @Autowired private SqlSessionTemplate mybatis; public int insertFlight(FlightVO vo){ return mybatis.insert("flightDAOTemplate.insertFlight", vo); } public int updateFlight(FlightVO vo){ return mybatis.update("flightDAOTemplate.updateFlight", vo); } public int deleteFlight(FlightVO vo){ return mybatis.delete("flightDAOTemplate.deleteFlight", vo); } public FlightVO getFlight(FlightVO vo) { return mybatis.selectOne("flightDAOTemplate.getFlight", vo); } public List<FlightVO> getFlightList(FlightVO vo) { // 검색 기능 전 return mybatis.selectList("flightDAOTemplate.getFlightList", vo); } //페이징처리를 위해 생성 public int countFlight() { return mybatis.selectOne("flightDAOTemplate.countFlight"); } //페이징처리를 위해 생성 public List<FlightVO> selectFlight(PagingVO vo) { return mybatis.selectList("flightDAOTemplate.selectFlight", vo); } } <file_sep>/src/main/webapp/sql/0429_kimj7737.sql -- 댓글 기능 추가를 위한 테이블 생성 CREATE TABLE REPLY( REPLY_NO NUMBER NOT NULL, /* 댓글 번호 */ MEMBERS_ID VARCHAR2(300), /* 멤버 아이디 (작성자) */ STORY_NO NUMBER, /* 댓글달린 게시글 번호 */ REPLY_TEXT VARCHAR2(3000), /* 댓글 내용 */ REPLY_DATE DATE default sysdate /* 댓글 작성일 */ ); ALTER TABLE REPLY ADD CONSTRAINT PK_REPLY PRIMARY KEY ( REPLY_NO ); CREATE SEQUENCE REPLY_SEQ increment by 1 start with 1 nocache;<file_sep>/src/main/java/com/tjoeunit/biz/payment/PaymentService.java package com.tjoeunit.biz.payment; import java.util.List; import com.tjoeunit.biz.common.PagingVO; public interface PaymentService { //결제 등록 int insertPayment(PaymentVO vo); List<PaymentVO> getPaymentList(int members_no); //페이징처리를 위해 생성 : 게시물 총 개수 int countPayment(); //페이징처리를 위해 생성 : 항공권 조회 List<PaymentVO> selectPayment(PagingVO vo); } <file_sep>/src/main/webapp/sql/DB_Alter_Activity_0426.sql ALTER TABLE ACTIVITY DROP COLUMN ACTIVITY_IMG;<file_sep>/src/main/java/com/tjoeunit/view/story/StoryController.java package com.tjoeunit.view.story; import java.io.IOException; import java.util.List; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import com.tjoeunit.biz.common.PagingVO; import com.tjoeunit.biz.story.StoryReplyService; import com.tjoeunit.biz.story.StoryReplyVO; import com.tjoeunit.biz.story.StoryService; import com.tjoeunit.biz.story.StoryVO; @Controller public class StoryController { @Autowired private StoryService storyService; @Autowired private StoryReplyService replyService; // 글 등록 페이지 불러오기 @RequestMapping(value="/story/insertStoryPage.do", method=RequestMethod.GET) public String insertStoryPage() throws IOException { System.out.println("여행 이야기 등록 페이지 호출"); return null; } // 글 등록 @RequestMapping(value="/story/insertStory.do", method=RequestMethod.POST) public String insertStory(StoryVO vo, Model model) throws Exception { System.out.println("여행이야기 등록 처리"); int cnt = storyService.insertStory(vo); String msg="여행 이야기 등록 실패", url="/story/insertStoryPage.do"; if(cnt>0) { msg="등록되었습니다."; url="/story/getStoryList.do"; } model.addAttribute("msg", msg); model.addAttribute("url", url); return "common/message"; } // 글 수정 페이지 불러오기 @RequestMapping(value="/story/updateStoryPage.do", method=RequestMethod.GET) public String updateStoryPage(StoryVO vo, Model model) throws IOException { System.out.println("여행 이야기 수정 페이지 호출"); StoryVO story = storyService.getStory(vo); model.addAttribute("story", story); return null; } // 글 수정 @RequestMapping("/story/updateStory.do") public String updateStory(StoryVO vo, Model model) throws Exception { System.out.println("여행 이야기 수정 처리"); int cnt = storyService.updateStory(vo); String msg="수정 실패", url="/story/updateStoryPage.do"; if(cnt>0) { msg="수정되었습니다."; url="/story/getStory.do?story_no="+vo.getStory_no(); } model.addAttribute("msg", msg); model.addAttribute("url", url); return "common/message"; } // 글 삭제 @RequestMapping("/story/deleteStory.do") public String deleteStory(StoryVO vo, Model model) throws Exception { System.out.println("여행 이야기 삭제 기능 처리"); storyService.deleteStory(vo); String msg="삭제되었습니다."; String url="/story/getStoryList.do"; model.addAttribute("msg", msg); model.addAttribute("url", url); return "common/message"; } /* 글 목록 보기 : 페이징 처리 전 @RequestMapping(value="/getStoryList.do", method = RequestMethod.GET) public String getStoryList(StoryVO vo, Model model) { //ModelAndView의 Model 딴에 있는 변수를 매개변수로 List<StoryVO> storyList = storyService.getStoryList(vo); model.addAttribute("storyList", storyList); //key Value System.out.println("여행 이야기 목록 보기"); return "story/getStoryList"; } */ // 글 목록 보기 : 페이징 처리 후 @RequestMapping(value="/story/getStoryList.do", method = RequestMethod.GET) public String storyListPaging(PagingVO vo, Model model, @RequestParam(value="nowPage", required=false) String nowPage, @RequestParam(value="cntPerPage", required=false) String cntPerPage) { int total = storyService.countStory(); if (nowPage == null && cntPerPage == null) { nowPage = "1"; cntPerPage = "20"; } else if (nowPage == null) { nowPage = "1"; } else if (cntPerPage == null) { cntPerPage = "20"; } vo = new PagingVO(total, Integer.parseInt(nowPage), Integer.parseInt(cntPerPage)); model.addAttribute("paging", vo); model.addAttribute("storyList", storyService.selectStory(vo)); return "story/getStoryList"; } // 글 상세 조회 @RequestMapping(value="/story/getStory.do", method = RequestMethod.GET) public String getStory(StoryVO vo, Model model) { System.out.println("여행 이야기 상세 조회 처리"); storyService.viewCountStory(vo); StoryVO story = storyService.getStory(vo); model.addAttribute("story", story); //댓글 목록 조회 List<StoryReplyVO> replyList = replyService.getReplyList(vo.getStory_no()); model.addAttribute("replyList", replyList); return "story/getStory"; } // 댓글 작성 @RequestMapping(value="/story/replyWrite.do", method = RequestMethod.POST) public String replyWrite(StoryVO vo, StoryReplyVO rvo, Model model) throws Exception { System.out.println("댓글 등록 처리"); int cnt = replyService.createReply(rvo); String msg="댓글 등록 실패", url="/story/getStory.do?story_no="+vo.getStory_no(); if(cnt>0) { msg="댓글이 등록되었습니다."; url="/story/getStory.do?story_no="+vo.getStory_no(); } model.addAttribute("msg", msg); model.addAttribute("url", url); return "common/message"; } // 댓글 삭제 @RequestMapping(value= "/story/replyDelete.do", method=RequestMethod.GET) public String replyDelete(StoryReplyVO rvo, Model model, StoryVO vo, HttpSession session) throws Exception { System.out.println("댓글 삭제 처리"); // 댓글을 보여줄 때 c:foreach로 보여주기 때문에 jsp x 컨트롤러 o // 로그인 중인 회원의 아이디와 댓글 작성자의 아이디를 비교 세션에 아이디 값이 없는 경우도 처리 System.out.println("스토리 번호 = "+vo.getStory_no()); System.out.println("코멘트 번호 = "+rvo.getReply_no()); // 세션을 통해 로그인 중인 회원의 아이디를 추출 String session_id = ""; if(session.getAttribute("members_id") != null) { session_id = (String)session.getAttribute("members_id"); } System.out.println("로그인 회원 아이디 = "+session_id); // 댓글번호를 통해 댓글 작성자의 아이디를 추출 String reply_id = replyService.selectIdByReplyNo(rvo.getReply_no()); System.out.println("댓글 작성자 아이디 = "+reply_id); String msg = ""; String url = ""; // 세션에 아이디 없음 if(session_id.isEmpty()) { System.out.println("로그인 중인 아이디 없음"); msg = "로그인이 필요한 서비스입니다"; url = "/story/getStory.do?story_no="+vo.getStory_no(); // 아이디가 같은 경우 (메서드 실행) }else if(session_id.equals(reply_id)) { System.out.println("아이디 일치"); msg = "댓글이 삭제되었습니다"; url = "/story/getStory.do?story_no="+vo.getStory_no(); replyService.deleteReply(rvo); // 아이디가 다른 경우 }else { System.out.println("아이디 불일치"); msg = "아이디가 일치하지 않습니다"; url = "/story/getStory.do?story_no="+vo.getStory_no(); } model.addAttribute("msg", msg); model.addAttribute("url", url); return "common/message"; } /* 관리자 관련 컨트롤러 */ // adminStory로 이동 @RequestMapping(value="/adminStory/adminStory.do", method=RequestMethod.GET) public String adminStory(PagingVO vo, Model model, @RequestParam(value="nowPage", required=false) String nowPage, @RequestParam(value="cntPerPage", required=false) String cntPerPage) { System.out.println("여행이야기 관리자 목록으로 이동"); int total = storyService.countStory(); if (nowPage == null && cntPerPage == null) { nowPage = "1"; cntPerPage = "20"; } else if (nowPage == null) { nowPage = "1"; } else if (cntPerPage == null) { cntPerPage = "20"; } vo = new PagingVO(total, Integer.parseInt(nowPage), Integer.parseInt(cntPerPage)); model.addAttribute("paging", vo); model.addAttribute("storyList", storyService.selectStory(vo)); return "/adminStory/adminStory"; } // 글 상세 조회 @RequestMapping(value="/adminStory/adminStoryDetail.do", method = RequestMethod.GET) public String adminStoryDetail(StoryVO vo, Model model) { System.out.println("여행 이야기 관리자 상세 조회 처리"); StoryVO story = storyService.getStory(vo); model.addAttribute("story", story); //댓글 목록 조회 List<StoryReplyVO> replyList = replyService.getReplyList(vo.getStory_no()); model.addAttribute("replyList", replyList); return "adminStory/adminStoryDetail"; } // 사용자 댓글 삭제 @RequestMapping(value= "/adminStory/adminReplyDelete.do", method=RequestMethod.GET) public String adminReplyDelete(StoryReplyVO rvo, Model model, StoryVO vo) throws Exception { System.out.println("댓글 삭제 처리"); replyService.deleteReply(rvo); String msg="[관리자] 댓글을 삭제했습니다."; String url="/adminStory/adminStoryDetail.do?story_no="+vo.getStory_no(); model.addAttribute("msg", msg); model.addAttribute("url", url); return "common/message"; } // 부적합한 게시글 삭제 @RequestMapping("/adminStory/adminStoryDelete.do") public String adminStoryDelete(StoryVO vo, Model model, StoryReplyVO rvo) throws Exception { System.out.println("여행 이야기 관리자 게시글 삭제 기능 처리"); replyService.deleteReply(rvo); storyService.deleteStory(vo); String msg="[관리자] 게시글을 삭제했습니다."; String url="/adminStory/adminStory.do"; model.addAttribute("msg", msg); model.addAttribute("url", url); return "common/message"; } } <file_sep>/src/main/java/com/tjoeunit/biz/members/Impl/MembersDAO.java package com.tjoeunit.biz.members.Impl; import java.util.List; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.tjoeunit.biz.members.MembersVO; import com.tjoeunit.biz.payment.PaymentVO; @Repository public class MembersDAO { @Autowired private SqlSessionTemplate mybatis; public int insertMembers(MembersVO vo) { return mybatis.insert("membersDAOTemplate.insertMembers", vo); } public int checkIdDup(String members_id) { return mybatis.selectOne("membersDAOTemplate.checkIdDup", members_id); } public int deleteMembers(int members_no) { return mybatis.delete("membersDAOTemplate.deleteMembers", members_no); } public String checkMembersPw(String members_id) { return mybatis.selectOne("membersDAOTemplate.checkMembersPw", members_id); } public MembersVO selectByMembersId(String members_id) { return mybatis.selectOne("membersDAOTemplate.selectByMembersId" ,members_id); } public MembersVO selectByMembersNo(int members_no) { return mybatis.selectOne("membersDAOTemplate.selectByMembersNo", members_no); } public String checkPwById(String members_id) { return mybatis.selectOne("membersDAOTemplate.checkPwById", members_id); } public int updatePw(MembersVO vo) { return mybatis.update("membersDAOTemplate.updatePw", vo); } public int updateMembers(MembersVO vo) { return mybatis.update("membersDAOTemplate.updateMembers", vo); } public List<MembersVO> getMembersList(MembersVO vo) { return mybatis.selectList("membersDAOTemplate.getMembersList", vo); } } <file_sep>/src/main/java/com/tjoeunit/view/payment/PaymentController.java package com.tjoeunit.view.payment; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.tjoeunit.biz.common.PagingVO; import com.tjoeunit.biz.payment.PaymentService; import com.tjoeunit.biz.payment.PaymentVO; @Controller public class PaymentController { @Autowired private PaymentService paymentService; @RequestMapping(value="/payment/payment.do", method=RequestMethod.POST) @ResponseBody public int PaymentPage(PaymentVO vo, Model model, HttpServletRequest request) { String members_no = request.getParameter("members_no"); String flight_no = request.getParameter("flight_no"); String activity_no = request.getParameter("activity_no"); String lantrip_no = request.getParameter("lantrip_no"); String hotel_no = request.getParameter("hotel_no"); String payment_bookdate = request.getParameter("payment_bookdate"); String payment_quantity = request.getParameter("payment_quantity"); String payment_price = request.getParameter("payment_price"); String flight_title = request.getParameter("flight_title"); String hotel_title = request.getParameter("hotel_title"); String activity_title = request.getParameter("activity_title"); String lantrip_title = request.getParameter("lantrip_title"); String product_category = request.getParameter("product_category"); vo.setMembers_no(members_no); vo.setActivity_no(activity_no); vo.setFlight_no(flight_no); vo.setLantrip_no(lantrip_no); vo.setHotel_no(hotel_no); vo.setPayment_bookdate(payment_bookdate); vo.setPayment_quantity(payment_quantity); vo.setPayment_price(payment_price); vo.setFlight_title(flight_title); vo.setHotel_title(hotel_title); vo.setActivity_title(activity_title); vo.setLantrip_title(lantrip_title); vo.setProduct_category(product_category); System.out.println("카카오페이 결제 payment_no = seq"); System.out.println("카카오페이 결제 vo="+vo); int result = paymentService.insertPayment(vo); System.out.println("카카오페이 결제 result="+result); return result; } // 관리자 결제정보 @RequestMapping(value="/adminPayment/adminPaymentList.do", method=RequestMethod.GET) public String adminPaymentInfoPage(PagingVO vo, Model model, @RequestParam(value="nowPage", required=false) String nowPage, @RequestParam(value="cntPerPage", required=false) String cntPerPage) { int total = paymentService.countPayment(); if (nowPage == null && cntPerPage == null) { nowPage = "1"; cntPerPage = "20"; } else if (nowPage == null) { nowPage = "1"; } else if (cntPerPage == null) { cntPerPage = "20"; } vo = new PagingVO(total, Integer.parseInt(nowPage), Integer.parseInt(cntPerPage)); model.addAttribute("paging", vo); model.addAttribute("paymentList", paymentService.selectPayment(vo)); return "adminPayment/adminPaymentList"; } } <file_sep>/src/main/java/com/tjoeunit/biz/activity/ActivityVO.java package com.tjoeunit.biz.activity; public class ActivityVO { private int activity_no; private String activity_title; private String activity_content; private String activity_thumb; private int activity_price; private String activity_area; private String activity_video; /* * private String activity_video; private String activity_img1; private String * activity_img2; private String activity_img3; private String activity_img4; * private String activity_img5; */ // 콜솔에서 확인 가능 @Override public String toString() { return "ActivityVO [activity_no="+activity_no+", activity_title="+activity_title+", activity_content="+activity_content +", activity_thumb="+activity_thumb+", activity_price="+activity_price+", activity_area="+activity_area+"]"; } public int getActivity_no() { return activity_no; } public void setActivity_no(int activity_no) { this.activity_no = activity_no; } public String getActivity_title() { return activity_title; } public void setActivity_title(String activity_title) { this.activity_title = activity_title; } public String getActivity_content() { return activity_content; } public void setActivity_content(String activity_content) { this.activity_content = activity_content; } public String getActivity_thumb() { return activity_thumb; } public void setActivity_thumb(String activity_thumb) { this.activity_thumb = activity_thumb; } public int getActivity_price() { return activity_price; } public void setActivity_price(int activity_price) { this.activity_price = activity_price; } public String getActivity_area() { return activity_area; } public void setActivity_area(String activity_area) { this.activity_area = activity_area; } public String getActivity_video() { return activity_video; } public void setActivity_video(String activity_video) { this.activity_video = activity_video; } } <file_sep>/src/main/java/com/tjoeunit/biz/activity/ActivityService.java package com.tjoeunit.biz.activity; import java.util.List; import com.tjoeunit.biz.common.PagingVO; import com.tjoeunit.biz.activity.ActivityVO; public interface ActivityService { // CRUD 기능의 메서드 구현 // 액티비티 등록 int insertActivity(ActivityVO vo); // 액티비티 목록 List<ActivityVO> getActivityList(ActivityVO vo); // 액티비티 상세 조회 ActivityVO getActivity(ActivityVO vo); // 액티비티 수정 int updateActivity(ActivityVO vo); // 액티비티 삭제 int deleteActivity(ActivityVO vo); //페이징처리를 위해 생성 : 게시물 총 개수 int countActivity(); //페이징처리를 위해 생성 : 항공권 조회 List<ActivityVO> selectActivity(PagingVO vo); } <file_sep>/src/main/webapp/sql/DB_Create_0422-1.sql CREATE TABLE ADMIN ( ADMIN_NO NUMBER NOT NULL, ADMIN_ID VARCHAR2(300), ADMIN_PW VARCHAR2(300), ADMIN_NAME VARCHAR2(300), ADMIN_TEL VARCHAR2(300), JOIN_DATE DATE default sysdate ); ALTER TABLE ADMIN ADD CONSTRAINT PK_ADMIN PRIMARY KEY ( ADMIN_NO ); CREATE TABLE MEMBERS ( MEMBERS_NO NUMBER NOT NULL, MEMBERS_ID VARCHAR2(300), MEMBERS_PW VARCHAR2(300), MEMBERS_NAME VARCHAR2(300), MEMBERS_TEL VARCHAR2(100), MEMBERS_EMAIL VARCHAR2(300), MEMBERS_REGDATE DATE default sysdate, MEMBERS_OUTDATE DATE, MEMBERS_GENDER VARCHAR2(300), MEMBERS_ZIPCODE VARCHAR2(300), MEMBERS_ADDRESS VARCHAR2(300), MEMBERS_ADDRESS_DETAIL VARCHAR2(300) ); ALTER TABLE MEMBERS ADD CONSTRAINT PK_MEMBERS PRIMARY KEY ( MEMBERS_NO ); CREATE TABLE STORY ( STORY_NO NUMBER NOT NULL, MEMBERS_NO NUMBER, STORY_TITLE VARCHAR2(300), STORY_CONTENT CLOB, STORY_WRITER VARCHAR2(300), STORY_CNT NUMBER default 0, STORY_DATE DATE default sysdate ); ALTER TABLE STORY ADD CONSTRAINT PK_STORY PRIMARY KEY ( STORY_NO ); ALTER TABLE STORY ADD CONSTRAINT FK_MEMBERS_TO_STORY FOREIGN KEY ( MEMBERS_NO ) REFERENCES MEMBERS ( MEMBERS_NO ); CREATE TABLE FLIGHT ( FLIGHT_NO NUMBER NOT NULL, FLIGHT_TITLE VARCHAR2(300), FLIGHT_CONTENT VARCHAR2(3000), FLIGHT_IMG1 VARCHAR2(1500), FLIGHT_THUMB VARCHAR2(1500), FLIGHT_PRICE VARCHAR2(300), FLIGHT_DEPARTURE VARCHAR2(300), FLIGHT_ARRIVAL VARCHAR2(300) ); ALTER TABLE FLIGHT ADD CONSTRAINT PK_FLIGHT PRIMARY KEY ( FLIGHT_NO ); CREATE TABLE HOTEL ( HOTEL_NO NUMBER NOT NULL, HOTEL_TITLE VARCHAR2(300), HOTEL_CONTENT VARCHAR2(3000), HOTEL_IMG VARCHAR2(1500), HOTEL_THUMB VARCHAR2(1500), HOTEL_PRICE VARCHAR2(300), HOTEL_CATEGORY VARCHAR2(300), HOTEL_AREA VARCHAR2(300) ); ALTER TABLE HOTEL ADD CONSTRAINT PK_HOTEL PRIMARY KEY ( HOTEL_NO ); CREATE TABLE ACTIVITY ( ACTIVITY_NO NUMBER NOT NULL, ACTIVITY_TITLE VARCHAR2(300), ACTIVITY_CONTENT VARCHAR2(3000), ACTIVITY_IMG VARCHAR2(1500), ACTIVITY_THUMB VARCHAR2(1500), ACTIVITY_PRICE VARCHAR2(300), ACTIVITY_VIDEO VARCHAR2(1500), ACTIVITY_AREA VARCHAR2(300) ); ALTER TABLE ACTIVITY ADD CONSTRAINT PK_ACTIVITY PRIMARY KEY ( ACTIVITY_NO ); CREATE TABLE LANTRIP ( LANTRIP_NO NUMBER NOT NULL, LANTRIP_TITLE VARCHAR2(300), LANTRIP_CONTENT VARCHAR2(3000), LANTRIP_IMG1 VARCHAR2(1500), LANTRIP_THUMB VARCHAR2(1500), LANTRIP_PRICE VARCHAR2(300), LANTRIP_VIDEO VARCHAR2(1500), LANTRIP_AREA VARCHAR2(300) ); ALTER TABLE LANTRIP ADD CONSTRAINT PK_LANTRIP PRIMARY KEY ( LANTRIP_NO ); CREATE TABLE PRACTICE ( PRACTICE_NO NUMBER NOT NULL, PRACTICE_TITLE VARCHAR2(300), PRACTICE_CONTENT VARCHAR2(3000) ); ALTER TABLE PRACTICE ADD CONSTRAINT PK_PRACTICE PRIMARY KEY ( PRACTICE_NO ); CREATE TABLE QNA ( QNA_NO NUMBER NOT NULL, MEMBERS_NO NUMBER, QNA_TITLE VARCHAR2(300), QNA_CONTENT VARCHAR2(3000), QNA_WRITER VARCHAR2(300), QNA_DATE DATE default sysdate ); ALTER TABLE QNA ADD CONSTRAINT PK_QNA PRIMARY KEY ( QNA_NO ); ALTER TABLE QNA ADD CONSTRAINT FK_MEMBERS_TO_QNA FOREIGN KEY ( MEMBERS_NO ) REFERENCES MEMBERS ( MEMBERS_NO ); CREATE TABLE PAYMENT ( PAYMENT_NO NUMBER NOT NULL, MEMBERS_NO NUMBER, FLIGHT_NO NUMBER, HOTEL_NO NUMBER, ACTIVITY_NO NUMBER, LANTRIP_NO NUMBER, PAYMENT_BOOKDATE DATE default sysdate, PAYMENT_QUANTITY VARCHAR2(300), PAYMENT_PRICE VARCHAR2(300), PAYMENT_DATE DATE default sysdate ); ALTER TABLE PAYMENT ADD CONSTRAINT PK_PAYMENT PRIMARY KEY ( PAYMENT_NO ); ALTER TABLE PAYMENT ADD CONSTRAINT FK_MEMBERS_TO_PAYMENT FOREIGN KEY ( MEMBERS_NO ) REFERENCES MEMBERS ( MEMBERS_NO ); ALTER TABLE PAYMENT ADD CONSTRAINT FK_FLIGHT_TO_PAYMENT FOREIGN KEY ( FLIGHT_NO ) REFERENCES FLIGHT ( FLIGHT_NO ); ALTER TABLE PAYMENT ADD CONSTRAINT FK_HOTEL_TO_PAYMENT FOREIGN KEY ( HOTEL_NO ) REFERENCES HOTEL ( HOTEL_NO ); ALTER TABLE PAYMENT ADD CONSTRAINT FK_ACTIVITY_TO_PAYMENT FOREIGN KEY ( ACTIVITY_NO ) REFERENCES ACTIVITY ( ACTIVITY_NO ); ALTER TABLE PAYMENT ADD CONSTRAINT FK_LANTRIP_TO_PAYMENT FOREIGN KEY ( LANTRIP_NO ) REFERENCES LANTRIP ( LANTRIP_NO ); /* 시퀀스 */ CREATE SEQUENCE MEMBERS_SEQ increment by 1 start with 1 nocache; CREATE SEQUENCE FLIGHT_SEQ increment by 1 start with 1 nocache; CREATE SEQUENCE HOTEL_SEQ increment by 1 start with 1 nocache; CREATE SEQUENCE ACTIVITY_SEQ increment by 1 start with 1 nocache; CREATE SEQUENCE LANTRIP_SEQ increment by 1 start with 1 nocache; CREATE SEQUENCE PAYMENT_SEQ increment by 1 start with 1 nocache; CREATE SEQUENCE STORY_SEQ increment by 1 start with 1 nocache; CREATE SEQUENCE ADMIN_SEQ increment by 1 start with 1 nocache; CREATE SEQUENCE QNA_SEQ increment by 1 start with 1 nocache; CREATE SEQUENCE PRACTICE_SEQ increment by 1 start with 1 nocache; /* 관리자 정보 입력 */ INSERT INTO ADMIN (ADMIN_NO, ADMIN_ID, ADMIN_PW, ADMIN_NAME, ADMIN_TEL, JOIN_DATE) VALUES(999, 'admin', '1004', '운영자', '010-1004-1004', sysdate); commit<file_sep>/src/main/java/com/tjoeunit/biz/hotel/HotelService.java package com.tjoeunit.biz.hotel; import java.util.List; import com.tjoeunit.biz.common.PagingVO; import com.tjoeunit.biz.flight.FlightVO; public interface HotelService { //숙박권 등록 int insertHotel(HotelVO vo); //숙박 목록 조회 List<HotelVO> getHotelList(HotelVO vo); //숙박 상세 조회 HotelVO getHotel(HotelVO vo); //숙박권 수정 int updateHotel(HotelVO vo); //숙박권 삭제. int deleteHotel(HotelVO vo); //페이징처리를 위해 생성 : 게시물 총 개수 int countHotel(); //페이징처리를 위해 생성 : 항공권 조회 List<HotelVO> selectHotel(PagingVO vo); } <file_sep>/src/main/java/com/tjoeunit/view/hotel/HotelController.java package com.tjoeunit.view.hotel; import java.io.File; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import com.tjoeunit.biz.common.PagingVO; import com.tjoeunit.biz.hotel.HotelService; import com.tjoeunit.biz.hotel.HotelVO; @Controller public class HotelController { @Autowired private HotelService hotelService; // 숙박 결제 정보 받아서 결제 페이지로 보내기 @RequestMapping(value="/hotel/hotelPayment.do", method=RequestMethod.POST) public String flightPaymentPage(HttpServletRequest request, Model model) { String members_no = (String)request.getParameter("members_no"); String hotel_no = request.getParameter("hotel_no"); String payment_price = request.getParameter("payment_price"); String payment_quantity = request.getParameter("payment_quantity"); String payment_bookdate = request.getParameter("payment_bookdate"); String hotel_title = request.getParameter("hotel_title"); String product_category = request.getParameter("product_category"); System.out.println("members_no="+members_no); System.out.println("hotel_no="+hotel_no); System.out.println("payment_price="+payment_price); System.out.println("payment_quantity="+payment_quantity); System.out.println("payment_bookdate="+payment_bookdate); System.out.println("hotel_title="+hotel_title); System.out.println("product_category="+product_category); model.addAttribute("members_no", members_no); model.addAttribute("hotel_no", hotel_no); model.addAttribute("payment_price", payment_price); model.addAttribute("payment_quantity", payment_quantity); model.addAttribute("payment_bookdate", payment_bookdate); model.addAttribute("hotel_title", hotel_title); model.addAttribute("product_category", product_category); return "payment/payment"; } //숙박권 등록 페이지 @RequestMapping(value="/hotel/insertHotel.do", method = RequestMethod.GET) public String insertHotelPage(){ System.out.println("숙박 등록 화면 보기 처리"); return "hotel/insertHotel"; } // 숙박 등록 처리 @RequestMapping(value ="/hotel/insertHotel.do", method = RequestMethod.POST) public String insertHotel(HotelVO vo, HttpSession session, MultipartFile[] hotelImgUpload, Model model) throws Exception { System.out.println("숙박권 등록 처리"); // 파일 업로드 처리 String hotelImg = session.getServletContext().getRealPath("/hotelUpload/"); System.out.println("==>"+hotelImgUpload.length); for(int i = 0; i < hotelImgUpload.length; i++) { System.out.println("==>"+hotelImgUpload[i].isEmpty()); if(!hotelImgUpload[i].isEmpty()) { String hotelUploadName = hotelImgUpload[i].getOriginalFilename(); hotelImgUpload[i].transferTo(new File(hotelImg+hotelUploadName)); switch(i) { case 0 : vo.setHotel_thumb(hotelUploadName); break; } }else { switch(i) { case 0 : vo.setHotel_thumb(null); } } } // DB연동처리 System.out.println(vo); int cnt = hotelService.insertHotel(vo); String msg="숙박권 등록 실패", url="/hotel/insertHotel.do"; if(cnt>0) { msg="숙박권 등록 성공"; url="/hotel/getHotelList.do"; } model.addAttribute("msg", msg); model.addAttribute("url", url); return "common/message"; } // 숙박권 목록 보기 : 페이징 처리 전 목록 컨트롤러 /*@RequestMapping(value="/hotel/getHotelList.do", method = RequestMethod.GET) public String getHotelList(HotelVO vo, Model model){ System.out.println("숙박 목록 검색 처리"); List<HotelVO> hotelList = hotelService.getHotelList(vo); model.addAttribute("hotelList", hotelList); return "hotel/getHotelList"; } // 모델에는 2개의 값이 담긴다. 모델엔 뷰니까 모델값과 뷰값*/ // 숙박권 목록 보기 : 페이징 처리 후 목록 컨트롤러 @RequestMapping(value="/hotel/getHotelList.do", method = RequestMethod.GET) public String hotelListPaging(PagingVO vo, Model model, @RequestParam(value="nowPage", required=false) String nowPage, @RequestParam(value="cntPerPage", required=false) String cntPerPage) { int total = hotelService.countHotel(); if (nowPage == null && cntPerPage == null) { nowPage = "1"; cntPerPage = "20"; } else if (nowPage == null) { nowPage = "1"; } else if (cntPerPage == null) { cntPerPage = "20"; } vo = new PagingVO(total, Integer.parseInt(nowPage), Integer.parseInt(cntPerPage)); model.addAttribute("paging", vo); model.addAttribute("hotelList", hotelService.selectHotel(vo)); return "hotel/getHotelList"; } // 숙박권 상세 조회 @RequestMapping(value="/hotel/getHotel.do", method = RequestMethod.GET) public String getHotel(HotelVO vo, Model model){ //vo에 hotel_no 값이 저장되어 있는지 확인 System.out.println("숙박권 상세 페이지 hotel_no = " + vo.getHotel_no()); //hotel_no 를 이용하여 전체 정보를 flight에 저장 HotelVO hotel = hotelService.getHotel(vo); System.out.println("숙박권 정보 " + hotel); //hotel에 저장된 값을 모델에 키 밸류로 저장 model.addAttribute("hotel",hotel); //보여줄 페이지 리턴 return "hotel/getHotel"; } // 숙박권 수정 페이지 @RequestMapping(value="/hotel/updateHotel.do", method = RequestMethod.GET) public String updateHotelPage(HotelVO vo,Model model){ //vo에 hotel_no 값이 저장되어 있는지 확인 System.out.println("숙박권 수정 화면 보기 처리"); //hotel_no 를 이용하여 전체 정보를 hotel에 저장 HotelVO hotel = hotelService.getHotel(vo); System.out.println("숙박권 정보 " + hotel); //flight에 저장된 값을 모델에 키 밸류로 저장 model.addAttribute("hotel",hotel); return "hotel/updateHotel"; } // 숙박권 수정 처리 @RequestMapping(value = "/hotel/updateHotel.do", method = RequestMethod.POST) public String updateHotel(HotelVO vo, HttpSession session, MultipartFile[] hotelImgUpload, HttpServletRequest request, Model model) throws Exception { System.out.println("수정 처리 전 숙박권 vo = " + vo); // 1. hotelImg 에 경로 지정 String hotelImg = session.getServletContext().getRealPath("/hotelUpload/"); // 2. 업로드 할 이미지 개수 확인 System.out.println("==>"+hotelImgUpload.length); // 3. 업로드 할 사진이 존재하지 않을 때 (기존 썸네일 선택 시 input 태그의 type 설정을 text로 지정하고 페이지를 불러들일 때 부터 DB 저장된 값을 value 에 넣어둠) if(hotelImgUpload.length < 1) { // DB 에서 읽어 온 값을 그대로 vo 에 저장시킴 String hotel_thumb = request.getParameter("hotelImgUpload"); System.out.println("기존 썸네일 사용 시 파일명 : " + hotel_thumb); vo.setHotel_thumb(hotel_thumb); // 4. 업로드 할 사진이 존재할 때 }else { for(int i = 0; i < hotelImgUpload.length; i++) { String hotelUploadName = hotelImgUpload[i].getOriginalFilename(); hotelImgUpload[i].transferTo(new File(hotelImg+hotelUploadName)); System.out.println("변경 썸네일 사용 시 파일명 : " + hotelUploadName); } } System.out.println("수정 처리 될 숙박권 vo = " + vo); int cnt = hotelService.updateHotel(vo); String msg="숙박권 수정 실패", url="/hotel/updateHotel.do?hotel_no="+vo.getHotel_no(); if(cnt>0) { msg="숙박권 수정 성공"; url="/hotel/getHotel.do?hotel_no="+vo.getHotel_no(); } model.addAttribute("msg", msg); model.addAttribute("url", url); return "common/message"; } // 숙박권 삭제 @RequestMapping(value ="/hotel/deleteHotel.do") public String deleteHotel(HotelVO vo,Model model){ System.out.println("숙박권 삭제 처리 hotel_no = " + vo.getHotel_no()); int cnt = hotelService.deleteHotel(vo); String msg="숙박권 삭제 실패", url="/hotel/getHotle.do?hotel_no="+vo.getHotel_no(); if(cnt>0) { msg="숙박권 삭제 성공"; url="/hotel/getHotelList.do"; } model.addAttribute("msg", msg); model.addAttribute("url", url); return "common/message"; } //////////////////////////////////////////////////관리자//////////////////////////////////////////////////////// //////////////////////////////////////////////////관리자//////////////////////////////////////////////////////// //////////////////////////////////////////////////관리자//////////////////////////////////////////////////////// //////////////////////////////////////////////////관리자//////////////////////////////////////////////////////// //////////////////////////////////////////////////관리자//////////////////////////////////////////////////////// //////////////////////////////////////////////////관리자//////////////////////////////////////////////////////// // 관리자 숙박권 목록 페이지로 이동 /* @RequestMapping(value="/adminHotel/adminHotel.do", method=RequestMethod.GET) public String adminHotel(HotelVO vo, Model model) { System.out.println("숙박권 관리자 목록으로 이동"); List<HotelVO> hotelList = hotelService.getHotelList(vo); model.addAttribute("hotelList", hotelList); return "adminHotel/adminHotel"; } */ // 관리자 항공권 목록 페이지 : 페이징 처리 후 목록 컨트롤러 @RequestMapping(value="/adminHotel/adminHotel.do", method = RequestMethod.GET) public String adminHotelListPaging(PagingVO vo, Model model, @RequestParam(value="nowPage", required=false) String nowPage, @RequestParam(value="cntPerPage", required=false) String cntPerPage) { int total = hotelService.countHotel(); if (nowPage == null && cntPerPage == null) { nowPage = "1"; cntPerPage = "20"; } else if (nowPage == null) { nowPage = "1"; } else if (cntPerPage == null) { cntPerPage = "20"; } vo = new PagingVO(total, Integer.parseInt(nowPage), Integer.parseInt(cntPerPage)); model.addAttribute("paging", vo); model.addAttribute("hotelList", hotelService.selectHotel(vo)); return "adminHotel/adminHotel"; } // 관리자 숙박권 등록 페이지로 이동 @RequestMapping(value="/adminHotel/insertHotel.do", method = RequestMethod.GET) public String adminInsertHotelPage(){ return "adminHotel/insertHotel"; } // 관리자 숙박권 등록 처리 @RequestMapping(value ="/adminHotel/insertHotel.do", method = RequestMethod.POST) public String adminInsertHotel(HotelVO vo, HttpSession session, MultipartFile[] hotelImgUpload, Model model) throws Exception { System.out.println("숙박권 등록 처리"); // 파일 업로드 처리 String hotelImg = session.getServletContext().getRealPath("/hotelUpload/"); System.out.println("==>"+hotelImgUpload.length); for(int i = 0; i < hotelImgUpload.length; i++) { System.out.println("==>"+hotelImgUpload[i].isEmpty()); if(!hotelImgUpload[i].isEmpty()) { String hotelUploadName = hotelImgUpload[i].getOriginalFilename(); hotelImgUpload[i].transferTo(new File(hotelImg+hotelUploadName)); switch(i) { case 0 : vo.setHotel_thumb(hotelUploadName); break; } }else { switch(i) { case 0 : vo.setHotel_thumb(null); } } } // DB연동처리 System.out.println(vo); int cnt = hotelService.insertHotel(vo); String msg="숙박권 등록 실패", url="/adminHotel/insertHotel.do"; if(cnt>0) { msg="숙박권 등록 성공"; url="/adminHotel/adminHotel.do"; } model.addAttribute("msg", msg); model.addAttribute("url", url); // 화면전환 return "common/message"; } // 관리자 숙박권 상세보기 @RequestMapping(value="/adminHotel/adminHotelDetail.do", method = RequestMethod.GET) public String getAdminHotel(HotelVO vo, Model model){ System.out.println("숙박권 상세 페이지"); HotelVO hotel = hotelService.getHotel(vo); model.addAttribute("hotel",hotel); return "adminHotel/adminHotelDetail"; } // 관리자 숙박권 삭제 처리 @RequestMapping(value="/adminHotel/adminHotelDelete.do") public String adminHotelDelete(HotelVO vo,Model model){ System.out.println("숙박권 삭제 처리 hotle_no = " + vo.getHotel_no()); int cnt = hotelService.deleteHotel(vo); String msg="숙박권 삭제 실패", url="/adminHotle/adminHotelDetail.do?hotel_no="+vo.getHotel_no(); if(cnt>0) { msg="숙박권 삭제 성공"; url="/adminHotel/adminHotel.do"; } model.addAttribute("msg", msg); model.addAttribute("url", url); return "common/message"; } // 관리자 숙박권 수정 페이지로 이동 @RequestMapping(value ="/adminHotel/adminHotelUpdate.do", method = RequestMethod.GET) public String adminupdateHotel(HotelVO vo, Model model) { //vo에 hotel_no 값이 저장되어 있는지 확인 System.out.println("숙박권 수정 페이지 hotel_no = " + vo.getHotel_no()); //hotel_no 를 이용하여 전체 정보를 hotel에 저장 HotelVO hotel = hotelService.getHotel(vo); System.out.println("숙박권 정보 " + hotel); //hotel에 저장된 값을 모델에 키 밸류로 저장 model.addAttribute("hotel", hotel); return "adminHotel/adminHotelUpdate"; } // 관리자 숙박권 수정 처리 @RequestMapping(value = "/adminHotel/adminHotelUpdate.do", method = RequestMethod.POST) public String adminHotelUpdate(HotelVO vo, HttpSession session, MultipartFile[] hotelImgUpload, HttpServletRequest request, Model model) throws Exception { System.out.println("수정 처리 전 숙박권 vo = " + vo); // 1. hotelImg 에 경로 지정 String hotelImg = session.getServletContext().getRealPath("/hotelUpload/"); // 2. 업로드 할 이미지 개수 확인 System.out.println("==>"+hotelImgUpload.length); // 3. 업로드 할 사진이 존재하지 않을 때 (기존 썸네일 선택 시 input 태그의 type 설정을 text로 지정하고 페이지를 불러들일 때 부터 DB 저장된 값을 value 에 넣어둠) if(hotelImgUpload.length < 1) { // DB 에서 읽어 온 값을 그대로 vo 에 저장시킴 String hotel_thumb = request.getParameter("hotelImgUpload"); System.out.println("기존 썸네일 사용 시 파일명 : " + hotel_thumb); vo.setHotel_thumb(hotel_thumb); // 4. 업로드 할 사진이 존재할 때 }else { for(int i=0; i<hotelImgUpload.length; i++) { String flightUploadName = hotelImgUpload[i].getOriginalFilename(); hotelImgUpload[i].transferTo(new File(hotelImg+flightUploadName)); System.out.println("변경 썸네일 사용 시 파일명 : " + flightUploadName); vo.setHotel_thumb(flightUploadName); } } System.out.println("수정 처리 될 항공권 vo = " + vo); int cnt = hotelService.updateHotel(vo); String msg="숙박권 수정 실패", url="/adminHotel/adminHotelUpdate.do?hotel_no="+vo.getHotel_no(); if(cnt>0) { msg="항공권 수정 성공"; url="/adminHotel/adminHotelDetail.do?hotel_no="+vo.getHotel_no(); } model.addAttribute("msg", msg); model.addAttribute("url", url); return "common/message"; } } <file_sep>/src/main/java/com/tjoeunit/biz/payment/Impl/PaymentDAO.java package com.tjoeunit.biz.payment.Impl; import java.util.List; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.tjoeunit.biz.common.PagingVO; import com.tjoeunit.biz.payment.PaymentVO; @Repository public class PaymentDAO { @Autowired private SqlSessionTemplate mybatis; public int insertPayment(PaymentVO vo){ return mybatis.insert("paymentDAOTemplate.insertPayment", vo); } public List<PaymentVO> getPaymentList(int members_no) { return mybatis.selectList("paymentDAOTemplate.getPaymentList", members_no); } //페이징처리를 위해 생성 public int countPayment() { return mybatis.selectOne("paymentDAOTemplate.countPayment"); } //페이징처리를 위해 생성 public List<PaymentVO> selectPayment(PagingVO vo) { return mybatis.selectList("paymentDAOTemplate.selectPayment", vo); } } <file_sep>/src/main/java/com/tjoeunit/view/members/MembersController.java package com.tjoeunit.view.members; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.tjoeunit.biz.flight.FlightVO; import com.tjoeunit.biz.members.MembersService; import com.tjoeunit.biz.members.MembersVO; import com.tjoeunit.biz.payment.PaymentService; import com.tjoeunit.biz.payment.PaymentVO; @Controller public class MembersController { @Autowired private MembersService membersService; @Autowired private PaymentService paymentService; //관리자 : 회원수정 처리 @RequestMapping(value="/adminMembers/adminUpdateMembers.do", method=RequestMethod.POST) public String adminUpdateMembers(MembersVO vo, Model model) { System.out.println("관리자 회원 수정 처리 vo = "+vo); String msg="회원 수정 실패", url="/adminMembers/adminMembersDetail.do?members_no="+vo.getMembers_no(); int cnt = membersService.updateMembers(vo); if(cnt>0) { msg="회원 수정 성공"; url="/adminMembers/adminMembersDetail.do?members_no="+vo.getMembers_no(); } model.addAttribute("msg", msg); model.addAttribute("url", url); return "common/message"; } //관리자 : 회원수정 페이지 @RequestMapping(value="/adminMembers/updateMembers.do", method=RequestMethod.GET) public String adminUpdateMembersPage(MembersVO vo, Model model) { System.out.println("관리자 회원 수정 페이지 vo = "+vo); MembersVO members = membersService.selectByMembersNo(vo.getMembers_no()); model.addAttribute("members", members); return "adminMembers/adminUpdateMembers"; } //관리자 : 회원삭제 @RequestMapping(value="/adminMembers/deleteMembers.do", method=RequestMethod.GET) public String adminDeleteMembers(MembersVO vo, Model model) { System.out.println("관리자 회원삭제 members_no = "+vo.getMembers_no()); int cnt = membersService.deleteMembers(vo.getMembers_no()); System.out.println("cnt = "+cnt); String msg="회원 삭제 실패", url="/adminMembers/adminMembersDetail.do?members_no="+vo.getMembers_no(); if(cnt>0) { msg="회원 삭제 성공"; url="/adminMembers/adminMembersList.do"; } model.addAttribute("msg", msg); model.addAttribute("url", url); return "common/message"; } //관리자 : 회원상세 페이지 @RequestMapping(value="/adminMembers/adminMembersDetail.do", method=RequestMethod.GET) public String adminMembersDetail(HttpServletRequest request, Model model) { System.out.println("관리자 회원상세 페이지"); int members_no = Integer.parseInt((request.getParameter("members_no"))); MembersVO members = membersService.selectByMembersNo(members_no); model.addAttribute("members", members); return "adminMembers/adminMembersDetail"; } //관리자 : 회원목록 페이지 @RequestMapping(value="/adminMembers/adminMembersList.do", method=RequestMethod.GET) public String adminMembersList (MembersVO vo, Model model) { System.out.println("관리자 회원목록 페이지"); List<MembersVO> membersList = membersService.getMembersList(vo); System.out.println(membersList); model.addAttribute("membersList", membersList); return "adminMembers/adminMembersList"; } //결제정보 페이지 @RequestMapping(value="/members/infoPayMembers.do", method=RequestMethod.GET) public String infoPayMembersPage(HttpSession session,PaymentVO vo, Model model) { System.out.println("회원결제정보 페이지"); int members_no = (Integer)session.getAttribute("members_no"); List<PaymentVO> paymentList = paymentService.getPaymentList(members_no); model.addAttribute("paymentList", paymentList); return "members/infoPayMembers"; } //회원가입 페이지 @RequestMapping(value="/members/insertMembers.do", method=RequestMethod.GET) public String insertMembersPage() { System.out.println("회원가입 페이지"); return "members/insertMembers"; } //회원가입 처리 @RequestMapping(value="/members/insertMembers.do", method=RequestMethod.POST) public String insertMembers(MembersVO vo, Model model) throws Exception { System.out.println("회원가입 처리"); int cnt = membersService.insertMembers(vo); String msg="회원 가입 실패", url="/members/insertMembers.do"; if(cnt>0) { msg="회원 가입 성공"; url="/index.do"; } model.addAttribute("msg", msg); model.addAttribute("url", url); model.addAttribute("member_id", vo.getMembers_id()); return "common/message"; } //회원 등록 시 아이디 중복 확인 (Ajax) @RequestMapping("/members/checkIdDup.do") @ResponseBody public int checkIdDup(@RequestParam String members_id) { System.out.println("members_id = " + members_id); int cnt = membersService.checkIdDup(members_id); System.out.println("cnt = "+cnt); return cnt; } //회원 로그인 페이지 @RequestMapping(value="/members/loginMembers.do", method=RequestMethod.GET) public String loginMembersPage() { System.out.println("회원 로그인 페이지"); return "members/loginMembers"; } //회원 로그인 처리 @RequestMapping(value="/members/loginMembers.do", method=RequestMethod.POST) public String loginMembers(@RequestParam String members_id, @RequestParam String members_pw, HttpServletRequest request, Model model) { System.out.println("회원 로그인 처리"); System.out.println("members_id = " + members_id +", members_pw = " + members_pw); int result = membersService.loginMembers(members_id, members_pw); //result = 0 아이디가 존재하지 않거나 비밀번호가 일치하지 않음 //result = 1 아이디가 존재하고 비밀번호 일치 System.out.println("로그인 결과 result = " + result); //기본값 설정 String msg = "로그인 실패", url = "/members/loginMembers.do"; if(result == 1) { MembersVO vo = membersService.selectByMembersId(members_id); msg = vo.getMembers_id() + "님 로그인 성공"; url = "/index.do"; //세션에 저장 HttpSession session = request.getSession(); session.setAttribute("members_no", vo.getMembers_no()); session.setAttribute("members_id", vo.getMembers_id()); session.setAttribute("members_name", vo.getMembers_name()); } model.addAttribute("msg", msg); model.addAttribute("url", url); return "common/message"; } //회원 로그아웃 처리 @RequestMapping(value="/members/logoutMembers.do", method=RequestMethod.GET) public String logoutMembers(Model model, HttpSession session) { String members_id = (String)session.getAttribute("members_id"); String msg = members_id + "님 로그아웃 되었습니다"; String url = "/index.do"; // 세션 전체 제거, 무효화 session.invalidate(); model.addAttribute("msg", msg); model.addAttribute("url", url); return "common/messageLogout"; } //회원 로그인 페이지 @RequestMapping(value="/members/indexMembers.do", method=RequestMethod.GET) public String indexMembersPage() { System.out.println("마이페이지 첫 화면"); return "members/indexMembers"; } //회원 정보 페이지 @RequestMapping(value="/members/infoMembers.do", method=RequestMethod.GET) public String infoMembersPage(HttpSession session, Model model) { System.out.println("회원정보 페이지"); String members_id = (String)session.getAttribute("members_id"); MembersVO members = membersService.selectByMembersId(members_id); model.addAttribute("members", members); return "members/infoMembers"; } //회원 탈퇴 @RequestMapping("/members/deleteMembers.do") public String deleteMembers(HttpSession session, Model model) { int members_no = (Integer)session.getAttribute("members_no"); String members_id = (String)session.getAttribute("members_id"); System.out.println("회원 탈퇴 처리 members_no = " + members_no); System.out.println("회원 탈퇴 처리 members_id = " + members_id); String msg="회원 삭제 실패", url="/members/infoMembers.do"; int cnt = membersService.deleteMembers(members_no); if(cnt>0) { msg= members_id + "님 탈퇴 처리되었습니다"; url="/index.do"; } // 세션 전체 제거, 무효화 session.invalidate(); model.addAttribute("msg", msg); model.addAttribute("url", url); return "common/messageLogout"; } //비밀번호 변경 페이지 @RequestMapping(value="/members/updatePw.do", method=RequestMethod.GET) public String updatePwPage() { System.out.println("비밀번호 변경 페이지"); return "members/updatePw"; } //비밀번호 변경 @RequestMapping(value="/members/updatePw.do", method=RequestMethod.POST) public String updatePw(HttpSession session, HttpServletRequest request, MembersVO vo, Model model) { System.out.println("비밀번호 변경 처리"); //로그인 되어있는 아이디 String members_id = (String)session.getAttribute("members_id"); //기존 비밀번호 입력 값 String members_pw_use = request.getParameter("members_pw_use"); //새 비밀번호 입력 값 String members_pw = request.getParameter("members_pw"); System.out.println("members_id = " + members_id); System.out.println("members_pw_use = " + members_pw_use); System.out.println("members_pw = " + members_pw); //1. 기존 비밀번호가 일치하는지 확인 (아이디를 통해 비밀번호 일치 여부 확인) //아이디를 통해 비밀번호를 가져옴 String members_pw_db = membersService.checkPwById(members_id); System.out.println("members_pw_db = " + members_pw_db); String msg=""; String url=""; //일치하지 않을 경우 : 비밀번호 불일치를 알려주고 비밀번호 변경 페이지로 이동 if(!members_pw_db.equals(members_pw_use)) { msg = "비밀번호를 확인하세요"; url = "/members/updatePw.do"; //일치 할 경우 : 새 비밀번호로 변경시키고 회원정보 페이지로 이동 }else { vo.setMembers_id(members_id); vo.setMembers_pw(members_pw); int result = membersService.updatePw(vo); System.out.println("result = " + result); msg = "비밀번호 변경 실패"; url = "/members/updatePw.do"; if(result > 0) { msg = "비밀번호가 변경되었습니다"; url = "/members/infoMembers.do"; } } model.addAttribute("msg", msg); model.addAttribute("url", url); return "common/message"; } //회원정보 변경 페이지 @RequestMapping(value="/members/updateMembers.do", method=RequestMethod.GET) public String updateMembersPage(HttpSession session, Model model) { System.out.println("회원정보 변경 페이지"); String members_id = (String)session.getAttribute("members_id"); MembersVO members = membersService.selectByMembersId(members_id); model.addAttribute("members", members); return "members/updateMembers"; } @RequestMapping(value="/members/updateMembers.do", method=RequestMethod.POST) public String updateMembers(MembersVO vo, Model model) { System.out.println("회원정보 변경 처리"); int cnt = membersService.updateMembers(vo); String msg="회원정보 변경 실패", url="/members/updateMembers.do"; if(cnt > 0) { msg = "회원정보 변경 성공"; url = "/members/infoMembers.do"; } model.addAttribute("msg", msg); model.addAttribute("url", url); return "common/message"; } }<file_sep>/src/main/java/com/tjoeunit/biz/members/MembersService.java package com.tjoeunit.biz.members; import java.util.List; import com.tjoeunit.biz.payment.PaymentVO; public interface MembersService { //고객 등록 int insertMembers(MembersVO vo); //고객 아이디 중복 확인을 위한 메서드 int checkIdDup(String members_id); //고객 로그인 int loginMembers(String members_id, String members_pw); //고객 아이디로 고객 VO 조회 MembersVO selectByMembersId(String members_id); //고객 아이디로 비밀번호 조회 String checkPwById(String members_id); //고객 비밀번호 변경 int updatePw(MembersVO vo); //고객 정보 수정 int updateMembers(MembersVO vo); //고객 삭제 int deleteMembers(int members_no); //고객 번호로 아이디 가져오기 MembersVO selectByMembersNo(int members_no); //관리자 회원목록 보기 List<MembersVO> getMembersList(MembersVO vo); }
a0707acce8ad645c5fd42739391bf4bdde02ee03
[ "Java", "SQL" ]
23
Java
Sona0817/tripfullproj
7eeb8449e2304c49fd67acd17705366e2b2b99f5
e0de0216dbb0156fb967d3247a0608b7ca536946
refs/heads/master
<file_sep># Ty_redis 简易操作redis页面 <file_sep>from flask import Flask from config import * from flask import * import requests app = Flask(__name__) @app.route("/") def hello(): return "Welcome to Ty redis page!" @app.route("/index" , methods=['POST', 'GET']) def index(): res = "tingyun" if request.method == 'POST': operate_type = request.form['type'] if operate_type == "get": ret = requests.post('http://127.0.0.1:18888/snapchat/snapchat' , data = { 'Type': 'get'}) if ret.status_code == 200: res = ret.content.decode() else: res = "operator get banned_key 【sc:hash:banned:user】 failed" elif operate_type == "add": uid = request.form['uid'] res = requests.post('http://127.0.0.1:18888/snapchat/snapchat' , data = { 'Type': 'add' , 'uid' : uid}) if res.status_code == 200: res = "operator add uid 【%s】 ok"%(uid) else: res = "operator add uid 【%s】 failed"%(uid) elif operate_type == "remove": uid = request.form['uid'] res = requests.post('http://127.0.0.1:18888/snapchat/snapchat' , data = { 'Type': 'remove' , 'uid' : uid}) if res.status_code == 200: res = "operator remove uid 【%s】 ok"%(uid) else: res = "operator remove uid 【%s】 failed"%(uid) elif operate_type == "search": uid = request.form['uid'] ret = requests.post('http://127.0.0.1:18888/snapchat/snapchat' , data = { 'Type': 'search' , 'uid' : uid}) if ret.status_code == 200: res = ret.content.decode() else: res = "operator search uid 【%s】 failed"%(uid) else: res = "method not valid" return render_template('index.html', data=res) if __name__ == '__main__': app.jinja_env.auto_reload = True app.config['TEMPLATES_AUTO_RELOAD'] = True app.run(host='127.0.0.1', port=18889 ,debug=True)
0bc3a0e5bfcc50da6a44e67b1a31ddaf45b462d0
[ "Markdown", "Python" ]
2
Markdown
tingyunsay/Ty_redis
c80ff82d780148a81d00794be27279a0b9bced2c
6b322479787dfb62b4570b233690ab6e21f23ba3
refs/heads/master
<repo_name>F15HYF4C3/ReduxBasics<file_sep>/src/Components/Counter.js import React, { Component } from 'react' import {connect} from 'react-redux'; class Counter extends Component { handleUpdate(str){ this.props.dispatch({ type: str }) } render() { return ( <div> {this.props.myFirstProperty} <br/> <button onClick={()=>{this.handleUpdate('add_number')}}>+</button> <button onClick={()=>{this.handleUpdate('subtract_number')}}>-</button> </div> ) } } export default connect(state => state)(Counter);<file_sep>/src/Redux/Reducer/reducer.js import {combineReducers} from 'redux'; const myFirstProperty = (state=`Josh`, action) => { switch(action.type){ case 'update_firstProp': return action.payload.name; default: return state; } } const count = (state=0, action) => { switch(action.type){ case 'add_number' : state++; return state case 'subtract_number' : state --; return state; default: return state; } } const myOtherProperty = (state=`Other`, action) => { return state; } export default combineReducers({myFirstProperty, count, myOtherProperty})
598c1942faf3f5f9ff0ff8ecc64883d012b49a49
[ "JavaScript" ]
2
JavaScript
F15HYF4C3/ReduxBasics
c5a6e713afe0a5222493511feedbd8abb6514374
dd91c3a5a5c99282dd5f868dd8e74c6798b664b8
refs/heads/master
<repo_name>eduardonalves/rudo<file_sep>/js/controllers.js angular.module('app.controllers', []) .controller('assineCtrl', ['$scope','$location','$ionicSideMenuDelegate', '$stateParams','$ionicLoading','$ionicPopup','$ionicHistory', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$location,$ionicSideMenuDelegate, $stateParams,$ionicLoading,$ionicPopup,$ionicHistory) { var connectedRef = firebase.database().ref(".info/connected"); $scope.tentativas = 0; //$scope.conectDiv=true; connectedRef.on("value", function(snap) { $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); if (snap.val() === true) { $scope.conectDiv=true; $timeout(function () { $('body').trigger('click'); // $scope.conectDiv=true; },1500); //$window.location.reload(); } else { $scope.conectDiv=false; $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); } }); $ionicSideMenuDelegate.canDragContent(false); $scope.$on('$ionicView.beforeEnter', function (event, viewData) { userLoggedOn = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(userLoggedOn) { if(!userLoggedOn){ $location.path('/login') } }); viewData.enableBack = true; $scope.countLine=0; //firebase.auth().onAuthStateChanged(function(user) { user = firebase.auth().currentUser; if (user){ $scope.countLine++; $scope.user = firebase.auth().currentUser; firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { $scope.datauser = snapshot.val(); //console.log(snapshot.val()); }); }else{ //$location.path('/page5') } //}); }); $scope.ionicGoBack = function() { $ionicHistory.goBack(); }; $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', duration: 1000 }).then(function(){ //console.log("The loading indicator is now displayed"); }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); }; user = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(user) { $scope.user = firebase.auth().currentUser; }); $scope.showAlert = function(texto) { var alertPopup = $ionicPopup.alert({ title: texto.titulo, template: texto.mensagem }); alertPopup.then(function(res) { }); }; $scope.assinar = function() { $scope.showLoading(); $.getJSON( "http://hudo.000webhostapp.com/entregapp/RestPedidos/pagseguromobile?ref="+$scope.user.uid+"", function( data ){ $scope.hideLoading(); if(data[0] !='Existe' && data[0] !='E' ) { // //console.log(data[0]); window.open('https://sandbox.pagseguro.uol.com.br/v2/pre-approvals/request.html?code='+data[0],'_system'); $scope.hideLoading(); }else{ // //console.log(data[0]); $scope.texto ={}; $scope.texto.titulo ='Falha'; $scope.texto.mensagem ='Esta conta já possui uma assinatura Premium.'; $scope.showAlert($scope.texto); } }); /**/ } }]) .controller('acompanharFilasCtrl', ['$scope','$timeout', '$ionicSideMenuDelegate','$stateParams','$location','$ionicLoading','$ionicPopup',// The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$timeout,$ionicSideMenuDelegate, $stateParams,$location,$ionicLoading,$ionicPopup) { var connectedRef = firebase.database().ref(".info/connected"); $scope.tentativas = 0; //$scope.conectDiv=true; connectedRef.on("value", function(snap) { $scope.conectDiv=true; $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); if (snap.val() === true) { $scope.conectDiv=true; $timeout(function () { $('body').trigger('click'); // $scope.conectDiv=true; },1500); //$window.location.reload(); } else { $scope.conectDiv=false; $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); } }); $ionicSideMenuDelegate.canDragContent(false); userLoggedOn = firebase.auth().currentUser; $scope.userLoggedOn = userLoggedOn; firebase.auth().onAuthStateChanged(function(userLoggedOn) { if(!userLoggedOn){ $location.path('/login') } }); $scope.$on('$ionicView.leave', function(){ //$ionicSideMenuDelegate.canDragContent(true); //$('.ion-navicon').show(); $scope.showContent=false; }); $scope.$on('$ionicView.beforeEnter', function (event, viewData) { userLoggedOn = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(userLoggedOn) { if(!userLoggedOn){ $location.path('/login') } }); //viewData.enableBack = true; $scope.showLoading(); firebase.auth().onAuthStateChanged(function(user) { user = firebase.auth().currentUser; $scope.user = firebase.auth().currentUser; firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { $scope.datauser = snapshot.val(); //$scope.hideLoading(); if(snapshot.val() != null){ if(typeof $scope.datauser.categoria != 'undefined'){ firebase.database().ref().child('categorias').child($scope.datauser.categoria).once("value", function(snapshot2) { $scope.datauser.categoriaNome = snapshot2.val(); //console.log($scope.datauser.categoriaNome); },function(error) { $timeout(function(){ $scope.hideLoading(); },2000); }); } } $timeout(function(){ $scope.showContent=true; $scope.hideLoading(); },2000); //console.log(snapshot.val()); },function(error) { $timeout(function(){ $scope.showContent=true; $scope.hideLoading(); },2000); }); }); }); $scope.logout = function (){ firebase.auth().signOut().then(function() { // Sign-out successful. $scope.user = null; //$location.path('/login'); navigator.app.exitApp(); }, function(error) { // An error happened. }); } user = firebase.auth().currentUser; $scope.user = user; firebase.auth().onAuthStateChanged(function(user) { $scope.user = firebase.auth().currentUser; }); $scope.uploadProgres =0; $scope.showProgress=false; $scope.showProgress=false; $scope.getImage = function (source) { //alert('passou1'); // Retrieve image file location from specified source $('#configForm').submit(function(event) { event.preventDefault(); }); $scope.showImage=false; var options = { maximumImagesCount: 1, quality: 50 }; $scope.showLoading(); window.imagePicker.getPictures( function(results) { //alert('passou2'); for (var i = 0; i < results.length; i++) { //getFileEntry(results[i]); var imageData = results[i]; var filename = imageData.split("/").pop(); var storageRef = firebase.storage().ref(); var getFileBlob = function(url, cb) { var xhr = new XMLHttpRequest(); xhr.open("GET", url); xhr.responseType = "blob"; xhr.addEventListener('load', function() { cb(xhr.response); }); xhr.send(); }; var blobToFile = function(blob, name) { blob.lastModifiedDate = new Date(); blob.name = name; return blob; }; var getFileObject = function(filePathOrUrl, cb) { getFileBlob(filePathOrUrl, function(blob) { cb(blobToFile(blob, 'test.jpg')); }); }; getFileObject(imageData, function(fileObject) { var uploadTask = storageRef.child('images/'+user.uid+'.jpg').put(fileObject); uploadTask.on('state_changed', function(snapshot) { //alert(snapshot); }, function(error) { //alert(error); }, function() { var downloadURL = uploadTask.snapshot.downloadURL; $scope.datauser.foto = downloadURL; firebase.database().ref('users/' + user.uid).set($scope.datauser, function(error) { $scope.texto ={}; $scope.hideLoading(); if(error){ $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='Não conseguimos salvar a configuração.'; $scope.showAlert($scope.texto); }else{ $scope.texto.titulo ='Tudo Certo!'; $scope.texto.mensagem ='Sua configuração foi salva!'; $scope.showAlert($scope.texto); } }); //alert(downloadURL); // handle image here }); }); $timeout(function(){ $scope.hideLoading(); },2000); } }, function (error) { $scope.showImage=false; $timeout(function(){ $scope.hideLoading(); },2000); alert('Error: ' + error); }, options ); $timeout(function(){ $scope.hideLoading(); },2000); } $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', duration: 10000, }).then(function(){ //console.log("The loading indicator is now displayed"); }); }; // Triggered on a button click, or some other target $scope.showPopup = function() { // An elaborate, custom popup var myPopup = $ionicPopup.show({ title: 'Cancelar Conta', subTitle: 'Deseja Canelar a conta Premium?', scope: $scope, buttons: [ { text: '<b>Sim</b>', type: 'button-assertive', onTap: function(e) { $scope.confirmarcancelamento(); } }, { text: 'Não' } ] }); } $scope.showAlert = function(texto) { var alertPopup = $ionicPopup.alert({ title: texto.titulo, template: texto.mensagem }); alertPopup.then(function(res) { }); }; $scope.confirmarcancelamento = function() { $scope.showLoading(); $.getJSON( "http://hudo.000webhostapp.com/entregapp/RestPedidos/cancelarpagseguro?ref="+$scope.user.uid+"", function( data ){ $scope.hideLoading(); if(data[0] !='Not Found' && data[0] !='N' ) { //console.log(data[0]); }else{ // //console.log(data[0]); $scope.texto ={}; $scope.texto.titulo ='Falha'; $scope.texto.mensagem ='Não foi possível cancelar a assinatura, por favor entre em contato com <EMAIL>'; $scope.showAlert($scope.texto); } }); } $scope.setRaio = function(usercad) { $scope.showLoading(); $scope.datauser.raio = usercad.raio || null; $scope.datauser.nome = usercad.nome || null; //user = firebase.auth().currentUser; //firebase.auth().onAuthStateChanged(function(user) { //$scope.user = firebase.auth().currentUser; firebase.database().ref('users/' + user.uid).set($scope.datauser, function(error) { $scope.texto ={}; $scope.hideLoading(); if(error){ $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='Não conseguimos salvar a configuração.'; $scope.showAlert($scope.texto); }else{ $scope.texto.titulo ='Tudo Certo!'; $scope.texto.mensagem ='Sua configuração foi salva!'; $scope.showAlert($scope.texto); } }); //}); } $scope.cancelar = function() { $scope.showPopup(); /**/ } $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); }; //$scope.showLoading(); //$scope.hideLoading(); }]) .controller('guichesCtrl', ['$scope','$timeout','$ionicSideMenuDelegate', '$stateParams','$location','$ionicLoading','$ionicHistory','$ionicPopup',// The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$timeout, $ionicSideMenuDelegate,$stateParams,$location,$ionicLoading,$ionicHistory,$ionicPopup) { var connectedRef = firebase.database().ref(".info/connected"); $scope.tentativas = 0; //$scope.conectDiv=true; connectedRef.on("value", function(snap) { $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); if (snap.val() === true) { $scope.conectDiv=true; $timeout(function () { $('body').trigger('click'); // $scope.conectDiv=true; },1500); //$window.location.reload(); } else { $scope.conectDiv=false; $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); } }); $ionicSideMenuDelegate.canDragContent(false); userLoggedOn = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(userLoggedOn) { if(!userLoggedOn){ $location.path('/login') } }); $scope.remover = function(key) { $scope.showLoading(); user = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(user) { firebase.database().ref().child('guiches').child(user.uid).child(key).remove(); //console.log(key); $scope.hideLoading(); }); } $scope.cadastrar = function(guiche) { //console.log(guiche); $scope.showLoading(); if(guiche != '' && typeof guiche != 'undefined') { user = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(user) { firebase.database().ref().child('guiches').child(user.uid).orderByChild("guiche").startAt(guiche).endAt(guiche).limitToFirst(1).once("value", function(snapshot) { if(snapshot.val() != null){ $scope.hideLoading(); $scope.texto ={}; $scope.texto.titulo ='Aviso'; $scope.texto.mensagem ='Este guichê já existe.'; $scope.showAlert($scope.texto); }else{ firebase.database().ref('guiches/' + user.uid ).push({ guiche: guiche, }, function(error) { if(!error) { $scope.texto ={}; $scope.texto.titulo ='Tudo Certo'; $scope.texto.mensagem ='A operação foi efetuada.'; $scope.hideLoading(); $scope.showAlert($scope.texto); $('[name="guiche"]').val(''); } }); } }); }); }else{ $scope.hideLoading(); $scope.texto ={}; $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='O guichê não pode estar vazio.'; $scope.showAlert($scope.texto); } } $scope.showAlert = function(texto) { var alertPopup = $ionicPopup.alert({ title: texto.titulo, template: texto.mensagem }); alertPopup.then(function(res) { }); }; $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', duration: 1000 }).then(function(){ //console.log("The loading indicator is now displayed"); }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); }; $scope.ionicGoBack = function() { $ionicHistory.goBack(); }; $scope.$on('$ionicView.beforeEnter', function (event, viewData) { viewData.enableBack = true; $scope.items =[]; user = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(user) { firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { $scope.datauser = snapshot.val(); //console.log(snapshot.val()); }); firebase.database().ref().child('guiches').child(user.uid).on("value", function(snapshot) { if(snapshot.val() != null){ $scope.items = snapshot.val(); // //console.log($scope.items); }else{ $scope.totalItens =$scope.items.length; } $scope.hideLoading(); }); }) }); $scope.showLoading(); //$scope.hideLoading(); }]) .controller('gerarSenhasClienteCtrl', ['$scope','$timeout','$ionicSideMenuDelegate', '$ionicPopup', '$stateParams', '$ionicHistory', '$location','$ionicLoading', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$timeout, $ionicSideMenuDelegate,$ionicPopup, $stateParams,$ionicHistory, $location, $ionicLoading) { var connectedRef = firebase.database().ref(".info/connected"); $scope.tentativas = 0; //$scope.conectDiv=true; connectedRef.on("value", function(snap) { $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); if (snap.val() === true) { $scope.conectDiv=true; $timeout(function () { $('body').trigger('click'); // $scope.conectDiv=true; },1500); //$window.location.reload(); } else { $scope.conectDiv=false; //console.log('off'); $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); } }); $ionicSideMenuDelegate.canDragContent(false); userLoggedOn = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(userLoggedOn) { if(!userLoggedOn){ $location.path('/login') } }); $scope.retornaNome = function(num) { switch (num) { case 1: return 'Comum'; break; case 2: return 'Prioritária'; break; case 3: return 'Manual'; break; default: } } $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...' }).then(function(){ //console.log("The loading indicator is now displayed"); }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); }; $scope.ionicGoBack = function() { $ionicHistory.goBack(); }; $scope.contadorSenhaCanc= 0; $scope.contaSenhasCanceladas = function() { setDateTime(); user = firebase.auth().currentUser; $scope.countLine=0; //firebase.auth().onAuthStateChanged(function(user) { if (user){ $scope.countLine++; var hoje =getDateSmall(userDateTimeFull); $scope.contadorSenhaCanc=0; firebase.database().ref().child('senhas_canceladas_usuarios').child(user.uid).orderByChild('data').equalTo(hoje).once("value", function(snapshot3){ //console.log(snapshot3.val()); if(snapshot3.val() != null){ $.each(snapshot3.val(), function(key3,val3) { $scope.contadorSenhaCanc ++; }); //console.log($scope.contadorSenhaCanc); return $scope.contadorSenhaCanc; } }); } //}); } $scope.cancelarsenha = function() { setDateTime(); $scope.showLoading(); $scope.texto ={} user = firebase.auth().currentUser; $scope.countLine=0; // firebase.auth().onAuthStateChanged(function(user) { if (user){ $scope.countLine++; var contCandeladas = $scope.contaSenhasCanceladas(); firebase.database().ref().child('geo_filas_senhas').child($stateParams.id).orderByChild('user_id').equalTo(user.uid).once("value", function(snapshot){ if(snapshot.val() != null){ $.each(snapshot.val(), function(key,val) { //console.log(val); firebase.database().ref().child('senhas_usuarios').child(user.uid).orderByChild('numero').equalTo(val.numero).once("value", function(snapshot2){ //console.log(snapshot2.val()); if(snapshot2.val() != null) { $.each(snapshot2.val(), function(key2,val2) { var hoje =getDateSmall(userDateTimeFull); firebase.database().ref('senhas_canceladas_usuarios/' + user.uid).push({ loja_id:$stateParams.id,data:hoje }, function(error) { }); if($scope.contadorSenhaCanc < 3) { firebase.database().ref().child('senhas_usuarios').child(user.uid).child(key2).remove(); firebase.database().ref().child('geo_filas_senhas').child($stateParams.id).child(key).remove(); $scope.texto.titulo ='Boa!'; $scope.texto.mensagem ='Sua senha foi cancelada.'; $scope.hideLoading(); $scope.showAlert($scope.texto); }else{ $scope.texto.titulo ='Ops, algo deu errado!'; $scope.texto.mensagem ='Você já não pode mais cancelar senhas por hoje.'; $scope.hideLoading(); $scope.showAlert($scope.texto); } }); } $scope.hideLoading(); }); }); $scope.hideLoading(); }else{ $scope.texto.titulo ='Opa!'; $scope.texto.mensagem ='Você não tem senhas nesta fila.'; $scope.showAlert($scope.texto); } $scope.hideLoading(); }); }else{ $scope.hideLoading(); } //}); }; var user = firebase.auth().currentUser; $scope.numFilasInativas=0; $scope.$on('$ionicView.beforeEnter', function (event, viewData) { viewData.enableBack = true; $scope.numFilasInativas=0; $scope.lojaFila= []; $scope.showLoading(); firebase.database().ref().child('geo_filas').child($stateParams.id).once("value", function(snapshot) { $scope.items = []; if(snapshot.val() != null ){ $scope.items.push(snapshot.val()); $scope.numFilasInativas = 0; $.each(snapshot.val(), function (key, val) { //console.log(val); if(val.manual == false && val.ativa == false) { $scope.numFilasInativas++; } }); //console.log($scope.numFilasInativas); }else{ $scope.totalItens =$scope.items.length; } $scope.hideLoading(); firebase.database().ref().child('users').child($stateParams.id).once("value", function(snapshot2) { if(snapshot2.val() != null ){ //console.log(snapshot2.val()); $scope.lojaFila = snapshot2.val(); $scope.limite = snapshot2.val().limit; } }); }); }); $scope.showAlert = function(texto) { var alertPopup = $ionicPopup.alert({ title: texto.titulo, template: texto.mensagem }); alertPopup.then(function(res) { }); }; $scope.contador=''; $scope.contaNumero = function(id){ setDateTime(); user = firebase.auth().currentUser; $scope.contadorAuxSenha = 0; $scope.countLine=0; //firebase.auth().onAuthStateChanged(function(user) { if (user){ $scope.countLine++; if($scope.contadorAuxSenha==0) { firebase.database().ref().child('geo_filas').child($stateParams.id).child(id).once("value", function(snapshot) { fila =snapshot.val(); $scope.contador = parseInt(fila.numero_contador) + 1; // //console.log($scope.contador); user = firebase.auth().currentUser; var mykey = firebase.database().ref('geo_filas_senhas/' + $stateParams.id).push(); var prefixo = fila.prefixo || ''; var contador = $scope.contador || 1; var posFixoRestaurante = ''; if(typeof $scope.lojaFila.categoria != 'undefined'){ if($scope.lojaFila.categoria== 1){ posFixoRestaurante =''; posFixoRestaurante= $('#qtdPessoas').val(); if(typeof posFixoRestaurante != 'undefined' && posFixoRestaurante != '? undefined:undefined ?'){ posFixoRestaurante = ' P-'+ posFixoRestaurante; }else { posFixoRestaurante = ' P-'+ 1; } } } var nome = fila.nome || 'S/N'; var user_id = $('#user_id').val() || null; firebase.database().ref('geo_filas_senhas/' + $stateParams.id).push({ pos:contador, numero:prefixo + $scope.contador + posFixoRestaurante, ativo:'true', tipo:nome,data:getDate(userDateTimeFull),user_id:user.uid, }, function(error) { $scope.texto={}; if(error){ $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='Operaçao não efetuada.'; $scope.hideLoading(); $scope.showAlert($scope.texto); }else { $scope.texto.titulo ='Tudo Certo'; $scope.texto.mensagem ='Sua senha '+ prefixo + contador + posFixoRestaurante; firebase.database().ref('geo_filas').child($stateParams.id).child(id).child('/numero_contador').set( $scope.contador); if(user.uid != '') { firebase.database().ref('senhas_usuarios/' + user.uid).push({ pos:contador, numero:prefixo + $scope.contador + posFixoRestaurante, ativo:'true', tipo:nome,data:getDate(userDateTimeFull),loja_id:$stateParams.id, }, function(error) { }); } // $('#qtdPessoas').val(''); $scope.hideLoading(); $scope.showAlert($scope.texto); } }); }); } } //}); } $scope.contaSenha = function() { setDateTime(); var dateObj = new Date(); var month = dateObj.getUTCMonth() + 1; //months from 1-12 var day = dateObj.getUTCDate(); var year = dateObj.getUTCFullYear(); var ref = firebase.database().ref("senhas_gratis/"+$stateParams.id+'/'+ year +'/'+ month); ref.once("value").then(function(snapshot) { var a = snapshot.numChildren(); // 1 ("name") $scope.contadorSenha = snapshot.child(day).numChildren(); // 2 ("first", "last") }); } $scope.contadorSenha = $scope.contaSenha(); $scope.setlogsenha = function() { setDateTime(); var dateObj = new Date(); var month = dateObj.getUTCMonth() + 1; //months from 1-12 var day = dateObj.getUTCDate(); var year = dateObj.getUTCFullYear(); user = firebase.auth().currentUser; firebase.database().ref('senhas_gratis/' + user.uid +'/' + year +'/'+ month+'/'+ day ).push({qtd:1}); } //$scope.setlogsenha(); $scope.gerarSenha = function(value, id) { $scope.showLoading(); user = firebase.auth().currentUser; $scope.countLine=0; //firebase.auth().onAuthStateChanged(function(user) { if (user){ $scope.countLine++; firebase.database().ref().child('geo_filas_senhas').child($stateParams.id).orderByChild('user_id').equalTo(user.uid).once("value", function(snapshot){ $scope.texto= {}; if(snapshot.val() == null) { user = firebase.auth().currentUser; $scope.contaSenha(); if( $scope.contadorSenha >= $scope.limite) { $scope.texto.titulo ='Ops! Que embaraçoso.'; $scope.texto.mensagem ='Acabaram as senhas disponíveis deste estabelecimento por hoje. Tente pegar uma senha outro dia.'; $scope.hideLoading(); $scope.showAlert($scope.texto); }else{ userNotf = user.displayName; userNotf = userNotf || user.email; userNotf = userNotf || null; if(userNotf != '' && userNotf !=null){ sendNotificationTouUserNewNumberEstab($stateParams.id,userNotf); } $scope.setlogsenha(); $scope.contaNumero(id); } }else{ $scope.texto.titulo ='Ops! Que embaraçoso.'; $scope.texto.mensagem ='Você já tem uma senha ativa neste estabelecimento, e não pode pegar outra senha neste momento. Cancele sua senha ou aguarde a sua senha ser chamada.'; $scope.hideLoading(); $scope.showAlert($scope.texto); } }); } //}); } $scope.pos={}; $scope.pos.lat=0; $scope.pos.lon=0; $scope.post={}; $scope.imageUrl=''; var onSuccessPos = function(position) { $scope.pos.lat = position.coords.latitude; $scope.pos.lon= position.coords.longitude; //console.log($scope.pos.lon); }; // onError Callback receives a PositionError object function onErrorPos(error) { $scope.posErro=error; calldialog(); } navigator.geolocation.getCurrentPosition(onSuccessPos, onErrorPos, {maximumAge:60000, timeout:5000, enableHighAccuracy:true}); //$scope.fila.user_id =''; $scope.fila = []; if (user) { // User is signed in. //alert('1'); //console.log(user); $scope.fila.user_id = user.uid; } else { $location.path('/page5') } var firebaseRef = firebase.database().ref().child('geo_filas'); var geoFire = new GeoFire(firebaseRef); var ref = geoFire.ref(); // ref === firebaseRef //var mykey = ref.child('dados').push(); //console.log(user.uid); var user = firebase.auth().currentUser //$scope.showConfirm(); // An alert dialog $scope.cadastrarFila = function(fila) { var user = firebase.auth().currentUser var nome = fila.nome || null; var ativa = fila.ativa || false; var prioridade = fila.prioridade || false; var prioridade_qtd = fila.qtd_prioridade || 0; var manual = fila.manual || false; var numero_contador = fila.numero_contador || 0; var prefixo = fila.prefixo || ''; $scope.texto= {}; //console.log(nome); if(nome == null || nome == 'undefined' ) { $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='O nome não poder estar vazio.'; $scope.showAlert($scope.texto); }else{ firebase.database().ref('geo_filas/' + user.uid + '/' + $stateParams.id).set({ nome: nome, ativa:ativa, prioridade:prioridade, prioridade_qtd:prioridade_qtd, manual:manual, numero_contador:numero_contador, prefixo:prefixo, }, function(error) { if(error){ $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='Não conseguimos realizar a operação.'; $scope.showAlert($scope.texto); }else { $scope.texto.titulo ='Tudo certo!'; $scope.texto.mensagem ='A operação foi efetuada.'; $scope.showAlert($scope.texto); } }); } } }]) .controller('painelLojaCtrl', ['$scope','$timeout', '$ionicSideMenuDelegate','$stateParams','$location','$ionicLoading','$timeout', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$timeout, $ionicSideMenuDelegate,$stateParams,$location,$ionicLoading,$timeout) { var connectedRef = firebase.database().ref(".info/connected"); $scope.tentativas = 0; //$scope.conectDiv=true; connectedRef.on("value", function(snap) { $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); if (snap.val() === true) { $scope.conectDiv=true; $timeout(function () { $('body').trigger('click'); // $scope.conectDiv=true; },1500); //$window.location.reload(); } else { $scope.conectDiv=false; $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); } }); $ionicSideMenuDelegate.canDragContent(false); userLoggedOn = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(userLoggedOn) { if(!userLoggedOn){ $location.path('/login') } }); $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', }).then(function(){ //console.log("The loading indicator is now displayed"); }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); }; $scope.verFila = function(id) { $location.path('/painelloja/'+id); } $scope.ionicGoBack = function() { $ionicHistory.goBack(); }; $scope.$on('$ionicView.beforeEnter', function (event, viewData) { viewData.enableBack = true; $scope.showLoading(); $scope.countLine=0; //firebase.auth().onAuthStateChanged(function(user) { user = firebase.auth().currentUser; if (user){ $scope.countLine++; $timeout(function() { firebase.database().ref().child('users').child($stateParams.id).once("value", function(snapshot) { $scope.datauser = snapshot.val(); //console.log($scope.datauser); if($scope.datauser.role == 2) { firebase.database().ref().child('geo_filas_senhas_usadas').child($stateParams.id).limitToLast(1).on("child_added", function(snapshot) { if(snapshot.val() != null ){ $scope.senha=snapshot.val(); $scope.hideLoading(); } }); $scope.senhasAnterioresAux=[] var ref = firebase.database().ref().child('geo_filas_senhas_usadas').child($stateParams.id); $scope.senhasAnteriores=[]; ref.orderByKey().limitToLast(10).on("child_added", function(snapshot) { if(snapshot.val() != null ){ //if($scope.senhasAnteriores.length < 5){ $scope.senhasAnteriores.unshift(snapshot.val()); // }else{ //$scope.senhasAnterioresAux.unshift(snapshot.val()); //} //countRef++; } }); } $scope.minhasenha=''; firebase.database().ref().child('geo_filas_senhas').child($stateParams.id).orderByChild('user_id').equalTo(user.uid).once("value", function(snapshot){ if(snapshot.val() != null) { $.each(snapshot.val(), function (key, val) { $scope.minhasenha = val; }); //$scope.minhasenha=snapshot.val(); //console.log($scope.minhasenha); } }); }); $timeout(function () { $('#filtro').val(' '); $scope.hideLoading(); }, 3000); },2500); } else { $scope.hideLoading(); $location.path('/page5') } //}); }); $scope.moredata = false; $scope.loadMoreData=function() { if(typeof $scope.senhasAnterioresAux[0] != "undefined") { $scope.senhasAnteriores.push($scope.senhasAnterioresAux[0]); $scope.senhasAnterioresAux.shift(); $scope.$broadcast('scroll.infiniteScrollComplete'); }else{ $timeout(function() { $scope.$broadcast('scroll.infiniteScrollComplete'); $scope.moredata=true; },3000); } }; $scope.mostrar = function() { $('.nav-bar-container').fadeIn(1000); $('.tabs').fadeIn(1000); } $scope.esconder = function() { $('.nav-bar-container').fadeOut(1000); $('.tabs').fadeOut(1000); } //alert(); }]) .controller('gerarsenhascategoriasCtrl', ['$scope','$window','$ionicSideMenuDelegate','$timeout' ,'$stateParams','$location','$ionicLoading','$ionicHistory',// The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$window,$ionicSideMenuDelegate ,$timeout,$stateParams,$location,$ionicLoading,$ionicHistory) { var connectedRef = firebase.database().ref(".info/connected"); $scope.tentativas = 0; //$scope.conectDiv=true; connectedRef.on("value", function(snap) { $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); if (snap.val() === true) { $scope.conectDiv=true; $timeout(function () { $('body').trigger('click'); // $scope.conectDiv=true; },1500); //$window.location.reload(); } else { $scope.conectDiv=false; $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); } }); $ionicSideMenuDelegate.canDragContent(false); $scope.$on('$ionicView.beforeEnter', function (event, viewData) { //calldialog(); $scope.showLoading(); //alert('passou1'); navigator.geolocation.getCurrentPosition(onSuccessPos, onErrorPos, {maximumAge:60000, timeout:5000, enableHighAccuracy:true}); //navigator.geolocation.getCurrentPosition(onSuccessPos, onErrorPos); viewData.enableBack = true; // }); $scope.ionicGoBack = function() { $ionicHistory.goBack(); }; $scope.$on('$ionicView.leave', function(){ $scope.pos={}; $scope.pos.lat=0; $scope.pos.lon=0; $scope.noStores=false; }); var geoQuery; $scope.pos={}; $scope.pos.lat=0; $scope.pos.lon=0; $scope.noStores=false; if($stateParams.id == 't') { var firebaseRef = firebase.database().ref().child('geo_lojas'); }else{ var firebaseRef = firebase.database().ref().child('geo_lojas_cat').child($stateParams.id); } var geoFire = new GeoFire(firebaseRef); var ref = geoFire.ref(); firebase.auth().onAuthStateChanged(function(user) { if (user) { $scope.user = user; } }); function onSuccessPos(position) { $scope.pos.lat = position.coords.latitude; $scope.pos.lon= position.coords.longitude; //alert('passou2'); //-22.5108 //-43.1844 //console.log(); user = firebase.auth().currentUser; //console.log(user); //console.log($scope.lojaId); $scope.countLine=0; //firebase.auth().onAuthStateChanged(function(user) { if (user){ $scope.countLine++; $scope.user = user; $scope.lojas=[]; firebase.database().ref().child('users').child(user.uid).once("value", function(snapshotuser) { $scope.datauser = snapshotuser.val(); var raio = snapshotuser.val().raio || 50; raio = parseInt(raio); geoQuery = geoFire.query({ center: [$scope.pos.lat, $scope.pos.lon], radius: raio }); $scope.hasStore = false; var onKeyEnteredRegistration = geoQuery.on("key_entered", function(key, location) { //console.log(location); $scope.hasStore = true; $scope.noStores=false; $scope.temloja='tem'; $scope.showLoading(); if($stateParams.id == 't') { firebase.database().ref().child('users').child(key).once("value", function(snapshot) { $scope.segue='N'; //console.log(snapshot.val()); $timeout(function() { $('#filtro').val(''); $('#filtro').trigger('change'); //$('#filtro').focus(); $scope.hideLoading(); },3500); firebase.database().ref().child('lojas_seguidores').child(key).orderByValue().equalTo($scope.user.uid).once("value", function(snapshot2) { if(snapshot2.val() != null){ //console.log(snapshot2.val()); $scope.segue='S'; //$scope.hasStore =true; //$scope.noStores=false; }else{ //$scope.hasStore = false; //$scope.noStores=true; } //console.log(snapshot.val()); //console.log('aqui'); dadosLojas = { 'email':snapshot.val().email, //'endereco':snapshot.val().endereco, 'foto':snapshot.val().foto, 'nome':snapshot.val().nome, 'categoriaNome':returnCategoria(snapshot.val().categoria), 'categoria':snapshot.val().categoria, 'rudovip':snapshot.val().rudovip, 'desconto':snapshot.val().desconto, 'porcentagem':snapshot.val().porcentagem, 'condicoes':snapshot.val().condicoes, 'endereco':snapshot.val().endereco, 'bairro':snapshot.val().bairro, 'cidade':snapshot.val().cidade, 'uf':snapshot.val().uf, 'telefone1':snapshot.val().telefone1, 'telefone2':snapshot.val().telefone2, 'id':key, 'segue':$scope.segue, raio:50, } if($scope.lojas.length < 5) { $scope.lojas.unshift(dadosLojas); }else { $scope.lojas.unshift(dadosLojas); } $scope.hideLoading(); //console.log(snapshot.key); }); $scope.hideLoading(); //$scope.lojas.push(dadosLojas); //console.log($scope.lojas); }); }else { firebase.database().ref().child('geo_lojas_cat').child($stateParams.id).child(key).child('dados').once("value", function(snapshot) { $scope.segue='N'; $timeout(function() { $('#filtro').val(''); $('#filtro').trigger('change'); $scope.hideLoading(); //$('#filtro').focus(); },3000); firebase.database().ref().child('lojas_seguidores').child(key).orderByValue().equalTo($scope.user.uid).once("value", function(snapshot2) { if(snapshot2.val() != null){ //console.log(snapshot2.val()); $scope.segue='S'; }else{ $scope.noStores=true; } firebase.database().ref().child('users').child(key).once("value", function(snapshot3) { if(snapshot3.val() != null){ //console.log(snapshot3.val()); //console.log(returnCategoria($stateParams.id)); //console.log($stateParams.id); dadosLojas = { 'email':snapshot.val().email, 'endereco':snapshot.val().endereco, 'foto':snapshot3.val().foto, 'nome':snapshot.val().nome, 'categoriaNome':returnCategoria($stateParams.id), 'telefone':snapshot.val().telefone, 'id':key, 'segue':$scope.segue, raio:50, } $scope.lojas.unshift(dadosLojas); $scope.hideLoading(); } }); //console.log(snapshot.key); }); $scope.hideLoading(); //$scope.lojas.push(dadosLojas); //console.log($scope.lojas); }); } }); }); $scope.hideLoading(); // //console.log(onKeyEnteredRegistration); }else{ $scope.hideLoading(); } //}); }; // onError Callback receives a PositionError object function onErrorPos(error) { $scope.hideLoading(); calldialog(); $scope.posErro=error; //alert(error); } //$scope.moredata = false; /*$scope.loadMoreData=function() { if(typeof $scope.lojas[0] != "undefined") { $scope.lojas.push($scope.lojas[0]); $scope.lojas.shift(); $scope.$broadcast('scroll.infiniteScrollComplete'); }else{ $timeout(function() { $scope.$broadcast('scroll.infiniteScrollComplete'); $scope.moredata=true; },3000); } };*/ $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', }).then(function(){ //console.log("The loading indicator is now displayed"); }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); }; $scope.verFila=function(id) { } $scope.seguirEstabelecimento=function(id) { $scope.showLoading(); $scope.lojaId = id; user = firebase.auth().currentUser; //console.log($scope.lojaId); $scope.countLine=0; //firebase.auth().onAuthStateChanged(function(user) { if (user){ $scope.countLine++; //console.log(); firebase.database().ref().child('lojas_seguidores').child($scope.lojaId).orderByValue().equalTo(user.uid).once("value", function(snapshot) { if(snapshot.val() != null){ $.each(snapshot.val(), function (key, val) { firebase.database().ref('lojas_seguidores/'+$scope.lojaId+'/'+key).remove(); firebase.database().ref('usuarios_favoritos').child(user.uid).child($scope.lojaId).remove(); $('#seguir'+id).removeClass('segueS'); $('#seguir'+id).removeClass('segueN'); $('#seguir'+id).addClass('segueN'); }); $scope.hideLoading(); }else{ $('#seguir'+id).removeClass('segueN'); $('#seguir'+id).removeClass('segueS'); $('#seguir'+id).addClass('segueS'); firebase.database().ref().child('lojas_seguidores').child($scope.lojaId).push(user.uid); firebase.database().ref().child('usuarios_favoritos').child(user.uid).child($scope.lojaId).push($scope.lojaId); } $scope.hideLoading(); //console.log(snapshot.key); }); } //$scope.hideLoading(); //}); } }]) .controller('configurarSenhasCtrl', ['$scope','$timeout','$ionicSideMenuDelegate', '$stateParams','$location','$ionicLoading','$ionicHistory',// The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$timeout,$ionicSideMenuDelegate, $stateParams,$location,$ionicLoading,$ionicHistory) { var connectedRef = firebase.database().ref(".info/connected"); $scope.tentativas = 0; //$scope.conectDiv=true; connectedRef.on("value", function(snap) { $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); if (snap.val() === true) { $scope.conectDiv=true; $timeout(function () { $('body').trigger('click'); // $scope.conectDiv=true; },1500); //$window.location.reload(); } else { $scope.conectDiv=false; $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); } }); userLoggedOn = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(userLoggedOn) { if(!userLoggedOn){ $location.path('/login') } }); $ionicSideMenuDelegate.canDragContent(false); var user=""; $scope.ionicGoBack = function() { $ionicHistory.goBack(); }; $scope.retornaNome = function(num) { switch (num) { case 1: return 'Comum'; break; case 2: return 'Prioritária'; break; case 3: return 'Manual'; break; default: } } $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', duration: 3000 }).then(function(){ //console.log("The loading indicator is now displayed"); }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); }; $scope.$on('$ionicView.beforeEnter', function (event, viewData) { viewData.enableBack = true; $scope.showLoading(); user = firebase.auth().currentUser; $scope.countLine=0; //firebase.auth().onAuthStateChanged(function(user) { if (user){ $scope.countLine++; firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { $scope.datauser = snapshot.val(); //console.log(snapshot.val()); }); // User is signed in. //console.log(user); $scope.items =[]; firebase.database().ref().child('geo_filas').child(user.uid).on("value", function(snapshot) { if(snapshot.val() != null){ //console.log(snapshot.val()); $scope.items.push(snapshot.val()); //console.log($scope.items); }else{ $scope.totalItens =$scope.items.length; } $scope.hideLoading(); // //console.log($scope.items); }); } else { // No user is signed in. $location.path('/page5'); } //}); }); $scope.hideLoading(); $scope.irEditarFila = function(texto) { $location.path('/cadastrarfilas/'+texto); } $scope.showTrueFalse = function(texto) { // //console.log(texto); if(texto== true){ return 'Ativa'; }else{ return 'Inativa'; } } }]) .controller('gerarSenhasCtrl', ['$scope', '$ionicSideMenuDelegate','$stateParams','$ionicPopup','$location','$ionicLoading','$timeout', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope, $ionicSideMenuDelegate,$stateParams,$ionicPopup,$location,$ionicLoading,$timeout) { var connectedRef = firebase.database().ref(".info/connected"); $scope.tentativas = 0; //$scope.conectDiv=true; connectedRef.on("value", function(snap) { $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); if (snap.val() === true) { $scope.conectDiv=true; $timeout(function () { $('body').trigger('click'); $('#filtro').val(''); $('#filtro').trigger('change'); $('#filtro2').val(''); $('#filtro2').trigger('change'); // $scope.conectDiv=true; },1500); //$window.location.reload(); } else { $scope.conectDiv=false; $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); } }); $scope.limite =1; $scope.tituloPagina=''; $ionicSideMenuDelegate.canDragContent(false); $scope.$on('$ionicView.beforeEnter', function (event, viewData) { //$scope.conectDiv=true; $scope.showLoading(); //console.log('entrou3'); user = firebase.auth().currentUser; $scope.datauser = ''; userLoggedOn = user; firebase.auth().onAuthStateChanged(function(userLoggedOn) { if(!userLoggedOn){ $location.path('/login') } }); //console.log($scope.datauser); $scope.countLine = 0; // firebase.auth().onAuthStateChanged(function(user) { if (user) { $scope.countLine++; //$scope.showLoading(); //console.log('contador de linhas da 1148 é :'+$scope.countLine); $timeout(function() { //console.log('aqui1'); firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { $scope.datauser = snapshot.val(); //console.log(snapshot.val()); //$scope.showLoading(); //console.log('aqui2'); if(snapshot.val().role ==2){ $scope.tituloPagina='Gerar Senhas'; //console.log('aqui3'); firebase.database().ref().child('geo_filas').child(user.uid).once("value", function(snapshot) { //console.log('aqui4'); $scope.items = []; if(snapshot.val() != null ){ $scope.items.push(snapshot.val()); //console.log($scope.items); }else{ $scope.totalItens =$scope.items.length; } $scope.hideLoading(); firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { if(snapshot.val() != null ){ $scope.limite = snapshot.val().limit; } },function(error) { $scope.hideLoading(); }); },function(error) { $scope.hideLoading(); }); }else{ $scope.tituloPagina='<NAME>'; $scope.showLoading(); //console.log('aqui'); firebase.database().ref().child('categorias').orderByChild('categorias').once("value", function(snapshot) { //console.log('aqui2'); if(snapshot.val() != null ){ //console.log('aqui3'); $scope.categorias = snapshot.val(); $scope.optCategorias = []; $.each($scope.categorias, function(key, value){ if(value != '' && typeof value != 'undefined' && typeof value != undefined && value != null){ $scope.optCategorias.push({'categoria': value,'id':key}); } }); //console.log($scope.optCategorias); $timeout(function () { //console.log('aqui4'); $('#filtro').val(''); $('#filtro').trigger('change'); $scope.hideLoading(); }, 1000); }else{ $timeout(function () { $scope.hideLoading(); }, 2000); } // $('#filtro').focus(); },function(error){ //console.log('aqui 5'); $scope.hideLoading(); }); } }, function(error){ //console.log('aqui 6'); $scope.hideLoading(); }); },2500); }else{ //console.log('aqui3'); $scope.tituloPagina='Pegar Senha'; $scope.showLoading(); $timeout(function () { $scope.showLoading(); user = firebase.auth().currentUser; if(user) { $scope.showLoading(); firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { $scope.datauser = snapshot.val(); if(snapshot.val().role ==2) { $scope.tituloPagina='Gerar Senhas'; //console.log('aqui3'); firebase.database().ref().child('geo_filas').child(user.uid).once("value", function(snapshot) { // //console.log('aqui4'); $scope.items = []; if(snapshot.val() != null ){ $scope.items.push(snapshot.val()); // //console.log($scope.items); }else{ $scope.totalItens =$scope.items.length; } $scope.hideLoading(); firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { if(snapshot.val() != null ){ $scope.limite = snapshot.val().limit; } },function(error) { $scope.hideLoading(); }); },function(error) { $scope.hideLoading(); }); } }); //console.log($scope.datauser); $scope.showLoading(); firebase.database().ref().child('categorias').orderByChild('categorias').once("value", function(snapshot) { //console.log('aqui2'); //$scope.showLoading(); if(snapshot.val() != null ){ $scope.categorias = snapshot.val(); $scope.optCategorias = []; $.each($scope.categorias, function(key, value){ if(value != '' && typeof value != 'undefined' && typeof value != undefined && value != null){ $scope.optCategorias.push({'categoria': value,'id':key}); } }); //console.log($scope.optCategorias); $timeout(function () { //console.log($scope.optCategorias); $('#filtro').val(''); $('#filtro').trigger('change'); $scope.hideLoading(); }, 3000); }else{ $timeout(function () { $scope.hideLoading(); }, 2000); } // $('#filtro').focus(); }, function(error){ //console.log('aqui 5'); $scope.hideLoading(); }); //console.log('aqui1'); }else{ $scope.showLoading(); } }, 3000); //console.log('aqui'); // document.location.href = '#/page5'; } //}); $timeout(function() { //$('#filtro').val(''); //$('#filtro').trigger('change'); //$('#filtro').focus(); $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); },3000); //$scope.titulo='Gerar Senhas'; //$scope.hideLoading(); }); $scope.gerarSenhasCategorias = function(texto) { $location.path('/gerarsenhascategorias/'+texto); } $scope.removeUser = function() { $scope.showUserNotFind = false; $scope.userToNotify =[]; $('#busca').val(''); } $scope.showMensageuser = function(search) { if($scope.userToNotify == null || $scope.userToNotify == '' ) { $scope.showUserNotFind = true; $timeout(function() { $scope.showUserNotFind = false; },9000); }else { $scope.showUserNotFind = false; } } $scope.retornaNome = function(num) { switch (num) { case 1: return 'Comum'; break; case 2: return 'Prioritária'; break; case 3: return 'Manual'; break; default: } } $scope.userToNotify=''; $scope.buscarUsuarios = function(search) { $scope.showUserNotFind = false; if(typeof search != 'undefined' ) { busca = search.split("@"); //var rootRef = firebase.database.ref(); //var usersRef = rootRef.child("users"); // //console.log(usersRef.parent.isEqual(rootRef)); firebase.database().ref().child('users').orderByChild('email').equalTo(search).on("value", function(snapshot) { $scope.userToNotify=snapshot.val(); // //console.log(snapshot.val()); }); if(busca.length == 1){ } //console.log(search); } } $scope.pos={}; $scope.pos.lat=0; $scope.pos.lon=0; $scope.post={}; $scope.imageUrl=''; $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...' }).then(function(){ }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ }); }; $scope.showAlert = function(texto) { var alertPopup = $ionicPopup.alert({ title: texto.titulo, template: texto.mensagem }); alertPopup.then(function(res) { }); }; $scope.contador=''; $scope.contaNumero = function(id){ setDateTime(); user = firebase.auth().currentUser; $scope.contadorAuxSenha = 0; $scope.countLine=0; //firebase.auth().onAuthStateChanged(function(user) { if (user){ $scope.countLine++; if($scope.contadorAuxSenha==0){ $scope.contadorAuxSenha ++ firebase.database().ref().child('geo_filas').child(user.uid).child(id).once("value", function(snapshot){ if(snapshot.val() != null) { fila =snapshot.val(); $scope.contador = parseInt(fila.numero_contador) + 1; // //console.log($scope.contador); user = firebase.auth().currentUser; var mykey = firebase.database().ref('geo_filas_senhas/' + user.uid).push(); var prefixo = fila.prefixo || ''; var contador = $scope.contador || 1; var nome = fila.nome || 'S/N'; var posFixoRestaurante = ''; if(typeof $scope.datauser.categoria != 'undefined'){ if($scope.datauser.categoria== 1){ posFixoRestaurante= $('#qtdPessoas').val(); if(typeof posFixoRestaurante != 'undefined' && posFixoRestaurante != '? undefined:undefined ?'){ posFixoRestaurante = ' P-'+ posFixoRestaurante; }else { posFixoRestaurante = ' P-'+ 1; } } } firebase.database().ref('geo_filas_senhas/' + user.uid).push({ pos:contador, numero:prefixo + $scope.contador + posFixoRestaurante, ativo:'true', tipo:nome,data:getDate(userDateTimeFull),user_id:$scope.user_id , }, function(error) { $scope.hideLoading(); $scope.texto={}; if(error){ $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='Não conseguimos efetuar a operação.'; $scope.hideLoading(); $scope.showAlert($scope.texto); }else { $scope.texto.titulo ='Tudo certo!'; $scope.texto.mensagem ='Sua senha é '+ prefixo + contador + posFixoRestaurante; firebase.database().ref('geo_filas').child(user.uid).child(id).child('/numero_contador').set( $scope.contador); if($scope.user_id != '' && $scope.user_id != null) { firebase.database().ref('senhas_usuarios/' + $scope.user_id).push({ pos:contador, numero:prefixo + $scope.contador + posFixoRestaurante, ativo:'true', tipo:nome,data:getDate(userDateTimeFull),loja_id:$scope.user_id , }, function(error) { }); } $scope.hideLoading(); $('#qtdPessoas').val(''); $scope.showAlert($scope.texto); } }); }else { $scope.texto={}; $scope.texto.titulo ='Ops! Que embaraçoso'; $scope.texto.mensagem ='Algo deu errado, a operação não foi efetuada.'; $scope.hideLoading(); $scope.showAlert($scope.texto); } }); } } //}); } $scope.contaSenha = function() { setDateTime(); $scope.countLine=0; firebase.auth().onAuthStateChanged(function(user) { if (user){ var dateObj = new Date(); var month = dateObj.getUTCMonth() + 1; //months from 1-12 var day = dateObj.getUTCDate(); var year = dateObj.getUTCFullYear(); $scope.countLine++; user = firebase.auth().currentUser; var ref = firebase.database().ref("senhas_gratis/"+user.uid+'/'+ year +'/'+ month); ref.once("value") .then(function(snapshot) { var a = snapshot.numChildren(); // 1 ("name") $scope.contadorSenha = snapshot.child(day).numChildren(); // 2 ("first", "last") // //console.log($scope.contadorSenha); //return b; }); } }); } $scope.contadorSenha = $scope.contaSenha(); $scope.setlogsenha = function() { setDateTime(); //$timeout(function () { var dateObj = new Date(); var month = dateObj.getUTCMonth() + 1; //months from 1-12 var day = dateObj.getUTCDate(); var year = dateObj.getUTCFullYear(); user = firebase.auth().currentUser; firebase.database().ref('senhas_gratis/' + user.uid +'/' + year +'/'+ month+'/'+ day ).push({qtd:1}); //}, 300); } //$scope.setlogsenha(); $scope.gerarSenha = function(value, id) { $scope.showLoading(); user = firebase.auth().currentUser; var user_id = $('#user_id').val(); $scope.user_id = $('#user_id').val() || null; user_id = user_id || null; $('#user_id').val(''); $('#busca').val(''); $scope.userToNotify =[]; $scope.contaSenha(); $scope.texto= {}; if( $scope.contadorSenha >= $scope.limite) { $scope.texto.titulo ='Aviso'; $scope.texto.mensagem ='Limite de senhas diárias excedido. Aumente o limite em configurações -> Minha Conta.'; $scope.hideLoading(); $scope.showAlert($scope.texto); }else{ $scope.setlogsenha(); $scope.contaNumero(id); estab = user.displayName; estab = estab || user.email; if(user_id != '' && user_id !=null){ sendNotificationTouUserNewNumber(user_id,estab); } } } $scope.senhamanual=''; $scope.gerarSenhaManual = function(value, id, senhamanual) { setDateTime(); $scope.showLoading(); //console.log('aqui'); var user_id = $('#user_id').val(); $scope.user_id = $('#user_id').val() || null; user_id = user_id || null; $('#user_id').val(''); $('#busca').val(''); $scope.userToNotify =[]; if(senhamanual != '') { user = firebase.auth().currentUser; $scope.setlogsenha(); $scope.existNum =''; $scope.contaSenha(); $scope.texto= {}; //console.log('aqi232'); if( $scope.contadorSenha >= $scope.limite) { $scope.texto.titulo ='Aviso'; $scope.texto.mensagem ='Limite de senha diárias excedido.'; $scope.hideLoading(); $scope.showAlert($scope.texto); }else{ firebase.database().ref().child('geo_filas_senhas').child(user.uid).orderByChild("numero").startAt(senhamanual).endAt(senhamanual).once("value", function(snapshot) { if(snapshot.val() != null && snapshot.val() != 'null' && snapshot.val() != ''){ $scope.texto={}; $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='Este número já está em uso.'; $scope.hideLoading(); $scope.showAlert($scope.texto); }else{ var mykey = firebase.database().ref('geo_filas_senhas/' + user.uid).push(); firebase.database().ref('geo_filas_senhas/' + user.uid +'/' + mykey.key ).set({ pos:'1', numero:senhamanual, ativo:'true',tipo:value.nome,data:getDate(userDateTimeFull),user_id:user_id, }, function(error) { $scope.texto={}; if(error){ $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='Operaçao não efetuada.'; $scope.hideLoading(); $scope.showAlert($scope.texto); }else { $scope.texto.titulo ='Tudo Certo'; $scope.texto.mensagem ='Sua senha é '+ senhamanual; estab = user.displayName; estab = estab || user.email; if(user_id != '' && user_id !=null){ sendNotificationTouUserNewNumber(user_id,estab); } $scope.hideLoading(); $scope.showAlert($scope.texto); } }); } }); } }else{ $scope.texto={}; $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='O valor do campo manual não pode ficar vazio.'; $scope.hideLoading(); $scope.showAlert($scope.texto); } } }]) .controller('configuraEsCtrl', ['$scope','$ionicSideMenuDelegate', '$stateParams','$location','$ionicLoading','$timeout', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$ionicSideMenuDelegate, $stateParams,$location,$ionicLoading,$timeout) { var connectedRef = firebase.database().ref(".info/connected"); $scope.tentativas = 0; //$scope.conectDiv=true; connectedRef.on("value", function(snap) { $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); if (snap.val() === true) { $scope.conectDiv=true; $timeout(function () { $('body').trigger('click'); // $scope.conectDiv=true; },1500); //$window.location.reload(); } else { $scope.conectDiv=false; $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); } }); userLoggedOn = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(userLoggedOn) { if(!userLoggedOn){ $location.path('/login') } }); $ionicSideMenuDelegate.canDragContent(false); $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', duration: 15000 }).then(function(){ //console.log("The loading indicator is now displayed"); }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); }; $scope.titulo =''; $scope.$on('$ionicView.leave', function(){ //$ionicSideMenuDelegate.canDragContent(true); //$('.ion-navicon').show(); }); $scope.$on('$ionicView.beforeEnter', function (event, viewData) { $scope.showContent= false; $timeout(function () { $scope.showContent= true; }, 2500); $scope.showLoading(); var lojasAux = {}; $scope.lojas =[]; $scope.noticket = false; $scope.countLine = 0; //firebase.auth().onAuthStateChanged(function(user) { user = firebase.auth().currentUser; $scope.datauser = user; if (user){ $scope.countLine++; //console.log('contador da linha 1525 é :'+$scope.countLine); $timeout(function() { firebase.database().ref().child('users').child(user.uid).once("value", function(snapshotuser){ $scope.datauser = snapshotuser.val(); //console.log($scope.datauser); if($scope.datauser.role == 2) { $scope.titulo ='Minha Fila'; firebase.database().ref().child('geo_filas_senhas_usadas').child(user.uid).limitToLast(1).on("child_added", function(snapshot) { if(snapshot.val() != null ){ $scope.senha=snapshot.val(); $scope.hideLoading(); $scope.noticket = false; }else{ $scope.noticket = true; $scope.hideLoading(); } },function(error) { $scope.hideLoading(); }); $scope.senhasAnterioresAux=[] var ref = firebase.database().ref().child('geo_filas_senhas_usadas').child(user.uid); $scope.senhasAnteriores=[]; ref.orderByKey().limitToLast(10).on("child_added", function(snapshot) { if(snapshot.val() != null ){ $scope.senhasAnteriores.unshift(snapshot.val()); //countRef++; } },function(error) { $scope.hideLoading(); }); $('#filtro').val(' '); }else { $scope.titulo ='Favoritos'; $scope.hasLojas='S'; firebase.database().ref().child('usuarios_favoritos').child(user.uid).once("value", function(snapshot) { var lojasAux = {}; if(snapshot.val() != null ){ $scope.lojas =[]; lojasAux.segue='S'; $.each(snapshot.val(), function (key, val) { $scope.hasLojas='S'; firebase.database().ref().child('users').child(key).once("value", function(snapshot2) { if(snapshot2.val() != null){ lojasAux = snapshot2.val(); lojasAux.key = key; lojasAux.segue='S'; lojasAux.categoriaNome= returnCategoria(snapshot2.val().categoria); //console.log(snapshot2.val()); $scope.lojas.push(lojasAux); $timeout(function(){ $('#filtro2').val(''); $scope.hideLoading(); //console.log('her34'); },1000); //console.log($scope.lojas); }else{ lojasAux.segue='N'; $scope.hasLojas='N'; } },function(error) { $scope.hideLoading(); }); }); //console.log(snapshot.val()); //$scope.lojas=snapshot.val(); $scope.hideLoading(); }else{ $scope.hasLojas='N'; $scope.hideLoading(); } }, function(error) { $scope.hideLoading(); }); } }, function(error) { //console.log('error aqui'); $scope.hideLoading(); }); //$scope.hideLoading(); },2500); //$scope.showLoading(); } else { $scope.hideLoading(); $location.path('/page5') } //}); }); $scope.seguirEstabelecimento=function(id) { $scope.showLoading(); $scope.lojaId = id; user = firebase.auth().currentUser; //console.log($scope.lojaId); $scope.countLine=0; // firebase.auth().onAuthStateChanged(function(user) { if (user){ $scope.countLine++; //console.log('contador da linha 1615 é :'+$scope.countLine); //console.log(); firebase.database().ref().child('lojas_seguidores').child($scope.lojaId).orderByValue().equalTo(user.uid).once("value", function(snapshot) { if(snapshot.val() != null){ $.each(snapshot.val(), function (key, val) { firebase.database().ref('lojas_seguidores/'+$scope.lojaId+'/'+key).remove(); firebase.database().ref('usuarios_favoritos').child(user.uid).child($scope.lojaId).remove(); $('#seguir'+id).removeClass('segueS'); $('#seguir'+id).removeClass('segueN'); $('#seguir'+id).addClass('segueN'); }); $scope.hideLoading(); }else{ $('#seguir'+id).removeClass('segueN'); $('#seguir'+id).removeClass('segueS'); $('#seguir'+id).addClass('segueS'); firebase.database().ref().child('lojas_seguidores').child($scope.lojaId).push(user.uid); firebase.database().ref().child('usuarios_favoritos').child(user.uid).child($scope.lojaId).push($scope.lojaId); $scope.hideLoading(); } //console.log(snapshot.key); }); } //$scope.hideLoading(); //}); } $scope.moredata = false; $scope.loadMoreData=function() { if(typeof $scope.senhasAnterioresAux[0] != "undefined") { $scope.senhasAnteriores.push($scope.senhasAnterioresAux[0]); $scope.senhasAnterioresAux.shift(); $scope.$broadcast('scroll.infiniteScrollComplete'); }else{ $timeout(function() { $scope.$broadcast('scroll.infiniteScrollComplete'); $scope.moredata=true; },3000); } }; /*$scope.clicarCorpo = function() { //console.log('aqui'); if($('.tabs').is(":visible")){ $scope.esconder(); }else{ $scope.mostrar(); } }*/ $scope.mostrar = function() { $('.nav-bar-container').fadeIn(1000); $('.tabs').fadeIn(1000); } $scope.esconder = function() { $('.nav-bar-container').fadeOut(1000); $('.tabs').fadeOut(1000); } //alert(); }]) .controller('menuCtrl', ['$scope','$ionicSideMenuDelegate', '$stateParams','$ionicLoading','$timeout', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$ionicSideMenuDelegate, $stateParams,$ionicLoading,$timeout) { $ionicSideMenuDelegate.canDragContent(false); $scope.$on('$ionicView.beforeEnter', function (event, viewData) { //viewData.enableBack = true; firebase.auth().onAuthStateChanged(function(user) { user = firebase.auth().currentUser; $scope.user = firebase.auth().currentUser; firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { $scope.datauser = snapshot.val(); //console.log(snapshot.val()); }); }); }); $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', duration: 3000 }).then(function(){ //console.log("The loading indicator is now displayed"); }); }; $scope.logoff = function() { firebase.auth().signOut().then(function() { // Sign-out successful. }, function(error) { // An error happened. }); //$timeout(function() { // document.location.href = '#/page5'; //},3000); } }]) .controller('loginCtrl', ['$scope','$timeout','$location','$cordovaOauth', '$stateParams','$ionicLoading','$ionicHistory','$timeout','$ionicSideMenuDelegate', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$timeout,$location,$cordovaOauth, $stateParams,$ionicLoading,$ionicHistory,$timeout,$ionicSideMenuDelegate) { $ionicSideMenuDelegate.canDragContent(false); $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', duration: 6000 }).then(function(){ //console.log("The loading indicator is now displayed"); }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); }; /*$scope.ionicGoBack = function() { $ionicHistory.goBack(); };*/ var user = firebase.auth().currentUser; $scope.$on('$ionicView.enter', function(){ $ionicSideMenuDelegate.canDragContent(false); $('.ion-navicon').hide(); }); $scope.$on('$ionicView.beforeEnter', function (event, viewData) { viewData.enableBack = false; $scope.notToShow = false; $scope.showContent = false; $timeout(function () { $scope.showContent = true; }, 6000); //$scope.showLoading(); user = firebase.auth().currentUser; //console.log(user); $scope.countLine=0; firebase.auth().onAuthStateChanged(function(user) { //alert('<PASSWORD>'); $scope.showLoading(); if(user){ $scope.countLine++; $scope.user = firebase.auth().currentUser; firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { //console.log('aqui2'); $scope.datauser = snapshot.val(); //$location.path('#/page1/page3');; document.location.href = '#/page1/page3'; }, function(error) { //document.location.href = '#/page1/page3'; }); } }); }); }]) .controller('login2Ctrl', ['$scope','$location','$cordovaOauth', '$stateParams','$ionicLoading','$ionicHistory','$timeout','$ionicSideMenuDelegate', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$location,$cordovaOauth, $stateParams,$ionicLoading,$ionicHistory,$timeout,$ionicSideMenuDelegate) { $ionicSideMenuDelegate.canDragContent(false); $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', duration: 3000 }).then(function(){ //console.log("The loading indicator is now displayed"); }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); }; $scope.ionicGoBack = function() { $ionicHistory.goBack(); }; var user = firebase.auth().currentUser; $scope.$on('$ionicView.enter', function(){ $ionicSideMenuDelegate.canDragContent(false); $('.ion-navicon').hide(); }); $scope.$on('$ionicView.beforeEnter', function (event, viewData) { viewData.enableBack = true; $scope.notToShow = false; //$scope.showLoading(); user = firebase.auth().currentUser; //console.log(user); $scope.countLine=0; firebase.auth().onAuthStateChanged(function(user) { //alert('passou1'); if(user){ $scope.countLine++; $scope.user = firebase.auth().currentUser; firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { // //console.log('aqui2'); $scope.datauser = snapshot.val(); //$location.path('#/page1/page3');; document.location.href = '#/page1/page3'; }, function(error) { //document.location.href = '#/page1/page3'; }); } }); }); $scope.loginTwitter = function(user) { $scope.showLoading(); $('.aviso-login').html(''); var provider = new firebase.auth.TwitterAuthProvider(); firebase.auth().signInWithPopup(provider).then(function(result) { // This gives you a the Twitter OAuth 1.0 Access Token and Secret. // You can use these server side with your app's credentials to access the Twitter API. var token = result.credential.accessToken; var secret = result.credential.secret; // The signed-in user info. var user = result.user; document.location.href = '#/page1/page3'; // ... }).catch(function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // The email of the user's account used. var email = error.email; // The firebase.auth.AuthCredential type that was used. var credential = error.credential; // ... $('.divAvisoLogin').show(); $('.aviso-login').html('Ops, não encontramos o seu cadastro.'); }); $timeout(function() { firebase.auth().onAuthStateChanged(function(user) { user = firebase.auth().currentUser; $scope.user = firebase.auth().currentUser; firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { //console.log(snapshot.val()); }); document.location.href = '#/page1/page3'; }); },1000); } $scope.loginGoogle = function(user) { $scope.showLoading(); $('.aviso-login').html(''); var provider = new firebase.auth.GoogleAuthProvider(); firebase.auth().signInWithPopup(provider).then(function(result) { // This gives you a Google Access Token. You can use it to access the Google API. var token = result.credential.accessToken; // The signed-in user info. var user = result.user; //console.log(user); document.location.href = '#/page1/page3'; // ... }).catch(function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // The email of the user's account used. var email = error.email; // The firebase.auth.AuthCredential type that was used. var credential = error.credential; $('.divAvisoLogin').show(); $('.aviso-login').html('Ops, não encontramos o seu cadastro.'); // ... }); $timeout(function() { firebase.auth().onAuthStateChanged(function(user) { user = firebase.auth().currentUser; $scope.user = firebase.auth().currentUser; // //console.log(user); document.location.href = '#/page1/page3'; }); },1000); } $scope.esqueciasenha = function(user) { $scope.showLoading(); $('.divAvisoLogin').hide(); if (typeof user == 'undefined') { $('.aviso-login').html('Ops. Digite o email'); $('.divAvisoLogin').show(); }else if(user.email == '' || user.email == null){ $('.aviso-login').html('Ops. Digite o email'); $('.divAvisoLogin').show(); }else{ var auth = firebase.auth(); auth.sendPasswordResetEmail(user.email).then(function() { $('.aviso-login').html('Tudo certo! Um e-mail foi enviado para a redeficição da sua senha.'); $('.divAvisoLogin').show(); }, function(error) { $('.aviso-login').html('Ops! Ocorreu um erro e não conseguimos continuar com a redefinição da sua senha.'); $('.divAvisoLogin').show(); }); } } $scope.loginManual = function(user) { $scope.showLoading(); $('.divAvisoLogin').hide(); if(typeof user == 'undefined'){ $('.aviso-login').html('Ops. Digite o Email e Senha'); $('.divAvisoLogin').show(); }else{ // //console.log(user); firebase.auth().signInWithEmailAndPassword(user.email, user.password).catch(function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; //console.log(errorCode.length); if(errorCode.length == 19){ $('.divAvisoLogin').show(); $('.aviso-login').html('Algo deu errado, verifique seu email e senha.'); }else if (errorCode.length == 27) { $('.divAvisoLogin').show(); $('.aviso-login').html('Sem conexão com a internet.'); } }); $timeout(function() { firebase.auth().onAuthStateChanged(function(user) { user = firebase.auth().currentUser; $scope.user = firebase.auth().currentUser; firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { //console.log(snapshot.val()); document.location.href = '#/page1/page3'; }); }); },1000); } } $scope.loginFacebook = function(user) { $('.divAvisoLogin').hide(); var auth = new firebase.auth.FacebookAuthProvider(); $cordovaOauth.facebook("111991969424960", ["email"]).then(function(result) { var credential = firebase.auth.FacebookAuthProvider.credential(result.access_token); firebase.auth().signInWithCredential(credential).catch(function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // The email of the user's account used. var email = error.email; // The firebase.auth.AuthCredential type that was used. var credential = error.credential; if (errorCode === 'auth/account-exists-with-different-credential') { //alert('Email já está associado com uma outra conta.'); $('.divAvisoLogin').show(); $('.aviso-login').html('Email já está associado com uma outra conta.'); // Handle account linking here, if using. } else { console.error(error); } }); user = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(user) { $scope.showLoading(); user = firebase.auth().currentUser; $scope.user = firebase.auth().currentUser; $timeout(function() { firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { if(snapshot.val() != null){ document.location.href = '#/page1/page3'; }else{ $('.divAvisoLogin').show(); $('.aviso-login').html('Algo deu errado, esta conta ainda não possui cadastro.'); var user = firebase.auth().currentUser; user.delete().then(function() { // User deleted. }, function(error) { // An error happened. }); } },function(error){ $scope.hideLoading(); $('.divAvisoLogin').show(); $('.aviso-login').html('Algo deu errado, por favor verifique a sua conexão com a internet.'); }); },5000); }); }, function(error) { //alert("ERROR: " + error); }); } }]) .controller('cadastrarfilasCtrl', ['$scope','$ionicSideMenuDelegate', '$ionicPopup', '$stateParams', '$ionicHistory', '$location','$ionicLoading', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope, $ionicSideMenuDelegate,$ionicPopup, $stateParams,$ionicHistory, $location, $ionicLoading) { var connectedRef = firebase.database().ref(".info/connected"); $scope.tentativas = 0; //$scope.conectDiv=true; connectedRef.on("value", function(snap) { $scope.conectDiv=true; $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); if (snap.val() === true) { $scope.conectDiv=true; $timeout(function () { $('body').trigger('click'); // $scope.conectDiv=true; },1500); //$window.location.reload(); } else { $scope.conectDiv=false; $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); } }); userLoggedOn = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(userLoggedOn) { if(!userLoggedOn){ $location.path('/login') } }); $ionicSideMenuDelegate.canDragContent(false); $scope.retornaNome = function(num) { switch (num) { case 1: return 'Comum'; break; case 2: return 'Prioritária'; break; case 3: return 'Manual'; break; default: } } $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', //duration: 3000 }).then(function(){ //console.log("The loading indicator is now displayed"); }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); }; $scope.ionicGoBack = function() { $ionicHistory.goBack(); }; var user = firebase.auth().currentUser; $scope.$on('$ionicView.beforeEnter', function (event, viewData) { viewData.enableBack = true; $scope.notToShow = false; //$scope.conectDiv=true; $scope.showLoading(); firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { $scope.datauser = snapshot.val(); //console.log(snapshot.val()); if($scope.datauser.role ==2){ firebase.database().ref().child('geo_filas').child(user.uid).child($stateParams.id).on("value", function(snapshot) { if(snapshot.val() != null ){ $scope.fila = snapshot.val(); //console.log($scope.fila); } $scope.hideLoading(); },function(error) { $scope.hideLoading(); }); }else { $scope.hideLoading(); } },function (error) { $scope.hideLoading(); }); }); //console.log($stateParams.id); $scope.pos={}; $scope.pos.lat=0; $scope.pos.lon=0; $scope.post={}; $scope.imageUrl=''; var onSuccessPos = function(position) { $scope.pos.lat = position.coords.latitude; $scope.pos.lon= position.coords.longitude; //console.log($scope.pos.lon); }; // onError Callback receives a PositionError object function onErrorPos(error) { $scope.posErro=error; calldialog(); } navigator.geolocation.getCurrentPosition(onSuccessPos, onErrorPos, {maximumAge:60000, timeout:5000, enableHighAccuracy:true}); //$scope.fila.user_id =''; $scope.fila = []; if (user) { // User is signed in. //alert('1'); //console.log(user); $scope.fila.user_id = user.uid; } else { $location.path('/page5') } var firebaseRef = firebase.database().ref().child('geo_filas'); var geoFire = new GeoFire(firebaseRef); var ref = geoFire.ref(); // ref === firebaseRef //var mykey = ref.child('dados').push(); //console.log(user.uid); var user = firebase.auth().currentUser //$scope.showConfirm(); // An alert dialog $scope.showAlert = function(texto) { var alertPopup = $ionicPopup.alert({ title: texto.titulo, template: texto.mensagem }); alertPopup.then(function(res) { //console.log('Thank you for not eating my delicious ice cream cone'); $location.path('/page2'); }); }; $scope.cadastrarFila = function(fila) { var user = firebase.auth().currentUser var nome = fila.nome || null; var ativa = fila.ativa || false; var prioridade = fila.prioridade || false; var prioridade_qtd = fila.qtd_prioridade || 0; var manual = fila.manual || false; var numero_contador = fila.numero_contador || 0; var prefixo = fila.prefixo || ''; $scope.texto= {}; //console.log(nome); if(nome == null || nome == 'undefined' ) { $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='O nome não poder estar vazio.'; $scope.showAlert($scope.texto); }else{ firebase.database().ref('geo_filas/' + user.uid + '/' + $stateParams.id).set({ nome: nome, ativa:ativa, prioridade:prioridade, prioridade_qtd:prioridade_qtd, manual:manual, numero_contador:numero_contador, prefixo:prefixo, }, function(error) { if(error){ $scope.texto.titulo ='Ops! Foi mal!'; $scope.texto.mensagem ='Não conseguimos desta vez.'; $scope.showAlert($scope.texto); }else { $scope.texto.titulo ='Tudo certo!'; $scope.texto.mensagem ='A configuração foi salva.'; $scope.showAlert($scope.texto); } }); } } }]) .controller('signupCtrl', ['$scope','$cordovaOauth','$location','$firebaseObject','$firebaseAuth', '$stateParams','$ionicPopup','$ionicLoading','$timeout','$ionicSideMenuDelegate', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$cordovaOauth ,$location, $firebaseObject,$firebaseAuth,$stateParams,$ionicPopup,$ionicLoading,$timeout,$ionicSideMenuDelegate) { $scope.$on('$ionicView.enter', function(){ $ionicSideMenuDelegate.canDragContent(false); $('.ion-navicon').hide(); user = firebase.auth().currentUser; //alert('<PASSWORD>'); firebase.auth().onAuthStateChanged(function(user) { if(user){ // document.location.href = '#/page1/page3'; } }); }); $scope.$on('$ionicView.leave', function(){ //$ionicSideMenuDelegate.canDragContent(true); //$('.ion-navicon').show(); }); $scope.$on('$ionicView.beforeEnter', function (event, viewData) { user = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(user) { if(user){ $scope.showLoading(); $timeout(function () { $scope.showLoading(); //$location.path('#/page1/page3');; document.location.href = '#/page1/page3'; }, 3000); } }); }); $scope.loginNormal = function (e) { $scope.user= e; ref.authWithPassword({ email : $scope.user.email, password : $<PASSWORD> }, function(error, authData) { if (error) { } else { //$location.path('#/page1/page3');; document.location.href = '#/page1/page3'; // window.location.href = '#/home'; } }); } $scope.showPopup = function(texto) { var alertPopup = $ionicPopup.alert({ title: texto.titulo, template: texto.mensagem }); }; $scope.validaEmail= function(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; //$('.aviso-cadastro').hide(); if(re.test(email)){ $('.divAvisoEmail').hide(); $('.lb-email ').removeClass('myredcolor'); return true; }else { $('.divAvisoEmail').show(); $('.lb-email ').addClass('myredcolor'); return false; } } $scope.difpassword = function(user) { $('.aviso-cadastro').html(''); if(typeof user !=='undefined') { if (user.password != <PASSWORD> && (user.password != '' && user.cpassword != '') ) { $('.lb-password ').addClass('myredcolor'); $('.divAviso').show(); return false; }else{ $('.lb-password ').removeClass('myredcolor'); $('.divAviso').hide(); return true; } }else { $('.lb-password ').removeClass('myredcolor'); $('.divAviso').hide(); return true; } } $scope.validaCadastro = function(user) { $('.aviso-cadastro').html(''); if(user.email == null || user.email == ''){ $scope.texto.titulo='Ops! Algo deu errado.'; $scope.texto.mensagem='O campo email não pode ficar vazio.'; return false; }else{ return true; } } $scope.validaFormulario = function(user) { $('.aviso-cadastro').html(''); var flagValid=true; if($scope.difpassword(user)== false){ flagValid= false; } if(!$scope.validaEmail(user.email)){ flagValid= false; } if($scope.validaCadastro(user)== false){ flagValid= false; } return flagValid; } function logUser(user) { var ref = firebase.database().ref("users"); // //console.log(user); var obj = { "user": user }; ref.push(obj); // or however you wish to update the node } $scope.pos={}; $scope.pos.lat=0; $scope.pos.lon=0; $scope.post={}; $scope.imageUrl=''; var onSuccessPos = function(position) { $scope.pos.lat = position.coords.latitude; $scope.pos.lon= position.coords.longitude; //console.log($scope.pos.lon); }; $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', duration: 3000 }).then(function(){ // //console.log("The loading indicator is now displayed"); }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ // //console.log("The loading indicator is now hidden"); }); }; $scope.showAlert = function(texto) { var alertPopup = $ionicPopup.alert({ title: texto.titulo, template: texto.mensagem }); alertPopup.then(function(res) { //console.log('Thank you for not eating my delicious ice cream cone'); //$location.path('/page1/page10'); }); }; function onErrorPos(error) { $scope.posErro=error; calldialog(); } navigator.geolocation.getCurrentPosition(onSuccessPos, onErrorPos, {maximumAge:60000, timeout:5000, enableHighAccuracy:true}); $scope.cadastrarUsuarioCliente = function(user) { $scope.showLoading(); $('.aviso-cadastro').html(''); if(typeof user != 'undefined') { //console.log('aqui'); if($scope.validaCadastro(user)){ if($scope.validaFormulario(user)){ firebase.auth().createUserWithEmailAndPassword(user.email, user.password).catch(function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; var errorWeek ='auth/weak-password'; $('.lb-email ').removeClass('myredcolor'); // //console.log('aqui1'); if(errorCode.length == 18){ $('.aviso-cadastro').html('Ops, a senha deve ter pelo menos 6 caracteres!'); $('.divAvisoCadastro').show(); }else if(errorCode.length == 25){ $('.lb-email ').addClass('myredcolor'); $('.aviso-cadastro').html('Ops, este email já se encontra em uso.'); $('.divAvisoCadastro').show(); }else if (errorCode.length == 27) { $('.divAvisoCadastro').show(); $('.aviso-cadastro').html('Sem conexão com a internet.'); } // ... }); $scope.cadastrarManualCliente=1; firebase.auth().onAuthStateChanged(function(user) { if($scope.cadastrarManualCliente == 1){ user = firebase.auth().currentUser; $scope.user = firebase.auth().currentUser; //console.log($scope.user); firebase.database().ref('users/' + user.uid).remove(); firebase.database().ref('users/' + user.uid).set({ email: user.email, active:1, role:3, ver_fila:true, nome:user.displayName, email:user.email, foto:user.photoURL, raio:50, }, function(error) { if(error){ //console.log('erro'); }else{ } }); $scope.cadastrarManualCliente=0; $timeout(function() { //$location.path('#/page1/page3');; document.location.href = '#/page1/page3'; },1000); } }); //}); } } }else{ $('.aviso-cadastro').html('Ops, digite o usuário e a senha!'); $('.divAvisoCadastro').show(); //console.log('aqui2'); } //console.log(user); } $scope.cadastrarUsuarioFacebookCliente = function(user) { var auth = new firebase.auth.FacebookAuthProvider(); $('.divAvisoCadastro').hide(); $cordovaOauth.facebook("111991969424960", ["email"]).then(function(result) { var credential = firebase.auth.FacebookAuthProvider.credential(result.access_token); firebase.auth().signInWithCredential(credential).catch(function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // The email of the user's account used. var email = error.email; // The firebase.auth.AuthCredential type that was used. var credential = error.credential; if (errorCode === 'auth/account-exists-with-different-credential') { //alert('Email already associated with another account.'); // Handle account linking here, if using. $('.divAvisoCadastro').show(); $('.divAvisoCadastro').html('Email já está associado com uma outra conta.'); } else { console.error(error); } }); }, function(error) { //alert("ERROR: " + error); }); user = firebase.auth().currentUser; //alert('<PASSWORD>'); $scope.cadastraUsuarioFacebookFlag= 1; firebase.auth().onAuthStateChanged(function(user) { //alert('passou2'); if($scope.cadastraUsuarioFacebookFlag == 1){ firebase.database().ref().child('users').child(user.uid).child('email').once("value", function(snapshot) { //console.log(snapshot.val()); if(snapshot.val() != null && snapshot.val() != 'null' ){ //$location.path('#/page1/page3');; document.location.href = '#/page1/page3'; }else{ //console.log('aqui2'); firebase.database().ref('users/' + user.uid).remove(); firebase.database().ref('users/' + user.uid).set({ email: user.email, active:1, role:3, ver_fila:true, nome:user.displayName, email:user.email, foto:user.photoURL, raio:50, }, function(error) { //$location.path('#/page1/page3');; document.location.href = '#/page1/page3'; }); } }); $scope.cadastraUsuarioFacebookFlag=0; } }); } }]) .controller('minhacontaCtrl', ['$scope','$location','$ionicSideMenuDelegate', '$stateParams','$ionicHistory','$ionicLoading','$ionicPopup','$timeout', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$location,$ionicSideMenuDelegate, $stateParams,$ionicHistory,$ionicLoading,$ionicPopup,$timeout) { userLoggedOn = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(userLoggedOn) { if(!userLoggedOn){ $location.path('/login') } }); var connectedRef = firebase.database().ref(".info/connected"); $scope.conectDiv=true; connectedRef.on("value", function(snap) { $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); if (snap.val() === true) { $scope.conectDiv=true; $timeout(function () { $('body').trigger('click'); // $scope.conectDiv=true; },1500); //$window.location.reload(); } else { $scope.conectDiv=false; $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); } }); $ionicSideMenuDelegate.canDragContent(false); $scope.$on('$ionicView.beforeEnter', function (event, viewData) { viewData.enableBack = true; $scope.notToShow = false; $scope.showLoadingNoTime(); $scope.countLine=0; user = firebase.auth().currentUser; //firebase.auth().onAuthStateChanged(function(user) { if (user){ $scope.countLine++; ///$scope.showLoading(); $scope.user = firebase.auth().currentUser; //console.log($scope.user); //$scope.showLoading(); firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { $scope.datauser = snapshot.val(); //console.log(snapshot.val()); }); firebase.database().ref().child('geo_lojas').child(user.uid).child('dados').once("value", function(snapshot) { $scope.dataLojas = snapshot.val(); //console.log(snapshot.val()); }); } $('.numeric').keyup(function () { this.value = this.value.replace(/[^0-9\.]/g,''); }); //}); $scope.categorias = ''; $scope.optCategorias=[]; $scope.pos={}; $scope.pos.lat=0; $scope.pos.lon=0; $scope.post={}; $scope.imageUrl=''; var onSuccessPos = function(position) { $scope.pos.lat = position.coords.latitude; $scope.pos.lon= position.coords.longitude; //console.log($scope.pos.lon); }; function onErrorPos(error) { $scope.posErro=error; calldialog(); } $scope.optCategorias=[]; navigator.geolocation.getCurrentPosition(onSuccessPos, onErrorPos, {maximumAge:60000, timeout:5000, enableHighAccuracy:true}); firebase.database().ref().child('categorias').on("value", function(snapshot) { //$scope.showLoading(); if(snapshot.val() != null ){ $scope.categorias = snapshot.val(); $scope.optCategorias=[] ; angular.forEach($scope.categorias, function(value, key) { $scope.optCategorias.push({ chave: key, valor: value }); }); $timeout(function () { if(typeof $scope.datauser != 'undefined'){ $('#categoria').val($scope.datauser.categoria); $('#categoria').trigger('change'); } $scope.hideLoading(); },3000); } },function(error) { $scope.hideLoading(); }); }); $scope.getImage = function (source) { //alert('passou1'); // Retrieve image file location from specified source $('#configForm').submit(function(event) { event.preventDefault(); }); $scope.showImage=false; var options = { maximumImagesCount: 1, quality: 50 }; $scope.showLoading(); window.imagePicker.getPictures( function(results) { //alert('passou2'); for (var i = 0; i < results.length; i++) { //getFileEntry(results[i]); var imageData = results[i]; var filename = imageData.split("/").pop(); var storageRef = firebase.storage().ref(); var getFileBlob = function(url, cb) { var xhr = new XMLHttpRequest(); xhr.open("GET", url); xhr.responseType = "blob"; xhr.addEventListener('load', function() { cb(xhr.response); }); xhr.send(); }; var blobToFile = function(blob, name) { blob.lastModifiedDate = new Date(); blob.name = name; return blob; }; var getFileObject = function(filePathOrUrl, cb) { getFileBlob(filePathOrUrl, function(blob) { cb(blobToFile(blob, 'test.jpg')); }); }; getFileObject(imageData, function(fileObject) { var uploadTask = storageRef.child('images/'+user.uid+'.jpg').put(fileObject); uploadTask.on('state_changed', function(snapshot) { //alert(snapshot); }, function(error) { //alert(error); }, function() { var downloadURL = uploadTask.snapshot.downloadURL; $scope.datauser.foto = downloadURL; firebase.database().ref('users/' + user.uid).set($scope.datauser, function(error) { $scope.texto ={}; $scope.hideLoading(); if(error){ $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='Não conseguimos salvar a configuração.'; $scope.showAlert($scope.texto); }else{ $scope.texto.titulo ='Tudo Certo!'; $scope.texto.mensagem ='Sua configuração foi salva!'; $scope.showAlert($scope.texto); } }); //alert(downloadURL); // handle image here }); }); $timeout(function(){ $scope.hideLoading(); },2000); } }, function (error) { $scope.showImage=false; alert('Error: ' + error); $timeout(function(){ $scope.hideLoading(); },2000); }, options ); $timeout(function(){ $scope.hideLoading(); },2000); } $scope.editarUsuario = function(userData) { //console.log(userData); user = firebase.auth().currentUser; $scope.user = firebase.auth().currentUser; //navigator.geolocation.getCurrentPosition(onSuccessPos, onErrorPos, {enableHighAccuracy:true}); $scope.showLoading(); cat = $("#categoria").val(); desc = $("#descricao").val(); nome = $("#nome").val(); limite = $("#limite").val(); ver_fila = $("#ver_fila").val(); rudovip = $("#rudovip").val(); desconto = $("#desconto").val(); porcentagem = $("#porcentagem").val(); condicoes = $("#condicoes").val(); endereco = $("#endereco").val(); bairro = $("#bairro").val(); cidade = $("#cidade").val(); uf = $("#uf").val(); telefone1 = $("#telefone1").val(); telefone2 = $("#telefone2").val(); if($('#ver_fila').hasClass('ng-empty')) { ver_fila = false; }else{ ver_fila = true; } if($('#rudovip').hasClass('ng-empty')) { rudovip = false; }else{ rudovip = true; } if($('#desconto').hasClass('ng-empty')) { desconto = false; }else{ desconto = true; } cat = cat || null; desc = desc || null; limite = limite || null; $scope.datauser2 =[]; $scope.datauser2.nome = nome || null; porcentagem = porcentagem || null; condicoes = condicoes || null; if(user.displayName != null && user.displayName !='' && typeof user.displayName!= 'undefined') { $scope.datauser2.nome = user.displayName; //console.log('aqui1'); } $scope.datauser2.foto =''; if(user.photoURL != null && user.photoURL !='' && typeof user.photoURL!= 'undefined') { $scope.datauser2.foto = user.photoURL; }else if($scope.datauser.foto != null && $scope.datauser.foto !='' && typeof $scope.datauser.foto!= 'undefined'){ $scope.datauser2.foto = $scope.datauser.foto; }else{ $scope.datauser2.foto = null; } //user.displayName=nome; //user.photoURL= foto; //nome = user.displayName; //console.log(ver_fila); ver_fila = ver_fila || null; rudovip = rudovip || null; desconto = desconto || null; endereco = endereco || null; bairro = bairro || null; cidade = cidade || null; uf = uf || null; telefone1 = telefone1 || null; telefone2 = telefone2 || null; //firebase.auth().onAuthStateChanged(function(user) { //console.log($scope.datauser.categoria); //console.log(user.uid); //if(typeof $scope.datauser.categoria !='undefined'){ if(typeof user.uid != 'undefined'){ firebase.database().ref('geo_lojas_cat').child(0).child(user.uid).remove(); firebase.database().ref('geo_lojas_cat').child(1).child(user.uid).remove(); firebase.database().ref('geo_lojas_cat').child(2).child(user.uid).remove(); firebase.database().ref('geo_lojas_cat').child(3).child(user.uid).remove(); firebase.database().ref('geo_lojas_cat').child(4).child(user.uid).remove(); firebase.database().ref('geo_lojas_cat').child(5).child(user.uid).remove(); firebase.database().ref('geo_lojas_cat').child(6).child(user.uid).remove(); firebase.database().ref('geo_lojas_cat').child(7).child(user.uid).remove(); firebase.database().ref('geo_lojas_cat').child(8).child(user.uid).remove(); firebase.database().ref('geo_lojas_cat').child(9).child(user.uid).remove(); firebase.database().ref('geo_lojas_cat').child(10).child(user.uid).remove(); firebase.database().ref('geo_lojas_cat').child(11).child(user.uid).remove(); firebase.database().ref('geo_lojas_cat').child(12).child(user.uid).remove(); } //} firebase.database().ref('users/' + user.uid).set({ email: user.email, active:1, role:2, limit:limite, nome:$scope.datauser2.nome, foto:$scope.datauser2.foto, descricao:desc, categoria:cat, raio:50, ver_fila:ver_fila, rudovip:rudovip, desconto:desconto, porcentagem:porcentagem, condicoes:condicoes, endereco:endereco, bairro:bairro, cidade:cidade, uf:uf, telefone1:telefone1, telefone2:telefone2, }, function(error) { if(error){ $scope.texto={}; $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='Ops, o perfil não foi atualizado.'; $scope.hideLoading(); $scope.showPopup($scope.texto); }else{ firebase.database().ref().child('geo_lojas').child(cat).remove(); var firebaseRef = firebase.database().ref().child('geo_lojas_cat').child(cat); var geoFire = new GeoFire(firebaseRef); var ref = geoFire.ref(); // ref === firebaseRef var mykey = ref.child('lojas').push(); geoFire.set(user.uid, [$scope.pos.lat, $scope.pos.lon]).then(function() { //console.log("Provided key has been added to GeoFire"); firebase.database().ref('geo_lojas_cat/'+cat+'/'+ user.uid+'/dados').set({ endereco:'-', telefone:'-', nome:$scope.datauser2.nome, email:user.email, foto:$scope.datauser2.foto, raio:50, rudovip:rudovip, desconto:desconto, porcentagem:porcentagem, condicoes:condicoes, endereco:endereco, bairro:bairro, cidade:cidade, uf:uf, telefone1:telefone1, telefone2:telefone2, }, function(error) { }); if(($scope.pos.lat != '' && $scope.pos.lat != null) && ($scope.pos.lon != '' && $scope.pos.lon != null ) ){ firebase.database().ref('geo_lojas/'+ user.uid+'/l').set({ 0:$scope.pos.lat, 1:$scope.pos.lon }, function(error) { }); } }, function(error) { //console.log("Error: " + error); }); $scope.texto={}; $scope.texto.titulo ='Tudo Certo'; $scope.texto.mensagem ='Seu perfil foi atualizado.'; $scope.hideLoading(); $scope.showPopup($scope.texto); } }); //}); } $scope.showPopup = function(texto) { var alertPopup = $ionicPopup.alert({ title: texto.titulo, template: texto.mensagem }); }; $scope.showLoadingNoTime = function() { $ionicLoading.show({ template: 'Carregando...', }).then(function(){ // //console.log("The loading indicator is now displayed"); }); }; $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', duration: 3000 }).then(function(){ // //console.log("The loading indicator is now displayed"); }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ // //console.log("The loading indicator is now hidden"); }); }; }]) .controller('signuptwoCtrl', ['$scope','$cordovaOauth','$location', '$stateParams','$ionicPopup','$ionicLoading','$timeout','$ionicSideMenuDelegate', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$cordovaOauth, $location,$stateParams,$ionicPopup,$ionicLoading,$timeout,$ionicSideMenuDelegate) { $scope.$on('$ionicView.enter', function(){ $ionicSideMenuDelegate.canDragContent(false); $('.ion-navicon').hide(); }); $scope.pos={}; $scope.pos.lat=0; $scope.pos.lon=0; var onSuccessPos = function(position) { $scope.pos.lat = position.coords.latitude; $scope.pos.lon= position.coords.longitude; //console.log($scope.pos.lon); }; function onErrorPos(error) { $scope.posErro=error; $scope.pos.lat=0; $scope.pos.lon=0; calldialog(); } $scope.$on('$ionicView.beforeEnter', function (event, viewData) { navigator.geolocation.getCurrentPosition(onSuccessPos, onErrorPos, {maximumAge:60000, timeout:5000, enableHighAccuracy:true}); user = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(user) { if(user) { navigator.geolocation.getCurrentPosition(onSuccessPos, onErrorPos, {enableHighAccuracy:true}); $scope.showLoading(); $timeout(function () { $scope.showLoading(); //$location.path('#/page1/page3');; document.location.href = '#/page1/page3'; }, 3000); } }); }); $scope.$on('$ionicView.leave', function(){ //$ionicSideMenuDelegate.canDragContent(true); //$('.ion-navicon').show(); }); $scope.loginNormal = function (e) { $scope.user= e; ref.authWithPassword({ email : $scope.user.email, password : $<PASSWORD> }, function(error, authData) { if (error) { } else { //$location.path('#/page1/page3');; document.location.href = '#/page1/page3'; // window.location.href = '#/home'; } }); } $scope.showPopup = function(texto) { var alertPopup = $ionicPopup.alert({ title: texto.titulo, template: texto.mensagem }); }; $scope.validaEmail= function(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; //$('.aviso-cadastro').hide(); if(re.test(email)){ $('.divAvisoEmail').hide(); $('.lb-email ').removeClass('myredcolor'); return true; }else { $('.divAvisoEmail').show(); $('.lb-email ').addClass('myredcolor'); return false; } } $scope.difpassword = function(user) { $('.aviso-cadastro').html(''); if(typeof user !=='undefined') { if (user.password != <PASSWORD> && (user.password != '' && user.cpassword != '') ) { $('.lb-password ').addClass('myredcolor'); $('.divAviso').show(); return false; }else{ $('.lb-password ').removeClass('myredcolor'); $('.divAviso').hide(); return true; } }else { $('.lb-password ').removeClass('myredcolor'); $('.divAviso').hide(); return true; } } $scope.validaCadastro = function(user) { navigator.geolocation.getCurrentPosition(onSuccessPos, onErrorPos, {enableHighAccuracy:true}); $('.aviso-cadastro').html(''); if(user.email == null || user.email == ''){ $scope.texto.titulo='Ops! Algo deu errado.'; $scope.texto.mensagem='O campo email não pode ficar vazio.'; return false; }else{ return true; } } $scope.validaFormulario = function(user) { $('.aviso-cadastro').html(''); var flagValid=true; if($scope.difpassword(user)== false){ flagValid= false; } if(!$scope.validaEmail(user.email)){ flagValid= false; } if($scope.validaCadastro(user)== false){ flagValid= false; } return flagValid; } function logUser(user) { var ref = firebase.database().ref("users"); // //console.log(user); var obj = { "user": user }; ref.push(obj); // or however you wish to update the node } $scope.post={}; $scope.imageUrl=''; var onSuccessPos = function(position) { $scope.pos.lat = position.coords.latitude; $scope.pos.lon= position.coords.longitude; //console.log($scope.pos.lon); }; $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', duration: 3000 }).then(function(){ // //console.log("The loading indicator is now displayed"); }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ // //console.log("The loading indicator is now hidden"); }); }; $scope.showAlert = function(texto) { var alertPopup = $ionicPopup.alert({ title: texto.titulo, template: texto.mensagem }); alertPopup.then(function(res) { //console.log('Thank you for not eating my delicious ice cream cone'); //$location.path('/page1/page10'); }); }; function onErrorPos(error) { $scope.posErro=error; calldialog(); } navigator.geolocation.getCurrentPosition(onSuccessPos, onErrorPos, {maximumAge:60000, timeout:5000, enableHighAccuracy:true}); $scope.cadastrarUsuario = function(user) { $scope.showLoading(); $('.aviso-cadastro').html(''); if(typeof user != 'undefined') { //console.log('aqui'); if($scope.validaCadastro(user)){ if($scope.validaFormulario(user)){ $scope.showLoading(); firebase.auth().createUserWithEmailAndPassword(user.email, user.password).catch(function(error) { // Handle Errors here. $scope.showLoading(); var errorCode = error.code; var errorMessage = error.message; var errorWeek ='auth/weak-password'; $('.lb-email ').removeClass('myredcolor'); // //console.log('aqui1'); if(errorCode.length == 18){ $('.aviso-cadastro').html('Ops, a senha deve ter pelo menos 6 caracteres!'); $('.divAvisoCadastro').show(); }else if(errorCode.length == 25){ $('.lb-email ').addClass('myredcolor'); $('.aviso-cadastro').html('Ops, este email já se encontra em uso.'); $('.divAvisoCadastro').show(); }else if (errorCode.length == 27) { $('.divAvisoCadastro').show(); $('.aviso-cadastro').html('Sem conexão com a internet.'); } // ... }); //console.log('cadastrou'); $scope.cadastraUsuarioManualEstabelecimentoflag = 1; $timeout(function () { firebase.auth().onAuthStateChanged(function(userLoggedOn) { var user = firebase.auth().currentUser; $scope.user = firebase.auth().currentUser;; //console.log('mudou'); $scope.showLoading(); if($scope.cadastraUsuarioManualEstabelecimentoflag == 1){ //console.log('flagou'); //$scope.user = firebase.auth().currentUser; //console.log($scope.user); if(user != null){ firebase.database().ref('users/' + user.uid).remove(); firebase.database().ref('geo_filas/' + user.uid ).remove(); var firebaseRef = firebase.database().ref().child('geo_lojas'); var geoFire = new GeoFire(firebaseRef); var ref = geoFire.ref(); // ref === firebaseRef var mykey = ref.child('lojas').push(); firebase.database().ref('users/' + user.uid).set({ email: user.email, active:1, role:2, limit:10000, nome:null, email:user.email, foto:null, raio:50, }, function(error) { if(error){ //console.log('erro'); }else{ } }); //console.log('cadastrou1'); //console.log('Tudo Certo'); $scope.showLoading(); //Cadastra Fila Comum //var user = firebase.auth().currentUser firebase.database().ref('limit/' + user.uid).set({ limit:10000, }, function(error) { }); firebase.database().ref('geo_filas/' + user.uid ).push({ nome: 1, ativa:true, prioridade:false, prioridade_qtd:0, manual:false, numero_contador:0, prefixo:'CM-', }, function(error) { }); //Cadastra fila Prioritária firebase.database().ref('geo_filas/' + user.uid ).push({ nome: 2, ativa:true, prioridade:true, prioridade_qtd:2, manual:false, numero_contador:0, prefixo:'PR-', }, function(error) { }); //Cadastra fila Manual firebase.database().ref('geo_filas/' + user.uid ).push({ nome: 3, ativa:true, prioridade:false, prioridade_qtd:0, manual:true, numero_contador:0, prefixo:'MN-', }, function(error) { }); firebase.database().ref('geo_lojas/' + $scope.user.uid+'/dados').set({ endereco:'-', telefone:'-', nome:null, email:user.email, foto:null, raio:50, }, function(error) { }); geoFire.set($scope.user.uid, [$scope.pos.lat, $scope.pos.lon]).then(function() { //console.log("Provided key has been added to GeoFire"); firebase.database().ref('geo_lojas/' + $scope.user.uid+'/dados').set({ endereco:'-', telefone:'-', nome:null, email:user.email, foto:null, raio:50, }, function(error) { }); }, function(error) { //console.log("Error: " + error); }); $timeout(function () { //$location.path('#/page1/page3');; document.location.href = '#/page1/page3'; }, 4000); //console.log('cadastrou2'); $scope.cadastraUsuarioManualEstabelecimentoflag = 0; }else{ $timeout(function () { var user = firebase.auth().currentUser; $scope.user = firebase.auth().currentUser; //console.log('cadastrou1'); //console.log('Tudo Certo'); var firebaseRef = firebase.database().ref().child('geo_lojas'); var geoFire = new GeoFire(firebaseRef); var ref = geoFire.ref(); // ref === firebaseRef firebase.database().ref('users/' + user.uid).remove(); firebase.database().ref('geo_filas/' + user.uid ).remove(); firebase.database().ref('users/' + user.uid).set({ email: user.email, active:1, role:2, limit:10000, nome:null, email:user.email, foto:null, raio:50, }, function(error) { if(error){ //console.log('erro'); }else{ } }); var mykey = ref.child('lojas').push(); $scope.showLoading(); //Cadastra Fila Comum //var user = firebase.auth().currentUser firebase.database().ref('limit/' + user.uid).set({ limit:10000, }, function(error) { }); firebase.database().ref('geo_filas/' + user.uid ).push({ nome: 1, ativa:true, prioridade:false, prioridade_qtd:0, manual:false, numero_contador:0, prefixo:'CM-', }, function(error) { }); //Cadastra fila Prioritária firebase.database().ref('geo_filas/' + user.uid ).push({ nome: 2, ativa:true, prioridade:true, prioridade_qtd:2, manual:false, numero_contador:0, prefixo:'PR-', }, function(error) { }); //Cadastra fila Manual firebase.database().ref('geo_filas/' + user.uid ).push({ nome: 3, ativa:true, prioridade:false, prioridade_qtd:0, manual:true, numero_contador:0, prefixo:'MN-', }, function(error) { }); firebase.database().ref('geo_lojas/' + $scope.user.uid+'/dados').set({ endereco:'-', telefone:'-', nome:null, email:user.email, foto:null, raio:50, }, function(error) { }); geoFire.set($scope.user.uid, [$scope.pos.lat, $scope.pos.lon]).then(function() { //console.log("Provided key has been added to GeoFire"); firebase.database().ref('geo_lojas/' + $scope.user.uid+'/dados').set({ endereco:'-', telefone:'-', nome:null, email:user.email, foto:null, raio:50, }, function(error) { }); }, function(error) { //console.log("Error: " + error); }); $timeout(function () { //$location.path('#/page1/page3');; document.location.href = '#/page1/page3'; }, 4000); //console.log('cadastrou2'); $scope.cadastraUsuarioManualEstabelecimentoflag = 0; }, 3000); } }else { //console.log('errou'); } }); }, 2000); }else{ } } }else{ $('.aviso-cadastro').html('Ops, digite o usuário e a senha!'); $('.divAvisoCadastro').show(); //console.log('aqui2'); } //console.log(user); } $scope.cadastrarUsuarioFacebook = function(user) { $('.divAvisoCadastro').hide(); var auth = new firebase.auth.FacebookAuthProvider(); $cordovaOauth.facebook("111991969424960", ["email"]).then(function(result) { var credential = firebase.auth.FacebookAuthProvider.credential(result.access_token); firebase.auth().signInWithCredential(credential).catch(function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // The email of the user's account used. var email = error.email; // The firebase.auth.AuthCredential type that was used. var credential = error.credential; if (errorCode === 'auth/account-exists-with-different-credential') { //alert('Email already associated with another account.'); // Handle account linking here, if using. $('.divAvisoCadastro').show(); $('.divAvisoCadastro').html('Email já está associado com uma outra conta.'); } else { console.error(error); } }); //alert('logou'); //console.log(data); user = firebase.auth().currentUser; //alert('passou1'); firebase.auth().onAuthStateChanged(function(user) { //alert('passou2'); $scope.showLoading(); firebase.database().ref().child('users').child(user.uid).child('email').once("value", function(snapshot) { if(snapshot.val() != null ){ //$location.path('#/page1/page3');; document.location.href = '#/page1/page3'; }else{ firebase.database().ref('users/' + user.uid).remove(); firebase.database().ref('geo_filas/' + user.uid ).remove(); firebase.database().ref('users/' + user.uid).set({ email: user.email, active:1, role:2, limit:10000, nome:user.displayName, email:user.email, foto:user.photoURL, raio:50, }, function(error) { if(error){ //console.log('erro'); }else{ } }); //console.log('Tudo Certo'); firebase.database().ref('users/' + user.uid).remove(); firebase.database().ref('geo_filas/' + user.uid ).remove(); firebase.database().ref('users/' + user.uid).set({ email: user.email, active:1, role:2, limit:10000, nome:user.displayName, email:user.email, foto:user.photoURL, raio:50, }, function(error) { if(error){ //console.log('erro'); }else{ } }); //console.log('Tudo Certo'); var firebaseRef = firebase.database().ref().child('geo_lojas'); var geoFire = new GeoFire(firebaseRef); var ref = geoFire.ref(); // ref === firebaseRef var mykey = ref.child('lojas').push(); geoFire.set(user.uid, [$scope.pos.lat, $scope.pos.lon]).then(function() { //console.log("Provided key has been added to GeoFire"); firebase.database().ref('geo_lojas/' + user.uid+'/dados').set({ endereco:'-', telefone:'-', nome:user.displayName, email:user.email, foto:user.photoURL, raio:50, }, function(error) { }); }, function(error) { //console.log("Error: " + error); }); //Cadastra Fila Comum //var user = firebase.auth().currentUser firebase.database().ref('limit/' + user.uid).set({ limit:10000, }, function(error) { }); firebase.database().ref('geo_filas/' + user.uid ).push({ nome: 1, ativa:true, prioridade:false, prioridade_qtd:0, manual:false, numero_contador:0, prefixo:'CM-', }, function(error) { }); //Cadastra fila Prioritária firebase.database().ref('geo_filas/' + user.uid ).push({ nome: 2, ativa:true, prioridade:true, prioridade_qtd:2, manual:false, numero_contador:0, prefixo:'PR-', }, function(error) { }); //Cadastra fila Manual firebase.database().ref('geo_filas/' + user.uid ).push({ nome: 3, ativa:true, prioridade:false, prioridade_qtd:0, manual:true, numero_contador:0, prefixo:'MN-', }, function(error) { }); $timeout(function() { //$location.path('#/page1/page3');; document.location.href = '#/page1/page3'; },2000); } }); }); }, function(error) { // alert("ERROR: " + error); }); } $scope.Prioritária = function(user) { $scope.user=user; $('.myredcolor').removeClass('myredcolor'); //$scope.validaCadastro(user); if($scope.validaFormulario(user)) { firebase.auth().createUserWithEmailAndPassword(user.email, user.password).then(function(user) { // [END createwithemail] // callSomeFunction(); Optional // var user = firebase.auth().currentUser; // //console.log(user.uid); //function writeUserData(userId, email) { firebase.database().ref('users/' + user.uid).set({ email: user.email, active:1, limit:10000, role:2, raio:50, }, function(error) { if(error){ //console.log('erro'); }else{ //console.log('Tudo Certo'); var firebaseRef = firebase.database().ref().child('geo_lojas'); var geoFire = new GeoFire(firebaseRef); var ref = geoFire.ref(); // ref === firebaseRef var mykey = ref.child('lojas').push(); geoFire.set(user.uid, [$scope.pos.lat, $scope.pos.lon]).then(function() { //console.log("Provided key has been added to GeoFire"); firebase.database().ref('geo_lojas/' + user.uid+'/dados').set({ loja: 'Loja teste', endereco:'endereco teste', telefone:'telefone teste', foto:'undefined', raio:50, }, function(error) { }); }, function(error) { //console.log("Error: " + error); }); } }); //} //alert('salvou'); /*user.updateProfile({ displayName: username }).then(function() { // Update successful. }, function(error) { // An error happened. });*/ }, function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // [START_EXCLUDE] if (errorCode == 'auth/weak-password') { alert('The password is too weak.'); } else { console.error(error); } // [END_EXCLUDE] }); /*firebase.auth().createUserWithEmailAndPassword(user.email, user.password).catch(function(error,userData) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; if (errorCode == 'auth/weak-password') { alert('The password is too weak.'); } else { alert(errorMessage); } //console.log(userData); });*/ /*firebase.auth().createUserWithEmailAndPassword(user.email, user.password) .catch(function(error) { //console.log('aqui'); var user = firebase.auth().currentUser; logUser(user); // Optional }, function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; var msg= ''; if(error=='Error: The specified email address is already in use.') { msg='Email já em uso. Escolha outro email.'; $('.lb-email').addClass('myredcolor'); } if(error=='Error: Unable to contact the Firebase server.') { msg='Sem conexão com a internet. Tente mais terde.'; } $('.aviso-erro').html(msg); $('.divAvisoEmailUso').show(); return false; });*/ } } }]) .controller('pageCtrl', ['$scope', '$stateParams','$ionicSideMenuDelegate','$location', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope, $stateParams,$ionicSideMenuDelegate,$location) { $ionicSideMenuDelegate.canDragContent(false); $scope.$on('$ionicView.beforeEnter', function (event, viewData) { //viewData.enableBack = true; firebase.auth().onAuthStateChanged(function(user) { user = firebase.auth().currentUser; $scope.user = firebase.auth().currentUser; firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { $scope.datauser = snapshot.val(); //console.log(snapshot.val()); }); }); }); }]) .controller('page2Ctrl', ['$scope', '$stateParams','$ionicSideMenuDelegate', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope, $stateParams,$ionicSideMenuDelegate) { $ionicSideMenuDelegate.canDragContent(false); $scope.$on('$ionicView.beforeEnter', function (event, viewData) { //viewData.enableBack = true; firebase.auth().onAuthStateChanged(function(user) { user = firebase.auth().currentUser; $scope.user = firebase.auth().currentUser; firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { $scope.datauser = snapshot.val(); //console.log(snapshot.val()); }); }); }); }]) .controller('page3Ctrl', ['$scope', '$stateParams','$ionicSideMenuDelegate', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope, $stateParams,$ionicSideMenuDelegate) { $ionicSideMenuDelegate.canDragContent(false); $scope.$on('$ionicView.beforeEnter', function (event, viewData) { //viewData.enableBack = true; firebase.auth().onAuthStateChanged(function(user) { user = firebase.auth().currentUser; $scope.user = firebase.auth().currentUser; firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { $scope.datauser = snapshot.val(); //console.log(snapshot.val()); }); }); }); }]) .controller('filasCtrl', ['$scope','$timeout', '$ionicPopup', '$stateParams', '$ionicHistory', '$location','$ionicLoading','$ionicSideMenuDelegate', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$timeout, $ionicPopup, $stateParams, $ionicHistory, $location,$ionicLoading,$ionicSideMenuDelegate) { //alert(); var connectedRef = firebase.database().ref(".info/connected"); $scope.tentativas = 0; //$scope.conectDiv=true; connectedRef.on("value", function(snap) { $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); if (snap.val() === true) { $scope.conectDiv=true; $timeout(function () { $('body').trigger('click'); // $scope.conectDiv=true; },1500); //$window.location.reload(); } else { $scope.conectDiv=false; $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); } }); userLoggedOn = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(userLoggedOn) { if(!userLoggedOn){ $location.path('/login') } }); $ionicSideMenuDelegate.canDragContent(false); $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', duration: 15000, }).then(function(){ //console.log("The loading indicator is now displayed"); }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); }; $scope.showAlert = function(texto) { var alertPopup = $ionicPopup.alert({ title: texto.titulo, template: texto.mensagem }); alertPopup.then(function(res) { //console.log('Thank you for not eating my delicious ice cream cone'); //$location.path('/page1/page10'); }); }; $scope.tituloPagina =''; $scope.$on('$ionicView.leave', function(){ $scope.hasSenhas = true; }); $scope.$on('$ionicView.beforeEnter', function (event, viewData) { $scope.showLoading(); $scope.senhasAnteriores=[]; $scope.hasSenhas =true; user = firebase.auth().currentUser; if (user) { //console.log('aquilslfkdsl'); firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { $scope.datauser = snapshot.val(); if($scope.datauser.role==3){ $scope.tituloPagina = "<NAME>"; $scope.showLoading(); $scope.senhasAnteriores=[]; firebase.database().ref().child('senhas_usuarios').child(user.uid).limitToLast(50).once("value", function(snapshot3) { $scope.showLoading(); if(snapshot3.val() != null ) { $.each(snapshot3.val(), function (key, val) { //$scope.showLoading(); // //console.log(val); firebase.database().ref().child('users').child(val.loja_id).once("value", function(snapshot4) { if(snapshot4.val() != null ) { val.loja = snapshot4.val().nome; val.loja_email = snapshot4.val().email; val.loja_foto = snapshot4.val().foto; val.categoria = snapshot4.val().categoria; val.categoriaNome = snapshot4.val().categoriaNome; $scope.senhasAnteriores.unshift(val); //$scope.conectDiv=true; //console.log($scope.senhasAnteriores); } },function (error) { //$scope.hideLoading(); }); }); $timeout(function(){ $('#filtro').val(''); $('#filtro').trigger('change'); },1000); }else{ //$scope.hideLoading(); $scope.hasSenhas = false; } $timeout(function(){ $scope.hideLoading(); },2000); },function(error) { $timeout(function(){ $scope.hideLoading(); },2000); }); }else{ $scope.tituloPagina = "<NAME>"; } //console.log(snapshot.val()); },function(error) { $timeout(function(){ $scope.hideLoading(); },2000); }); $scope.items = []; firebase.database().ref().child('geo_filas').child(user.uid).once("value", function(snapshot) { if(snapshot.val() != null ){ $.each(snapshot.val(), function(index, value) { if(value.nome==1 && value.ativa !=false){ //console.log('aqui'); $scope.showComum= true; } if(value.nome==3 && value.ativa !=false){ $scope.showManual=true; } if(value.nome==2 && value.ativa !=false){ $scope.showPrioridade=true; } }); }else{ $scope.totalItens =$scope.items.length; } $timeout(function(){ $scope.hideLoading(); },2000); // },function(error) { $timeout(function(){ $scope.hideLoading(); },2000); }); $scope.guiches = ''; firebase.database().ref().child('guiches').child(user.uid).on("value", function(snapshot) { if(snapshot.val() != null ){ //console.log(snapshot.val()); $scope.guiches = snapshot.val(); } }); } //$scope.hideLoading(); },function(error) { $timeout(function(){ $scope.hideLoading(); },2000); }); $scope.loadMoreData=function() { if(typeof $scope.senhasAnterioresAux[0] != "undefined") { $scope.senhasAnteriores.push($scope.senhasAnterioresAux[0]); $scope.senhasAnterioresAux.shift(); $scope.$broadcast('scroll.infiniteScrollComplete'); }else{ $timeout(function() { $scope.$broadcast('scroll.infiniteScrollComplete'); $scope.moredata=true; },3000); } }; $scope.chamarProximo = function() { } $scope.changeGuiche = function(guiche) { $scope.guiche = guiche; } $scope.chamarPrioritario = function() { setDateTime(); user = firebase.auth().currentUser; $scope.showLoading(); $scope.countLine =0; //firebase.auth().onAuthStateChanged(function(user) { if (user){ $scope.countLine++; //console.log('contador da linha 1615 é :'+$scope.countLine); //console.log(user); firebase.database().ref().child('geo_filas_senhas').child(user.uid).orderByChild("tipo").equalTo(2).limitToFirst(1).once("value", function(snapshot) { if(snapshot.val() != null){ // $scope.items.push(snapshot.val()); var myKey; var array = $.map(snapshot.val(), function(value, index) { //myKey = index; return [value]; }); var myKey = $.map(snapshot.val(), function(value, index) { return index; }); //console.log(snapshot.key); for (var i = 0; i < array.length; i++) { obj = array[i]; firebase.database().ref().child('geo_filas_senhas').child(user.uid).child(myKey[0]).remove(); // //console.log($scope.guiche); var guiche = $scope.guiche || null; if (typeof obj.user_id != 'undefined' ) { sendNotificationTouUser(obj.user_id); firebase.database().ref().child('senhas_usuarios').child(obj.user_id).orderByChild("loja_id").equalTo(user.uid).limitToLast(100).once("value", function(snapshot4) { // //console.log(snapshot.val()); if(snapshot4.val() != null){ $.each(snapshot4.val(), function (key2, val2) { if(val2.numero == obj.numero) { val2.data_hora_chamada = getDate(userDateTimeFull); firebase.database().ref('senhas_usuarios').child(obj.user_id).child(key2).set( val2); } }); } }); } firebase.database().ref('geo_filas_senhas_usadas/' + user.uid).push({ 'numero': obj.numero, 'tipo': obj.tipo, 'data':obj.data, 'data_hora_chamada':getDate(userDateTimeFull), 'guiche': guiche, }, function(error) { if(error){ $scope.removeu =true; //console.log('aqui1'); $scope.texto={}; $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='Operaçao não efetuada.'; $scope.hideLoading(); $scope.showAlert($scope.texto); }else{ //console.log('aqui2'); $scope.texto={}; $scope.texto.titulo ='Tudo Certo'; $scope.texto.mensagem ='A senha foi '+obj.numero+' chamada.'; $scope.hideLoading(); $scope.showAlert($scope.texto); } }); // //console.log($scope.removeu); //console.log(obj.ativo); } //console.log(snapshot.key); }else { //console.log('aqui2'); $scope.texto={}; $scope.texto.titulo ='Aviso'; $scope.texto.mensagem ='Não existem senhas ativas nesta fila.'; $scope.hideLoading(); $scope.showAlert($scope.texto); } }); } //}); } $scope.chamarComum = function() { user = firebase.auth().currentUser; setDateTime(); $scope.showLoading(); $scope.countLine=0; //firebase.auth().onAuthStateChanged(function(user) { if (user){ $scope.countLine++; //console.log('contador da linha 1525 é :'+$scope.countLine); //console.log(user); firebase.database().ref().child('geo_filas_senhas').child(user.uid).orderByChild("tipo").equalTo(1).limitToFirst(1).once("value", function(snapshot) { // //console.log(snapshot.val()); if(snapshot.val() != null){ // $scope.items.push(snapshot.val()); var myKey; var array = $.map(snapshot.val(), function(value, index) { //myKey = index; return [value]; }); var myKey = $.map(snapshot.val(), function(value, index) { return index; }); //console.log(snapshot.key); for (var i = 0; i < array.length; i++) { obj = array[i]; firebase.database().ref().child('geo_filas_senhas').child(user.uid).child(myKey[0]).remove(); //console.log($scope.guiche); var guiche = $scope.guiche || null; //alert('passou1'); if (typeof obj.user_id != 'undefined' ) { //alert('passou2'); sendNotificationTouUser(obj.user_id); firebase.database().ref().child('senhas_usuarios').child(obj.user_id).orderByChild("loja_id").equalTo(user.uid).limitToLast(100).once("value", function(snapshot4) { // //console.log(snapshot.val()); if(snapshot4.val() != null){ $.each(snapshot4.val(), function (key2, val2) { if(val2.numero == obj.numero) { val2.data_hora_chamada = getDate(userDateTimeFull); firebase.database().ref('senhas_usuarios').child(obj.user_id).child(key2).set( val2); } }); } }); } firebase.database().ref('geo_filas_senhas_usadas/' + user.uid).push({ 'numero': obj.numero, 'tipo': obj.tipo, 'data':obj.data, 'data_hora_chamada':getDate(userDateTimeFull), 'guiche': guiche, }, function(error) { if(error){ $scope.removeu =true; //console.log('aqui1'); $scope.texto={}; $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='Operaçao não efetuada.'; $scope.hideLoading(); $scope.showAlert($scope.texto); }else{ //console.log('aqui2'); $scope.texto={}; $scope.texto.titulo ='Tudo Certo'; $scope.texto.mensagem ='A senha foi '+obj.numero+' chamada.'; $scope.hideLoading(); $scope.showAlert($scope.texto); } }); //console.log($scope.removeu); //console.log(obj.ativo); } //console.log(snapshot.key); }else { //console.log('aqui2'); $scope.texto={}; $scope.texto.titulo ='Aviso'; $scope.texto.mensagem ='Não existem senhas ativas nesta fila.'; $scope.hideLoading(); $scope.showAlert($scope.texto); } }); } //}); } }]) .controller('versenhasCtrl', ['$scope','$ionicPopup', '$stateParams', '$ionicHistory', '$location','$timeout','$ionicLoading','$ionicSideMenuDelegate', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope, $ionicPopup, $stateParams, $ionicHistory, $location,$timeout,$ionicLoading,$ionicSideMenuDelegate) { //alert(); userLoggedOn = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(userLoggedOn) { if(!userLoggedOn){ $location.path('/login') } }); $ionicSideMenuDelegate.canDragContent(false); $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', duration: 3000 }).then(function(){ // //console.log("The loading indicator is now displayed"); }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ // //console.log("The loading indicator is now hidden"); }); }; $scope.ionicGoBack = function() { $ionicHistory.goBack(); }; $scope.$on('$ionicView.beforeEnter', function (event, viewData) { viewData.enableBack = true; $scope.showLoading(); var user = firebase.auth().currentUser; if (user) { firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { $scope.datauser = snapshot.val(); //console.log(snapshot.val()); }); $scope.items = []; var array =[]; firebase.database().ref().child('geo_filas_senhas').child(user.uid).on("value", function(snapshot) { if(snapshot.val() != null){ $.each(snapshot.val(), function (key, val) { val.key = key; var array = $.map(val, function(value, index) { return [value]; }); $scope.items.push(array); }); }else{ $scope.totalItens =$scope.items.length; } }); $scope.guiches = ''; firebase.database().ref().child('guiches').child(user.uid).on("value", function(snapshot) { if(snapshot.val() != null ){ // //console.log(snapshot.val()); $scope.guiches = snapshot.val(); } }); } else { $location.path('/page5'); } $timeout(function(){ $scope.filtro=''; },1000); }); $scope.hideLoading(); $scope.showAlert = function(texto) { var alertPopup = $ionicPopup.alert({ title: texto.titulo, template: texto.mensagem }); alertPopup.then(function(res) { //console.log('Thank you for not eating my delicious ice cream cone'); //$location.path('/page1/page10'); }); }; //console.log(user); $scope.changeGuiche = function(guiche) { $scope.guiche = guiche; } $scope.mostrar=true; $scope.chamarSenhaId = function(senha,id,guiche) { setDateTime(); user = firebase.auth().currentUser; $scope.mostrar=false; $scope.showLoading(); $scope.countLine=0; //firebase.auth().onAuthStateChanged(function(user) { if (user){ $scope.countLine++; //console.log('contador da linha 1525 é :'+$scope.countLine); //console.log(user); if(id != senha[5]){ //console.log('aqyui2'); firebase.database().ref().child('geo_filas_senhas').child(user.uid).child(id).remove(); }else{ //console.log(senha); firebase.database().ref().child('geo_filas_senhas').child(user.uid).child(senha[5]).remove(); if(typeof senha[6] != 'undefined') { firebase.database().ref().child('geo_filas_senhas').child(user.uid).child(senha[6]).remove(); } } //firebase.database().ref().child('geo_filas_senhas').child(user.uid).child(myKey[0]).remove(); var guiche = $scope.guiche || null; if (typeof senha[5] != 'undefined' && typeof senha[6] != 'undefined') { sendNotificationTouUser(senha[5]); firebase.database().ref().child('senhas_usuarios').child(senha[5]).orderByChild("loja_id").equalTo(user.uid).limitToLast(100).once("value", function(snapshot4) { // //console.log(snapshot.val()); if(snapshot4.val() != null){ $.each(snapshot4.val(), function (key2, val2) { if(val2.numero == senha[2]) { val2.data_hora_chamada = getDate(userDateTimeFull); firebase.database().ref('senhas_usuarios').child(senha[5]).child(key2).set( val2); } }); } }); } firebase.database().ref('geo_filas_senhas_usadas/' + user.uid).push({ 'numero': senha[2], 'tipo': senha[4], 'data': senha[1], 'data_hora_chamada':getDate(userDateTimeFull), 'guiche': guiche, }, function(error) { if(error){ $scope.removeu =true; //console.log('aqui1'); $scope.texto={}; $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='Operaçao não efetuada.'; $scope.hideLoading(); $scope.showAlert($scope.texto); }else{ //console.log('aqui2'); var user = firebase.auth().currentUser; //console.log("show after directive partial loaded"); if (user) { $scope.items = []; // User is signed in. //var userId = firebase.auth().currentUser.uid; var array =[]; firebase.database().ref().child('geo_filas_senhas').child(user.uid).on("value", function(snapshot) { //firebase.database().ref().child('geo_filas').child(user.uid).once('value').then(function(snapshot) { if(snapshot.val() != null){ $.each(snapshot.val(), function (key, val) { val.key = key; var array = $.map(val, function(value, index) { return [value]; }); $scope.items.push(array); //console.log($scope.items); }); //$scope.items.push(snapshot.val()) ; //console.log(snapshot.val()); }else{ $scope.totalItens =$scope.items.length; } }); } else { //$location.path('/page5'); } // alert(); $timeout(function(){ $scope.filtro=''; $scope.mostrar=true; },1000); $scope.texto={}; $scope.texto.titulo ='Tudo Certo'; $scope.texto.mensagem ='A senha foi '+senha[2]+' chamada.'; $scope.hideLoading(); $scope.showAlert($scope.texto); } }); } //}); } }]) .controller('termosCtrl', ['$scope','$ionicPopup', '$stateParams', '$ionicHistory', '$location','$timeout','$ionicLoading','$ionicSideMenuDelegate', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope, $ionicPopup, $stateParams, $ionicHistory, $location,$timeout,$ionicLoading,$ionicSideMenuDelegate) { //alert(); $ionicSideMenuDelegate.canDragContent(false); }]) .controller('tabs1Controller', ['$scope','$ionicLoading', '$stateParams','$ionicPopup','$location','$ionicLoading','$timeout','$ionicSideMenuDelegate', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$ionicLoading, $stateParams,$ionicPopup,$location,$ionicLoading,$timeout,$ionicSideMenuDelegate) { $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', }).then(function(){ // //console.log("The loading indicator is now displayed"); }); }; $ionicSideMenuDelegate.canDragContent(false); $scope.limite =1; $scope.tituloPrimeiro=''; $scope.tituloSegundo=''; $scope.tituloTerceiro =''; $scope.tituloQuarto =''; $scope.tituloPrimeiroIco=''; $scope.tituloSegundoIco=''; $scope.tituloTerceiroIco =''; $scope.tituloQuartoIco =''; $scope.$on('$ionicView.enter', function(){ $ionicSideMenuDelegate.canDragContent(false); //$('.ion-navicon').hide(); $scope.showContent= false; $timeout(function () { $scope.showContent= true; }, 2500); }); $scope.$on('$ionicView.leave', function(){ $scope.showContent= false; $scope.conectDiv= true; $scope.hasStore=true; $scope.hasLojas=''; }); $scope.$on('$ionicView.beforeEnter', function (event, viewData) { //$scope.showLoading(); var onSuccessPos = function(position) { $scope.pos.lat = position.coords.latitude; $scope.pos.lon= position.coords.longitude; //console.log($scope.pos.lon); }; function onErrorPos(error) { $scope.posErro=error; calldialog(); } $scope.pos = {}; $scope.pos.lat = 0; $scope.pos.lon= 0; var onSuccessPos2 = function(position) { $scope.pos.lat = position.coords.latitude; $scope.pos.lon= position.coords.longitude; //console.log($scope.pos.lon); }; function onErrorPos2(error) { $scope.posErro=error; //calldialog(); } function tentarcadastrarnovamente(loja, usuario,uid) { navigator.geolocation.getCurrentPosition(onSuccessPos2, onErrorPos2, {maximumAge:60000, timeout:5000, enableHighAccuracy:true}); setTimeout(function() { if($scope.pos.lat != 'undefined' && $scope.pos.lat != '' && $scope.pos.lat != null){ geoFire.set(uid, [$scope.pos.lat, $scope.pos.lon]).then(function() { //console.log("Provided key has been added to GeoFire"); firebase.database().ref('geo_lojas/' + uid+'/dados').set({ endereco:'-', telefone:'-', nome:usuario.nome, email:usuario.email, foto:usuario.foto, raio:50, }, function(error) { }); }, function(error) { //console.log("Error: " + error); }); firebase.database().ref('geo_filas/' + uid ).remove(); firebase.database().ref('limit/' + uid).set({ limit:10000, }, function(error) { }); firebase.database().ref('geo_filas/' + uid ).push({ nome: 1, ativa:true, prioridade:false, prioridade_qtd:0, manual:false, numero_contador:0, prefixo:'CM-', }, function(error) { }); //Cadastra fila Prioritária firebase.database().ref('geo_filas/' + uid ).push({ nome: 2, ativa:true, prioridade:true, prioridade_qtd:2, manual:false, numero_contador:0, prefixo:'PR-', }, function(error) { }); //Cadastra fila Manual firebase.database().ref('geo_filas/' + uid ).push({ nome: 3, ativa:true, prioridade:false, prioridade_qtd:0, manual:true, numero_contador:0, prefixo:'MN-', }, function(error) { }); if(typeof snapshot.val().categoria != 'undefined'){ var firebaseRef2 = firebase.database().ref().child('geo_lojas_cat').child(snapshot.val().categoria); var geoFire2 = new GeoFire(firebaseRef2); var ref2 = geoFire.ref(); // ref === firebaseRef geoFire2.set(uid, [$scope.pos.lat, $scope.pos.lon]).then(function() { //console.log("Provided key has been added to GeoFire"); firebase.database().ref('geo_lojas_cat/'+snapshot.val().categoria+'/'+ uid+'/dados').set({ endereco:'-', telefone:'-', nome:usuario.nome, email:usuario.email, foto:usuario.foto, raio:50, }, function(error) { }); }); } }else{ tentarcadastrarnovamente(loja, usuario ,uid) } },1000); } navigator.geolocation.getCurrentPosition(onSuccessPos, onErrorPos, {maximumAge:60000, timeout:5000, enableHighAccuracy:true}); $scope.showContent= false; $timeout(function () { $scope.showContent= true; }, 2500); user = firebase.auth().currentUser; $scope.countLine=0; firebase.auth().onAuthStateChanged(function(user) { if (user){ $scope.countLine++; $timeout(function() { //console.log(user.uid); firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { $scope.datauser = snapshot.val(); //console.log(snapshot.val()); $scope.isAndroid = ionic.Platform.isAndroid(); $scope.isIos = ionic.Platform.isIOS(); //console.log($scope.isIos); if(snapshot.val() != null) { if(snapshot.val().role ==2){ $scope.tituloPrimeiro='<NAME>'; $scope.tituloSegundo ='<NAME>'; $scope.tituloTerceiro ='Minha Fila'; $scope.tituloQuarto ='Configurações'; if($scope.isAndroid == true){ $scope.tituloPrimeiroIco='ion-plus-circled'; $scope.tituloSegundoIco='ion-speakerphone'; $scope.tituloTerceiroIco ='ion-person-stalker'; $scope.tituloQuartoIco ='ion-gear-a'; }else if($scope.isIos == true){ $scope.tituloPrimeiroIco='ion-ios-plus'; $scope.tituloSegundoIco='ion-speakerphone'; $scope.tituloTerceiroIco ='ion-person-stalker'; $scope.tituloQuartoIco ='ion-ios-gear'; }else{ $scope.tituloPrimeiroIco='ion-plus-circled'; $scope.tituloSegundoIco='ion-speakerphone'; $scope.tituloTerceiroIco ='ion-person-stalker'; $scope.tituloQuartoIco ='ion-gear-a'; } $scope.usuario ={}; $scope.usuario.nome = snapshot.val().nome || null; $scope.usuario.email = snapshot.val().email || null; $scope.usuario.foto = snapshot.val().foto || null; firebase.database().ref().child('geo_lojas').child(user.uid).once("value", function(snapshotgeolojas) { if(snapshotgeolojas.val() == null) { var firebaseRef = firebase.database().ref().child('geo_lojas'); var geoFire = new GeoFire(firebaseRef); var ref = geoFire.ref(); // ref === firebaseRef if($scope.pos.lat != 'undefined' && $scope.pos.lat != '' && $scope.pos.lat != null){ geoFire.set(user.uid, [$scope.pos.lat, $scope.pos.lon]).then(function() { //console.log("Provided key has been added to GeoFire"); firebase.database().ref('geo_lojas/' + user.uid+'/dados').set({ endereco:'-', telefone:'-', nome:$scope.usuario.nome, email:$scope.usuario.email, foto:$scope.usuario.foto, raio:50, }, function(error) { }); }, function(error) { //console.log("Error: " + error); }); firebase.database().ref('geo_filas/' + user.uid ).remove(); firebase.database().ref('limit/' + user.uid).set({ limit:10000, }, function(error) { }); firebase.database().ref('geo_filas/' + user.uid ).push({ nome: 1, ativa:true, prioridade:false, prioridade_qtd:0, manual:false, numero_contador:0, prefixo:'CM-', }, function(error) { }); //Cadastra fila Prioritária firebase.database().ref('geo_filas/' + user.uid ).push({ nome: 2, ativa:true, prioridade:true, prioridade_qtd:2, manual:false, numero_contador:0, prefixo:'PR-', }, function(error) { }); //Cadastra fila Manual firebase.database().ref('geo_filas/' + user.uid ).push({ nome: 3, ativa:true, prioridade:false, prioridade_qtd:0, manual:true, numero_contador:0, prefixo:'MN-', }, function(error) { }); if(typeof snapshot.val().categoria != 'undefined'){ var firebaseRef2 = firebase.database().ref().child('geo_lojas_cat').child(snapshot.val().categoria); var geoFire2 = new GeoFire(firebaseRef2); var ref2 = geoFire.ref(); // ref === firebaseRef geoFire2.set(user.uid, [$scope.pos.lat, $scope.pos.lon]).then(function() { //console.log("Provided key has been added to GeoFire"); firebase.database().ref('geo_lojas_cat/'+snapshot.val().categoria+'/'+ user.uid+'/dados').set({ endereco:'-', telefone:'-', nome:$scope.usuario.nome, email:$scope.usuario.email, foto:$scope.usuario.foto, raio:50, }, function(error) { }); }); } }else{ tentarcadastrarnovamente(snapshotgeolojas, $scope.usuario,user.uid ) } } }); }else{ $scope.tituloPrimeiro='Pegar Senha'; $scope.tituloSegundo ='Minhas Filas'; $scope.tituloTerceiro ='Favoritos'; $scope.tituloQuarto ='Configurações'; if($scope.isAndroid == true){ $scope.tituloPrimeiroIco='ion-pricetags'; $scope.tituloSegundoIco='ion-person-stalker'; $scope.tituloTerceiroIco ='ion-heart'; $scope.tituloQuartoIco ='ion-gear-a'; }else if($scope.isIos == true){ $scope.tituloPrimeiroIco='ion-ios-pricetags'; $scope.tituloSegundoIco='ion-person-stalker'; $scope.tituloTerceiroIco ='ion-heart'; $scope.tituloQuartoIco ='ion-ios-gear'; }else{ $scope.tituloPrimeiroIco='ion-pricetags'; $scope.tituloSegundoIco='ion-person-stalker'; $scope.tituloTerceiroIco ='ion-heart'; $scope.tituloQuartoIco ='ion-gear-a'; } } } }); },2500); }else{ document.location.href = '#/page5'; } }); }); }]) angular.module('app.controllers', []) .controller('assineCtrl', ['$scope','$location','$ionicSideMenuDelegate', '$stateParams','$ionicLoading','$ionicPopup','$ionicHistory', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$location,$ionicSideMenuDelegate, $stateParams,$ionicLoading,$ionicPopup,$ionicHistory) { var connectedRef = firebase.database().ref(".info/connected"); $scope.tentativas = 0; //$scope.conectDiv=true; connectedRef.on("value", function(snap) { $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); if (snap.val() === true) { $scope.conectDiv=true; $timeout(function () { $('body').trigger('click'); // $scope.conectDiv=true; },1500); //$window.location.reload(); } else { $scope.conectDiv=false; $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); } }); $ionicSideMenuDelegate.canDragContent(false); $scope.$on('$ionicView.beforeEnter', function (event, viewData) { userLoggedOn = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(userLoggedOn) { if(!userLoggedOn){ $location.path('/login') } }); viewData.enableBack = true; $scope.countLine=0; //firebase.auth().onAuthStateChanged(function(user) { user = firebase.auth().currentUser; if (user){ $scope.countLine++; $scope.user = firebase.auth().currentUser; firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { $scope.datauser = snapshot.val(); //console.log(snapshot.val()); }); }else{ //$location.path('/page5') } //}); }); $scope.ionicGoBack = function() { $ionicHistory.goBack(); }; $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', duration: 1000 }).then(function(){ //console.log("The loading indicator is now displayed"); }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); }; user = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(user) { $scope.user = firebase.auth().currentUser; }); $scope.showAlert = function(texto) { var alertPopup = $ionicPopup.alert({ title: texto.titulo, template: texto.mensagem }); alertPopup.then(function(res) { }); }; $scope.assinar = function() { $scope.showLoading(); $.getJSON( "http://hudo.000webhostapp.com/entregapp/RestPedidos/pagseguromobile?ref="+$scope.user.uid+"", function( data ){ $scope.hideLoading(); if(data[0] !='Existe' && data[0] !='E' ) { // //console.log(data[0]); window.open('https://sandbox.pagseguro.uol.com.br/v2/pre-approvals/request.html?code='+data[0],'_system'); $scope.hideLoading(); }else{ // //console.log(data[0]); $scope.texto ={}; $scope.texto.titulo ='Falha'; $scope.texto.mensagem ='Esta conta já possui uma assinatura Premium.'; $scope.showAlert($scope.texto); } }); /**/ } }]) .controller('acompanharFilasCtrl', ['$scope','$timeout', '$ionicSideMenuDelegate','$stateParams','$location','$ionicLoading','$ionicPopup',// The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$timeout,$ionicSideMenuDelegate, $stateParams,$location,$ionicLoading,$ionicPopup) { var connectedRef = firebase.database().ref(".info/connected"); $scope.tentativas = 0; //$scope.conectDiv=true; connectedRef.on("value", function(snap) { $scope.conectDiv=true; $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); if (snap.val() === true) { $scope.conectDiv=true; $timeout(function () { $('body').trigger('click'); // $scope.conectDiv=true; },1500); //$window.location.reload(); } else { $scope.conectDiv=false; $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); } }); $ionicSideMenuDelegate.canDragContent(false); userLoggedOn = firebase.auth().currentUser; $scope.userLoggedOn = userLoggedOn; firebase.auth().onAuthStateChanged(function(userLoggedOn) { if(!userLoggedOn){ $location.path('/login') } }); $scope.$on('$ionicView.leave', function(){ //$ionicSideMenuDelegate.canDragContent(true); //$('.ion-navicon').show(); $scope.showContent=false; }); $scope.$on('$ionicView.beforeEnter', function (event, viewData) { userLoggedOn = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(userLoggedOn) { if(!userLoggedOn){ $location.path('/login') } }); //viewData.enableBack = true; $scope.showLoading(); firebase.auth().onAuthStateChanged(function(user) { user = firebase.auth().currentUser; $scope.user = firebase.auth().currentUser; firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { $scope.datauser = snapshot.val(); //$scope.hideLoading(); if(snapshot.val() != null){ if(typeof $scope.datauser.categoria != 'undefined'){ firebase.database().ref().child('categorias').child($scope.datauser.categoria).once("value", function(snapshot2) { $scope.datauser.categoriaNome = snapshot2.val(); //console.log($scope.datauser.categoriaNome); },function(error) { $timeout(function(){ $scope.hideLoading(); },2000); }); } } $timeout(function(){ $scope.showContent=true; $scope.hideLoading(); },2000); //console.log(snapshot.val()); },function(error) { $timeout(function(){ $scope.showContent=true; $scope.hideLoading(); },2000); }); }); }); $scope.logout = function (){ firebase.auth().signOut().then(function() { // Sign-out successful. $scope.user = null; //$location.path('/login'); navigator.app.exitApp(); }, function(error) { // An error happened. }); } user = firebase.auth().currentUser; $scope.user = user; firebase.auth().onAuthStateChanged(function(user) { $scope.user = firebase.auth().currentUser; }); $scope.uploadProgres =0; $scope.showProgress=false; $scope.showProgress=false; $scope.getImage = function (source) { //alert('passou1'); // Retrieve image file location from specified source $('#configForm').submit(function(event) { event.preventDefault(); }); $scope.showImage=false; var options = { maximumImagesCount: 1, quality: 50 }; $scope.showLoading(); window.imagePicker.getPictures( function(results) { //alert('passou2'); for (var i = 0; i < results.length; i++) { //getFileEntry(results[i]); var imageData = results[i]; var filename = imageData.split("/").pop(); var storageRef = firebase.storage().ref(); var getFileBlob = function(url, cb) { var xhr = new XMLHttpRequest(); xhr.open("GET", url); xhr.responseType = "blob"; xhr.addEventListener('load', function() { cb(xhr.response); }); xhr.send(); }; var blobToFile = function(blob, name) { blob.lastModifiedDate = new Date(); blob.name = name; return blob; }; var getFileObject = function(filePathOrUrl, cb) { getFileBlob(filePathOrUrl, function(blob) { cb(blobToFile(blob, 'test.jpg')); }); }; getFileObject(imageData, function(fileObject) { var uploadTask = storageRef.child('images/'+user.uid+'.jpg').put(fileObject); uploadTask.on('state_changed', function(snapshot) { //alert(snapshot); }, function(error) { //alert(error); }, function() { var downloadURL = uploadTask.snapshot.downloadURL; $scope.datauser.foto = downloadURL; firebase.database().ref('users/' + user.uid).set($scope.datauser, function(error) { $scope.texto ={}; $scope.hideLoading(); if(error){ $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='Não conseguimos salvar a configuração.'; $scope.showAlert($scope.texto); }else{ $scope.texto.titulo ='Tudo Certo!'; $scope.texto.mensagem ='Sua configuração foi salva!'; $scope.showAlert($scope.texto); } }); //alert(downloadURL); // handle image here }); }); $timeout(function(){ $scope.hideLoading(); },2000); } }, function (error) { $scope.showImage=false; $timeout(function(){ $scope.hideLoading(); },2000); alert('Error: ' + error); }, options ); $timeout(function(){ $scope.hideLoading(); },2000); } $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', duration: 10000, }).then(function(){ //console.log("The loading indicator is now displayed"); }); }; // Triggered on a button click, or some other target $scope.showPopup = function() { // An elaborate, custom popup var myPopup = $ionicPopup.show({ title: 'Cancelar Conta', subTitle: 'Deseja Canelar a conta Premium?', scope: $scope, buttons: [ { text: '<b>Sim</b>', type: 'button-assertive', onTap: function(e) { $scope.confirmarcancelamento(); } }, { text: 'Não' } ] }); } $scope.showAlert = function(texto) { var alertPopup = $ionicPopup.alert({ title: texto.titulo, template: texto.mensagem }); alertPopup.then(function(res) { }); }; $scope.confirmarcancelamento = function() { $scope.showLoading(); $.getJSON( "http://hudo.000webhostapp.com/entregapp/RestPedidos/cancelarpagseguro?ref="+$scope.user.uid+"", function( data ){ $scope.hideLoading(); if(data[0] !='Not Found' && data[0] !='N' ) { //console.log(data[0]); }else{ // //console.log(data[0]); $scope.texto ={}; $scope.texto.titulo ='Falha'; $scope.texto.mensagem ='Não foi possível cancelar a assinatura, por favor entre em contato com <EMAIL>'; $scope.showAlert($scope.texto); } }); } $scope.setRaio = function(usercad) { $scope.showLoading(); $scope.datauser.raio = usercad.raio || null; $scope.datauser.nome = usercad.nome || null; //user = firebase.auth().currentUser; //firebase.auth().onAuthStateChanged(function(user) { //$scope.user = firebase.auth().currentUser; firebase.database().ref('users/' + user.uid).set($scope.datauser, function(error) { $scope.texto ={}; $scope.hideLoading(); if(error){ $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='Não conseguimos salvar a configuração.'; $scope.showAlert($scope.texto); }else{ $scope.texto.titulo ='Tudo Certo!'; $scope.texto.mensagem ='Sua configuração foi salva!'; $scope.showAlert($scope.texto); } }); //}); } $scope.cancelar = function() { $scope.showPopup(); /**/ } $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); }; //$scope.showLoading(); //$scope.hideLoading(); }]) .controller('guichesCtrl', ['$scope','$timeout','$ionicSideMenuDelegate', '$stateParams','$location','$ionicLoading','$ionicHistory','$ionicPopup',// The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$timeout, $ionicSideMenuDelegate,$stateParams,$location,$ionicLoading,$ionicHistory,$ionicPopup) { var connectedRef = firebase.database().ref(".info/connected"); $scope.tentativas = 0; //$scope.conectDiv=true; connectedRef.on("value", function(snap) { $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); if (snap.val() === true) { $scope.conectDiv=true; $timeout(function () { $('body').trigger('click'); // $scope.conectDiv=true; },1500); //$window.location.reload(); } else { $scope.conectDiv=false; $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); } }); $ionicSideMenuDelegate.canDragContent(false); userLoggedOn = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(userLoggedOn) { if(!userLoggedOn){ $location.path('/login') } }); $scope.remover = function(key) { $scope.showLoading(); user = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(user) { firebase.database().ref().child('guiches').child(user.uid).child(key).remove(); //console.log(key); $scope.hideLoading(); }); } $scope.cadastrar = function(guiche) { //console.log(guiche); $scope.showLoading(); if(guiche != '' && typeof guiche != 'undefined') { user = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(user) { firebase.database().ref().child('guiches').child(user.uid).orderByChild("guiche").startAt(guiche).endAt(guiche).limitToFirst(1).once("value", function(snapshot) { if(snapshot.val() != null){ $scope.hideLoading(); $scope.texto ={}; $scope.texto.titulo ='Aviso'; $scope.texto.mensagem ='Este guichê já existe.'; $scope.showAlert($scope.texto); }else{ firebase.database().ref('guiches/' + user.uid ).push({ guiche: guiche, }, function(error) { if(!error) { $scope.texto ={}; $scope.texto.titulo ='Tudo Certo'; $scope.texto.mensagem ='A operação foi efetuada.'; $scope.hideLoading(); $scope.showAlert($scope.texto); $('[name="guiche"]').val(''); } }); } }); }); }else{ $scope.hideLoading(); $scope.texto ={}; $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='O guichê não pode estar vazio.'; $scope.showAlert($scope.texto); } } $scope.showAlert = function(texto) { var alertPopup = $ionicPopup.alert({ title: texto.titulo, template: texto.mensagem }); alertPopup.then(function(res) { }); }; $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', duration: 1000 }).then(function(){ //console.log("The loading indicator is now displayed"); }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); }; $scope.ionicGoBack = function() { $ionicHistory.goBack(); }; $scope.$on('$ionicView.beforeEnter', function (event, viewData) { viewData.enableBack = true; $scope.items =[]; user = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(user) { firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { $scope.datauser = snapshot.val(); //console.log(snapshot.val()); }); firebase.database().ref().child('guiches').child(user.uid).on("value", function(snapshot) { if(snapshot.val() != null){ $scope.items = snapshot.val(); // //console.log($scope.items); }else{ $scope.totalItens =$scope.items.length; } $scope.hideLoading(); }); }) }); $scope.showLoading(); //$scope.hideLoading(); }]) .controller('gerarSenhasClienteCtrl', ['$scope','$timeout','$ionicSideMenuDelegate', '$ionicPopup', '$stateParams', '$ionicHistory', '$location','$ionicLoading', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$timeout, $ionicSideMenuDelegate,$ionicPopup, $stateParams,$ionicHistory, $location, $ionicLoading) { var connectedRef = firebase.database().ref(".info/connected"); $scope.tentativas = 0; //$scope.conectDiv=true; connectedRef.on("value", function(snap) { $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); if (snap.val() === true) { $scope.conectDiv=true; $timeout(function () { $('body').trigger('click'); // $scope.conectDiv=true; },1500); //$window.location.reload(); } else { $scope.conectDiv=false; //console.log('off'); $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); } }); $ionicSideMenuDelegate.canDragContent(false); userLoggedOn = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(userLoggedOn) { if(!userLoggedOn){ $location.path('/login') } }); $scope.retornaNome = function(num) { switch (num) { case 1: return 'Comum'; break; case 2: return 'Prioritária'; break; case 3: return 'Manual'; break; default: } } $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...' }).then(function(){ //console.log("The loading indicator is now displayed"); }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); }; $scope.ionicGoBack = function() { $ionicHistory.goBack(); }; $scope.contadorSenhaCanc= 0; $scope.contaSenhasCanceladas = function() { setDateTime(); user = firebase.auth().currentUser; $scope.countLine=0; //firebase.auth().onAuthStateChanged(function(user) { if (user){ $scope.countLine++; var hoje =getDateSmall(userDateTimeFull); $scope.contadorSenhaCanc=0; firebase.database().ref().child('senhas_canceladas_usuarios').child(user.uid).orderByChild('data').equalTo(hoje).once("value", function(snapshot3){ //console.log(snapshot3.val()); if(snapshot3.val() != null){ $.each(snapshot3.val(), function(key3,val3) { $scope.contadorSenhaCanc ++; }); //console.log($scope.contadorSenhaCanc); return $scope.contadorSenhaCanc; } }); } //}); } $scope.cancelarsenha = function() { setDateTime(); $scope.showLoading(); $scope.texto ={} user = firebase.auth().currentUser; $scope.countLine=0; // firebase.auth().onAuthStateChanged(function(user) { if (user){ $scope.countLine++; var contCandeladas = $scope.contaSenhasCanceladas(); firebase.database().ref().child('geo_filas_senhas').child($stateParams.id).orderByChild('user_id').equalTo(user.uid).once("value", function(snapshot){ if(snapshot.val() != null){ $.each(snapshot.val(), function(key,val) { //console.log(val); firebase.database().ref().child('senhas_usuarios').child(user.uid).orderByChild('numero').equalTo(val.numero).once("value", function(snapshot2){ //console.log(snapshot2.val()); if(snapshot2.val() != null) { $.each(snapshot2.val(), function(key2,val2) { var hoje =getDateSmall(userDateTimeFull); firebase.database().ref('senhas_canceladas_usuarios/' + user.uid).push({ loja_id:$stateParams.id,data:hoje }, function(error) { }); if($scope.contadorSenhaCanc < 3) { firebase.database().ref().child('senhas_usuarios').child(user.uid).child(key2).remove(); firebase.database().ref().child('geo_filas_senhas').child($stateParams.id).child(key).remove(); $scope.texto.titulo ='Boa!'; $scope.texto.mensagem ='Sua senha foi cancelada.'; $scope.hideLoading(); $scope.showAlert($scope.texto); }else{ $scope.texto.titulo ='Ops, algo deu errado!'; $scope.texto.mensagem ='Você já não pode mais cancelar senhas por hoje.'; $scope.hideLoading(); $scope.showAlert($scope.texto); } }); } $scope.hideLoading(); }); }); $scope.hideLoading(); }else{ $scope.texto.titulo ='Opa!'; $scope.texto.mensagem ='Você não tem senhas nesta fila.'; $scope.showAlert($scope.texto); } $scope.hideLoading(); }); }else{ $scope.hideLoading(); } //}); }; var user = firebase.auth().currentUser; $scope.numFilasInativas=0; $scope.$on('$ionicView.beforeEnter', function (event, viewData) { viewData.enableBack = true; $scope.numFilasInativas=0; $scope.lojaFila= []; $scope.showLoading(); firebase.database().ref().child('geo_filas').child($stateParams.id).once("value", function(snapshot) { $scope.items = []; if(snapshot.val() != null ){ $scope.items.push(snapshot.val()); $scope.numFilasInativas = 0; $.each(snapshot.val(), function (key, val) { //console.log(val); if(val.manual == false && val.ativa == false) { $scope.numFilasInativas++; } }); //console.log($scope.numFilasInativas); }else{ $scope.totalItens =$scope.items.length; } $scope.hideLoading(); firebase.database().ref().child('users').child($stateParams.id).once("value", function(snapshot2) { if(snapshot2.val() != null ){ //console.log(snapshot2.val()); $scope.lojaFila = snapshot2.val(); $scope.limite = snapshot2.val().limit; } }); }); }); $scope.showAlert = function(texto) { var alertPopup = $ionicPopup.alert({ title: texto.titulo, template: texto.mensagem }); alertPopup.then(function(res) { }); }; $scope.contador=''; $scope.contaNumero = function(id){ setDateTime(); user = firebase.auth().currentUser; $scope.contadorAuxSenha = 0; $scope.countLine=0; //firebase.auth().onAuthStateChanged(function(user) { if (user){ $scope.countLine++; if($scope.contadorAuxSenha==0) { firebase.database().ref().child('geo_filas').child($stateParams.id).child(id).once("value", function(snapshot) { fila =snapshot.val(); $scope.contador = parseInt(fila.numero_contador) + 1; // //console.log($scope.contador); user = firebase.auth().currentUser; var mykey = firebase.database().ref('geo_filas_senhas/' + $stateParams.id).push(); var prefixo = fila.prefixo || ''; var contador = $scope.contador || 1; var posFixoRestaurante = ''; if(typeof $scope.lojaFila.categoria != 'undefined'){ if($scope.lojaFila.categoria== 1){ posFixoRestaurante =''; posFixoRestaurante= $('#qtdPessoas').val(); if(typeof posFixoRestaurante != 'undefined' && posFixoRestaurante != '? undefined:undefined ?'){ posFixoRestaurante = ' P-'+ posFixoRestaurante; }else { posFixoRestaurante = ' P-'+ 1; } } } var nome = fila.nome || 'S/N'; var user_id = $('#user_id').val() || null; firebase.database().ref('geo_filas_senhas/' + $stateParams.id).push({ pos:contador, numero:prefixo + $scope.contador + posFixoRestaurante, ativo:'true', tipo:nome,data:getDate(userDateTimeFull),user_id:user.uid, }, function(error) { $scope.texto={}; if(error){ $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='Operaçao não efetuada.'; $scope.hideLoading(); $scope.showAlert($scope.texto); }else { $scope.texto.titulo ='Tudo Certo'; $scope.texto.mensagem ='Sua senha '+ prefixo + contador + posFixoRestaurante; firebase.database().ref('geo_filas').child($stateParams.id).child(id).child('/numero_contador').set( $scope.contador); if(user.uid != '') { firebase.database().ref('senhas_usuarios/' + user.uid).push({ pos:contador, numero:prefixo + $scope.contador + posFixoRestaurante, ativo:'true', tipo:nome,data:getDate(userDateTimeFull),loja_id:$stateParams.id, }, function(error) { }); } // $('#qtdPessoas').val(''); $scope.hideLoading(); $scope.showAlert($scope.texto); } }); }); } } //}); } $scope.contaSenha = function() { setDateTime(); var dateObj = new Date(); var month = dateObj.getUTCMonth() + 1; //months from 1-12 var day = dateObj.getUTCDate(); var year = dateObj.getUTCFullYear(); var ref = firebase.database().ref("senhas_gratis/"+$stateParams.id+'/'+ year +'/'+ month); ref.once("value").then(function(snapshot) { var a = snapshot.numChildren(); // 1 ("name") $scope.contadorSenha = snapshot.child(day).numChildren(); // 2 ("first", "last") }); } $scope.contadorSenha = $scope.contaSenha(); $scope.setlogsenha = function() { setDateTime(); var dateObj = new Date(); var month = dateObj.getUTCMonth() + 1; //months from 1-12 var day = dateObj.getUTCDate(); var year = dateObj.getUTCFullYear(); user = firebase.auth().currentUser; firebase.database().ref('senhas_gratis/' + user.uid +'/' + year +'/'+ month+'/'+ day ).push({qtd:1}); } //$scope.setlogsenha(); $scope.gerarSenha = function(value, id) { $scope.showLoading(); user = firebase.auth().currentUser; $scope.countLine=0; //firebase.auth().onAuthStateChanged(function(user) { if (user){ $scope.countLine++; firebase.database().ref().child('geo_filas_senhas').child($stateParams.id).orderByChild('user_id').equalTo(user.uid).once("value", function(snapshot){ $scope.texto= {}; if(snapshot.val() == null) { user = firebase.auth().currentUser; $scope.contaSenha(); if( $scope.contadorSenha >= $scope.limite) { $scope.texto.titulo ='Ops! Que embaraçoso.'; $scope.texto.mensagem ='Acabaram as senhas disponíveis deste estabelecimento por hoje. Tente pegar uma senha outro dia.'; $scope.hideLoading(); $scope.showAlert($scope.texto); }else{ userNotf = user.displayName; userNotf = userNotf || user.email; userNotf = userNotf || null; if(userNotf != '' && userNotf !=null){ sendNotificationTouUserNewNumberEstab($stateParams.id,userNotf); } $scope.setlogsenha(); $scope.contaNumero(id); } }else{ $scope.texto.titulo ='Ops! Que embaraçoso.'; $scope.texto.mensagem ='Você já tem uma senha ativa neste estabelecimento, e não pode pegar outra senha neste momento. Cancele sua senha ou aguarde a sua senha ser chamada.'; $scope.hideLoading(); $scope.showAlert($scope.texto); } }); } //}); } $scope.pos={}; $scope.pos.lat=0; $scope.pos.lon=0; $scope.post={}; $scope.imageUrl=''; var onSuccessPos = function(position) { $scope.pos.lat = position.coords.latitude; $scope.pos.lon= position.coords.longitude; //console.log($scope.pos.lon); }; // onError Callback receives a PositionError object function onErrorPos(error) { $scope.posErro=error; calldialog(); } navigator.geolocation.getCurrentPosition(onSuccessPos, onErrorPos, {maximumAge:60000, timeout:5000, enableHighAccuracy:true}); //$scope.fila.user_id =''; $scope.fila = []; if (user) { // User is signed in. //alert('1'); //console.log(user); $scope.fila.user_id = user.uid; } else { $location.path('/page5') } var firebaseRef = firebase.database().ref().child('geo_filas'); var geoFire = new GeoFire(firebaseRef); var ref = geoFire.ref(); // ref === firebaseRef //var mykey = ref.child('dados').push(); //console.log(user.uid); var user = firebase.auth().currentUser //$scope.showConfirm(); // An alert dialog $scope.cadastrarFila = function(fila) { var user = firebase.auth().currentUser var nome = fila.nome || null; var ativa = fila.ativa || false; var prioridade = fila.prioridade || false; var prioridade_qtd = fila.qtd_prioridade || 0; var manual = fila.manual || false; var numero_contador = fila.numero_contador || 0; var prefixo = fila.prefixo || ''; $scope.texto= {}; //console.log(nome); if(nome == null || nome == 'undefined' ) { $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='O nome não poder estar vazio.'; $scope.showAlert($scope.texto); }else{ firebase.database().ref('geo_filas/' + user.uid + '/' + $stateParams.id).set({ nome: nome, ativa:ativa, prioridade:prioridade, prioridade_qtd:prioridade_qtd, manual:manual, numero_contador:numero_contador, prefixo:prefixo, }, function(error) { if(error){ $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='Não conseguimos realizar a operação.'; $scope.showAlert($scope.texto); }else { $scope.texto.titulo ='Tudo certo!'; $scope.texto.mensagem ='A operação foi efetuada.'; $scope.showAlert($scope.texto); } }); } } }]) .controller('painelLojaCtrl', ['$scope','$timeout', '$ionicSideMenuDelegate','$stateParams','$location','$ionicLoading','$timeout', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$timeout, $ionicSideMenuDelegate,$stateParams,$location,$ionicLoading,$timeout) { var connectedRef = firebase.database().ref(".info/connected"); $scope.tentativas = 0; //$scope.conectDiv=true; connectedRef.on("value", function(snap) { $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); if (snap.val() === true) { $scope.conectDiv=true; $timeout(function () { $('body').trigger('click'); // $scope.conectDiv=true; },1500); //$window.location.reload(); } else { $scope.conectDiv=false; $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); } }); $ionicSideMenuDelegate.canDragContent(false); userLoggedOn = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(userLoggedOn) { if(!userLoggedOn){ $location.path('/login') } }); $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', }).then(function(){ //console.log("The loading indicator is now displayed"); }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); }; $scope.verFila = function(id) { $location.path('/painelloja/'+id); } $scope.ionicGoBack = function() { $ionicHistory.goBack(); }; $scope.$on('$ionicView.beforeEnter', function (event, viewData) { viewData.enableBack = true; $scope.showLoading(); $scope.countLine=0; //firebase.auth().onAuthStateChanged(function(user) { user = firebase.auth().currentUser; if (user){ $scope.countLine++; $timeout(function() { firebase.database().ref().child('users').child($stateParams.id).once("value", function(snapshot) { $scope.datauser = snapshot.val(); //console.log($scope.datauser); if($scope.datauser.role == 2) { firebase.database().ref().child('geo_filas_senhas_usadas').child($stateParams.id).limitToLast(1).on("child_added", function(snapshot) { if(snapshot.val() != null ){ $scope.senha=snapshot.val(); $scope.hideLoading(); } }); $scope.senhasAnterioresAux=[] var ref = firebase.database().ref().child('geo_filas_senhas_usadas').child($stateParams.id); $scope.senhasAnteriores=[]; ref.orderByKey().limitToLast(10).on("child_added", function(snapshot) { if(snapshot.val() != null ){ //if($scope.senhasAnteriores.length < 5){ $scope.senhasAnteriores.unshift(snapshot.val()); // }else{ //$scope.senhasAnterioresAux.unshift(snapshot.val()); //} //countRef++; } }); } $scope.minhasenha=''; firebase.database().ref().child('geo_filas_senhas').child($stateParams.id).orderByChild('user_id').equalTo(user.uid).once("value", function(snapshot){ if(snapshot.val() != null) { $.each(snapshot.val(), function (key, val) { $scope.minhasenha = val; }); //$scope.minhasenha=snapshot.val(); //console.log($scope.minhasenha); } }); }); $timeout(function () { $('#filtro').val(' '); $scope.hideLoading(); }, 3000); },2500); } else { $scope.hideLoading(); $location.path('/page5') } //}); }); $scope.moredata = false; $scope.loadMoreData=function() { if(typeof $scope.senhasAnterioresAux[0] != "undefined") { $scope.senhasAnteriores.push($scope.senhasAnterioresAux[0]); $scope.senhasAnterioresAux.shift(); $scope.$broadcast('scroll.infiniteScrollComplete'); }else{ $timeout(function() { $scope.$broadcast('scroll.infiniteScrollComplete'); $scope.moredata=true; },3000); } }; $scope.mostrar = function() { $('.nav-bar-container').fadeIn(1000); $('.tabs').fadeIn(1000); } $scope.esconder = function() { $('.nav-bar-container').fadeOut(1000); $('.tabs').fadeOut(1000); } //alert(); }]) .controller('gerarsenhascategoriasCtrl', ['$scope','$window','$ionicSideMenuDelegate','$timeout' ,'$stateParams','$location','$ionicLoading','$ionicHistory',// The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$window,$ionicSideMenuDelegate ,$timeout,$stateParams,$location,$ionicLoading,$ionicHistory) { var connectedRef = firebase.database().ref(".info/connected"); $scope.tentativas = 0; //$scope.conectDiv=true; connectedRef.on("value", function(snap) { $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); if (snap.val() === true) { $scope.conectDiv=true; $timeout(function () { $('body').trigger('click'); // $scope.conectDiv=true; },1500); //$window.location.reload(); } else { $scope.conectDiv=false; $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); } }); $ionicSideMenuDelegate.canDragContent(false); $scope.$on('$ionicView.beforeEnter', function (event, viewData) { //calldialog(); $scope.showLoading(); //alert('passou1'); navigator.geolocation.getCurrentPosition(onSuccessPos, onErrorPos, {maximumAge:60000, timeout:5000, enableHighAccuracy:true}); //navigator.geolocation.getCurrentPosition(onSuccessPos, onErrorPos); viewData.enableBack = true; // }); $scope.ionicGoBack = function() { $ionicHistory.goBack(); }; $scope.$on('$ionicView.leave', function(){ $scope.pos={}; $scope.pos.lat=0; $scope.pos.lon=0; $scope.noStores=false; }); var geoQuery; $scope.pos={}; $scope.pos.lat=0; $scope.pos.lon=0; $scope.noStores=false; if($stateParams.id == 't') { var firebaseRef = firebase.database().ref().child('geo_lojas'); }else{ var firebaseRef = firebase.database().ref().child('geo_lojas_cat').child($stateParams.id); } var geoFire = new GeoFire(firebaseRef); var ref = geoFire.ref(); firebase.auth().onAuthStateChanged(function(user) { if (user) { $scope.user = user; } }); function onSuccessPos(position) { $scope.pos.lat = position.coords.latitude; $scope.pos.lon= position.coords.longitude; //alert('passou2'); //-22.5108 //-43.1844 //console.log(); user = firebase.auth().currentUser; //console.log(user); //console.log($scope.lojaId); $scope.countLine=0; //firebase.auth().onAuthStateChanged(function(user) { if (user){ $scope.countLine++; $scope.user = user; $scope.lojas=[]; firebase.database().ref().child('users').child(user.uid).once("value", function(snapshotuser) { $scope.datauser = snapshotuser.val(); var raio = snapshotuser.val().raio || 50; raio = parseInt(raio); geoQuery = geoFire.query({ center: [$scope.pos.lat, $scope.pos.lon], radius: raio }); $scope.hasStore = false; var onKeyEnteredRegistration = geoQuery.on("key_entered", function(key, location) { //console.log(location); $scope.hasStore = true; $scope.noStores=false; $scope.temloja='tem'; $scope.showLoading(); if($stateParams.id == 't') { firebase.database().ref().child('users').child(key).once("value", function(snapshot) { $scope.segue='N'; //console.log(snapshot.val()); $timeout(function() { $('#filtro').val(''); $('#filtro').trigger('change'); //$('#filtro').focus(); $scope.hideLoading(); },3500); firebase.database().ref().child('lojas_seguidores').child(key).orderByValue().equalTo($scope.user.uid).once("value", function(snapshot2) { if(snapshot2.val() != null){ //console.log(snapshot2.val()); $scope.segue='S'; //$scope.hasStore =true; //$scope.noStores=false; }else{ //$scope.hasStore = false; //$scope.noStores=true; } //console.log(snapshot.val()); //console.log('aqui'); dadosLojas = { 'email':snapshot.val().email, //'endereco':snapshot.val().endereco, 'foto':snapshot.val().foto, 'nome':snapshot.val().nome, 'categoriaNome':returnCategoria(snapshot.val().categoria), 'categoria':snapshot.val().categoria, 'rudovip':snapshot.val().rudovip, 'desconto':snapshot.val().desconto, 'porcentagem':snapshot.val().porcentagem, 'condicoes':snapshot.val().condicoes, 'endereco':snapshot.val().endereco, 'bairro':snapshot.val().bairro, 'cidade':snapshot.val().cidade, 'uf':snapshot.val().uf, 'telefone1':snapshot.val().telefone1, 'telefone2':snapshot.val().telefone2, 'id':key, 'segue':$scope.segue, raio:50, } if($scope.lojas.length < 5) { $scope.lojas.unshift(dadosLojas); }else { $scope.lojas.unshift(dadosLojas); } $scope.hideLoading(); //console.log(snapshot.key); }); $scope.hideLoading(); //$scope.lojas.push(dadosLojas); //console.log($scope.lojas); }); }else { firebase.database().ref().child('geo_lojas_cat').child($stateParams.id).child(key).child('dados').once("value", function(snapshot) { $scope.segue='N'; $timeout(function() { $('#filtro').val(''); $('#filtro').trigger('change'); $scope.hideLoading(); //$('#filtro').focus(); },3000); firebase.database().ref().child('lojas_seguidores').child(key).orderByValue().equalTo($scope.user.uid).once("value", function(snapshot2) { if(snapshot2.val() != null){ //console.log(snapshot2.val()); $scope.segue='S'; }else{ $scope.noStores=true; } firebase.database().ref().child('users').child(key).once("value", function(snapshot3) { if(snapshot3.val() != null){ //console.log(snapshot3.val()); //console.log(returnCategoria($stateParams.id)); //console.log($stateParams.id); dadosLojas = { 'email':snapshot.val().email, 'endereco':snapshot.val().endereco, 'foto':snapshot3.val().foto, 'nome':snapshot.val().nome, 'categoriaNome':returnCategoria($stateParams.id), 'telefone':snapshot.val().telefone, 'id':key, 'segue':$scope.segue, raio:50, } $scope.lojas.unshift(dadosLojas); $scope.hideLoading(); } }); //console.log(snapshot.key); }); $scope.hideLoading(); //$scope.lojas.push(dadosLojas); //console.log($scope.lojas); }); } }); }); $scope.hideLoading(); // //console.log(onKeyEnteredRegistration); }else{ $scope.hideLoading(); } //}); }; // onError Callback receives a PositionError object function onErrorPos(error) { $scope.hideLoading(); calldialog(); $scope.posErro=error; //alert(error); } //$scope.moredata = false; /*$scope.loadMoreData=function() { if(typeof $scope.lojas[0] != "undefined") { $scope.lojas.push($scope.lojas[0]); $scope.lojas.shift(); $scope.$broadcast('scroll.infiniteScrollComplete'); }else{ $timeout(function() { $scope.$broadcast('scroll.infiniteScrollComplete'); $scope.moredata=true; },3000); } };*/ $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', }).then(function(){ //console.log("The loading indicator is now displayed"); }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); }; $scope.verFila=function(id) { } $scope.seguirEstabelecimento=function(id) { $scope.showLoading(); $scope.lojaId = id; user = firebase.auth().currentUser; //console.log($scope.lojaId); $scope.countLine=0; //firebase.auth().onAuthStateChanged(function(user) { if (user){ $scope.countLine++; //console.log(); firebase.database().ref().child('lojas_seguidores').child($scope.lojaId).orderByValue().equalTo(user.uid).once("value", function(snapshot) { if(snapshot.val() != null){ $.each(snapshot.val(), function (key, val) { firebase.database().ref('lojas_seguidores/'+$scope.lojaId+'/'+key).remove(); firebase.database().ref('usuarios_favoritos').child(user.uid).child($scope.lojaId).remove(); $('#seguir'+id).removeClass('segueS'); $('#seguir'+id).removeClass('segueN'); $('#seguir'+id).addClass('segueN'); }); $scope.hideLoading(); }else{ $('#seguir'+id).removeClass('segueN'); $('#seguir'+id).removeClass('segueS'); $('#seguir'+id).addClass('segueS'); firebase.database().ref().child('lojas_seguidores').child($scope.lojaId).push(user.uid); firebase.database().ref().child('usuarios_favoritos').child(user.uid).child($scope.lojaId).push($scope.lojaId); } $scope.hideLoading(); //console.log(snapshot.key); }); } //$scope.hideLoading(); //}); } }]) .controller('configurarSenhasCtrl', ['$scope','$timeout','$ionicSideMenuDelegate', '$stateParams','$location','$ionicLoading','$ionicHistory',// The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$timeout,$ionicSideMenuDelegate, $stateParams,$location,$ionicLoading,$ionicHistory) { var connectedRef = firebase.database().ref(".info/connected"); $scope.tentativas = 0; //$scope.conectDiv=true; connectedRef.on("value", function(snap) { $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); if (snap.val() === true) { $scope.conectDiv=true; $timeout(function () { $('body').trigger('click'); // $scope.conectDiv=true; },1500); //$window.location.reload(); } else { $scope.conectDiv=false; $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); } }); userLoggedOn = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(userLoggedOn) { if(!userLoggedOn){ $location.path('/login') } }); $ionicSideMenuDelegate.canDragContent(false); var user=""; $scope.ionicGoBack = function() { $ionicHistory.goBack(); }; $scope.retornaNome = function(num) { switch (num) { case 1: return 'Comum'; break; case 2: return 'Prioritária'; break; case 3: return 'Manual'; break; default: } } $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', duration: 3000 }).then(function(){ //console.log("The loading indicator is now displayed"); }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); }; $scope.$on('$ionicView.beforeEnter', function (event, viewData) { viewData.enableBack = true; $scope.showLoading(); user = firebase.auth().currentUser; $scope.countLine=0; //firebase.auth().onAuthStateChanged(function(user) { if (user){ $scope.countLine++; firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { $scope.datauser = snapshot.val(); //console.log(snapshot.val()); }); // User is signed in. //console.log(user); $scope.items =[]; firebase.database().ref().child('geo_filas').child(user.uid).on("value", function(snapshot) { if(snapshot.val() != null){ //console.log(snapshot.val()); $scope.items.push(snapshot.val()); //console.log($scope.items); }else{ $scope.totalItens =$scope.items.length; } $scope.hideLoading(); // //console.log($scope.items); }); } else { // No user is signed in. $location.path('/page5'); } //}); }); $scope.hideLoading(); $scope.irEditarFila = function(texto) { $location.path('/cadastrarfilas/'+texto); } $scope.showTrueFalse = function(texto) { // //console.log(texto); if(texto== true){ return 'Ativa'; }else{ return 'Inativa'; } } }]) .controller('gerarSenhasCtrl', ['$scope', '$ionicSideMenuDelegate','$stateParams','$ionicPopup','$location','$ionicLoading','$timeout', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope, $ionicSideMenuDelegate,$stateParams,$ionicPopup,$location,$ionicLoading,$timeout) { var connectedRef = firebase.database().ref(".info/connected"); $scope.tentativas = 0; //$scope.conectDiv=true; connectedRef.on("value", function(snap) { $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); if (snap.val() === true) { $scope.conectDiv=true; $timeout(function () { $('body').trigger('click'); $('#filtro').val(''); $('#filtro').trigger('change'); $('#filtro2').val(''); $('#filtro2').trigger('change'); // $scope.conectDiv=true; },1500); //$window.location.reload(); } else { $scope.conectDiv=false; $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); } }); $scope.limite =1; $scope.tituloPagina=''; $ionicSideMenuDelegate.canDragContent(false); $scope.$on('$ionicView.beforeEnter', function (event, viewData) { //$scope.conectDiv=true; $scope.showLoading(); //console.log('entrou3'); user = firebase.auth().currentUser; $scope.datauser = ''; userLoggedOn = user; firebase.auth().onAuthStateChanged(function(userLoggedOn) { if(!userLoggedOn){ $location.path('/login') } }); //console.log($scope.datauser); $scope.countLine = 0; // firebase.auth().onAuthStateChanged(function(user) { if (user) { $scope.countLine++; //$scope.showLoading(); //console.log('contador de linhas da 1148 é :'+$scope.countLine); $timeout(function() { //console.log('aqui1'); firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { $scope.datauser = snapshot.val(); //console.log(snapshot.val()); //$scope.showLoading(); //console.log('aqui2'); if(snapshot.val().role ==2){ $scope.tituloPagina='Gerar Senhas'; //console.log('aqui3'); firebase.database().ref().child('geo_filas').child(user.uid).once("value", function(snapshot) { //console.log('aqui4'); $scope.items = []; if(snapshot.val() != null ){ $scope.items.push(snapshot.val()); //console.log($scope.items); }else{ $scope.totalItens =$scope.items.length; } $scope.hideLoading(); firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { if(snapshot.val() != null ){ $scope.limite = snapshot.val().limit; } },function(error) { $scope.hideLoading(); }); },function(error) { $scope.hideLoading(); }); }else{ $scope.tituloPagina='Pegar Senha'; $scope.showLoading(); //console.log('aqui'); firebase.database().ref().child('categorias').orderByChild('categorias').once("value", function(snapshot) { //console.log('aqui2'); if(snapshot.val() != null ){ //console.log('aqui3'); $scope.categorias = snapshot.val(); $scope.optCategorias = []; $.each($scope.categorias, function(key, value){ if(value != '' && typeof value != 'undefined' && typeof value != undefined && value != null){ $scope.optCategorias.push({'categoria': value,'id':key}); } }); //console.log($scope.optCategorias); $timeout(function () { //console.log('aqui4'); $('#filtro').val(''); $('#filtro').trigger('change'); $scope.hideLoading(); }, 1000); }else{ $timeout(function () { $scope.hideLoading(); }, 2000); } // $('#filtro').focus(); },function(error){ //console.log('aqui 5'); $scope.hideLoading(); }); } }, function(error){ //console.log('aqui 6'); $scope.hideLoading(); }); },2500); }else{ //console.log('aqui3'); $scope.tituloPagina='Pegar Senha'; $scope.showLoading(); $timeout(function () { $scope.showLoading(); user = firebase.auth().currentUser; if(user) { $scope.showLoading(); firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { $scope.datauser = snapshot.val(); if(snapshot.val().role ==2) { $scope.tituloPagina='Gerar Senhas'; //console.log('aqui3'); firebase.database().ref().child('geo_filas').child(user.uid).once("value", function(snapshot) { // //console.log('aqui4'); $scope.items = []; if(snapshot.val() != null ){ $scope.items.push(snapshot.val()); // //console.log($scope.items); }else{ $scope.totalItens =$scope.items.length; } $scope.hideLoading(); firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { if(snapshot.val() != null ){ $scope.limite = snapshot.val().limit; } },function(error) { $scope.hideLoading(); }); },function(error) { $scope.hideLoading(); }); } }); //console.log($scope.datauser); $scope.showLoading(); firebase.database().ref().child('categorias').orderByChild('categorias').once("value", function(snapshot) { //console.log('aqui2'); //$scope.showLoading(); if(snapshot.val() != null ){ $scope.categorias = snapshot.val(); $scope.optCategorias = []; $.each($scope.categorias, function(key, value){ if(value != '' && typeof value != 'undefined' && typeof value != undefined && value != null){ $scope.optCategorias.push({'categoria': value,'id':key}); } }); //console.log($scope.optCategorias); $timeout(function () { //console.log($scope.optCategorias); $('#filtro').val(''); $('#filtro').trigger('change'); $scope.hideLoading(); }, 3000); }else{ $timeout(function () { $scope.hideLoading(); }, 2000); } // $('#filtro').focus(); }, function(error){ //console.log('aqui 5'); $scope.hideLoading(); }); //console.log('aqui1'); }else{ $scope.showLoading(); } }, 3000); //console.log('aqui'); // document.location.href = '#/page5'; } //}); $timeout(function() { //$('#filtro').val(''); //$('#filtro').trigger('change'); //$('#filtro').focus(); $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); },3000); //$scope.titulo='Gerar Senhas'; //$scope.hideLoading(); }); $scope.gerarSenhasCategorias = function(texto) { $location.path('/gerarsenhascategorias/'+texto); } $scope.removeUser = function() { $scope.showUserNotFind = false; $scope.userToNotify =[]; $('#busca').val(''); } $scope.showMensageuser = function(search) { if($scope.userToNotify == null || $scope.userToNotify == '' ) { $scope.showUserNotFind = true; $timeout(function() { $scope.showUserNotFind = false; },9000); }else { $scope.showUserNotFind = false; } } $scope.retornaNome = function(num) { switch (num) { case 1: return 'Comum'; break; case 2: return 'Prioritária'; break; case 3: return 'Manual'; break; default: } } $scope.userToNotify=''; $scope.buscarUsuarios = function(search) { $scope.showUserNotFind = false; if(typeof search != 'undefined' ) { busca = search.split("@"); //var rootRef = firebase.database.ref(); //var usersRef = rootRef.child("users"); // //console.log(usersRef.parent.isEqual(rootRef)); firebase.database().ref().child('users').orderByChild('email').equalTo(search).on("value", function(snapshot) { $scope.userToNotify=snapshot.val(); // //console.log(snapshot.val()); }); if(busca.length == 1){ } //console.log(search); } } $scope.pos={}; $scope.pos.lat=0; $scope.pos.lon=0; $scope.post={}; $scope.imageUrl=''; $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...' }).then(function(){ }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ }); }; $scope.showAlert = function(texto) { var alertPopup = $ionicPopup.alert({ title: texto.titulo, template: texto.mensagem }); alertPopup.then(function(res) { }); }; $scope.contador=''; $scope.contaNumero = function(id){ setDateTime(); user = firebase.auth().currentUser; $scope.contadorAuxSenha = 0; $scope.countLine=0; //firebase.auth().onAuthStateChanged(function(user) { if (user){ $scope.countLine++; if($scope.contadorAuxSenha==0){ $scope.contadorAuxSenha ++ firebase.database().ref().child('geo_filas').child(user.uid).child(id).once("value", function(snapshot){ if(snapshot.val() != null) { fila =snapshot.val(); $scope.contador = parseInt(fila.numero_contador) + 1; // //console.log($scope.contador); user = firebase.auth().currentUser; var mykey = firebase.database().ref('geo_filas_senhas/' + user.uid).push(); var prefixo = fila.prefixo || ''; var contador = $scope.contador || 1; var nome = fila.nome || 'S/N'; var posFixoRestaurante = ''; if(typeof $scope.datauser.categoria != 'undefined'){ if($scope.datauser.categoria== 1){ posFixoRestaurante= $('#qtdPessoas').val(); if(typeof posFixoRestaurante != 'undefined' && posFixoRestaurante != '? undefined:undefined ?'){ posFixoRestaurante = ' P-'+ posFixoRestaurante; }else { posFixoRestaurante = ' P-'+ 1; } } } firebase.database().ref('geo_filas_senhas/' + user.uid).push({ pos:contador, numero:prefixo + $scope.contador + posFixoRestaurante, ativo:'true', tipo:nome,data:getDate(userDateTimeFull),user_id:$scope.user_id , }, function(error) { $scope.hideLoading(); $scope.texto={}; if(error){ $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='Não conseguimos efetuar a operação.'; $scope.hideLoading(); $scope.showAlert($scope.texto); }else { $scope.texto.titulo ='Tudo certo!'; $scope.texto.mensagem ='Sua senha é '+ prefixo + contador + posFixoRestaurante; firebase.database().ref('geo_filas').child(user.uid).child(id).child('/numero_contador').set( $scope.contador); if($scope.user_id != '' && $scope.user_id != null) { firebase.database().ref('senhas_usuarios/' + $scope.user_id).push({ pos:contador, numero:prefixo + $scope.contador + posFixoRestaurante, ativo:'true', tipo:nome,data:getDate(userDateTimeFull),loja_id:$scope.user_id , }, function(error) { }); } $scope.hideLoading(); $('#qtdPessoas').val(''); $scope.showAlert($scope.texto); } }); }else { $scope.texto={}; $scope.texto.titulo ='Ops! Que embaraçoso'; $scope.texto.mensagem ='Algo deu errado, a operação não foi efetuada.'; $scope.hideLoading(); $scope.showAlert($scope.texto); } }); } } //}); } $scope.contaSenha = function() { setDateTime(); $scope.countLine=0; firebase.auth().onAuthStateChanged(function(user) { if (user){ var dateObj = new Date(); var month = dateObj.getUTCMonth() + 1; //months from 1-12 var day = dateObj.getUTCDate(); var year = dateObj.getUTCFullYear(); $scope.countLine++; user = firebase.auth().currentUser; var ref = firebase.database().ref("senhas_gratis/"+user.uid+'/'+ year +'/'+ month); ref.once("value") .then(function(snapshot) { var a = snapshot.numChildren(); // 1 ("name") $scope.contadorSenha = snapshot.child(day).numChildren(); // 2 ("first", "last") // //console.log($scope.contadorSenha); //return b; }); } }); } $scope.contadorSenha = $scope.contaSenha(); $scope.setlogsenha = function() { setDateTime(); //$timeout(function () { var dateObj = new Date(); var month = dateObj.getUTCMonth() + 1; //months from 1-12 var day = dateObj.getUTCDate(); var year = dateObj.getUTCFullYear(); user = firebase.auth().currentUser; firebase.database().ref('senhas_gratis/' + user.uid +'/' + year +'/'+ month+'/'+ day ).push({qtd:1}); //}, 300); } //$scope.setlogsenha(); $scope.gerarSenha = function(value, id) { $scope.showLoading(); user = firebase.auth().currentUser; var user_id = $('#user_id').val(); $scope.user_id = $('#user_id').val() || null; user_id = user_id || null; $('#user_id').val(''); $('#busca').val(''); $scope.userToNotify =[]; $scope.contaSenha(); $scope.texto= {}; if( $scope.contadorSenha >= $scope.limite) { $scope.texto.titulo ='Aviso'; $scope.texto.mensagem ='Limite de senhas diárias excedido. Aumente o limite em configurações -> Minha Conta.'; $scope.hideLoading(); $scope.showAlert($scope.texto); }else{ $scope.setlogsenha(); $scope.contaNumero(id); estab = user.displayName; estab = estab || user.email; if(user_id != '' && user_id !=null){ sendNotificationTouUserNewNumber(user_id,estab); } } } $scope.senhamanual=''; $scope.gerarSenhaManual = function(value, id, senhamanual) { setDateTime(); $scope.showLoading(); //console.log('aqui'); var user_id = $('#user_id').val(); $scope.user_id = $('#user_id').val() || null; user_id = user_id || null; $('#user_id').val(''); $('#busca').val(''); $scope.userToNotify =[]; if(senhamanual != '') { user = firebase.auth().currentUser; $scope.setlogsenha(); $scope.existNum =''; $scope.contaSenha(); $scope.texto= {}; //console.log('aqi232'); if( $scope.contadorSenha >= $scope.limite) { $scope.texto.titulo ='Aviso'; $scope.texto.mensagem ='Limite de senha diárias excedido.'; $scope.hideLoading(); $scope.showAlert($scope.texto); }else{ firebase.database().ref().child('geo_filas_senhas').child(user.uid).orderByChild("numero").startAt(senhamanual).endAt(senhamanual).once("value", function(snapshot) { if(snapshot.val() != null && snapshot.val() != 'null' && snapshot.val() != ''){ $scope.texto={}; $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='Este número já está em uso.'; $scope.hideLoading(); $scope.showAlert($scope.texto); }else{ var mykey = firebase.database().ref('geo_filas_senhas/' + user.uid).push(); firebase.database().ref('geo_filas_senhas/' + user.uid +'/' + mykey.key ).set({ pos:'1', numero:senhamanual, ativo:'true',tipo:value.nome,data:getDate(userDateTimeFull),user_id:user_id, }, function(error) { $scope.texto={}; if(error){ $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='Operaçao não efetuada.'; $scope.hideLoading(); $scope.showAlert($scope.texto); }else { $scope.texto.titulo ='Tudo Certo'; $scope.texto.mensagem ='Sua senha é '+ senhamanual; estab = user.displayName; estab = estab || user.email; if(user_id != '' && user_id !=null){ sendNotificationTouUserNewNumber(user_id,estab); } $scope.hideLoading(); $scope.showAlert($scope.texto); } }); } }); } }else{ $scope.texto={}; $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='O valor do campo manual não pode ficar vazio.'; $scope.hideLoading(); $scope.showAlert($scope.texto); } } }]) .controller('configuraEsCtrl', ['$scope','$ionicSideMenuDelegate', '$stateParams','$location','$ionicLoading','$timeout', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$ionicSideMenuDelegate, $stateParams,$location,$ionicLoading,$timeout) { var connectedRef = firebase.database().ref(".info/connected"); $scope.tentativas = 0; //$scope.conectDiv=true; connectedRef.on("value", function(snap) { $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); if (snap.val() === true) { $scope.conectDiv=true; $timeout(function () { $('body').trigger('click'); // $scope.conectDiv=true; },1500); //$window.location.reload(); } else { $scope.conectDiv=false; $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); } }); userLoggedOn = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(userLoggedOn) { if(!userLoggedOn){ $location.path('/login') } }); $ionicSideMenuDelegate.canDragContent(false); $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', duration: 15000 }).then(function(){ //console.log("The loading indicator is now displayed"); }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); }; $scope.titulo =''; $scope.$on('$ionicView.leave', function(){ //$ionicSideMenuDelegate.canDragContent(true); //$('.ion-navicon').show(); }); $scope.$on('$ionicView.beforeEnter', function (event, viewData) { $scope.showContent= false; $timeout(function () { $scope.showContent= true; }, 2500); $scope.showLoading(); var lojasAux = {}; $scope.lojas =[]; $scope.noticket = false; $scope.countLine = 0; //firebase.auth().onAuthStateChanged(function(user) { user = firebase.auth().currentUser; $scope.datauser = user; if (user){ $scope.countLine++; //console.log('contador da linha 1525 é :'+$scope.countLine); $timeout(function() { firebase.database().ref().child('users').child(user.uid).once("value", function(snapshotuser){ $scope.datauser = snapshotuser.val(); //console.log($scope.datauser); if($scope.datauser.role == 2) { $scope.titulo ='Minha Fila'; firebase.database().ref().child('geo_filas_senhas_usadas').child(user.uid).limitToLast(1).on("child_added", function(snapshot) { if(snapshot.val() != null ){ $scope.senha=snapshot.val(); $scope.hideLoading(); $scope.noticket = false; }else{ $scope.noticket = true; $scope.hideLoading(); } },function(error) { $scope.hideLoading(); }); $scope.senhasAnterioresAux=[] var ref = firebase.database().ref().child('geo_filas_senhas_usadas').child(user.uid); $scope.senhasAnteriores=[]; ref.orderByKey().limitToLast(10).on("child_added", function(snapshot) { if(snapshot.val() != null ){ $scope.senhasAnteriores.unshift(snapshot.val()); //countRef++; } },function(error) { $scope.hideLoading(); }); $('#filtro').val(' '); }else { $scope.titulo ='Favoritos'; $scope.hasLojas='S'; firebase.database().ref().child('usuarios_favoritos').child(user.uid).once("value", function(snapshot) { var lojasAux = {}; if(snapshot.val() != null ){ $scope.lojas =[]; lojasAux.segue='S'; $.each(snapshot.val(), function (key, val) { $scope.hasLojas='S'; firebase.database().ref().child('users').child(key).once("value", function(snapshot2) { if(snapshot2.val() != null){ lojasAux = snapshot2.val(); lojasAux.key = key; lojasAux.segue='S'; lojasAux.categoriaNome= returnCategoria(snapshot2.val().categoria); //console.log(snapshot2.val()); $scope.lojas.push(lojasAux); $timeout(function(){ $('#filtro2').val(''); $scope.hideLoading(); //console.log('her34'); },1000); //console.log($scope.lojas); }else{ lojasAux.segue='N'; $scope.hasLojas='N'; } },function(error) { $scope.hideLoading(); }); }); //console.log(snapshot.val()); //$scope.lojas=snapshot.val(); $scope.hideLoading(); }else{ $scope.hasLojas='N'; $scope.hideLoading(); } }, function(error) { $scope.hideLoading(); }); } }, function(error) { //console.log('error aqui'); $scope.hideLoading(); }); //$scope.hideLoading(); },2500); //$scope.showLoading(); } else { $scope.hideLoading(); $location.path('/page5') } //}); }); $scope.seguirEstabelecimento=function(id) { $scope.showLoading(); $scope.lojaId = id; user = firebase.auth().currentUser; //console.log($scope.lojaId); $scope.countLine=0; // firebase.auth().onAuthStateChanged(function(user) { if (user){ $scope.countLine++; //console.log('contador da linha 1615 é :'+$scope.countLine); //console.log(); firebase.database().ref().child('lojas_seguidores').child($scope.lojaId).orderByValue().equalTo(user.uid).once("value", function(snapshot) { if(snapshot.val() != null){ $.each(snapshot.val(), function (key, val) { firebase.database().ref('lojas_seguidores/'+$scope.lojaId+'/'+key).remove(); firebase.database().ref('usuarios_favoritos').child(user.uid).child($scope.lojaId).remove(); $('#seguir'+id).removeClass('segueS'); $('#seguir'+id).removeClass('segueN'); $('#seguir'+id).addClass('segueN'); }); $scope.hideLoading(); }else{ $('#seguir'+id).removeClass('segueN'); $('#seguir'+id).removeClass('segueS'); $('#seguir'+id).addClass('segueS'); firebase.database().ref().child('lojas_seguidores').child($scope.lojaId).push(user.uid); firebase.database().ref().child('usuarios_favoritos').child(user.uid).child($scope.lojaId).push($scope.lojaId); $scope.hideLoading(); } //console.log(snapshot.key); }); } //$scope.hideLoading(); //}); } $scope.moredata = false; $scope.loadMoreData=function() { if(typeof $scope.senhasAnterioresAux[0] != "undefined") { $scope.senhasAnteriores.push($scope.senhasAnterioresAux[0]); $scope.senhasAnterioresAux.shift(); $scope.$broadcast('scroll.infiniteScrollComplete'); }else{ $timeout(function() { $scope.$broadcast('scroll.infiniteScrollComplete'); $scope.moredata=true; },3000); } }; /*$scope.clicarCorpo = function() { //console.log('aqui'); if($('.tabs').is(":visible")){ $scope.esconder(); }else{ $scope.mostrar(); } }*/ $scope.mostrar = function() { $('.nav-bar-container').fadeIn(1000); $('.tabs').fadeIn(1000); } $scope.esconder = function() { $('.nav-bar-container').fadeOut(1000); $('.tabs').fadeOut(1000); } //alert(); }]) .controller('menuCtrl', ['$scope','$ionicSideMenuDelegate', '$stateParams','$ionicLoading','$timeout', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$ionicSideMenuDelegate, $stateParams,$ionicLoading,$timeout) { $ionicSideMenuDelegate.canDragContent(false); $scope.$on('$ionicView.beforeEnter', function (event, viewData) { //viewData.enableBack = true; firebase.auth().onAuthStateChanged(function(user) { user = firebase.auth().currentUser; $scope.user = firebase.auth().currentUser; firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { $scope.datauser = snapshot.val(); //console.log(snapshot.val()); }); }); }); $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', duration: 3000 }).then(function(){ //console.log("The loading indicator is now displayed"); }); }; $scope.logoff = function() { firebase.auth().signOut().then(function() { // Sign-out successful. }, function(error) { // An error happened. }); //$timeout(function() { // document.location.href = '#/page5'; //},3000); } }]) .controller('loginCtrl', ['$scope','$timeout','$location','$cordovaOauth', '$stateParams','$ionicLoading','$ionicHistory','$timeout','$ionicSideMenuDelegate', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$timeout,$location,$cordovaOauth, $stateParams,$ionicLoading,$ionicHistory,$timeout,$ionicSideMenuDelegate) { $ionicSideMenuDelegate.canDragContent(false); $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', duration: 6000 }).then(function(){ //console.log("The loading indicator is now displayed"); }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); }; /*$scope.ionicGoBack = function() { $ionicHistory.goBack(); };*/ var user = firebase.auth().currentUser; $scope.$on('$ionicView.enter', function(){ $ionicSideMenuDelegate.canDragContent(false); $('.ion-navicon').hide(); }); $scope.$on('$ionicView.beforeEnter', function (event, viewData) { viewData.enableBack = false; $scope.notToShow = false; $scope.showContent = false; $timeout(function () { $scope.showContent = true; }, 6000); //$scope.showLoading(); user = firebase.auth().currentUser; //console.log(user); $scope.countLine=0; firebase.auth().onAuthStateChanged(function(user) { //alert('passou1'); $scope.showLoading(); if(user){ $scope.countLine++; $scope.user = firebase.auth().currentUser; firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { //console.log('aqui2'); $scope.datauser = snapshot.val(); //$location.path('#/page1/page3');; document.location.href = '#/page1/page3'; }, function(error) { //document.location.href = '#/page1/page3'; }); } }); }); }]) .controller('login2Ctrl', ['$scope','$location','$cordovaOauth', '$stateParams','$ionicLoading','$ionicHistory','$timeout','$ionicSideMenuDelegate', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$location,$cordovaOauth, $stateParams,$ionicLoading,$ionicHistory,$timeout,$ionicSideMenuDelegate) { $ionicSideMenuDelegate.canDragContent(false); $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', duration: 3000 }).then(function(){ //console.log("The loading indicator is now displayed"); }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); }; $scope.ionicGoBack = function() { $ionicHistory.goBack(); }; var user = firebase.auth().currentUser; $scope.$on('$ionicView.enter', function(){ $ionicSideMenuDelegate.canDragContent(false); $('.ion-navicon').hide(); }); $scope.$on('$ionicView.beforeEnter', function (event, viewData) { viewData.enableBack = true; $scope.notToShow = false; //$scope.showLoading(); user = firebase.auth().currentUser; //console.log(user); $scope.countLine=0; firebase.auth().onAuthStateChanged(function(user) { //alert('passou1'); if(user){ $scope.countLine++; $scope.user = firebase.auth().currentUser; firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { // //console.log('aqui2'); $scope.datauser = snapshot.val(); //$location.path('#/page1/page3');; document.location.href = '#/page1/page3'; }, function(error) { //document.location.href = '#/page1/page3'; }); } }); }); $scope.loginTwitter = function(user) { $scope.showLoading(); $('.aviso-login').html(''); var provider = new firebase.auth.TwitterAuthProvider(); firebase.auth().signInWithPopup(provider).then(function(result) { // This gives you a the Twitter OAuth 1.0 Access Token and Secret. // You can use these server side with your app's credentials to access the Twitter API. var token = result.credential.accessToken; var secret = result.credential.secret; // The signed-in user info. var user = result.user; document.location.href = '#/page1/page3'; // ... }).catch(function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // The email of the user's account used. var email = error.email; // The firebase.auth.AuthCredential type that was used. var credential = error.credential; // ... $('.divAvisoLogin').show(); $('.aviso-login').html('Ops, não encontramos o seu cadastro.'); }); $timeout(function() { firebase.auth().onAuthStateChanged(function(user) { user = firebase.auth().currentUser; $scope.user = firebase.auth().currentUser; firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { //console.log(snapshot.val()); }); document.location.href = '#/page1/page3'; }); },1000); } $scope.loginGoogle = function(user) { $scope.showLoading(); $('.aviso-login').html(''); var provider = new firebase.auth.GoogleAuthProvider(); firebase.auth().signInWithPopup(provider).then(function(result) { // This gives you a Google Access Token. You can use it to access the Google API. var token = result.credential.accessToken; // The signed-in user info. var user = result.user; //console.log(user); document.location.href = '#/page1/page3'; // ... }).catch(function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // The email of the user's account used. var email = error.email; // The firebase.auth.AuthCredential type that was used. var credential = error.credential; $('.divAvisoLogin').show(); $('.aviso-login').html('Ops, não encontramos o seu cadastro.'); // ... }); $timeout(function() { firebase.auth().onAuthStateChanged(function(user) { user = firebase.auth().currentUser; $scope.user = firebase.auth().currentUser; // //console.log(user); document.location.href = '#/page1/page3'; }); },1000); } $scope.esqueciasenha = function(user) { $scope.showLoading(); $('.divAvisoLogin').hide(); if (typeof user == 'undefined') { $('.aviso-login').html('Ops. Digite o email'); $('.divAvisoLogin').show(); }else if(user.email == '' || user.email == null){ $('.aviso-login').html('Ops. Digite o email'); $('.divAvisoLogin').show(); }else{ var auth = firebase.auth(); auth.sendPasswordResetEmail(user.email).then(function() { $('.aviso-login').html('Tudo certo! Um e-mail foi enviado para a redeficição da sua senha.'); $('.divAvisoLogin').show(); }, function(error) { $('.aviso-login').html('Ops! Ocorreu um erro e não conseguimos continuar com a redefinição da sua senha.'); $('.divAvisoLogin').show(); }); } } $scope.loginManual = function(user) { $scope.showLoading(); $('.divAvisoLogin').hide(); if(typeof user == 'undefined'){ $('.aviso-login').html('Ops. Digite o Email e Senha'); $('.divAvisoLogin').show(); }else{ // //console.log(user); firebase.auth().signInWithEmailAndPassword(user.email, user.password).catch(function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; //console.log(errorCode.length); if(errorCode.length == 19){ $('.divAvisoLogin').show(); $('.aviso-login').html('Algo deu errado, verifique seu email e senha.'); }else if (errorCode.length == 27) { $('.divAvisoLogin').show(); $('.aviso-login').html('Sem conexão com a internet.'); } }); $timeout(function() { firebase.auth().onAuthStateChanged(function(user) { user = firebase.auth().currentUser; $scope.user = firebase.auth().currentUser; firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { //console.log(snapshot.val()); document.location.href = '#/page1/page3'; }); }); },1000); } } $scope.loginFacebook = function(user) { $('.divAvisoLogin').hide(); var auth = new firebase.auth.FacebookAuthProvider(); $cordovaOauth.facebook("111991969424960", ["email"]).then(function(result) { var credential = firebase.auth.FacebookAuthProvider.credential(result.access_token); firebase.auth().signInWithCredential(credential).catch(function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // The email of the user's account used. var email = error.email; // The firebase.auth.AuthCredential type that was used. var credential = error.credential; if (errorCode === 'auth/account-exists-with-different-credential') { //alert('Email já está associado com uma outra conta.'); $('.divAvisoLogin').show(); $('.aviso-login').html('Email já está associado com uma outra conta.'); // Handle account linking here, if using. } else { console.error(error); } }); user = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(user) { $scope.showLoading(); user = firebase.auth().currentUser; $scope.user = firebase.auth().currentUser; $timeout(function() { firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { if(snapshot.val() != null){ document.location.href = '#/page1/page3'; }else{ $('.divAvisoLogin').show(); $('.aviso-login').html('Algo deu errado, esta conta ainda não possui cadastro.'); var user = firebase.auth().currentUser; user.delete().then(function() { // User deleted. }, function(error) { // An error happened. }); } },function(error){ $scope.hideLoading(); $('.divAvisoLogin').show(); $('.aviso-login').html('Algo deu errado, por favor verifique a sua conexão com a internet.'); }); },5000); }); }, function(error) { //alert("ERROR: " + error); }); } }]) .controller('cadastrarfilasCtrl', ['$scope','$ionicSideMenuDelegate', '$ionicPopup', '$stateParams', '$ionicHistory', '$location','$ionicLoading', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope, $ionicSideMenuDelegate,$ionicPopup, $stateParams,$ionicHistory, $location, $ionicLoading) { var connectedRef = firebase.database().ref(".info/connected"); $scope.tentativas = 0; //$scope.conectDiv=true; connectedRef.on("value", function(snap) { $scope.conectDiv=true; $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); if (snap.val() === true) { $scope.conectDiv=true; $timeout(function () { $('body').trigger('click'); // $scope.conectDiv=true; },1500); //$window.location.reload(); } else { $scope.conectDiv=false; $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); } }); userLoggedOn = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(userLoggedOn) { if(!userLoggedOn){ $location.path('/login') } }); $ionicSideMenuDelegate.canDragContent(false); $scope.retornaNome = function(num) { switch (num) { case 1: return 'Comum'; break; case 2: return 'Prioritária'; break; case 3: return 'Manual'; break; default: } } $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', //duration: 3000 }).then(function(){ //console.log("The loading indicator is now displayed"); }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); }; $scope.ionicGoBack = function() { $ionicHistory.goBack(); }; var user = firebase.auth().currentUser; $scope.$on('$ionicView.beforeEnter', function (event, viewData) { viewData.enableBack = true; $scope.notToShow = false; //$scope.conectDiv=true; $scope.showLoading(); firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { $scope.datauser = snapshot.val(); //console.log(snapshot.val()); if($scope.datauser.role ==2){ firebase.database().ref().child('geo_filas').child(user.uid).child($stateParams.id).on("value", function(snapshot) { if(snapshot.val() != null ){ $scope.fila = snapshot.val(); //console.log($scope.fila); } $scope.hideLoading(); },function(error) { $scope.hideLoading(); }); }else { $scope.hideLoading(); } },function (error) { $scope.hideLoading(); }); }); //console.log($stateParams.id); $scope.pos={}; $scope.pos.lat=0; $scope.pos.lon=0; $scope.post={}; $scope.imageUrl=''; var onSuccessPos = function(position) { $scope.pos.lat = position.coords.latitude; $scope.pos.lon= position.coords.longitude; //console.log($scope.pos.lon); }; // onError Callback receives a PositionError object function onErrorPos(error) { $scope.posErro=error; calldialog(); } navigator.geolocation.getCurrentPosition(onSuccessPos, onErrorPos, {maximumAge:60000, timeout:5000, enableHighAccuracy:true}); //$scope.fila.user_id =''; $scope.fila = []; if (user) { // User is signed in. //alert('1'); //console.log(user); $scope.fila.user_id = user.uid; } else { $location.path('/page5') } var firebaseRef = firebase.database().ref().child('geo_filas'); var geoFire = new GeoFire(firebaseRef); var ref = geoFire.ref(); // ref === firebaseRef //var mykey = ref.child('dados').push(); //console.log(user.uid); var user = firebase.auth().currentUser //$scope.showConfirm(); // An alert dialog $scope.showAlert = function(texto) { var alertPopup = $ionicPopup.alert({ title: texto.titulo, template: texto.mensagem }); alertPopup.then(function(res) { //console.log('Thank you for not eating my delicious ice cream cone'); $location.path('/page2'); }); }; $scope.cadastrarFila = function(fila) { var user = firebase.auth().currentUser var nome = fila.nome || null; var ativa = fila.ativa || false; var prioridade = fila.prioridade || false; var prioridade_qtd = fila.qtd_prioridade || 0; var manual = fila.manual || false; var numero_contador = fila.numero_contador || 0; var prefixo = fila.prefixo || ''; $scope.texto= {}; //console.log(nome); if(nome == null || nome == 'undefined' ) { $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='O nome não poder estar vazio.'; $scope.showAlert($scope.texto); }else{ firebase.database().ref('geo_filas/' + user.uid + '/' + $stateParams.id).set({ nome: nome, ativa:ativa, prioridade:prioridade, prioridade_qtd:prioridade_qtd, manual:manual, numero_contador:numero_contador, prefixo:prefixo, }, function(error) { if(error){ $scope.texto.titulo ='Ops! Foi mal!'; $scope.texto.mensagem ='Não conseguimos desta vez.'; $scope.showAlert($scope.texto); }else { $scope.texto.titulo ='Tudo certo!'; $scope.texto.mensagem ='A configuração foi salva.'; $scope.showAlert($scope.texto); } }); } } }]) .controller('signupCtrl', ['$scope','$cordovaOauth','$location','$firebaseObject','$firebaseAuth', '$stateParams','$ionicPopup','$ionicLoading','$timeout','$ionicSideMenuDelegate', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$cordovaOauth ,$location, $firebaseObject,$firebaseAuth,$stateParams,$ionicPopup,$ionicLoading,$timeout,$ionicSideMenuDelegate) { $scope.$on('$ionicView.enter', function(){ $ionicSideMenuDelegate.canDragContent(false); $('.ion-navicon').hide(); user = firebase.auth().currentUser; //alert('passou1'); firebase.auth().onAuthStateChanged(function(user) { if(user){ // document.location.href = '#/page1/page3'; } }); }); $scope.$on('$ionicView.leave', function(){ //$ionicSideMenuDelegate.canDragContent(true); //$('.ion-navicon').show(); }); $scope.$on('$ionicView.beforeEnter', function (event, viewData) { user = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(user) { if(user){ $scope.showLoading(); $timeout(function () { $scope.showLoading(); //$location.path('#/page1/page3');; document.location.href = '#/page1/page3'; }, 3000); } }); }); $scope.loginNormal = function (e) { $scope.user= e; ref.authWithPassword({ email : $scope.user.email, password : $<PASSWORD> }, function(error, authData) { if (error) { } else { //$location.path('#/page1/page3');; document.location.href = '#/page1/page3'; // window.location.href = '#/home'; } }); } $scope.showPopup = function(texto) { var alertPopup = $ionicPopup.alert({ title: texto.titulo, template: texto.mensagem }); }; $scope.validaEmail= function(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; //$('.aviso-cadastro').hide(); if(re.test(email)){ $('.divAvisoEmail').hide(); $('.lb-email ').removeClass('myredcolor'); return true; }else { $('.divAvisoEmail').show(); $('.lb-email ').addClass('myredcolor'); return false; } } $scope.difpassword = function(user) { $('.aviso-cadastro').html(''); if(typeof user !=='undefined') { if (user.password != <PASSWORD> && (user.password != '' && user.cpassword != '') ) { $('.lb-password ').addClass('myredcolor'); $('.divAviso').show(); return false; }else{ $('.lb-password ').removeClass('myredcolor'); $('.divAviso').hide(); return true; } }else { $('.lb-password ').removeClass('myredcolor'); $('.divAviso').hide(); return true; } } $scope.validaCadastro = function(user) { $('.aviso-cadastro').html(''); if(user.email == null || user.email == ''){ $scope.texto.titulo='Ops! Algo deu errado.'; $scope.texto.mensagem='O campo email não pode ficar vazio.'; return false; }else{ return true; } } $scope.validaFormulario = function(user) { $('.aviso-cadastro').html(''); var flagValid=true; if($scope.difpassword(user)== false){ flagValid= false; } if(!$scope.validaEmail(user.email)){ flagValid= false; } if($scope.validaCadastro(user)== false){ flagValid= false; } return flagValid; } function logUser(user) { var ref = firebase.database().ref("users"); // //console.log(user); var obj = { "user": user }; ref.push(obj); // or however you wish to update the node } $scope.pos={}; $scope.pos.lat=0; $scope.pos.lon=0; $scope.post={}; $scope.imageUrl=''; var onSuccessPos = function(position) { $scope.pos.lat = position.coords.latitude; $scope.pos.lon= position.coords.longitude; //console.log($scope.pos.lon); }; $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', duration: 3000 }).then(function(){ // //console.log("The loading indicator is now displayed"); }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ // //console.log("The loading indicator is now hidden"); }); }; $scope.showAlert = function(texto) { var alertPopup = $ionicPopup.alert({ title: texto.titulo, template: texto.mensagem }); alertPopup.then(function(res) { //console.log('Thank you for not eating my delicious ice cream cone'); //$location.path('/page1/page10'); }); }; function onErrorPos(error) { $scope.posErro=error; calldialog(); } navigator.geolocation.getCurrentPosition(onSuccessPos, onErrorPos, {maximumAge:60000, timeout:5000, enableHighAccuracy:true}); $scope.cadastrarUsuarioCliente = function(user) { $scope.showLoading(); $('.aviso-cadastro').html(''); if(typeof user != 'undefined') { //console.log('aqui'); if($scope.validaCadastro(user)){ if($scope.validaFormulario(user)){ firebase.auth().createUserWithEmailAndPassword(user.email, user.password).catch(function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; var errorWeek ='auth/weak-password'; $('.lb-email ').removeClass('myredcolor'); // //console.log('aqui1'); if(errorCode.length == 18){ $('.aviso-cadastro').html('Ops, a senha deve ter pelo menos 6 caracteres!'); $('.divAvisoCadastro').show(); }else if(errorCode.length == 25){ $('.lb-email ').addClass('myredcolor'); $('.aviso-cadastro').html('Ops, este email já se encontra em uso.'); $('.divAvisoCadastro').show(); }else if (errorCode.length == 27) { $('.divAvisoCadastro').show(); $('.aviso-cadastro').html('Sem conexão com a internet.'); } // ... }); $scope.cadastrarManualCliente=1; firebase.auth().onAuthStateChanged(function(user) { if($scope.cadastrarManualCliente == 1){ user = firebase.auth().currentUser; $scope.user = firebase.auth().currentUser; //console.log($scope.user); firebase.database().ref('users/' + user.uid).remove(); firebase.database().ref('users/' + user.uid).set({ email: user.email, active:1, role:3, ver_fila:true, nome:user.displayName, email:user.email, foto:user.photoURL, raio:50, }, function(error) { if(error){ //console.log('erro'); }else{ } }); $scope.cadastrarManualCliente=0; $timeout(function() { //$location.path('#/page1/page3');; document.location.href = '#/page1/page3'; },1000); } }); //}); } } }else{ $('.aviso-cadastro').html('Ops, digite o usuário e a senha!'); $('.divAvisoCadastro').show(); //console.log('aqui2'); } //console.log(user); } $scope.cadastrarUsuarioFacebookCliente = function(user) { var auth = new firebase.auth.FacebookAuthProvider(); $('.divAvisoCadastro').hide(); $cordovaOauth.facebook("111991969424960", ["email"]).then(function(result) { var credential = firebase.auth.FacebookAuthProvider.credential(result.access_token); firebase.auth().signInWithCredential(credential).catch(function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // The email of the user's account used. var email = error.email; // The firebase.auth.AuthCredential type that was used. var credential = error.credential; if (errorCode === 'auth/account-exists-with-different-credential') { //alert('Email already associated with another account.'); // Handle account linking here, if using. $('.divAvisoCadastro').show(); $('.divAvisoCadastro').html('Email já está associado com uma outra conta.'); } else { console.error(error); } }); }, function(error) { //alert("ERROR: " + error); }); user = firebase.auth().currentUser; //alert('passou1'); $scope.cadastraUsuarioFacebookFlag= 1; firebase.auth().onAuthStateChanged(function(user) { //alert('<PASSWORD>ou2'); if($scope.cadastraUsuarioFacebookFlag == 1){ firebase.database().ref().child('users').child(user.uid).child('email').once("value", function(snapshot) { //console.log(snapshot.val()); if(snapshot.val() != null && snapshot.val() != 'null' ){ //$location.path('#/page1/page3');; document.location.href = '#/page1/page3'; }else{ //console.log('aqui2'); firebase.database().ref('users/' + user.uid).remove(); firebase.database().ref('users/' + user.uid).set({ email: user.email, active:1, role:3, ver_fila:true, nome:user.displayName, email:user.email, foto:user.photoURL, raio:50, }, function(error) { //$location.path('#/page1/page3');; document.location.href = '#/page1/page3'; }); } }); $scope.cadastraUsuarioFacebookFlag=0; } }); } }]) .controller('minhacontaCtrl', ['$scope','$location','$ionicSideMenuDelegate', '$stateParams','$ionicHistory','$ionicLoading','$ionicPopup','$timeout', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$location,$ionicSideMenuDelegate, $stateParams,$ionicHistory,$ionicLoading,$ionicPopup,$timeout) { userLoggedOn = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(userLoggedOn) { if(!userLoggedOn){ $location.path('/login') } }); var connectedRef = firebase.database().ref(".info/connected"); $scope.conectDiv=true; connectedRef.on("value", function(snap) { $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); if (snap.val() === true) { $scope.conectDiv=true; $timeout(function () { $('body').trigger('click'); // $scope.conectDiv=true; },1500); //$window.location.reload(); } else { $scope.conectDiv=false; $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); } }); $ionicSideMenuDelegate.canDragContent(false); $scope.$on('$ionicView.beforeEnter', function (event, viewData) { viewData.enableBack = true; $scope.notToShow = false; $scope.showLoadingNoTime(); $scope.countLine=0; user = firebase.auth().currentUser; //firebase.auth().onAuthStateChanged(function(user) { if (user){ $scope.countLine++; ///$scope.showLoading(); $scope.user = firebase.auth().currentUser; //console.log($scope.user); //$scope.showLoading(); firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { $scope.datauser = snapshot.val(); //console.log(snapshot.val()); }); firebase.database().ref().child('geo_lojas').child(user.uid).child('dados').once("value", function(snapshot) { $scope.dataLojas = snapshot.val(); //console.log(snapshot.val()); }); } $('.numeric').keyup(function () { this.value = this.value.replace(/[^0-9\.]/g,''); }); //}); $scope.categorias = ''; $scope.optCategorias=[]; $scope.pos={}; $scope.pos.lat=0; $scope.pos.lon=0; $scope.post={}; $scope.imageUrl=''; var onSuccessPos = function(position) { $scope.pos.lat = position.coords.latitude; $scope.pos.lon= position.coords.longitude; //console.log($scope.pos.lon); }; function onErrorPos(error) { $scope.posErro=error; calldialog(); } $scope.optCategorias=[]; navigator.geolocation.getCurrentPosition(onSuccessPos, onErrorPos, {maximumAge:60000, timeout:5000, enableHighAccuracy:true}); firebase.database().ref().child('categorias').on("value", function(snapshot) { //$scope.showLoading(); if(snapshot.val() != null ){ $scope.categorias = snapshot.val(); $scope.optCategorias=[] ; angular.forEach($scope.categorias, function(value, key) { $scope.optCategorias.push({ chave: key, valor: value }); }); $timeout(function () { if(typeof $scope.datauser != 'undefined'){ $('#categoria').val($scope.datauser.categoria); $('#categoria').trigger('change'); } $scope.hideLoading(); },3000); } },function(error) { $scope.hideLoading(); }); }); $scope.getImage = function (source) { //alert('passou1'); // Retrieve image file location from specified source $('#configForm').submit(function(event) { event.preventDefault(); }); $scope.showImage=false; var options = { maximumImagesCount: 1, quality: 50 }; $scope.showLoading(); window.imagePicker.getPictures( function(results) { //alert('passou2'); for (var i = 0; i < results.length; i++) { //getFileEntry(results[i]); var imageData = results[i]; var filename = imageData.split("/").pop(); var storageRef = firebase.storage().ref(); var getFileBlob = function(url, cb) { var xhr = new XMLHttpRequest(); xhr.open("GET", url); xhr.responseType = "blob"; xhr.addEventListener('load', function() { cb(xhr.response); }); xhr.send(); }; var blobToFile = function(blob, name) { blob.lastModifiedDate = new Date(); blob.name = name; return blob; }; var getFileObject = function(filePathOrUrl, cb) { getFileBlob(filePathOrUrl, function(blob) { cb(blobToFile(blob, 'test.jpg')); }); }; getFileObject(imageData, function(fileObject) { var uploadTask = storageRef.child('images/'+user.uid+'.jpg').put(fileObject); uploadTask.on('state_changed', function(snapshot) { //alert(snapshot); }, function(error) { //alert(error); }, function() { var downloadURL = uploadTask.snapshot.downloadURL; $scope.datauser.foto = downloadURL; firebase.database().ref('users/' + user.uid).set($scope.datauser, function(error) { $scope.texto ={}; $scope.hideLoading(); if(error){ $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='Não conseguimos salvar a configuração.'; $scope.showAlert($scope.texto); }else{ $scope.texto.titulo ='Tudo Certo!'; $scope.texto.mensagem ='Sua configuração foi salva!'; $scope.showAlert($scope.texto); } }); //alert(downloadURL); // handle image here }); }); $timeout(function(){ $scope.hideLoading(); },2000); } }, function (error) { $scope.showImage=false; alert('Error: ' + error); $timeout(function(){ $scope.hideLoading(); },2000); }, options ); $timeout(function(){ $scope.hideLoading(); },2000); } $scope.editarUsuario = function(userData) { // //console.log(userData); user = firebase.auth().currentUser; $scope.user = firebase.auth().currentUser; //navigator.geolocation.getCurrentPosition(onSuccessPos, onErrorPos, {enableHighAccuracy:true}); $scope.showLoading(); cat = $("#categoria").val(); desc = $("#descricao").val(); nome = $("#nome").val(); limite = $("#limite").val(); ver_fila = $("#ver_fila").val(); rudovip = $("#rudovip").val(); desconto = $("#desconto").val(); porcentagem = $("#porcentagem").val(); condicoes = $("#condicoes").val(); endereco =userData.endereco; bairro = userData.bairro; cidade = userData.cidade; uf = userData.uf; telefone1 = userData.telefone1; telefone2 = userData.telefone2; if($('#ver_fila').hasClass('ng-empty')) { ver_fila = false; }else{ ver_fila = true; } if($('#rudovip').hasClass('ng-empty')) { rudovip = false; }else{ rudovip = true; } if($('#desconto').hasClass('ng-empty')) { desconto = false; }else{ desconto = true; } cat = cat || null; desc = desc || null; limite = limite || null; $scope.datauser2 =[]; $scope.datauser2.nome = nome || null; porcentagem = porcentagem || null; condicoes = condicoes || null; if(user.displayName != null && user.displayName !='' && typeof user.displayName!= 'undefined') { $scope.datauser2.nome = user.displayName; //console.log('aqui1'); } $scope.datauser2.foto =''; if(user.photoURL != null && user.photoURL !='' && typeof user.photoURL!= 'undefined') { $scope.datauser2.foto = user.photoURL; }else if($scope.datauser.foto != null && $scope.datauser.foto !='' && typeof $scope.datauser.foto!= 'undefined'){ $scope.datauser2.foto = $scope.datauser.foto; }else{ $scope.datauser2.foto = null; } //user.displayName=nome; //user.photoURL= foto; //nome = user.displayName; //console.log(ver_fila); ver_fila = ver_fila || null; rudovip = rudovip || null; desconto = desconto || null; endereco = endereco || null; bairro = bairro || null; cidade = cidade || null; uf = uf || null; telefone1 = telefone1 || null; telefone2 = telefone2 || null; //firebase.auth().onAuthStateChanged(function(user) { //console.log($scope.datauser.categoria); //console.log(user.uid); //if(typeof $scope.datauser.categoria !='undefined'){ if(typeof user.uid != 'undefined'){ firebase.database().ref('geo_lojas_cat').child(0).child(user.uid).remove(); firebase.database().ref('geo_lojas_cat').child(1).child(user.uid).remove(); firebase.database().ref('geo_lojas_cat').child(2).child(user.uid).remove(); firebase.database().ref('geo_lojas_cat').child(3).child(user.uid).remove(); firebase.database().ref('geo_lojas_cat').child(4).child(user.uid).remove(); firebase.database().ref('geo_lojas_cat').child(5).child(user.uid).remove(); firebase.database().ref('geo_lojas_cat').child(6).child(user.uid).remove(); firebase.database().ref('geo_lojas_cat').child(7).child(user.uid).remove(); firebase.database().ref('geo_lojas_cat').child(8).child(user.uid).remove(); firebase.database().ref('geo_lojas_cat').child(9).child(user.uid).remove(); firebase.database().ref('geo_lojas_cat').child(10).child(user.uid).remove(); firebase.database().ref('geo_lojas_cat').child(11).child(user.uid).remove(); firebase.database().ref('geo_lojas_cat').child(12).child(user.uid).remove(); } //} firebase.database().ref('users/' + user.uid).set({ email: user.email, active:1, role:2, limit:limite, nome:$scope.datauser2.nome, foto:$scope.datauser2.foto, descricao:desc, categoria:cat, raio:50, ver_fila:ver_fila, rudovip:rudovip, desconto:desconto, porcentagem:porcentagem, condicoes:condicoes, endereco:endereco, bairro:bairro, cidade:cidade, uf:uf, telefone1:telefone1, telefone2:telefone2, }, function(error) { if(error){ $scope.texto={}; $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='Ops, o perfil não foi atualizado.'; $scope.hideLoading(); $scope.showPopup($scope.texto); }else{ firebase.database().ref().child('geo_lojas').child(cat).remove(); var firebaseRef = firebase.database().ref().child('geo_lojas_cat').child(cat); var geoFire = new GeoFire(firebaseRef); var ref = geoFire.ref(); // ref === firebaseRef var mykey = ref.child('lojas').push(); geoFire.set(user.uid, [$scope.pos.lat, $scope.pos.lon]).then(function() { //console.log("Provided key has been added to GeoFire"); firebase.database().ref('geo_lojas_cat/'+cat+'/'+ user.uid+'/dados').set({ endereco:'-', telefone:'-', nome:$scope.datauser2.nome, email:user.email, foto:$scope.datauser2.foto, raio:50, rudovip:rudovip, desconto:desconto, porcentagem:porcentagem, condicoes:condicoes, endereco:endereco, bairro:bairro, cidade:cidade, uf:uf, telefone1:telefone1, telefone2:telefone2, }, function(error) { }); if(($scope.pos.lat != '' && $scope.pos.lat != null) && ($scope.pos.lon != '' && $scope.pos.lon != null ) ){ firebase.database().ref('geo_lojas/'+ user.uid+'/l').set({ 0:$scope.pos.lat, 1:$scope.pos.lon }, function(error) { }); } }, function(error) { //console.log("Error: " + error); }); $scope.texto={}; $scope.texto.titulo ='Tudo Certo'; $scope.texto.mensagem ='Seu perfil foi atualizado.'; $scope.hideLoading(); $scope.showPopup($scope.texto); } }); //}); } $scope.showPopup = function(texto) { var alertPopup = $ionicPopup.alert({ title: texto.titulo, template: texto.mensagem }); }; $scope.showLoadingNoTime = function() { $ionicLoading.show({ template: 'Carregando...', }).then(function(){ // //console.log("The loading indicator is now displayed"); }); }; $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', duration: 3000 }).then(function(){ // //console.log("The loading indicator is now displayed"); }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ // //console.log("The loading indicator is now hidden"); }); }; }]) .controller('signuptwoCtrl', ['$scope','$cordovaOauth','$location', '$stateParams','$ionicPopup','$ionicLoading','$timeout','$ionicSideMenuDelegate', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$cordovaOauth, $location,$stateParams,$ionicPopup,$ionicLoading,$timeout,$ionicSideMenuDelegate) { $scope.$on('$ionicView.enter', function(){ $ionicSideMenuDelegate.canDragContent(false); $('.ion-navicon').hide(); }); $scope.pos={}; $scope.pos.lat=0; $scope.pos.lon=0; var onSuccessPos = function(position) { $scope.pos.lat = position.coords.latitude; $scope.pos.lon= position.coords.longitude; //console.log($scope.pos.lon); }; function onErrorPos(error) { $scope.posErro=error; $scope.pos.lat=0; $scope.pos.lon=0; calldialog(); } $scope.$on('$ionicView.beforeEnter', function (event, viewData) { navigator.geolocation.getCurrentPosition(onSuccessPos, onErrorPos, {maximumAge:60000, timeout:5000, enableHighAccuracy:true}); user = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(user) { if(user) { navigator.geolocation.getCurrentPosition(onSuccessPos, onErrorPos, {enableHighAccuracy:true}); $scope.showLoading(); $timeout(function () { $scope.showLoading(); //$location.path('#/page1/page3');; document.location.href = '#/page1/page3'; }, 3000); } }); }); $scope.$on('$ionicView.leave', function(){ //$ionicSideMenuDelegate.canDragContent(true); //$('.ion-navicon').show(); }); $scope.loginNormal = function (e) { $scope.user= e; ref.authWithPassword({ email : $scope.user.email, password : $<PASSWORD> }, function(error, authData) { if (error) { } else { //$location.path('#/page1/page3');; document.location.href = '#/page1/page3'; // window.location.href = '#/home'; } }); } $scope.showPopup = function(texto) { var alertPopup = $ionicPopup.alert({ title: texto.titulo, template: texto.mensagem }); }; $scope.validaEmail= function(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; //$('.aviso-cadastro').hide(); if(re.test(email)){ $('.divAvisoEmail').hide(); $('.lb-email ').removeClass('myredcolor'); return true; }else { $('.divAvisoEmail').show(); $('.lb-email ').addClass('myredcolor'); return false; } } $scope.difpassword = function(user) { $('.aviso-cadastro').html(''); if(typeof user !=='undefined') { if (user.password != <PASSWORD> && (user.password != '' && user.cpassword != '') ) { $('.lb-password ').addClass('myredcolor'); $('.divAviso').show(); return false; }else{ $('.lb-password ').removeClass('myredcolor'); $('.divAviso').hide(); return true; } }else { $('.lb-password ').removeClass('myredcolor'); $('.divAviso').hide(); return true; } } $scope.validaCadastro = function(user) { navigator.geolocation.getCurrentPosition(onSuccessPos, onErrorPos, {enableHighAccuracy:true}); $('.aviso-cadastro').html(''); if(user.email == null || user.email == ''){ $scope.texto.titulo='Ops! Algo deu errado.'; $scope.texto.mensagem='O campo email não pode ficar vazio.'; return false; }else{ return true; } } $scope.validaFormulario = function(user) { $('.aviso-cadastro').html(''); var flagValid=true; if($scope.difpassword(user)== false){ flagValid= false; } if(!$scope.validaEmail(user.email)){ flagValid= false; } if($scope.validaCadastro(user)== false){ flagValid= false; } return flagValid; } function logUser(user) { var ref = firebase.database().ref("users"); // //console.log(user); var obj = { "user": user }; ref.push(obj); // or however you wish to update the node } $scope.post={}; $scope.imageUrl=''; var onSuccessPos = function(position) { $scope.pos.lat = position.coords.latitude; $scope.pos.lon= position.coords.longitude; //console.log($scope.pos.lon); }; $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', duration: 3000 }).then(function(){ // //console.log("The loading indicator is now displayed"); }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ // //console.log("The loading indicator is now hidden"); }); }; $scope.showAlert = function(texto) { var alertPopup = $ionicPopup.alert({ title: texto.titulo, template: texto.mensagem }); alertPopup.then(function(res) { //console.log('Thank you for not eating my delicious ice cream cone'); //$location.path('/page1/page10'); }); }; function onErrorPos(error) { $scope.posErro=error; calldialog(); } navigator.geolocation.getCurrentPosition(onSuccessPos, onErrorPos, {maximumAge:60000, timeout:5000, enableHighAccuracy:true}); $scope.cadastrarUsuario = function(user) { $scope.showLoading(); $('.aviso-cadastro').html(''); if(typeof user != 'undefined') { //console.log('aqui'); if($scope.validaCadastro(user)){ if($scope.validaFormulario(user)){ $scope.showLoading(); firebase.auth().createUserWithEmailAndPassword(user.email, user.password).catch(function(error) { // Handle Errors here. $scope.showLoading(); var errorCode = error.code; var errorMessage = error.message; var errorWeek ='auth/weak-password'; $('.lb-email ').removeClass('myredcolor'); // //console.log('aqui1'); if(errorCode.length == 18){ $('.aviso-cadastro').html('Ops, a senha deve ter pelo menos 6 caracteres!'); $('.divAvisoCadastro').show(); }else if(errorCode.length == 25){ $('.lb-email ').addClass('myredcolor'); $('.aviso-cadastro').html('Ops, este email já se encontra em uso.'); $('.divAvisoCadastro').show(); }else if (errorCode.length == 27) { $('.divAvisoCadastro').show(); $('.aviso-cadastro').html('Sem conexão com a internet.'); } // ... }); //console.log('cadastrou'); $scope.cadastraUsuarioManualEstabelecimentoflag = 1; $timeout(function () { firebase.auth().onAuthStateChanged(function(userLoggedOn) { var user = firebase.auth().currentUser; $scope.user = firebase.auth().currentUser;; //console.log('mudou'); $scope.showLoading(); if($scope.cadastraUsuarioManualEstabelecimentoflag == 1){ //console.log('flagou'); //$scope.user = firebase.auth().currentUser; //console.log($scope.user); if(user != null){ firebase.database().ref('users/' + user.uid).remove(); firebase.database().ref('geo_filas/' + user.uid ).remove(); var firebaseRef = firebase.database().ref().child('geo_lojas'); var geoFire = new GeoFire(firebaseRef); var ref = geoFire.ref(); // ref === firebaseRef var mykey = ref.child('lojas').push(); firebase.database().ref('users/' + user.uid).set({ email: user.email, active:1, role:2, limit:10000, nome:null, email:user.email, foto:null, raio:50, }, function(error) { if(error){ //console.log('erro'); }else{ } }); //console.log('cadastrou1'); //console.log('Tudo Certo'); $scope.showLoading(); //Cadastra Fila Comum //var user = firebase.auth().currentUser firebase.database().ref('limit/' + user.uid).set({ limit:10000, }, function(error) { }); firebase.database().ref('geo_filas/' + user.uid ).push({ nome: 1, ativa:true, prioridade:false, prioridade_qtd:0, manual:false, numero_contador:0, prefixo:'CM-', }, function(error) { }); //Cadastra fila Prioritária firebase.database().ref('geo_filas/' + user.uid ).push({ nome: 2, ativa:true, prioridade:true, prioridade_qtd:2, manual:false, numero_contador:0, prefixo:'PR-', }, function(error) { }); //Cadastra fila Manual firebase.database().ref('geo_filas/' + user.uid ).push({ nome: 3, ativa:true, prioridade:false, prioridade_qtd:0, manual:true, numero_contador:0, prefixo:'MN-', }, function(error) { }); firebase.database().ref('geo_lojas/' + $scope.user.uid+'/dados').set({ endereco:'-', telefone:'-', nome:null, email:user.email, foto:null, raio:50, }, function(error) { }); geoFire.set($scope.user.uid, [$scope.pos.lat, $scope.pos.lon]).then(function() { //console.log("Provided key has been added to GeoFire"); firebase.database().ref('geo_lojas/' + $scope.user.uid+'/dados').set({ endereco:'-', telefone:'-', nome:null, email:user.email, foto:null, raio:50, }, function(error) { }); }, function(error) { //console.log("Error: " + error); }); $timeout(function () { //$location.path('#/page1/page3');; document.location.href = '#/page1/page3'; }, 4000); //console.log('cadastrou2'); $scope.cadastraUsuarioManualEstabelecimentoflag = 0; }else{ $timeout(function () { var user = firebase.auth().currentUser; $scope.user = firebase.auth().currentUser; //console.log('cadastrou1'); //console.log('Tudo Certo'); var firebaseRef = firebase.database().ref().child('geo_lojas'); var geoFire = new GeoFire(firebaseRef); var ref = geoFire.ref(); // ref === firebaseRef firebase.database().ref('users/' + user.uid).remove(); firebase.database().ref('geo_filas/' + user.uid ).remove(); firebase.database().ref('users/' + user.uid).set({ email: user.email, active:1, role:2, limit:10000, nome:null, email:user.email, foto:null, raio:50, }, function(error) { if(error){ //console.log('erro'); }else{ } }); var mykey = ref.child('lojas').push(); $scope.showLoading(); //Cadastra Fila Comum //var user = firebase.auth().currentUser firebase.database().ref('limit/' + user.uid).set({ limit:10000, }, function(error) { }); firebase.database().ref('geo_filas/' + user.uid ).push({ nome: 1, ativa:true, prioridade:false, prioridade_qtd:0, manual:false, numero_contador:0, prefixo:'CM-', }, function(error) { }); //Cadastra fila Prioritária firebase.database().ref('geo_filas/' + user.uid ).push({ nome: 2, ativa:true, prioridade:true, prioridade_qtd:2, manual:false, numero_contador:0, prefixo:'PR-', }, function(error) { }); //Cadastra fila Manual firebase.database().ref('geo_filas/' + user.uid ).push({ nome: 3, ativa:true, prioridade:false, prioridade_qtd:0, manual:true, numero_contador:0, prefixo:'MN-', }, function(error) { }); firebase.database().ref('geo_lojas/' + $scope.user.uid+'/dados').set({ endereco:'-', telefone:'-', nome:null, email:user.email, foto:null, raio:50, }, function(error) { }); geoFire.set($scope.user.uid, [$scope.pos.lat, $scope.pos.lon]).then(function() { //console.log("Provided key has been added to GeoFire"); firebase.database().ref('geo_lojas/' + $scope.user.uid+'/dados').set({ endereco:'-', telefone:'-', nome:null, email:user.email, foto:null, raio:50, }, function(error) { }); }, function(error) { //console.log("Error: " + error); }); $timeout(function () { //$location.path('#/page1/page3');; document.location.href = '#/page1/page3'; }, 4000); //console.log('cadastrou2'); $scope.cadastraUsuarioManualEstabelecimentoflag = 0; }, 3000); } }else { //console.log('errou'); } }); }, 2000); }else{ } } }else{ $('.aviso-cadastro').html('Ops, digite o usuário e a senha!'); $('.divAvisoCadastro').show(); //console.log('aqui2'); } //console.log(user); } $scope.cadastrarUsuarioFacebook = function(user) { $('.divAvisoCadastro').hide(); var auth = new firebase.auth.FacebookAuthProvider(); $cordovaOauth.facebook("111991969424960", ["email"]).then(function(result) { var credential = firebase.auth.FacebookAuthProvider.credential(result.access_token); firebase.auth().signInWithCredential(credential).catch(function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // The email of the user's account used. var email = error.email; // The firebase.auth.AuthCredential type that was used. var credential = error.credential; if (errorCode === 'auth/account-exists-with-different-credential') { //alert('Email already associated with another account.'); // Handle account linking here, if using. $('.divAvisoCadastro').show(); $('.divAvisoCadastro').html('Email já está associado com uma outra conta.'); } else { console.error(error); } }); //alert('logou'); //console.log(data); user = firebase.auth().currentUser; //alert('passou1'); firebase.auth().onAuthStateChanged(function(user) { //alert('passou2'); $scope.showLoading(); firebase.database().ref().child('users').child(user.uid).child('email').once("value", function(snapshot) { if(snapshot.val() != null ){ //$location.path('#/page1/page3');; document.location.href = '#/page1/page3'; }else{ firebase.database().ref('users/' + user.uid).remove(); firebase.database().ref('geo_filas/' + user.uid ).remove(); firebase.database().ref('users/' + user.uid).set({ email: user.email, active:1, role:2, limit:10000, nome:user.displayName, email:user.email, foto:user.photoURL, raio:50, }, function(error) { if(error){ //console.log('erro'); }else{ } }); //console.log('Tudo Certo'); firebase.database().ref('users/' + user.uid).remove(); firebase.database().ref('geo_filas/' + user.uid ).remove(); firebase.database().ref('users/' + user.uid).set({ email: user.email, active:1, role:2, limit:10000, nome:user.displayName, email:user.email, foto:user.photoURL, raio:50, }, function(error) { if(error){ //console.log('erro'); }else{ } }); //console.log('Tudo Certo'); var firebaseRef = firebase.database().ref().child('geo_lojas'); var geoFire = new GeoFire(firebaseRef); var ref = geoFire.ref(); // ref === firebaseRef var mykey = ref.child('lojas').push(); geoFire.set(user.uid, [$scope.pos.lat, $scope.pos.lon]).then(function() { //console.log("Provided key has been added to GeoFire"); firebase.database().ref('geo_lojas/' + user.uid+'/dados').set({ endereco:'-', telefone:'-', nome:user.displayName, email:user.email, foto:user.photoURL, raio:50, }, function(error) { }); }, function(error) { //console.log("Error: " + error); }); //Cadastra Fila Comum //var user = firebase.auth().currentUser firebase.database().ref('limit/' + user.uid).set({ limit:10000, }, function(error) { }); firebase.database().ref('geo_filas/' + user.uid ).push({ nome: 1, ativa:true, prioridade:false, prioridade_qtd:0, manual:false, numero_contador:0, prefixo:'CM-', }, function(error) { }); //Cadastra fila Prioritária firebase.database().ref('geo_filas/' + user.uid ).push({ nome: 2, ativa:true, prioridade:true, prioridade_qtd:2, manual:false, numero_contador:0, prefixo:'PR-', }, function(error) { }); //Cadastra fila Manual firebase.database().ref('geo_filas/' + user.uid ).push({ nome: 3, ativa:true, prioridade:false, prioridade_qtd:0, manual:true, numero_contador:0, prefixo:'MN-', }, function(error) { }); $timeout(function() { //$location.path('#/page1/page3');; document.location.href = '#/page1/page3'; },2000); } }); }); }, function(error) { // alert("ERROR: " + error); }); } $scope.Prioritária = function(user) { $scope.user=user; $('.myredcolor').removeClass('myredcolor'); //$scope.validaCadastro(user); if($scope.validaFormulario(user)) { firebase.auth().createUserWithEmailAndPassword(user.email, user.password).then(function(user) { // [END createwithemail] // callSomeFunction(); Optional // var user = firebase.auth().currentUser; // //console.log(user.uid); //function writeUserData(userId, email) { firebase.database().ref('users/' + user.uid).set({ email: user.email, active:1, limit:10000, role:2, raio:50, }, function(error) { if(error){ //console.log('erro'); }else{ //console.log('Tudo Certo'); var firebaseRef = firebase.database().ref().child('geo_lojas'); var geoFire = new GeoFire(firebaseRef); var ref = geoFire.ref(); // ref === firebaseRef var mykey = ref.child('lojas').push(); geoFire.set(user.uid, [$scope.pos.lat, $scope.pos.lon]).then(function() { //console.log("Provided key has been added to GeoFire"); firebase.database().ref('geo_lojas/' + user.uid+'/dados').set({ loja: 'Loja teste', endereco:'endereco teste', telefone:'telefone teste', foto:'undefined', raio:50, }, function(error) { }); }, function(error) { //console.log("Error: " + error); }); } }); //} //alert('salvou'); /*user.updateProfile({ displayName: username }).then(function() { // Update successful. }, function(error) { // An error happened. });*/ }, function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; // [START_EXCLUDE] if (errorCode == 'auth/weak-password') { alert('The password is too weak.'); } else { console.error(error); } // [END_EXCLUDE] }); /*firebase.auth().createUserWithEmailAndPassword(user.email, user.password).catch(function(error,userData) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; if (errorCode == 'auth/weak-password') { alert('The password is too weak.'); } else { alert(errorMessage); } //console.log(userData); });*/ /*firebase.auth().createUserWithEmailAndPassword(user.email, user.password) .catch(function(error) { //console.log('aqui'); var user = firebase.auth().currentUser; logUser(user); // Optional }, function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; var msg= ''; if(error=='Error: The specified email address is already in use.') { msg='Email já em uso. Escolha outro email.'; $('.lb-email').addClass('myredcolor'); } if(error=='Error: Unable to contact the Firebase server.') { msg='Sem conexão com a internet. Tente mais terde.'; } $('.aviso-erro').html(msg); $('.divAvisoEmailUso').show(); return false; });*/ } } }]) .controller('pageCtrl', ['$scope', '$stateParams','$ionicSideMenuDelegate','$location', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope, $stateParams,$ionicSideMenuDelegate,$location) { $ionicSideMenuDelegate.canDragContent(false); $scope.$on('$ionicView.beforeEnter', function (event, viewData) { //viewData.enableBack = true; firebase.auth().onAuthStateChanged(function(user) { user = firebase.auth().currentUser; $scope.user = firebase.auth().currentUser; firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { $scope.datauser = snapshot.val(); //console.log(snapshot.val()); }); }); }); }]) .controller('page2Ctrl', ['$scope', '$stateParams','$ionicSideMenuDelegate', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope, $stateParams,$ionicSideMenuDelegate) { $ionicSideMenuDelegate.canDragContent(false); $scope.$on('$ionicView.beforeEnter', function (event, viewData) { //viewData.enableBack = true; firebase.auth().onAuthStateChanged(function(user) { user = firebase.auth().currentUser; $scope.user = firebase.auth().currentUser; firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { $scope.datauser = snapshot.val(); //console.log(snapshot.val()); }); }); }); }]) .controller('page3Ctrl', ['$scope', '$stateParams','$ionicSideMenuDelegate', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope, $stateParams,$ionicSideMenuDelegate) { $ionicSideMenuDelegate.canDragContent(false); $scope.$on('$ionicView.beforeEnter', function (event, viewData) { //viewData.enableBack = true; firebase.auth().onAuthStateChanged(function(user) { user = firebase.auth().currentUser; $scope.user = firebase.auth().currentUser; firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { $scope.datauser = snapshot.val(); //console.log(snapshot.val()); }); }); }); }]) .controller('filasCtrl', ['$scope','$timeout', '$ionicPopup', '$stateParams', '$ionicHistory', '$location','$ionicLoading','$ionicSideMenuDelegate', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$timeout, $ionicPopup, $stateParams, $ionicHistory, $location,$ionicLoading,$ionicSideMenuDelegate) { //alert(); var connectedRef = firebase.database().ref(".info/connected"); $scope.tentativas = 0; //$scope.conectDiv=true; connectedRef.on("value", function(snap) { $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); if (snap.val() === true) { $scope.conectDiv=true; $timeout(function () { $('body').trigger('click'); // $scope.conectDiv=true; },1500); //$window.location.reload(); } else { $scope.conectDiv=false; $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); } }); userLoggedOn = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(userLoggedOn) { if(!userLoggedOn){ $location.path('/login') } }); $ionicSideMenuDelegate.canDragContent(false); $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', duration: 15000, }).then(function(){ //console.log("The loading indicator is now displayed"); }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ //console.log("The loading indicator is now hidden"); }); }; $scope.showAlert = function(texto) { var alertPopup = $ionicPopup.alert({ title: texto.titulo, template: texto.mensagem }); alertPopup.then(function(res) { //console.log('Thank you for not eating my delicious ice cream cone'); //$location.path('/page1/page10'); }); }; $scope.tituloPagina =''; $scope.$on('$ionicView.leave', function(){ $scope.hasSenhas = true; }); $scope.$on('$ionicView.beforeEnter', function (event, viewData) { $scope.showLoading(); $scope.senhasAnteriores=[]; $scope.hasSenhas =true; user = firebase.auth().currentUser; if (user) { //console.log('aquilslfkdsl'); firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { $scope.datauser = snapshot.val(); if($scope.datauser.role==3){ $scope.tituloPagina = "Minhas Senhas"; $scope.showLoading(); $scope.senhasAnteriores=[]; firebase.database().ref().child('senhas_usuarios').child(user.uid).limitToLast(50).once("value", function(snapshot3) { $scope.showLoading(); if(snapshot3.val() != null ) { $.each(snapshot3.val(), function (key, val) { //$scope.showLoading(); // //console.log(val); firebase.database().ref().child('users').child(val.loja_id).once("value", function(snapshot4) { if(snapshot4.val() != null ) { val.loja = snapshot4.val().nome; val.loja_email = snapshot4.val().email; val.loja_foto = snapshot4.val().foto; val.categoria = snapshot4.val().categoria; val.categoriaNome = snapshot4.val().categoriaNome; $scope.senhasAnteriores.unshift(val); //$scope.conectDiv=true; //console.log($scope.senhasAnteriores); } },function (error) { //$scope.hideLoading(); }); }); $timeout(function(){ $('#filtro').val(''); $('#filtro').trigger('change'); },1000); }else{ //$scope.hideLoading(); $scope.hasSenhas = false; } $timeout(function(){ $scope.hideLoading(); },2000); },function(error) { $timeout(function(){ $scope.hideLoading(); },2000); }); }else{ $scope.tituloPagina = "<NAME>"; } //console.log(snapshot.val()); },function(error) { $timeout(function(){ $scope.hideLoading(); },2000); }); $scope.items = []; firebase.database().ref().child('geo_filas').child(user.uid).once("value", function(snapshot) { if(snapshot.val() != null ){ $.each(snapshot.val(), function(index, value) { if(value.nome==1 && value.ativa !=false){ //console.log('aqui'); $scope.showComum= true; } if(value.nome==3 && value.ativa !=false){ $scope.showManual=true; } if(value.nome==2 && value.ativa !=false){ $scope.showPrioridade=true; } }); }else{ $scope.totalItens =$scope.items.length; } $timeout(function(){ $scope.hideLoading(); },2000); // },function(error) { $timeout(function(){ $scope.hideLoading(); },2000); }); $scope.guiches = ''; firebase.database().ref().child('guiches').child(user.uid).on("value", function(snapshot) { if(snapshot.val() != null ){ //console.log(snapshot.val()); $scope.guiches = snapshot.val(); } }); } //$scope.hideLoading(); },function(error) { $timeout(function(){ $scope.hideLoading(); },2000); }); $scope.loadMoreData=function() { if(typeof $scope.senhasAnterioresAux[0] != "undefined") { $scope.senhasAnteriores.push($scope.senhasAnterioresAux[0]); $scope.senhasAnterioresAux.shift(); $scope.$broadcast('scroll.infiniteScrollComplete'); }else{ $timeout(function() { $scope.$broadcast('scroll.infiniteScrollComplete'); $scope.moredata=true; },3000); } }; $scope.chamarProximo = function() { } $scope.changeGuiche = function(guiche) { $scope.guiche = guiche; } $scope.chamarPrioritario = function() { setDateTime(); user = firebase.auth().currentUser; $scope.showLoading(); $scope.countLine =0; //firebase.auth().onAuthStateChanged(function(user) { if (user){ $scope.countLine++; //console.log('contador da linha 1615 é :'+$scope.countLine); //console.log(user); firebase.database().ref().child('geo_filas_senhas').child(user.uid).orderByChild("tipo").equalTo(2).limitToFirst(1).once("value", function(snapshot) { if(snapshot.val() != null){ // $scope.items.push(snapshot.val()); var myKey; var array = $.map(snapshot.val(), function(value, index) { //myKey = index; return [value]; }); var myKey = $.map(snapshot.val(), function(value, index) { return index; }); //console.log(snapshot.key); for (var i = 0; i < array.length; i++) { obj = array[i]; firebase.database().ref().child('geo_filas_senhas').child(user.uid).child(myKey[0]).remove(); // //console.log($scope.guiche); var guiche = $scope.guiche || null; if (typeof obj.user_id != 'undefined' ) { sendNotificationTouUser(obj.user_id); firebase.database().ref().child('senhas_usuarios').child(obj.user_id).orderByChild("loja_id").equalTo(user.uid).limitToLast(100).once("value", function(snapshot4) { // //console.log(snapshot.val()); if(snapshot4.val() != null){ $.each(snapshot4.val(), function (key2, val2) { if(val2.numero == obj.numero) { val2.data_hora_chamada = getDate(userDateTimeFull); firebase.database().ref('senhas_usuarios').child(obj.user_id).child(key2).set( val2); } }); } }); } firebase.database().ref('geo_filas_senhas_usadas/' + user.uid).push({ 'numero': obj.numero, 'tipo': obj.tipo, 'data':obj.data, 'data_hora_chamada':getDate(userDateTimeFull), 'guiche': guiche, }, function(error) { if(error){ $scope.removeu =true; //console.log('aqui1'); $scope.texto={}; $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='Operaçao não efetuada.'; $scope.hideLoading(); $scope.showAlert($scope.texto); }else{ //console.log('aqui2'); $scope.texto={}; $scope.texto.titulo ='Tudo Certo'; $scope.texto.mensagem ='A senha foi '+obj.numero+' chamada.'; $scope.hideLoading(); $scope.showAlert($scope.texto); } }); // //console.log($scope.removeu); //console.log(obj.ativo); } //console.log(snapshot.key); }else { //console.log('aqui2'); $scope.texto={}; $scope.texto.titulo ='Aviso'; $scope.texto.mensagem ='Não existem senhas ativas nesta fila.'; $scope.hideLoading(); $scope.showAlert($scope.texto); } }); } //}); } $scope.chamarComum = function() { user = firebase.auth().currentUser; setDateTime(); $scope.showLoading(); $scope.countLine=0; //firebase.auth().onAuthStateChanged(function(user) { if (user){ $scope.countLine++; //console.log('contador da linha 1525 é :'+$scope.countLine); //console.log(user); firebase.database().ref().child('geo_filas_senhas').child(user.uid).orderByChild("tipo").equalTo(1).limitToFirst(1).once("value", function(snapshot) { // //console.log(snapshot.val()); if(snapshot.val() != null){ // $scope.items.push(snapshot.val()); var myKey; var array = $.map(snapshot.val(), function(value, index) { //myKey = index; return [value]; }); var myKey = $.map(snapshot.val(), function(value, index) { return index; }); //console.log(snapshot.key); for (var i = 0; i < array.length; i++) { obj = array[i]; firebase.database().ref().child('geo_filas_senhas').child(user.uid).child(myKey[0]).remove(); //console.log($scope.guiche); var guiche = $scope.guiche || null; //alert('passou1'); if (typeof obj.user_id != 'undefined' ) { //alert('passou2'); sendNotificationTouUser(obj.user_id); firebase.database().ref().child('senhas_usuarios').child(obj.user_id).orderByChild("loja_id").equalTo(user.uid).limitToLast(100).once("value", function(snapshot4) { // //console.log(snapshot.val()); if(snapshot4.val() != null){ $.each(snapshot4.val(), function (key2, val2) { if(val2.numero == obj.numero) { val2.data_hora_chamada = getDate(userDateTimeFull); firebase.database().ref('senhas_usuarios').child(obj.user_id).child(key2).set( val2); } }); } }); } firebase.database().ref('geo_filas_senhas_usadas/' + user.uid).push({ 'numero': obj.numero, 'tipo': obj.tipo, 'data':obj.data, 'data_hora_chamada':getDate(userDateTimeFull), 'guiche': guiche, }, function(error) { if(error){ $scope.removeu =true; //console.log('aqui1'); $scope.texto={}; $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='Operaçao não efetuada.'; $scope.hideLoading(); $scope.showAlert($scope.texto); }else{ //console.log('aqui2'); $scope.texto={}; $scope.texto.titulo ='Tudo Certo'; $scope.texto.mensagem ='A senha foi '+obj.numero+' chamada.'; $scope.hideLoading(); $scope.showAlert($scope.texto); } }); //console.log($scope.removeu); //console.log(obj.ativo); } //console.log(snapshot.key); }else { //console.log('aqui2'); $scope.texto={}; $scope.texto.titulo ='Aviso'; $scope.texto.mensagem ='Não existem senhas ativas nesta fila.'; $scope.hideLoading(); $scope.showAlert($scope.texto); } }); } //}); } }]) .controller('versenhasCtrl', ['$scope','$ionicPopup', '$stateParams', '$ionicHistory', '$location','$timeout','$ionicLoading','$ionicSideMenuDelegate', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope, $ionicPopup, $stateParams, $ionicHistory, $location,$timeout,$ionicLoading,$ionicSideMenuDelegate) { //alert(); userLoggedOn = firebase.auth().currentUser; firebase.auth().onAuthStateChanged(function(userLoggedOn) { if(!userLoggedOn){ $location.path('/login') } }); $ionicSideMenuDelegate.canDragContent(false); $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', duration: 3000 }).then(function(){ // //console.log("The loading indicator is now displayed"); }); }; $scope.hideLoading = function(){ $ionicLoading.hide().then(function(){ // //console.log("The loading indicator is now hidden"); }); }; $scope.ionicGoBack = function() { $ionicHistory.goBack(); }; $scope.$on('$ionicView.beforeEnter', function (event, viewData) { viewData.enableBack = true; $scope.showLoading(); var user = firebase.auth().currentUser; if (user) { firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { $scope.datauser = snapshot.val(); //console.log(snapshot.val()); }); $scope.items = []; var array =[]; firebase.database().ref().child('geo_filas_senhas').child(user.uid).on("value", function(snapshot) { if(snapshot.val() != null){ $.each(snapshot.val(), function (key, val) { val.key = key; var array = $.map(val, function(value, index) { return [value]; }); $scope.items.push(array); }); }else{ $scope.totalItens =$scope.items.length; } }); $scope.guiches = ''; firebase.database().ref().child('guiches').child(user.uid).on("value", function(snapshot) { if(snapshot.val() != null ){ // //console.log(snapshot.val()); $scope.guiches = snapshot.val(); } }); } else { $location.path('/page5'); } $timeout(function(){ $scope.filtro=''; },1000); }); $scope.hideLoading(); $scope.showAlert = function(texto) { var alertPopup = $ionicPopup.alert({ title: texto.titulo, template: texto.mensagem }); alertPopup.then(function(res) { //console.log('Thank you for not eating my delicious ice cream cone'); //$location.path('/page1/page10'); }); }; //console.log(user); $scope.changeGuiche = function(guiche) { $scope.guiche = guiche; } $scope.mostrar=true; $scope.chamarSenhaId = function(senha,id,guiche) { setDateTime(); user = firebase.auth().currentUser; $scope.mostrar=false; $scope.showLoading(); $scope.countLine=0; //firebase.auth().onAuthStateChanged(function(user) { if (user){ $scope.countLine++; //console.log('contador da linha 1525 é :'+$scope.countLine); //console.log(user); if(id != senha[5]){ //console.log('aqyui2'); firebase.database().ref().child('geo_filas_senhas').child(user.uid).child(id).remove(); }else{ //console.log(senha); firebase.database().ref().child('geo_filas_senhas').child(user.uid).child(senha[5]).remove(); if(typeof senha[6] != 'undefined') { firebase.database().ref().child('geo_filas_senhas').child(user.uid).child(senha[6]).remove(); } } //firebase.database().ref().child('geo_filas_senhas').child(user.uid).child(myKey[0]).remove(); var guiche = $scope.guiche || null; if (typeof senha[5] != 'undefined' && typeof senha[6] != 'undefined') { sendNotificationTouUser(senha[5]); firebase.database().ref().child('senhas_usuarios').child(senha[5]).orderByChild("loja_id").equalTo(user.uid).limitToLast(100).once("value", function(snapshot4) { // //console.log(snapshot.val()); if(snapshot4.val() != null){ $.each(snapshot4.val(), function (key2, val2) { if(val2.numero == senha[2]) { val2.data_hora_chamada = getDate(userDateTimeFull); firebase.database().ref('senhas_usuarios').child(senha[5]).child(key2).set( val2); } }); } }); } firebase.database().ref('geo_filas_senhas_usadas/' + user.uid).push({ 'numero': senha[2], 'tipo': senha[4], 'data': senha[1], 'data_hora_chamada':getDate(userDateTimeFull), 'guiche': guiche, }, function(error) { if(error){ $scope.removeu =true; //console.log('aqui1'); $scope.texto={}; $scope.texto.titulo ='Ops! Algo deu errado.'; $scope.texto.mensagem ='Operaçao não efetuada.'; $scope.hideLoading(); $scope.showAlert($scope.texto); }else{ //console.log('aqui2'); var user = firebase.auth().currentUser; //console.log("show after directive partial loaded"); if (user) { $scope.items = []; // User is signed in. //var userId = firebase.auth().currentUser.uid; var array =[]; firebase.database().ref().child('geo_filas_senhas').child(user.uid).on("value", function(snapshot) { //firebase.database().ref().child('geo_filas').child(user.uid).once('value').then(function(snapshot) { if(snapshot.val() != null){ $.each(snapshot.val(), function (key, val) { val.key = key; var array = $.map(val, function(value, index) { return [value]; }); $scope.items.push(array); //console.log($scope.items); }); //$scope.items.push(snapshot.val()) ; //console.log(snapshot.val()); }else{ $scope.totalItens =$scope.items.length; } }); } else { //$location.path('/page5'); } // alert(); $timeout(function(){ $scope.filtro=''; $scope.mostrar=true; },1000); $scope.texto={}; $scope.texto.titulo ='Tudo Certo'; $scope.texto.mensagem ='A senha foi '+senha[2]+' chamada.'; $scope.hideLoading(); $scope.showAlert($scope.texto); } }); } //}); } }]) .controller('termosCtrl', ['$scope','$ionicPopup', '$stateParams', '$ionicHistory', '$location','$timeout','$ionicLoading','$ionicSideMenuDelegate', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope, $ionicPopup, $stateParams, $ionicHistory, $location,$timeout,$ionicLoading,$ionicSideMenuDelegate) { //alert(); $ionicSideMenuDelegate.canDragContent(false); }]) .controller('tabs1Controller', ['$scope','$ionicLoading', '$stateParams','$ionicPopup','$location','$ionicLoading','$timeout','$ionicSideMenuDelegate', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller // You can include any angular dependencies as parameters for this function // TIP: Access Route Parameters for your page via $stateParams.parameterName function ($scope,$ionicLoading, $stateParams,$ionicPopup,$location,$ionicLoading,$timeout,$ionicSideMenuDelegate) { $scope.showLoading = function() { $ionicLoading.show({ template: 'Carregando...', }).then(function(){ // //console.log("The loading indicator is now displayed"); }); }; $ionicSideMenuDelegate.canDragContent(false); $scope.limite =1; $scope.tituloPrimeiro=''; $scope.tituloSegundo=''; $scope.tituloTerceiro =''; $scope.tituloQuarto =''; $scope.tituloPrimeiroIco=''; $scope.tituloSegundoIco=''; $scope.tituloTerceiroIco =''; $scope.tituloQuartoIco =''; $scope.$on('$ionicView.enter', function(){ $ionicSideMenuDelegate.canDragContent(false); //$('.ion-navicon').hide(); $scope.showContent= false; $timeout(function () { $scope.showContent= true; }, 2500); }); $scope.$on('$ionicView.leave', function(){ $scope.showContent= false; $scope.conectDiv= true; $scope.hasStore=true; $scope.hasLojas=''; }); $scope.$on('$ionicView.beforeEnter', function (event, viewData) { //$scope.showLoading(); var onSuccessPos = function(position) { $scope.pos.lat = position.coords.latitude; $scope.pos.lon= position.coords.longitude; //console.log($scope.pos.lon); }; function onErrorPos(error) { $scope.posErro=error; calldialog(); } $scope.pos = {}; $scope.pos.lat = 0; $scope.pos.lon= 0; var onSuccessPos2 = function(position) { $scope.pos.lat = position.coords.latitude; $scope.pos.lon= position.coords.longitude; //console.log($scope.pos.lon); }; function onErrorPos2(error) { $scope.posErro=error; //calldialog(); } function tentarcadastrarnovamente(loja, usuario,uid) { navigator.geolocation.getCurrentPosition(onSuccessPos2, onErrorPos2, {maximumAge:60000, timeout:5000, enableHighAccuracy:true}); setTimeout(function() { if($scope.pos.lat != 'undefined' && $scope.pos.lat != '' && $scope.pos.lat != null){ geoFire.set(uid, [$scope.pos.lat, $scope.pos.lon]).then(function() { //console.log("Provided key has been added to GeoFire"); firebase.database().ref('geo_lojas/' + uid+'/dados').set({ endereco:'-', telefone:'-', nome:usuario.nome, email:usuario.email, foto:usuario.foto, raio:50, }, function(error) { }); }, function(error) { //console.log("Error: " + error); }); firebase.database().ref('geo_filas/' + uid ).remove(); firebase.database().ref('limit/' + uid).set({ limit:10000, }, function(error) { }); firebase.database().ref('geo_filas/' + uid ).push({ nome: 1, ativa:true, prioridade:false, prioridade_qtd:0, manual:false, numero_contador:0, prefixo:'CM-', }, function(error) { }); //Cadastra fila Prioritária firebase.database().ref('geo_filas/' + uid ).push({ nome: 2, ativa:true, prioridade:true, prioridade_qtd:2, manual:false, numero_contador:0, prefixo:'PR-', }, function(error) { }); //Cadastra fila Manual firebase.database().ref('geo_filas/' + uid ).push({ nome: 3, ativa:true, prioridade:false, prioridade_qtd:0, manual:true, numero_contador:0, prefixo:'MN-', }, function(error) { }); if(typeof snapshot.val().categoria != 'undefined'){ var firebaseRef2 = firebase.database().ref().child('geo_lojas_cat').child(snapshot.val().categoria); var geoFire2 = new GeoFire(firebaseRef2); var ref2 = geoFire.ref(); // ref === firebaseRef geoFire2.set(uid, [$scope.pos.lat, $scope.pos.lon]).then(function() { //console.log("Provided key has been added to GeoFire"); firebase.database().ref('geo_lojas_cat/'+snapshot.val().categoria+'/'+ uid+'/dados').set({ endereco:'-', telefone:'-', nome:usuario.nome, email:usuario.email, foto:usuario.foto, raio:50, }, function(error) { }); }); } }else{ tentarcadastrarnovamente(loja, usuario ,uid) } },1000); } navigator.geolocation.getCurrentPosition(onSuccessPos, onErrorPos, {maximumAge:60000, timeout:5000, enableHighAccuracy:true}); $scope.showContent= false; $timeout(function () { $scope.showContent= true; }, 2500); user = firebase.auth().currentUser; $scope.countLine=0; firebase.auth().onAuthStateChanged(function(user) { if (user){ $scope.countLine++; $timeout(function() { //console.log(user.uid); firebase.database().ref().child('users').child(user.uid).once("value", function(snapshot) { $scope.datauser = snapshot.val(); //console.log(snapshot.val()); $scope.isAndroid = ionic.Platform.isAndroid(); $scope.isIos = ionic.Platform.isIOS(); //console.log($scope.isIos); if(snapshot.val() != null) { if(snapshot.val().role ==2){ $scope.tituloPrimeiro='<NAME>'; $scope.tituloSegundo ='<NAME>'; $scope.tituloTerceiro ='Minha Fila'; $scope.tituloQuarto ='Configurações'; if($scope.isAndroid == true){ $scope.tituloPrimeiroIco='ion-plus-circled'; $scope.tituloSegundoIco='ion-speakerphone'; $scope.tituloTerceiroIco ='ion-person-stalker'; $scope.tituloQuartoIco ='ion-gear-a'; }else if($scope.isIos == true){ $scope.tituloPrimeiroIco='ion-ios-plus'; $scope.tituloSegundoIco='ion-speakerphone'; $scope.tituloTerceiroIco ='ion-person-stalker'; $scope.tituloQuartoIco ='ion-ios-gear'; }else{ $scope.tituloPrimeiroIco='ion-plus-circled'; $scope.tituloSegundoIco='ion-speakerphone'; $scope.tituloTerceiroIco ='ion-person-stalker'; $scope.tituloQuartoIco ='ion-gear-a'; } $scope.usuario ={}; $scope.usuario.nome = snapshot.val().nome || null; $scope.usuario.email = snapshot.val().email || null; $scope.usuario.foto = snapshot.val().foto || null; firebase.database().ref().child('geo_lojas').child(user.uid).once("value", function(snapshotgeolojas) { if(snapshotgeolojas.val() == null) { var firebaseRef = firebase.database().ref().child('geo_lojas'); var geoFire = new GeoFire(firebaseRef); var ref = geoFire.ref(); // ref === firebaseRef if($scope.pos.lat != 'undefined' && $scope.pos.lat != '' && $scope.pos.lat != null){ geoFire.set(user.uid, [$scope.pos.lat, $scope.pos.lon]).then(function() { //console.log("Provided key has been added to GeoFire"); firebase.database().ref('geo_lojas/' + user.uid+'/dados').set({ endereco:'-', telefone:'-', nome:$scope.usuario.nome, email:$scope.usuario.email, foto:$scope.usuario.foto, raio:50, }, function(error) { }); }, function(error) { //console.log("Error: " + error); }); firebase.database().ref('geo_filas/' + user.uid ).remove(); firebase.database().ref('limit/' + user.uid).set({ limit:10000, }, function(error) { }); firebase.database().ref('geo_filas/' + user.uid ).push({ nome: 1, ativa:true, prioridade:false, prioridade_qtd:0, manual:false, numero_contador:0, prefixo:'CM-', }, function(error) { }); //Cadastra fila Prioritária firebase.database().ref('geo_filas/' + user.uid ).push({ nome: 2, ativa:true, prioridade:true, prioridade_qtd:2, manual:false, numero_contador:0, prefixo:'PR-', }, function(error) { }); //Cadastra fila Manual firebase.database().ref('geo_filas/' + user.uid ).push({ nome: 3, ativa:true, prioridade:false, prioridade_qtd:0, manual:true, numero_contador:0, prefixo:'MN-', }, function(error) { }); if(typeof snapshot.val().categoria != 'undefined'){ var firebaseRef2 = firebase.database().ref().child('geo_lojas_cat').child(snapshot.val().categoria); var geoFire2 = new GeoFire(firebaseRef2); var ref2 = geoFire.ref(); // ref === firebaseRef geoFire2.set(user.uid, [$scope.pos.lat, $scope.pos.lon]).then(function() { //console.log("Provided key has been added to GeoFire"); firebase.database().ref('geo_lojas_cat/'+snapshot.val().categoria+'/'+ user.uid+'/dados').set({ endereco:'-', telefone:'-', nome:$scope.usuario.nome, email:$scope.usuario.email, foto:$scope.usuario.foto, raio:50, }, function(error) { }); }); } }else{ tentarcadastrarnovamente(snapshotgeolojas, $scope.usuario,user.uid ) } } }); }else{ $scope.tituloPrimeiro='Pegar Senha'; $scope.tituloSegundo ='Minhas Filas'; $scope.tituloTerceiro ='Favoritos'; $scope.tituloQuarto ='Configurações'; if($scope.isAndroid == true){ $scope.tituloPrimeiroIco='ion-pricetags'; $scope.tituloSegundoIco='ion-person-stalker'; $scope.tituloTerceiroIco ='ion-heart'; $scope.tituloQuartoIco ='ion-gear-a'; }else if($scope.isIos == true){ $scope.tituloPrimeiroIco='ion-ios-pricetags'; $scope.tituloSegundoIco='ion-person-stalker'; $scope.tituloTerceiroIco ='ion-heart'; $scope.tituloQuartoIco ='ion-ios-gear'; }else{ $scope.tituloPrimeiroIco='ion-pricetags'; $scope.tituloSegundoIco='ion-person-stalker'; $scope.tituloTerceiroIco ='ion-heart'; $scope.tituloQuartoIco ='ion-gear-a'; } } } }); },2500); }else{ document.location.href = '#/page5'; } }); }); }]) <file_sep>/README.md # Rudo App para automação de filas a distância. Ionic, Angular e Firebase. <file_sep>/js/routes.js angular.module('app.routes', []) .config(function($stateProvider, $urlRouterProvider) { // Ionic uses AngularUI Router which uses the concept of states // Learn more here: https://github.com/angular-ui/ui-router // Set up the various states which the app can be in. // Each state's controller can be found in controllers.js $stateProvider .state('tabsController.acompanharFilas', { url: '/page2', views: { 'tab1': { templateUrl: 'templates/acompanharFilas.html', controller: 'acompanharFilasCtrl' } } }) .state('tabsController.gerarSenhas', { url: '/page3', views: { 'tab2': { templateUrl: 'templates/gerarSenhas.html', controller: 'gerarSenhasCtrl' } } }) .state('tabsController.filas', { url: '/page10', views: { 'tab4': { templateUrl: 'templates/filas.html', controller: 'filasCtrl' } } }) .state('tabsController.configuraEs', { url: '/page4', views: { 'tab3': { templateUrl: 'templates/configuraEs.html', controller: 'configuraEsCtrl' } } }) .state('tabsController', { url: '/page1', templateUrl: 'templates/tabsController.html', abstract:true }) .state('signup', { url: '/page6', templateUrl: 'templates/signup.html', controller: 'signupCtrl' }) .state('signuptwo', { url: '/page10', templateUrl: 'templates/signuptwo.html', controller: 'signuptwoCtrl' }) .state('cadastrarfilas', { url: '/cadastrarfilas/:id', templateUrl: 'templates/cadastrarfilas.html', controller: 'cadastrarfilasCtrl' }) .state('versenhas', { url: '/versenhas', templateUrl: 'templates/versenhas.html', controller: 'versenhasCtrl' }) .state('page', { url: '/page7', templateUrl: 'templates/page.html', controller: 'pageCtrl' }) .state('page2', { url: '/page8', templateUrl: 'templates/page2.html', controller: 'page2Ctrl' }) .state('page3', { url: '/page9', templateUrl: 'templates/page3.html', controller: 'page3Ctrl' }) .state('configurarsenhas', { url: '/configurarsenhas', templateUrl: 'templates/configurarsenhas.html', controller: 'configurarSenhasCtrl' }) .state('guiches', { url: '/guiches', templateUrl: 'templates/guiches.html', controller: 'guichesCtrl' }) .state('assine', { url: '/assine', templateUrl: 'templates/assine.html', controller: 'assineCtrl' }) .state('minhaconta', { url: '/minhaconta', templateUrl: 'templates/minhaconta.html', controller: 'minhacontaCtrl' }) .state('termos', { url: '/termos', templateUrl: 'templates/termos.html', controller: 'termosCtrl' }) .state('gerarsenhascategorias', { url: '/gerarsenhascategorias/:id', templateUrl: 'templates/gerarsenhascategorias.html', controller: 'gerarsenhascategoriasCtrl' }) .state('painelloja', { url: '/painelloja/:id', templateUrl: 'templates/painelloja.html', controller: 'painelLojaCtrl' }) .state('gerarsenhasclientes', { url: '/gerarsenhasclientes/:id', templateUrl: 'templates/gerarSenhasClientes.html', controller: 'gerarSenhasClienteCtrl' }) .state('login', { url: '/page5', templateUrl: 'templates/login.html', controller: 'loginCtrl' }) .state('login2', { url: '/login2', templateUrl: 'templates/login2.html', controller: 'login2Ctrl' }) //$urlRouterProvider.otherwise('/page1/page3') $urlRouterProvider.otherwise('/page5') });
565d503e4f4cc422f5e6db3a192759bb01a88b3e
[ "JavaScript", "Markdown" ]
3
JavaScript
eduardonalves/rudo
42b88156b018e9974db1e552f871b9b41f58f6ba
2f396042b77b14597adc878a47b815ba031b61d9
refs/heads/master
<repo_name>abhi-cloud/recruitment_assignment<file_sep>/Booked.java package com.example.myfirst; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; public class Booked extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_booked); } } <file_sep>/models.py # DevCom Rcruitment assignment # THINK task 1 of backend assignment from uuid import uuid4 from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Book(models.Model): id = models.UUIDField(primary_key = True, default = uuid4, editable = false) time_of_addition = models.DateTimeField(default = timezone.now) isbn = models.CharField(max_length = 13) title = models.CharField(max_length = 50) author = models.CharField(max_length = 50) short_description = models.TextField() # here i have setup one to many relationship between users and books, in both # owner as well as current_rentee field # users model is automatically defined in django, and is initiated after some migration commands # users will be added to User model after SignUp owner = models.ForeignKey( User, on_delete = models.CASCADE, blank = False) current_rentee = models.ForeignKey( User, default = None, on_delete = models.SET_DEFAULT, blank = True) def __str__(self): return self.title class Meta: verbose_name = "Book" verbose_name_plural = "Books" ordering = ("title",)<file_sep>/models_task2.py # DevCom Rcruitment assignment # THINK task 2 of backend assignment from uuid import uuid4 from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Author(models.Model): id = models.UUIDField(primary_key = True, default = uuid4, editable = False, ) name = models.CharField(max_length = 50) def __str__(self): return self.name class Book(models.Model): id = models.UUIDField(primary_key = True, default = uuid4, editable = false) time_of_addition = models.DateTimeField(default = timezone.now) isbn = models.CharField(max_length = 13) title = models.CharField(max_length = 50) short_description = models.TextField() owner = models.ForeignKey( User, on_delete = models.CASCADE, blank = False) #author also has reference to Author model author = models.ForeignKey( Author, default = None, on_delete = models.SET_DEFAULT, blank = True) current_rentee = models.ForeignKey( User, default = None, on_delete = models.SET_DEFAULT, blank = True) def __str__(self): return self.title class Meta: verbose_name = "Book" verbose_name_plural = "Books" ordering = ("title",) class AuthorBookRelation(models.Model): id = models.UUIDField(primary_key = True, default = uuid4, editable = False, ) author = models.ForeignKey( Author, on_delete = models.CASCADE, default = uuid4) book = models.ForeignKey( Book, on_delete = models.CASCADE, default= uuid4) def __str__(self): return self.author.name + " --> " + self.book.title class Meta: verbose_name = "Author-Book Relation" verbose_name_plural = "Author-Book Relations" ordering = ("author_name",)
ecf204280d00b6e534abcdf79a99f0bb84d9b80b
[ "Java", "Python" ]
3
Java
abhi-cloud/recruitment_assignment
0b0fc9597766aff5965ea52ec73a854e62b358d2
9bb7d7b507cb983be08b27fbab86d59f7d98047e